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
6,619,073
Why can't a branch name contain the 'space' char?
<p>I tried:</p> <pre><code>git branch "MyProj/bin/ ignored" </code></pre> <p>and received:</p> <pre><code>fatal: 'MyProj/bin/ ignored' is not a valid branch name. </code></pre> <p>The <a href="http://www.kernel.org/pub/software/scm/git/docs/git-branch.html" rel="noreferrer">git-branch</a> man page points to the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html" rel="noreferrer">git-check-ref-format</a> man page to get the actual rules for a valid branch name.</p> <p>Sure enough, the reason for the above fatal error appears to be the inclusion of a space character.</p> <p>Any idea why, in this day and age, spaces are still excluded from a branch name (I would have expected it in ancient CVS, for example, but Git?)</p> <p>What could be valid technical reasons for that?</p>
6,619,113
5
3
null
2011-07-08 01:37:09.41 UTC
4
2022-08-25 10:41:26.227 UTC
2012-08-26 13:10:25.953 UTC
null
335,418
null
586,707
null
1
71
git|git-branch
59,397
<p>I do not know if you are going to find a pure, technical reason down at the bottom of this. However, I can offer that spaces tend to throw wrenches in all sorts of *nix utilities and filename processing, so it may have been to avoid accidentally doing anything wrong further down the line. After all, a git branch boils down to a file in the repo and this avoids dealing with spaces in that file's name (specifically, a branch is a file in .git/refs/heads/, as mentioned in the comment).</p> <p>Mostly I would guess the reason is philosophical, and meant to keep things simple. Branch names are human-readable names that have no real reason to be complicated (and require typing two extra chars each time haha, to invoke the ghost of the sysadmin who has aliased every command to an indecipherable three letter combination). Otherwise known as the "why cd is not chdir" argument.</p>
6,967,738
What is Big O of a loop?
<p>I was reading about <strong>Big O notation</strong>. It stated,</p> <blockquote> <p>The big O of a loop is the number of iterations of the loop into number of statements within the loop.</p> </blockquote> <p>Here is a code snippet,</p> <pre><code>for (int i=0 ;i&lt;n; i++) { cout &lt;&lt;"Hello World"&lt;&lt;endl; cout &lt;&lt;"Hello SO"; } </code></pre> <p>Now according to the definition, the Big O should be <strong>O(n*2)</strong> but it is <strong>O(n)</strong>. Can anyone help me out by explaining why is that? Thanks in adavance.</p>
6,967,775
7
5
null
2011-08-06 15:15:43.283 UTC
5
2022-01-09 14:31:23.61 UTC
null
null
null
user379888
null
null
1
18
big-o
56,307
<p>If you check the <em>definition</em> of the O() notation you will see that (multiplier) constants doesn't matter.</p> <p>The work to be done within the loop is <em>not</em> 2. There are two statements, for each of them you have to do a couple of machine instructions, maybe it's 50, or 78, or whatever, but this is completely irrelevant for the asymptotic complexity calculations because they are all constants. It doesn't depend on <code>n</code>. It's just O(1).</p> <pre><code>O(1) = O(2) = O(c) where c is a constant. O(n) = O(3n) = O(cn) </code></pre>
6,904,166
Should I use window.variable or var?
<p>We have a lot of setup JS code that defines panels, buttons, etc that will be used in many other JS files.</p> <p>Typically, we do something like:</p> <p><strong>grid.js</strong></p> <pre><code>var myGrid = ..... </code></pre> <p><strong>combos.js</strong></p> <pre><code>var myCombo = ..... </code></pre> <p>Then, in our application code, we:</p> <p><strong>application.js</strong></p> <pre><code>function blah() { myGrid.someMethod() } </code></pre> <p><strong>someother.js</strong></p> <pre><code>function foo() { myCombo.someMethod(); myGrid.someMethod(); } </code></pre> <p>So, should we be using the <code>var myGrid</code> or is better to use <code>window.myGrid</code></p> <p>What's the difference?</p>
6,904,252
7
0
null
2011-08-01 20:39:58.273 UTC
14
2018-03-06 12:58:45.17 UTC
2011-08-01 20:43:07.917 UTC
null
28,053
null
59,202
null
1
54
javascript|global-variables
43,525
<p>I would suggest creating a namespace variable <code>var App = {};</code></p> <pre><code>App.myGrid = ... </code></pre> <p>That way you can limit the pollution of the global namespace.</p> <p>EDIT: Regarding the number of variables issue - 2 possible solutions come to mind:</p> <ol> <li>You can further namespace them by type(Grids, Buttons, etc) or by relationship(ClientInfoSection, AddressSection, etc)</li> <li>You encapsulate your methods in objects that get instantiated with the components you have</li> </ol> <p>ex: you have</p> <pre><code>function foo() { myCombo.someMethod(); myGrid.someMethod(); } </code></pre> <p>becomes:</p> <pre><code>var Foo = function(combo, grid) { var myCombo = combo;//will be a private property this.myGrid = grid;//will be a public property this.foo = function() {//public method myCombo.someMethod(); myGrid.someMethod(); } } App.myFoo = new Foo(someCombo, someGrid); App.myFoo.foo(); </code></pre> <p>this way you limit the amount of little objects and only expose what you need (namely the foo function)</p> <p>PS: if you need to expose the internal components then add them to this inside the constructor function</p>
6,535,217
CSS adding border radius to an IFrame
<p>Adding a border to an IFrame is no biggie - you do it like this e.g.: </p> <pre><code> border: 4px solid #000; -moz-border-radius: 15px; border-radius: 15px; </code></pre> <p>The problem is that when you load content to that IFrame, the content overlaps the borders in the corners, like so: </p> <p><img src="https://i.stack.imgur.com/6gKZy.jpg" alt="IFrame content overlapping with CSS border"></p> <p>Any ideas how one might get past this issue? E.g. is there a JavaScript library that would take care of this...</p>
6,535,295
11
1
null
2011-06-30 13:08:17.4 UTC
3
2021-05-02 17:26:09.693 UTC
null
null
null
null
7,382
null
1
18
css|iframe|border
60,776
<p>Border radius isn't well supported or consistent yet. If you want the desired affect, try using DIV's around the element and use graphics instead, with an overflow of hidden in your CSS. You might want to look into the sliding doors tehnique if your iframe varies in height.</p> <p><a href="http://www.alistapart.com/articles/slidingdoors/" rel="nofollow">http://www.alistapart.com/articles/slidingdoors/</a></p> <p>Hope this helps.</p> <p>Good luck!</p>
38,350,249
SparkContext Error - File not found /tmp/spark-events does not exist
<p>Running a Python Spark Application via API call - On submitting the Application - response - Failed SSH into the Worker</p> <p>My python application exists in </p> <pre><code>/root/spark/work/driver-id/wordcount.py </code></pre> <p>Error can be found in </p> <pre><code>/root/spark/work/driver-id/stderr </code></pre> <p>Show the following error - </p> <pre><code>Traceback (most recent call last): File "/root/wordcount.py", line 34, in &lt;module&gt; main() File "/root/wordcount.py", line 18, in main sc = SparkContext(conf=conf) File "/root/spark/python/lib/pyspark.zip/pyspark/context.py", line 115, in __init__ File "/root/spark/python/lib/pyspark.zip/pyspark/context.py", line 172, in _do_init File "/root/spark/python/lib/pyspark.zip/pyspark/context.py", line 235, in _initialize_context File "/root/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 1064, in __call__ File "/root/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext. : java.io.FileNotFoundException: File file:/tmp/spark-events does not exist. at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:402) at org.apache.hadoop.fs.FilterFileSystem.getFileStatus(FilterFileSystem.java:255) at org.apache.spark.scheduler.EventLoggingListener.start(EventLoggingListener.scala:100) at org.apache.spark.SparkContext.&lt;init&gt;(SparkContext.scala:549) at org.apache.spark.api.java.JavaSparkContext.&lt;init&gt;(JavaSparkContext.scala:59) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:234) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381) at py4j.Gateway.invoke(Gateway.java:214) at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:79) at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:68) at py4j.GatewayConnection.run(GatewayConnection.java:209) at java.lang.Thread.run(Thread.java:745) </code></pre> <p>It indicates - /tmp/spark-events Does not exist - which is true However, in wordcount.py</p> <pre><code>from pyspark import SparkContext, SparkConf ... few more lines ... def main(): conf = SparkConf().setAppName("MyApp").setMaster("spark://ec2-54-209-108-127.compute-1.amazonaws.com:7077") sc = SparkContext(conf=conf) sc.stop() if __name__ == "__main__": main() </code></pre>
38,350,483
4
1
null
2016-07-13 11:20:04.963 UTC
10
2018-02-15 08:58:18.6 UTC
2016-07-13 11:25:50.357 UTC
null
5,157,515
null
5,157,515
null
1
24
python|amazon-web-services|apache-spark|amazon-ec2|pyspark
23,985
<p><code>/tmp/spark-events</code> is the location that Spark store the events logs. Just create this directory in the master machine and you're set.</p> <pre><code>$mkdir /tmp/spark-events $ sudo /root/spark-ec2/copy-dir /tmp/spark-events/ RSYNC'ing /tmp/spark-events to slaves... ec2-54-175-163-32.compute-1.amazonaws.com </code></pre>
51,239,649
Declaring a variable with two types: "int char"
<p>I'm a C++ beginner, and I'm reading <em>Bjarne Stroustrup's Programming: Principles and Practice Using C++</em>.</p> <p>In the section on <em>3.9.2 Unsafe conversions</em>, the author mentioned </p> <blockquote> <p>When the initializer is an integer literal, the compiler can check the actual value and accept values that do not imply narrowing:</p> <pre><code>int char b1 {1000}; // error: narrowing (assuming 8-bit chars) </code></pre> </blockquote> <p>I'm puzzled by this declaration. It uses two types (<code>int</code> and <code>char</code>). I have never seen such declaration in Java and Swift before (the two languages I'm relatively familiar with). Is this a typo or a valid C++ syntax?</p>
51,239,696
4
10
null
2018-07-09 06:53:21.61 UTC
3
2018-12-24 08:44:35.29 UTC
2018-07-10 06:22:18.393 UTC
null
978,917
null
5,581,182
null
1
81
c++|type-conversion|initialization|uniform-initialization|narrowing
7,193
<p>It's a mistake in the book. That is not a valid C++ declaration, even without the supposed narrowing conversion.</p> <p>It isn't mentioned in any of the erratas on <a href="http://www.stroustrup.com/Programming/PPP2errata.html" rel="noreferrer">Bjarne Stroustrup's page</a>(4th printing and earlier), though, which is odd. It's a clear enough mistake. I imagine since it's commented with <code>//error</code> few people notice the mistake in the declaration itself.</p>
15,836,199
WCF NamedPipe CommunicationException - "The pipe has been ended. (109, 0x6d)."
<p>I am writing a Windows Service with accompanying "status tool." The service hosts a WCF named pipe endpoint for inter-process communication. Through the named pipe, the status tool can periodically query the service for the latest "status."</p> <p><img src="https://i.stack.imgur.com/zU9LO.jpg" alt="enter image description here"></p> <p>On my development machine, I have multiple IP Addresses; one of them is a "local" network with a 192.168.1.XX address. The other is the "corporate" network, with a 10.0.X.XX address. The Windows Service collects UDP multicast traffic on a single IP Address.</p> <p>The Windows Service has, until now, worked fine as long as it uses the "192.168.1.XX," address. It consistently reports the status correctly to the client.</p> <p>As soon as I switched to the other, "corporate" IP Address (10.0.X.XX) and restarted the service, I get continuous "CommunicationExceptions" when retrieving the status:</p> <pre><code>"There was an error reading from the pipe: The pipe has been ended. (109, 0x6d)." </code></pre> <p>Now, I wouldn't think that the UDP Client's 'claimed' IP address should have anything to do with the functionality of the Named-Pipe interface; they are completely separate pieces of the application!</p> <p>Here are the relevant WCF config sections:</p> <pre><code>//On the Client app: string myNamedPipe = "net.pipe://127.0.0.1/MyNamedPipe"; ChannelFactory&lt;IMyService&gt; proxyFactory = new ChannelFactory&lt;IMyService&gt;( new NetNamedPipeBinding(), new EndpointAddress(myNamedPipe)); //On the Windows Service: string myNamedPipe = "net.pipe://127.0.0.1/MyNamedPipe"; myService = new MyService(myCustomArgs); serviceContractHost = new ServiceHost(myService ); serviceContractHost.AddServiceEndpoint( typeof(IMyService), new NetNamedPipeBinding(), myNamedPipe); serviceContractHost.Open(); </code></pre> <p>I wouldn't think this is a 'permissions' issue - I'm running the client with administrative privileges - but perhaps there's some domain-specific reason this broke?</p>
15,865,834
10
2
null
2013-04-05 14:14:18.803 UTC
3
2021-06-10 09:50:21.29 UTC
2013-04-08 02:46:05.783 UTC
null
741,988
null
741,988
null
1
16
c#|wcf|windows-services|named-pipes
38,181
<p>The IP Address was, it turns out, a complete red herring.</p> <p>The real reason for the exception was invalid Enum values being returned by the WCF service.</p> <p>My enum was defined thusly:</p> <pre><code>[DataContract] public enum MyEnumValues : Byte { [EnumMember] Enum1 = 0x10, [EnumMember] Enum2 = 0x20, [EnumMember] Enum3 = 0x30, [EnumMember] Enum4 = 0x40, } </code></pre> <p>It looks fine on the surface.</p> <p>But the raw status reported by the underlying service was a Byte value of "0," and there was no corresponding Enum value for which to cast it.</p> <p>Once I ensured that the Enum values were all valid, the tool lit up like a Christmas tree.</p> <p>When in doubt, assume your WCF data is invalid.</p>
15,715,825
How do you get the Git repository's name in some Git repository?
<p>When you are working in some Git directory, how can you get the Git repository name in some Git repository? Are there any Git commands?</p> <pre><code># I did check out bar repository and working in somewhere # under bar directory at this moment such as below. $ git clone git://github.com/foo/bar.git $ cd bar/baz/qux/quux/corge/grault # and I am working in here! $ git xxx # &lt;- ??? bar </code></pre>
15,716,016
18
4
null
2013-03-30 06:47:04.637 UTC
54
2022-09-12 19:55:41.653 UTC
2018-07-17 12:28:39.053 UTC
null
63,550
null
688,608
null
1
230
git|repository
318,756
<p>Well, if, for the repository name you mean the Git root directory name (the one that contains the <code>.git</code> directory) you can run this:</p> <pre class="lang-bash prettyprint-override"><code>basename `git rev-parse --show-toplevel` </code></pre> <p>The <code>git rev-parse --show-toplevel</code> part gives you the path to that directory and <code>basename</code> strips the first part of the path.</p>
52,979,555
Can mathematical operators *, /, +, -, ^ be used to convert a non-zero number to 1?
<p>I am working with software (Oracle Siebel) that only supports JavaScript expressions with operators multiply, divide, subtract, add, and XOR (<code>*</code>, <code>/</code>, <code>-</code>, <code>+</code>, <code>^</code>). I don't have other operators such as <code>!</code> or <code>? :</code> available.</p> <p>Using the above operators, is it possible to convert a number to 1 if it is non-zero and leave it 0 if it's already zero? The number may be positive, zero, or negative.</p> <p>Example:</p> <pre><code>var c = 55; var d; // d needs to set as 1 </code></pre> <p>I tried <code>c / c</code> , but it evaluates to <code>NaN</code> when <code>c</code> is 0. <code>d</code> needs to be 0 when <code>c</code> is 0.</p> <p>c is a currency value, and it will have a maximum of two trailing digits and 12 leading digits.</p> <p>I am trying to emulate an <code>if</code> condition by converting a number to a Boolean 0 or 1, and then multiplying other parts of the expression.</p>
52,979,644
4
6
null
2018-10-25 00:06:39.543 UTC
18
2018-11-18 21:46:01.307 UTC
2018-10-28 03:53:01.573 UTC
null
159,145
null
925,549
null
1
121
javascript|siebel
15,432
<p><code>c / (c + 5e-324)</code> should work. (The constant <code>5e-324</code> is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE" rel="noreferrer"><code>Number.MIN_VALUE</code></a>, the smallest representable positive number.) If x is 0, that is exactly 0, and if x is nonzero (technically, if x is at least 4.45014771701440252e-308, which the smallest non-zero number allowed in the question, 0.01, is), JavaScript's floating-point math is too imprecise for the answer to be different than 1, so it will come out as exactly 1.</p>
35,445,373
Entity Framework query performance differs extrem with raw SQL execution
<p>I have a question about Entity Framework query execution performance.</p> <p><strong>Schema</strong>:</p> <p>I have a table structure like this:</p> <pre><code>CREATE TABLE [dbo].[DataLogger] ( [ID] [bigint] IDENTITY(1,1) NOT NULL, [ProjectID] [bigint] NULL, CONSTRAINT [PrimaryKey1] PRIMARY KEY CLUSTERED ( [ID] ASC ) ) CREATE TABLE [dbo].[DCDistributionBox] ( [ID] [bigint] IDENTITY(1,1) NOT NULL, [DataLoggerID] [bigint] NOT NULL, CONSTRAINT [PrimaryKey2] PRIMARY KEY CLUSTERED ( [ID] ASC ) ) ALTER TABLE [dbo].[DCDistributionBox] ADD CONSTRAINT [FK_DCDistributionBox_DataLogger] FOREIGN KEY([DataLoggerID]) REFERENCES [dbo].[DataLogger] ([ID]) CREATE TABLE [dbo].[DCString] ( [ID] [bigint] IDENTITY(1,1) NOT NULL, [DCDistributionBoxID] [bigint] NOT NULL, [CurrentMPP] [decimal](18, 2) NULL, CONSTRAINT [PrimaryKey3] PRIMARY KEY CLUSTERED ( [ID] ASC ) ) ALTER TABLE [dbo].[DCString] ADD CONSTRAINT [FK_DCString_DCDistributionBox] FOREIGN KEY([DCDistributionBoxID]) REFERENCES [dbo].[DCDistributionBox] ([ID]) CREATE TABLE [dbo].[StringData] ( [DCStringID] [bigint] NOT NULL, [TimeStamp] [datetime] NOT NULL, [DCCurrent] [decimal](18, 2) NULL, CONSTRAINT [PrimaryKey4] PRIMARY KEY CLUSTERED ( [TimeStamp] DESC, [DCStringID] ASC) ) CREATE NONCLUSTERED INDEX [TimeStamp_DCCurrent-NonClusteredIndex] ON [dbo].[StringData] ([DCStringID] ASC, [TimeStamp] ASC) INCLUDE ([DCCurrent]) </code></pre> <p>Standard indexes on the foreign keys also exist (I don't want to list them all for space reasons).</p> <p>The <code>[StringData]</code> table as has following storage stats:</p> <ul> <li>Data space: 26,901.86 MB</li> <li>Row count: 131,827,749</li> <li>Partitioned: true</li> <li>Partition count: 62</li> </ul> <p><strong>Usage</strong>:</p> <p>I now want to group the data in the <code>[StringData]</code> table and do some aggregation.</p> <p>I created an Entity Framework query (detailed infos to the query can be found <a href="https://stackoverflow.com/questions/35436442">here</a>):</p> <pre><code>var compareData = model.StringDatas .AsNoTracking() .Where(p =&gt; p.DCString.DCDistributionBox.DataLogger.ProjectID == projectID &amp;&amp; p.TimeStamp &gt;= fromDate &amp;&amp; p.TimeStamp &lt; tillDate) .Select(d =&gt; new { TimeStamp = d.TimeStamp, DCCurrentMpp = d.DCCurrent / d.DCString.CurrentMPP }) .GroupBy(d =&gt; DbFunctions.AddMinutes(DateTime.MinValue, DbFunctions.DiffMinutes(DateTime.MinValue, d.TimeStamp) / minuteInterval * minuteInterval)) .Select(d =&gt; new { TimeStamp = d.Key, DCCurrentMppMin = d.Min(v =&gt; v.DCCurrentMpp), DCCurrentMppMax = d.Max(v =&gt; v.DCCurrentMpp), DCCurrentMppAvg = d.Average(v =&gt; v.DCCurrentMpp), DCCurrentMppStDev = DbFunctions.StandardDeviationP(d.Select(v =&gt; v.DCCurrentMpp)) }) .ToList(); </code></pre> <p>The excecution timespan is exceptional long!?</p> <ul> <li>Execution result: 92rows</li> <li>Execution time: ~16000ms</li> </ul> <p><strong>Attempts</strong>:</p> <p>I now took a look into the Entity Framework generated SQL query and looks like this:</p> <pre><code>DECLARE @p__linq__4 DATETIME = 0; DECLARE @p__linq__3 DATETIME = 0; DECLARE @p__linq__5 INT = 15; DECLARE @p__linq__6 INT = 15; DECLARE @p__linq__0 BIGINT = 20827; DECLARE @p__linq__1 DATETIME = '06.02.2016 00:00:00'; DECLARE @p__linq__2 DATETIME = '07.02.2016 00:00:00'; SELECT 1 AS [C1], [GroupBy1].[K1] AS [C2], [GroupBy1].[A1] AS [C3], [GroupBy1].[A2] AS [C4], [GroupBy1].[A3] AS [C5], [GroupBy1].[A4] AS [C6] FROM ( SELECT [Project1].[K1] AS [K1], MIN([Project1].[A1]) AS [A1], MAX([Project1].[A2]) AS [A2], AVG([Project1].[A3]) AS [A3], STDEVP([Project1].[A4]) AS [A4] FROM ( SELECT DATEADD (minute, ((DATEDIFF (minute, @p__linq__4, [Project1].[TimeStamp])) / @p__linq__5) * @p__linq__6, @p__linq__3) AS [K1], [Project1].[C1] AS [A1], [Project1].[C1] AS [A2], [Project1].[C1] AS [A3], [Project1].[C1] AS [A4] FROM ( SELECT [Extent1].[TimeStamp] AS [TimeStamp], [Extent1].[DCCurrent] / [Extent2].[CurrentMPP] AS [C1] FROM [dbo].[StringData] AS [Extent1] INNER JOIN [dbo].[DCString] AS [Extent2] ON [Extent1].[DCStringID] = [Extent2].[ID] INNER JOIN [dbo].[DCDistributionBox] AS [Extent3] ON [Extent2].[DCDistributionBoxID] = [Extent3].[ID] INNER JOIN [dbo].[DataLogger] AS [Extent4] ON [Extent3].[DataLoggerID] = [Extent4].[ID] WHERE (([Extent4].[ProjectID] = @p__linq__0) OR (([Extent4].[ProjectID] IS NULL) AND (@p__linq__0 IS NULL))) AND ([Extent1].[TimeStamp] &gt;= @p__linq__1) AND ([Extent1].[TimeStamp] &lt; @p__linq__2) ) AS [Project1] ) AS [Project1] GROUP BY [K1] ) AS [GroupBy1] </code></pre> <p>I copied this SQL query into SSMS on the same machine, connected with same connection string as the Entity Framework.</p> <p>The result is a very much improved performance:</p> <ul> <li>Execution result: 92rows</li> <li>Execution time: 517ms</li> </ul> <p>I also do some loop runing test and the result is strange. The test looks like this</p> <pre><code>for (int i = 0; i &lt; 50; i++) { DateTime begin = DateTime.UtcNow; [...query...] TimeSpan excecutionTimeSpan = DateTime.UtcNow - begin; Debug.WriteLine("{0}th run: {1}", i, excecutionTimeSpan.ToString()); } </code></pre> <p>The result is very different and looks random(?):</p> <pre><code>0th run: 00:00:11.0618580 1th run: 00:00:11.3339467 2th run: 00:00:10.0000676 3th run: 00:00:10.1508140 4th run: 00:00:09.2041939 5th run: 00:00:07.6710321 6th run: 00:00:10.3386312 7th run: 00:00:17.3422765 8th run: 00:00:13.8620557 9th run: 00:00:14.9041528 10th run: 00:00:12.7772906 11th run: 00:00:17.0170235 12th run: 00:00:14.7773750 </code></pre> <p><strong>Question</strong>:</p> <p>Why is Entity Framework query execution so slow? The resulting row count is really low and the raw SQL query shows a very fast performance.</p> <p><strong>Update 1</strong>:</p> <p>I take care that its not a MetaContext or Model creation delay. Some other queries are executed on the same Model instance right before with good performance.</p> <p><strong>Update 2</strong> (related to the answer of @x0007me):</p> <p>Thanks for the hint but this can be eliminated by changing the model settings like this:</p> <pre><code>modelContext.Configuration.UseDatabaseNullSemantics = true; </code></pre> <p>The EF generated SQL is now:</p> <pre><code>SELECT 1 AS [C1], [GroupBy1].[K1] AS [C2], [GroupBy1].[A1] AS [C3], [GroupBy1].[A2] AS [C4], [GroupBy1].[A3] AS [C5], [GroupBy1].[A4] AS [C6] FROM ( SELECT [Project1].[K1] AS [K1], MIN([Project1].[A1]) AS [A1], MAX([Project1].[A2]) AS [A2], AVG([Project1].[A3]) AS [A3], STDEVP([Project1].[A4]) AS [A4] FROM ( SELECT DATEADD (minute, ((DATEDIFF (minute, @p__linq__4, [Project1].[TimeStamp])) / @p__linq__5) * @p__linq__6, @p__linq__3) AS [K1], [Project1].[C1] AS [A1], [Project1].[C1] AS [A2], [Project1].[C1] AS [A3], [Project1].[C1] AS [A4] FROM ( SELECT [Extent1].[TimeStamp] AS [TimeStamp], [Extent1].[DCCurrent] / [Extent2].[CurrentMPP] AS [C1] FROM [dbo].[StringData] AS [Extent1] INNER JOIN [dbo].[DCString] AS [Extent2] ON [Extent1].[DCStringID] = [Extent2].[ID] INNER JOIN [dbo].[DCDistributionBox] AS [Extent3] ON [Extent2].[DCDistributionBoxID] = [Extent3].[ID] INNER JOIN [dbo].[DataLogger] AS [Extent4] ON [Extent3].[DataLoggerID] = [Extent4].[ID] WHERE ([Extent4].[ProjectID] = @p__linq__0) AND ([Extent1].[TimeStamp] &gt;= @p__linq__1) AND ([Extent1].[TimeStamp] &lt; @p__linq__2) ) AS [Project1] ) AS [Project1] GROUP BY [K1] ) AS [GroupBy1] </code></pre> <p>So you can see the problem you described is now solved, but the execution time does not change.</p> <p>Also, as you can see in the schema and the raw execution time, I used optimized structure with high optimized indexer.</p> <p><strong>Update 3</strong> (related to the answer of @Vladimir Baranov):</p> <p>I don't see why this can be related to query plan caching. Because in the MSDN is clearly descripted that the EF6 make use of query plan caching.</p> <p>A simple test proof that the huge excecution time differenz is not related to the query plan caching (phseudo code):</p> <pre><code>using(var modelContext = new ModelContext()) { modelContext.Query(); //1th run activates caching modelContext.Query(); //2th used cached plan } </code></pre> <p>As the result, both queries run with the same excecution time.</p> <p><strong>Update 4</strong> (related to the answer of @bubi):</p> <p>I tried to run the query that is generated by the EF as you descripted it:</p> <pre><code>int result = model.Database.ExecuteSqlCommand(@"SELECT 1 AS [C1], [GroupBy1].[K1] AS [C2], [GroupBy1].[A1] AS [C3], [GroupBy1].[A2] AS [C4], [GroupBy1].[A3] AS [C5], [GroupBy1].[A4] AS [C6] FROM ( SELECT [Project1].[K1] AS [K1], MIN([Project1].[A1]) AS [A1], MAX([Project1].[A2]) AS [A2], AVG([Project1].[A3]) AS [A3], STDEVP([Project1].[A4]) AS [A4] FROM ( SELECT DATEADD (minute, ((DATEDIFF (minute, 0, [Project1].[TimeStamp])) / @p__linq__5) * @p__linq__6, 0) AS [K1], [Project1].[C1] AS [A1], [Project1].[C1] AS [A2], [Project1].[C1] AS [A3], [Project1].[C1] AS [A4] FROM ( SELECT [Extent1].[TimeStamp] AS [TimeStamp], [Extent1].[DCCurrent] / [Extent2].[CurrentMPP] AS [C1] FROM [dbo].[StringData] AS [Extent1] INNER JOIN [dbo].[DCString] AS [Extent2] ON [Extent1].[DCStringID] = [Extent2].[ID] INNER JOIN [dbo].[DCDistributionBox] AS [Extent3] ON [Extent2].[DCDistributionBoxID] = [Extent3].[ID] INNER JOIN [dbo].[DataLogger] AS [Extent4] ON [Extent3].[DataLoggerID] = [Extent4].[ID] WHERE ([Extent4].[ProjectID] = @p__linq__0) AND ([Extent1].[TimeStamp] &gt;= @p__linq__1) AND ([Extent1].[TimeStamp] &lt; @p__linq__2) ) AS [Project1] ) AS [Project1] GROUP BY [K1] ) AS [GroupBy1]", new SqlParameter("p__linq__0", 20827), new SqlParameter("p__linq__1", fromDate), new SqlParameter("p__linq__2", tillDate), new SqlParameter("p__linq__5", 15), new SqlParameter("p__linq__6", 15)); </code></pre> <ul> <li>Execution result: 92</li> <li>Execution time: ~16000ms</li> </ul> <p>It took exact as long as the normal EF query!?</p> <p><strong>Update 5</strong> (related to the answer of @vittore):</p> <p>I create a traced call tree, maybe it helps:</p> <p><a href="https://i.stack.imgur.com/9G8tB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9G8tB.png" alt="call tree trace"></a></p> <p><strong>Update 6</strong> (related to the answer of @usr):</p> <p>I created two showplan XML via SQL Server Profiler.</p> <p><a href="http://pastebin.com/6We2u6Dg" rel="noreferrer">Fast run (SSMS).SQLPlan</a></p> <p><a href="http://pastebin.com/B2mty2R9" rel="noreferrer">Slow run (EF).SQLPlan</a></p> <p><strong>Update 7</strong> (related to the comments of @VladimirBaranov):</p> <p>I now run some more test case related to your comments.</p> <p>First I eleminate time taking order operations by using a new computed column and a matching INDEXER. This reduce the perfomance lag related to <code>DATEADD(MINUTE, DATEDIFF(MINUTE, 0, [TimeStamp] ) / 15* 15, 0)</code>. Detail for how and why you can find <a href="https://stackoverflow.com/questions/35436442">here</a>.</p> <p>The Result look s like this:</p> <p>Pure EntityFramework query:</p> <pre><code>for (int i = 0; i &lt; 3; i++) { DateTime begin = DateTime.UtcNow; var result = model.StringDatas .AsNoTracking() .Where(p =&gt; p.DCString.DCDistributionBox.DataLogger.ProjectID == projectID &amp;&amp; p.TimeStamp15Minutes &gt;= fromDate &amp;&amp; p.TimeStamp15Minutes &lt; tillDate) .Select(d =&gt; new { TimeStamp = d.TimeStamp15Minutes, DCCurrentMpp = d.DCCurrent / d.DCString.CurrentMPP }) .GroupBy(d =&gt; d.TimeStamp) .Select(d =&gt; new { TimeStamp = d.Key, DCCurrentMppMin = d.Min(v =&gt; v.DCCurrentMpp), DCCurrentMppMax = d.Max(v =&gt; v.DCCurrentMpp), DCCurrentMppAvg = d.Average(v =&gt; v.DCCurrentMpp), DCCurrentMppStDev = DbFunctions.StandardDeviationP(d.Select(v =&gt; v.DCCurrentMpp)) }) .ToList(); TimeSpan excecutionTimeSpan = DateTime.UtcNow - begin; Debug.WriteLine("{0}th run pure EF: {1}", i, excecutionTimeSpan.ToString()); } </code></pre> <p>0th run pure EF: <strong>00:00:12.6460624</strong></p> <p>1th run pure EF: <strong>00:00:11.0258393</strong></p> <p>2th run pure EF: <strong>00:00:08.4171044</strong></p> <p>I now used the EF generated SQL as a SQL query:</p> <pre><code>for (int i = 0; i &lt; 3; i++) { DateTime begin = DateTime.UtcNow; int result = model.Database.ExecuteSqlCommand(@"SELECT 1 AS [C1], [GroupBy1].[K1] AS [TimeStamp15Minutes], [GroupBy1].[A1] AS [C2], [GroupBy1].[A2] AS [C3], [GroupBy1].[A3] AS [C4], [GroupBy1].[A4] AS [C5] FROM ( SELECT [Project1].[TimeStamp15Minutes] AS [K1], MIN([Project1].[C1]) AS [A1], MAX([Project1].[C1]) AS [A2], AVG([Project1].[C1]) AS [A3], STDEVP([Project1].[C1]) AS [A4] FROM ( SELECT [Extent1].[TimeStamp15Minutes] AS [TimeStamp15Minutes], [Extent1].[DCCurrent] / [Extent2].[CurrentMPP] AS [C1] FROM [dbo].[StringData] AS [Extent1] INNER JOIN [dbo].[DCString] AS [Extent2] ON [Extent1].[DCStringID] = [Extent2].[ID] INNER JOIN [dbo].[DCDistributionBox] AS [Extent3] ON [Extent2].[DCDistributionBoxID] = [Extent3].[ID] INNER JOIN [dbo].[DataLogger] AS [Extent4] ON [Extent3].[DataLoggerID] = [Extent4].[ID] WHERE ([Extent4].[ProjectID] = @p__linq__0) AND ([Extent1].[TimeStamp15Minutes] &gt;= @p__linq__1) AND ([Extent1].[TimeStamp15Minutes] &lt; @p__linq__2) ) AS [Project1] GROUP BY [Project1].[TimeStamp15Minutes] ) AS [GroupBy1];", new SqlParameter("p__linq__0", 20827), new SqlParameter("p__linq__1", fromDate), new SqlParameter("p__linq__2", tillDate)); TimeSpan excecutionTimeSpan = DateTime.UtcNow - begin; Debug.WriteLine("{0}th run: {1}", i, excecutionTimeSpan.ToString()); } </code></pre> <p>0th run: <strong>00:00:00.8381200</strong></p> <p>1th run: <strong>00:00:00.6920736</strong></p> <p>2th run: <strong>00:00:00.7081006</strong></p> <p>and with <code>OPTION(RECOMPILE)</code>:</p> <pre><code>for (int i = 0; i &lt; 3; i++) { DateTime begin = DateTime.UtcNow; int result = model.Database.ExecuteSqlCommand(@"SELECT 1 AS [C1], [GroupBy1].[K1] AS [TimeStamp15Minutes], [GroupBy1].[A1] AS [C2], [GroupBy1].[A2] AS [C3], [GroupBy1].[A3] AS [C4], [GroupBy1].[A4] AS [C5] FROM ( SELECT [Project1].[TimeStamp15Minutes] AS [K1], MIN([Project1].[C1]) AS [A1], MAX([Project1].[C1]) AS [A2], AVG([Project1].[C1]) AS [A3], STDEVP([Project1].[C1]) AS [A4] FROM ( SELECT [Extent1].[TimeStamp15Minutes] AS [TimeStamp15Minutes], [Extent1].[DCCurrent] / [Extent2].[CurrentMPP] AS [C1] FROM [dbo].[StringData] AS [Extent1] INNER JOIN [dbo].[DCString] AS [Extent2] ON [Extent1].[DCStringID] = [Extent2].[ID] INNER JOIN [dbo].[DCDistributionBox] AS [Extent3] ON [Extent2].[DCDistributionBoxID] = [Extent3].[ID] INNER JOIN [dbo].[DataLogger] AS [Extent4] ON [Extent3].[DataLoggerID] = [Extent4].[ID] WHERE ([Extent4].[ProjectID] = @p__linq__0) AND ([Extent1].[TimeStamp15Minutes] &gt;= @p__linq__1) AND ([Extent1].[TimeStamp15Minutes] &lt; @p__linq__2) ) AS [Project1] GROUP BY [Project1].[TimeStamp15Minutes] ) AS [GroupBy1] OPTION(RECOMPILE);", new SqlParameter("p__linq__0", 20827), new SqlParameter("p__linq__1", fromDate), new SqlParameter("p__linq__2", tillDate)); TimeSpan excecutionTimeSpan = DateTime.UtcNow - begin; Debug.WriteLine("{0}th run: {1}", i, excecutionTimeSpan.ToString()); } </code></pre> <p>0th run with RECOMPILE: <strong>00:00:00.8260932</strong></p> <p>1th run with RECOMPILE: <strong>00:00:00.9139730</strong></p> <p>2th run with RECOMPILE: <strong>00:00:01.0680665</strong></p> <p>Same SQL query excecuted in SSMS (without RECOMPILE):</p> <p><strong>00:00:01.105</strong></p> <p>Same SQL query excecuted in SSMS (with RECOMPILE):</p> <p><strong>00:00:00.902</strong></p> <p>I hope this are all values you needed.</p>
35,552,124
4
30
null
2016-02-16 23:59:16.413 UTC
13
2019-07-08 11:03:31.757 UTC
2017-05-23 11:46:46.347 UTC
null
-1
null
1,112,048
null
1
25
c#|sql-server|entity-framework|sql-server-2008|entity-framework-6
13,768
<p>In this answer I'm focusing on the original observation: the query generated by EF is slow, but when the same query is run in SSMS it is fast.</p> <p>One possible explanation of this behaviour is <a href="https://www.brentozar.com/archive/2013/06/the-elephant-and-the-mouse-or-parameter-sniffing-in-sql-server/" rel="noreferrer">Parameter sniffing</a>.</p> <blockquote> <p>SQL Server uses a process called parameter sniffing when it executes stored procedures that have parameters. When the procedure is compiled or recompiled, the value passed into the parameter is evaluated and used to create an execution plan. That value is then stored with the execution plan in the plan cache. On subsequent executions, that same value – and same plan – is used.</p> </blockquote> <p>So, EF generates a query that has few parameters. The first time you run this query the server creates an execution plan for this query using values of parameters that were in effect in the first run. That plan is usually pretty good. But, later on you run the same EF query using other values for parameters. It is possible that for new values of parameters the previously generated plan is not optimal and the query becomes slow. The server keeps using the previous plan, because it is still the same query, just values of parameters are different.</p> <p>If at this moment you take the query text and try to run it directly in SSMS the server will create a new execution plan, because technically it is not the same query that is issued by EF application. Even one character difference is enough, any change in the session settings is also enough for the server to treat the query as a new one. As a result the server has two plans for the seemingly same query in its cache. The first "slow" plan is slow for the new values of parameters, because it was originally built for different parameter values. The second "fast" plan is built for the current parameter values, so it is fast.</p> <p>The article <a href="http://www.sommarskog.se/query-plan-mysteries.html" rel="noreferrer">Slow in the Application, Fast in SSMS</a> by Erland Sommarskog explains this and other related areas in much more details.</p> <p>There are several ways to discard cached plans and force the server to regenerate them. Changing the table or changing the table indexes should do it - it should discard all plans that are related to this table, both "slow" and "fast". Then you run the query in EF application with new values of parameters and get a new "fast" plan. You run the query in SSMS and get a second "fast" plan with new values of parameters. The server still generates two plans, but both plans are fast now.</p> <p>Another variant is adding <code>OPTION(RECOMPILE)</code> to the query. With this option the server would not store the generated plan in its cache. So, every time the query runs the server would use actual parameter values to generate the plan that (it thinks) would be optimal for the given parameter values. The downside is an added overhead of the plan generation.</p> <p>Mind you, the server still could choose a "bad" plan with this option due to outdated statistics, for example. But, at least, parameter sniffing would not be a problem.</p> <hr> <p>Those who wonder how to add <code>OPTION (RECOMPILE)</code> hint to the query that is generated by EF have a look at this answer:</p> <p><a href="https://stackoverflow.com/a/26762756/4116017">https://stackoverflow.com/a/26762756/4116017</a></p>
33,169,404
In Python, why should one use JSON scheme instead of a dictionary?
<p>(This is an edit of the original question) <em>&quot;What's the difference between Python Dictionary and JSON?&quot;</em> <em><strong>&quot;needed clarity&quot;</strong></em> although for me it is very clear and logical! Anyway, here's an attempt to &quot;improve&quot; it ...</p> <hr /> <p>Is there any benefit in converting a Python dictionary to JSON, except for transferability between different platforms and languages? Look at the following example:</p> <pre><code>d = {'a':111, 'b':222, 'c':333} print('Dictionary:', d) j = json.dumps(d, indent=4) print('JSON:\n%s' % j) </code></pre> <p>Output:</p> <pre><code>Dictionary: {'a': 111, 'b': 222, 'c': 333} JSON: { &quot;a&quot;: 111, &quot;b&quot;: 222, &quot;c&quot;: 333 } </code></pre> <p>They are almost identical. So, why should one use JSON?</p>
33,169,622
2
5
null
2015-10-16 11:29:58.38 UTC
12
2021-07-16 00:16:30.82 UTC
2021-07-16 00:16:30.82 UTC
null
13,412,932
null
3,250,984
null
1
35
python|json
58,549
<p>It is apples vs. oranges comparison: JSON is a data format (a string), Python dictionary is a data structure (in-memory object).</p> <p>If you need to exchange data between different (perhaps even non-Python) processes then you could use JSON format to <em>serialize</em> your Python dictionary.</p> <p>The text representation of a dictionary looks like (but it is not) json format:</p> <pre><code>&gt;&gt;&gt; print(dict(zip('abc', range(3)))) {'a': 0, 'b': 1, 'c': 2} </code></pre> <p>Text representation (a string) of an object is not the object itself (even string objects and their text representations are different things e.g., <code>"\n"</code> is a single newline character but obviously its text representation is several characters).</p>
13,440,549
GCC verbose mode output explanation
<p>I'm new to linux. Can anyone explain to me the following verbose mode output for my hello world program? Also, what do the files <code>crt1.o</code>, <code>crti.o</code>, <code>crtend.o</code>, <code>crtbegin.o</code> and <code>crtn.o</code> and <code>lc</code> and <code>lgcc</code> do? Any other explanatory links are also welcome.</p> <pre><code>$ gcc -v hello.c Reading specs from /usr/lib/gcc-lib/i686/3.3.1/specs Configured with: ../configure --prefix=/usr Thread model: posix gcc version 3.3.1 /usr/lib/gcc-lib/i686/3.3.1/cc1 -quiet -v -D__GNUC__=3 -D__GNUC_MINOR__=3 -D__GNUC_PATCHLEVEL__=1 hello.c -quiet -dumpbase hello.c -auxbase hello -Wall -version -o /tmp/cceCee26.s GNU C version 3.3.1 (i686-pc-linux-gnu) compiled by GNU C version 3.3.1 (i686-pc-linux-gnu) GGC heuristics: --param ggc-min-expand=51 --param ggc-min-heapsize=40036 ignoring nonexistent directory "/usr/i686/include" #include "..." search starts here: #include &lt;...&gt; search starts here: /usr/local/include /usr/include /usr/lib/gcc-lib/i686/3.3.1/include /usr/include End of search list. as -V -Qy -o /tmp/ccQynbTm.o /tmp/cceCee26.s GNU assembler version 2.12.90.0.1 (i386-linux) using BFD version 2.12.90.0.1 20020307 Debian/GNU Linux /usr/lib/gcc-lib/i686/3.3.1/collect2 --eh-frame-hdr -m elf_i386 -dynamic-linker /lib/ld-linux.so.2 /usr/lib/crt1.o /usr/lib/crti.o /usr/lib/gcc-lib/i686/3.3.1/crtbegin.o -L/usr/lib/gcc-lib/i686/3.3.1 -L/usr/lib/gcc-lib/i686/3.3.1/../../.. /tmp/ccQynbTm.o -lgcc -lgcc_eh -lc -lgcc -lgcc_eh /usr/lib/gcc-lib/i686/3.3.1/crtend.o /usr/lib/crtn.o </code></pre>
13,456,065
1
2
null
2012-11-18 13:26:43.987 UTC
11
2019-07-31 07:05:05.68 UTC
2012-11-19 13:38:58.427 UTC
null
29,995
null
1,232,311
null
1
27
linux|gcc|verbose
71,191
<p>The first part is the version and configuration data for the compiler driver (that's the <code>gcc</code> binary, which is not actually the compiler itself):</p> <pre><code>Reading specs from /usr/lib/gcc-lib/i686/3.3.1/specs Configured with: ../configure --prefix=/usr Thread model: posix gcc version 3.3.1 </code></pre> <p>Then it prints the command it uses to call the real compiler, <code>cc1</code>:</p> <pre><code> /usr/lib/gcc-lib/i686/3.3.1/cc1 -quiet -v -D__GNUC__=3 -D__GNUC_MINOR__=3 -D__GNUC_PATCHLEVEL__=1 hello.c -quiet -dumpbase hello.c -auxbase hello -Wall -version -o /tmp/cceCee26.s </code></pre> <p>And <code>cc1</code> prints it's version and config info.</p> <pre><code>GNU C version 3.3.1 (i686-pc-linux-gnu) compiled by GNU C version 3.3.1 (i686-pc-linux-gnu) GGC heuristics: --param ggc-min-expand=51 --param ggc-min-heapsize=40036 </code></pre> <p>Then <code>cc1</code> tells you what directories it will search for include files.</p> <pre><code>ignoring nonexistent directory "/usr/i686/include" #include "..." search starts here: #include &lt;...&gt; search starts here: /usr/local/include /usr/include /usr/lib/gcc-lib/i686/3.3.1/include /usr/include End of search list. </code></pre> <p>The compiler is now complete, so <code>gcc</code> tells you the assembler command it will use.</p> <pre><code> as -V -Qy -o /tmp/ccQynbTm.o /tmp/cceCee26.s </code></pre> <p>And the assembler, <code>as</code>, gives its version info.</p> <pre><code>GNU assembler version 2.12.90.0.1 (i386-linux) using BFD version 2.12.90.0.1 20020307 Debian/GNU Linux </code></pre> <p>The assembler is now done so <code>gcc</code> gives the linker command. It's using <code>collect2</code> as an intermediary to the real linker <code>ld</code>, but that's not important here.</p> <pre><code>/usr/lib/gcc-lib/i686/3.3.1/collect2 --eh-frame-hdr -m elf_i386 -dynamic-linker /lib/ld-linux.so.2 /usr/lib/crt1.o /usr/lib/crti.o /usr/lib/gcc-lib/i686/3.3.1/crtbegin.o -L/usr/lib/gcc-lib/i686/3.3.1 -L/usr/lib/gcc-lib/i686/3.3.1/../../.. /tmp/ccQynbTm.o -lgcc -lgcc_eh -lc -lgcc -lgcc_eh /usr/lib/gcc-lib/i686/3.3.1/crtend.o /usr/lib/crtn.o </code></pre> <p>The linker gives no verbose output (try <code>-Wl,-v</code>), so that's it.</p> <p>The "crt" files mean "C RunTime". They are small sections of code inserted at the start of your program, and at the end. They take care of initialising your global variables, heap, and stack. They call <code>atexit</code> functions after you return from <code>main</code>. And some more besides. </p> <p>Hope that helps.</p>
13,485,468
How to map and remove nil values in Ruby
<p>I have a <code>map</code> which either changes a value or sets it to nil. I then want to remove the nil entries from the list. The list doesn't need to be kept.</p> <p>This is what I currently have:</p> <pre class="lang-rb prettyprint-override"><code># A simple example function, which returns a value or nil def transform(n) rand &gt; 0.5 ? n * 10 : nil } end items.map! { |x| transform(x) } # [1, 2, 3, 4, 5] =&gt; [10, nil, 30, 40, nil] items.reject! { |x| x.nil? } # [10, nil, 30, 40, nil] =&gt; [10, 30, 40] </code></pre> <p>I'm aware I could just do a loop and conditionally collect in another array like this:</p> <pre class="lang-rb prettyprint-override"><code>new_items = [] items.each do |x| x = transform(x) new_items.append(x) unless x.nil? end items = new_items </code></pre> <p>But it doesn't seem that idiomatic. Is there a nice way to map a function over a list, removing/excluding the nils as you go?</p>
57,323,856
9
2
null
2012-11-21 02:29:13.47 UTC
54
2021-07-05 13:28:49.887 UTC
2019-12-15 21:50:28.903 UTC
null
128,421
null
647,107
null
1
418
ruby
314,591
<p><strong>Ruby 2.7+</strong></p> <p><em>There is now!</em></p> <p>Ruby 2.7 is introducing <code>filter_map</code> for this exact purpose. It's idiomatic and performant, and I'd expect it to become the norm very soon.</p> <p>For example:</p> <pre><code>numbers = [1, 2, 5, 8, 10, 13] enum.filter_map { |i| i * 2 if i.even? } # =&gt; [4, 16, 20] </code></pre> <p>In your case, as the block evaluates to falsey, simply:</p> <pre><code>items.filter_map { |x| process_x url } </code></pre> <p>&quot;<a href="https://blog.saeloun.com/2019/05/25/ruby-2-7-enumerable-filter-map.html" rel="noreferrer">Ruby 2.7 adds Enumerable#filter_map</a>&quot; is a good read on the subject, with some performance benchmarks against some of the earlier approaches to this problem:</p> <pre><code>N = 100_000 enum = 1.upto(1_000) Benchmark.bmbm do |x| x.report(&quot;select + map&quot;) { N.times { enum.select { |i| i.even? }.map{ |i| i + 1 } } } x.report(&quot;map + compact&quot;) { N.times { enum.map { |i| i + 1 if i.even? }.compact } } x.report(&quot;filter_map&quot;) { N.times { enum.filter_map { |i| i + 1 if i.even? } } } end # Rehearsal ------------------------------------------------- # select + map 8.569651 0.051319 8.620970 ( 8.632449) # map + compact 7.392666 0.133964 7.526630 ( 7.538013) # filter_map 6.923772 0.022314 6.946086 ( 6.956135) # --------------------------------------- total: 23.093686sec # # user system total real # select + map 8.550637 0.033190 8.583827 ( 8.597627) # map + compact 7.263667 0.131180 7.394847 ( 7.405570) # filter_map 6.761388 0.018223 6.779611 ( 6.790559) </code></pre>
13,395,114
How to initialize List<String> object in Java?
<p>I can not initialize a List as in the following code:</p> <pre><code>List&lt;String&gt; supplierNames = new List&lt;String&gt;(); supplierNames.add("sup1"); supplierNames.add("sup2"); supplierNames.add("sup3"); System.out.println(supplierNames.get(1)); </code></pre> <p>I face the following error: </p> <blockquote> <p>Cannot instantiate the type <code>List&lt;String&gt;</code></p> </blockquote> <p>How can I instantiate <code>List&lt;String&gt;</code>?</p>
13,395,230
13
1
null
2012-11-15 10:01:09.583 UTC
106
2022-05-27 15:37:06.003 UTC
2014-10-17 16:33:50.713 UTC
null
1,683,669
null
1,824,361
null
1
499
java|list
1,747,302
<p>If you check the <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html" rel="noreferrer">API</a> for <code>List</code> you'll notice it says:</p> <pre><code>Interface List&lt;E&gt; </code></pre> <p>Being an <code>interface</code> means it cannot be instantiated (no <code>new List()</code> is possible).</p> <p>If you check that link, you'll find some <code>class</code>es that implement <code>List</code>:</p> <blockquote> <p>All Known Implementing Classes:</p> <p><code>AbstractList</code>, <code>AbstractSequentialList</code>, <code>ArrayList</code>, <code>AttributeList</code>, <code>CopyOnWriteArrayList</code>, <code>LinkedList</code>, <code>RoleList</code>, <code>RoleUnresolvedList</code>, <code>Stack</code>, <code>Vector</code></p> </blockquote> <p>Some of those can be instantiated (the ones that are not defined as <code>abstract class</code>). Use their links to know more about them, I.E: to know which fits better your needs.</p> <p>The 3 most commonly used ones probably are:</p> <pre><code> List&lt;String&gt; supplierNames1 = new ArrayList&lt;String&gt;(); List&lt;String&gt; supplierNames2 = new LinkedList&lt;String&gt;(); List&lt;String&gt; supplierNames3 = new Vector&lt;String&gt;(); </code></pre> <hr /> <p>Bonus:<br /> You can also instantiate it with values, in an easier way, using the <code>Arrays</code> <code>class</code>, as follows:</p> <pre><code>List&lt;String&gt; supplierNames = Arrays.asList(&quot;sup1&quot;, &quot;sup2&quot;, &quot;sup3&quot;); System.out.println(supplierNames.get(1)); </code></pre> <p>But note you are not allowed to add more elements to that list, as it's <code>fixed-size</code>.</p>
20,627,138
TypeScript "this" scoping issue when called in jquery callback
<p>I'm not sure of the best approach for handling scoping of &quot;this&quot; in TypeScript.</p> <p>Here's an example of a common pattern in the code I am converting over to TypeScript:</p> <pre><code>class DemonstrateScopingProblems { private status = &quot;blah&quot;; public run() { alert(this.status); } } var thisTest = new DemonstrateScopingProblems(); // works as expected, displays &quot;blah&quot;: thisTest.run(); // doesn't work; this is scoped to be the document so this.status is undefined: $(document).ready(thisTest.run); </code></pre> <p>Now, I could change the call to...</p> <pre><code>$(document).ready(thisTest.run.bind(thisTest)); </code></pre> <p>...which does work. But it's kinda horrible. It means that code can all compile and work fine in some circumstances, but if we forget to bind the scope it will break.</p> <p>I would like a way to do it within the class, so that when using the class we don't need to worry about what &quot;this&quot; is scoped to.</p> <p>Any suggestions?</p> <h1>Update</h1> <p>Another approach that works is using the fat arrow:</p> <pre><code>class DemonstrateScopingProblems { private status = &quot;blah&quot;; public run = () =&gt; { alert(this.status); } } </code></pre> <p>Is that a valid approach?</p>
20,627,988
4
3
null
2013-12-17 06:06:53.09 UTC
44
2021-10-20 11:01:31.523 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
45,031
null
1
113
typescript|this
60,265
<p>You have a few options here, each with its own trade-offs. Unfortunately there is no obvious best solution and it will really depend on the application.</p> <p><strong>Automatic Class Binding</strong><br> As shown in your question:</p> <pre><code>class DemonstrateScopingProblems { private status = "blah"; public run = () =&gt; { alert(this.status); } } </code></pre> <ul> <li>Good/bad: This creates an additional closure per method per instance of your class. If this method is usually only used in regular method calls, this is overkill. However, if it's used a lot in callback positions, it's more efficient for the class instance to capture the <code>this</code> context instead of each call site creating a new closure upon invoke.</li> <li>Good: Impossible for external callers to forget to handle <code>this</code> context</li> <li>Good: Typesafe in TypeScript</li> <li>Good: No extra work if the function has parameters</li> <li>Bad: Derived classes can't call base class methods written this way using <code>super.</code></li> <li>Bad: The exact semantics of which methods are "pre-bound" and which aren't create an additional non-typesafe contract between your class and its consumers.</li> </ul> <p><strong>Function.bind</strong><br> Also as shown:</p> <pre><code>$(document).ready(thisTest.run.bind(thisTest)); </code></pre> <ul> <li>Good/bad: Opposite memory/performance trade-off compared to the first method</li> <li>Good: No extra work if the function has parameters</li> <li>Bad: In TypeScript, this currently has no type safety</li> <li>Bad: Only available in ECMAScript 5, if that matters to you</li> <li>Bad: You have to type the instance name twice</li> </ul> <p><strong>Fat arrow</strong><br> In TypeScript (shown here with some dummy parameters for explanatory reasons):</p> <pre><code>$(document).ready((n, m) =&gt; thisTest.run(n, m)); </code></pre> <ul> <li>Good/bad: Opposite memory/performance trade-off compared to the first method</li> <li>Good: In TypeScript, this has 100% type safety</li> <li>Good: Works in ECMAScript 3</li> <li>Good: You only have to type the instance name once</li> <li>Bad: You'll have to type the parameters twice</li> <li>Bad: Doesn't work with variadic parameters</li> </ul>
3,425,869
Data-oriented design in practice?
<p>There has been <a href="https://stackoverflow.com/questions/1641580/what-is-data-oriented-design">one more question</a> on what data-oriented design is, and there's one <a href="http://gamesfromwithin.com/data-oriented-design" rel="noreferrer">article</a> which is often referred to (and I've read it like 5 or 6 times already). I understand the general concept of this, especially when dealing with, for example, 3d models, where you'd like to keep all vertexes together, and not pollute your faces with normals, etc.</p> <p>However, I do have a hard time visualizing how data-oriented design might work for anything but the most trivial cases (3d models, particles, BSP-trees, and so on). Are there any good examples out there which really embraces data-oriented design and shows how this might work in practice? I can plow through large code-bases if needed.</p> <p>What I'm especially interested in is the mantra "where there's one there are many", which I can't really seem to connect with the rest here. Yes, there are always more than one enemy, yet, you still need to update each enemy individually, cause they're not moving the same way now are they? Same goes for the 'balls'-example in the accepted answer to the question above (I actually asked this in a comment to that answer, but haven't gotten a reply yet). Is it simply that the rendering will only need the positions, and not the velocities, whereas the game simulation will need both, but not the materials? Or am I missing something? Perhaps I've already understood it and it's a far more straightforward concept than I thought.</p> <p>Any pointers would be much appreciated!</p>
9,873,278
2
0
null
2010-08-06 16:44:04.083 UTC
14
2019-08-21 11:55:25.083 UTC
2017-05-23 12:25:13.63 UTC
null
-1
null
46,991
null
1
24
data-oriented-design
9,318
<p>So, what is DOD all about? Obviously, it's about performance, but it's not just that. It's also about well-designed code that is readable, easy to understand and even reusable. Now Object Oriented design is all about designing code and data to fit into encapsulated virtual "objects". Each object is a seperate entity with variables for properties that object might have and methods to take action on itself or other objects in the world. The advantage of OO design is that it's easy to mentally model your code into objects because the whole (real) world around us seems to work in the same way. Objects with properties that can interact with each other.</p> <p>Now the problem is that the cpu in your computer works in a completely different way. It works best when you let it do the same things again and again. Why is that? Because of a little thing called cache. Accessing RAM on a modern computer can take 100 or 200 CPU cycles (and the CPU has to wait all that time!), which is way too long. So there's this small portion of memory on the CPU that can be accessed really quickly, cache memory. Problem is it's only a few MB tops. So every time you need data that wasn't in cache, you still need to go the long way to RAM. That's not just that way for data, the same goes for code. Trying to execute a function that's not in instruction cache will cause a stall while the code is loaded from RAM.</p> <p>Back to OO programming. Objects are big, but most functions need only a small portion of that data, so we're wasting cache by loading unnecessary data. Methods call other methods which call other methods, thrashing your instruction cache. Still, we often do a lot of the same stuff over and over again. Let's take a bullet from a game for example. In a naive implementation each bullet could be a separate object. There might be a bullet manager class. It calls the first bullet's update function. It updates the 3D position using the direction/velocity. This causes a lot of other data from the object to be loaded into the cache. Next, we call the World Manager class to check for a collision with other objects. This loads lots of other stuff into the cache, maybe it even causes code from the original bullet manager class to get dropped from instruction cache. Now we return to the bullet update, there was no collision, so we return to bullet manager. It might need to load some code again. Next up, bullet #2 update. This loads lots of data into the cache, calls world... etc. So in this hypthetical situation, we've got 2 stalls for loading code and let's say 2 stalls for loading data. That's at least 400 cycles wasted, for 1 bullet, and we haven't taken bullets that hit something else into account. Now a CPU runs at 3+ GHz so we're not going to notice one bullet, but what if we've got 100 bullets? Or even more?</p> <p>So this is the where there's one there's many story. Yes, there are some cases where you've only got on object, your manager classes, file access, etc. But more often, there's a lot of similar cases. Naive, or even not-naive object oriented design will lead to lots of problems. So enter data oriented design. The key of DOD is to model your code around your data, not the other way around as with OO-design. This starts at the first stages of design. You do not first design your OO code and then optimize it. You start by listing and examining your data and thinking out how you want to modify it(I'll get to a practical example in a moment). Once you know how your code is going to modify the data you can lay it out in a way that makes it as efficient as possible to process it. Now you may think this can only lead to a horrible soup of code and data everywhere but that is only the case if you design it badly (bad design is just as easy with OO programming). If you design it well, code and data can be neatly designed around specific functionality, leading to very readable and even very reusable code.</p> <p>So back to our bullets. Instead of creating a class for each bullet, we only keep the bullet manager. Each bullet has a position and a velocity. Each bullet's position needs to be updated. Each bullet has to have a collision check and all bullets that have hit something need to take some action accordingly. So just by taking a look at this description I can design this whole system in a much better way. Let's put the positions of all bullets in an array/vector. Let's put the velocity of all bullets in an array/vector. Now let's start by iterating allong those two arrays and updating each position value with it's corresponding velocity. Now, all data loaded into the data cache is data we're going to use. We can even put a smart pre-loading command to already pre-load some array data in advance so the data's in cache when we get to it. Next, collision check. I'm not going into detail here, but you can imagine how updating all bullets after each other can help. Also note that if there's a collision, we're not going to call a new function or do anything. We just keep a vector with all bullets that had collision and when collision checking is done, we can update all those after each other. See how we just went from lots of memory access to almost none by laying our data out differently? Did you also notice how our code and data, even though not designed in an OO way any more, are still easy to understand and easy to reuse?</p> <p>So to get back to the "where there's one there's many". When designing OO code you think about one object, the prototype/class. A bullet has a velocity, a bullet has a position, a bullet will move each frame by it's velocity, a bullet can hit something, etc. When you think about that, you will think about a class, with velocity, position, and an update function which moves the bullet and checks for collision. However, when you have multiple objects you need to think about all of them. Bullets have positions, velocity. Some bullets may have collision. Do you see how we're not thinking about an individual object any longer? We're thinking about all of them and are designing code a lot differently now.</p> <p>I hope this helps answer your second part of the question. It's not about whether you need to update each enemy or not, it's about the most efficient way to update them. And while designing only your enemies using DOD may not help gain much performance, designing the entire game around these principles (only where applicable!) may lead to a lot of performance gains!</p> <p>So onto the first part of the question, that is other examples of DOD. I'm sorry but I don't have that much there. There is one really good example though, I came across this some time ago, a series on data oriented design of a behavior tree by Bjoern Knafla: <a href="http://bjoernknafla.com/data-oriented-behavior-tree-overview" rel="noreferrer">http://bjoernknafla.com/data-oriented-behavior-tree-overview</a> You probably want to start at the first one in the series of 4, links are in the article itself. Hope this still helps, despite the old question. Or maybe some other SO user come across this question and have some use from this answer.</p>
3,621,721
marking existing column as primary key in datatable
<p>I have a datatable from database on the basis of some query.</p> <p>I want that datatable to have a primary key for an existing column.</p> <p>How can I do this?</p>
3,621,752
2
0
null
2010-09-01 20:03:26.13 UTC
6
2017-01-18 06:53:35.49 UTC
2010-09-01 20:10:17.207 UTC
null
23,199
null
357,261
null
1
30
.net|datatable
44,352
<p>Assuming the name of the column in your data table you want to be the primary key is called <code>pk_column</code>, you could do this (assume <code>dt</code> is your <code>DataTable</code>):</p> <pre><code>dt.PrimaryKey = new DataColumn[] { dt.Columns["pk_column"] }; </code></pre> <p>If your primary key is made up of multiple columns, you can add them to the array, like so:</p> <pre><code>dt.PrimaryKey = new DataColumn[] { dt.Columns["pk_column1"], dt.Columns["pk_column2"] }; </code></pre> <p>So if you were making student_id your primary key, you could do this:</p> <pre><code>dt.PrimaryKey = new DataColumn[] { dt.Columns["student_id"] }; </code></pre>
4,016,117
Default EJB transaction mode for asynchronous methods?
<ol> <li><p>When I have an <code>@Asynchronous</code> method in an EJB, and I don't specify the <code>@TransactionAttribute</code>, then how exactly does the container handle the transaction boundaries? Obviously, it can't use the calling thread's transaction, so what does it do?</p></li> <li><p>Same question, but regarding methods that are triggered by the TimerService. </p></li> </ol> <hr> <p>EDIT: I think I phrased that poorly. I already know that the default mode is 'REQUIRED'. So it should be safe to assume that those methods will always be called within a transaction. But my question is, what does that transaction's life-cycle look like? Does the container create a new transaction for each call? Or does it re-use the same transaction for all the calls on an asynchronous worker thread? If it's the latter, then when does the transaction get closed?</p>
4,029,234
2
0
null
2010-10-25 15:29:25.767 UTC
9
2022-02-17 22:37:52.97 UTC
2010-10-25 17:21:31.65 UTC
null
365,719
null
365,719
null
1
36
java|jakarta-ee|glassfish|ejb|ejb-3.1
16,018
<p>Similar to an MDB the transaction is started by the container just before your <code>@Asynchronous</code>, <code>@Schedule</code> or <code>@Timeout</code> method (and applicable interceptors) is actually invoked and committed just after the method (and interceptors) completes.</p> <p>As per usual, the transaction propagates to all beans called in said method and all beans those beans call, recursively. Of course other beans invoked are welcome to change the transaction semantics of their method call via specifying other <code>@TransactionAttribute</code> settings (say <code>REQUIRES_NEW</code>, or <code>NOT_SUPPORTED</code>).</p> <p>Side note, transactions are never propagated to beans with <code>@TransactionManagement(BEAN)</code>. The container will <em>always</em> suspend any transaction in progress before invoking a method on a Bean-Managed Transaction bean.</p> <p>EDIT:</p> <p>Answering the edited question more directly; there are no means via the Java Transaction API to have one transaction span several threads and therefore no means in EJB. Every <code>@Asynchronous</code> call is completely disconnected from the caller's transaction (if any). You will essentially get either a new transaction, no transaction, or an exception depending on what <code>@TransactionAttribute</code> you used. Same with any calls from the <code>TimerService</code>.</p>
3,766,433
What is difference in adodb and oledb?
<p>What is the difference between <code>adodb</code> and <code>oledb</code>?</p> <p>What is the relation between these two?</p> <p>Where does <code>ado.net</code> stands in context of <code>adodb</code> and <code>oledb</code>?</p>
3,766,472
2
1
null
2010-09-22 05:01:24.96 UTC
4
2016-10-07 06:33:47.697 UTC
null
null
null
null
13,198
null
1
43
ado.net|oledb|adodb
49,724
<p><a href="http://en.wikipedia.org/wiki/ActiveX_Data_Objects" rel="noreferrer">Adodb (ActiveX Data Objects DB)</a> is an API layer over OLE DB. It works well with MS-based databases such as Sql Server, providing a consistent API and optimizations. That being said you can use ADODB to connect with non-MS data sources as well but that would mean that you will require an OLEDB/ODBC Provider for the data source. </p> <p>In simpler terms, to connect to any data source you need a driver. Here are a couple of common scenarios to think of:</p> <ol> <li>ADODB for Data Source that has ODBC Driver Only - ADODB uses OLEDB Provider for ODBC which loads ODBC Driver which then connects to Data Source.</li> <li>ADODB for Data Source with OLEDB Driver (like SQL Server) - ADODB uses OLEDB Provider for SQL Server to talk directly with DB.</li> </ol> <p><a href="http://en.wikipedia.org/wiki/OLEDB" rel="noreferrer">Oledb (Object Linking and Embedding DB)</a> is a standard format supported by a large number of dbs, so you can connect to oracle, db2 etc. using Oledb. You can also use OLEDB directly to connect to Sql Server but the API is messier as compared to a adodb connection which is optimized to work with Sql Server and MS Access.</p> <p>ADO.Net is a .Net based db connection "architecture". In ADO.Net there's a library for Oledb - System.Data.OledbClient. Adodb has been replaced/upgraded and ADO.Net now uses the System.Data.SqlClient library for MS-based databases/data providers.</p>
29,362,394
Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)
<p>I have installed Laravel 5 successfully and changed MySQL credentials in database.php file in config directory to '</p> <pre><code>mysql' =&gt; [ 'driver' =&gt; 'mysql', 'host' =&gt; env('DB_HOST', 'localhost'), 'database' =&gt; env('DB_DATABASE', 'wdcollect'), 'username' =&gt; env('DB_USERNAME', 'root'), 'password' =&gt; env('DB_PASSWORD', ''), 'charset' =&gt; 'utf8', 'collation' =&gt; 'utf8_unicode_ci', 'prefix' =&gt; '', 'strict' =&gt; false, ], </code></pre> <p>I don't want to use homestead and I have changed .env file to</p> <pre><code>APP_ENV=local APP_DEBUG=true APP_KEY=apLIzEMOgtc5BUxdT9WRLSvAoIIWO87N DB_HOST=localhost DB_DATABASE=wdcollect DB_USERNAME=root DB_PASSWORD= CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=sync MAIL_DRIVER=smtp MAIL_HOST=mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null </code></pre> <p>I don't understand that why it's saying that access denied for 'homestead'@'localhost'</p>
29,406,025
31
3
null
2015-03-31 06:54:24.073 UTC
9
2022-09-19 12:29:50.687 UTC
2015-04-02 07:56:33.007 UTC
null
1,564,365
null
1,392,035
null
1
49
php|database|xampp|localhost|laravel-5
141,922
<p>It's working now. I had to restart server. Thanks</p>
16,082,297
How to change the position of menu items on actionbar
<p>I'm developing one application in which I have to add a custom layout on actionbar. Adding the custom layout is done, but when I'm adding the menu items on actionbar my custom layout changes it's position from right of the actionbar to center of the actionbar. Below is the image what I have achieved so far.</p> <p><img src="https://i.stack.imgur.com/wERrp.png" alt="Done till here"></p> <p>I want something like this on the actionbar.</p> <p><img src="https://i.stack.imgur.com/5colE.png" alt="Like this"></p> <p>Custom layout(yellow button) at the right most part of actionbar and menu items in the middle.</p> <p>Adding my code to achieve this custom layout using native android actionbar:</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayUseLogoEnabled(false); actionBar.setDisplayHomeAsUpEnabled(false); actionBar.setDisplayShowCustomEnabled(true); cView = getLayoutInflater().inflate(R.layout.header, null); actionBar.setCustomView(cView); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.websearch_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); default: return super.onOptionsItemSelected(item); } } </code></pre> <p>How can this be achieved?</p> <p>Any kind of help will be appreciated.</p>
16,082,440
4
0
null
2013-04-18 11:57:46.643 UTC
4
2015-01-13 09:51:47.537 UTC
2013-04-18 12:05:13.19 UTC
null
1,321,290
null
1,321,290
null
1
15
android|android-layout|android-actionbar|menuitem
43,598
<p>I assume you are setting your custom view as a custom view in the action bar. If you are using ActionbarSherlock you can instead add the custom view as a normal menu item and set an action view for it using <code>.setActionView(yourCustomView or yourCustomLayoutId)</code>. You can then set <code>.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)</code> to display the view. Just make sure your custom view is set to width <code>wrap_content</code> or otherwise it will push the other menu items off the screen. This might also work without ActionbarSherlock, but I haven't tried it there yet.</p> <p>EDIT: Try modifying your <code>onCreateOptionsMenu</code> method</p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.websearch_menu, menu); // add this menu.add(Menu.NONE, 0, Menu.NONE, "custom") .setActionView(R.layout.header) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); return true; } </code></pre> <p>and remove this from your onCreate method</p> <pre><code>actionBar.setDisplayShowCustomEnabled(true); cView = getLayoutInflater().inflate(R.layout.header, null); actionBar.setCustomView(cView); </code></pre> <p>EDIT:</p> <p>If you need to reference the views from your custom layout, you can do this in your <code>onCreateOptionsMenu</code> method as follows (note: I wrote this code in the browser, so no guarantee that I didn't make a typo or something):</p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { // inflate the menu and add the item with id viewId, // which has your layout as actionview View actionView = menu.getItem(viewId).getActionView(); View viewFromMyLayout = actionView.findViewById(R.id.viewFromMyLayout); // here you can set listeners to your view or store a reference // to it somewhere, so you can use it later return true; } </code></pre>
16,282,231
Get notified from logon and logoff
<p>I have to develop a program which runs on a local pc as a service an deliver couple of user status to a server. At the beginning I have to detect the user <strong>logon</strong> and <strong>logoff</strong>.</p> <p>My idea was to use the <code>ManagementEventWatcher</code> class and to query the <code>Win32_LogonSession</code> to be notified if something changed. </p> <p>My first test works well, here is the code part <em>(This would executed as a thread from a service)</em>:</p> <pre><code>private readonly static WqlEventQuery qLgi = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance ISA \"Win32_LogonSession\""); public EventWatcherUser() { } public void DoWork() { ManagementEventWatcher eLgiWatcher = new ManagementEventWatcher(EventWatcherUser.qLgi); eLgiWatcher.EventArrived += new EventArrivedEventHandler(HandleEvent); eLgiWatcher.Start(); } private void HandleEvent(object sender, EventArrivedEventArgs e) { ManagementBaseObject f = (ManagementBaseObject)e.NewEvent["TargetInstance"]; using (StreamWriter fs = new StreamWriter("C:\\status.log", true)) { fs.WriteLine(f.Properties["LogonId"].Value); } } </code></pre> <p>But I have some understanding problems and I’m not sure if this is the common way to solve that task.</p> <ol> <li><p>If I query <code>Win32_LogonSession</code> I get several records which are associated to the same user. For example I get this IDs 7580798 and 7580829 and if I query </p> <p>ASSOCIATORS OF {Win32_LogonSession.LogonId=X} WHERE ResultClass=Win32_UserAccount</p> <p>I get the same record for different IDs. (Win32_UserAccount.Domain="PC-Name",Name="User1")</p> <p>Why are there several logon session with the same user? What is the common way to get the current signed in user? Or better how to get notified correctly by the login of a user?</p></li> <li><p>I thought I could use the same way with <code>__InstanceDeletionEvent</code> to determine if a user is log off. But I guess if the event is raised, I cant query <code>Win32_UserAccount</code> for the username after that. I’m right?</p></li> </ol> <p>I’m at the right direction or are there better ways? It would be awesome if you could help me!</p> <p><strong>Edit</strong> Is the WTSRegisterSessionNotification class the correct way? I don't know if it's possible, because in a service I haven't a window handler.</p>
38,301,428
4
7
null
2013-04-29 15:14:35.593 UTC
11
2019-03-16 00:13:20.853 UTC
2013-05-06 09:11:28.77 UTC
null
200,349
null
690,017
null
1
26
c#|events|authentication|logoff
29,717
<p>I use <a href="https://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onsessionchange(v=vs.110).aspx" rel="nofollow">ServiceBase.OnSessionChange</a> to catch the different user events and load the necessary information afterwards.</p> <pre><code>protected override void OnSessionChange(SessionChangeDescription desc) { var user = Session.Get(desc.SessionId); } </code></pre> <p>To load the session information I use the <a href="https://msdn.microsoft.com/en-us/library/aa383861(v=vs.85).aspx" rel="nofollow">WTS_INFO_CLASS</a>. See my example below:</p> <pre><code>internal static class NativeMethods { public enum WTS_INFO_CLASS { WTSInitialProgram, WTSApplicationName, WTSWorkingDirectory, WTSOEMId, WTSSessionId, WTSUserName, WTSWinStationName, WTSDomainName, WTSConnectState, WTSClientBuildNumber, WTSClientName, WTSClientDirectory, WTSClientProductId, WTSClientHardwareId, WTSClientAddress, WTSClientDisplay, WTSClientProtocolType, WTSIdleTime, WTSLogonTime, WTSIncomingBytes, WTSOutgoingBytes, WTSIncomingFrames, WTSOutgoingFrames, WTSClientInfo, WTSSessionInfo } [DllImport("Kernel32.dll")] public static extern uint WTSGetActiveConsoleSessionId(); [DllImport("Wtsapi32.dll")] public static extern bool WTSQuerySessionInformation(IntPtr hServer, Int32 sessionId, WTS_INFO_CLASS wtsInfoClass, out IntPtr ppBuffer, out Int32 pBytesReturned); [DllImport("Wtsapi32.dll")] public static extern void WTSFreeMemory(IntPtr pointer); } public static class Status { public static Byte Online { get { return 0x0; } } public static Byte Offline { get { return 0x1; } } public static Byte SignedIn { get { return 0x2; } } public static Byte SignedOff { get { return 0x3; } } } public static class Session { private static readonly Dictionary&lt;Int32, User&gt; User = new Dictionary&lt;Int32, User&gt;(); public static bool Add(Int32 sessionId) { IntPtr buffer; int length; var name = String.Empty; var domain = String.Empty; if (NativeMethods.WTSQuerySessionInformation(IntPtr.Zero, sessionId, NativeMethods.WTS_INFO_CLASS.WTSUserName, out buffer, out length) &amp;&amp; length &gt; 1) { name = Marshal.PtrToStringAnsi(buffer); NativeMethods.WTSFreeMemory(buffer); if (NativeMethods.WTSQuerySessionInformation(IntPtr.Zero, sessionId, NativeMethods.WTS_INFO_CLASS.WTSDomainName, out buffer, out length) &amp;&amp; length &gt; 1) { domain = Marshal.PtrToStringAnsi(buffer); NativeMethods.WTSFreeMemory(buffer); } } if (name == null || name.Length &lt;= 0) { return false; } User.Add(sessionId, new User(name, domain)); return true; } public static bool Remove(Int32 sessionId) { return User.Remove(sessionId); } public static User Get(Int32 sessionId) { if (User.ContainsKey(sessionId)) { return User[sessionId]; } return Add(sessionId) ? Get(sessionId) : null; } public static UInt32 GetActiveConsoleSessionId() { return NativeMethods.WTSGetActiveConsoleSessionId(); } } public class AvailabilityChangedEventArgs : EventArgs { public bool Available { get; set; } public AvailabilityChangedEventArgs(bool isAvailable) { Available = isAvailable; } } public class User { private readonly String _name; private readonly String _domain; private readonly bool _isDomainUser; private bool _signedIn; public static EventHandler&lt;AvailabilityChangedEventArgs&gt; AvailabilityChanged; public User(String name, String domain) { _name = name; _domain = domain; if (domain.Equals("EXAMPLE.COM")) { _isDomainUser = true; } else { _isDomainUser = false; } } public String Name { get { return _name; } } public String Domain { get { return _domain; } } public bool IsDomainUser { get { return _isDomainUser; } } public bool IsSignedIn { get { return _signedIn; } set { if (_signedIn == value) return; _signedIn = value; OnAvailabilityChanged(this, new AvailabilityChangedEventArgs(IsSignedIn)); } } protected void OnAvailabilityChanged(object sender, AvailabilityChangedEventArgs e) { if (AvailabilityChanged != null) { AvailabilityChanged(this, e); } } } </code></pre> <p>The following code use the static <code>AvailabilityChanged</code> event from <code>User</code>, which gets fired as soon as the session state changes. The arg <code>e</code> contains the specific user.</p> <pre><code>public Main() { User.AvailabilityChanged += UserAvailabilityChanged; } private static void UserAvailabilityChanged(object sender, AvailabilityChangedEventArgs e) { var user = sender as User; if (user == null) return; System.Diagnostics.Debug.WriteLine(user.IsSignedIn); } </code></pre>
16,165,728
Android: notifyDataSetChanged(); not working
<p>I have a database in a server and from a Tablet I take some values from one table in the database. I load this information correctly into a list but I would like to know why when there is a change, nothing happens even if I use <code>notifyDataSetChanged();</code>. I must say that for loading the loading data y use the AsyncTaskClass So, my problem is that I don't know if use the notifyDataSetChanged(); method correctly ,because if there's is a change I would like to refresh the image. Here is some part of the code of the class:</p> <pre><code>@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.all_candidatos); candidatosList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); new CargarCandidatos().execute(); } // public void timer(){ // new CountDownTimer(tiempo, 100) { // // public void onTick(long millisUntilFinished) { // // } // // public void onFinish() { // // new CargarCandidatos().execute(); // // } // }.start();} /** * Background Async Task to Load all product by making HTTP Request * */ class CargarCandidatos extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Monitorizacion.this); pDialog.setMessage("Loading ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url * */ protected String doInBackground(String... args) { List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); JSONObject json = jParser.makeHttpRequest(url_candidatos, "GET", params); Log.d("Candidatos: ", json.toString()); try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { candidatos = json.getJSONArray(TAG_CANDIDATOS); for (int i = 0; i &lt; candidatos.length(); i++) { JSONObject c = candidatos.getJSONObject(i); // Storing each json item in variable String nserie = c.getString(TAG_NSERIE); String dni = c.getString(TAG_DNI); String nombre = c.getString(TAG_NOMBRE); String test = c.getString(TAG_TEST); String pregunta = c.getString(TAG_PREGUNTA); String bateria = c.getString(TAG_BATERIA); // creating new HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // adding each child node to HashMap key =&gt; value map.put(TAG_NSERIE, nserie); map.put(TAG_DNI, dni); map.put(TAG_NOMBRE, nombre); map.put(TAG_TEST, test); map.put(TAG_PREGUNTA, pregunta); map.put(TAG_BATERIA, bateria); // adding HashList to ArrayList candidatosList.add(map); } } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { pDialog.dismiss(); runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * */ adapter = new SimpleAdapter( Monitorizacion.this, candidatosList, R.layout.list_item, new String[] { TAG_NSERIE, TAG_DNI, TAG_NOMBRE, TAG_TEST, TAG_PREGUNTA, TAG_BATERIA}, new int[] { R.id.id, R.id.dni, R.id.nombre, R.id.test, R.id.pregunta, R.id.bateria}); setListAdapter(adapter); adapter.notifyDataSetChanged(); // timer(); } }); } } } </code></pre>
20,479,071
8
3
null
2013-04-23 09:27:28.153 UTC
9
2021-08-20 10:24:14.653 UTC
2014-05-02 12:51:36.293 UTC
null
1,318,946
null
2,008,828
null
1
29
android|refresh|adapter
73,309
<p>One of the main reasons <code>notifyDataSetChanged()</code> won't work for you - is,</p> <p><strong>Your adapter loses reference to your list</strong>.</p> <p>When you first initialize the <code>Adapter</code> it takes a reference of your <code>arrayList</code> and passes it to its superclass. But if you reinitialize your existing <code>arrayList</code> it loses the reference, and hence, the communication channel with <code>Adapter</code>.</p> <p>When creating and adding a new list to the <code>Adapter</code>. Always follow these guidelines:</p> <ol> <li>Initialise the <code>arrayList</code> while declaring it globally.</li> <li>Add the List to the adapter directly without checking for null and empty values. Set the adapter to the list directly (don't check for any condition). Adapter guarantees you that wherever you make changes to the data of the <code>arrayList</code> it will take care of it, but never lose the reference.</li> <li>Always modify the data in the arrayList itself (if your data is completely new then you can call <code>adapter.clear()</code> and <code>arrayList.clear()</code> before actually adding data to the list) but don't set the adapter i.e If the new data is populated in the <code>arrayList</code> than just <code>adapter.notifyDataSetChanged()</code></li> </ol> <p>Stay true to the Documentation.</p>
16,390,004
Change default console loglevel during boot up
<p>I setup a CentOS 6.3 setup, on which the console loglevel is set to 4, and default log level is set to 4. I know I can change the default console log level using the following steps:</p> <pre><code>cat /proc/sys/kernel/printk 4 4 1 7 echo 5 &gt; /proc/sys/kernel/printk cat /proc/sys/kernel/printk 5 4 1 7 </code></pre> <p>However, upon reboot, the console log level reverts back to the original value. Do I need to recompile the kernel, or is there a way I can get the changed value to be persistent across reboot.</p>
16,390,389
1
0
null
2013-05-05 23:02:13.12 UTC
9
2017-09-11 07:08:22.623 UTC
2013-05-06 08:08:37.503 UTC
null
151,019
null
1,348,939
null
1
30
linux|linux-kernel
106,365
<blockquote> <p>Do I need to recompile the kernel, </p> </blockquote> <p>No.</p> <blockquote> <p>or is there a way I can get the changed value to be persistent across reboot. </p> </blockquote> <p>Yes.<br> Use the kernel command line parameter <code>loglevel</code>:</p> <pre><code>loglevel= All Kernel Messages with a loglevel smaller than the console loglevel will be printed to the console. It can also be changed with klogd or other programs. The loglevels are defined as follows: 0 (KERN_EMERG) system is unusable 1 (KERN_ALERT) action must be taken immediately 2 (KERN_CRIT) critical conditions 3 (KERN_ERR) error conditions 4 (KERN_WARNING) warning conditions 5 (KERN_NOTICE) normal but significant condition 6 (KERN_INFO) informational 7 (KERN_DEBUG) debug-level messages </code></pre> <p>The entire list of parameters possible on the kernel command line are in the <a href="https://www.kernel.org/doc/Documentation/admin-guide/kernel-parameters.txt" rel="noreferrer"><code>Linux/Documentation/kernel-parameters.txt</code></a> file in the source tree. </p> <p>Depending on your bootloader (e.g. Grub or U-Boot), you will have to edit text to add this new parameter to the command line. Use <code>cat /proc/cmdline</code> to view the kernel command line used for the previous boot.</p> <hr> <p><strong>Addendum</strong> </p> <p>To display everything, the number supplied for the loglevel parameter would have be be greater than KERN_DEBUG.<br> That is, you would have to specify <code>loglevel=8</code>.<br> Or simply use the <code>ignore_loglevel</code> parameter to display all kernel messages. </p>
16,169,161
Why can I use operator= but not operator== with C++11 brace-initializers?
<p>See this example:</p> <pre><code>struct Foo { int a; int b; bool operator == (const Foo &amp; x) { return a == x.a &amp;&amp; b == x.b; } }; int main () { Foo a; a = {1, 2}; if (a == {1, 2}) // error: expected primary-expression before ‘{’ token { } } </code></pre> <p>The line <code>a={1,2}</code> is fine. The braces are convert to a <code>Foo</code> to match the argument type of the implicit <code>operator=</code> method. It still works if <code>operator=</code> is user-defined.</p> <p>The line <code>if (a=={1,2}})</code> errors as indicated.</p> <p>Why does the expression <code>{1,2}</code> not convert to a <code>Foo</code> to match the user-defined <code>operator==</code> method?</p>
16,169,240
5
5
null
2013-04-23 12:17:47.99 UTC
4
2013-04-23 18:28:42.267 UTC
2013-04-23 12:57:59.02 UTC
null
458,742
null
458,742
null
1
32
c++|c++11
981
<p>List-initialization cannot be used as an argument to an operator <em>in the general case</em>. Per Paragraph 8.5.4/1 of the C++11 Standard:</p> <blockquote> <p>[...] List-initialization can be used</p> <p>— as the initializer in a variable definition (8.5)</p> <p>— as the initializer in a new expression (5.3.4)</p> <p>— in a return statement (6.6.3)</p> <p>— as a for-range-initializer (6.5)</p> <p>— <strong>as a function argument</strong> (5.2.2)</p> <p>— as a subscript (5.2.1)</p> <p>— as an argument to a constructor invocation (8.5, 5.2.3)</p> <p>— as an initializer for a non-static data member (9.2)</p> <p>— in a mem-initializer (12.6.2)</p> <p>— <strong>on the right-hand side of an assignment</strong> (5.17)</p> </blockquote> <p>The last item explains why list-initialization is allowed on the right side of <code>operator =</code>, even though it is not allowed in general for an arbitrary operator.</p> <p>Because of the fifth item above, however, it can be used as an argument to a regular function call, this way:</p> <pre><code>if (a.operator == ({1, 2})) </code></pre>
16,044,229
How to get keyboard input in pygame?
<p>I am making a game in pygame 1.9.2. It's a faily simple game in which a ship moves between five columns of bad guys who attack by moving slowly downward. I am attempting to make it so that the ship moves left and right with the left and right arrow keys. Here is my code:</p> <pre class="lang-py prettyprint-override"><code>keys=pygame.key.get_pressed() if keys[K_LEFT]: location-=1 if location==-1: location=0 if keys[K_RIGHT]: location+=1 if location==5: location=4 </code></pre> <p>It works too well. The ship moves too fast. It is near impossible to have it move only one location, left or right. How can i make it so the ship only moves once every time the key is pressed?</p>
16,044,380
10
0
null
2013-04-16 18:15:49.023 UTC
16
2022-05-28 16:58:19.93 UTC
2021-03-12 06:29:33.503 UTC
null
7,579,547
null
1,704,897
null
1
71
python|pygame|keyboard
261,900
<p>You can get the events from pygame and then watch out for the <code>KEYDOWN</code> event, instead of looking at the keys returned by <code>get_pressed()</code>(which gives you keys that are currently pressed down, whereas the <code>KEYDOWN</code> event shows you which keys were pressed down on <em>that frame</em>).</p> <p>What's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.</p> <pre class="lang-py prettyprint-override"><code>events = pygame.event.get() for event in events: if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: location -= 1 if event.key == pygame.K_RIGHT: location += 1 </code></pre> <p>To support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.</p> <pre class="lang-py prettyprint-override"><code>move_ticker = 0 keys=pygame.key.get_pressed() if keys[K_LEFT]: if move_ticker == 0: move_ticker = 10 location -= 1 if location == -1: location = 0 if keys[K_RIGHT]: if move_ticker == 0: move_ticker = 10 location+=1 if location == 5: location = 4 </code></pre> <p>Then somewhere during the game loop you would do something like this:</p> <pre class="lang-py prettyprint-override"><code>if move_ticker &gt; 0: move_ticker -= 1 </code></pre> <p>This would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)</p>
29,185,601
Is it possible to use ES6 in a Chrome Extension?
<p>I've just started building a Chrome Extension and was curious if I'd be able to use ES6 with it.</p> <p>In the following <a href="http://kangax.github.io/compat-table/es6/" rel="noreferrer">compatibility table</a>, Chrome 41 shows that it currently has 41% compatibility. A couple key features like <code>class</code> are not included in that 41% and so I was curious if there were other options, such as transpiling.</p> <p>I've already used <a href="https://babeljs.io/" rel="noreferrer">Babel</a>, an ES6 transpiler, with Ember CLI and it has worked great. </p> <p>However, I find the build process a bit different when developing a chrome extension. For example, when testing an extension I'm developing, I load it into the browser via the "Load unpacked extension" option which points directly to the source code. </p> <p>For the extension I am building, I am using the <a href="https://github.com/yeoman/generator-chrome-extension" rel="noreferrer">yeoman chrome extension generator</a> as a base. Ideally, I'd like to be able to set up some sort of grunt task that hooks into the <code>debug</code> task and then transpiles the code any time it changes to a separate directory. From there, I could load the contents of that directory via the <code>load unpacked extension</code> option. However, I'm not exactly sure how to do this or if there are other options instead.</p>
31,836,220
1
5
null
2015-03-21 17:16:23.133 UTC
9
2018-11-19 18:21:41.24 UTC
null
null
null
null
1,832,638
null
1
32
javascript|google-chrome|google-chrome-extension|gruntjs|ecmascript-6
11,037
<p><strong>Update</strong> This answer was originally written in 2015. The compatibility table link shows Chrome, FF, Edge, and Safari are <em>more</em> compatible than Babel now.</p> <p>Chrome 49+, FF 45+ may not benefit from Babel. Other browsers, may need transpiling.</p> <p><strong>Original</strong></p> <p>I am also currently developing a Chrome Extension in ES6. Your questions seems to be more general so I try to answer this based on my experiences.</p> <blockquote> <p>In the following <a href="http://kangax.github.io/compat-table/es6/" rel="noreferrer">compatibility table</a>, Chrome 41 shows that it currently has 41% compatibility. A couple key features like <code>class</code> are not included in that 41% and so I was curious if there were other options, such as transpiling.</p> </blockquote> <p>This is true. You can easily use all existing ES6 Features without worries and transpiling. Every new Chrome release has some more features, which makes it quite exciting to wait ;) Chrome 44 now covers 48%, including <code>class</code>.</p> <p>However, if you want go full ES6 then a compiler is still the best option. You don't have to worry about supported features and simply write ES6 code, which will be compiled to proper ES5 code.</p> <p>My current setup is <strong>Browserify</strong> (via <a href="https://github.com/jmreidy/grunt-browserify" rel="noreferrer"><code>grunt-browserify</code></a>) using <a href="https://github.com/babel/babelify" rel="noreferrer"><strong>Babelify</strong></a> as compiler. Browserify enables you to also use ES6 Modules, which give you the full power of ES6.</p> <p><strong>Gruntfile.js</strong></p> <pre><code>browserify: { dist: { options: { transform: [ ['babelify', { loose: 'all' }] ], browserifyOptions: { debug: true }, exclude: '' }, files: { 'path/to/es5/app.js': ['path/to/es6/**/*.js'] } } } // Then it will be uglified and copied to dist. </code></pre> <p>That means my Extension still runs with ES5 code though, but that doesn't matters much for me as I still can write in ES6. </p> <p>If you really want to use available ES6 features (which I did before), it can be quite frustrating/annoying as you always have to look up whats possible in Chrome and mostly it's waiting for a new Chrome release.</p> <blockquote> <p>However, I find the build process a bit different when developing a chrome extension. For example, when testing an extension I'm developing, I load it into the browser via the "Load unpacked extension" option which points directly to the source code.</p> </blockquote> <p>Well it's not really different to any other project I think. Depending on what Chrome specific features you are using, you could either just develop your project and later test it via loading it into the browser or just link the "Load unpacked extension" path to your generated <code>dist/build/public</code> folder. Doing that, it's always the current state. This works for me the best.</p> <p>Hope that helps a bit :)</p>
17,130,711
How align 2 adjacent divs horizontally WITHOUT float?
<p>I want to make 2 divs beside each other to be aligned on the same horizontal line <strong>WITHOUT FLOATs</strong> </p> <p>I've tried Position:relative ,, but no luck</p> <p>See the example below : <a href="http://jsfiddle.net/XVzLK" rel="noreferrer">http://jsfiddle.net/XVzLK</a></p> <pre><code>&lt;div style="width:200px;height:100px;background:#ccc;"&gt; &lt;div style="background:Blue; float:left; width:100px; height:100px;"&gt;&lt;/div&gt; &lt;div style="background:red; float:left; margin-left:100px; width:100px; height:100px;"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>From the link above, I need the red box to be on the same line of blue box with no space below ..</p> <p><strong>EDIT</strong> : I want the red box to stay outside the container gray box (just as it is) thanks</p>
17,130,739
5
0
null
2013-06-16 06:15:02.357 UTC
3
2016-12-14 11:56:50.61 UTC
2013-06-16 07:02:06.023 UTC
null
1,995,199
null
1,995,199
null
1
12
html|css|xhtml|position
53,628
<p>Use Position properties when your height and width are fixed</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="width:200px;height:100px;position:relative;background:#ccc;"&gt; &lt;div style="background:Blue; position:absolute; left:0%; width:50%; height:100%;"&gt; &lt;/div&gt; &lt;div style="background:red; position:absolute; left:50%; width:50%; height:100%;"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
17,356,782
tracert command returns timed out
<p>tracert returns requested time out. What I understand from this is the packets lost some where on the network.</p> <p>Does it mean the issue is with the ISP or with the hosting provider or my windows system?</p> <pre><code>10 * * * Request timed out. 11 * * * Request timed out. 12 * * * Request timed out. 13 * * * Request timed out. 14 * * * Request timed out. 15 * * * Request timed out. 16 * * * Request timed out. 17 * * * Request timed out. 18 * * * Request timed out. 19 * * * Request timed out. 20 * * * Request timed out. 21 * * * Request timed out. 22 * * * Request timed out. 23 * * * Request timed out. 24 * * * Request timed out. 25 * * * Request timed out. 26 * * * Request timed out. 27 * * * Request timed out. 28 * * * Request timed out. 29 * * * Request timed out. 30 * * * Request timed out. </code></pre> <p>The first 9 were successful.</p>
17,356,990
5
0
null
2013-06-28 03:36:16.533 UTC
2
2022-09-06 16:29:08.763 UTC
2014-04-11 05:42:54.643 UTC
null
1,505,792
null
1,505,792
null
1
18
traceroute
108,155
<p>I can't see the first 9 hops but if they are all the same then you may have a firewall configuration issue that prevents the packets from either getting out or getting back.</p> <p>Try again turning off your firewall (temporarily!). The other option is that your ISP may drop ICMP traffic as a matter of course, or only when they are busy with other traffic.</p> <p>ICMP (the protocol used by traceroute) is of the lowest priority, and when higher priority traffic is ongoing the router may be configured to simply drop ICMP packets. There is also the possibility that the ISP drops all ICMP packets as a matter of security since many DOS (Denial of Service) attacks are based on probing done with ICMP packets.</p>
22,388,079
How is an object stored in heap?
<p>How exactly an object is stored in heap. For example, a bicycle class can be defined like this: </p> <pre><code>public class Bicycle { public int gear; public int speed; public Bicycle(int startSpeed, int startGear) { gear = startGear; speed = startSpeed; } public void setGear(int newValue) { gear = newValue; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } } </code></pre> <p>then I can create an bicycle object:</p> <pre><code>Bicycle bicycle = new Bicycle(20,10) </code></pre> <p>Then this bicycle object should be stored in heap. But I don't understand how heap exactly store these instance variables and methods such as speed and gear.I understand that heap should be implemented as tree. So how the object is stored in a tree? Also when you use <code>bicycle.speed</code> to find the value of speed, what will be time complexity?</p>
22,388,910
3
3
null
2014-03-13 18:45:29.953 UTC
11
2021-11-16 15:32:33.037 UTC
2021-11-16 15:32:33.037 UTC
null
5,459,839
null
2,446,230
null
1
19
java|object|memory-management|heap-memory
10,604
<p>Want someone else to do your CS homework eh? ;)</p> <p>Depending on the language the exact implementation will be different (how it's stored in memory), but the general concept is the same.</p> <p>You have your stack memory and your heap memory, the local variables and parameters go on the stack, and whenever you <code>new</code> something it goes into the heap. It's called a stack because values are pushed onto it when you declare it or call a function, and popped off and they go out of scope.</p> <pre> +--------------+ | | | | | | | | | | | | | | | | | | | | | | | | +--------------+ Stack Heap </pre> <p>Each instance variable takes up however much memory its type does (depending on the language), the compiler adds it all up and that's the <code>sizeof</code> the type (à la C++). Methods go into code space and does not get <code>new</code>ed into the object (I think for now you'll be better off to not consider this in learning about how memory is organized, just think of it as magic).</p> <p>So in your example:</p> <pre><code>Bicycle bicycle = new Bicycle(20,10) </code></pre> <ul> <li><code>bicycle</code> is a reference to the heap memory address, today in most languages/systems it will cost you either 32 and 64 bits on the stack.</li> <li>The <code>new</code> allocates memory in the heap. The compiler figures out the size of Bicycle and creates assembly/machine code that allocates the amount of memory it requires.</li> </ul> <p>This is how the memory looks after this line:</p> <pre> +--------------+ | | | Bicycle obj | | | |--------------| | | | | | | | | |--------------| | | | bicycle ref | | | +--------------+ Stack Heap </pre> <p>More specifically, since the Bicycle class has two instance variables (or fields as they are called in Java) and both are <code>int</code>s, and an <code>int</code> in Java is 32 bits or 4 bytes, the size of your Bicycle object is 4 bytes * 2 fields = 8 bytes.</p> <pre> +-------------+ | | 0| gear | | | 4| speed | | | |-------------| | | 8| | |-------------| 12| | | bicycle=0x4 | | | +--------------+ Stack Heap </pre> <p>Time complexity to access memory is O(1). The compiler is able to figure out the exact memory address of <code>speed</code>, since as the second int field in the object, is at bicycle+0x4.</p>
21,625,628
Android Studio starting in debug mode by default
<p>I have been working on a project, and when I run the project in android studio it had been running correct and when I ran in debug mode it ran correctly. </p> <p>All of a sudden, when I try to run the project normally, it pops up on the device waiting for debugger </p> <p>and in the logcat I get this:</p> <pre><code>02-07 10:38:46.444 3968-3968/com.geog.test D/dalvikvm﹕ Late-enabling CheckJNI 02-07 10:38:46.784 3968-3968/com.geog.test W/ActivityThread﹕ Application com.geog.visitdub is waiting for the debugger on port 8100... 02-07 10:38:46.804 3968-3968/com.geog.test I/System.out﹕ Sending WAIT chunk </code></pre> <p>and it goes no further. I don't know why this is happening, there is no debug command in the manifest, I have killed the adb and restarted as I did with android studio.</p> <p>It's a real pain in the a*** as I can't run the app without going through debug mode. If anyone has any ideas I'd like to hear them</p> <p>Thanks</p>
21,631,164
8
4
null
2014-02-07 10:44:03.503 UTC
1
2020-10-18 05:02:09 UTC
null
null
null
null
1,250,031
null
1
30
debugging|android-studio
17,370
<p>Restart your Android Device once and also check there should not be any breakpoints in your java classes.</p>
45,061,324
Repeating local notifications for specific days of week (Swift 3 IOS 10)
<p>I am trying to schedule local notifications for specific days of week (e.g. Monday, Wednesday and etc) and then repeat them weekly. This is how the screen for setting notifications looks:</p> <p><a href="https://i.stack.imgur.com/EZPnp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EZPnp.png" alt="enter image description here" /></a></p> <p>User can select time for the notification and repeating days.</p> <p>My method for scheduling single non repeating notification looks like this:</p> <pre><code>static func scheduleNotification(reminder: Reminder) { // Setup notification content. let content = UNMutableNotificationContent() //content.title = NSString.localizedUserNotificationString(forKey: &quot;Reminder&quot;, arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: reminder.reminderMessage, arguments: nil) content.sound = UNNotificationSound.default() // Configure the triger for specified time. // let dateComponentes = reminder.dateComponents // TODO: Configure repeating alarm // For the testing purposes we will not repeat the reminder let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponentes, repeats: false) // Create the request object. let request = UNNotificationRequest(identifier: &quot;\(reminder.reminderId)&quot;, content: content, trigger: trigger) // Schedule the request. let notificationCenter = UNUserNotificationCenter.current() notificationCenter.add(request) { (error: Error?) in if let theError = error { print(theError.localizedDescription) } } } </code></pre> <p>The date components are extracted from UIDatePicker widget and stored in reminder class:</p> <pre><code>let date = reminderTimeDatePicker.date.addingTimeInterval(60 * 60 * 24 * 7) let components = Calendar.current.dateComponents([.weekday, .hour, .minute], from: date) ... reminder.dateComponents = components </code></pre> <p>I have an array <code>selectedDays[Int]</code> (as a property of reminder class) to hold info on days of week on which the notification should fire.</p> <p>How can I schedule notification on specific day of week and how to repeat it weekly?</p> <p>Even a single comment will be helpful, and thank you in advance.</p>
45,062,818
2
5
null
2017-07-12 15:01:21.583 UTC
14
2018-09-13 19:34:29.923 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
6,828,707
null
1
14
ios|swift|swift3|notifications
13,829
<p>You can use below function to get Date from selected picker value:</p> <pre><code> //Create Date from picker selected value. func createDate(weekday: Int, hour: Int, minute: Int, year: Int)-&gt;Date{ var components = DateComponents() components.hour = hour components.minute = minute components.year = year components.weekday = weekday // sunday = 1 ... saturday = 7 components.weekdayOrdinal = 10 components.timeZone = .current let calendar = Calendar(identifier: .gregorian) return calendar.date(from: components)! } //Schedule Notification with weekly bases. func scheduleNotification(at date: Date, body: String, titles:String) { let triggerWeekly = Calendar.current.dateComponents([.weekday,.hour,.minute,.second,], from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true) let content = UNMutableNotificationContent() content.title = titles content.body = body content.sound = UNNotificationSound.default() content.categoryIdentifier = "todoList" let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger) UNUserNotificationCenter.current().delegate = self //UNUserNotificationCenter.current().removeAllPendingNotificationRequests() UNUserNotificationCenter.current().add(request) {(error) in if let error = error { print("Uh oh! We had an error: \(error)") } } } </code></pre> <p>After getting a value from picker pass picker hour, minute and year with selected week day as (Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4, thursday = 5, Friday = 6, Saturday = 7) to function <code>func createDate(weekday: Int, hour: Int, minute: Int, year: Int)</code> to get notification fire date on weekly bases, and after getting date call function <code>func scheduleNotification(at date: Date, body: String, titles:String)</code> for schedule a notification.</p>
17,215,484
floating-point promotion : stroustrup vs compiler - who is right?
<p>In section 10.5.1 of Stroustrup's new book "The C++ Programming Language - Fourth Edition" he says, that before an arithmetic operation is performed, integral promotion is used to create ints out of shorter integer types, and similarly, floating-point promotion is used to create doubles out of floats.</p> <p>I confirmed the first claim with the following code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;typeinfo&gt; int main() { short a; short b; std::cout &lt;&lt; typeid(a + b).name() &lt;&lt; std::endl; } </code></pre> <p>This outputs "int" with vc++ and "i" with gcc.</p> <p>But testing it with floats instead of shorts, the output is still "float" or "f":</p> <pre><code>#include &lt;iostream&gt; #include &lt;typeinfo&gt; int main() { float a; float b; std::cout &lt;&lt; typeid(a + b).name() &lt;&lt; std::endl; } </code></pre> <p>According to Stroustrup there are no exceptions to the floating-point promotion-rule, so I expected "double" or "d" as output.</p> <p>Is the mentioned section about promotions wrong or somehow unclear? And is there any difference in C++98 and C++11 regarding type promotions?</p>
17,215,694
2
11
null
2013-06-20 13:53:52.577 UTC
4
2014-09-22 19:19:30.443 UTC
2013-06-20 14:21:17.403 UTC
null
2,143,766
null
2,143,766
null
1
35
c++|c++11
1,498
<p>I don't know what exactly Stroustrup's book says, but according to the standard, <code>float</code>s will not be converted to <code>double</code>s in this case. Before applying most arithmetic binary operators, the <em>usual arithmetic conversions</em> described in 5p9 are applied:</p> <blockquote> <ul> <li>If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed. </li> <li>If either operand is of type long double, the other shall be converted to long double.</li> <li>Otherwise, if either operand is double, the other shall be converted to double.</li> <li>Otherwise, if either operand is float, the other shall be converted to float.</li> <li>Otherwise, the integral promotions (4.5) shall be performed on both operands. [...]</li> </ul> </blockquote> <p>The integral promotions are what causes two <code>short</code>s to be converted to <code>int</code>s. But two <code>float</code>s will not be converted to <code>double</code>s according to these rules. If you add a <code>float</code> to a <code>double</code>, the <code>float</code> will be converted to a <code>double</code>.</p> <p>The above is from C++11. C++03 contains the same rules, except for the one referring to scoped enumerations.</p>
37,094,631
Get the pushed ID for specific value in firebase android
<p>I want to retrive the id that generated by firebase when I pushed value to it like next </p> <p><a href="https://i.stack.imgur.com/C63F3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/C63F3.png" alt="Firebase"></a></p> <p>I want to retrieve "-KGdKiPSODz7JXzlgl9J" this id for that email I tried by getKey() but it return "users" and when user get value it return the whole object from the id to profile picture and that won't make me get it as User object in my app </p> <p>how solve this ?</p> <pre><code> Firebase users = myFirebaseRef.child("users"); users.orderByChild("email").equalTo("[email protected]").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { dataSnapshot.getKey(); Log.d("User",dataSnapshot.getRef().toString()); Log.d("User",dataSnapshot.getValue().toString()); } @Override public void onCancelled(FirebaseError firebaseError) { Log.d("User",firebaseError.getMessage() ); } }); </code></pre>
39,492,322
14
4
null
2016-05-07 23:16:17.637 UTC
15
2020-10-30 11:44:27.823 UTC
2019-01-23 16:27:41.707 UTC
null
6,435,732
null
3,553,843
null
1
40
android|firebase|firebase-realtime-database
112,618
<p>UPDATE 1: it can obtain also by one line </p> <blockquote> <pre><code>String key = mDatabase.child("posts").push().getKey(); </code></pre> </blockquote> <p>//**************************************************************//</p> <p>after searching and trying a lot of things i came to 2 ways to do that . 1. first one to get the key when i upload the post to the server via this function </p> <pre><code> public void uploadPostToFirebase(Post post) { DatabaseReference mFirebase = mFirebaseObject .getReference(Constants.ACTIVE_POSTS_KEY) .child(post.type); mFirebase.push().setValue(post); Log.d("Post Key" , mFirebase.getKey()); } </code></pre> <ol> <li><p>i used it in my code to get the key after i have already pushed it to node for it in my database </p> <pre><code>public void getUserKey(String email) { Query queryRef = databaseRef.child(Constants.USERS_KEY) .orderByChild(Constants.USERS_EMAIL) .equalTo(email); queryRef.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { //TODO auto generated } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { //TODO auto generated; } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { //TODO auto generated; } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { //TODO auto generated } @Override public void onCancelled(DatabaseError databaseError) { //TODO auto generated } }); } </code></pre></li> </ol>
18,220,104
"Write Failed: Broken Pipe" when trying to login through ssh with a specific user
<p>I am attempting to setup an SSHFTP server, and upon connecting via apache@localhost, I am immediately disconnected with a "Write Failed: Broken Pipe" error message. I can connect fine with <code>jack@localhost</code>, but not the user <code>apache</code>.</p> <p>These are the only settings I added to sshd_config (I want to only allow apache when I get it working):</p> <pre><code>Match User apache ChrootDirectory /apache AllowTCPForwarding no X11Forwarding no ForceCommand /usr/lib/openssh/sftp-server Match #AllowUsers apache </code></pre> <p>And this is what I added to ssh_config:</p> <pre><code>ServerAliveInterval 120 TCPKeepAlive no </code></pre> <p>I made sure the user apache had full permissions on the /apache folder, and I can login as this user fine and modify items in Terminal. The folder only has 2 files: index.html and test.php</p> <p>I also went to another computer on the network, and used FileZilla to login as the user <code>jack</code>. It worked just fine.</p> <p>This is the log of the Terminal when I try to connect.</p> <pre><code>jack@JacksServer:~$ ssh -v apache@localhost OpenSSH_5.9p1 Debian-5ubuntu1.1, OpenSSL 1.0.1 14 Mar 2012 debug1: Reading configuration data /etc/ssh/ssh_config debug1: /etc/ssh/ssh_config line 19: Applying options for * debug1: Connecting to localhost [127.0.0.1] port 22. debug1: Connection established. debug1: identity file /home/jack/.ssh/id_rsa type -1 debug1: identity file /home/jack/.ssh/id_rsa-cert type -1 debug1: identity file /home/jack/.ssh/id_dsa type -1 debug1: identity file /home/jack/.ssh/id_dsa-cert type -1 debug1: identity file /home/jack/.ssh/id_ecdsa type -1 debug1: identity file /home/jack/.ssh/id_ecdsa-cert type -1 debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9p1 Debian-5ubuntu1.1 debug1: match: OpenSSH_5.9p1 Debian-5ubuntu1.1 pat OpenSSH* debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_5.9p1 Debian-5ubuntu1.1 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: server-&gt;client aes128-ctr hmac-md5 none debug1: kex: client-&gt;server aes128-ctr hmac-md5 none debug1: sending SSH2_MSG_KEX_ECDH_INIT debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug1: Server host key: ECDSA bb:f3:74:9d:97:80:89:dc:d9:68:53:5c:f7:25:19:4e debug1: Host 'localhost' is known and matches the ECDSA host key. debug1: Found key in /home/jack/.ssh/known_hosts:1 debug1: ssh_ecdsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey,password debug1: Next authentication method: publickey debug1: Trying private key: /home/jack/.ssh/id_rsa debug1: Trying private key: /home/jack/.ssh/id_dsa debug1: Trying private key: /home/jack/.ssh/id_ecdsa debug1: Next authentication method: password apache@localhost's password: debug1: Authentication succeeded (password). Authenticated to localhost ([127.0.0.1]:22). debug1: channel 0: new [client-session] debug1: Requesting [email protected] debug1: Entering interactive session. Write failed: Broken pipe jack@JacksServer:~$ </code></pre> <p>Ubuntu version info:</p> <pre><code>Distributor ID: Ubuntu Description: Ubuntu 12.04.2 LTS Release: 12.04 Codename: precise </code></pre> <p>Edit:</p> <p>I ran the command <code>sudo grep -ir ssh /var/log/*</code> and got this:</p> <pre><code>/var/log/auth.log~:Aug 13 16:08:15 JacksServer sshd[32292]: fatal: bad ownership or modes for chroot directory "/apache" /var/log/auth.log~:Aug 13 16:08:15 JacksServer sshd[32156]: pam_unix(sshd:session): session closed for user apache </code></pre> <p>I tried doing <code>chmod 755 /apache</code> as some websites have suggested, and changing ownership, but I am still getting this error. The folder is currently owned by the user <code>apache</code>.</p> <p>Some more info about the apache user:</p> <pre><code>root@JacksServer:/apache# ls -la /apache total 24 drwxr-xr-x 4 apache root 4096 Aug 13 15:49 . drwxr-xr-x 29 root root 4096 Aug 13 03:06 .. drwxr-xr-x 2 apache nogroup 4096 Aug 13 13:57 .cache -rw-r--r-- 1 apache root 5 Aug 13 03:56 index.html -rw-r--r-- 1 apache root 0 Aug 13 03:56 index.html~ drwxr-xr-x 8 apache root 4096 Aug 13 15:51 .ssh -rw-r--r-- 1 apache root 20 Aug 13 03:59 test.php -rw-r--r-- 1 apache root 0 Aug 13 03:59 test.php~ root@JacksServer:/apache# ls -la /apache/.ssh total 92 drwxr-xr-x 8 apache root 4096 Aug 13 15:51 . drwxr-xr-x 4 apache root 4096 Aug 13 15:49 .. -rw-r--r-- 1 apache jack 220 Jun 6 20:08 .bash_logout drwxr-xr-x 19 apache jack 4096 Aug 13 15:04 .cache drwxr-xr-x 3 apache jack 4096 Jun 6 20:49 .compiz-1 drwxr-xr-x 3 apache jack 4096 Jun 6 20:22 .dbus drwxr-xr-x 5 apache jack 4096 Aug 13 05:37 .gconf -rw-r----- 1 apache jack 0 Aug 13 15:47 .gksu.lock drwxr-xr-x 3 apache jack 4096 Jun 6 20:22 .local -rw-r--r-- 1 apache jack 675 Jun 6 20:08 .profile -rw------- 1 apache jack 256 Jun 6 20:22 .pulse-cookie drwxr-xr-x 2 apache jack 4096 Aug 13 14:20 .ssh -rw------- 1 apache jack 56 Aug 13 04:45 .Xauthority -rw------- 1 apache jack 44215 Aug 13 13:54 .xsession-errors </code></pre>
18,246,535
3
4
null
2013-08-13 22:12:15.097 UTC
4
2013-10-31 11:51:39.337 UTC
2013-08-14 08:50:40.31 UTC
null
1,490,169
null
1,490,169
null
1
13
ubuntu|ssh|sftp
68,629
<p>The answers to both are in this thread: <a href="https://askubuntu.com/questions/134425/how-can-i-chroot-sftp-only-ssh-users-into-their-homes">https://askubuntu.com/questions/134425/how-can-i-chroot-sftp-only-ssh-users-into-their-homes</a></p> <p>"Basically the chroot directory has to be owned by root and can't be any group-write access."</p> <p>This would mean you need to ensure that your <code>ChrootDirectory</code> (<code>/apache</code>) is owned by root, and not writeable by any group/others. This is due to some obscure setuid related security risks <a href="http://lists.mindrot.org/pipermail/openssh-unix-dev/2009-May/027651.html" rel="noreferrer">outlined here</a>. </p> <p>Also, to answer the question about <code>/bin/false: No such file or directory</code>: Try using <code>/sbin/nologin</code> instead.</p>
5,061,629
Where can I find the Northwind database for Microsoft SQL Server 2008?
<p>I'm trying to find and create/import the Northwind database to practice my Linq-fu.</p> <p>I cannot find it for the life of me, searching just turns me to this page, which in turn tells me to find it on the official page which isn't there.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms227484%28v=vs.90%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms227484%28v=vs.90%29.aspx</a></p> <p>Where can I find the Northwind database?</p>
5,061,639
3
0
null
2011-02-21 02:04:48.163 UTC
4
2016-03-31 00:44:16.783 UTC
null
null
null
delete
null
null
1
26
sql-server|northwind
63,586
<p>Northwind doesn't come installed with SQL Server 2008. You can instead:</p> <ul> <li><a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyId=06616212-0356-46A0-8DA2-EEBC53A68034&amp;displaylang=en" rel="noreferrer">download <em>scripts</em> for creating the Northwind and pubs sample databases</a>. </li> <li><a href="http://archive.msdn.microsoft.com/northwind/Release/ProjectReleases.aspx?ReleaseId=1401" rel="noreferrer">download Northwind and pubs MDF/LDF from Microsoft</a>. The article is titled "SQL Server 2000 Sample Databases".</li> </ul> <p>They come in SQL Server 2000 format / compatibility mode. Microsoft seems to have stopped using these 2 in favour of the new sample database for SQL Server 2008: AdventureWorks.</p> <p>You can <a href="http://msftdbprodsamples.codeplex.com/releases/view/55926" rel="noreferrer">download AdventureWorks 2008 R2 SR1</a>. </p> <p>Microsoft has its <a href="http://msftdbprodsamples.codeplex.com/" rel="noreferrer">SQL Server Product Database samples at CodePlex</a>.</p>
4,947,025
Post data and retrieve the response using PHP Curl?
<p>I'm very new to working with web services, and so I'm finding this pretty confusing.</p> <p>If I have a URL I'm trying to post some JSON data to, I understand how to do this using the CURL PHP method. </p> <p>What I'm wondering is, if I do this, and the URL has some kind of server response.. how do I get that response in my php and use it to take different actions within the PHP accordingly?</p> <p>Thanks!</p> <p>-Elliot</p>
4,947,093
3
2
null
2011-02-09 15:37:48.94 UTC
7
2016-09-27 00:31:41.693 UTC
null
null
null
null
132,331
null
1
27
php|post|curl|webservice-client
98,596
<p>You'll have to set the CURLOPT_RETURNTRANSFER option to true.</p> <pre><code>$ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); </code></pre> <p>The response to your request will be available in the $result variable.</p>
18,487,596
Error 'jquery-2.0.2.min.map not found'
<p>I'm getting this error in Google Chrome developer tools:</p> <blockquote> <p>jquery-2.0.2.min.map not found</p> </blockquote> <p>I found a way to get rid of it by removing this line from my <code>jquery-2.0.2.min.js</code>:</p> <pre><code>//@ sourceMappingURL=jquery-2.0.2.min.map </code></pre> <p>However, I don't believe this was a good idea, since this may be just a temporary fix that may be a problem in the future. Since I don't really understand the nature of this error and the goofy solution: what's causing this error and is there a better fix for it?</p> <p>Apparently, this is not a question related to <a href="http://en.wikipedia.org/wiki/JQuery" rel="nofollow noreferrer">jQuery</a> 2.0.2 only. A very similar Stack&nbsp;Overflow question with a great explanation is <em><a href="https://stackoverflow.com/q/18365315/1479895">jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)</a></em>. I hope this will shed some light on the situation.</p>
18,489,135
4
1
null
2013-08-28 12:14:37.247 UTC
24
2015-05-29 08:39:32.98 UTC
2017-05-23 12:16:58.67 UTC
null
-1
null
1,479,895
null
1
78
jquery|google-chrome-devtools
80,382
<p><strong>1. <a href="http://jquery.com/download/" rel="noreferrer">Download</a> the map file and uncompressed version of jquery. Put them with minified version.</strong> <img src="https://i.stack.imgur.com/HFX44.png" alt="JavaScript"></p> <p><strong>2. Include minified version into your HTML</strong> <img src="https://i.stack.imgur.com/yWZ2b.png" alt="HTML"></p> <p><strong>3. Check in Chrome</strong> <img src="https://i.stack.imgur.com/BeLYF.png" alt="Chrome"></p> <p><strong>4. Read <a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/" rel="noreferrer">Introduction to JavaScript Source Maps</a></strong></p> <p><strong>5. Get familiar with <a href="https://developers.google.com/chrome-developer-tools/docs/javascript-debugging" rel="noreferrer">Debugging JavaScript</a></strong></p>
18,692,068
Will MySQL reuse deleted ID's when Auto Increment is applied
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html">http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html</a></p> <p>That document I'm reading seems to say something like:</p> <p>"In this case (when the AUTO_INCREMENT column is part of a multiple-column index), AUTO_INCREMENT values are reused if you delete the row with the biggest AUTO_INCREMENT value in any group."</p> <p>I don't really understand what's being said there. Aren't the values supposed to be reused automatically?</p> <p>Thanks in advance...</p>
18,692,168
5
1
null
2013-09-09 05:40:46.02 UTC
5
2019-02-12 03:25:05.743 UTC
null
null
null
null
922,360
null
1
28
mysql|auto-increment
20,640
<p>InnoDB resets the auto_increment field when you restart the database.</p> <p>When InnoDB restarts, it finds the highest value in the column and then starts from there.</p> <p>This won't happen in MyISAM because it caches the last incremented id.</p> <p><strong>Update</strong></p> <p>This feature/bug has been around since 2003 and can lead to serious issues. Take the example below,</p> <ol> <li><p>Table t1 has an auto-inc primary key.</p> </li> <li><p>Table t2 has a column for the primary key in t1 without a foreign key &quot;constraint&quot;. In other words, when a row is deleted in t1 the corresponding rows in t2 are orphaned.</p> </li> <li><p>As we know with InnoDB restart, an id <strong>can</strong> be re-issued. Therefore orphaned rows in t2 can be falsely linked to new rows in t1.</p> </li> </ol> <blockquote> <p>This bug has been finally fixed in <strong>MySQL 8.0.0</strong> <a href="https://dev.mysql.com/worklog/task/?id=6204" rel="noreferrer"><em>WL#6204 - InnoDB persistent max value for autoinc columns</em></a>.</p> <p><strong>InnoDB will keep track of the maximum value and on restart preserve that max value and start from there.</strong></p> </blockquote>
18,461,072
'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine though Microsoft.ACE.OLEDB.12.0 is installed
<p>I get the following exception</p> <pre><code>'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine </code></pre> <p>though I have installed </p> <pre><code>'Microsoft.ACE.OLEDB.12.0' </code></pre> <ul> <li>In my local dev machine I have also office 2010 </li> </ul> <p>What is wrong?</p>
20,393,107
6
3
null
2013-08-27 08:54:24.617 UTC
2
2016-06-07 13:24:50.453 UTC
2013-08-27 09:14:00.42 UTC
null
1,065,525
null
450,602
null
1
1
c#|iis|ms-office|oledb
44,744
<p>If you system is 64 bit,Then you have to change your pool settings to allow 32 bit applications that is OLEDB. ,then this link might help.</p> <p><a href="http://help.webcontrolcenter.com/KB/a1114/how-to-enable-32-bit-application-pool-iis-7-dedicatedvps.aspx">http://help.webcontrolcenter.com/KB/a1114/how-to-enable-32-bit-application-pool-iis-7-dedicatedvps.aspx</a></p>
18,365,551
woocommerce get_woocommerce_currency_symbol()
<p>I am developing an extension for woocommerce WordPress plugin.</p> <p>I would like to display the currency symbol outside of the loop in a custom function</p> <p>I have the following:</p> <pre><code>function my_function( ) { global $woocommerce; echo get_woocommerce_currency_symbol(); } </code></pre> <p>I am not sure why but this doesn't output the symbol? Am I missing something?</p>
18,372,673
8
0
null
2013-08-21 18:59:30.923 UTC
9
2022-01-24 21:53:42.71 UTC
2019-07-17 07:27:52.35 UTC
null
1,214,660
null
1,214,660
null
1
45
wordpress|woocommerce
111,146
<p>Your code should work, which means the issue might be in the database. You can check these 2 functions:<br><a href="https://woocommerce.github.io/code-reference/namespaces/default.html#function_get_woocommerce_currency" rel="noreferrer">get_woocommerce_currency()</a> and <a href="https://woocommerce.github.io/code-reference/namespaces/default.html#function_get_woocommerce_currency_symbol" rel="noreferrer">get_woocommerce_currency_symbol()</a> <br> from the WooCommerce docs that shows that you are using the functions correct.<br> <br>What is left is for you to start some troubleshooting steps to see what causes the error:<br><br> What is <code>get_option('woocommerce_currency')</code> returning? If nothing, then you have no currency set and that is why you get nothing from <code>get_woocommerce_currency_symbol();</code> <br><br> What happens if you add a currency as a parameter to <code>get_woocommerce_currency_symbol</code>? it gets displayed? something like <code>echo get_woocommerce_currency_symbol(&quot;USD&quot;);</code> <br><br> You should add to your script some error handling lines, to inform the user that he needs to have the currency set before using your extension.</p>
18,291,036
What is the difference between count(0), count(1).. and count(*) in mySQL/SQL?
<p>I was recently asked this question in an interview. I tried this in mySQL, and got the same results(final results). All gave the number of rows in that particular table. Can anyone explain the major difference between them.</p>
18,291,041
9
2
null
2013-08-17 16:33:48.353 UTC
15
2021-09-11 07:17:18.04 UTC
2013-10-29 15:28:06.603 UTC
null
1,310,876
null
1,310,876
null
1
57
mysql|sql
101,657
<p>Nothing really, unless you specify a field in a table or an expression within parantheses instead of constant values or *</p> <p>Let me give you a detailed answer. Count will give you non-null record number of given field. Say you have a table named A</p> <pre><code>select 1 from A select 0 from A select * from A </code></pre> <p>will all return same number of records, that is the number of rows in table A. Still the output is different. If there are 3 records in table. With X and Y as field names</p> <pre><code>select 1 from A will give you 1 1 1 select 0 from A will give you 0 0 0 select * from A will give you ( assume two columns X and Y is in the table ) X Y -- -- value1 value1 value2 (null) value3 (null) </code></pre> <p>So, all three queries return the same number. Unless you use </p> <pre><code>select count(Y) from A </code></pre> <p>since there is only one non-null value you will get 1 as output</p>
18,660,798
here-document gives 'unexpected end of file' error
<p>I need my script to send an email from terminal. Based on what I've seen here and many other places online, I formatted it like this:</p> <pre class="lang-none prettyprint-override"><code>/var/mail -s "$SUBJECT" "$EMAIL" &lt;&lt; EOF Here's a line of my message! And here's another line! Last line of the message here! EOF </code></pre> <p>However, when I run this I get this warning:</p> <pre><code>myfile.sh: line x: warning: here-document at line y delimited by end-of-file (wanted 'EOF') myfile.sh: line x+1: syntax error: unexpected end of file </code></pre> <p>...where line x is the last written line of code in the program, and line y is the line with <code>/var/mail</code> in it. I've tried replacing <code>EOF</code> with other things (<code>ENDOFMESSAGE</code>, <code>FINISH</code>, etc.) but to no avail. Nearly everything I've found online has it done this way, and I'm really new at bash so I'm having a hard time figuring it out on my own. Could anyone offer any help?</p>
18,660,985
10
4
null
2013-09-06 14:59:42.693 UTC
19
2022-07-16 03:43:23.037 UTC
2017-11-26 20:01:18.41 UTC
null
3,266,847
null
2,661,085
null
1
108
bash|email|heredoc
156,993
<p>The <code>EOF</code> token must be at the beginning of the line, you can't indent it along with the block of code it goes with.</p> <p>If you write <code>&lt;&lt;-EOF</code> you may indent it, but it must be indented with <kbd>Tab</kbd> characters, not spaces. So it still might not end up even with the block of code.</p> <p>Also make sure you have no whitespace <strong>after</strong> the <code>EOF</code> token on the line.</p>
18,746,929
Using Auto Layout in UITableView for dynamic cell layouts & variable row heights
<p>How do you use Auto Layout within <code>UITableViewCell</code>s in a table view to let each cell's content and subviews determine the row height (itself/automatically), while maintaining smooth scrolling performance?</p>
18,746,930
28
3
null
2013-09-11 16:48:39.377 UTC
1,384
2021-07-16 16:34:47.713 UTC
2017-10-11 11:06:07.583 UTC
null
5,638,630
null
796,419
null
1
1,598
ios|uitableview|autolayout|row-height
680,794
<p><strong>TL;DR:</strong> Don't like reading? Jump straight to the sample projects on GitHub:</p> <ul> <li><a href="https://github.com/smileyborg/TableViewCellWithAutoLayoutiOS8" rel="noreferrer">iOS 8 Sample Project</a> - Requires iOS 8</li> <li><a href="https://github.com/smileyborg/TableViewCellWithAutoLayout" rel="noreferrer">iOS 7 Sample Project</a> - Works on iOS 7+</li> </ul> <h1>Conceptual Description</h1> <p>The first 2 steps below are applicable regardless of which iOS versions you are developing for.</p> <h2>1. Set Up &amp; Add Constraints</h2> <p>In your <code>UITableViewCell</code> subclass, add constraints so that the subviews of the cell have their edges pinned to the edges of the cell's <strong>contentView</strong> (most importantly to the top AND bottom edges). <strong>NOTE: don't pin subviews to the cell itself; only to the cell's <code>contentView</code>!</strong> Let the intrinsic content size of these subviews drive the height of the table view cell's content view by making sure the <em>content compression resistance</em> and <em>content hugging</em> constraints in the vertical dimension for each subview are not being overridden by higher-priority constraints you have added. (<a href="https://stackoverflow.com/questions/22599069/what-is-the-content-compression-resistance-and-content-hugging-of-a-uiview">Huh? Click here.</a>)</p> <p>Remember, the idea is to have the cell's subviews connected vertically to the cell's content view so that they can &quot;exert pressure&quot; and make the content view expand to fit them. Using an example cell with a few subviews, here is a visual illustration of what <strong>some</strong> <em>(not all!)</em> of your constraints would need to look like:</p> <p><img src="https://i.stack.imgur.com/CTUPi.png" alt="Example illustration of constraints on a table view cell." /></p> <p>You can imagine that as more text is added to the multi-line body label in the example cell above, it will need to grow vertically to fit the text, which will effectively force the cell to grow in height. (Of course, you need to get the constraints right in order for this to work correctly!)</p> <p>Getting your constraints right is definitely the <strong>hardest and most important part</strong> of getting dynamic cell heights working with Auto Layout. If you make a mistake here, it could prevent everything else from working -- so take your time! I recommend setting up your constraints in code because you know exactly which constraints are being added where, and it's a lot easier to debug when things go wrong. Adding constraints in code can be just as easy as and significantly more powerful than Interface Builder using layout anchors, or one of the fantastic open source APIs available on GitHub.</p> <ul> <li>If you're adding constraints in code, you should do this once from within the <code>updateConstraints</code> method of your UITableViewCell subclass. Note that <code>updateConstraints</code> may be called more than once, so to avoid adding the same constraints more than once, make sure to wrap your constraint-adding code within <code>updateConstraints</code> in a check for a boolean property such as <code>didSetupConstraints</code> (which you set to YES after you run your constraint-adding code once). On the other hand, if you have code that updates existing constraints (such as adjusting the <code>constant</code> property on some constraints), place this in <code>updateConstraints</code> but outside of the check for <code>didSetupConstraints</code> so it can run every time the method is called.</li> </ul> <h2>2. Determine Unique Table View Cell Reuse Identifiers</h2> <p>For every unique set of constraints in the cell, use a unique cell reuse identifier. In other words, if your cells have more than one unique layout, each unique layout should receive its own reuse identifier. (A good hint that you need to use a new reuse identifier is when your cell variant has a different number of subviews, or the subviews are arranged in a distinct fashion.)</p> <p>For example, if you were displaying an email message in each cell, you might have 4 unique layouts: messages with just a subject, messages with a subject and a body, messages with a subject and a photo attachment, and messages with a subject, body, and photo attachment. Each layout has completely different constraints required to achieve it, so once the cell is initialized and the constraints are added for one of these cell types, the cell should get a unique reuse identifier specific to that cell type. This means when you dequeue a cell for reuse, the constraints have already been added and are ready to go for that cell type.</p> <p>Note that due to differences in intrinsic content size, cells with the same constraints (type) may still have varying heights! Don't confuse fundamentally different layouts (different constraints) with different calculated view frames (solved from identical constraints) due to different sizes of content.</p> <ul> <li>Do not add cells with completely different sets of constraints to the same reuse pool (i.e. use the same reuse identifier) and then attempt to remove the old constraints and set up new constraints from scratch after each dequeue. The internal Auto Layout engine is not designed to handle large scale changes in constraints, and you will see massive performance issues.</li> </ul> <h2>For iOS 8 - Self-Sizing Cells</h2> <h3>3. Enable Row Height Estimation</h3> <blockquote> <p>To enable self-sizing table view cells, you must set the table view’s rowHeight property to UITableViewAutomaticDimension. You must also assign a value to the estimatedRowHeight property. As soon as both of these properties are set, the system uses Auto Layout to calculate the row’s actual height</p> <p><sub>Apple: <a href="https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithSelf-SizingTableViewCells.html" rel="noreferrer">Working with Self-Sizing Table View Cells</a></sub></p> </blockquote> <p>With iOS 8, Apple has internalized much of the work that previously had to be implemented by you prior to iOS 8. In order to allow the self-sizing cell mechanism to work, you must first set the <code>rowHeight</code> property on the table view to the constant <code>UITableView.automaticDimension</code>. Then, you simply need to enable row height estimation by setting the table view's <code>estimatedRowHeight</code> property to a nonzero value, for example:</p> <pre><code>self.tableView.rowHeight = UITableView.automaticDimension; self.tableView.estimatedRowHeight = 44.0; // set to whatever your &quot;average&quot; cell height is </code></pre> <p>What this does is provide the table view with a temporary estimate/placeholder for the row heights of cells that are not yet onscreen. Then, when these cells are about to scroll on screen, the actual row height will be calculated. To determine the actual height for each row, the table view automatically asks each cell what height its <code>contentView</code> needs to be based on the known fixed width of the content view (which is based on the table view's width, minus any additional things like a section index or accessory view) and the auto layout constraints you have added to the cell's content view and subviews. Once this actual cell height has been determined, the old estimated height for the row is updated with the new actual height (and any adjustments to the table view's contentSize/contentOffset are made as needed for you).</p> <p>Generally speaking, the estimate you provide doesn't have to be very accurate -- it is only used to correctly size the scroll indicator in the table view, and the table view does a good job of adjusting the scroll indicator for incorrect estimates as you scroll cells onscreen. You should set the <code>estimatedRowHeight</code> property on the table view (in <code>viewDidLoad</code> or similar) to a constant value that is the &quot;average&quot; row height. <em>Only if your row heights have extreme variability (e.g. differ by an order of magnitude) and you notice the scroll indicator &quot;jumping&quot; as you scroll should you bother implementing <code>tableView:estimatedHeightForRowAtIndexPath:</code> to do the minimal calculation required to return a more accurate estimate for each row.</em></p> <h2>For iOS 7 support (implementing auto cell sizing yourself)</h2> <h3>3. Do a Layout Pass &amp; Get The Cell Height</h3> <p>First, instantiate an offscreen instance of a table view cell, <em>one instance for each reuse identifier</em>, that is used strictly for height calculations. (Offscreen meaning the cell reference is stored in a property/ivar on the view controller and never returned from <code>tableView:cellForRowAtIndexPath:</code> for the table view to actually render onscreen.) Next, the cell must be configured with the exact content (e.g. text, images, etc) that it would hold if it were to be displayed in the table view.</p> <p>Then, force the cell to immediately layout its subviews, and then use the <code>systemLayoutSizeFittingSize:</code> method on the <code>UITableViewCell</code>'s <code>contentView</code> to find out what the required height of the cell is. Use <code>UILayoutFittingCompressedSize</code> to get the smallest size required to fit all the contents of the cell. The height can then be returned from the <code>tableView:heightForRowAtIndexPath:</code> delegate method.</p> <h3>4. Use Estimated Row Heights</h3> <p>If your table view has more than a couple dozen rows in it, you will find that doing the Auto Layout constraint solving can quickly bog down the main thread when first loading the table view, as <code>tableView:heightForRowAtIndexPath:</code> is called on each and every row upon first load (in order to calculate the size of the scroll indicator).</p> <p>As of iOS 7, you can (and absolutely should) use the <code>estimatedRowHeight</code> property on the table view. What this does is provide the table view with a temporary estimate/placeholder for the row heights of cells that are not yet onscreen. Then, when these cells are about to scroll on screen, the actual row height will be calculated (by calling <code>tableView:heightForRowAtIndexPath:</code>), and the estimated height updated with the actual one.</p> <p>Generally speaking, the estimate you provide doesn't have to be very accurate -- it is only used to correctly size the scroll indicator in the table view, and the table view does a good job of adjusting the scroll indicator for incorrect estimates as you scroll cells onscreen. You should set the <code>estimatedRowHeight</code> property on the table view (in <code>viewDidLoad</code> or similar) to a constant value that is the &quot;average&quot; row height. <em>Only if your row heights have extreme variability (e.g. differ by an order of magnitude) and you notice the scroll indicator &quot;jumping&quot; as you scroll should you bother implementing <code>tableView:estimatedHeightForRowAtIndexPath:</code> to do the minimal calculation required to return a more accurate estimate for each row.</em></p> <h3>5. (If Needed) Add Row Height Caching</h3> <p>If you've done all the above and are still finding that performance is unacceptably slow when doing the constraint solving in <code>tableView:heightForRowAtIndexPath:</code>, you'll unfortunately need to implement some caching for cell heights. (This is the approach suggested by Apple's engineers.) The general idea is to let the Autolayout engine solve the constraints the first time, then cache the calculated height for that cell and use the cached value for all future requests for that cell's height. The trick of course is to make sure you clear the cached height for a cell when anything happens that could cause the cell's height to change -- primarily, this would be when that cell's content changes or when other important events occur (like the user adjusting the Dynamic Type text size slider).</p> <h3>iOS 7 Generic Sample Code (with lots of juicy comments)</h3> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Determine which reuse identifier should be used for the cell at this // index path, depending on the particular layout required (you may have // just one, or may have many). NSString *reuseIdentifier = ...; // Dequeue a cell for the reuse identifier. // Note that this method will init and return a new cell if there isn't // one available in the reuse pool, so either way after this line of // code you will have a cell with the correct constraints ready to go. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; // Configure the cell with content for the given indexPath, for example: // cell.textLabel.text = someTextForThisCell; // ... // Make sure the constraints have been set up for this cell, since it // may have just been created from scratch. Use the following lines, // assuming you are setting up constraints from within the cell's // updateConstraints method: [cell setNeedsUpdateConstraints]; [cell updateConstraintsIfNeeded]; // If you are using multi-line UILabels, don't forget that the // preferredMaxLayoutWidth needs to be set correctly. Do it at this // point if you are NOT doing it within the UITableViewCell subclass // -[layoutSubviews] method. For example: // cell.multiLineLabel.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds); return cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // Determine which reuse identifier should be used for the cell at this // index path. NSString *reuseIdentifier = ...; // Use a dictionary of offscreen cells to get a cell for the reuse // identifier, creating a cell and storing it in the dictionary if one // hasn't already been added for the reuse identifier. WARNING: Don't // call the table view's dequeueReusableCellWithIdentifier: method here // because this will result in a memory leak as the cell is created but // never returned from the tableView:cellForRowAtIndexPath: method! UITableViewCell *cell = [self.offscreenCells objectForKey:reuseIdentifier]; if (!cell) { cell = [[YourTableViewCellClass alloc] init]; [self.offscreenCells setObject:cell forKey:reuseIdentifier]; } // Configure the cell with content for the given indexPath, for example: // cell.textLabel.text = someTextForThisCell; // ... // Make sure the constraints have been set up for this cell, since it // may have just been created from scratch. Use the following lines, // assuming you are setting up constraints from within the cell's // updateConstraints method: [cell setNeedsUpdateConstraints]; [cell updateConstraintsIfNeeded]; // Set the width of the cell to match the width of the table view. This // is important so that we'll get the correct cell height for different // table view widths if the cell's height depends on its width (due to // multi-line UILabels word wrapping, etc). We don't need to do this // above in -[tableView:cellForRowAtIndexPath] because it happens // automatically when the cell is used in the table view. Also note, // the final width of the cell may not be the width of the table view in // some cases, for example when a section index is displayed along // the right side of the table view. You must account for the reduced // cell width. cell.bounds = CGRectMake(0.0, 0.0, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds)); // Do the layout pass on the cell, which will calculate the frames for // all the views based on the constraints. (Note that you must set the // preferredMaxLayoutWidth on multiline UILabels inside the // -[layoutSubviews] method of the UITableViewCell subclass, or do it // manually at this point before the below 2 lines!) [cell setNeedsLayout]; [cell layoutIfNeeded]; // Get the actual height required for the cell's contentView CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height; // Add an extra point to the height to account for the cell separator, // which is added between the bottom of the cell's contentView and the // bottom of the table view cell. height += 1.0; return height; } // NOTE: Set the table view's estimatedRowHeight property instead of // implementing the below method, UNLESS you have extreme variability in // your row heights and you notice the scroll indicator &quot;jumping&quot; // as you scroll. - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { // Do the minimal calculations required to be able to return an // estimated row height that's within an order of magnitude of the // actual height. For example: if ([self isTallCellAtIndexPath:indexPath]) { return 350.0; } else { return 40.0; } } </code></pre> <h1>Sample Projects</h1> <ul> <li><a href="https://github.com/smileyborg/TableViewCellWithAutoLayoutiOS8" rel="noreferrer">iOS 8 Sample Project</a> - Requires iOS 8</li> <li><a href="https://github.com/smileyborg/TableViewCellWithAutoLayout" rel="noreferrer">iOS 7 Sample Project</a> - Works on iOS 7+</li> </ul> <p>These projects are fully working examples of table views with variable row heights due to table view cells containing dynamic content in UILabels.</p> <h2>Xamarin (C#/.NET)</h2> <p>If you're using Xamarin, check out this <a href="https://github.com/kentcb/TableViewCellWithAutoLayout_dotNET" rel="noreferrer">sample project</a> put together by <a href="https://stackoverflow.com/users/5380/kent-boogaart">@KentBoogaart</a>.</p>
27,499,607
Why am I still getting a cannot find Java SE Runtime Environment?
<p>These are the errors I get when I try to run a simple java version in the command window.<img src="https://i.stack.imgur.com/WUxcL.png" alt="enter image description here"></p> <p>I followed the advice on <a href="https://stackoverflow.com/questions/8644992/error-registry-key-software-javasoft-java-runtime-environment-currentversion">Error: Registry key &#39;Software\JavaSoft\Java Runtime Environment&#39;\CurrentVersion&#39;?</a>. When I went on regedit, here's what I saw <img src="https://i.stack.imgur.com/y95Te.png" alt=""></p> <p>Which meant that there was nothing to change - right runtime version. I then did the next step which was to "delete all previous versions of Java (using "Programs and Features" uninstall process) and then re-install just the version you want to work with" However, that didn't work either...... Here is my current java directory(see that i have everything installed) <img src="https://i.stack.imgur.com/9Trqw.png" alt="enter image description here"></p> <p>And my current environmental variables are</p> <pre><code>JAVA_HOME - C:\Program Files\Java\jdk1.7.0_71 Path - C:\Program Files\Java\jdk1.7.0_71\bin </code></pre> <p>which i believe are correct as well from <a href="http://www.oracle.com/technetwork/java/javase/install-windows-189425.html" rel="noreferrer">http://www.oracle.com/technetwork/java/javase/install-windows-189425.html</a></p> <p>Does anyone know how i can get rid of this issue? I could do one more uninstall/install but I think that be a waste of time and won't make a difference.</p>
27,500,126
6
11
null
2014-12-16 07:29:03.89 UTC
2
2020-09-01 21:17:01.983 UTC
2017-05-23 12:34:14.043 UTC
null
-1
null
3,761,297
null
1
14
java|runtime|environment
72,769
<p>I want to thank @almas-shaikh for this answer. His comment made me check over C:\Program Files\Java\jdk1.7.0_71\jre\bin and see that there was no java.dll library file inside that directory. What I did next was just deleting the jdk and reinstalling it via jdk-7u71-windows-x64.exe executable. Now when I execute java -home, I get <img src="https://i.stack.imgur.com/VdC5S.png" alt="enter image description here"></p> <p>Now the part I don't get is how the java.dll library file was deleted in the first place......</p>
15,310,261
PHP - Checking if array index exist or is null
<p>Is there a way to check if an array index <strong>exists or is null</strong>? <code>isset()</code> doesn't tell you whether the index doesn't exist or exists but is null. If I do : <code>isset($array[$index]) || is_null($array[$index])</code> it won't work because if the index doesn't exist is_null will crash.</p> <p>How can I check this please? Also is there a way to check only if something exist, no matter if it is set to null or not?</p>
15,310,446
3
4
null
2013-03-09 11:43:41.58 UTC
9
2017-11-07 09:27:47.737 UTC
2013-03-09 11:59:23.84 UTC
null
583,237
null
1,560,774
null
1
42
php|arrays|null|indexing|isset
74,657
<p>The function <a href="http://php.net/manual/en/function.array-key-exists.php" rel="noreferrer">array_key_exists()</a> can do that, and <a href="http://php.net/manual/en/function.property-exists.php" rel="noreferrer">property_exists()</a> for objects, plus what Vineet1982 said. Thanks for your help.</p>
28,014,922
Is it possible to make realistic n-body solar system simulation in matter of size and mass?
<p>Important note: this question has <strong><em>utterly no</em></strong> relation to "PhysX", which is a computer-game-physics system (useful for the physics in arcade games such as ball games, etc); PhysX is a system built-in to Unity3D and other game engines; PhysX is totally irrelevant here.</p> <p>//////////////////// UPDATE (read bottom first) /////////////////////</p> <p>I have been logging the values and searching where the exact problem is, and i think i found it. I have something like this in my code</p> <pre><code>Velocity += Acceleration * Time.deltaTime; position += Velocity * Time.deltaTime; </code></pre> <p>The acceleration is something like 0,0000000000000009.. right now. As the code flows, velocity increases as it should be, no problem with the float. But in the beggining, the initial position of earth is (0,0,23500f) You can see this in the chart i gave at the end.</p> <p>Well now when i add speed * timedelta (which is something like 0,00000000000000005 at this point) to position which is 23500, it basicly doesn't adds it. position is still (0, 0, 23500) not something like (0,0, 23500.00000000000005), thus the earth doesn't move, thus the acceleration doesn't change.</p> <p>If i set the initial position of earth to 0,0,0 and still, set the acceleration to 0.0000000000000000009 to assuume it's position is (0,0,23500) It then "ADDS" the velocity * timedelta. It becomes something like (0,0,000000000000000000005) and keep increases. When the float is 0, there is no problem with adding such small value. But if the float is something like 23500, then it doesn't adds up the small values.</p> <p>I don't know if it's exactly unity's problem or c#'s float.</p> <p>And that's why i can't make it work with small values. If i can overcome this, my problem will be solved.</p> <p>///////////////////////////////////////////////////////////////////////////////</p> <p>i have been develeping n-body phyics to simulate our solar system, so i have been gathering data around to make it as realistic as possible. But there is a problem with the data size. I searched every tiny bit of internet and i couldn't find a single explanation how people overcomes this. (If they so) So i trying my shot here.</p> <p>So, to keep the ratio of distance, radius and "mass" between planets fixed, i created an excel file to calculate all the datas. (Because why the heck would someone put "what would be the earth's mass if it had "that" radius chart" on the internet?) I will give the ss as attachment. It basicly "normalizes" or in other words "scales" every property of a planet to a given reference. In this case, i took the reference as "earth's radius."</p> <p>I work in unity, and you know, you can't work with "too big" or "too small" values in unity. So i had to scale the solar system down, "a lot!"</p> <p>So i use the Newton's law of universal gravitation, which is F = GMm/r^2, to make it simple, i am directly calculating the a = GM/r^2, for a given body from all other bodies. </p> <p>So, the real value of earth's gravitational acceleration "towards sun" is roughly 0,000006 km/s^2, which is even incredibly small value to work with in unity, but it could work. Yet, to get this value,1 i need to set earth's radius (scale) to 6371 unit, and sun to scale of 696,342!, which is TOO big to render it in unity.</p> <p>So i said, let the earth's radius be 1, in unity units. So, when the radius changes, everything changes, the mass, the distance... I kept the density of the planet and calculate the mass from the new volume with the new radius. All the calculations are in the attachment.</p> <p>So the thing is, when i take the earth's radius as 1, the gravitational accelaration towards sun becomes is something like 0,0000000000009 which is ridiculously small. And of course Unity doesn't work with that value.</p> <p>So, if i increase the earth's radius instead, then the mass and radius of the Sun gets ridiculously big and then again, i can't work with it.</p> <p>I don't know how other people fixed this, what they did to overcome this problem but as i see from here, it looks impossible to make realistic n-body simulation of solar system. (in unity atleast)</p> <p>So i need to have 10 rep to post images -_-, i will give link instead. <a href="http://berkaydursun.com/solar_system_simulator/data.PNG" rel="noreferrer">http://berkaydursun.com/solar_system_simulator/data.PNG</a> Also one directory up is the working experimental solar system simulation with n-body calculations but with UNREALISTIC values. It works quite well, and it even looks somehow close to real, but no, it doesn't have the right ratios ^^ You can test it here if you wish <a href="http://berkaydursun.com/solar_system_simulator/" rel="noreferrer">http://berkaydursun.com/solar_system_simulator/</a></p> <p>Edit: WoW I almost started every paragraph with "So" ^^</p>
28,020,934
2
3
null
2015-01-18 21:18:06.26 UTC
8
2022-01-08 05:53:16.887 UTC
2022-01-08 05:53:16.887 UTC
null
44,729
null
3,316,441
null
1
10
c#|simulation|game-physics|physics|orbital-mechanics
9,491
<p>I did program sol system simulation too so here are mine insights:</p> <ol> <li><p><strong>rendering</strong></p> <p>I use <strong>OpenGL</strong> with <strong>1:1</strong> scaling. All units are in <strong>SI</strong> so <strong>[m,s,kg,...]</strong>. The problem gets started with <strong>Z-buffer</strong>. The usual <strong>Z-buffer</strong> bit wide is <code>16/24/32 bit</code> which is nowhere near what you need. I am rendering from <strong>0.1m up to 1000 AU</strong> so how to overcome this?</p> <p>I did manage it by rendering with 3 frustrums at once combining <strong>Z-sorting</strong> and <strong>Z-buffering</strong> (Z-sort is necessary because of transparent rings ...and other effects). So first I render most distant parts up to <code>zfar=1000AU</code>. Sky dome is projected at <code>z=750AU</code> distance then clear the <strong>Z-buffer</strong> and render objects up to <code>zfar=0.1AU</code>. Then clear the <strong>Z-buffer</strong> again and render close objects up to <code>zfar=100000 m</code>.</p> <p>To get this work you have to have as precise projection matrix as you can. <a href="https://stackoverflow.com/a/24009436/2521214">The <code>gluPerspective</code> has unprecise cotangens</a> so it needs to repair concerned elements (get me a long time to spot that). <code>Z near</code> value is dependent on the <strong>Z-buffer</strong> bit width. When coded properly then this works good even with zoom <code>10000x</code>. I use this program as navigation/searcher of objects for mine telescope :) in real time from mine home view. I combine 3D stars, astro bodies, ships, real ground (via DTM and satellite texture). Its capable even of red-cyan anaglyph output :). Can render from surface,atmosphere,space ... (not just locked to Earth). No other 3th party lib then OpenGL is used. Here is how it looks like:</p> <p><img src="https://i.stack.imgur.com/Mm5FM.jpg" alt="img" /> <img src="https://i.stack.imgur.com/7H5rW.png" alt="img" /> <img src="https://i.stack.imgur.com/0Xjab.jpg" alt="img" /> <img src="https://i.stack.imgur.com/Yhlod.png" alt="img" /> <img src="https://i.stack.imgur.com/YPV5K.png" alt="img" /></p> <p>As you can see it works fine on any altitude or zoom the atmosphere is done like this <a href="https://stackoverflow.com/a/19659648/2521214">atmosphere scattering shader</a></p> </li> <li><p><strong>simulation</strong></p> <p>I am not using <strong>n-body</strong> gravity simulation because for that you need a lot of data that is very very hard to get (and almost impossible in desired precision). The computations must be done <strong>very precisely</strong>.</p> <p>I use <strong>Kepler's equation</strong> instead so see these:</p> <ul> <li><a href="https://stackoverflow.com/a/25403425/2521214">Solving Kepler's equation</a></li> <li><a href="https://stackoverflow.com/a/25722336/2521214">C++ implementation</a>.</li> </ul> <p>If you still want to use gravity model then use <strong>JPL horizons</strong> from <strong>NASA</strong>. I think they have also source codes in C/C++ there but they are using incompatible reference frame with mine maps so it is unusable for me.</p> <p>In general Kepler's equation has bigger error but it is not increasing with time too much. The gravity model is more precise but its error is rising with time and you need to update the astro body data continuously to make it work ...</p> </li> </ol> <p><strong>[edit1] integration precision</strong></p> <p>your current implementation is like this:</p> <pre class="lang-cpp prettyprint-override"><code>// object variables double acc[3],vel[3],pos[3]; // timer iteration double dt=timer.interval; for (int i=0;i&lt;3;i++) { vel[i]+=acc[i]*dt; pos[i]+=vel[i]*dt; } </code></pre> <p>The problem is when you are adding very small and very big value then they are shifted to the same exponent before addition which will round off significant data To avoid this just change it to this:</p> <pre class="lang-cpp prettyprint-override"><code>// object variables double vel0[3],pos0[3]; // low double vel1[3],pos1[3]; // high double acc [3],vel [3],pos [3]; // full // timer iteration double dt =timer.interval; double max=10.0; // precision range constant for (int i=0;i&lt;3;i++) { vel0[i]+=acc[i]*dt; if (fabs(vel0[i]&gt;=max)) { vel1[i]+=vel0[i]; vel0[i]=0.0; } vel[i]=vel0[i]+vel1[i]; pos0[i]+=vel[i]*dt; if (fabs(pos0[i]&gt;=max)) { pos1[i]+=pos0[i]; pos0[i]=0.0; } pos[i]=pos0[i]+pos1[i]; } </code></pre> <p>Now <code>xxx0</code> is integrated up to <code>max</code> and the whole thing is added to <code>xxx1</code></p> <p>The rounding is still there but it is not cumulative anymore. You have to select <code>max</code> value that the integration itself is safe and also the addition <code>xxx0+xxx1</code> have to be safe. So if the numbers are too different for one spliting then split twice or more ...</p> <ul> <li>like: <code>xxx0+=yyy*dt; if (fabs(xxx0&gt;max0))... if (fabs(xxx1&gt;max1))...</code></li> </ul> <p>This however does not fully use the dynamic range of added variables to their full potential. There are alternatives that does it like this:</p> <ul> <li><a href="https://stackoverflow.com/a/66984548/2521214">How to emulate double precision using two floats</a></li> </ul> <p><strong>[Edit2] Stars</strong></p> <ul> <li><a href="http://www.nightscapes.net/techniques/TechnicalPapers/StarColors.pdf" rel="nofollow noreferrer">The Colors of the Stars</a> The best star visualization I ever saw</li> <li><a href="https://stackoverflow.com/a/22630970/2521214">Star B-V color index to apparent RGB color</a> all star catalogues uses B-V index</li> <li><a href="https://stackoverflow.com/a/22630641/2521214">Using Stelar catalogs</a> also star names cross-reference link is there</li> <li><a href="https://stackoverflow.com/a/40171880/2521214">Skybox: combine different star data</a></li> </ul> <p><strong>[Edit3] Improving Newton D'ALembert integration precision even more</strong></p> <p>The basic problem with iterative integration is that applaying gravity based acceleration based on current body position will result in bigger orbits because durring integration step <code>dt</code> the position changes a bit which is not accounted in the naive integration. To remedy this take a look at this picture:</p> <p><a href="https://i.stack.imgur.com/1W2ch.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1W2ch.png" alt="integration" /></a></p> <p>Let assume our body is at circular orbit and in the 0 deg position. Instead of using acceleration direction based on current position I used position after <code>0.5*dt</code>. This augment the acceleration small bit resulting in much much higher precision (correspondence to Kepler orbits). With this tweak I was able to successfully convert from Kepler orbit into Newton D'Alembert for 2 body system. (doing this for n-body is the next step). Of coarse correlating with real data from our solar system is only possible for 2 body system not affected by tidal effects and or moons. To construct own fictional data you can use Kepler circular orbit and contripedal force equalizing gravity:</p> <pre><code>G = 6.67384e-11; v = sqrt(G*M/a); // orbital speed T = sqrt((4.0*M_PI*M_PI*a*a*a)/(G*(m+M))); // orbital period </code></pre> <p>where <code>a</code> is the circular orbit radius <code>m</code> is body mass , <code>M</code> is focal body mass (sun). To maintain precision in acceptable tolerance (for me) the integration step <code>dt</code> should be:</p> <pre><code>dt = 0.000001*T </code></pre> <p>So to put new body for testing just put it at:</p> <pre><code>pos = (a,0,0) vel = (0,sqrt(G*M/a),0) </code></pre> <p>While main focal body (Sun) is at:</p> <pre><code>pos = (0,0,0) vel = (0,0,0) </code></pre> <p>This will place your body in circular orbit so you can compare Kepler versus Newton D'Alembert to evaluate precision of your simulation.</p>
27,966,757
Find min value in array > 0
<p>I am looking to find the lowest positive value in an array and its position in the list. If a value within the list is duplicated, only the FIRST instance is of interest. This is what I have which does what I want but includes 0.</p> <pre><code>print "Position:", myArray.index(min(myArray)) print "Value:", min(myArray) </code></pre> <p>for example, as it stands if,</p> <p><code>myArray = [4, 8, 0, 1, 5]</code></p> <p>then Position: 2, Value: 0</p> <p>I want it to present position: 3, value: 1</p>
27,966,830
7
4
null
2015-01-15 15:21:53.5 UTC
4
2016-11-04 18:55:46.733 UTC
2015-01-15 17:05:39.13 UTC
null
2,359,271
null
3,001,499
null
1
21
python|list|search|min
50,306
<p>You can use a <a href="https://wiki.python.org/moin/Generators" rel="noreferrer">generator expression</a> with <code>min</code>. This will set <code>m</code> as the minimum value in <code>a</code> that is greater than 0. It then uses <code>list.index</code> to find the index of the first time this value appears.</p> <pre><code>a = [4, 8, 0, 1, 5] m = min(i for i in a if i &gt; 0) print("Position:", a.index(m)) print("Value:", m) # Position: 3 # Value: 1 </code></pre>
7,881,883
JAXB Customizations With a Poorly Formed WSDL
<p>This is driving me insane. I have a schema embedded within a WSDL that needs customization because WSIMPORT is throwing the following error</p> <pre><code>[ERROR] Complex type and its child element share the same name "DomainsMap". Use a class customization to resolve this conflict. line 878 of file:/C:/jaxws-ri/bin/ArtesiaWebServices.wsdl </code></pre> <p>1) I have no control over this WSDL as I am building a WSDL first client and I expect it to go over revisions w/o any formal consultation or release to me. 2) It is not acceptable any longer to manually fix this naming collision because I need to include the construction of stubs into an automated build chain. </p> <p>I must use an external customization file. I just can't seem to figure out how to get the customization to work.</p> <p>Here is the offending WSDL fragment:</p> <pre><code>&lt;wsdl:definitions&gt; &lt;wsdl:types&gt; &lt;xs:schema&gt; . . . &lt;xs:complexType final="extension restriction" name="domainsMap"&gt; &lt;xs:sequence&gt; &lt;xs:element name="domainsMap"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element maxOccurs="unbounded" minOccurs="0" name="entry"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element minOccurs="0" name="key" type="xs:string"/&gt; &lt;xs:element minOccurs="0" name="value" type="tns:domainValueMap"/&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; </code></pre> <p>This would be a great chance for you to flex your JAXB skills. Any help would be greatly appreciated.</p> <p>I've been staring at the jaxb documentation for hours and still no luck. I can offer the entire WSDL if need be. Can anyone help? </p>
7,890,753
2
0
null
2011-10-24 20:55:13.933 UTC
8
2011-10-31 12:52:06.46 UTC
2011-10-25 12:33:09.133 UTC
null
654,200
null
654,200
null
1
13
web-services|soap|wsdl|jaxb
19,536
<p>Well this morning I came in to work and was able to figure this out. Sometimes just walking away from the problem and coming back with a fresh head is the best way. Here is the solution that worked for me:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;jaxws:bindings xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:jaxws="http://java.sun.com/xml/ns/jaxws" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.1" xmlns:xs="http://www.w3.org/2001/XMLSchema" wsdlLocation="ArtesiaWebServices.wsdl"&gt; &lt;enableWrapperStyle&gt;true&lt;/enableWrapperStyle&gt; &lt;enableAsyncMapping&gt;false&lt;/enableAsyncMapping&gt; &lt;jaxws:bindings node="wsdl:definitions/wsdl:types/xs:schema/xs:complexType[@name='domainsMap']/xs:sequence/xs:element[@name='domainsMap']/xs:complexType"&gt; &lt;!-- This binding will fix the domainsMap inner element called domainsMap. sheesh, who names stuff like that?! --&gt; &lt;jaxb:class name="DomainsMapElement"/&gt; &lt;/jaxws:bindings&gt; &lt;jaxws:bindings node="wsdl:definitions/wsdl:types/xs:schema/xs:complexType[@name='domainValueMap']/xs:sequence/xs:element[@name='domainValueMap']/xs:complexType"&gt; &lt;!-- This binding will fix the domainValueMap inner element called domainValueMap. sheesh, who names stuff like that?! --&gt; &lt;jaxb:class name="DomainValueMapElement"/&gt; &lt;/jaxws:bindings&gt; &lt;/jaxws:bindings&gt; </code></pre> <p>I use the above external binding file with the wsimport tool in the following command.</p> <p>Important things about this binding file:</p> <ul> <li>The namespace for jaxws bindings is used. This is the only way I could get the node selection to work properly</li> <li><p>The node selection has to end with /xs:complexType. If you stop at selecting the the element name the compiler will generate errors.</p> <p>wsimport -d generated -keep -b ArtesiaExternalBinding.xml ArtesiaWebServices.wsdl</p></li> </ul> <p>Options used: <br><strong>-d generated</strong> specifies the output directory (a folder named 'generated' in this case) <br><strong>-b ArtesiaExternalBinding.xml</strong> tells the JAXB compiler to use the binding file. <br><strong>-keep</strong> keep the stubs (i just use the stubs for inspection)</p> <p>finally, I found this to be the most helpful tidbit of information: <a href="http://jax-ws.java.net/nonav/2.1.2m1/docs/customizations.html#2.9_XML_schema_customization" rel="noreferrer">java.net documents on jaxws customizations</a></p> <p>This is what lead me to nesting the jaxb customizations within jaxws tags. Thanks for the link <strong>Petru Gardea</strong></p>
59,876,638
Disable prettier for a single file
<p>I need to disable <strong>prettier</strong> for a <em>single file</em> (API URLs file) in my project in Vs-code. actually, I need each API and its URL to be in one line, but prettier breaks them in two lines.</p> <p><strong>before</strong></p> <pre><code>export const GET_SEARCH_TEACHERS = params =&gt; myexampleFunction_app_base(`teachers/search/${params.search}`); </code></pre> <p><strong>after</strong></p> <pre><code>export const GET_SEARCH_TEACHERS = params =&gt; myexampleFunction_app_base(`teachers/search/${params.search}`); </code></pre>
59,879,483
4
8
null
2020-01-23 10:42:17.813 UTC
2
2022-02-24 17:38:43.827 UTC
2021-07-19 07:02:08.007 UTC
null
3,952,180
null
3,952,180
null
1
45
javascript|reactjs|ecmascript-6|visual-studio-code|prettier
69,217
<p>If you want a certain file in a repo to never be formatted by prettier, you can add it to a .prettierignore file: <a href="https://prettier.io/docs/en/ignore.html#ignoring-files" rel="noreferrer">Disable Prettier for one file</a></p> <p>From the docs:</p> <blockquote> <p>To exclude files from formatting, create a .prettierignore file in the root of your project. .prettierignore uses <a href="https://git-scm.com/docs/gitignore#_pattern_format" rel="noreferrer">gitignore</a> syntax.</p> <p>Example:</p> <pre><code># Ignore artifacts: build coverage # Ignore all HTML files: *.html </code></pre> </blockquote>
8,375,456
How to delete multiple rows with 2 columns as composite primary key in MySQL?
<p>My innodb table has the following structure: 4 columns <code>(CountryID, Year, %Change, Source)</code>, with the 2 columns <code>(CountryID, Year)</code> as the primary key. How do I delete multiple rows other than using a for-loop to delete each row?</p> <p>I'm looking for something similar to </p> <pre><code>DELETE FROM CPI WHERE CountryID AND Year IN (('AD', 2010), ('AF', 2009), ('AG', 1992)) </code></pre>
8,375,561
1
4
null
2011-12-04 13:00:29.267 UTC
5
2019-01-28 13:47:08.837 UTC
2019-01-28 13:47:08.837 UTC
null
2,270,475
null
960,706
null
1
47
mysql|sql-delete|composite-primary-key|multiple-records
21,580
<p>The answer in Oracle is:</p> <pre><code>delete from cpi where (countryid, year) in (('AD', 2010), ('AF', 2009), ('AG', 1992)) </code></pre> <p>It's fairly standard SQL syntax and I think MySQL is the same.</p>
5,001,529
How can I say "love" without character or digits in JavaScript?
<p>Inspired by Ryan Barnett's PPT of BlackHat DC 2011, especially the code below:</p> <pre><code>($=[$=[]][(__=!$+$)[_=-~-~-~$]+({}+$)[_/_]+ ($$=($_=!''+$)[_/_]+$_[+$])])()[__[_/_]+__ [_+~$]+$_[_]+$$](_/_) </code></pre> <p>Yesterday was special day for lovers, so I tried to write something similar. Which basically alert "I love you" without any character or digits.</p> <p>e.g. "I" can be obtained from <code>((_=-~[])/--_+[])[_]</code></p> <p>we have "[object Object]", "true", "false", "NaN", "Infinity" to use, I cannot figure out a way to get "v" this way.</p> <p>I tried to think of <code>String.fromCharCode()</code>, (Ryan already get <code>window</code> reference for us, so in theory, we can <code>window["String"]["fromCharCode"](118)</code>) however I miss "S" and "C" character here. Also think about <code>window["eval"](...)</code>, again, I have no "v".</p> <p>Just try to explain a little bit, <code>[]</code> is empty, when apply <code>+/-/~</code> operate to it, it converts to number <code>0</code>, and <code>~[]</code> gives <code>1</code>, <code>1/0</code> gives <code>Infinitey</code>. Then it comes to <code>1/0 + []</code>, they will both converted to string for the add, which gives <code>"Infinity"</code>, and <code>"Infinity"[_] == "Infinity"[0] == "I"</code>...</p> <p>The original code of Ryan is more complex, it utilized a lot more, includes scope, special return value, etc. (this is another story)</p> <p>This might not seem to be a great idea to do things, but just very interesting.</p> <p>With help with meze, I was able to produce this for Firefox:</p> <pre><code>($=($=[$=[]][(__=!$+$)[_=-~-~-~$]+(_$={}+$)[_/_]+ ($$=($_=!''+$)[_/_]+$_[+$])])())[__[_/_]+__ [_+~$]+$_[_]+$$]((_$_=(__$=-~[])/--__$+[])[__$]+_$[_+++_]+__[__$=-~-~[]]+_$[-~[]]+($[_$[$__=_+_]+_$[++$__]+_$[++$__]+_$[++$__]+_$[++$__]+_$[++$__]]+[])[ $__+$__+--_]+__[++_]+_$[$__=_+--_]+_$_[_+++_]+_$[_/_]+$_[__$]); </code></pre> <p>it basically is <code>alert("I love you")</code>, many thanks! If only I get the help yesterday, which I have not post this yet :(</p> <p>JavaScript is beautiful, some varibles for your reference:</p> <pre><code>$_ = "true" __ = "false" _$ = "[object Object]" $$ = "rt" _$_ = "Infinity" _ = 3 = 4 = 3 = 4 = 3 $ = window $__ = 8 = 13 __$ = 0 = 2 </code></pre> <p>Some variables are reused many times, will not try to leave details, it is not a fun job :) I am happy, we are finally here! This actually has lots of potential, as we now have "v", and lots of digits, we will in theory possible to <code>eval()</code> lots of... things easier. I will show this to my wife, hope she enjoys the _$-+()...</p> <p>example as your reference: <a href="http://jsfiddle.net/Y4wqw/">http://jsfiddle.net/Y4wqw/</a></p> <p>btw, we can shorten the code a bit, as we already have reference to <code>sort()</code>, which can be used instead of window["Object"] to get the "native code" => "v", here it is: </p> <pre><code>($=($_$=($=[$=[]][(__=!$+$)[_=-~-~-~$]+(_$={}+$)[_/_]+ ($$=($_=!''+$)[_/_]+$_[+$])]))())[__[_/_]+__ [_+~$]+$_[_]+$$]((_$_=(__$=-~[])/--__$+[])[__$]+_$[_+++_]+__[__$=-~-~[]]+_$[-~[]]+($_$+[])[(__$&lt;&lt;__$&lt;&lt;__$)-_+~[]]+$_[--_]+_$[$__=_+++_]+_$_[_+--_]+_$[_/_]+$_[__$]); </code></pre> <p>Again, it works only in Firefox, might not try to migrate to other browser. And I love Firefox.</p>
5,002,155
4
8
null
2011-02-15 08:57:22.24 UTC
19
2011-02-15 18:01:40.777 UTC
2011-02-15 12:31:51.56 UTC
null
275,133
null
275,133
null
1
39
javascript|obfuscation
5,436
<p>Well at least in Firefox, JavaScript native objects return <code>function Object() { [native code] }</code>, which has 'v'. So if we have <code>window</code> and <code>Object</code>, then i suppose we could do:</p> <pre><code>(window["Object"]+0)[29]; </code></pre>
5,315,497
How to center a label text in WPF?
<p>How to center a label text in WPF?</p> <pre> <code> Label HorizontalAlignment="Center" Content="What?" FontSize="25" FontWeight="Bold" Canvas.Top="5" </code> </pre>
5,315,555
4
0
null
2011-03-15 17:23:01.643 UTC
6
2019-07-04 13:41:31.823 UTC
2011-03-15 18:10:59.567 UTC
null
375,422
null
375,422
null
1
116
c#|.net|wpf
158,284
<p>use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.control.horizontalcontentalignment.aspx" rel="noreferrer">HorizontalContentAlignment</a> property. </p> <p><strong>Sample</strong></p> <pre><code>&lt;Label HorizontalContentAlignment="Center"/&gt; </code></pre>
5,588,799
Objective-C: How do you access parent properties from subclasses?
<p>If I have this class defined, how do I access the <code>someObject</code> property in subclasses without compiler errors?</p> <pre><code>@interface MyBaseClass // someObject property not declared here because I want it to be scoped // protected. Only this class instance and subclass instances should be // able to see the someObject property. @end // This is a private interface extension...properties declared here // won't be visible to subclasses. However, I don't see any way to // declare protected properties... @interface MyBaseClass (private) @property (nonatomic, readwrite, retain) NSObject *someObject; @end </code></pre> <p> <pre><code>@interface MySubclass : MyBaseClass @end @implementation MySubclass - (id) init { // Try to do something with the super classes' someObject property. // Always throws compile errors. // Semantic Issue: Property 'someObject' not found // object of type 'MySubclass *' self.someObject = nil; } @end </code></pre> <p><br><br> I'm obviously not understanding how inheritance works in objective-c. Could someone enlighten me?</p>
9,283,083
5
1
null
2011-04-07 23:29:10.767 UTC
15
2015-01-14 17:41:43.967 UTC
2012-10-24 14:18:33.607 UTC
null
257,550
null
257,550
null
1
48
objective-c|cocoa-touch|cocoa|oop
42,872
<p>The solution you're after is to declare the MyBaseClass private property in a class extension:</p> <pre><code>@interface MyBaseClass () @property (nonatomic, readwrite, retain) NSObject *someObject; @end </code></pre> <p>You are then free to make that declaration <em>both</em> in MyBaseClass <em>and</em> in MySubclass. This lets MySubclass know about these properties so that its code can talk about them.</p> <p>If the repetition bothers you, put the class extension in a .h file of its own and import it into both .m files.</p> <p>I will give an example from my own code. Here is <em>MyDownloaderPrivateProperties.h</em>:</p> <pre><code>@interface MyDownloader () @property (nonatomic, strong, readwrite) NSURLConnection* connection; @property (nonatomic, copy, readwrite) NSURLRequest* request; @property (nonatomic, strong, readwrite) NSMutableData* mutableReceivedData; @end </code></pre> <p>There is no corresponding <em>.m</em> file and that's all that's in this file; it is, as it were, purely declarative. Now here's the start of <em>MyDownloader.m</em>:</p> <pre><code>#import "MyDownloader.h" #import "MyDownloaderPrivateProperties.h" @implementation MyDownloader @synthesize connection=_connection; @synthesize request=_request; @synthesize mutableReceivedData=_mutableReceivedData; // ... </code></pre> <p>And here's the start of its subclass <em>MyImageDownloader.m</em>:</p> <pre><code>#import "MyImageDownloader.h" #import "MyDownloaderPrivateProperties.h" </code></pre> <p>Problem solved. Privacy is preserved, as these are the only classes that import <em>MyDownloaderPrivateProperties.h</em> so they are the only classes that know about these properties as far as the compiler is concerned (and that's all that privacy is in Objective-C). The subclass can access the private properties whose accessors are synthesized by the superclass. I believe that's what you wanted to accomplish in the first place.</p>
5,150,676
How to remove a field from params[:something]
<p>My registration form, which is a form for the Users model, takes a string value for company. However, I have just made a change such that users belongs_to companies. Therefore, I need to pass an object of Company to the Users model. </p> <p>I want to use the string value from the form to obtain the an object of Company:</p> <pre><code>@user.company = Company.find_by_name(params[:company]) </code></pre> <p>I believe the above works, however the form is passing the :company (which is string) into the model when I call:</p> <pre><code>@user = User.new(params[:user]) </code></pre> <p>Therefore, I want to know (and cannot find how) to remove the :company param before passing it to the User model. </p>
5,150,695
6
0
null
2011-03-01 05:03:03.983 UTC
26
2022-04-21 13:05:41.247 UTC
null
null
null
null
638,529
null
1
135
ruby-on-rails
107,423
<p><strong>Rails 4/5 - edited answer</strong> (see comments)</p> <p>Since this question was written newer versions of Rails have added the <a href="https://apidock.com/rails/Hash/extract%21" rel="noreferrer">extract!</a> and <a href="https://apidock.com/rails/Hash/except" rel="noreferrer">except</a> eg:</p> <pre><code>new_params = params.except[the one I wish to remove] </code></pre> <p>This is a safer way to 'grab' all the params you need into a copy WITHOUT destroying the original passed in params (which is NOT a good thing to do as it will make debugging and maintenance of your code very hard over time). </p> <p>Or you could just pass directly without copying eg:</p> <pre><code>@person.update(params[:person].except(:admin)) </code></pre> <p>The <code>extract!</code> (has the ! bang operator) will modify the original so use with more care!</p> <p><strong>Original Answer</strong></p> <p>You can remove a key/value pair from a Hash using <code>Hash#delete</code>:</p> <pre><code>params.delete :company </code></pre> <p>If it's contained in params[:user], then you'd use this:</p> <pre><code>params[:user].delete :company </code></pre>
4,880,489
Android ClassNotFoundException
<p>I am having a problem with one of my apps and I was wondering if anyone could give me any insight into what maybe causing it.</p> <p>I am getting a <strong>ClassNotFoundException</strong>, the important line below is</p> <pre><code>E/AndroidRuntime(21982): Caused by: java.lang.ClassNotFoundException: couk.doridori.goigo.customUI.GoBoardView in loader dalvik.system.PathClassLoader@446fc3d0 </code></pre> <p>Now this app has been out for over a year and 2 days ago I had two seperate users contact me regarding this issue, one on a HTC wildfire (2.1) and one a Samsung Galaxy S (?). Now I cannot recreate this problem on my devices (2.2 and 1.6) or an emulator (2.1) and cannot really work out why this class cannot be found by the classloader. I have spent a while googling to no avail, and hopes someone has some pointers! It only seems to be when an activity is loaded which when the contentView is set, it tries to inflate a custom View called <strong>GoBoardView</strong> which extends the View class, this is just doing some simple canvas drawing and is not using any third party libs or any other classes that would have a packagename clash or anything.</p> <p>Please help! Just in case its a build issue I am updating all my SDK and ADT through eclipse as it was building against 1.6 and using the old ADT, but I have no idea if this will help just thought worth a try. Any advice would be great thanks! (see below for EDIT)</p> <pre><code>E/AndroidRuntime(21982): java.lang.RuntimeException: Unable to start activity ComponentInfo{couk.doridori.goigoFull/couk.doridori.goigoFull.Board}: android.view.InflateException: Binary XML file line #14: Error inflating class couk.doridori.goigo.customUI.GoBoardView E/AndroidRuntime(21982): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596) E/AndroidRuntime(21982): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621) E/AndroidRuntime(21982): at android.app.ActivityThread.access$2200(ActivityThread.java:126) E/AndroidRuntime(21982): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932) E/AndroidRuntime(21982): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime(21982): at android.os.Looper.loop(Looper.java:123) E/AndroidRuntime(21982): at android.app.ActivityThread.main(ActivityThread.java:4603) E/AndroidRuntime(21982): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(21982): at java.lang.reflect.Method.invoke(Method.java:521) E/AndroidRuntime(21982): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) E/AndroidRuntime(21982): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) E/AndroidRuntime(21982): at dalvik.system.NativeStart.main(Native Method) E/AndroidRuntime(21982): Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class couk.doridori.goigo.customUI.GoBoardView E/AndroidRuntime(21982): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:576) E/AndroidRuntime(21982): at android.view.LayoutInflater.rInflate(LayoutInflater.java:618) E/AndroidRuntime(21982): at android.view.LayoutInflater.rInflate(LayoutInflater.java:621) E/AndroidRuntime(21982): at android.view.LayoutInflater.rInflate(LayoutInflater.java:621) E/AndroidRuntime(21982): at android.view.LayoutInflater.inflate(LayoutInflater.java:407) E/AndroidRuntime(21982): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) E/AndroidRuntime(21982): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) E/AndroidRuntime(21982): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207) E/AndroidRuntime(21982): at android.app.Activity.setContentView(Activity.java:1629) E/AndroidRuntime(21982): at couk.doridori.goigoFull.Board.onCreate(Board.java:31) E/AndroidRuntime(21982): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) E/AndroidRuntime(21982): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544) E/AndroidRuntime(21982): ... 11 more E/AndroidRuntime(21982): Caused by: java.lang.ClassNotFoundException: couk.doridori.goigo.customUI.GoBoardView in loader dalvik.system.PathClassLoader@446fc3d0 E/AndroidRuntime(21982): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243) E/AndroidRuntime(21982): at java.lang.ClassLoader.loadClass(ClassLoader.java:573) E/AndroidRuntime(21982): at java.lang.ClassLoader.loadClass(ClassLoader.java:532) E/AndroidRuntime(21982): at android.view.LayoutInflater.createView(LayoutInflater.java:466) E/AndroidRuntime(21982): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565) E/AndroidRuntime(21982): ... 22 more </code></pre> <p><strong>EDIT</strong></p> <p>Ok, researching some of the links that users to have commented in reply to this question, it seems that the use of the wrong context for loading activities can cause this problem. I find this interesting becuase <strong>one</strong> of the <strong>two</strong> log reports i have been send has this exception preceeded by </p> <pre><code>W/ActivityManager( 1222): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { flg=0x20000 cmp=couk.doridori.goigoFull/.Games } </code></pre> <p>which is quite self explanatory - problem is i have no idea where this activity could be being started from where it uses a non activity context, so im a bit stumped, thinking it maye be some multitasking like quirk and its being brought back into the foreground of something . This can then apparently cause problems with the classLoader. If this was happening on a users phone i cant see why i cannot reproduce this (and most other users cannot either).</p> <p>The other thing i found through the links which is interesting, is some people have encountered problems due to a "incorrect apk installation', which can be resolved by a reinstall, which i have asked the users who have had the problem to try (which does not make a difference). Also it seems once the problem is encountered (which is on first use) it will be persistent.</p>
5,009,215
9
1
null
2011-02-02 22:09:57.67 UTC
3
2014-02-12 12:28:08.88 UTC
2012-07-28 21:50:11.003 UTC
null
533,552
null
236,743
null
1
34
java|android|classnotfoundexception
55,494
<p>I can't help but notice that your Activity name is <code>couk.doridori.goigoFull.Board</code> but your missing custom View class is <code>couk.doridori.goigo.customUI.GoBoardView</code> ... it looks like you might have two different packages (goigo vs goigoFull).</p> <p>Are you by any chance doing clever things with library projects? You'll want to be really careful with fully-qualified classnames in code and in layout xml...</p> <p>(If not please add some more information about your project setup and also paste your layout XML which the layoutinflater is choking on) </p>
5,210,033
Using only CSS, show div on hover over another element
<p>I would like to show a div when someone hovers over an <code>&lt;a&gt;</code> element, but I would like to do this in CSS and not JavaScript. Do you know how this can be achieved?</p>
5,210,074
15
5
null
2011-03-06 10:47:13.34 UTC
105
2022-02-17 12:38:28.383 UTC
2021-08-12 13:38:41.737 UTC
null
2,756,409
null
377,381
null
1
353
css
858,362
<p>You can do something like <a href="http://jsfiddle.net/Vqmaw/">this</a>: <div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>div { display: none; } a:hover + div { display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a&gt;Hover over me!&lt;/a&gt; &lt;div&gt;Stuff shown on hover&lt;/div&gt;</code></pre> </div> </div> </p> <p>This uses the <a href="http://meyerweb.com/eric/articles/webrev/200007a.html">adjacent sibling selector</a>, and is the basis of the <a href="http://www.alistapart.com/articles/dropdowns">suckerfish dropdown menu</a>. </p> <p>HTML5 allows anchor elements to wrap almost anything, so in that case the <code>div</code> element can be made a child of the anchor. Otherwise the principle is the same - use the <code>:hover</code> pseudo-class to change the <code>display</code> property of another element. </p>
5,595,418
Joins are for lazy people?
<p>I recently had a discussion with another developer who claimed to me that JOINs (SQL) are useless. This is technically true but he added that using joins is less efficient than making several requests and link tables in the code (C# or Java). </p> <p>For him joins are for lazy people that don't care about performance. Is this true? Should we avoid using joins?</p>
5,595,501
21
3
null
2011-04-08 13:02:15.127 UTC
27
2012-04-10 10:49:49.967 UTC
2011-04-09 08:41:24.723 UTC
null
298,479
null
196,526
null
1
168
c#|java|sql|join
7,754
<p>No, we should avoid developers who hold such incredibly wrong opinions.</p> <p>In many cases, a database join is several orders of magnitude faster than anything done via the client, because it avoids DB roundtrips, and the DB can use indexes to perform the join.</p> <p><s>Off the top of my head, I can't even imagine a single scenario where a correctly used join would be slower than the equivalent client-side operation.</s></p> <p><strong>Edit:</strong> There are some rare cases where custom client code can do things more efficiently than a straightforward DB join (see comment by meriton). But this is very much the exception.</p>
17,023,523
"a" Does not contain a definition for"b" and no extension method ' b ' accepting a first argument of type
<p>I got an error which i cant fix:</p> <pre><code>Error 1 'System.Windows.Forms.Label' does not contain a definition for 'Copy' and no extension method 'Copy' accepting a first argument of type'System.Windows.Forms.Label' could be found (are you missing a using directive or an assembly reference?) //path 156 22 FileWatcherEigen </code></pre> <p>That was my error. Can someone help me and explain to me what went wrong?</p> <p>This is my code:</p> <pre><code>using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private bool pause = false; private bool cut1 = false; private bool copy1 = false; public Form1() { InitializeComponent(); } // The lines with performed actions of a file private void fileSystemWatcher1_Created(object sender,System.IO.FileSystemEventArgs e) { if (!pause) { listBox1.Items.Add("File Created&gt; " + e.FullPath + " -Date:" + DateTime.Now); } } private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e) { if (!pause) { listBox1.Items.Add("File Changed&gt; " + e.FullPath + " -Date:" + DateTime.Now); } } private void fileSystemWatcher1_Deleted(object sender, System.IO.FileSystemEventArgs e) { if (!pause) { listBox1.Items.Add("File Deleted&gt; " + e.FullPath + " -Date:" + DateTime.Now); } } private void fileSystemWatcher1_Renamed(object sender, System.IO.RenamedEventArgs e) { if (!pause) { listBox1.Items.Add("File Renamed&gt; " + e.FullPath + " -Date:" + DateTime.Now); } } private void fileSystemWatcher2_Changed(object sender, System.IO.FileSystemEventArgs e) { if (!pause) { listBox1.Items.Add("File Changed&gt; " + e.FullPath + " -Date:" + DateTime.Now); } } private void fileSystemWatcher2_Created(object sender, System.IO.FileSystemEventArgs e) { if (!pause) { listBox1.Items.Add("File Created&gt; " + e.FullPath + " -Date:" + DateTime.Now); } } private void fileSystemWatcher2_Deleted(object sender, System.IO.FileSystemEventArgs e) { if (!pause) { listBox1.Items.Add("File Deleted&gt; " + e.FullPath + " -Date:" + DateTime.Now); } } private void fileSystemWatcher2_Renamed(object sender, System.IO.RenamedEventArgs e) { if (!pause) { listBox1.Items.Add("File Renamed&gt; " + e.FullPath + " -Date:" + DateTime.Now); } } //1st directory private void button2_Click(object sender, EventArgs e) { if (dlgOpenDir.ShowDialog() == DialogResult.OK) { fileSystemWatcher1.EnableRaisingEvents = false; // Stop watching fileSystemWatcher1.IncludeSubdirectories = true; fileSystemWatcher1.Path = dlgOpenDir.SelectedPath; textBox1.Text = dlgOpenDir.SelectedPath; // Text of textBox2 = Path of fileSystemWatcher2 fileSystemWatcher1.EnableRaisingEvents = true; // Begin watching } } //2nd directory private void button3_Click(object sender, EventArgs e) { if (dlgOpenDir.ShowDialog() == DialogResult.OK) { fileSystemWatcher2.EnableRaisingEvents = false; // Stop watching fileSystemWatcher2.IncludeSubdirectories = true; fileSystemWatcher2.Path = dlgOpenDir.SelectedPath; textBox2.Text = dlgOpenDir.SelectedPath; // Text of textBox2 = Path of fileSystemWatcher2 fileSystemWatcher2.EnableRaisingEvents = true; // Begin watching } } //log private void button1_Click(object sender, EventArgs e) { DialogResult resDialog = dlgSaveFile.ShowDialog(); if (resDialog.ToString() == "OK") { FileInfo fi = new FileInfo(dlgSaveFile.FileName); StreamWriter sw = fi.CreateText(); foreach (string sItem in listBox1.Items) { sw.WriteLine(sItem); } sw.Close(); } } //pause watching private void pause_button_Click(object sender, EventArgs e) { if (!pause) { pause = true; pause_button.Text = "Unpause"; } else { pause = false; pause_button.Text = "Pause Watching"; } } //clear listbox private void clear_button_Click(object sender, EventArgs e) { listBox1.Items.Clear(); } private void Transfer_Click(object sender, EventArgs e) { if (copy1) { File.Copy(FileBrowseBox.Text, Path.Combine(DestinationBox.Text, Path.ChangeExtension(FileNameBox.Text, Path.GetExtension(FileBrowseBox.Text)))); } } private void Browse_file_Click(object sender, EventArgs e) { DialogResult resDialog = openFileDialog1.ShowDialog(); if (resDialog == DialogResult.OK) { FileBrowseBox.Text = openFileDialog1.FileName; } } private void Browse_destination_Click(object sender, EventArgs e) { DialogResult resDialog = folderBrowserDialog1.ShowDialog(); if (resDialog == DialogResult.OK) { DestinationBox.Text = folderBrowserDialog1.SelectedPath; } } private void CopyButton_CheckedChanged(object sender, EventArgs e) { copy1 = true; } } } </code></pre> <p>It says the problem is within this part:</p> <pre><code> File.Copy(FileBrowseBox.Text, Path.Combine(DestinationBox.Text, Path.ChangeExtension(FileNameBox.Text, Path.GetExtension(FileBrowseBox.Text)))); </code></pre> <p>I have tried to find it on this forum but i couldn't really find the answer or solution</p> <p>It does work with this code:</p> <pre><code>using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private bool cut = false; private bool copy = false; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { File.Copy(FileBrowseBox.Text, Path.Combine(DestinationBox.Text, Path.ChangeExtension(FileBox.Text, Path.GetExtension(FileBrowseBox.Text)))); label2.Text = "File Transfer Succeeded"; } private void button2_Click(object sender, EventArgs e) { DialogResult resDialog = openFileDialog1.ShowDialog(); if (resDialog == DialogResult.OK) { FileBrowseBox.Text = openFileDialog1.FileName; label2.Text = ""; } } private void button3_Click(object sender, EventArgs e) { DialogResult resDialog = folderBrowserDialog1.ShowDialog(); if (resDialog == DialogResult.OK) { DestinationBox.Text = folderBrowserDialog1.SelectedPath; label2.Text = ""; } } private void radioButton1_CheckedChanged(object sender, EventArgs e) { copy = true; } private void radioButton2_CheckedChanged(object sender, EventArgs e) { cut = true; } } } </code></pre>
17,023,571
5
0
null
2013-06-10 12:09:37.873 UTC
null
2017-10-30 23:30:43.24 UTC
2013-12-04 15:26:19.4 UTC
null
2,459,641
null
2,459,641
null
1
10
c#|.net|winforms
46,751
<p>You're getting this error because you have a label named <code>File</code> on your form that's being referenced rather than <code>System.IO.File</code>. You can either rename the <code>Label</code>, which I'd recommend, or you can use the fully qualified path of <code>System.IO.File.Copy</code> instead.</p>
12,562,506
NSParagraphStyle line spacing ignored
<p>A simple test that is failed: Make a new project with just one subview (UITextView) and put the following in:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineHeightMultiple = 50.f; paragraphStyle.lineSpacing = 100.f; paragraphStyle.minimumLineHeight = 200.f; paragraphStyle.maximumLineHeight = 500.f; UIFont *font = [UIFont fontWithName:@"AmericanTypewriter" size:24.f]; self.textView.attributedText = [[NSAttributedString alloc] initWithString: @"This is a test.\n Will I pass?" attributes: @{NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName : font}]; } </code></pre> <p>Line spacing is the same as if the attribute were not there. Has anything got this to work successfully? I put in ridiculous numbers just to show that it won't change...</p>
13,903,361
6
2
null
2012-09-24 09:46:17.48 UTC
13
2014-12-23 18:57:27.893 UTC
null
null
null
null
1,155,387
null
1
24
objective-c|uitextview|ios6|nsattributedstring
41,530
<p>This is a bug in NSHTMLWriter which is the private class which UITextView uses to convert attributedText into HTML. Internally it displays this HTML via a UIWebDocumentView. Read more on the inner workings of UITextView in my writeup here: <a href="http://www.cocoanetics.com/2012/12/uitextview-caught-with-trousers-down/">http://www.cocoanetics.com/2012/12/uitextview-caught-with-trousers-down/</a></p> <p>The problem comes from an easy to miss speciality in the font CSS shorthand. If you specify a pixel size with the font shorthand then this sets BOTH the font-size as well as the line-height. Since NSHTMLWriter puts the font AFTER the line-height this causes the line-height to be cancelled out by the font size.</p> <p>See here for my Radar which includes the full analysis of the bug: <a href="http://www.cocoanetics.com/2012/12/radar-uitextview-ignores-minimummaximum-line-height-in-attributed-string/">http://www.cocoanetics.com/2012/12/radar-uitextview-ignores-minimummaximum-line-height-in-attributed-string/</a></p> <p>I suggest you file a bug report as well and mention my Radar #12863734.</p>
12,630,827
Using .Net 4.5 Async Feature for Socket Programming
<p>I've previously used <code>BeginAccept()</code> and <code>BeginRead()</code>, but with Visual Studio 2012 I want to make use of the new asynchronous (<code>async</code>, <code>await</code>) features in my socket server program.</p> <p>How can I complete the <code>AcceptAsync</code> and <code>ReceiveAsync</code> functions?</p> <pre><code>using System.Net; using System.Net.Sockets; namespace OfficialServer.Core.Server { public abstract class CoreServer { private const int ListenLength = 500; private const int ReceiveTimeOut = 30000; private const int SendTimeOut = 30000; private readonly Socket _socket; protected CoreServer(int port, string ip = "0.0.0.0") { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Bind(new IPEndPoint(IPAddress.Parse(ip), port)); _socket.Listen(ListenLength); _socket.ReceiveTimeout = ReceiveTimeOut; _socket.SendTimeout = SendTimeOut; _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); } public void Start() { } } } </code></pre>
12,631,467
2
1
null
2012-09-27 22:16:07.007 UTC
38
2020-06-23 14:32:56.653 UTC
2013-06-18 21:34:53.763 UTC
null
23,199
null
1,666,700
null
1
42
c#|sockets|.net-4.5
47,535
<p>...because you're so determined, I put together a very simple example of how to write an echo server to get you on your way. Anything received gets echoed back to the client. The server will stay running for 60s. Try telnetting to it on localhost port 6666. Take time to understand exactly what's going on here.</p> <pre><code>void Main() { CancellationTokenSource cts = new CancellationTokenSource(); TcpListener listener = new TcpListener(IPAddress.Any, 6666); try { listener.Start(); //just fire and forget. We break from the "forgotten" async loops //in AcceptClientsAsync using a CancellationToken from `cts` AcceptClientsAsync(listener, cts.Token); Thread.Sleep(60000); //block here to hold open the server } finally { cts.Cancel(); listener.Stop(); } } async Task AcceptClientsAsync(TcpListener listener, CancellationToken ct) { var clientCounter = 0; while (!ct.IsCancellationRequested) { TcpClient client = await listener.AcceptTcpClientAsync() .ConfigureAwait(false); clientCounter++; //once again, just fire and forget, and use the CancellationToken //to signal to the "forgotten" async invocation. EchoAsync(client, clientCounter, ct); } } async Task EchoAsync(TcpClient client, int clientIndex, CancellationToken ct) { Console.WriteLine("New client ({0}) connected", clientIndex); using (client) { var buf = new byte[4096]; var stream = client.GetStream(); while (!ct.IsCancellationRequested) { //under some circumstances, it's not possible to detect //a client disconnecting if there's no data being sent //so it's a good idea to give them a timeout to ensure that //we clean them up. var timeoutTask = Task.Delay(TimeSpan.FromSeconds(15)); var amountReadTask = stream.ReadAsync(buf, 0, buf.Length, ct); var completedTask = await Task.WhenAny(timeoutTask, amountReadTask) .ConfigureAwait(false); if (completedTask == timeoutTask) { var msg = Encoding.ASCII.GetBytes("Client timed out"); await stream.WriteAsync(msg, 0, msg.Length); break; } //now we know that the amountTask is complete so //we can ask for its Result without blocking var amountRead = amountReadTask.Result; if (amountRead == 0) break; //end of stream. await stream.WriteAsync(buf, 0, amountRead, ct) .ConfigureAwait(false); } } Console.WriteLine("Client ({0}) disconnected", clientIndex); } </code></pre>
12,048,273
Selecting second children of first div children in javascript
<p>I have an html that look something like this:</p> <pre><code>&lt;div id="mainDiv"&gt; &lt;-- I have this &lt;div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;-- I need to get this &lt;/div&gt; &lt;span&gt;&lt;/span&gt; &lt;more stuff /&gt; &lt;/div&gt; </code></pre> <p>i am using:</p> <pre><code>var mainDiv = document.getElementById('mainDiv'); </code></pre> <p>because I need that div in a var, but i also need to get that second div on the first div inside mainDiv into a variable. </p> <p>How could I do it in a simple cross-browser way?</p>
12,048,299
6
0
null
2012-08-21 03:59:35.307 UTC
9
2019-03-23 13:07:50.193 UTC
null
null
null
null
1,186,827
null
1
45
javascript|html|parent-child|getelementbyid
123,056
<p>Assuming that structure is static you can do this:</p> <pre><code>var mainDiv = document.getElementById('mainDiv'), childDiv = mainDiv.getElementsByTagName('div')[0], requiredDiv = childDiv.getElementsByTagName('div')[1]; </code></pre> <p>Further reading: <a href="https://developer.mozilla.org/en-US/docs/DOM/element.getElementsByTagName" rel="noreferrer"><code>.getElementsByTagName()</code> (from MDN)</a>.</p>
12,101,508
Accessing the query string in ASP.Net Web Api?
<p>I'm using the default template generated by Asp.net Web Api. I'm working with the Get() Part:</p> <pre><code> // GET api/values public IEnumerable&lt;string&gt; Get() { return new string[] { "value1", "value2" }; } </code></pre> <p>For some reason the i thought the only thing you had to do to access to query string was just to create an input string variable. So i created one more function (the only change i made) to the default controller generated:</p> <pre><code> public IEnumerable&lt;string&gt; Get(string queryString) { return new string[] { "value3", "value4" }; } </code></pre> <p>I put a break point in both methods but even if i add a query string it always goes to the function with no parameters. So if i go to <code>http://mybaseurl/api/values?foo=f</code> it still is going to Get() instead of get(string queryString). Does it not work the way i thought? I know i can access the query string in the Get() function using <code>Request.RequestUri.ParseQueryString();</code> but i prefer to have it separated like this if possible.</p>
12,102,847
3
0
null
2012-08-23 23:48:02.007 UTC
9
2020-05-01 11:48:17.733 UTC
null
null
null
null
127,954
null
1
59
routing|query-string|asp.net-web-api
70,380
<p>The query string key name should match the parameter name of the action: </p> <p>/api/values?<strong>queryString=f</strong></p> <pre><code>public IEnumerable&lt;string&gt; Get(string queryString) { return new string[] { "value3", "value4" }; } </code></pre>
12,499,171
Can I set a header with python's SimpleHTTPServer?
<p>I'm using <code>SimpleHTTPServer</code> to test some webpages I'm working on. It works great, however I need to do some cross-domain requests. That requires setting a <code>Access-Control-Allow-Origin</code> header with the domains the page is allowed to access.</p> <p>Is there an easy way to set a header with SimpleHTTPServer and serve the original content? The header would be the same on each request.</p>
13,354,482
4
0
null
2012-09-19 16:42:39.26 UTC
9
2021-04-27 14:53:18.52 UTC
2012-09-19 17:34:42.38 UTC
null
373,446
null
373,446
null
1
63
python|cross-domain|simplehttpserver
41,327
<p>This is a bit of a hack because it changes <code>end_headers()</code> behavior, but I think it's slightly better than copying and pasting the entire <code>SimpleHTTPServer.py</code> file.</p> <p>My approach overrides <code>end_headers()</code> in a subclass and in it calls <code>send_my_headers()</code> followed by calling the superclass's <code>end_headers()</code>.</p> <p>It's not 1 - 2 lines either, less than 20 though; mostly boilerplate.</p> <pre><code>#!/usr/bin/env python try: from http import server # Python 3 except ImportError: import SimpleHTTPServer as server # Python 2 class MyHTTPRequestHandler(server.SimpleHTTPRequestHandler): def end_headers(self): self.send_my_headers() server.SimpleHTTPRequestHandler.end_headers(self) def send_my_headers(self): self.send_header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;) if __name__ == '__main__': server.test(HandlerClass=MyHTTPRequestHandler) </code></pre>
12,400,243
What is the correct way to write to temp file during unit tests with Maven?
<p>I have written a unit test that writes a file to the file-system, given no path it writes to the working directory; so if executed from the project directory it writes in the project root, if in the projects parent directory it writes to the parents root directory.</p> <p>So what is the correct way to write to the target directory? Quite possibly a directory inside the target directory?</p> <p>If I quite simply specify <code>target/</code> with the file it will write to the parent projects target instead of the projects target.</p> <p><strong>UPDATE</strong>: I actually want the file after the test finishes. The file is for an extraction format for third-parties that needs to be sent to the third parties. The test can be switched on/off to allow me to only run if the format of the file changes for re-approval. It's not a huge problem where the file goes, but I would like something that's easy to find.</p>
12,400,605
7
0
null
2012-09-13 05:59:17.45 UTC
15
2022-05-20 11:26:03.82 UTC
2012-09-13 06:40:17.82 UTC
null
140,037
null
140,037
null
1
77
java|maven|junit4
83,018
<p>You could try to use <a href="http://junit.org/junit4/javadoc/latest/org/junit/rules/TemporaryFolder.html" rel="noreferrer">TemporaryFolder</a> JUnit @Rule as described <a href="http://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/" rel="noreferrer">here</a></p> <blockquote> <p>The <a href="http://junit.org/junit4/javadoc/latest/org/junit/rules/TemporaryFolder.html" rel="noreferrer">TemporaryFolder</a> creates a folder in the default temporary file directory specified by the system property java.io.tmpdir. The method newFile creates a new file in the temporary directory and newFolder creates a new folder.</p> <p>When the test method finishes, JUnit automatically deletes all files and directories in and including the TemporaryFolder. JUnit guarantees to delete the resources, whether the test passes or fails.</p> </blockquote> <hr /> <p><strong>After Question Updated</strong></p> <p>You can change the working directory used by <a href="http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html#workingDirectory" rel="noreferrer"><code>maven-surefire-plugin</code></a>.</p> <pre><code>&lt;plugins&gt; [...] &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.12.3&lt;/version&gt; &lt;configuration&gt; &lt;workingDirectory&gt;${project.build.directory}&lt;/workingDirectory&gt; &lt;/configuration&gt; &lt;/plugin&gt; [...] &lt;/plugins&gt; </code></pre> <p>You can change that working directory to anything you need for your tests like <code>${project.build.directory}/my_special_dir/</code>.</p> <p>The working directory in surefire plugin only affects tests being run and ONLY for tests being conducted by maven. If you run your tests from within an IDE the working directory will be something else.</p>
12,608,242
Latest jQuery version on Google's CDN
<p>I read in the <a href="https://developers.google.com/speed/libraries/devguide#jquery" rel="noreferrer">official doc</a> of the Google CDN that this is the <code>src</code> to jQuery: </p> <pre><code>&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"&gt;&lt;/script&gt; </code></pre> <p>However, it is annoying to have to change my jQuery <code>src</code> reference at each version update. </p> <p>I've found that if I set the version to <code>1</code> then Google returns the latest version of jQuery.</p> <pre><code>http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js /*! jQuery v1.8.2 jquery.com | jquery.org/license */ </code></pre> <p>Is this the right thing to do? Is there any official URL to reference the latest version of jQuery hosted on the Google CDN?</p>
12,608,285
4
1
null
2012-09-26 18:36:21.9 UTC
35
2017-11-20 18:21:37.523 UTC
2015-12-03 18:52:56.803 UTC
null
1,709,587
null
356,042
null
1
103
jquery|google-cdn
219,275
<p><strong>UPDATE 7/3/2014:</strong> As of now, <code>jquery-latest.js</code> is no longer being updated. From the <a href="http://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/">jQuery blog</a>:</p> <blockquote> <p>We know that <a href="http://code.jquery.com/jquery-latest.js">http://code.jquery.com/jquery-latest.js</a> is abused because of the CDN statistics showing it’s the most popular file. That wouldn’t be the case if it was only being used by developers to make a local copy.</p> <p>We have decided to stop updating this file, as well as the minified copy, keeping both files at version 1.11.1 forever.</p> <p>The Google CDN team has joined us in this effort to prevent inadvertent web breakage and no longer updates the file at <a href="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js">http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js</a>. That file will stay locked at version 1.11.1 as well.</p> </blockquote> <p>The following, now moot, answer is preserved here for historical reasons.</p> <hr> <p><a href="http://webcache.googleusercontent.com/search?q=cache:http://www.impressivewebs.com/linking-to-jquery/">Don't do this. Seriously, don't.</a></p> <p>Linking to major versions of jQuery does work, but it's a bad idea -- whole new features get added and deprecated with each decimal update. If you update jQuery automatically without testing your code <strong>COMPLETELY</strong>, you risk an unexpected surprise if the API for some critical method has changed.</p> <p>Here's what you should be doing: write your code using the latest version of jQuery. Test it, debug it, publish it when it's ready for production. </p> <p>Then, when a new version of jQuery rolls out, ask yourself: <strong>Do I need this new version in my code?</strong> For instance, is there some critical browser compatibility that didn't exist before, or will it speed up my code in most browsers? </p> <p>If the answer is "no", don't bother updating your code to the latest jQuery version. <a href="http://jquery.com/upgrade-guide/1.9/">Doing so might even add NEW errors to your code which didn't exist before</a>. No responsible developer would automatically include new code from another site without testing it thoroughly.</p> <p>There's simply no good reason to ALWAYS be using the latest version of jQuery. The old versions are still available on the CDNs, and if they work for your purposes, then why bother replacing them?</p> <hr> <p>A secondary, but possibly more important, issue is caching. Many people link to jQuery on a CDN because many other sites do, and your users have a good chance of having that version already cached.</p> <p>The problem is, <a href="http://www.bucketsoft.com/blog/post/maximize-your-chances-of-caching-your">caching only works if you provide a full version number</a>. If you provide a partial version number, far-future caching doesn't happen -- because if it did, some users would get different minor versions of jQuery from the same URL. (Say that the link to 1.7 points to 1.7.1 one day and 1.7.2 the next day. How will the browser make sure it's getting the latest version today? Answer: no caching.)</p> <blockquote> <p>In fact <a href="http://www.bucketsoft.com/blog/post/maximize-your-chances-of-caching-your">here's a breakdown</a> of several options and their expiration settings...</p> <p><a href="http://code.jquery.com/jquery-latest.min.js">http://code.jquery.com/jquery-latest.min.js</a> (no cache)</p> <p><a href="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js</a> (1 hour)</p> <p><a href="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js">http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js</a> (1 hour)</p> <p><a href="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js</a> (1 year)</p> </blockquote> <p>So, by linking to jQuery this way, you're actually <strong>eliminating</strong> one of the major reasons to use a CDN in the first place.</p> <hr> <p><a href="http://code.jquery.com/jquery-latest.min.js">http://code.jquery.com/jquery-latest.min.js</a> may not always give you the version you expect, either. As of this writing, it links to the latest version of jQuery 1.x, even though jQuery 2.x has been released as well. This is because jQuery 1.x is compatible with older browsers including IE 6/7/8, and <a href="http://blog.jquery.com/2013/04/18/jquery-2-0-released/">jQuery 2.x is not</a>. If you want the latest version of jQuery 2.x, then (for now) you need to specify that explicitly.</p> <p>The two versions have the same API, so there is no perceptual difference for compatible browsers. However, jQuery 1.x is a larger download than 2.x.</p>
19,081,701
iOS 7 UIImagePickerController has black preview
<p>I have a UIImagePickerController being called with sourceType camera and 80% of the time I get a black preview. If I wait, let's say around 30 seconds, I get a good preview and it will be good for around 50% of the time, then it can break again.</p> <p>The image in question is very similar to this. <a href="https://stackoverflow.com/questions/16746839/idevice-camera-shows-black-instead-of-preview">iDevice camera shows black instead of preview</a></p> <p>Other people imply that GCD might be causing some issues with the camera, and that updates to the UI while the image picker is being loaded break it. I put a lock on every GCD block that calls the main thread for this purpose.</p> <p>This is an example of an image that rotates to simulate an activity indicator.</p> <pre><code>-(void)animateLoadingImage { if (isMainThreadBlocked) { return; } self.radians += M_PI_4 / 2; [UIView beginAnimations:@"progress rotation" context:nil]; [UIView setAnimationDuration:.1]; self.loadingImageView.transform = CGAffineTransformMakeRotation(self.radians); [UIView commitAnimations]; } </code></pre> <p>PS: Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates.</p> <p>This shows ALWAYS when I try to open the picker controller, but it shows it even if the camera shows the preview correctly. I don't think the error is around here but this bugs me a lot also.</p>
19,970,479
7
4
null
2013-09-29 18:29:25.52 UTC
10
2016-03-22 10:59:33.747 UTC
2017-05-23 10:28:40.62 UTC
null
-1
null
2,059,170
null
1
21
iphone|uiimagepickercontroller|ios7
11,225
<p>There doesn't seem to be a good answer to this anywhere online, so I had to slog through this myself to figure it out.</p> <p>I'm using ARC (like probably most others these days), so the answer above didn't really help me.</p> <p>This black camera issue happens as a side effect of doing UIKit stuff off of the main thread on iOS 7. Broadly, background UIKit operations results in all sorts of weird things happening on iOS 7 (memory not being deallocated promptly, weird performance hitches, and the black camera issue).</p> <p>To prevent this, you need to not do ANY UIKit stuff on background threads. </p> <p>Things you cannot do on background threads: - Allocate/initialize UIViews and subclasses - Modify UIViews and subclasses (e.g., setting frame, setting .image/.text attributes, etc).</p> <p>Now, the problem with doing this stuff on the main thread is that it can mess with UI performance, which is why you see all these iOS 6 "background loading" solutions that DO NOT work optimally on iOS 7 (i.e., causing the black camera issue, among other things).</p> <p>There are two things that I did to fix performance while preventing the ill effects of background UIKit operations: - Pre-create and initialize all UIImages on a background thread. The only thing you should be doing with UIImages on the main thread is setting "imageView.image = preloadedImageObject;" - Re-use views whenever possible. Doing [[UIView alloc] init] on the main thread can still be problematic if you're doing it in a cellForRowAtIndex or in another situation where responsiveness is super important.</p> <p>Best of luck! You can test how you're doing by monitoring memory usage while your app is running. Background UIKit => rapidly escalating memory usage.</p>
3,652,560
What is the Android UiThread (UI thread)
<p>Can someone explain to me what exactly the UI thread is? On developer.android.com it says about the runOnUiThread function</p> <blockquote> <p>public final void runOnUiThread (Runnable action)</p> <p>Since: API Level 1 Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.</p> </blockquote> <p>Does the UI thread mean that this will be run everytime the activity is pushed the the background by some ui activity like incoming call or screen dimming etc.? If not, what exactly does the UI thread include ?</p> <p>Thank you</p>
3,653,478
3
0
null
2010-09-06 15:20:33.803 UTC
38
2019-08-06 20:33:41.94 UTC
2011-09-27 15:42:21.483 UTC
null
194,894
null
434,885
null
1
90
android|ui-thread
86,899
<p>The UIThread is the main thread of execution for your application. This is where most of your application code is run. All of your application components (Activities, Services, ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to those components are performed in this thread.</p> <p>For instance, let's say your application is a single Activity class. Then all of the lifecycle methods and most of your event handling code is run in this UIThread. These are methods like <code>onCreate</code>, <code>onPause</code>, <code>onDestroy</code>, <code>onClick</code>, etc. Additionally, this is where all of the updates to the UI are made. Anything that causes the UI to be updated or changed HAS to happen on the UI thread. </p> <p><a href="http://developer.android.com/guide/components/processes-and-threads.html" rel="noreferrer">For more info on your application's Processes and Threads click here.</a></p> <p>When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread. So what happens if this background thread needs to do something that changes the UI? This is what the <code>runOnUiThread</code> is for. Actually you're supposed to use a Handler (see the link below for more info on this). It provides these background threads the ability to execute code that can modify the UI. They do this by putting the UI-modifying code in a Runnable object and passing it to the runOnUiThread method.</p> <p><a href="http://developer.android.com/guide/components/processes-and-threads.html#WorkerThreads" rel="noreferrer">For more info on spawning worker threads and updating the UI from them click here</a></p> <p>I personally only use the <code>runOnUiThread</code> method in my Instrumentation Tests. Since the test code does not execute in the UIThread, you need to use this method to run code that modifies the UI. So, I use it to inject click and key events into my application. I can then check the state of the application to make sure the correct things happened.</p> <p><a href="http://developer.android.com/tools/testing/activity_testing.html#RunOnUIThread" rel="noreferrer">For more info on testing and running code on the UIThread click here</a></p>
8,714,250
Isn't "const" redundant when passing by value?
<p>I was reading my C++ book (Deitel) when I came across a function to calculate the volume of a cube. The code is the following:</p> <pre><code>double cube (const double side){ return side * side * side; } </code></pre> <p>The explanation for using the "const" qualifier was this one: "The const qualified should be used to enforce the principle of least privilege, telling the compiler that the function does not modify variable side".</p> <p><strong>My question</strong>: isn't the use of "const" redundant/unnecessary here since the variable is being passed by value, so the function can't modify it anyway?</p>
8,714,278
2
6
null
2012-01-03 15:06:11.46 UTC
13
2015-09-20 09:46:55.72 UTC
2012-01-03 15:16:00.063 UTC
null
476,681
null
799,779
null
1
94
c++|constants|pass-by-value
25,005
<p>The <code>const</code> qualifier prevents code inside the function from modifying the parameter itself. When a function is larger than trivial size, such an assurance helps you to quickly read and understand a function. If you know that the value of <code>side</code> won't change, then you don't have to worry about keeping track of its value over time as you read. Under some circumstances, this might even help the compiler generate better code.</p> <p>A non-trivial number of people do this as a matter of course, considering it generally good style.</p>
43,812,733
What does this warning message mean? 'img elements must have an alt prop, either with meaningful text, or an empty string for decorative images'
<p>Why am I getting this warning?</p> <blockquote> warning: img elements must have an alt prop, either with meaningful text, or an empty string for decorative images jsx-a11y/img-has-alt </blockquote> <p>It's showing line number 13 but there is nothing props is using.</p>
43,812,823
12
6
null
2017-05-05 19:46:51.743 UTC
6
2022-05-02 06:27:58.66 UTC
null
null
null
user7904085
null
null
1
44
javascript|reactjs
101,014
<p>Images should have an alt property. The alternate property comes into picture in several cases like the card not getting downloaded, incompatible browsers, or the image getting corrupt. You need to pass in a prop called alt to the image. </p> <p>Also, Alt tag is used by screen readers for visually impaired. Therefore it is considered as a good practice to always add a ALT tag to the image component. <a href="http://accessibility.psu.edu/images/imageshtml/" rel="noreferrer">Accessibility</a></p>
10,876,079
org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
<p>Here I want to display the JSON content using API key. But I am unable to get the authentication.</p> <p>I am getting the error in JsonObject:</p> <pre><code>org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONObject </code></pre> <p>In my android application, I just pass the API key and URL id to get the JSON response in the following URL. I display the JSON content using JSON array. </p> <p>But if I: </p> <pre><code>public class AndroidAPiActivity extends Activity { /* * FlickrQuery = FlickrQuery_url * + FlickrQuery_per_page * + FlickrQuery_nojsoncallback * + FlickrQuery_format * + FlickrQuery_tag + q * + FlickrQuery_key + FlickrApiKey */ String FlickrQuery_url = "http://192.138.11.9/api/interests/"; String FlickrQuery_per_page = "&amp;per_page=1"; String FlickrQuery_nojsoncallback = "&amp;nojsoncallback=1"; String FlickrQuery_format = "&amp;format=json"; String FlickrQuery_tag = "&amp;tags="; String FlickrQuery_key = "&amp;api_key="; // Apply your Flickr API: // www.flickr.com/services/apps/create/apply/? String FlickrApiKey = "f65215602df8f8af"; EditText searchText; Button searchButton; TextView textQueryResult, textJsonResult; ImageView imageFlickrPhoto; Bitmap bmFlickr; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); searchText = (EditText)findViewById(R.id.searchtext); searchButton = (Button)findViewById(R.id.searchbutton); textQueryResult = (TextView)findViewById(R.id.queryresult); textJsonResult = (TextView)findViewById(R.id.jsonresult); imageFlickrPhoto = (ImageView)findViewById(R.id.flickrPhoto); searchButton.setOnClickListener(searchButtonOnClickListener); } private Button.OnClickListener searchButtonOnClickListener = new Button.OnClickListener(){ public void onClick(View arg0) { // TODO Auto-generated method stub String searchQ = searchText.getText().toString(); String searchResult = QueryFlickr(searchQ); textQueryResult.setText(searchResult); String jsonResult = ParseJSON(searchResult); textJsonResult.setText(jsonResult); if (bmFlickr != null){ imageFlickrPhoto.setImageBitmap(bmFlickr); } }}; private String QueryFlickr(String q){ String qResult = null; String qString = FlickrQuery_url + FlickrQuery_per_page + FlickrQuery_nojsoncallback + FlickrQuery_format + FlickrQuery_tag + q + FlickrQuery_key + FlickrApiKey; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(qString); try { HttpEntity httpEntity = httpClient.execute(httpGet).getEntity(); if (httpEntity != null){ InputStream inputStream = httpEntity.getContent(); Reader in = new InputStreamReader(inputStream); BufferedReader bufferedreader = new BufferedReader(in); StringBuilder stringBuilder = new StringBuilder(); String stringReadLine = null; while ((stringReadLine = bufferedreader.readLine()) != null) { stringBuilder.append(stringReadLine + "\n"); } qResult = stringBuilder.toString(); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return qResult; } private String ParseJSON(String json){ String jResult = null; bmFlickr = null; String key_id; String category; String subcategory; String title; String icon_image; try { JSONObject JsonObject = new JSONObject(json); JSONObject Json_photos = JsonObject.getJSONObject("interests"); JSONArray JsonArray_photo = Json_photos.getJSONArray("interest"); //We have only one photo in this exercise JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(0); key_id = FlickrPhoto.getString("row_key"); category = FlickrPhoto.getString("category"); subcategory = FlickrPhoto.getString("subcategory"); title = FlickrPhoto.getString("title"); jResult = "\n key_id: " + key_id + "\n" + "category: " + category + "\n" + "subcategory: " + subcategory + "\n" + "title: " + title + "\n"; bmFlickr = LoadPhotoFromFlickr(key_id, category, subcategory,title); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jResult; } private Bitmap LoadPhotoFromFlickr( String key_id, String category, String subcategory, String title){ Bitmap bm= null; String icon_image = null; // String FlickrPhotoPath =""; String FlickrPhotoPath ="http://182.72.180.34/media/"+icon_image+".jpg"; URL FlickrPhotoUrl = null; try { FlickrPhotoUrl = new URL(FlickrPhotoPath); HttpURLConnection httpConnection = (HttpURLConnection) FlickrPhotoUrl.openConnection(); httpConnection.setDoInput(true); httpConnection.connect(); InputStream inputStream = httpConnection.getInputStream(); bm = BitmapFactory.decodeStream(inputStream); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bm; } } </code></pre>
10,876,576
6
2
null
2012-06-04 03:41:51.957 UTC
1
2021-08-08 09:30:47.913 UTC
2012-06-04 23:15:35.84 UTC
null
275,567
null
1,284,989
null
1
9
android|json|api|authentication
52,494
<h2>Update:</h2> <p>Based on the HTML response, I can tell you that this is not JSON. The response tells me that you have the incorrect URL for your web service.</p> <p>You need to check your URL.</p> <h2>Extra Info / Previous Answer:</h2> <p>It looks like the simple answer is the right one - your result is not a valid JSON string. See <a href="http://www.json.org/" rel="noreferrer">JSON.org</a> website for details on what JSON should look like.</p> <p>Check out <a href="http://json.parser.online.fr/" rel="noreferrer">JSON Parser Online</a> - I find its very useful when working with JSON.</p> <p>It is strange that you are requesting JSON, and it is not returning it properly - perhaps I have missed something.</p>
10,931,423
using dictConfig in python logging, need to create a logger with a different file than defined in dict.
<p>I have a LOG_SETTINGS dict that looks like:</p> <pre><code>LOG_SETTINGS = { 'version': 1, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter': 'detailed', 'stream': 'ext://sys.stdout', }, 'file': { 'class': 'logging.handlers.RotatingFileHandler', 'level': 'INFO', 'formatter': 'detailed', 'filename': '/tmp/junk.log', 'mode': 'a', 'maxBytes': 10485760, 'backupCount': 5, }, }, 'formatters': { 'detailed': { 'format': '%(asctime)s %(module)-17s line:%(lineno)-4d ' \ '%(levelname)-8s %(message)s', }, 'email': { 'format': 'Timestamp: %(asctime)s\nModule: %(module)s\n' \ 'Line: %(lineno)d\nMessage: %(message)s', }, }, 'loggers': { 'extensive': { 'level':'DEBUG', 'handlers': ['file',] }, } } </code></pre> <p>In my code I do the following:</p> <pre><code>logging.config.dictConfig(LOG_SETTINGS) logger = logging.getLogger('extensive') logger.info("This is from Runner {0}".format(self.default_name)) logger2 = logging.getLogger('extensive') logfile = logging.FileHandler("test.log") logger2.addHandler(logfile) logger2.info("This is from Runner {0} to the new file.".format(self.default_name)) </code></pre> <p>But the output is still written to the original log file defined in LOG_SETTINGS. What I am looking for is to have the ability to say: logger2.replaceHandler(logfile) rather than addHandler.</p> <p>Is there a way to do this?</p>
10,931,747
1
0
null
2012-06-07 12:05:15.87 UTC
9
2012-06-07 12:24:42.51 UTC
null
null
null
null
528,729
null
1
19
python|logging
19,210
<p>firstly, empty your logger handlers <code>logger.handlers = []</code> then add another handler.</p> <pre><code>logger2 = logging.getLogger('extensive') logfile = logging.FileHandler("test.log") logger2.handlers = [] logger2.addHandler(logfile) </code></pre>
11,414,452
Is there a way to check if text is in cyrillics or latin using C#?
<p>Is there a way to check if text is in cyrillics or latin using C#?</p>
11,414,800
3
0
null
2012-07-10 13:32:45.563 UTC
6
2018-05-14 06:50:24.883 UTC
2018-03-19 05:45:39.11 UTC
null
1,033,581
null
1,101,596
null
1
28
c#
13,289
<p>Use a Regex and check for <code>\p{IsCyrillic}</code>, for example:</p> <pre><code>if (Regex.IsMatch(stringToCheck, @"\p{IsCyrillic}")) { // there is at least one cyrillic character in the string } </code></pre> <p>This would be true for the string "abcабв" because it contains at least one cyrillic character. If you want it to be false if there are non cyrillic characters in the string, use:</p> <pre><code>if (!Regex.IsMatch(stringToCheck, @"\P{IsCyrillic}")) { // there are only cyrillic characters in the string } </code></pre> <p>This would be false for the string "abcабв", but true for "абв".</p> <p>To check what the IsCyrillic named block or other named blocks contain, have a look at this <a href="http://msdn.microsoft.com/en-us/library/20bw873z.aspx#SupportedNamedBlocks">http://msdn.microsoft.com/en-us/library/20bw873z.aspx#SupportedNamedBlocks</a></p>
11,170,425
how to unit test file upload in django
<p>In my django app, I have a view which accomplishes file upload.The core snippet is like this</p> <pre><code>... if (request.method == 'POST'): if request.FILES.has_key('file'): file = request.FILES['file'] with open(settings.destfolder+'/%s' % file.name, 'wb+') as dest: for chunk in file.chunks(): dest.write(chunk) </code></pre> <p>I would like to unit test the view.I am planning to test the happy path as well as the fail path..ie,the case where the <code>request.FILES</code> has no key 'file' , case where <code>request.FILES['file']</code> has <code>None</code>..</p> <p>How do I set up the post data for the happy path?Can somebody tell me?</p>
11,170,472
14
1
null
2012-06-23 14:49:08.113 UTC
27
2022-02-09 13:56:58.273 UTC
null
null
null
null
1,291,096
null
1
128
django|unit-testing|file-upload
78,145
<p>From Django docs on <a href="https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.Client.post" rel="noreferrer"><code>Client.post</code></a>:</p> <blockquote> <p>Submitting files is a special case. To POST a file, you need only provide the file field name as a key, and a file handle to the file you wish to upload as a value. For example:</p> </blockquote> <pre><code>c = Client() with open('wishlist.doc') as fp: c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp}) </code></pre>
13,122,791
Rails: Validation in model vs migration
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2367281/ruby-on-rails-is-it-better-to-validate-in-the-model-or-the-database">Ruby on Rails: Is it better to validate in the model or the database?</a> </p> </blockquote> <p>I see that it's possible to add same constraint/validation in both Rails model and migration. But which one is the best approach? Is it a good practice to validate both at model and database level (and why)? or they same in rails? </p> <p>For e.g. We can do same validation for name in both model and migration</p> <pre class="lang-rb prettyprint-override"><code>class User &lt; ActiveRecord::Base validates :name, :uniqueness =&gt; true, :presence =&gt; true end class CreateUser &lt; ActiveRecord::Migration def change create_table :users do |t| t.string :name, :unique =&gt; true, :null =&gt; false end end end </code></pre>
13,123,347
1
1
null
2012-10-29 13:42:02.35 UTC
9
2015-12-31 14:41:46.22 UTC
2017-05-23 11:46:51.4 UTC
null
-1
null
471,324
null
1
15
ruby-on-rails|ruby|database|ruby-on-rails-3|validation
5,896
<p>Wherever possible, validate at the database level as well as at the model level.</p> <p>Why? For starters, active record does not enforce validation in all contexts. The following methods skip validations, and will save the object to the database regardless of its validity:</p> <pre><code>decrement! decrement_counter increment! increment_counter toggle! touch update_all update_attribute update_column update_counters </code></pre> <p>If you pass <code>:validate =&gt; false</code> to <code>save</code>, it will also skip validation. See the <a href="http://guides.rubyonrails.org/active_record_validations_callbacks.html#skipping-validations">Active Record Validations and Callbacks Guide</a> section on Skipping Validations for details. (If this worries you, there is even <a href="https://github.com/garybernhardt/do_not_want">a gem</a> for disabling these methods.)</p> <p>So <strong>reason #1</strong> is that Rails validations are not full-proof by any means: relying on them exclusively is risky, particularly for mission-critical validations such as uniqueness.</p> <p>Speaking of which, <strong>reason #2</strong> (off the top of my head): activerecord validations are prone to race conditions, and Rails' uniqueness validator in particular <em>cannot guarantee uniqueness</em>. Here's <a href="http://nhw.pl/wp/2009/07/20/are-activerecord-validations-worth-anything">one article</a> among many that documents why this is so.</p> <p>Although they may be a rare occurrence, violations of uniqueness constraints can corrupt an entire data set. In the rare case that Rails is about to do this, you want at all costs to stop it, which is where the DB uniqueness constraint comes in: databases are built to handle this situation and will enforce uniqueness consistently, even when Rails does not.</p> <p>And <strong>reason #3</strong>: why <em>not</em> validate both in the model and in the DB? Sure, you duplicate a bit, but that's generally a pretty minor concern compared with the payoff if Rails misses something like a uniqueness validation check. This is really not an either/or proposition: it's <em>always</em> better to duplicate validation in the DB wherever you can, particularly for mission-critical constraints such as uniqueness.</p> <p>Anyway, those are my thoughts, hope that helps.</p> <p>Ref: <a href="https://www.destroyallsoftware.com/screencasts/catalog/where-correctness-is-enforced">Where Correctness Is Enforced</a> (screencast by Gary Bernhardt, need subscription to view)</p>
13,159,184
Is there a way to add nodes to a running Hadoop cluster?
<p>I have been playing with Cloudera and I define the number of clusters before I start my job then use the cloudera manager to make sure everything is running. </p> <p>I’m working on a new project that instead of using hadoop is using message queues to distribute the work but the results of the work are stored in HBase. I might launch 10 servers to process the job and store to Hbase but I’m wondering if I later decided to add a few more worker nodes can I easily (read: programmable) make them automatically connect to the running cluster so they can locally add to clusters HBase/HDFS?</p> <p>Is this possible and what would I need to learn in order to do it?</p>
13,160,326
5
0
null
2012-10-31 13:32:27.34 UTC
9
2019-03-22 06:47:06.807 UTC
null
null
null
null
1,735,075
null
1
15
hadoop|cluster-computing|hbase|hdfs|cloudera
27,452
<p>Here is the documentation for adding a node to <a href="http://wiki.apache.org/hadoop/FAQ#I_have_a_new_node_I_want_to_add_to_a_running_Hadoop_cluster.3B_how_do_I_start_services_on_just_one_node.3F">Hadoop</a> and for <a href="http://wiki.apache.org/hadoop/Hbase/FAQ_Operations#A8">HBase</a>. Looking at the documentation, there is no need to restart the cluster. A node can be added dynamically.</p>
12,730,384
iOS UIImageView scaling image down produces aliased image on iPad 2
<p>I am using UIImageView to display thumbnails of images that can then be selected to be viewed at full size. The UIImageView has its content mode set to aspect fit.</p> <p>The images are usually scaled down from around 500px x 500px to 100px x 100px. On the retina iPad they display really well while on the iPad2 they are badly aliased until the size gets closer to the native image size.</p> <p>Examples:</p> <p><img src="https://i.stack.imgur.com/Kf2so.png" alt="Original Image"></p> <p>Original Image</p> <p><img src="https://i.stack.imgur.com/lTReY.png" alt="Retina iPad 100x100"></p> <p>Retina iPad rendering at 100px x 100px</p> <p><img src="https://i.stack.imgur.com/8WXWl.png" alt="iPad 2 100x100"></p> <p>iPad 2 rendering at 100px x 100px</p> <p>The difference between iPad 2 and new iPad might just be the screen resolution or could be that the GPU is better equipped to scale images. Either way, the iPad 2 rendering is very poor.</p> <p>I have tried first reducing the image size by creating a new context, setting the interpolation quality to high and drawing the image into the context. In this case, the image looks fine on both iPads.</p> <p>Before I continue down the image copy/resize avenue, I wanted to check there wasn't something simpler I was missing. I appreciate that UIImage isn't there to be scaled but I was under the impression UIImageView was there to handle scaling but at the moment it doesn't seem to be doing a good job scaling down. What (if anything) am I missing?</p> <p><strong>Update</strong>: Note: The drop shadow on the rendered / resized images is added in code. Disabling this made no difference to the quality of the scaling.</p>
12,742,944
5
3
null
2012-10-04 15:12:08.783 UTC
13
2019-05-29 14:51:00.653 UTC
null
null
null
null
1,110,246
null
1
42
objective-c|ios|ipad|uiimageview
16,223
<p>Another approach I've tried that does seem to be improving things is to set the minificationFilter:</p> <pre><code>[imageView.layer setMinificationFilter:kCAFilterTrilinear] </code></pre> <p>The quality is certainly improved and I haven't noticed a performance hit.</p>
12,784,338
Match specific length x or y
<p><em>I'd like a regex that is either X or Y characters long</em>. For example, match a string that is either 8 or 11 characters long. I have currently implemented this like so: <code>^([0-9]{8}|[0-9]{11})$</code>.</p> <p>I could also implement it as: <code>^[0-9]{8}([0-9]{3})?$</code></p> <p>My question is: <strong>Can I have this regex without duplicating the <code>[0-9]</code> part</strong> (which is more complex than this simple <code>\d</code> example)?</p>
12,784,477
3
0
null
2012-10-08 15:01:31.713 UTC
14
2018-02-06 10:37:56.227 UTC
null
null
null
null
540,352
null
1
45
regex
31,666
<p>There is one way:</p> <pre><code>^(?=[0-9]*$)(?:.{8}|.{11})$ </code></pre> <p>or alternatively, if you want to do the length check first,</p> <pre><code>^(?=(?:.{8}|.{11})$)[0-9]*$ </code></pre> <p>That way, you have the complicated part only once and a generic <code>.</code> for the length check.</p> <p><strong>Explanation:</strong></p> <pre><code>^ # Start of string (?= # Assert that the following regex can be matched here: [0-9]* # any number of digits (and nothing but digits) $ # until end of string ) # (End of lookahead) (?: # Match either .{8} # 8 characters | # or .{11} # 11 characters ) # (End of alternation) $ # End of string </code></pre>
16,951,267
How to get the path of a file relative to the Git repository root?
<p>Example:</p> <pre><code>$ cd lib $ git absolute-path test.c # how to do this? lib/test.c </code></pre>
16,951,268
4
1
null
2013-06-05 23:00:58.363 UTC
2
2022-08-05 11:43:26.43 UTC
2019-04-21 11:43:23.92 UTC
null
525,872
null
525,872
null
1
37
git|path
20,517
<p>Use <a href="https://www.git-scm.com/docs/git-ls-files" rel="nofollow noreferrer"><code>git ls-files</code></a>:</p> <pre><code>$ cd lib $ git ls-files --full-name test.c lib/test.c </code></pre> <p>This only works for files that have been committed into the repo, but it's better than nothing.</p>
16,877,968
Call a Server-side Method on a Resource in a RESTful Way
<p>Keep in mind I have a rudimentary understanding of REST. Let's say I have this URL:</p> <pre><code>http://api.animals.com/v1/dogs/1/ </code></pre> <p>And now, I want to make the server make the dog bark. Only the server knows how to do this. Let's say I want to have it run on a CRON job that makes the dog bark every 10 minutes for the rest of eternity. What does that call look like? I kind of want to do this:</p> <p>URL request:</p> <pre><code>ACTION http://api.animals.com/v1/dogs/1/ </code></pre> <p>In the request body:</p> <pre><code>{"action":"bark"} </code></pre> <p>Before you get mad at me for making up my own HTTP method, help me out and give me a better idea on how I should invoke a server-side method in a RESTful way. :)</p> <p><strong>EDIT FOR CLARIFICATION</strong></p> <p>Some more clarification around what the "bark" method does. Here are some options that may result in differently structured API calls:</p> <ol> <li>bark just sends an email to dog.email and records nothing.</li> <li>bark sends an email to dog.email and the increments dog.barkCount by 1.</li> <li>bark creates a new "bark" record with bark.timestamp recording when the bark occured. It also increments dog.barkCount by 1.</li> <li>bark runs a system command to pull the latest version of the dog code down from Github. It then sends a text message to dog.owner telling them that the new dog code is in production.</li> </ol>
16,878,494
8
6
null
2013-06-01 22:39:19.88 UTC
131
2022-01-19 14:12:57.303 UTC
2022-01-19 14:12:57.303 UTC
null
4,294,399
null
102,635
null
1
162
rest|url|api-design
72,738
<h2>Why aim for a RESTful design?</h2> <p>The RESTful principles <strong>bring the features that make web sites easy</strong> (for a <em>random human user</em> to &quot;surf&quot; them) <strong>to the web services API design</strong>, so they are easy for a programmer to use. <a href="http://www.tbray.org/ongoing/When/200x/2009/03/20/Rest-Casuistry" rel="noreferrer">REST isn't good because it's REST, it's good because it's good.</a> And it is good mostly because it is <strong>simple</strong>.</p> <p>The simplicity of plain HTTP (without SOAP envelopes and single-URI overloaded <code>POST</code> services), what <strong>some may call <em>&quot;lack of features&quot;</em></strong>, is actually <strong>its greatest strength</strong>. Right off the bat, HTTP asks you to have <em>addressability</em> and <em>statelessness</em>: the two basic design decisions that keep HTTP scalable up to today's mega-sites (and mega-services).</p> <p>But REST is not the silver bulltet: <strong>Sometimes an RPC-style</strong> (&quot;Remote Procedure Call&quot; - such as SOAP) <strong>may be appropriate</strong>, and sometimes other needs take precedence over the virtues of the Web. This is fine. What we don't really like <strong>is needless complexity</strong>. Too often a programmer or a company brings in RPC-style Services for a job that plain old HTTP could handle just fine. The effect is that HTTP is reduced to a transport protocol for an enormous XML payload that explains what's &quot;really&quot; going on (not the URI or the HTTP method give a clue about it). The resulting service is far too complex, impossible to debug, and won't work unless your clients have the <strong>exact setup</strong> as the developer intended.</p> <p>Same way a Java/C# code can be <em>not</em> object-oriented, just using HTTP does not make a design RESTful. One may be caught up in the rush of <strong>thinking</strong> about their services <strong>in terms of actions and remote methods</strong> that should be called. No wonder this will mostly end up in a RPC-Style service (or a REST-RPC-hybrid). The first step is to think differently. A RESTful design can be achieved in many ways, one way is to <strong>think of your application in terms of resources, not actions:</strong></p> <blockquote> <p> Instead of thinking in terms of actions it can perform (&quot;do a search for places on the map&quot;)...</p> <p>...try to think in terms of the <strong>results</strong> of those actions (&quot;the list of places on the map matching a search criteria&quot;).</p> </blockquote> <p>I'll go for examples below. (Other key aspect of REST is the use of HATEOAS - I don't brush it here, but I talk about it quickly <a href="https://stackoverflow.com/a/30607633/1850609">at another post</a>.)</p> <br> <h2>Issues of the first design</h2> <p>Let's take a look a the proposed design:</p> <pre><code>ACTION http://api.animals.com/v1/dogs/1/ </code></pre> <p>First off, we should not consider creating a <strong>new HTTP verb</strong> (<code>ACTION</code>). Generally speaking, this is <em>undesirable</em> for several reasons:</p> <ul> <li><strong>(1)</strong> Given only the service URI, how will a &quot;random&quot; programmer know the <code>ACTION</code> verb exists?</li> <li><strong>(2)</strong> if the programmer knows it exists, how will he know its semantics? What does that verb mean?</li> <li><strong>(3)</strong> what properties (safety, idempotence) should one expect that verb to have?</li> <li><strong>(4)</strong> what if the programmer has a very simple client that only handles standard HTTP verbs?</li> <li><strong>(5)</strong> ...</li> </ul> <p>Now let's <strong>consider using <code>POST</code></strong> (I'll discuss why below, just take my word for it now):</p> <pre><code>POST /v1/dogs/1/ HTTP/1.1 Host: api.animals.com {&quot;action&quot;:&quot;bark&quot;} </code></pre> <p>This <em>could</em> be OK... but <strong>only if</strong>:</p> <ul> <li><code>{&quot;action&quot;:&quot;bark&quot;}</code> was a document; and</li> <li><code>/v1/dogs/1/</code> was a &quot;document processor&quot; (factory-like) URI. <sub>A &quot;document processor&quot; is a URI that you'd just &quot;throw things at&quot; and &quot;forget&quot; about them - the processor may redirect you to a newly created resource after the &quot;throwing&quot;. E.g. the URI for posting messages at a message broker service, which, after the posting would redirect you to a URI that shows the status of the message's processing.</sub></li> </ul> <p>I don't know much about your system, but I'd already bet both aren't true:</p> <ul> <li><code>{&quot;action&quot;:&quot;bark&quot;}</code> <strong>is not a document</strong>, it actually <strong>is the method</strong> you are trying to <em>ninja-sneak</em> into the service; and</li> <li>the <code>/v1/dogs/1/</code> URI represents a &quot;dog&quot; resource (probably the dog with <code>id==1</code>) and not a document processor.</li> </ul> <p>So all we know now is that the design above is not so RESTful, but what is that exactly? <strong>What is so bad about it?</strong> Basically, it is bad because that is complex URI with complex meanings. You can't infer anything from it. How would a programmer know a dog have a <code>bark</code> action that can be secretly infused with a <code>POST</code> into it?</p> <br> <h2>Designing your question's API calls</h2> <p>So let's cut to the chase and try to design those barks RESTfully by thinking <strong>in terms of resources</strong>. Allow me to quote the <a href="https://rads.stackoverflow.com/amzn/click/com/0596529260" rel="noreferrer" rel="nofollow noreferrer">Restful Web Services</a> book:</p> <blockquote> <p>A <code>POST</code> request is an attempt to create a new resource from an existing one. The existing resource may be the parent of the new one in a data-structure sense, the way the root of a tree is the parent of all its leaf nodes. Or the existing resource may be a special <em>&quot;factory&quot;</em> resource whose only purpose is to generate other resources. The representation sent along with a <code>POST</code> request describes the initial state of the new resource. As with PUT, a <code>POST</code> request doesn’t need to include a representation at all.</p> </blockquote> <p>Following the description above we can see that <strong><code>bark</code></strong> can be modeled as <strong>a subresource of a <code>dog</code></strong> (since a <code>bark</code> is contained within a dog, that is, a bark is &quot;barked&quot; <strong>by</strong> a dog).</p> <p>From that reasoning we already got:</p> <ul> <li>The method is <code>POST</code></li> <li>The resource is <code>/barks</code>, subresource of dog: <code>/v1/dogs/1/barks</code>, representing a <code>bark</code> &quot;factory&quot;. That URI is unique for each dog (since it is under <code>/v1/dogs/{id}</code>).</li> </ul> <p>Now each case of your list has a specific behavior.</p> <p>##1. bark just sends an e-mail to <code>dog.email</code> and records nothing.</p> <p>Firstly, is barking (sending an e-mail) a synchronous or an asynchronous task? Secondly does the <code>bark</code> request require any document (the e-mail, maybe) or is it empty?</p> <br> <h3>1.1 bark sends an e-mail to <code>dog.email</code> and records nothing (as a synchronous task)</h3> <p>This case is simple. A call to the <code>barks</code> factory resource yields a bark (an e-mail sent) right away and the response (if OK or not) is given right away:</p> <pre><code>POST /v1/dogs/1/barks HTTP/1.1 Host: api.animals.com Authorization: Basic mAUhhuE08u724bh249a2xaP= (entity-body is empty - or, if you require a **document**, place it here) <strong>200 OK</strong> </code></pre> <p>As it records (changes) nothing, <code>200 OK</code> is enough. It shows that everything went as expected.</p> <br> <h3>1.2 bark sends an e-mail to <code>dog.email</code> and records nothing (as an asynchronous task)</h3> <p>In this case, the client must have a way to track the <code>bark</code> task. The <code>bark</code> task then should be a resource with it's own URI.:</p> <pre><code>POST /v1/dogs/1/barks HTTP/1.1 Host: api.animals.com Authorization: Basic mAUhhuE08u724bh249a2xaP= {document body, if needed; NOTE: when possible, the response SHOULD contain a short hypertext note with a hyperlink to the newly created resource (bark) URI, the same returned in the Location header (also notice that, for the 202 status code, the Location header meaning is not standardized, thus the importance of a hipertext/hyperlink response)} <strong>202 Accepted Location: http://api.animals.com/v1/dogs/1/barks/a65h44</strong> </code></pre> <p>This way, each <code>bark</code> is traceable. The client can then issue a <code>GET</code> to the <code>bark</code> URI to know it's current state. Maybe even use a <code>DELETE</code> to cancel it.</p> <br> <h2>2. bark sends an e-mail to <code>dog.email</code> and then increments <code>dog.barkCount</code> by 1</h2> <p>This one can be trickier, if you want to let the client know the <code>dog</code> resource gets changed:</p> <pre><code>POST /v1/dogs/1/barks HTTP/1.1 Host: api.animals.com Authorization: Basic mAUhhuE08u724bh249a2xaP= {document body, if needed; when possible, containing a hipertext/hyperlink with the address in the Location header -- says the standard} <strong>303 See Other Location: http://api.animals.com/v1/dogs/1</strong> </code></pre> <p>In this case, the <code>location</code> header's intent is to let the client know he should take a look at <code>dog</code>. From the <a href="https://www.rfc-editor.org/rfc/rfc2616#section-10.3.4" rel="noreferrer">HTTP RFC about <code>303</code></a>:</p> <blockquote> <p>This method exists primarily to allow the output of a <strong><code>POST</code>-activated script</strong> to redirect the user agent to a selected resource.</p> </blockquote> <p>If the task is asynchronous, a <code>bark</code> subresource is needed just like the <code>1.2</code> situation and the <code>303</code> should be returned at a <code>GET .../barks/Y</code> when the task is complete.</p> <br> <h2>3. bark creates a new &quot;<code>bark</code>&quot; record with <code>bark.timestamp</code> recording when the bark occured. It also increments <code>dog.barkCount</code> by 1.</h2> <pre><code>POST /v1/dogs/1/barks HTTP/1.1 Host: api.animals.com Authorization: Basic mAUhhuE08u724bh249a2xaP= (document body, if needed) <strong>201 Created Location: http://api.animals.com/v1/dogs/1/barks/a65h44</strong> </code></pre> <p>In here, the <code>bark</code> is a created due to the request, so the status <code>201 Created</code> is applied.</p> <p>If the creation is asynchronous, a <code>202 Accepted</code> is required (<a href="https://www.rfc-editor.org/rfc/rfc2616#section-10.2.2" rel="noreferrer">as the HTTP RFC says</a>) instead.</p> <p>The timestamp saved is a part of <code>bark</code> resource and can be retrieved with a <code>GET</code> to it. The updated dog can be &quot;documented&quot; in that <code>GET dogs/X/barks/Y</code> as well.</p> <br> <h2>4. bark runs a system command to pull the latest version of the dog code down from Github. It then sends a text message to <code>dog.owner</code> telling them that the new dog code is in production.</h2> <p>The wording of this one is complicated, but it pretty much is a simple asynchronous task:</p> <pre><code>POST /v1/dogs/1/barks HTTP/1.1 Host: api.animals.com Authorization: Basic mAUhhuE08u724bh249a2xaP= (document body, if needed) <strong>202 Accepted Location: http://api.animals.com/v1/dogs/1/barks/a65h44</strong> </code></pre> <p>The client then would issue <code>GET</code>s to <code>/v1/dogs/1/barks/a65h44</code> to know the current state (if the code was pulled, it the e-mail was sent to the owner and such). Whenever the dog changes, a <code>303</code> is appliable.</p> <br> <h2>Wrapping up</h2> <p>Quoting <a href="http://roy.gbiv.com/untangled/2009/it-is-okay-to-use-post" rel="noreferrer">Roy Fielding</a>:</p> <blockquote> <p>The only thing REST requires of methods is that they be uniformly defined for all resources (i.e., so that intermediaries don’t have to know the resource type in order to understand the meaning of the request).</p> </blockquote> <p>In the above examples, <code>POST</code> is uniformly designed. It will make the dog &quot;<code>bark</code>&quot;. That is not safe (meaning bark has effects on the resources), nor idempotent (each request yields a new <code>bark</code>), which fits the <code>POST</code> verb well.</p> <p>A programmer would know: a <code>POST</code> to <code>barks</code> yields a <code>bark</code>. The response status codes (also with entity-body and headers when necessary) do the job of explaining what changed and how the client can and should proceed.</p> <p><sub>Note: The primary sources used were: &quot;<a href="https://rads.stackoverflow.com/amzn/click/com/0596529260" rel="noreferrer" rel="nofollow noreferrer">Restful Web Services</a>&quot; book, the <a href="https://www.rfc-editor.org/rfc/rfc2616" rel="noreferrer">HTTP RFC</a> and <a href="http://roy.gbiv.com/untangled" rel="noreferrer">Roy Fielding's blog</a>.</sub></p> <br> <br> <hr /> <p><strong>Edit:</strong></p> <p>The question and thus the answer have changed quite a bit since they were first created. The <strong>original question</strong> asked about the design of a URI like:</p> <pre><code>ACTION http://api.animals.com/v1/dogs/1/?action=bark </code></pre> <p>Below is the explanation of why it is not a good choice:</p> <p>How clients tell the server <strong>WHAT TO DO</strong> with the data is the <em>method information</em>.</p> <ul> <li>RESTful web services convey method information in the HTTP method.</li> <li>Typical RPC-Style and SOAP services keep theirs in the entity-body and HTTP header.</li> </ul> <p><strong>WHICH PART</strong> of the data [the client wants the server] to operate on is the <em>scoping information</em>.</p> <ul> <li>RESTful services use the URI. SOAP/RPC-Style services once again use the entity-body and HTTP headers.</li> </ul> <p>As an example, take Google's URI <code>http://www.google.com/search?q=DOG</code>. There, the method information is <code>GET</code> and the scoping information is <code>/search?q=DOG</code>.</p> <p>Long story short:</p> <ul> <li>In <strong>RESTful architectures</strong>, the method information goes into the HTTP method.</li> <li>In <strong>Resource-Oriented Architectures</strong>, the scoping information goes into the URI.</li> </ul> <p>And the rule of thumb:</p> <blockquote> <p>If the HTTP method doesn’t match the method information, the service isn’t RESTful. If the scoping information isn’t in the URI, the service isn’t resource-oriented.</p> </blockquote> <p>You can put the <em>&quot;bark&quot;</em> <em>&quot;action&quot;</em> in the URL (or in the entity-body) and use <code>POST</code>. No problem there, it works, and may be the simplest way to do it, <strong>but this isn't RESTful</strong>.</p> <p>To keep your service really RESTful, you may have to take a step back and think about what you really want to do here (what effects will it have on the resources).</p> <p>I can't talk about your specific business needs, but let me give you an example: Consider a RESTful ordering service where orders are at URIs like <code>example.com/order/123</code>.</p> <p>Now say we want to cancel an order, how are we gonna do it? One may be tempted to think that is a <em>&quot;cancellation&quot;</em> <em>&quot;action&quot;</em> and design it as <code>POST example.com/order/123?do=cancel</code>.</p> <p>That is not RESTful, as we talked above. Instead, we might <code>PUT</code> a new representation of the <code>order</code> with a <code>canceled</code> element sent to <code>true</code>:</p> <pre><code>PUT /order/123 HTTP/1.1 Content-Type: application/xml &lt;order id=&quot;123&quot;&gt; &lt;customer id=&quot;89987&quot;&gt;...&lt;/customer&gt; &lt;canceled&gt;true&lt;/canceled&gt; ... &lt;/order&gt; </code></pre> <p>And that's it. If the order can't be canceled, a specific status code can be returned. <sup>(A subresource design, like <code>POST /order/123/canceled</code> with the entity-body <code>true</code> may, for simplicity, also be available.)</sup></p> <p>In your specific scenario, you may try something similar. That way, while a dog is barking, for example, a <code>GET</code> at <code>/v1/dogs/1/</code> could include that information <sup>(e.g. <code>&lt;barking&gt;true&lt;/barking&gt;</code>)</sup>. Or... if that's too complicated, loosen up your RESTful requirement and stick with <code>POST</code>.</p> <h3>Update:</h3> <p>I don't want to make the answer too big, but it takes a while to get the hang of exposing an algorithm (an <em>action</em>) as a set of resources. Instead of thinking in terms of actions (<em>&quot;do a search for places on the map&quot;</em>), one needs to think in terms of the results of that action (<em>&quot;the list of places on the map matching a search criteria&quot;</em>).</p> <p>You may find yourself coming back to this step if you find that your design doesn't fit HTTP's uniform interface.</p> <p>Query variables <strong>are</strong> <em>scoping information</em>, but do <strong>not</strong> denote new resources (<code>/post?lang=en</code> is clearly the <strong>same</strong> resource as <code>/post?lang=jp</code>, just a different representation). Rather, they are used to convey <strong>client state</strong> (like <code>?page=10</code>, so that state is not kept in the server; <code>?lang=en</code> is also an example here) or <strong>input parameters</strong> to <em>algorithmic resources</em> (<code>/search?q=dogs</code>, <code>/dogs?code=1</code>). Again, not distinct resources.</p> <h2>HTTP verbs' (methods) properties:</h2> <p>Another clear point that shows <code>?action=something</code> in the URI is not RESTful, are the properties of HTTP verbs:</p> <ul> <li><code>GET</code> and <code>HEAD</code> are safe (and idempotent);</li> <li><code>PUT</code> and <code>DELETE</code> are idempotent only;</li> <li><code>POST</code> is neither.</li> </ul> <p><strong>Safety</strong>: A <code>GET</code> or <code>HEAD</code> request is a request to <strong>read</strong> some data, not a request to change any server state. The client can make a <code>GET</code> or <code>HEAD</code> request 10 times and it's the same as making it once, or <em>never making it at all</em>.</p> <p><strong>Idempotence</strong>: An idempotent operation in one that has the same effect whether you apply it once or more than once (in math, multiplying by zero is idempotent). If you <code>DELETE</code> a resource once, deleting again will have the same effect (the resource is <code>GONE</code> already).</p> <p><sup><sub><code>POST</code> is neither safe nor idempotent. Making two identical <code>POST</code> requests to a 'factory' resource will probably result in two subordinate resources containing the same information. With overloaded (method in URI or entity-body) <code>POST</code>, all bets are off.</sub></sup></p> <p>Both these properties were important to the success of the HTTP protocol (over unreliable networks!): how many times have you updated (<code>GET</code>) the page without waiting until it is fully loaded?</p> <p>Creating an <em>action</em> and placing it in the URL clearly breaks the HTTP methods' contract. Once again, the technology allows you, you can do it, but that is not RESTful design.</p>
16,683,758
How to create a table from select query result in SQL Server 2008
<p>I want to create a table from select query result in SQL Server, I tried </p> <pre><code>create table temp AS select..... </code></pre> <p>but I got an error </p> <blockquote> <p>Incorrect syntax near the keyword 'AS'</p> </blockquote>
16,683,927
6
3
null
2013-05-22 04:57:38.89 UTC
48
2020-04-16 11:18:16.193 UTC
2013-05-22 05:05:04.18 UTC
null
13,302
null
2,366,147
null
1
247
sql|sql-server|sql-server-2008
1,120,527
<p>Use following syntax to create new table from old table in SQL server 2008</p> <pre><code>Select * into new_table from old_table </code></pre>
25,858,977
Xcode 6 crashes when validating or submitting app archive
<p>This worked fine 2 days ago using the exact same archive and provisioning profile (selected from the organizer). Anyone else seeing this? I haven't updated Xcode, so it seems like it might be something on Apple's end causing a failure?</p> <pre><code>Application Specific Information: ProductBuildVersion: 6A313 ASSERTION FAILURE in /SourceCache/IDEFrameworks/IDEFrameworks-6299/IDEFoundation/Issues/IDEIssueManager.m:457 Details: This method must only be called on the main thread Object: &lt;IDEIssueManager&gt; Method: +_issueProviderInfo Thread: &lt;NSThread: 0x7fa1abfa8e60&gt;{name = (null), num = 44} Hints: None Backtrace: 0 0x00000001027adf0a -[IDEAssertionHandler handleFailureInMethod:object:fileName:lineNumber:assertionSignature:messageFormat:arguments:] (in IDEKit) 1 0x000000010156dbaf _DVTAssertionHandler (in DVTFoundation) 2 0x000000010156de9e _DVTAssertionFailureHandler (in DVTFoundation) 3 0x0000000101ea2bce +[IDEIssueManager _issueProviderInfo] (in IDEFoundation) 4 0x0000000101ea224d -[IDEIssueManager _updateIssueProviders] (in IDEFoundation) 5 0x000000010157ffbe __73-[DVTObservingBlockToken observeValueForKeyPath:ofObject:change:context:]_block_invoke (in DVTFoundation) 6 0x00000001014fa6c8 DVTInvokeWithStrongOwnership (in DVTFoundation) 7 0x00000001013ae124 -[DVTObservingBlockToken observeValueForKeyPath:ofObject:change:context:] (in DVTFoundation) 8 0x00007fff8aed8f28 NSKeyValueNotifyObserver (in Foundation) 9 0x00007fff8aed80f8 NSKeyValueDidChange (in Foundation) 10 0x00007fff8aedcbe6 -[NSObject(NSKeyValueObserverNotification) didChangeValueForKey:] (in Foundation) 11 0x00007fff8ddf3f6f doSetValuesInSourceWithKVO (in CoreFoundation) 12 0x00007fff8ddf3e0f _CFXPreferencesReplaceValuesInNamedVolatileSource (in CoreFoundation) 13 0x00007fff8b07fafc -[NSUserDefaults(NSUserDefaults) setVolatileDomain:forName:] (in Foundation) 14 0x00000001124ad9e9 -[NSUserDefaults(ITunesConnectFoundationExtensions) REPLACEMENT_setVolatileDomain:forName:] (in ITunesConnectFoundation) 15 0x00000001124a3fac -[MZJSONServiceClient connectionDidFinishLoading:] (in ITunesConnectFoundation) 16 0x00007fff8af877fd __65-[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]_block_invoke (in Foundation) 17 0x00007fff8af8772d -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:] (in Foundation) 18 0x00007fff8af8761c -[NSURLConnectionInternal _withActiveConnectionAndDelegate:] (in Foundation) 19 0x00007fff989e9284 ___ZN27URLConnectionClient_Classic26_delegate_didFinishLoadingEU13block_pointerFvvE_block_invoke (in CFNetwork) 20 0x00007fff98a9f820 ___ZN27URLConnectionClient_Classic18_withDelegateAsyncEPKcU13block_pointerFvP16_CFURLConnectionPK33CFURLConnectionClientCurrent_VMaxE_block_invoke_2 (in CFNetwork) 21 0x00007fff989cc2ec ___ZNK17CoreSchedulingSet13_performAsyncEPKcU13block_pointerFvvE_block_invoke (in CFNetwork) 22 0x00007fff8de04a94 CFArrayApplyFunction (in CoreFoundation) 23 0x00007fff989cc1cb RunloopBlockContext::perform() (in CFNetwork) 24 0x00007fff989cc073 MultiplexerSource::perform() (in CFNetwork) 25 0x00007fff989cbea2 MultiplexerSource::_perform(void*) (in CFNetwork) 26 0x00007fff8de395b1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ (in CoreFoundation) 27 0x00007fff8de2ac62 __CFRunLoopDoSources0 (in CoreFoundation) 28 0x00007fff8de2a3ef __CFRunLoopRun (in CoreFoundation) 29 0x00007fff8de29e75 CFRunLoopRunSpecific (in CoreFoundation) 30 0x00007fff8af38adc -[NSRunLoop(NSRunLoop) runMode:beforeDate:] (in Foundation) 31 0x00007fff8af8110b -[NSRunLoop(NSRunLoop) runUntilDate:] (in Foundation) 32 0x00000001124a3468 -[MZJSONServiceClient getResultDictionary] (in ITunesConnectFoundation) 33 0x00000001124a55da -[MZLabelServiceClient invokeSOAPCall] (in ITunesConnectFoundation) 34 0x00000001124aa904 -[MZWebServiceOperationWorker execute] (in ITunesConnectFoundation) 35 0x00000001124aac02 -[MZWebServiceWorker run] (in ITunesConnectFoundation) 36 0x000000011248336c -[MZWorkItem main] (in ITunesConnectFoundation) 37 0x00007fff8aed78a1 -[__NSOperationInternal _start:] (in Foundation) 38 0x00007fff8aed754b __NSOQSchedule_f (in Foundation) 39 0x00007fff96f8528d _dispatch_client_callout (in libdispatch.dylib) 40 0x00007fff96f897e3 _dispatch_async_redirect_invoke (in libdispatch.dylib) 41 0x00007fff96f8528d _dispatch_client_callout (in libdispatch.dylib) 42 0x00007fff96f87082 _dispatch_root_queue_drain (in libdispatch.dylib) 43 0x00007fff96f88177 _dispatch_worker_thread2 (in libdispatch.dylib) 44 0x00007fff934d0ef8 _pthread_wqthread (in libsystem_pthread.dylib) 45 0x00007fff934d3fb9 start_wqthread (in libsystem_pthread.dylib) </code></pre>
26,027,417
12
9
null
2014-09-16 00:33:39.003 UTC
13
2016-09-13 07:29:57.34 UTC
null
null
null
null
2,191,913
null
1
60
ios|xcode
12,373
<p>Make sure you've accepted all of the new agreements in the Member Center.</p> <p>To check if you need to, you can go to the preferences -> accounts in XCode, and chose to <em>view details</em> of an account and attempt to <em>refresh</em> using the little button. Here, XCode will warn you that you need to accept new agreements in the Member Center before you can refresh.</p> <p>On the other hand, the Organizer will just crash instead of warning you about un-signed agreements.</p>
50,951,076
Why does `None is None is None` return True?
<p>Today, in an interview, the CTO asked me what looks like an easy question, </p> <p>What does this statement return ? :</p> <pre><code>None is None is None </code></pre> <p>I thought Python executed the first operation <code>None is None</code> and would return <code>True</code>. After that, it would compare <code>True is None</code> which would return <code>False</code>. But, to my surprise, the right answer is <code>True</code>. I am trying to find answer to this question, but after a couple of days searching I didn't find anything. Can someone explain why this happens?</p>
50,951,263
3
7
null
2018-06-20 14:50:29.53 UTC
9
2022-08-29 14:27:47.777 UTC
2022-08-29 14:27:47.777 UTC
null
523,612
null
8,040,117
null
1
57
python
2,387
<p>The bytecode shows that two comparisons are being performed here with the middle being duplicated:</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; def a(): ... return None is None is None ... &gt;&gt;&gt; dis.dis(a) 2 0 LOAD_CONST 0 (None) 3 LOAD_CONST 0 (None) 6 DUP_TOP 7 ROT_THREE 8 COMPARE_OP 8 (is) 11 JUMP_IF_FALSE_OR_POP 21 14 LOAD_CONST 0 (None) 17 COMPARE_OP 8 (is) 20 RETURN_VALUE &gt;&gt; 21 ROT_TWO 22 POP_TOP 23 RETURN_VALUE </code></pre> <p>As stated in the <a href="https://docs.python.org/3/reference/expressions.html#comparisons" rel="noreferrer">docs for comparisons</a> this is because these operators chain together.</p> <p><code>a op b op c</code> will be translated to <code>a op b and b op c</code> (note <code>b</code> is duplicated in the bytecode as shown above)</p>
4,353,834
Search through NSString using Regular Expression
<p>How might I go about searching/enumerating through an <code>NSString</code> using a regular expression?</p> <p>A regular expression such as: <code>/(NS|UI)+(\w+)/g</code>.</p>
4,353,868
2
0
null
2010-12-04 13:55:02.61 UTC
9
2018-01-24 15:17:59.43 UTC
2017-02-22 01:30:25.88 UTC
null
2,712,652
null
92,714
null
1
41
objective-c|cocoa|nsstring
44,433
<p>You need to use <a href="http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html" rel="noreferrer"><code>NSRegularExpression</code></a> class.</p> <p>Example inspired in the documentation:</p> <pre><code>NSString *yourString = @""; NSError *error = NULL; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(NS|UI)+(\\w+)" options:NSRegularExpressionCaseInsensitive error:&amp;error]; [regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){ // your code to handle matches here }]; </code></pre>
9,646,608
Use a heap overflow to write arbitrary data
<p>I've been trying to learn the basics of a heap overflow attack. I'm mostly interested in using a corruption or modification of the chunk metadata for the basis of the attack, but I'm also open to other suggestions. I know that my goal of the exploit should be do overwrite the <code>printf()</code> function pointer with that of the <code>challenge()</code> function pointer, but I can't seem to figure out how to achieve that write. I have the following piece of code which I want to exploit, which is using <code>malloc</code> from <code>glibc 2.11.2</code> :</p> <pre class="lang-c prettyprint-override"><code>void challenge() { puts("you win\n"); } int main(int argc, char **argv) { char *inputA, *inputB, *inputC; inputA = malloc(32); inputB = malloc(32); inputC = malloc(32); strcpy(inputA, argv[1]); strcpy(inputB, argv[2]); strcpy(inputC, argv[3]); free(inputC); free(inputB); free(inputA); printf("execute challenge to win\n"); } </code></pre> <p>Obviously, achieving an actual overwrite of an allocated chunk's metadata is trivial. However, I have not been able to find a way to exploit this code using any of the standard techniques. I have read and attempted to implement the techniques from:</p> <ul> <li>The paper: w00w00 on <a href="http://www.windowsecurity.com/uplarticle/1/heaptut.txt" rel="noreferrer">Heap Overflows</a> <ul> <li>Although the paper is very clear, the <code>unlink</code> technique has been obsolete for some time.</li> </ul></li> <li><a href="http://dl.packetstormsecurity.net/papers/attack/MallocMaleficarum.txt" rel="noreferrer">Malloc Maleficarum.txt</a> <ul> <li>This paper expands upon the exploit techniques from the w00w00 days, and accounts for the newer versions of glibc. However, I have not found that given the 5 techniques detailed in the paper, that the code above matches any of the prerequisites for those techniques.</li> </ul></li> <li><a href="https://www.blackhat.com/presentations/bh-usa-07/Ferguson/Whitepaper/bh-usa-07-ferguson-WP.pdf" rel="noreferrer">Understanding the Heap By Breaking it(pdf)</a> <ul> <li>The pdf gives a pretty good review of how the heap works, but focuses on double free techniques.</li> </ul></li> </ul> <p>I originally tried to exploit this code by manipulating the size value of the chunk for inputC, so that it pointed back to the head of the inputC chunk. When that didn't work, I tried pointing further back to the chunk of inputB. That is when I realized that the new glibc performs a sanity check on the size value.</p> <p>How can a user craft an exploit to take advantage of a free, assuming he has the ability to edit the allocated chunk's metadata to arbitrary values, and user it to overwrite a value in the GOT or write to any other arbitrary address?</p> <p>Note: When I write 'arbitrary address' I understand that memory pages may be read only or protected, I mean an address that I can assume I can write to.</p>
15,527,624
3
15
null
2012-03-10 12:58:00.44 UTC
16
2021-11-18 15:10:26.74 UTC
2021-11-18 15:10:26.74 UTC
null
5,459,839
null
228,489
null
1
22
c|security|heap-memory|exploit
15,318
<p>Note: I will say before I answer that this is purely an academic answer, not intended to be used for malicious purposes. I am aware of the exercises OP is doing and they are open source and not intended to encourage any users to use these techniques in unapproved circumstances.</p> <p>I will detail the technique below but for your reference I would take a look at the Vudo malloc tricks (It's referenced in one of your links above) because my overview is going to be a short one: <a href="http://www.phrack.com/issues.html?issue=57&amp;id=8" rel="nofollow noreferrer">http://www.phrack.com/issues.html?issue=57&amp;id=8</a></p> <p>It details how malloc handles creating blocks of memory, pulling memory from lists and other things. In particular the unlink attack is of interest for this attack (note: you're correct that glibc now performs a sanity check on sizes for this particular reason, but you should be on an older libc for this exercise... legacy bro).</p> <p>From the paper, an allocated block and a free block use the same data structure, but the data is handled differently. See here:</p> <pre><code>chunk -&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | prev_size: size of the previous chunk, in bytes (used | | by dlmalloc only if this previous chunk is free) | +---------------------------------------------------------+ | size: size of the chunk (the number of bytes between | | "chunk" and "nextchunk") and 2 bits status information | mem -&gt; +---------------------------------------------------------+ | fd: not used by dlmalloc because "chunk" is allocated | | (user data therefore starts here) | + - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | bk: not used by dlmalloc because "chunk" is allocated | | (there may be user data here) | + - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | | | | | user data (may be 0 bytes long) | | | | | next -&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | prev_size: not used by dlmalloc because "chunk" is | | allocated (may hold user data, to decrease wastage) | +---------------------------------------------------------+ </code></pre> <p>Allocated blocks don't use the fd or bk pointers, but free ones will. This is going to be important later. You should know enough programming to understand that "blocks" in Doug Lea's malloc are organized into a doubly-linked list; there's one list for free blocks and another for allocated ones (technically there are several lists for free depending on sizes but it's irrelevant here since the code allocates blocks of the same size). So when you're freeing a particular block, you have to fix the pointers to keep the list in tact.</p> <p>e.g. say you're freeing block y from the list below:</p> <pre><code>x &lt;-&gt; y &lt;-&gt; z </code></pre> <p>Notice that in the diagram above the spots for bk and fd contain the necessary pointers to iterate along the list. When malloc wants to take a block p off of the list it calls, among other things, a macro to fix the list:</p> <pre><code>#define unlink( y, BK, FD ) { BK = P-&gt;bk; FD = P-&gt;fd; FD-&gt;bk = BK; BK-&gt;fd = FD; } </code></pre> <p>The macro itself isn't hard to understand, but the important thing to note in older versions of libc is that it doesn't perform sanity checks on the size or the pointers being written to. What it means in your case is that without any sort of address randomization you can predictably and reliably determine the status of the heap and redirect an arbitrary pointer to an address of your choosing by overflowing the heap (via the strncopy here) in a specific way.</p> <p>There's a few things required to get the attack to work:</p> <ul> <li>the fd pointer for your block is pointing to the address you want to overwrite minus 12 bytes. The offset has to do with malloc cleaning up the alignment when it modifies the list</li> <li>The bk pointer of your block is pointing to your shellcode</li> <li>The size needs to be -4. This accomplishes a few things, namely it sets the status bits in the block </li> </ul> <p>So you'll have to play around with the offsets in your specific example, but the general malicious format that you're trying to pass with the strcpy here is of the format:</p> <p>| junk to fill up the legitimate buffer | -4 | -4 | addr you want to overwrite -12 (0x0C) | addr you want to call instead </p> <p>Note the negative number sets the prev_size field to -4, which makes the free routing believe that the prev_size chunk actually starts in the current chunk that you control/are corrupting. </p> <p>And yes, a proper explanation wouldn't be complete without mentioning that this attack doesn't work on current versions of glibc; the size has a sanity check done and the unlink method just won't work. That in combination with mitigations like address randomization make this attack not viable on anything but legacy systems. But the method described here is how I did that challenge ;)</p>
9,706,943
Conditional Formatting in a Razor Index View
<p>I'm trying to conditionally add a CSS <code>background-color</code> to a set of table rows, based on how close the item's expiry date is. Thirty days or less should be red, 90 - 31 days amber and the rest green. (I'm putting the red in first, once this is working I'll go back and do the amber/green rows).</p> <pre><code>@foreach (var item in Model) { int daysLeft = (item.ExpiryDate - DateTime.Today).Days; if (daysLeft &lt;= 30) { &lt;tr style="background-color:Red"&gt; } else { &lt;tr&gt; } &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.SupplierName) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.ExpiryDate) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.InceptionDate) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.Value) &lt;/td&gt; &lt;td&gt; @Html.ActionLink("Edit", "Edit", new { id = item.Id }) | @Html.ActionLink("Details", "Details", new { id = item.Id }) | @Html.ActionLink("Delete", "Delete", new { id = item.Id }) &lt;/td&gt; &lt;/tr&gt; } </code></pre> <p>When I run this page, I get a YSOD saying the <code>@foreach</code> block is missing its closing <code>}</code>, but as far as I can see they are matched so I'm assuming the <em>actual</em> problem is something else.</p>
9,706,987
2
0
null
2012-03-14 17:26:10.463 UTC
4
2012-03-14 17:31:49.347 UTC
null
null
null
null
1,738
null
1
28
asp.net-mvc-3|razor
37,009
<p>Razor requires that tags directly inside code blocks be balanced and well-formed.<br> Therefore, all of the code after the first opening <code>&lt;tr&gt;</code> tag is actually parsed as markup, so that the final <code>}</code> just closes the <code>if</code>.</p> <p>To fix that, you can force Razor to ignore the tag by prefixing the line with <code>@:</code>.</p> <p>Alternatively, you can get rid of the <code>if</code> entirely and write</p> <pre><code>string style = daysLeft &lt;= 30 ? "background-color:Red" : null; &lt;tr style="@style"&gt; ... &lt;/tr&gt; </code></pre>
9,714,139
Why does Zipping the same content twice gives two files with different SHA1?
<p>I have run into a strange problem with git and zip files. My build script takes a bunch of documentation html pages and zips them into a docs.zip I then check this file into git. </p> <p>The problem I am having is that every time I re-run the build script and get a new zip file the new zip file has a different SHA1 than the previous run. My build script is calling the ant zip task. However manualy calling the macOSX zip from the Mac OS X shell gives me a different sha1 if I zip up the same directory twice. </p> <p>Run 1: </p> <pre><code>zip foo.zip * openssl sha1 foo.zip rm foo.zip </code></pre> <p>Run 2: </p> <pre><code>zip foo.zip * openssl sha1 foo.zip </code></pre> <p>Run 1 and run2 give different SHA1 even though the content did not change between runs. In both cases zip prints out exactly the same files being zipped it does not indicate that any OS specific files like .DS_Store are being included in the zip file. </p> <p>Is the zip algoritm deterministic? If run on the same content will it produce exactly the same bits? if not why not? </p> <p>What are my choices for zipping the files in a deterministic way? There are thousands of them in the zipped up file, I don't expect those files to change much. I know that git will zip up any files you checkin but the motivation to zip them is to just keep the mass of them out of the way.</p>
9,714,323
4
2
null
2012-03-15 04:48:04.43 UTC
2
2022-09-03 06:41:30.053 UTC
null
null
null
null
438,319
null
1
30
git|ant|zip|gzip|sha
9,760
<p>According to Wikipedia <a href="http://en.wikipedia.org/wiki/Zip_%28file_format%29" rel="noreferrer">http://en.wikipedia.org/wiki/Zip_(file_format)</a> seems that zip files have headers for File last modification time and File last modification date so any zip file checked into git will appear to git to have changed if the zip is rebuilt from the same content since. And it seems that there is no flag to tell it to not set those headers.</p> <p>I am resorting to just using tar, it seems to produce the same bytes for the same input if run multiple times. </p>
10,058,068
In a Git cherry-pick or rebase merge conflict, how are BASE (aka "the ancestor"), LOCAL, and REMOTE determined?
<p>In a normal Git merge conflict, the three versions of a file in play for the three-way merge are roughly as follows:</p> <ul> <li>LOCAL: the version from my branch</li> <li>REMOTE: the version from the other branch</li> <li>BASE: the version from the common ancestor of the two branches (in particular, the common ancestor of my branch's HEAD and the other branch's HEAD)</li> </ul> <p>When a Git cherry-pick generates a merge conflict, there is no common ancestor, properly speaking, so how are these things determined? The same could be asked about rebase.</p>
10,058,070
1
0
null
2012-04-07 20:26:49.87 UTC
20
2015-03-02 07:58:32.587 UTC
2012-04-10 18:47:32.787 UTC
null
64,257
null
64,257
null
1
37
git|cherry-pick|git-cherry-pick
8,947
<p><strong>cherry-pick</strong></p> <p>Unless I have misled myself, then if you do "git cherry-pick &lt;commit C&gt;", then you get:</p> <ul> <li>LOCAL: the commit you're merging on top of (ie the HEAD of your branch)</li> <li>REMOTE: the commit you're cherry picking (i.e. &lt;commit C&gt;)</li> <li>BASE: the parent of the commit you're cherry-picking (ie C^, ie the parent of C)</li> </ul> <p>If it's not immediately clear why BASE should be C^, see the "why" section below.</p> <p>Meanwhile, let's take an example, and see that BASE <em>can be</em> but often <em>won't be</em> a common ancestor during a cherry-pick. Suppose the commit graph looks like this</p> <pre><code>E &lt;-- master | D | C &lt;-- foo_feature(*) |/ B | A </code></pre> <p>and you are in branch foo_feature (hence the asterisk). If you do "git cherry-pick &lt;commit D&gt;", then BASE for that cherry-pick will be commit B, which is a common ancestor of C and D. (C will be LOCAL and D will be REMOTE.) However, if you instead do "git cherry-pick &lt;commit E&gt;, then BASE will be commit D. (C will be LOCAL and E will be REMOTE.)</p> <p><strong>rebase</strong></p> <p>For background context, rebase is approximately iterated cherry-picking. In particular, rebasing topic on top of master (ie "git checkout topic; git rebase master") means approximately :</p> <pre><code>git checkout master # switch to master's HEAD commit git checkout -b topic_rebased # create new branch rooted there for each commit C in master..topic # for each topic commit not already in master... git cherry-pick C # bring it over to the new branch finally, forget what "topic" used to mean and now defined "topic" as the HEAD of topic_rebased. </code></pre> <p>The labels that apply during this process are extensions of the normal cherry-pick rules:</p> <ul> <li>LOCAL: the commit you're cherry-picking on top of <ul> <li>This is the HEAD of the new topic_rebased branch</li> <li>For the first commit only, this will be the same as the HEAD of master</li> </ul></li> <li>REMOTE: the commit you're cherry picking (i.e. &lt;commit C&gt;)</li> <li>BASE: the parent of the commit you're cherry-picking (C^, ie the parent of C)</li> </ul> <p>This implies something to keep in mind about LOCAL vs REMOTE, if you want to avoid confusion:</p> <blockquote> <p><em>Even though you were on branch topic when you initiated the rebase</em>, <strong><em>LOCAL never refers to a commit on the topic branch</em></strong> <em>while a rebase is in progress.</em> Instead, LOCAL always refers to a commit on the <em>new</em> branch being created (topic_rebased).</p> </blockquote> <p>(If one fails to keep this in mind, then during a nasty merge one may start asking oneself, "Wait, why is it saying these are <em>local</em> changes? I swear they were changes made on master, not on my branch.")</p> <p>To be more concrete, here is an example:</p> <p>Say we have commit graph</p> <pre><code>D &lt;-- foo_feature(*) | | C &lt;-- master B | |/ | A </code></pre> <p>and we are currently on branch foo_feature (indicated by "*"). If we run "git rebase master", the rebase will proceed in two steps:</p> <p>First, changes from B will be replayed on top of C. During this, C is LOCAL, B is REMOTE, and A is BASE. Note that A is a real common ancestor of B and C. After this first step, you have a graph approximately like so:</p> <pre><code> B' &lt;-- foo_feature D | | | | C &lt;-- master B / |/ | A </code></pre> <p>(In real life, B and D might have already been pruned out of the tree at this point, but I'm leaving them in here, in order to make it easier to spot any potential common ancestors.)</p> <p>Second, changes from D will be replayed on top of B'. During this, B' is LOCAL, D is REMOTE, and B is BASE. Note that B is not a relevant common ancestor of anything. (For example, it's not a common ancestor of the current LOCAL and REMOTE, B' and D. And it's not a common ancestor of the original branch heads, C and D). After this step, you have a branch approximately like so:</p> <pre><code> D' &lt;-- foo_feature | B' D | | | | C &lt;-- master B / |/ | A </code></pre> <p>For completeness, note by the end of the rebase B and D are removed from the graph, yielding:</p> <pre><code>D' &lt;-- foo_feature | B' | C &lt;-- master | A </code></pre> <p><strong>Why is BASE defined as it is?</strong></p> <p>As noted above, both for a cherry-pick and for a rebase, BASE is the parent (C^) of the the commit C being pulled in. In the general case C^ isn't a common ancestor, so why call it BASE? (In a normal merge BASE <em>is</em> a common ancestor. And part of git's successes in merging are due to its ability to find a good common ancestor.) </p> <p>Essentially, one does this as a way to implement "patch" functionality via the normal <a href="http://en.wikipedia.org/wiki/3-way_merge#Three-way_merge">three-way merge</a> algorithm. In particular you get these "patchy" properties:</p> <ul> <li>If &lt;commit C&gt; doesn't modify a given given region of the file, then the version of that region from your branch will prevail. (This is, regions that the "patch" doesn't call for changing don't get patched.)</li> <li>If &lt;commit C&gt; modifies a given region of the file and your branch leaves that region alone, then the version of that region from &lt;commit x&gt; will prevail. (That is, regions that the "patch" calls for changing get patched.)</li> <li>If &lt;commit C&gt; modifies a given region of the file but your branch has also modified that region, then you get a merge conflict.</li> </ul>
9,704,677
Jenkins - passing variables between jobs?
<p>I have two jobs in jenkins, both of which need the same parameter. </p> <p>How can I run the first job with a parameter so that when it triggers the second job, the same parameter is used?</p>
9,704,755
12
2
null
2012-03-14 15:12:09.297 UTC
18
2021-11-02 23:47:04.787 UTC
2017-11-15 15:05:05.35 UTC
null
411,902
null
78,182
null
1
98
continuous-integration|hudson|jenkins
218,712
<p>You can use <a href="https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+Trigger+Plugin" rel="noreferrer">Parameterized Trigger Plugin</a> which will let you pass parameters from one task to another.</p> <p>You need also add this parameter you passed from upstream in downstream.</p>
10,126,395
How to clone and change id?
<p>I need to clone the id and then add a number after it like so <code>id1</code>, <code>id2</code>, etc. Every time you hit clone you put the clone after the latest number of the id.</p> <pre><code>$(&quot;button&quot;).click(function() { $(&quot;#id&quot;).clone().after(&quot;#id&quot;); }); </code></pre>
10,127,093
6
0
null
2012-04-12 15:08:19.977 UTC
30
2021-06-17 06:24:15.597 UTC
2021-06-17 06:24:15.597 UTC
null
383,904
null
1,324,780
null
1
137
javascript|jquery|clone
205,083
<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>$('#cloneDiv').click(function(){ // get the last DIV which ID starts with ^= "klon" var $div = $('div[id^="klon"]:last'); // Read the Number from that DIV's ID (i.e: 3 from "klon3") // And increment that number by 1 var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1; // Clone it and assign the new ID (i.e: from num 4 to ID "klon4") var $klon = $div.clone().prop('id', 'klon'+num ); // Finally insert $klon wherever you want $div.after( $klon.text('klon'+num) ); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://code.jquery.com/jquery-3.1.0.js"&gt;&lt;/script&gt; &lt;button id="cloneDiv"&gt;CLICK TO CLONE&lt;/button&gt; &lt;div id="klon1"&gt;klon1&lt;/div&gt; &lt;div id="klon2"&gt;klon2&lt;/div&gt;</code></pre> </div> </div> </p> <hr> <h2>Scrambled elements, retrieve highest ID</h2> <p>Say you have many elements with IDs like <code>klon--5</code> but scrambled (not in order). Here we <strong>cannot</strong> go for <code>:last</code> or <code>:first</code>, therefore we need a mechanism to retrieve the highest ID:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const all = document.querySelectorAll('[id^="klon--"]'); const maxID = Math.max.apply(Math, [...all].map(el =&gt; +el.id.match(/\d+$/g)[0])); const nextId = maxID + 1; console.log(`New ID is: ${nextId}`);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="klon--12"&gt;12&lt;/div&gt; &lt;div id="klon--34"&gt;34&lt;/div&gt; &lt;div id="klon--8"&gt;8&lt;/div&gt;</code></pre> </div> </div> </p>
9,755,841
How can I change the version of npm using nvm?
<p>I've been using NVM to install the latest versions of Node.js for my Node.js work. It works totally fine for installing separate versions and switching between them. It also installs the latest version of NPM within each local .../bin folder along with the Node.js binary. However, there doesn't seem to be a way to switch the version of NPM that I'm using (or at least I can't figure it out).</p> <p>The only solution I can think of myself is to delete the binary that it's defaulting to (which is the NPM that was installed when I first installed node with NVM), and in its place to put the latest NPM binary. However, is there a better way to go about doing this?</p>
33,575,448
19
5
null
2012-03-18 03:49:55.893 UTC
99
2022-08-23 11:07:49.183 UTC
2022-08-09 19:32:15.34 UTC
null
63,550
null
798,491
null
1
432
node.js|npm
546,416
<p>As noted in <a href="https://stackoverflow.com/a/47519162/56817">another answer</a>, there is now a command for this:</p> <blockquote> <p>nvm now has a command to update npm. It's <code>nvm install-latest-npm</code> or <code>nvm install --latest-npm</code>.</p> </blockquote> <p><code>nvm install-latest-npm</code>: Attempt to upgrade to the latest working <code>npm</code> on the current Node.js version.</p> <p><code>nvm install --latest-npm</code>: After installing, attempt to upgrade to the latest working npm on the given Node.js version.</p> <p>Below are previous revisions of the correct answer to this question.</p> <p>For later versions of npm it is much simpler now. Just update the version that nvm installed, which lives in <code>~/.nvm/versions/node/[your-version]/lib/node_modules/npm</code>.</p> <p>I installed Node.js 4.2.2, which comes with npm 2.14.7, but I want to use npm 3. So I did:</p> <pre><code>cd ~/.nvm/versions/node/v4.2.2/lib npm install npm </code></pre> <p>Easy!</p> <p>And yes, this should work for any module, not just npm, that you want to be &quot;global&quot; for a specific version of node.</p> <hr /> <p>In a newer version, <code>npm -g</code> is smart and installs modules into the path above instead of the system global path.</p>
10,057,671
How does PHP 'foreach' actually work?
<p>Let me prefix this by saying that I know what <code>foreach</code> is, does and how to use it. This question concerns how it works under the bonnet, and I don't want any answers along the lines of "this is how you loop an array with <code>foreach</code>".</p> <hr> <p>For a long time I assumed that <code>foreach</code> worked with the array itself. Then I found many references to the fact that it works with a <em>copy</em> of the array, and I have since assumed this to be the end of the story. But I recently got into a discussion on the matter, and after a little experimentation found that this was not in fact 100% true.</p> <p>Let me show what I mean. For the following test cases, we will be working with the following array:</p> <pre><code>$array = array(1, 2, 3, 4, 5); </code></pre> <p><a href="http://codepad.org/7DIeObk9" rel="noreferrer">Test case 1</a>:</p> <pre><code>foreach ($array as $item) { echo "$item\n"; $array[] = $item; } print_r($array); /* Output in loop: 1 2 3 4 5 $array after loop: 1 2 3 4 5 1 2 3 4 5 */ </code></pre> <p>This clearly shows that we are not working directly with the source array - otherwise the loop would continue forever, since we are constantly pushing items onto the array during the loop. But just to be sure this is the case:</p> <p><a href="http://codepad.org/nirz6Ufh" rel="noreferrer">Test case 2</a>:</p> <pre><code>foreach ($array as $key =&gt; $item) { $array[$key + 1] = $item + 2; echo "$item\n"; } print_r($array); /* Output in loop: 1 2 3 4 5 $array after loop: 1 3 4 5 6 7 */ </code></pre> <p>This backs up our initial conclusion, we are working with a copy of the source array during the loop, otherwise we would see the modified values during the loop. <em>But...</em></p> <p>If we look in the <a href="http://php.net/manual/en/control-structures.foreach.php" rel="noreferrer">manual</a>, we find this statement:</p> <blockquote> <p>When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array.</p> </blockquote> <p>Right... this seems to suggest that <code>foreach</code> relies on the array pointer of the source array. But we've just proved that we're <em>not working with the source array</em>, right? Well, not entirely.</p> <p><a href="http://codepad.org/6n20ooMy" rel="noreferrer">Test case 3</a>:</p> <pre><code>// Move the array pointer on one to make sure it doesn't affect the loop var_dump(each($array)); foreach ($array as $item) { echo "$item\n"; } var_dump(each($array)); /* Output array(4) { [1]=&gt; int(1) ["value"]=&gt; int(1) [0]=&gt; int(0) ["key"]=&gt; int(0) } 1 2 3 4 5 bool(false) */ </code></pre> <p>So, despite the fact that we are not working directly with the source array, we are working directly with the source array pointer - the fact that the pointer is at the end of the array at the end of the loop shows this. Except this can't be true - if it was, then <a href="http://codepad.org/7DIeObk9" rel="noreferrer">test case 1</a> would loop forever.</p> <p>The PHP manual also states:</p> <blockquote> <p>As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.</p> </blockquote> <p>Well, let's find out what that "unexpected behavior" is (technically, any behavior is unexpected since I no longer know what to expect).</p> <p><a href="http://codepad.org/JJp79xSd" rel="noreferrer">Test case 4</a>:</p> <pre><code>foreach ($array as $key =&gt; $item) { echo "$item\n"; each($array); } /* Output: 1 2 3 4 5 */ </code></pre> <p><a href="http://codepad.org/IfwJyTCL" rel="noreferrer">Test case 5</a>:</p> <pre><code>foreach ($array as $key =&gt; $item) { echo "$item\n"; reset($array); } /* Output: 1 2 3 4 5 */ </code></pre> <p>...nothing that unexpected there, in fact it seems to support the "copy of source" theory.</p> <hr> <p><strong>The Question</strong></p> <p>What is going on here? My C-fu is not good enough for me to able to extract a proper conclusion simply by looking at the PHP source code, I would appreciate it if someone could translate it into English for me.</p> <p>It seems to me that <code>foreach</code> works with a <em>copy</em> of the array, but sets the array pointer of the source array to the end of the array after the loop.</p> <ul> <li>Is this correct and the whole story?</li> <li>If not, what is it really doing?</li> <li>Is there any situation where using functions that adjust the array pointer (<code>each()</code>, <code>reset()</code> et al.) during a <code>foreach</code> could affect the outcome of the loop?</li> </ul>
14,854,568
7
16
null
2012-04-07 19:33:57.893 UTC
781
2022-07-20 23:19:24.237 UTC
2016-12-27 02:52:11.407 UTC
null
383,779
null
889,949
null
1
2,229
php|loops|foreach|iteration|php-internals
446,144
<p><code>foreach</code> supports iteration over three different kinds of values:</p> <ul> <li>Arrays</li> <li>Normal objects</li> <li><a href="http://php.net/Traversable" rel="noreferrer"><code>Traversable</code></a> objects</li> </ul> <p>In the following, I will try to explain precisely how iteration works in different cases. By far the simplest case is <code>Traversable</code> objects, as for these <code>foreach</code> is essentially only syntax sugar for code along these lines:</p> <pre><code>foreach ($it as $k =&gt; $v) { /* ... */ } /* translates to: */ if ($it instanceof IteratorAggregate) { $it = $it-&gt;getIterator(); } for ($it-&gt;rewind(); $it-&gt;valid(); $it-&gt;next()) { $v = $it-&gt;current(); $k = $it-&gt;key(); /* ... */ } </code></pre> <p>For internal classes, actual method calls are avoided by using an internal API that essentially just mirrors the <code>Iterator</code> interface on the C level.</p> <p>Iteration of arrays and plain objects is significantly more complicated. First of all, it should be noted that in PHP "arrays" are really ordered dictionaries and they will be traversed according to this order (which matches the insertion order as long as you didn't use something like <code>sort</code>). This is opposed to iterating by the natural order of the keys (how lists in other languages often work) or having no defined order at all (how dictionaries in other languages often work).</p> <p>The same also applies to objects, as the object properties can be seen as another (ordered) dictionary mapping property names to their values, plus some visibility handling. In the majority of cases, the object properties are not actually stored in this rather inefficient way. However, if you start iterating over an object, the packed representation that is normally used will be converted to a real dictionary. At that point, iteration of plain objects becomes very similar to iteration of arrays (which is why I'm not discussing plain-object iteration much in here).</p> <p>So far, so good. Iterating over a dictionary can't be too hard, right? The problems begin when you realize that an array/object can change during iteration. There are multiple ways this can happen:</p> <ul> <li>If you iterate by reference using <code>foreach ($arr as &amp;$v)</code> then <code>$arr</code> is turned into a reference and you can change it during iteration.</li> <li>In PHP 5 the same applies even if you iterate by value, but the array was a reference beforehand: <code>$ref =&amp; $arr; foreach ($ref as $v)</code></li> <li>Objects have by-handle passing semantics, which for most practical purposes means that they behave like references. So objects can always be changed during iteration.</li> </ul> <p>The problem with allowing modifications during iteration is the case where the element you are currently on is removed. Say you use a pointer to keep track of which array element you are currently at. If this element is now freed, you are left with a dangling pointer (usually resulting in a segfault).</p> <p>There are different ways of solving this issue. PHP 5 and PHP 7 differ significantly in this regard and I'll describe both behaviors in the following. The summary is that PHP 5's approach was rather dumb and lead to all kinds of weird edge-case issues, while PHP 7's more involved approach results in more predictable and consistent behavior.</p> <p>As a last preliminary, it should be noted that PHP uses reference counting and copy-on-write to manage memory. This means that if you "copy" a value, you actually just reuse the old value and increment its reference count (refcount). Only once you perform some kind of modification a real copy (called a "duplication") will be done. See <a href="http://blog.golemon.com/2007/01/youre-being-lied-to.html" rel="noreferrer">You're being lied to</a> for a more extensive introduction on this topic.</p> <h2>PHP 5</h2> <h3>Internal array pointer and HashPointer</h3> <p>Arrays in PHP 5 have one dedicated "internal array pointer" (IAP), which properly supports modifications: Whenever an element is removed, there will be a check whether the IAP points to this element. If it does, it is advanced to the next element instead.</p> <p>While <code>foreach</code> does make use of the IAP, there is an additional complication: There is only one IAP, but one array can be part of multiple <code>foreach</code> loops:</p> <pre><code>// Using by-ref iteration here to make sure that it's really // the same array in both loops and not a copy foreach ($arr as &amp;$v1) { foreach ($arr as &amp;$v) { // ... } } </code></pre> <p>To support two simultaneous loops with only one internal array pointer, <code>foreach</code> performs the following shenanigans: Before the loop body is executed, <code>foreach</code> will back up a pointer to the current element and its hash into a per-foreach <code>HashPointer</code>. After the loop body runs, the IAP will be set back to this element if it still exists. If however the element has been removed, we'll just use wherever the IAP is currently at. This scheme mostly-kinda-sort of works, but there's a lot of weird behavior you can get out of it, some of which I'll demonstrate below.</p> <h3>Array duplication</h3> <p>The IAP is a visible feature of an array (exposed through the <code>current</code> family of functions), as such changes to the IAP count as modifications under copy-on-write semantics. This, unfortunately, means that <code>foreach</code> is in many cases forced to duplicate the array it is iterating over. The precise conditions are:</p> <ol> <li>The array is not a reference (is_ref=0). If it's a reference, then changes to it are <em>supposed</em> to propagate, so it should not be duplicated.</li> <li>The array has refcount>1. If <code>refcount</code> is 1, then the array is not shared and we're free to modify it directly.</li> </ol> <p>If the array is not duplicated (is_ref=0, refcount=1), then only its <code>refcount</code> will be incremented (*). Additionally, if <code>foreach</code> by reference is used, then the (potentially duplicated) array will be turned into a reference.</p> <p>Consider this code as an example where duplication occurs:</p> <pre><code>function iterate($arr) { foreach ($arr as $v) {} } $outerArr = [0, 1, 2, 3, 4]; iterate($outerArr); </code></pre> <p>Here, <code>$arr</code> will be duplicated to prevent IAP changes on <code>$arr</code> from leaking to <code>$outerArr</code>. In terms of the conditions above, the array is not a reference (is_ref=0) and is used in two places (refcount=2). This requirement is unfortunate and an artifact of the suboptimal implementation (there is no concern of modification during iteration here, so we don't really need to use the IAP in the first place).</p> <p>(*) Incrementing the <code>refcount</code> here sounds innocuous, but violates copy-on-write (COW) semantics: This means that we are going to modify the IAP of a refcount=2 array, while COW dictates that modifications can only be performed on refcount=1 values. This violation results in user-visible behavior change (while a COW is normally transparent) because the IAP change on the iterated array will be observable -- but only until the first non-IAP modification on the array. Instead, the three "valid" options would have been a) to always duplicate, b) do not increment the <code>refcount</code> and thus allowing the iterated array to be arbitrarily modified in the loop or c) don't use the IAP at all (the PHP 7 solution).</p> <h3>Position advancement order</h3> <p>There is one last implementation detail that you have to be aware of to properly understand the code samples below. The "normal" way of looping through some data structure would look something like this in pseudocode:</p> <pre><code>reset(arr); while (get_current_data(arr, &amp;data) == SUCCESS) { code(); move_forward(arr); } </code></pre> <p>However <code>foreach</code>, being a rather special snowflake, chooses to do things slightly differently:</p> <pre><code>reset(arr); while (get_current_data(arr, &amp;data) == SUCCESS) { move_forward(arr); code(); } </code></pre> <p>Namely, the array pointer is already moved forward <em>before</em> the loop body runs. This means that while the loop body is working on element <code>$i</code>, the IAP is already at element <code>$i+1</code>. This is the reason why code samples showing modification during iteration will always <code>unset</code> the <em>next</em> element, rather than the current one.</p> <h3>Examples: Your test cases</h3> <p>The three aspects described above should provide you with a mostly complete impression of the idiosyncrasies of the <code>foreach</code> implementation and we can move on to discuss some examples. </p> <p>The behavior of your test cases is simple to explain at this point:</p> <ul> <li><p>In test cases 1 and 2 <code>$array</code> starts off with refcount=1, so it will not be duplicated by <code>foreach</code>: Only the <code>refcount</code> is incremented. When the loop body subsequently modifies the array (which has refcount=2 at that point), the duplication will occur at that point. Foreach will continue working on an unmodified copy of <code>$array</code>.</p></li> <li><p>In test case 3, once again the array is not duplicated, thus <code>foreach</code> will be modifying the IAP of the <code>$array</code> variable. At the end of the iteration, the IAP is NULL (meaning iteration has done), which <code>each</code> indicates by returning <code>false</code>.</p></li> <li><p>In test cases 4 and 5 both <code>each</code> and <code>reset</code> are by-reference functions. The <code>$array</code> has a <code>refcount=2</code> when it is passed to them, so it has to be duplicated. As such <code>foreach</code> will be working on a separate array again.</p></li> </ul> <h3>Examples: Effects of <code>current</code> in foreach</h3> <p>A good way to show the various duplication behaviors is to observe the behavior of the <code>current()</code> function inside a <code>foreach</code> loop. Consider this example:</p> <pre><code>foreach ($array as $val) { var_dump(current($array)); } /* Output: 2 2 2 2 2 */ </code></pre> <p>Here you should know that <code>current()</code> is a by-ref function (actually: prefer-ref), even though it does not modify the array. It has to be in order to play nice with all the other functions like <code>next</code> which are all by-ref. By-reference passing implies that the array has to be separated and thus <code>$array</code> and the <code>foreach-array</code> will be different. The reason you get <code>2</code> instead of <code>1</code> is also mentioned above: <code>foreach</code> advances the array pointer <em>before</em> running the user code, not after. So even though the code is at the first element, <code>foreach</code> already advanced the pointer to the second.</p> <p>Now lets try a small modification:</p> <pre><code>$ref = &amp;$array; foreach ($array as $val) { var_dump(current($array)); } /* Output: 2 3 4 5 false */ </code></pre> <p>Here we have the is_ref=1 case, so the array is not copied (just like above). But now that it is a reference, the array no longer has to be duplicated when passing to the by-ref <code>current()</code> function. Thus <code>current()</code> and <code>foreach</code> work on the same array. You still see the off-by-one behavior though, due to the way <code>foreach</code> advances the pointer.</p> <p>You get the same behavior when doing by-ref iteration:</p> <pre><code>foreach ($array as &amp;$val) { var_dump(current($array)); } /* Output: 2 3 4 5 false */ </code></pre> <p>Here the important part is that foreach will make <code>$array</code> an is_ref=1 when it is iterated by reference, so basically you have the same situation as above.</p> <p>Another small variation, this time we'll assign the array to another variable:</p> <pre><code>$foo = $array; foreach ($array as $val) { var_dump(current($array)); } /* Output: 1 1 1 1 1 */ </code></pre> <p>Here the refcount of the <code>$array</code> is 2 when the loop is started, so for once we actually have to do the duplication upfront. Thus <code>$array</code> and the array used by foreach will be completely separate from the outset. That's why you get the position of the IAP wherever it was before the loop (in this case it was at the first position).</p> <h3>Examples: Modification during iteration</h3> <p>Trying to account for modifications during iteration is where all our foreach troubles originated, so it serves to consider some examples for this case.</p> <p>Consider these nested loops over the same array (where by-ref iteration is used to make sure it really is the same one):</p> <pre><code>foreach ($array as &amp;$v1) { foreach ($array as &amp;$v2) { if ($v1 == 1 &amp;&amp; $v2 == 1) { unset($array[1]); } echo "($v1, $v2)\n"; } } // Output: (1, 1) (1, 3) (1, 4) (1, 5) </code></pre> <p>The expected part here is that <code>(1, 2)</code> is missing from the output because element <code>1</code> was removed. What's probably unexpected is that the outer loop stops after the first element. Why is that?</p> <p>The reason behind this is the nested-loop hack described above: Before the loop body runs, the current IAP position and hash is backed up into a <code>HashPointer</code>. After the loop body it will be restored, but only if the element still exists, otherwise the current IAP position (whatever it may be) is used instead. In the example above this is exactly the case: The current element of the outer loop has been removed, so it will use the IAP, which has already been marked as finished by the inner loop!</p> <p>Another consequence of the <code>HashPointer</code> backup+restore mechanism is that changes to the IAP through <code>reset()</code> etc. usually do not impact <code>foreach</code>. For example, the following code executes as if the <code>reset()</code> were not present at all:</p> <pre><code>$array = [1, 2, 3, 4, 5]; foreach ($array as &amp;$value) { var_dump($value); reset($array); } // output: 1, 2, 3, 4, 5 </code></pre> <p>The reason is that, while <code>reset()</code> temporarily modifies the IAP, it will be restored to the current foreach element after the loop body. To force <code>reset()</code> to make an effect on the loop, you have to additionally remove the current element, so that the backup/restore mechanism fails:</p> <pre><code>$array = [1, 2, 3, 4, 5]; $ref =&amp; $array; foreach ($array as $value) { var_dump($value); unset($array[1]); reset($array); } // output: 1, 1, 3, 4, 5 </code></pre> <p>But, those examples are still sane. The real fun starts if you remember that the <code>HashPointer</code> restore uses a pointer to the element and its hash to determine whether it still exists. But: Hashes have collisions, and pointers can be reused! This means that, with a careful choice of array keys, we can make <code>foreach</code> believe that an element that has been removed still exists, so it will jump directly to it. An example:</p> <pre><code>$array = ['EzEz' =&gt; 1, 'EzFY' =&gt; 2, 'FYEz' =&gt; 3]; $ref =&amp; $array; foreach ($array as $value) { unset($array['EzFY']); $array['FYFY'] = 4; reset($array); var_dump($value); } // output: 1, 4 </code></pre> <p>Here we should normally expect the output <code>1, 1, 3, 4</code> according to the previous rules. How what happens is that <code>'FYFY'</code> has the same hash as the removed element <code>'EzFY'</code>, and the allocator happens to reuse the same memory location to store the element. So foreach ends up directly jumping to the newly inserted element, thus short-cutting the loop.</p> <h3>Substituting the iterated entity during the loop</h3> <p>One last odd case that I'd like to mention, it is that PHP allows you to substitute the iterated entity during the loop. So you can start iterating on one array and then replace it with another array halfway through. Or start iterating on an array and then replace it with an object:</p> <pre><code>$arr = [1, 2, 3, 4, 5]; $obj = (object) [6, 7, 8, 9, 10]; $ref =&amp; $arr; foreach ($ref as $val) { echo "$val\n"; if ($val == 3) { $ref = $obj; } } /* Output: 1 2 3 6 7 8 9 10 */ </code></pre> <p>As you can see in this case PHP will just start iterating the other entity from the start once the substitution has happened.</p> <h2>PHP 7</h2> <h3>Hashtable iterators</h3> <p>If you still remember, the main problem with array iteration was how to handle removal of elements mid-iteration. PHP 5 used a single internal array pointer (IAP) for this purpose, which was somewhat suboptimal, as one array pointer had to be stretched to support multiple simultaneous foreach loops <em>and</em> interaction with <code>reset()</code> etc. on top of that.</p> <p>PHP 7 uses a different approach, namely, it supports creating an arbitrary amount of external, safe hashtable iterators. These iterators have to be registered in the array, from which point on they have the same semantics as the IAP: If an array element is removed, all hashtable iterators pointing to that element will be advanced to the next element.</p> <p>This means that <code>foreach</code> will no longer use the IAP <strong>at all</strong>. The <code>foreach</code> loop will be absolutely no effect on the results of <code>current()</code> etc. and its own behavior will never be influenced by functions like <code>reset()</code> etc.</p> <h3>Array duplication</h3> <p>Another important change between PHP 5 and PHP 7 relates to array duplication. Now that the IAP is no longer used, by-value array iteration will only do a <code>refcount</code> increment (instead of duplication the array) in all cases. If the array is modified during the <code>foreach</code> loop, at that point a duplication will occur (according to copy-on-write) and <code>foreach</code> will keep working on the old array.</p> <p>In most cases, this change is transparent and has no other effect than better performance. However, there is one occasion where it results in different behavior, namely the case where the array was a reference beforehand:</p> <pre><code>$array = [1, 2, 3, 4, 5]; $ref = &amp;$array; foreach ($array as $val) { var_dump($val); $array[2] = 0; } /* Old output: 1, 2, 0, 4, 5 */ /* New output: 1, 2, 3, 4, 5 */ </code></pre> <p>Previously by-value iteration of reference-arrays was special cases. In this case, no duplication occurred, so all modifications of the array during iteration would be reflected by the loop. In PHP 7 this special case is gone: A by-value iteration of an array will <strong>always</strong> keep working on the original elements, disregarding any modifications during the loop.</p> <p>This, of course, does not apply to by-reference iteration. If you iterate by-reference all modifications will be reflected by the loop. Interestingly, the same is true for by-value iteration of plain objects:</p> <pre><code>$obj = new stdClass; $obj-&gt;foo = 1; $obj-&gt;bar = 2; foreach ($obj as $val) { var_dump($val); $obj-&gt;bar = 42; } /* Old and new output: 1, 42 */ </code></pre> <p>This reflects the by-handle semantics of objects (i.e. they behave reference-like even in by-value contexts).</p> <h3>Examples</h3> <p>Let's consider a few examples, starting with your test cases:</p> <ul> <li><p>Test cases 1 and 2 retain the same output: By-value array iteration always keep working on the original elements. (In this case, even <code>refcounting</code> and duplication behavior is exactly the same between PHP 5 and PHP 7).</p></li> <li><p>Test case 3 changes: <code>Foreach</code> no longer uses the IAP, so <code>each()</code> is not affected by the loop. It will have the same output before and after.</p></li> <li><p>Test cases 4 and 5 stay the same: <code>each()</code> and <code>reset()</code> will duplicate the array before changing the IAP, while <code>foreach</code> still uses the original array. (Not that the IAP change would have mattered, even if the array was shared.)</p></li> </ul> <p>The second set of examples was related to the behavior of <code>current()</code> under different <code>reference/refcounting</code> configurations. This no longer makes sense, as <code>current()</code> is completely unaffected by the loop, so its return value always stays the same.</p> <p>However, we get some interesting changes when considering modifications during iteration. I hope you will find the new behavior saner. The first example:</p> <pre><code>$array = [1, 2, 3, 4, 5]; foreach ($array as &amp;$v1) { foreach ($array as &amp;$v2) { if ($v1 == 1 &amp;&amp; $v2 == 1) { unset($array[1]); } echo "($v1, $v2)\n"; } } // Old output: (1, 1) (1, 3) (1, 4) (1, 5) // New output: (1, 1) (1, 3) (1, 4) (1, 5) // (3, 1) (3, 3) (3, 4) (3, 5) // (4, 1) (4, 3) (4, 4) (4, 5) // (5, 1) (5, 3) (5, 4) (5, 5) </code></pre> <p>As you can see, the outer loop no longer aborts after the first iteration. The reason is that both loops now have entirely separate hashtable iterators, and there is no longer any cross-contamination of both loops through a shared IAP.</p> <p>Another weird edge case that is fixed now, is the odd effect you get when you remove and add elements that happen to have the same hash:</p> <pre><code>$array = ['EzEz' =&gt; 1, 'EzFY' =&gt; 2, 'FYEz' =&gt; 3]; foreach ($array as &amp;$value) { unset($array['EzFY']); $array['FYFY'] = 4; var_dump($value); } // Old output: 1, 4 // New output: 1, 3, 4 </code></pre> <p>Previously the HashPointer restore mechanism jumped right to the new element because it "looked" like it's the same as the removed element (due to colliding hash and pointer). As we no longer rely on the element hash for anything, this is no longer an issue.</p>
7,928,364
How to import the Spring Framework sourcecode into an eclipse project?
<p>I wanted to pull in all the sourcecode from Spring into eclipse, but wasn't sure how to pull all those multiple projects into one eclipse project. Anyone know how to set this up?</p>
7,949,532
3
2
null
2011-10-28 11:03:01.52 UTC
8
2013-08-20 14:32:26.767 UTC
null
null
null
null
543,572
null
1
10
java|eclipse|spring
33,079
<p>See <a href="http://blog.springsource.com/2009/03/03/building-spring-3/" rel="nofollow">http://blog.springsource.com/2009/03/03/building-spring-3/</a></p>
7,705,548
MySQL - How can I always round up decimals?
<p>For instance I have the following value:</p> <p><code>0.000018</code></p> <p>This is 6 decimal places, but I want to round it up the nearest whole 4th decimal place, so that:</p> <p><code>0.000018 -&gt; 0.0001</code></p> <p>I've played with the round() funcction but if I simply use the round function:</p> <p><code>round(0.000018,4) = 0.0000</code></p> <p>When dealing with decimals for financial purposes, in this case one needs to round up and charge the customer instead of giving them a freebie! But <code>round()</code> will go round up or down depending on value, I need to consistently round up.</p> <p>Is there a simple way of doing this?</p>
7,705,576
3
3
null
2011-10-09 18:19:02.99 UTC
3
2016-01-08 15:08:44.443 UTC
2011-10-09 18:24:27.5 UTC
null
546,999
null
986,624
null
1
18
mysql|rounding
53,139
<p>You can use <a href="http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_ceil" rel="noreferrer">ceil (ceiling)</a>. It only rounds up, so you'll have to multiply with 10000, do the ceil and then divide the result again.</p> <p>So <code>ceil(0.000145* 10000) = ceil(1.45) = 2</code> Divide back and you'll have <code>0.0002</code></p> <p>EDIT: wait, wut? that doesn't work. I mean <code>FLOOR</code> obviously but the working is the same :D The manual is on the same page too :)</p> <p>So <code>floor(0.000145* 10000) = floor(1.45) = 1</code> Divide back and you'll have <code>0.0001</code></p>
8,019,957
DELETE ... FROM ... WHERE ... IN
<p>i'm looking for a way to delete records in table 1 with matching combinations in table 2 on 'stn' and 'jaar'. The contents of column 'jaar' in table2 is formatted in a previous stage/query by </p> <blockquote> <p>year(datum) AS 'jaar'</p> </blockquote> <p>Sorry, can't find again the site where i found this "solution".</p> <pre><code>DELETE FROM table1 WHERE stn, year(datum) IN (SELECT stn, jaar FROM table2); </code></pre>
8,020,458
3
2
null
2011-11-05 11:46:37.647 UTC
3
2015-04-16 16:00:49.7 UTC
2011-11-05 11:57:30.077 UTC
null
21,234
null
1,030,998
null
1
25
sql
116,004
<p>You can achieve this using <code>exists</code>:</p> <pre><code>DELETE FROM table1 WHERE exists( SELECT 1 FROM table2 WHERE table2.stn = table1.stn and table2.jaar = year(table1.datum) ) </code></pre>
11,909,304
WP -- Get posts by category?
<p>I'm using this in my page template to get posts by their category:</p> <pre><code>&lt;?php if (is_page(19)){ ?&gt; &lt;ul&gt; &lt;?php global $post; $args = array( 'category' =&gt; 'Testimonial' ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?&gt; &lt;li class="testimonial"&gt;&lt;?php the_content(); ?&gt;&lt;/li&gt;&lt;br/&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;?php } ?&gt; </code></pre> <p>but it's retrieving all posts instead. Not just the ones labeled Testimonial. Any idea what I'm doing wrong?</p>
11,909,320
5
1
null
2012-08-10 21:10:15.483 UTC
3
2021-10-26 09:20:33.29 UTC
null
null
null
null
1,210,614
null
1
20
php|wordpress
112,939
<p>Check here : <a href="https://developer.wordpress.org/reference/functions/get_posts/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/functions/get_posts/</a></p> <blockquote> <p>Note: The category parameter needs to be the ID of the category, and not the category name.</p> </blockquote>
11,777,908
Strict Standards: Only variables should be assigned by reference PHP 5.4
<p>I upgraded my PHP version to 5.4 (<a href="https://en.wikipedia.org/wiki/XAMPP" rel="nofollow noreferrer">XAMPP</a> 1.7.3 to 1.8.0). Now I see <em>Strict Standards</em> error, for <code>myDBconnection</code>:</p> <blockquote> <p>Strict Standards: Only variables should be assigned by reference in C:\xampp\htdocs\alous\include\dbconn.php on line 4</p> </blockquote> <h3>dbconn.php:</h3> <pre><code>&lt;?php defined('_VALID') or die('Restricted Access!'); $conn = &amp;ADONewConnection($config['db_type']); // &lt;--- This Line 4 if ( !$conn-&gt;Connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name'])) { echo 'Could not connect to MySQL! Please check your database settings!'; die(); } $conn-&gt;execute(&quot;SET NAMES 'utf8'&quot;); ?&gt; </code></pre> <p><em>Note:</em> I don't need to disable Strict Standards in php.ini with this method <code>error_reporting = E_ALL &amp; ~E_NOTICE &amp; ~E_STRICT</code>! I want to fix my PHP code.</p>
11,778,004
2
1
null
2012-08-02 12:56:34.41 UTC
6
2020-04-14 18:31:56.803 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,313,483
null
1
47
php|reference|porting
128,857
<p>You should remove the <code>&amp;</code> (ampersand) symbol, so that line 4 will look like this:</p> <pre><code>$conn = ADONewConnection($config['db_type']); </code></pre> <p>This is because ADONewConnection already returns an object by reference. As per <a href="http://php.net/manual/en/language.operators.assignment.php" rel="nofollow noreferrer">documentation</a>, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0</p>
11,855,428
NuGet Assembly outside lib folder
<p>I'm going to bang out a couple of questions here...first, with NuGet is it possible to create a package from a few DLLs? There is no visual studio project, just the command line and a couple of pre-compiled DLL files. </p> <p>Second, assuming that is possible, why do I continuously get the "Assembly outside of the lib folder" warning? I've tried everything I can think of to get associated assemblies to add themselves as references inside of the NuGet package. </p> <p>My file structure looks like this</p> <pre><code> Root - File1.dll - lib - File2.dll - File3.dll </code></pre> <p>When I tell NuGet to pack it using a .nuspec like this</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;package &gt; &lt;metadata&gt; &lt;id&gt;File1.dll&lt;/id&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;authors&gt;thisguy&lt;/authors&gt; &lt;owners&gt;thisguysmom&lt;/owners&gt; &lt;requireLicenseAcceptance&gt;false&lt;/requireLicenseAcceptance&gt; &lt;description&gt;This is some library&lt;/description&gt; &lt;releaseNotes&gt;Porting to NuGet&lt;/releaseNotes&gt; &lt;copyright&gt;Copyright 2012&lt;/copyright&gt; &lt;references&gt; &lt;reference file="File2.dll" /&gt; &lt;reference file="File3.dll" /&gt; &lt;/references&gt; &lt;/metadata&gt; &lt;/package&gt; </code></pre> <p>I receive that warning. From what I'm reading, I shouldn't even have to define the references node in any of my projects, as the lib folder items should automatically be added as references?</p> <p>Does anyone out there understand this NuGet mess?</p>
11,855,756
8
0
null
2012-08-07 23:14:37.803 UTC
10
2018-09-21 13:59:34.49 UTC
null
null
null
null
129,682
null
1
57
nuget|nuget-package
51,130
<p>Any dll that you want referenced should be under the lib folder. The warning is because file1.dll is outside lib and will be ignored during package installation. (Other special folder are "content" and "tools")</p> <p>I'd used this structure : </p> <pre><code>Root - lib - File1.dll - File2.dll - File3.dll </code></pre> <p>See : <a href="http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package#Package_Conventions" rel="noreferrer">http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package#Package_Conventions</a> for additional details.</p>
11,862,315
Changing the color of the title bar in WinForm
<p>Is it possible to change the color of the title bar of a WinForm in C#?</p> <pre><code> __________________________ [Form1_______________-|[]|X] &lt;- I want to change the color of this | | | | | | |__________________________| </code></pre>
12,017,003
5
7
null
2012-08-08 10:13:12.183 UTC
14
2022-06-21 08:09:17.173 UTC
2022-01-31 13:36:08.863 UTC
null
792,066
null
1,484,603
null
1
59
c#|.net|winforms
99,553
<p>I solved this problem. This is the code:</p> <pre><code>[DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("User32.dll")] private static extern IntPtr GetWindowDC(IntPtr hWnd); protected override void WndProc(ref Message m) { base.WndProc(ref m); const int WM_NCPAINT = 0x85; if (m.Msg == WM_NCPAINT) { IntPtr hdc = GetWindowDC(m.HWnd); if ((int)hdc != 0) { Graphics g = Graphics.FromHdc(hdc); g.FillRectangle(Brushes.Green, new Rectangle(0, 0, 4800, 23)); g.Flush(); ReleaseDC(m.HWnd, hdc); } } } </code></pre>
12,032,214
Print new output on same line
<p>I want to print the looped output to the screen on the same line.</p> <p>How do I this in the simplest way for Python 3.x</p> <p>I know this question has been asked for Python 2.7 by using a comma at the end of the line i.e. print I, but I can't find a solution for Python 3.x.</p> <pre><code>i = 0 while i &lt;10: i += 1 ## print (i) # python 2.7 would be print i, print (i) # python 2.7 would be 'print i,' </code></pre> <p>Screen output.</p> <pre><code>1 2 3 4 5 6 7 8 9 10 </code></pre> <hr> <p>What I want to print is: </p> <pre><code>12345678910 </code></pre> <p>New readers visit this link aswell <a href="http://docs.python.org/release/3.0.1/whatsnew/3.0.html" rel="noreferrer">http://docs.python.org/release/3.0.1/whatsnew/3.0.html</a></p>
12,032,234
7
2
null
2012-08-20 04:15:23.62 UTC
32
2020-01-16 15:35:43.047 UTC
2016-11-10 15:56:21.343 UTC
null
4,099,593
null
1,188,381
null
1
114
python|python-3.x|printing
422,742
<p>From <code>help(print)</code>:</p> <pre><code>Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. </code></pre> <p>You can use the <code>end</code> keyword:</p> <pre><code>&gt;&gt;&gt; for i in range(1, 11): ... print(i, end='') ... 12345678910&gt;&gt;&gt; </code></pre> <p>Note that you'll have to <code>print()</code> the final newline yourself. BTW, you won't get "12345678910" in Python 2 with the trailing comma, you'll get <code>1 2 3 4 5 6 7 8 9 10</code> instead.</p>