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
25,838,411
Can't prove that singleton types are singleton types while generating type class instance
<p>Suppose I've got a type class that proves that all the types in a Shapeless coproduct are singleton types:</p> <pre><code>import shapeless._ trait AllSingletons[A, C &lt;: Coproduct] { def values: List[A] } object AllSingletons { implicit def cnilSingletons[A]: AllSingletons[A, CNil] = new AllSingletons[A, CNil] { def values = Nil } implicit def coproductSingletons[A, H &lt;: A, T &lt;: Coproduct](implicit tsc: AllSingletons[A, T], witness: Witness.Aux[H] ): AllSingletons[A, H :+: T] = new AllSingletons[A, H :+: T] { def values = witness.value :: tsc.values } } </code></pre> <p>We can show that it works with a simple ADT:</p> <pre><code>sealed trait Foo case object Bar extends Foo case object Baz extends Foo </code></pre> <p>And then:</p> <pre><code>scala&gt; implicitly[AllSingletons[Foo, Bar.type :+: Baz.type :+: CNil]].values res0: List[Foo] = List(Bar, Baz) </code></pre> <p>Now we want to combine this with Shapeless's <code>Generic</code> mechanism that'll give us a coproduct representation of our ADT:</p> <pre><code>trait EnumerableAdt[A] { def values: Set[A] } object EnumerableAdt { implicit def fromAllSingletons[A, C &lt;: Coproduct](implicit gen: Generic.Aux[A, C], singletons: AllSingletons[A, C] ): EnumerableAdt[A] = new EnumerableAdt[A] { def values = singletons.values.toSet } } </code></pre> <p>I'd expect <code>implicitly[EnumerableAdt[Foo]]</code> to work, but it doesn't. We can use <code>-Xlog-implicits</code> to get some information about why:</p> <pre><code>&lt;console&gt;:17: shapeless.this.Witness.apply is not a valid implicit value for shapeless.Witness.Aux[Baz.type] because: Type argument Baz.type is not a singleton type implicitly[EnumerableAdt[Foo]] ^ &lt;console&gt;:17: this.AllSingletons.coproductSingletons is not a valid implicit value for AllSingletons[Foo,shapeless.:+:[Baz.type,shapeless.CNil]] because: hasMatchingSymbol reported error: could not find implicit value for parameter witness: shapeless.Witness.Aux[Baz.type] implicitly[EnumerableAdt[Foo]] ^ &lt;console&gt;:17: this.AllSingletons.coproductSingletons is not a valid implicit value for AllSingletons[Foo,this.Repr] because: hasMatchingSymbol reported error: could not find implicit value for parameter tsc: AllSingletons[Foo,shapeless.:+:[Baz.type,shapeless.CNil]] implicitly[EnumerableAdt[Foo]] ^ &lt;console&gt;:17: this.EnumerableAdt.fromAllSingletons is not a valid implicit value for EnumerableAdt[Foo] because: hasMatchingSymbol reported error: could not find implicit value for parameter singletons: AllSingletons[Foo,C] implicitly[EnumerableAdt[Foo]] ^ &lt;console&gt;:17: error: could not find implicit value for parameter e: EnumerableAdt[Foo] implicitly[EnumerableAdt[Foo]] ^ </code></pre> <p><code>Baz.type</code> obviously <em>is</em> a singleton type, though. We can try putting the <code>Witness</code> instances in scope manually just for fun:</p> <pre><code>implicit val barSingleton = Witness[Bar.type] implicit val bazSingleton = Witness[Baz.type] </code></pre> <p>And somehow now it works:</p> <pre><code>scala&gt; implicitly[EnumerableAdt[Foo]].values res1: Set[Foo] = Set(Bar, Baz) </code></pre> <p>I don't understand why these instances would work in this context while the ones generated by the <code>Witness.apply</code> macro method (which we used to create them) don't. What's going on here? Is there a convenient workaround that doesn't require us to enumerate the constructors manually?</p>
27,909,266
1
7
null
2014-09-14 21:58:15.447 UTC
12
2015-01-12 19:24:02.993 UTC
null
null
null
null
334,519
null
1
52
scala|shapeless|implicits|singleton-type
3,695
<p>This works as written as of the most recent shapeless 2.1.0-SNAPSHOT.</p>
10,248,649
Sending Data through Headphone jack in Android phones
<p>I'm currently dealing with a new project and I have to send data through headphone jack with specific voltage, then i can work on that voltage.</p> <p>so here i need to program the specific voltage depends on my data. is it possible that i can access the output voltage of headphones in android and then create a application to control that voltage?</p>
10,252,629
4
5
null
2012-04-20 14:58:12.693 UTC
11
2021-05-09 02:46:52.923 UTC
2016-01-03 19:31:33.743 UTC
null
877,329
null
1,229,388
null
1
14
android|headphones
38,265
<p>Here is a HackADay article dealing with this issue. <a href="http://hackaday.com/2010/02/01/android-audio-serial-connection/" rel="nofollow noreferrer">http://hackaday.com/2010/02/01/android-audio-serial-connection/</a> It offers working code which was quite a bit simpler than I thought it would be.</p> <p>Although, like others have suggested, including <a href="https://stackoverflow.com/a/7956506/374866">this</a> very similar SO post, you might have an easier time using the USB port.</p>
9,853,096
Proguard with OrmLite on Android
<p>How should I use proguard with ormlite library on Android?</p> <p>Trying this:</p> <pre><code>-keep class com.j256.** -keepclassmembers class com.j256.** -keep enum com.j256.** -keepclassmembers enum com.j256.** -keep interface com.j256.** -keepclassmembers interface com.j256.** </code></pre> <p>But I get:</p> <blockquote> <p>03-23 20:23:54.518: E/AndroidRuntime(3032): java.lang.RuntimeException: Unable to start activity ComponentInfo{cz.eman.android.cepro/cz.eman.android.cepro.activity.StationsOverviewActivity}: java.lang.IllegalStateException: Could not find constructor that takes a Context argument for helper class class kb</p> </blockquote> <p>I also tried to add this:</p> <pre><code>-keepclassmembers class * { public &lt;init&gt;(android.content.​Context); } </code></pre> <p>But I get another classmembers errors.</p>
10,281,236
8
5
null
2012-03-24 15:55:08.06 UTC
10
2017-11-10 08:56:20.4 UTC
2012-03-24 16:32:10.553 UTC
null
539,284
null
539,284
null
1
23
android|optimization|obfuscation|proguard|ormlite
11,689
<p>Thank you a lot for posts like this that help us to advance step by step.</p> <p>I've came up with other solution after i have tried the last one without success:</p> <pre><code># OrmLite uses reflection -keep class com.j256.** -keepclassmembers class com.j256.** { *; } -keep enum com.j256.** -keepclassmembers enum com.j256.** { *; } -keep interface com.j256.** -keepclassmembers interface com.j256.** { *; } </code></pre> <p>I hope it can help someone.</p>
9,695,115
Android borderless buttons
<p>I hate to be the third person to ask this, but the previous <a href="https://stackoverflow.com/questions/8855791/how-to-create-standard-borderless-buttons-like-in-the-design-guidline-mentioned">two</a> <a href="https://stackoverflow.com/questions/9167900/how-to-create-borderless-buttons-in-android">askings</a> haven't seemed to answer it fully. The android design guidelines detail <a href="http://developer.android.com/design/building-blocks/buttons.html" rel="noreferrer">borderless buttons</a>, but not how to make them. In one of the previous answers, there was a sugestion to use:</p> <p><code>style="@android:style/Widget.Holo.Button.Borderless"</code></p> <p>This works well for a Holo theme, but I use a lot of Holo.Light as well and </p> <p><code>style="@android:style/Widget.Holo.Light.Button.Borderless"</code></p> <p>Does not seem to exist. Is there a way to apply a style for such borderless buttons in Holo.Light, or better yet, simply apply a borderless tag without specifying which theme it belongs in, so the app can pick the proper style at runtime?</p> <p>Holo.ButtonBar seems to fit the bill for what I am looking for, except it provides no user feedback that it's been pressed.</p> <p>Also, is there a place in the documentation that lists such styles that can be applied and a description of them? No matter how much I google, and search through the docs, I can't find anything. There is just a non-descriptive list if I right click and edit style.</p> <p>Any help would be appreciated.</p> <p>Edit: Got a perfect answer from javram, and I wanted to add some XML for anyone interested in adding the partial borders google has adopted.</p> <p>Fora horizontal divider, this works great</p> <pre><code>&lt;View android:id="@+id/horizontal_divider_login" android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:background="@color/holo_blue" /&gt; </code></pre> <p>and this for a vertical one:</p> <pre><code>&lt;View android:id="@+id/vertical_divider" android:layout_width="1dip" android:layout_height="match_parent" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:background="@color/holo_blue" /&gt; </code></pre>
9,951,456
5
0
null
2012-03-14 02:26:12.87 UTC
9
2016-06-03 06:03:08.097 UTC
2017-05-23 12:34:21.327 UTC
null
-1
null
1,217,736
null
1
26
android|view|styles
41,218
<p>Check out my answer <a href="https://stackoverflow.com/a/9951394/780271">here</a>. In a nutshell the correct solution is to use the following:</p> <pre><code>android:background="?android:attr/selectableItemBackground" </code></pre>
9,990,117
How do I use the CoffeeScript existential operator to check some object properties for undefined?
<p>I would like to use the CoffeeScript existential operator to check some object properties for undefined. However, I encountered a little problem.</p> <p>Code like this:</p> <pre><code>console.log test if test? </code></pre> <p>Compiles to:</p> <pre><code>if (typeof test !== "undefined" &amp;&amp; test !== null) console.log(test); </code></pre> <p>Which is the behavior I would like to see. However, when I try using it against object properties, like this:</p> <pre><code>console.log test.test if test.test? </code></pre> <p>I get something like that:</p> <pre><code>if (test.test != null) console.log(test.test); </code></pre> <p>Which desn't look like a check against undefined at all. The only way I could have achieved the same (1:1) behavior as using it for objects was by using a larger check:</p> <pre><code>console.log test.test if typeof test.test != "undefined" and test.test != null </code></pre> <p>The question is - am I doing something wrong? Or is the compiled code what is enough to check for existence of a property (a null check with type conversion)?</p>
9,995,425
3
3
null
2012-04-03 09:01:02.087 UTC
13
2016-11-04 17:15:38.433 UTC
2016-11-04 17:15:38.433 UTC
null
479,863
null
940,569
null
1
30
coffeescript|existential-operator
15,011
<p>This is a common point of confusion with the existential operator: Sometimes</p> <pre><code>x? </code></pre> <p>compiles to</p> <pre><code>typeof test !== "undefined" &amp;&amp; test !== null </code></pre> <p>and other times it just compiles to</p> <pre><code>x != null </code></pre> <p><em>The two are equivalent,</em> because <code>x != null</code> will be <code>false</code> when <code>x</code> is either <code>null</code> or <code>undefined</code>. So <code>x != null</code> is a more compact way of expressing <code>(x !== undefined &amp;&amp; x !== null)</code>. The reason the <code>typeof</code> compilation occurs is that the compiler thinks <code>x</code> may not have been defined at all, in which case doing an equality test would trigger <code>ReferenceError: x is not defined</code>.</p> <p>In your particular case, <code>test.test</code> may have the value <code>undefined</code>, but you can't get a <code>ReferenceError</code> by referring to an undefined property on an existing object, so the compiler opts for the shorter output.</p>
28,241,500
Can't Create Entity Data Model - using MySql and EF6
<p>I'm trying to add an edmx Entity model to my C#/Web Project in Visual Studio 2013. My problem is that the file is not created.</p> <p>I do the following steps:</p> <ol> <li>Give the item a name</li> <li>Choose 'EF Designer from database'</li> <li>Choose the connection from the drop down (localhost) that already tested successfully connecting to MySQL databse</li> <li>The "Save connection settings in webc.config as" option is checked</li> <li>I click 'Next' AND the window disappeared and I get back to the code window</li> </ol> <p><strong>No edmx file is created.</strong> (although it works with SQL Server, but not for MySQL)</p> <p>I have <code>Entity Framework 6.1.2</code> installed, <code>MySql.Data</code>, <code>MySql.Data.Entities</code>, <code>MySql.Data.Entity</code>, <code>MySql.Web</code> -- all installed.</p> <p>I also rebuilt the project before trying to add an entity model file.</p> <p>I've installed the latest MySQL package with the latest <code>.NET connector</code>. </p> <p>Running: Visual Studio 2013 on Windows 7.</p> <p>Any ideas how to solve this?</p>
37,419,999
13
5
null
2015-01-30 17:34:35.227 UTC
18
2021-07-10 04:12:39.503 UTC
2015-01-30 17:40:16.367 UTC
null
865,939
null
865,939
null
1
28
mysql|entity-framework|visual-studio-2013|mysql-connector|ado.net-entity-data-model
51,981
<p>I solved this issue by following some steps below:</p> <ol> <li><p>Uninstall <code>MySql.Data.Entities</code> from Nuget by using command below in Package Manager Console: <code>Uninstall-Package MySql.Data.Entities</code></p></li> <li><p>Add project reference to the latest <code>MySql.Data.Entity.EF6.dll</code> from your MySql connector installation path at: <code>C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5</code></p></li> </ol>
7,871,569
How to change the datagridView Header color
<p>Now the datagridView Header Background color is showing in Gray. I want to change to differenct color. </p> <p>I Changed the background color in <code>ColumnHeaderDefaultCellStyle</code>, but nothing changed.</p> <p>How to do this.</p>
7,871,591
3
3
null
2011-10-24 05:23:27.783 UTC
2
2018-11-28 21:50:04.133 UTC
2011-10-24 05:43:54.733 UTC
null
621,013
null
128,071
null
1
6
vb.net|winforms|visual-studio
72,394
<p>In datagridView you can change the Header color by using <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcellstyle.aspx#Y1708" rel="nofollow noreferrer">DataGridViewCellStyle</a>, see the following code</p> <pre><code> ' Set the selection background color for all the cells. dataGridView1.DefaultCellStyle.SelectionBackColor = Color.White dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black ' Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default ' value won't override DataGridView.DefaultCellStyle.SelectionBackColor. dataGridView1.RowHeadersDefaultCellStyle.SelectionBackColor = Color.Empty ' Set the background color for all rows and for alternating rows. ' The value for alternating rows overrides the value for all rows. dataGridView1.RowsDefaultCellStyle.BackColor = Color.LightGray dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkGray ' Set the row and column header styles. dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Black dataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.Black </code></pre> <p>EDIT:</p> <p>Using the DataGridViewCellStyle, your header color will changes but a seperator for columns in the header section will not appear. So, heres a overrided event of OnPaint Event Handler have a look at <a href="https://stackoverflow.com/questions/2067942/data-grid-view-header-grid-color">this</a></p>
12,034,357
does Alarm Manager persist even after reboot?
<p>I am really new to android, I have been researching about alarms. I want to alarm if there is a birthday on that day. I've have used alarm manager. I was confused because i have read that it clears after reboot. I don't have an android phone so I'm just using the emulator.</p> <p>Here's my code :</p> <pre><code>public void schedAlarm() { AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); Intent intent = new Intent(this, AlarmService.class); pendingIntent = PendingIntent.getBroadcast(this, contact.id, intent, PendingIntent.FLAG_ONE_SHOT); am.setRepeating(AlarmManager.RTC, timetoAlarm, nextalarm, pendingIntent); } </code></pre> <p>I made this BroadcastRecever in replace for AlarmSerivce Here :</p> <pre><code>public void onReceive(Context context, Intent intent) { nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); CharSequence from = "It Birthday!"; CharSequence message =" Greet your friend."; PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0); Notification notif = new Notification(R.drawable.ic_launcher, "Birthday", System.currentTimeMillis()); notif.setLatestEventInfo(context, from, message, contentIntent); nm.notify(1, notif); } </code></pre> <p>is this enough??</p>
12,034,402
3
1
null
2012-08-20 08:22:35.88 UTC
18
2021-11-27 20:24:52.187 UTC
2012-08-20 08:49:54.427 UTC
null
1,610,879
null
1,610,879
null
1
56
android|alarmmanager|android-alarms
32,976
<p>A simple answer would be <strong>NO</strong>. But yes you can achieve this by creating a <code>BroadCastReceiver</code> which will start the Alarm while booting completes of the device. </p> <p>Use <code>&lt;action android:name="android.intent.action.BOOT_COMPLETED" /&gt;</code> for trapping boot activity in BroadCastReceiver class.</p> <p>You need to add above line in AndroidManifest.xml as follows, </p> <pre><code>&lt;receiver android:name=".AutoStartUp" android:enabled="true" android:exported="false" android:permission="android.permission.RECEIVE_BOOT_COMPLETED"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.BOOT_COMPLETED" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre>
11,868,964
List comprehension: Returning two (or more) items for each item
<p><strong>Is it possible to return 2 (or more) items for each item in a list comprehension?</strong></p> <p>What I want (example):</p> <pre><code>[f(x), g(x) for x in range(n)] </code></pre> <p>should return <code>[f(0), g(0), f(1), g(1), ..., f(n-1), g(n-1)]</code></p> <p>So, something to replace this block of code:</p> <pre><code>result = list() for x in range(n): result.add(f(x)) result.add(g(x)) </code></pre>
11,868,996
8
3
null
2012-08-08 16:27:53.19 UTC
15
2022-04-20 02:48:24.643 UTC
2019-11-07 15:25:19.833 UTC
null
68,587
null
1,428,974
null
1
128
python|list-comprehension
45,850
<pre><code>&gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; f = lambda x: x + 2 &gt;&gt;&gt; g = lambda x: x ** 2 &gt;&gt;&gt; list(chain.from_iterable((f(x), g(x)) for x in range(3))) [2, 0, 3, 1, 4, 4] </code></pre> <p>Timings:</p> <pre><code>from timeit import timeit f = lambda x: x + 2 g = lambda x: x ** 2 def fg(x): yield f(x) yield g(x) print timeit(stmt='list(chain.from_iterable((f(x), g(x)) for x in range(3)))', setup='gc.enable(); from itertools import chain; f = lambda x: x + 2; g = lambda x: x ** 2') print timeit(stmt='list(chain.from_iterable(fg(x) for x in range(3)))', setup='gc.enable(); from itertools import chain; from __main__ import fg; f = lambda x: x + 2; g = lambda x: x ** 2') print timeit(stmt='[func(x) for x in range(3) for func in (f, g)]', setup='gc.enable(); f = lambda x: x + 2; g = lambda x: x ** 2') print timeit(stmt='list(chain.from_iterable((f(x), g(x)) for x in xrange(10**6)))', setup='gc.enable(); from itertools import chain; f = lambda x: x + 2; g = lambda x: x ** 2', number=20) print timeit(stmt='list(chain.from_iterable(fg(x) for x in xrange(10**6)))', setup='gc.enable(); from itertools import chain; from __main__ import fg; f = lambda x: x + 2; g = lambda x: x ** 2', number=20) print timeit(stmt='[func(x) for x in xrange(10**6) for func in (f, g)]', setup='gc.enable(); f = lambda x: x + 2; g = lambda x: x ** 2', number=20) </code></pre> <blockquote> <p>2.69210777094</p> <p>3.13900787874</p> <p>1.62461071932</p> <p>25.5944058287</p> <p>29.2623711793</p> <p>25.7211849286</p> </blockquote>
61,412,424
AWS Athena too slow for an api?
<p>The plan was to get data from aws data exchange, move it to an s3 bucket then query it by aws athena for a data api. Everything works, just feels a bit slow. </p> <p>No matter the dataset nor the query I can't get below 2 second in athena response time. Which is a lot for an API. I checked the best practices but seems that those are also above 2 sec.</p> <p>So my question: Is 2 sec the minimal response time for athena?</p> <p>If so then I have to switch to postgres.</p>
61,456,332
1
4
null
2020-04-24 15:54:55.517 UTC
10
2020-04-27 10:12:00.697 UTC
null
null
null
null
4,169,767
null
1
19
amazon-web-services|amazon-athena
7,080
<p>Athena is indeed not a low latency data store. You will very rarely see response times below one second, and often they will be considerably longer. In the general case Athena is not suitable as a backend for an API, but of course that depends on what kind of an API it is. If it's some kind of analytics service, perhaps users don't expect sub second response times? I have built APIs that use Athena that work really well, but those were services where response times in seconds were expected (and even considered fast), and I got help from the Athena team to tune our account to our workload.</p> <p>To understand why Athena is "slow", we can dissect what happens when you submit a query to Athena:</p> <ol> <li>Your code starts a query by using the <code>StartQueryExecution</code> API call</li> <li>The Athena service receives the query, and puts it on a queue. If you're unlucky your query will sit in the queue for a while</li> <li>When there is available capacity the Athena service takes your query from the queue and makes a query plan</li> <li>The query plan requires loading table metadata from the Glue catalog, including the list of partitions, for all tables included in the query</li> <li>Athena also lists all the locations on S3 it got from the tables and partitions to produce a full list of files that will be processed</li> <li>The plan is then executed in parallel, and depending on its complexity, in multiple steps</li> <li>The results of the parallel executions are combined and a result is serialized as CSV and written to S3</li> <li>Meanwhile your code checks if the query has completed using the <code>GetQueryExecution</code> API call, until it gets a response that says that the execution has succeeded, failed, or been cancelled</li> <li>If the execution succeeded your code uses the <code>GetQueryResults</code> API call to retrieve the first page of results</li> <li>To respond to that API call, Athena reads the result CSV from S3, deserializes it, and serializes it as JSON for the API response</li> <li>If there are more than 1000 rows the last steps will be repeated</li> </ol> <p>A Presto expert could probably give more detail about steps 4-6, even though they are probably a bit modified in Athena's version of Presto. The details aren't very important for this discussion though.</p> <p>If you run a query over a lot of data, tens of gigabytes or more, the total execution time will be dominated by step 6. If the result is also big, 7 will be a factor.</p> <p>If your data set is small, and/or involves thousands of files on S3, then 4-5 will instead dominate.</p> <p>Here are some reasons why Athena queries can never be fast, even if they wouldn't touch S3 (for example <code>SELECT NOW()</code>):</p> <ul> <li>There will at least be three API calls before you get the response, a <code>StartQueryExecution</code>, a <code>GetQueryExecution</code>, and a <code>GetQueryResults</code>, just their round trip time (RTT) would add up to more than 100ms.</li> <li>You will most likely have to call <code>GetQueryExecution</code> multiple times, and the delay between calls will puts a bound on how quickly you can discover that the query has succeeded, e.g. if you call it every 100ms you will on average add half of 100ms + RTT to the total time because on average you'll miss the actual completion time by this much.</li> <li>Athena will writes the results to S3 before it marks the execution as succeeded, and since it produces a single CSV file this is not done in parallel. A big response takes time to write.</li> <li>The <code>GetQueryResults</code> must read the CSV from S3, parse it and serialize it as JSON. Subsequent pages must skip ahead in the CSV, and may be even slower.</li> <li>Athena is a multi tenant service, all customers are competing for resources, and your queries will get queued when there aren't enough resources available.</li> </ul> <p>If you want to know what affects the performance of your queries you can use the <code>ListQueryExecutions</code> API call to list recent query execution IDs (I think you can go back 90 days at the most), and then use <code>GetQueryExecution</code> to get query statistics (see <a href="https://docs.aws.amazon.com/athena/latest/APIReference/API_QueryExecutionStatistics.html" rel="noreferrer">the documentation for <code>QueryExecution.Statistics</code></a> for what each property means). With this information you can figure out if your slow queries are because of queueing, execution, or the overhead of making the API calls (if it's not the first two, it's likely the last).</p> <p>There are some things you can do to cut some of the delays, but these tips are unlikely to get you down to sub second latencies:</p> <ul> <li>If you query a lot of data use file formats that are optimized for that kind of thing, Parquet is almost always the answer – and also make sure your file sizes are optimal, around 100 MB.</li> <li>Avoid lots of files, and avoid deep hierarchies. Ideally have just one or a few files per partition, and don't organize files in "subdirectories" (S3 prefixes with slashes) except for those corresponding to partitions.</li> <li>Avoid running queries at the top of the hour, this is when everyone else's scheduled jobs run, there's significant contention for resources the first minutes of every hour.</li> <li>Skip <code>GetQueryExecution</code>, download the CSV from S3 directly. The <code>GetQueryExecution</code> call is convenient if you want to know the data types of the columns, but if you already know, or don't care, reading the data directly can save you some precious tens of milliseconds. If you need the column data types you can get the <code>….csv.metadata</code> file that is written alongside the result CSV, it's undocumented Protobuf data, see <a href="https://stackoverflow.com/questions/55991018/whats-the-data-format-of-athenas-csv-metadata-files">here</a> and <a href="https://github.com/burtcorp/athena-jdbc/blob/master/src/main/java/io/burt/athena/result/AthenaMetaDataParser.java" rel="noreferrer">here</a> for more information.</li> <li>Ask the Athena service team to tune your account. This might not be something you can get without higher tiers of support, I don't really know the politics of this and you need to start by talking to your account manager.</li> </ul>
3,412,376
What is the equivalent of document.createTextNode(' ') in jQuery
<p>What can I use in jquery instead of <code>document.createTextNode(' ')</code> js line.</p> <p>I'm trying to do sth like this : </p> <p>js : <code>divButtons.appendChild(document.createTextNode(' '));</code></p> <p>jquery : <code>$("#divButtons").append(?????);</code></p>
12,691,320
4
1
null
2010-08-05 06:53:27.9 UTC
null
2012-10-22 15:35:02.227 UTC
null
null
null
null
134,263
null
1
35
jquery
32,142
<p>Please be careful with the existing answers. They show how to append HTML. HTML is not Text. Treating text as HTML is a) a bug and b) dangerous.</p> <p>Here is a sane solution:</p> <pre><code>$('selector').append(document.createTextNode('text &lt; and &gt; not &amp; html!')) </code></pre> <p>This is using jQuery only for the append part. Nothing wrong with using createTextNode. jQuery uses createTextNode internally in its <code>text(str)</code> function.</p>
3,603,461
Is there a specific reason nested namespace declarations are not allowed in C++?
<p>The standard does not allow code like this:</p> <pre><code>namespace Hello::World { //Things that are in namespace Hello::World } </code></pre> <p>and instead requires</p> <pre><code>namespace Hello { namespace World { //Things that are in namespace Hello::World }} </code></pre> <p>What is the rationale? Was this simply not thought of at the time, or is there a specific reason it is not included?</p> <p>It seems that the first syntax more directly expresses in which namespace one is supposed to be, as the declaration mimics the actual use of the namespace in later code. It also results in less indentation if you are unfortunate enough to be using a "dumb" bracket counting indentation tool.</p>
3,603,539
5
5
null
2010-08-30 19:14:59.513 UTC
4
2022-05-04 18:59:10.513 UTC
2022-05-04 18:57:41.253 UTC
null
2,756,409
null
82,320
null
1
28
c++|namespaces|language-design
9,273
<p>The reason is most likely "because that's how the language evolved."</p> <p>There has been at least one proposal (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1524.htm" rel="noreferrer">"Nested Namespace Definition Proposal"</a> in 2003) to allow nested namespace definitions, but it was not selected for inclusion in C++0x.</p>
3,316,012
Can Mercurial use .hgignore to forget files?
<p>I forget to place the correct .hgignore into my project and am now confronted with many useless files in my repository. As these files are already under source control .hgignore will not pick em up.</p> <p>Is there a way for hg to forget all files matched by .hgignore?</p>
6,802,316
5
0
null
2010-07-23 07:08:57.847 UTC
14
2018-12-04 09:09:46.273 UTC
null
null
null
null
131,773
null
1
38
mercurial
4,895
<p><a href="http://www.selenic.com/hg/help/filesets">filesets</a> awesomeness (requires 1.9):</p> <pre><code>hg forget "set:hgignore() and not ignored()" </code></pre>
3,635,754
sql select * between exact number of rows
<p>I would like to know if I could using select statement retrieve exact position of the rows. e.g rows between 235 &amp; 250. Is this possible?</p> <p>Thanks in advance, shashi</p>
56,302,376
8
2
null
2010-09-03 12:35:59.213 UTC
3
2019-05-27 13:24:34.223 UTC
2010-09-03 12:43:45.85 UTC
null
420,892
null
414,977
null
1
8
sql|database
61,902
<p>We can do this by multiple way.</p> <ol> <li><p>we can do with the help of offset-fetch clause.</p> <p><code>select * from Table_Name order by Column_Name offset 234 rows fetch next 16 rows only</code></p></li> </ol> <p>it will fetch the record between 235-250. because it will skip first 234 rows and will fetch next 16 rows.</p> <ol start="2"> <li><p>we can use simple select statement with where clause.</p> <p><code>Select * from Table_Name where Column_Name Between 235 and 250</code></p></li> </ol> <p>it will also fetch same result.</p> <p>Hope it will help.</p>
3,377,309
Xcode 4: How do you view the console?
<p>I can't seem to find a way to have the console run (to show NSLog comments) in XCode 4. The normal method for the previous version of XCode does not work. Does anyone have an idea of how to accomplish this?</p>
3,377,337
8
3
null
2010-07-31 07:56:09.633 UTC
14
2015-09-24 05:06:30.547 UTC
null
null
null
null
400,057
null
1
96
iphone|objective-c|xcode4
183,062
<p>You need to click Log Navigator icon (far right in left sidebar). Then choose your Debug/Run session in left sidebar, and you will have console in editor area.</p> <p><img src="https://i.stack.imgur.com/RHoHb.png" alt="enter image description here"></p>
3,239,202
What's the correct way to hide the <h1> tag and not be banned from Google?
<p>The website I am working on uses an image defined in CSS as the main logo. The html code looks like this:</p> <pre><code>&lt;h1&gt;Something.com | The best something ever&lt;/h1&gt; </code></pre> <p>I would like to display just the image defined in CSS and pass the information from the h1 tag to the search enginges only.</p> <p>What's the correct way to do this? Google is very strict about this, I know that display:none is wrong, what about visibility: hidden ?</p> <p>Thanks in advance!</p>
3,239,332
10
0
null
2010-07-13 16:25:45.77 UTC
4
2022-05-11 11:13:15.61 UTC
2012-01-05 16:29:18.527 UTC
null
861,565
null
390,686
null
1
24
html|css|seo
68,413
<p>You should be fine with <code>visibility: hidden</code>. </p> <p>That said, if your image is part of the <strong>content</strong> (and I would dare to say that a company logo is content, not presentation), and you care about accessible html, you should consider changing your code to include the image as a <code>img</code> element with <code>title</code> and <code>alt</code>ernate text, instead of a css <code>background-image</code>.</p> <p>Additionally, if you hope to attract search engines to the keywords inside the <code>&lt;h1&gt;</code> element, you might want to include those words more than once in the page. The page title is a much more relevant place than the <code>h1</code> element, for example.</p>
3,550,341
Gantt charts with R
<p>How do I create a <a href="http://en.wikipedia.org/wiki/Gantt_chart" rel="nofollow noreferrer">Gantt chart</a> in R?</p> <p>I'm looking for something sophisticated (looking more or less like this): <img src="https://web.archive.org/web/20110227163953/https://upload.wikimedia.org/wikipedia/en/7/73/Pert_example_gantt_chart.gif" alt="this" /></p> <p>P.S. I could live without the dependency arrows.</p>
29,999,300
13
0
null
2010-08-23 18:06:02.943 UTC
80
2022-03-30 11:59:09.563 UTC
2022-03-30 04:40:37.443 UTC
null
13,095,326
null
170,792
null
1
108
r|charts|gantt-chart
80,895
<p>There are now a few elegant ways to generate a Gantt chart in R. </p> <p><strong>Using Candela</strong></p> <pre><code>library(candela) data &lt;- list( list(name='Do this', level=1, start=0, end=5), list(name='This part 1', level=2, start=0, end=3), list(name='This part 2', level=2, start=3, end=5), list(name='Then that', level=1, start=5, end=15), list(name='That part 1', level=2, start=5, end=10), list(name='That part 2', level=2, start=10, end=15)) candela('GanttChart', data=data, label='name', start='start', end='end', level='level', width=700, height=200) </code></pre> <p><a href="https://i.stack.imgur.com/zJjvM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zJjvM.png" alt="enter image description here"></a></p> <p><strong>Using DiagrammeR</strong></p> <pre><code>library(DiagrammeR) mermaid(" gantt dateFormat YYYY-MM-DD title A Very Nice Gantt Diagram section Basic Tasks This is completed :done, first_1, 2014-01-06, 2014-01-08 This is active :active, first_2, 2014-01-09, 3d Do this later : first_3, after first_2, 5d Do this after that : first_4, after first_3, 5d section Important Things Completed, critical task :crit, done, import_1, 2014-01-06,24h Also done, also critical :crit, done, import_2, after import_1, 2d Doing this important task now :crit, active, import_3, after import_2, 3d Next critical task :crit, import_4, after import_3, 5d section The Extras First extras :active, extras_1, after import_4, 3d Second helping : extras_2, after extras_1, 20h More of the extras : extras_3, after extras_1, 48h ") </code></pre> <p><img src="https://i.stack.imgur.com/OffVy.jpg" alt="enter image description here"></p> <p>Find this example and many more on <code>DiagrammeR</code> <a href="https://github.com/rich-iannone/DiagrammeR" rel="noreferrer">GitHub</a> </p> <hr> <p>If your data is stored in a <code>data.frame</code>, you can create the string to pass to <code>mermaid()</code> by converting it to the proper format.</p> <p>Consider the following:</p> <pre><code>df &lt;- data.frame(task = c("task1", "task2", "task3"), status = c("done", "active", "crit"), pos = c("first_1", "first_2", "first_3"), start = c("2014-01-06", "2014-01-09", "after first_2"), end = c("2014-01-08", "3d", "5d")) # task status pos start end #1 task1 done first_1 2014-01-06 2014-01-08 #2 task2 active first_2 2014-01-09 3d #3 task3 crit first_3 after first_2 5d </code></pre> <p>Using <code>dplyr</code> and <code>tidyr</code> (or any of your favorite data wrangling ressources):</p> <pre><code>library(tidyr) library(dplyr) mermaid( paste0( # mermaid "header", each component separated with "\n" (line break) "gantt", "\n", "dateFormat YYYY-MM-DD", "\n", "title A Very Nice Gantt Diagram", "\n", # unite the first two columns (task &amp; status) and separate them with ":" # then, unite the other columns and separate them with "," # this will create the required mermaid "body" paste(df %&gt;% unite(i, task, status, sep = ":") %&gt;% unite(j, i, pos, start, end, sep = ",") %&gt;% .$j, collapse = "\n" ), "\n" ) ) </code></pre> <p>As per mentioned by @GeorgeDontas in the comments, there is a <a href="https://github.com/rich-iannone/DiagrammeR/issues/77" rel="noreferrer">little hack</a> that could allow to change the labels of the x axis to dates instead of 'w.01, w.02'. </p> <p>Assuming you saved the above mermaid graph in <code>m</code>, do:</p> <pre><code>m$x$config = list(ganttConfig = list( axisFormatter = list(list( "%b %d, %Y" ,htmlwidgets::JS( 'function(d){ return d.getDay() == 1 }' ) )) )) </code></pre> <p>Which gives:</p> <p><a href="https://i.stack.imgur.com/GIZPX.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/GIZPX.jpg" alt="enter image description here"></a></p> <hr> <p><strong>Using timevis</strong></p> <p>From the <code>timevis</code> <a href="https://github.com/daattali/timevis" rel="noreferrer">GitHub</a>:</p> <blockquote> <p><code>timevis</code> lets you create rich and <em>fully interactive</em> timeline visualizations in R. Timelines can be included in Shiny apps and R markdown documents, or viewed from the R console and RStudio Viewer.</p> </blockquote> <pre><code>library(timevis) data &lt;- data.frame( id = 1:4, content = c("Item one" , "Item two" ,"Ranged item", "Item four"), start = c("2016-01-10", "2016-01-11", "2016-01-20", "2016-02-14 15:00:00"), end = c(NA , NA, "2016-02-04", NA) ) timevis(data) </code></pre> <p>Which gives:</p> <p><a href="https://i.stack.imgur.com/1YMZW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1YMZW.png" alt="enter image description here"></a></p> <hr> <p><strong>Using plotly</strong></p> <p>I stumbled upon this <a href="http://moderndata.plot.ly/gantt-charts-in-r-using-plotly/" rel="noreferrer">post</a> providing another method using <code>plotly</code>. Here's an example:</p> <pre><code>library(plotly) df &lt;- read.csv("https://cdn.rawgit.com/plotly/datasets/master/GanttChart-updated.csv", stringsAsFactors = F) df$Start &lt;- as.Date(df$Start, format = "%m/%d/%Y") client &lt;- "Sample Client" cols &lt;- RColorBrewer::brewer.pal(length(unique(df$Resource)), name = "Set3") df$color &lt;- factor(df$Resource, labels = cols) p &lt;- plot_ly() for(i in 1:(nrow(df) - 1)){ p &lt;- add_trace(p, x = c(df$Start[i], df$Start[i] + df$Duration[i]), y = c(i, i), mode = "lines", line = list(color = df$color[i], width = 20), showlegend = F, hoverinfo = "text", text = paste("Task: ", df$Task[i], "&lt;br&gt;", "Duration: ", df$Duration[i], "days&lt;br&gt;", "Resource: ", df$Resource[i]), evaluate = T ) } p </code></pre> <p>Which gives:</p> <p><a href="https://i.stack.imgur.com/hxdn8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hxdn8.png" alt="enter image description here"></a></p> <p>You can then add additional information and annotations, customize fonts and colors, etc. (see blog post for details)</p>
3,340,485
How to solve circular reference in json serializer caused by hibernate bidirectional mapping?
<p>I am writing a serializer to serialize POJO to JSON but stuck in circular reference problem. In hibernate bidirectional one-to-many relation, parent references child and child references back to parent and here my serializer dies. (see example code below)<br> How to break this cycle? Can we get owner tree of an object to see whether object itself exists somewhere in its own owner hierarchy? Any other way to find if the reference is going to be circular? or any other idea to resolve this problem?</p>
3,340,507
14
2
null
2010-07-27 03:11:49.773 UTC
38
2020-12-10 14:39:02.857 UTC
null
null
null
null
248,258
null
1
87
java|hibernate|json|serialization
97,477
<p>Can a bi-directional relationship even be represented in JSON? Some data formats are not good fits for some types of data modelling. </p> <p>One method for dealing with cycles when dealing with traversing object graphs is to keep track of which objects you've seen so far (using identity comparisons), to prevent yourself from traversing down an infinite cycle.</p>
3,700,971
Immutable array in Java
<p>Is there an immutable alternative to the primitive arrays in Java? Making a primitive array <code>final</code> doesn't actually prevent one from doing something like</p> <pre><code>final int[] array = new int[] {0, 1, 2, 3}; array[0] = 42; </code></pre> <p>I want the elements of the array to be unchangeable.</p>
3,700,995
15
11
null
2010-09-13 13:43:12.96 UTC
28
2021-10-16 18:50:18.25 UTC
null
null
null
ignoramus
null
null
1
175
java|arrays|immutability
121,837
<p>Not with primitive arrays. You'll need to use a List or some other data structure:</p> <pre><code>List&lt;Integer&gt; items = Collections.unmodifiableList(Arrays.asList(0,1,2,3)); </code></pre>
7,910,734
GsonBuilder setDateFormat for "2011-10-26T20:29:59-07:00"
<p>I'm getting a date/time in json as <code>2011-10-26T20:29:59-07:00</code>. What's the proper way to use <code>gsonBuilder.setDateFormat</code> to properly format this time? </p>
7,910,898
4
0
null
2011-10-27 01:18:09.677 UTC
19
2016-06-23 10:02:04.463 UTC
2011-10-27 01:49:17.447 UTC
null
157,882
null
479,180
null
1
56
java|date|gson
48,360
<p>The <code>-07:00</code> is the ISO 8601 time zone notation. This is not supported by <code>SimpleDateFormat</code> until <a href="http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">Java 7</a>. So, if you can <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" rel="noreferrer">upgrade</a> to Java 7, then you can use the <code>X</code> to represent that time zone notation:</p> <pre><code>Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssX").create(); </code></pre> <p>On <a href="http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">Java 6</a> you would need to do some pattern matching and replacing on the JSON string first to replace the <code>-07:00</code> part by the RFC 822 notation <code>-0700</code> so that you can use <code>Z</code>:</p> <pre><code>Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create(); </code></pre> <p>or by the general time zone notation <code>GMT-07:00</code> so that you can use <code>z</code>:</p> <pre><code>Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssz").create(); </code></pre>
61,576,659
How to Hot-Reload in ReactJS Docker
<p>This might sound simple, but I have this problem.</p> <p>I have two <code>docker</code> containers running. One is for my <code>front-end</code> and other is for my <code>backend</code> services.</p> <p>these are the <code>Dockerfile</code>s for both services.</p> <p><strong>front-end</strong> <code>Dockerfile</code> :</p> <pre><code># Use an official node runtime as a parent image FROM node:8 WORKDIR /app # Install dependencies COPY package.json /app RUN npm install --silent # Add rest of the client code COPY . /app EXPOSE 3000 CMD npm start </code></pre> <p><strong>backend</strong> <code>Dockerfile</code> :</p> <pre><code>FROM python:3.7.7 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY server.py /usr/src/app COPY . /usr/src/app EXPOSE 8083 # CMD ["python3", "-m", "http.server", "8080"] CMD ["python3", "./server.py"] </code></pre> <p>I am building images with the <code>docker-compose.yaml</code> as below:</p> <pre><code>version: "3.2" services: frontend: build: ./frontend ports: - 80:3000 depends_on: - backend backend: build: ./backends/banuka ports: - 8080:8083 </code></pre> <p><strong>How can I make this two services <code>Update</code> whenever there is a change to front-end or back-end</strong>?</p> <p>I found this repo, which is a booilerplate for <code>reactjs</code>, <code>python-flask</code> and <code>posgresel</code>, which says it has enabled <code>Hot reload</code> for both <code>reactjs</code> frontend and <code>python-flask</code> backend. But I couldn't find anything related to that. Can someone help me?</p> <p><a href="https://github.com/tomahim/react-flask-postgres-boilerplate-with-docker/blob/master/docker-compose.yml" rel="noreferrer">repo link</a></p> <p>What I want is: <strong>after every code change the container should b e up-to-date automatically !</strong></p>
61,577,792
1
8
null
2020-05-03 15:03:37.61 UTC
11
2020-05-03 16:18:58.437 UTC
null
null
null
null
13,456,401
null
1
21
python|node.js|reactjs|docker
16,984
<p>Try this in your docker-compose.yml </p> <pre><code>version: "3.2" services: frontend: build: ./frontend environment: CHOKIDAR_USEPOLLING: "true" volumes: - /app/node_modules - ./frontend:/app ports: - 80:3000 depends_on: - backend backend: build: ./backends/banuka environment: CHOKIDAR_USEPOLLING: "true" volumes: - ./backends/banuka:/app ports: - 8080:8083 </code></pre> <p>Basically you need that chokidar environment to enable hot reloading and you need volume bindings to make your code on your machine communicate with code in container. See if this works.</p>
4,360,868
How do you make layouts for several Android screen sizes?
<p>I've done some research on building layouts that work for multiple screen sizes and I'm looking for some clarification.</p> <p>Is it common practice to just make a separate layout file for each of the three screen sizes (small, medium, large) or can you accomplish this with an easier method?</p> <p>I've been testing my projects on a large screen device, and even though I use DIPs (density independent pixels) for padding, margins, etc, it still scrunches stuff up when I view it on smaller screens. Should I be designing my projects for medium-sized screens and then just allow Android to scale it appropriately?</p> <p>I'm not sure if this is a good question or not, but I am looking for what the common practice is for designing for multiple screen sizes. What do you do?</p> <p>Edit: In addition to this, for example, let's say I have a button that is 40dip above the bottom of the screen, should I literally write 40dip, or should I be using some sort of pixel math like 40 * screenWidth / blahblah or something so that it scales depending on the screen size the user has? I have limited experience with UIs...</p>
4,361,094
3
1
null
2010-12-05 20:05:21.367 UTC
8
2010-12-05 20:50:53.763 UTC
2010-12-05 20:10:52.663 UTC
null
487,840
null
487,840
null
1
28
android|layout|density-independent-pixel
23,587
<p>There are two axes to consider when it comes to screen size: physical size and density. Density is handled by providing measurements in dips and scaled resources as appropriate. But density does not always imply size or vice versa. See <a href="http://developer.android.com/guide/practices/screens_support.html" rel="noreferrer">http://developer.android.com/guide/practices/screens_support.html</a> for some further info on the mechanics.</p> <p>It is not common or recommended to have different layouts based on each screen <em>resolution</em> you support, but it is entirely reasonable to design different layouts for different size classes (small, medium, large). Different sized screens might benefit from adding, removing, or repositioning certain navigation elements depending on the app.</p> <p>Within a certain size class you should make sure that your layouts tolerate variances in exact screen resolution. As Falmarri suggested, use relative layouts, weights, and the other tools available to let your layout stretch gracefully.</p>
4,827,930
How to show indexes of NAs?
<p>I have the piece to display NAs, but I can't figure it out. </p> <pre><code>try(na.fail(x)) &gt; Error in na.fail.default(x) : missing values in object # display NAs myvector[is.na(x)] # returns NA NA NA NA </code></pre> <p>The only thing I get from this the length of the NA vector, which is actually not too helpful when the NAs where caused by a bug in my code that I am trying to track. How can I get the index of NA element(s) ?</p> <p>I also tried: </p> <pre><code>subset(x,is.na(x)) </code></pre> <p>which has the same effect.</p> <p>EDIT: </p> <pre><code>y &lt;- complete.cases(x) x[!y] # just returns another NA NA NA NA </code></pre>
4,828,230
4
2
null
2011-01-28 11:57:10.627 UTC
9
2021-04-01 18:27:12.593 UTC
2011-01-28 12:07:18.893 UTC
null
366,256
null
366,256
null
1
28
r|indexing
45,354
<p>You want the which function:</p> <pre><code>which(is.na(arr)) </code></pre>
4,435,016
install pil on virtualenv with libjpeg
<p>Currently I'm installing PIL into my virtual env as follows:</p> <pre><code>pip install -E . -r ./releases/%s/requirements.txt </code></pre> <p>where requirements.txt contains:</p> <pre><code>pil </code></pre> <p>I can upload png images but not jpeg images currently. From reading on the web it seems i may need libjpeg decoder? Am i installing pil incorrectly? What is the proper way to install pil for django in a virtual env with libjpeg?</p>
7,528,988
6
2
null
2010-12-14 01:05:51.1 UTC
16
2014-02-06 19:13:24.787 UTC
2010-12-14 01:18:13.19 UTC
null
75,033
null
225,128
null
1
16
django|python-imaging-library|virtualenv|pip
19,886
<p>You should install the libraries that others recommended but most importantly you should tell PIL where to find them. Edit the setup.py so that</p> <pre><code> JPEG_ROOT = None </code></pre> <p>becomes </p> <pre><code>JPEG_ROOT = libinclude("/usr/lib") </code></pre> <p>I found that the easiest way was to download the source with pip but not install:</p> <pre><code> pip install --no-install PIL </code></pre> <p>edit the setup (inside the build directory of the virtual environment) and the install</p> <pre><code> pip install PIL </code></pre> <p>you can find some more information in my <a href="http://three99.com/posts/how-to-install-pil-on-ubuntu-with-jpeg-support" rel="noreferrer">blog </a></p> <p>You can also try <a href="http://pypi.python.org/pypi/Pillow/" rel="noreferrer">pillow</a> which seems to do great job with little hassle (pip install pillow)</p>
4,144,394
Turning tracing off via app.config
<p>I'm trying to use System.Diagnostics to do some very basic logging. I figure I'd use what's in the box rather than taking on an extra dependency like Log4Net or EntLib. </p> <p>I'm all set up, tracing is working wonderfully. Code snippet:</p> <pre><code>Trace.TraceInformation("Hello World") </code></pre> <p>App.config:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;system.diagnostics&gt; &lt;trace autoflush="true" indentsize="4"&gt; &lt;listeners&gt; &lt;add name="TraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="Trace.log" traceOutputOptions="DateTime" /&gt; &lt;remove name="Default" /&gt; &lt;/listeners&gt; &lt;/trace&gt; &lt;/system.diagnostics&gt; &lt;/configuration&gt; </code></pre> <p>and my little "Hello World" shows nicely up in my Trace.log file. But now I'd like to switch OFF tracing, so I dig into MSDN and find <a href="http://msdn.microsoft.com/en-us/library/t06xyy08(v=VS.100).aspx" rel="noreferrer">How to: Configure Trace Switches </a>. I add the <code>&lt;switches&gt;</code> element, and now my app.config looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;system.diagnostics&gt; &lt;trace autoflush="true" indentsize="4"&gt; &lt;listeners&gt; &lt;add name="TraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="Trace.log" traceOutputOptions="DateTime" /&gt; &lt;remove name="Default" /&gt; &lt;/listeners&gt; &lt;/trace&gt; &lt;switches&gt; &lt;add name="Data" value="0" /&gt; &lt;/switches&gt; &lt;/system.diagnostics&gt; &lt;/configuration&gt; </code></pre> <p>The <code>value="0"</code> should turn off tracing - at least if you then follow <a href="http://msdn.microsoft.com/en-us/library/t20ke01d.aspx" rel="noreferrer">How to: Create and Initialize Trace Switches</a>, which tells you to add this line of code:</p> <pre><code>Dim dataSwitch As New BooleanSwitch("Data", "DataAccess module") </code></pre> <p>That doesn't make sense to me: I just have to declare an instance of the <code>BooleanSwicth</code> to be able to manage (disable) tracing via the .config file? Should I like ... <em>use</em> ... the object somewhere?</p> <p>Anyways, I'm sure I missed something really obvious somewhere. Please help.</p> <p><strong>How do I switch OFF tracing in app.config?</strong></p>
4,146,336
6
0
null
2010-11-10 12:21:58.607 UTC
11
2019-06-12 18:44:18.85 UTC
null
null
null
null
10,932
null
1
20
c#|.net|vb.net|configuration|trace
32,104
<p>I agree with @Alex Humphrey's recommendation to try using TraceSources. With TraceSources you gain more control over how your logging/tracing statements execute. For example, you could have code like this:</p> <pre><code>public class MyClass1 { private static readonly TraceSource ts = new TraceSource("MyClass1"); public DoSomething(int x) { ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x); } } public class MyClass2 { private static readonly TraceSource ts = new TraceSource("MyClass2"); public DoSomething(int x) { ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x); } } </code></pre> <p>The TraceSource.TraceEvent call will automatically check the level of the message (TraceEventType.Information) against the configured level of the associated Switch and will determine whether or not the message should actually be written out.</p> <p>By using a differently named TraceSource for each type, you can control the logging from those classes individually. You could enable MyClass1 logging or you could disable it or you could enable it but have it log only if the level of the message (TraceEventType) is greater than a certain value (maybe only log "Warning" and higher). At the same time, you could turn logging in MyClass2 on or off or set to a level, completely independently of MyClass1. All of this enabling/disabling/level stuff happens in the app.config file.</p> <p>Using the app.config file, you could also control all TraceSources (or groups of TraceSources) in the same way. So, you could configure so that MyClass1 and MyClass2 are both controlled by the same Switch.</p> <p>If you don't want to have a differently named TraceSource for each type, you could just create the same TraceSource in every class:</p> <pre><code>public class MyClass1 { private static readonly TraceSource ts = new TraceSource("MyApplication"); public DoSomething(int x) { ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x); } } public class MyClass2 { private static readonly TraceSource ts = new TraceSource("MyApplication"); public DoSomething(int x) { ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x); } } </code></pre> <p>This way, you could make all logging within your application happen at the same level (or be turned off or go the same TraceListener, or whatever).</p> <p>You could also configure different parts of your application to be independently configurable without having to go the "trouble" of defining a unique TraceSource in each type:</p> <pre><code>public class Analysis1 { private static readonly TraceSource ts = new TraceSource("MyApplication.Analysis"); public DoSomething(int x) { ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x); } } public class Analysis2 { private static readonly TraceSource ts = new TraceSource("MyApplication.Analysis"); public DoSomething(int x) { ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x); } } public class DataAccess1 { private static readonly TraceSource ts = new TraceSource("MyApplication.DataAccess"); public DoSomething(int x) { ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x); } } public class DataAccess2 { private static readonly TraceSource ts = new TraceSource("MyApplication.DataAccess"); public DoSomething(int x) { ts.TraceEvent(TraceEventType.Information, "In DoSomething. x = {0}", x); } } </code></pre> <p>With your class instrumented this way, you could make the "DataAccess" part of your app log at one level while the "Analysis" part of your app logs at a different level (of course, either or both parts of your app could be configured so that logging is disabled).</p> <p>Here is a part of an app.config file that configures TraceSources and TraceSwitches:</p> <pre><code>&lt;system.diagnostics&gt; &lt;trace autoflush="true"&gt;&lt;/trace&gt; &lt;sources&gt; &lt;source name="MyClass1" switchName="switch1"&gt; &lt;listeners&gt; &lt;remove name="Default"&gt;&lt;/remove&gt; &lt;add name="console"&gt;&lt;/add&gt; &lt;/listeners&gt; &lt;/source&gt; &lt;source name="MyClass2" switchName="switch2"&gt; &lt;listeners&gt; &lt;remove name="Default"&gt;&lt;/remove&gt; &lt;add name="console"&gt;&lt;/add&gt; &lt;/listeners&gt; &lt;/source&gt; &lt;/sources&gt; &lt;switches&gt; &lt;add name="switch1" value="Information"/&gt; &lt;add name="switch2" value="Warning"/&gt; &lt;/switches&gt; &lt;sharedListeners&gt; &lt;add name="console" type="System.Diagnostics.ConsoleTraceListener"&gt; &lt;/add&gt; &lt;add name="file" type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.txt"&gt; &lt;/add&gt; &lt;/sharedListeners&gt; &lt;/system.diagnostics&gt; </code></pre> <p>As you can see, you could configure a single TraceSource and a single Switch and all logging would occur with a single level of control (i.e. you could turn all logging off or make it log at a certain level).</p> <p>Alternatively, you could define multiple TraceSources (and reference the corresponding TraceSources in your code) and multiple Switches. The Switches may be shared (i.e. multiple TraceSources can use the same Switch).</p> <p>Ultimately, by putting in a little more effort now to use TraceSources and to reference appropriately named TraceSources in your code (i.e. define the TraceSource names logically so that you can have the desired degree of control over logging in your app), you will gain significant flexibility in the long run.</p> <p>Here are a few links that might help you with System.Diagnostics as you go forward:</p> <p><a href="https://stackoverflow.com/questions/2795310/net-diagnostics-best-practices">.net Diagnostics best practices?</a></p> <p><a href="https://stackoverflow.com/questions/576185/logging-best-practices">Logging best practices</a></p> <p><a href="https://stackoverflow.com/questions/3934685/vb-net-whats-the-best-approach-to-logging/3937102#3937102">What&#39;s the best approach to logging?</a></p> <p><a href="https://stackoverflow.com/questions/208735/does-the-net-tracesource-tracelistener-framework-have-something-similar-to-log4n/3580294#3580294">Does the .Net TraceSource/TraceListener framework have something similar to log4net&#39;s Formatters?</a></p> <p>In the links I posted, there is often discussion of the "best" logging framework. I am not trying to convince you to change from System.Diagnostics. The links also tend to have good information about using System.Diagnostics, that is why I posted them.</p> <p>Several of the links I posted contain a link to <a href="http://ukadcdiagnostics.codeplex.com/" rel="noreferrer">Ukadc.Diagnostics</a>. This is a really cool add on library for System.Diagnostics that adds rich formatting capability, similar to what you can do with log4net and NLog. This library imposes a config-only dependency on your app, not a code or reference dependency.</p>
4,100,594
How do you close Tool Windows in IntelliJ?
<p>I've got a zillion different tool windows all docked &amp; hidden in IntelliJ but what I'd really like to do is to close some of them. I'll never use them and they're just adding to the visual clutter. There are buttons for everything BUT closing.</p> <p>Any suggestions?</p>
4,100,705
6
1
null
2010-11-04 19:41:58.763 UTC
7
2016-04-28 21:48:48.75 UTC
null
null
null
null
12,503
null
1
49
intellij-idea
10,727
<p>From the <a href="http://www.jetbrains.com/idea/webhelp/appearance.html" rel="noreferrer">help files</a> it's <kbd>File > Settings > Appearance</kbd> that will help you. You can hide the tool windows by unselecting <code>Show tool window bars</code>.</p> <p>On a case by case basis, you could use <kbd>File > Other Settings > Configure Plugins</kbd></p> <p>and work through the wizard unselecting those plugins that you're not using. You'll need to restart <em>Intellij</em>, but it'll get rid of 'em.</p>
4,777,272
Android ListView with different layouts for each row
<p>I am trying to determine the best way to have a single ListView that contains different layouts for each row. I know how to create a custom row + custom array adapter to support a custom row for the entire list view, but how can I implement many different row styles in the ListView?</p>
4,777,306
6
1
null
2011-01-23 23:27:04.633 UTC
156
2019-01-09 12:57:46.84 UTC
2016-07-12 20:21:08.127 UTC
null
467,569
null
467,569
null
1
353
android|listview|listviewitem
204,976
<p>Since you know how many types of layout you would have - it's possible to use those methods.</p> <p><code>getViewTypeCount()</code> - this methods returns information how many types of rows do you have in your list</p> <p><code>getItemViewType(int position)</code> - returns information which layout type you should use based on position</p> <p>Then you inflate layout only if it's null and determine type using <code>getItemViewType</code>.</p> <p>Look at <strong><a href="http://android.amberfog.com/?p=296" rel="noreferrer">this tutorial</a></strong> for further information.</p> <p>To achieve some optimizations in structure that you've described in comment I would suggest:</p> <ul> <li>Storing views in object called <code>ViewHolder</code>. It would increase speed because you won't have to call <code>findViewById()</code> every time in <code>getView</code> method. See <a href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html" rel="noreferrer">List14 in API demos</a>.</li> <li>Create one generic layout that will conform all combinations of properties and hide some elements if current position doesn't have it.</li> </ul> <p>I hope that will help you. If you could provide some XML stub with your data structure and information how exactly you want to map it into row, I would be able to give you more precise advise. By pixel.</p>
4,431,945
Split and join back a binary file in java
<p>I am trying to divide a binary file (like video/audio/image) into chunks of 100kb each and then join those chunks back to get back the original file. My code seems to be working, in the sense that it divides the file and joins the chunks, the file I get back is of the same size as original. However, the problem is that the contents get truncated - that is, if it's a video file it stops after 2 seconds, if it is image file then only the upper part looks correct.</p> <p>Here is the code I am using (I can post the entire code if you like):</p> <p>For dividing:</p> <pre><code>File ifile = new File(fname); FileInputStream fis; String newName; FileOutputStream chunk; int fileSize = (int) ifile.length(); int nChunks = 0, read = 0, readLength = Chunk_Size; byte[] byteChunk; try { fis = new FileInputStream(ifile); StupidTest.size = (int)ifile.length(); while (fileSize &gt; 0) { if (fileSize &lt;= Chunk_Size) { readLength = fileSize; } byteChunk = new byte[readLength]; read = fis.read(byteChunk, 0, readLength); fileSize -= read; assert(read==byteChunk.length); nChunks++; newName = fname + ".part" + Integer.toString(nChunks - 1); chunk = new FileOutputStream(new File(newName)); chunk.write(byteChunk); chunk.flush(); chunk.close(); byteChunk = null; chunk = null; } fis.close(); fis = null; </code></pre> <p>And for joining file, I put the names of all chunks in a List, then sort it by name and then run the following code:</p> <pre><code>File ofile = new File(fname); FileOutputStream fos; FileInputStream fis; byte[] fileBytes; int bytesRead = 0; try { fos = new FileOutputStream(ofile,true); for (File file : files) { fis = new FileInputStream(file); fileBytes = new byte[(int) file.length()]; bytesRead = fis.read(fileBytes, 0,(int) file.length()); assert(bytesRead == fileBytes.length); assert(bytesRead == (int) file.length()); fos.write(fileBytes); fos.flush(); fileBytes = null; fis.close(); fis = null; } fos.close(); fos = null; </code></pre>
4,432,066
8
0
null
2010-12-13 18:04:19.887 UTC
11
2022-08-31 01:25:31.377 UTC
2011-05-11 07:45:04.12 UTC
null
41,956
null
342,390
null
1
19
java|file-io
21,193
<p>I can spot only 2 potential mistakes in the code:</p> <pre><code>int fileSize = (int) ifile.length(); </code></pre> <p>The above fails when the file is over 2GB since an <code>int</code> cannot hold more.</p> <pre><code>newName = fname + ".part" + Integer.toString(nChunks - 1); </code></pre> <p>A filename which is constructed like that should be sorted on a very specific manner. When using default string sorting, <code>name.part10</code> will namely come before <code>name.part2</code>. You'd like to supply a custom <a href="http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html" rel="noreferrer"><code>Comparator</code></a> which extracts and parses the part number as an int and then compare by that instead.</p>
4,217,398
When is ReaderWriterLockSlim better than a simple lock?
<p>I'm doing a very silly benchmark on the ReaderWriterLock with this code, where reading happens 4x more often than writting:</p> <pre><code>class Program { static void Main() { ISynchro[] test = { new Locked(), new RWLocked() }; Stopwatch sw = new Stopwatch(); foreach ( var isynchro in test ) { sw.Reset(); sw.Start(); Thread w1 = new Thread( new ParameterizedThreadStart( WriteThread ) ); w1.Start( isynchro ); Thread w2 = new Thread( new ParameterizedThreadStart( WriteThread ) ); w2.Start( isynchro ); Thread r1 = new Thread( new ParameterizedThreadStart( ReadThread ) ); r1.Start( isynchro ); Thread r2 = new Thread( new ParameterizedThreadStart( ReadThread ) ); r2.Start( isynchro ); w1.Join(); w2.Join(); r1.Join(); r2.Join(); sw.Stop(); Console.WriteLine( isynchro.ToString() + ": " + sw.ElapsedMilliseconds.ToString() + "ms." ); } Console.WriteLine( "End" ); Console.ReadKey( true ); } static void ReadThread(Object o) { ISynchro synchro = (ISynchro)o; for ( int i = 0; i &lt; 500; i++ ) { Int32? value = synchro.Get( i ); Thread.Sleep( 50 ); } } static void WriteThread( Object o ) { ISynchro synchro = (ISynchro)o; for ( int i = 0; i &lt; 125; i++ ) { synchro.Add( i ); Thread.Sleep( 200 ); } } } interface ISynchro { void Add( Int32 value ); Int32? Get( Int32 index ); } class Locked:List&lt;Int32&gt;, ISynchro { readonly Object locker = new object(); #region ISynchro Members public new void Add( int value ) { lock ( locker ) base.Add( value ); } public int? Get( int index ) { lock ( locker ) { if ( this.Count &lt;= index ) return null; return this[ index ]; } } #endregion public override string ToString() { return "Locked"; } } class RWLocked : List&lt;Int32&gt;, ISynchro { ReaderWriterLockSlim locker = new ReaderWriterLockSlim(); #region ISynchro Members public new void Add( int value ) { try { locker.EnterWriteLock(); base.Add( value ); } finally { locker.ExitWriteLock(); } } public int? Get( int index ) { try { locker.EnterReadLock(); if ( this.Count &lt;= index ) return null; return this[ index ]; } finally { locker.ExitReadLock(); } } #endregion public override string ToString() { return "RW Locked"; } } </code></pre> <p>But I get that both perform in more or less the same way:</p> <pre><code>Locked: 25003ms. RW Locked: 25002ms. End </code></pre> <p>Even making the read 20 times more often that writes, the performance is still (almost) the same. </p> <p>Am I doing something wrong here?</p> <p>Kind regards.</p>
4,217,515
11
3
null
2010-11-18 16:51:57.537 UTC
45
2022-07-20 16:17:02.883 UTC
2010-11-18 17:06:14.92 UTC
null
7,724
null
307,976
null
1
84
c#|.net|multithreading|locking
59,536
<p>In your example, the sleeps mean that <em>generally</em> there is no contention. An uncontended lock is very fast. For this to matter, you would need a <em>contended</em> lock; if there are <em>writes</em> in that contention, they should be about the same (<code>lock</code> may even be quicker) - but if it is <em>mostly</em> reads (with a write contention rarely), I would expect the <code>ReaderWriterLockSlim</code> lock to out-perform the <code>lock</code>.</p> <p>Personally, I prefer another strategy here, using reference-swapping - so reads can always read without ever checking / locking / etc. Writes make their change to a <em>cloned</em> copy, then use <code>Interlocked.CompareExchange</code> to swap the reference (re-applying their change if another thread mutated the reference in the interim).</p>
4,400,774
Java calculate hex representation of a SHA-1 digest of a String
<p>I'm storing the user password on the db as a sha1 hash.</p> <p>Unfortunately I'm getting strange answers.</p> <p>I'm storing the string as this:</p> <pre><code>MessageDigest cript = MessageDigest.getInstance("SHA-1"); cript.reset(); cript.update(userPass.getBytes("utf8")); this.password = new String(cript.digest()); </code></pre> <p>I wanted something like this --></p> <p>aff --> "0c05aa56405c447e6678b7f3127febde5c3a9238"</p> <p>rather than</p> <p>aff --> �V@\D~fx����:�8</p>
4,400,872
16
3
null
2010-12-09 16:44:07.587 UTC
9
2022-02-14 06:45:40.333 UTC
2016-01-14 19:07:46.407 UTC
null
995,935
null
196,886
null
1
61
java|hash|sha1
101,893
<p>This is happening because cript.digest() returns a byte array, which you're trying to print out as a character String. You want to convert it to a printable Hex String.</p> <p>Easy solution: Use Apache's <a href="http://commons.apache.org/codec/" rel="noreferrer">commons-codec library</a>:</p> <pre><code>String password = new String(Hex.encodeHex(cript.digest()), CharSet.forName("UTF-8")); </code></pre>
14,646,008
jQuery DatePicker Min Max dates
<p>I have the jQuery date picker setup and working but would like help with setting the minDate and maxDate options. My current code is below (without these options). How can I set the minDate as 3 months before the defaultDate, and maxDate as 28days after the defaultDate?</p> <pre><code>var expdisp = $("#expdisp").attr("value"); $("#expirydate" ).datepicker({ showOn: "button", buttonImage: "images/calendar.gif", buttonImageOnly: true, dateFormat: "dd/mm/yy", defaultDate: expdisp, showOtherMonths: true, selectOtherMonths: true, changeMonth: true, changeYear: true, }); </code></pre>
14,646,145
6
0
null
2013-02-01 12:10:31.22 UTC
0
2020-06-15 16:47:08.78 UTC
null
null
null
null
930,407
null
1
11
jquery|datepicker|maxdate|mindate
84,578
<pre><code>$(function() { $( "#datepicker" ).datepicker({ changeYear: true, minDate: '-3M', maxDate: '+28D', }); }); </code></pre> <p><a href="http://jsfiddle.net/kGjdL/114/">JSFiddle Demo</a></p> <p><strong>UPDATE</strong></p> <p>You can calculate tour max and min valid dates from the default date, then assign it to the date picker.</p> <pre><code>var expdisp = $("#expdisp").attr("value"); $("#expirydate" ).datepicker({ showOn: "button", buttonImage: "images/calendar.gif", buttonImageOnly: true, dateFormat: "dd/mm/yy", defaultDate: expdisp, showOtherMonths: true, selectOtherMonths: true, changeMonth: true, changeYear: true, minDate: '-3M', maxDate: '+28D', }); </code></pre> <p><a href="http://jsfiddle.net/kGjdL/120/">Update Demo</a></p>
14,810,084
How to find the difference of two timestamps in java?
<p>I have an <code>ArrayList</code> including several number of time-stamps and the aim is finding the difference of the first and the last elements of the <code>ArrayList</code>.</p> <pre><code>String a = ArrayList.get(0); String b = ArrayList.get(ArrayList.size()-1); long diff = b.getTime() - a.getTime(); </code></pre> <p>I also converted the types to int but still it gives me an error <code>The method getTime is undefined for the type String</code>.</p> <p>Additional info :</p> <p>I have a class A which includes </p> <pre><code>String timeStamp = new SimpleDateFormat("ss S").format(new Date()); </code></pre> <p>and there is a class B which has a method <code>private void dialogDuration(String timeStamp)</code></p> <p>and <code>dialogueDuration</code> method includes:</p> <pre><code>String a = timeSt.get(0); // timeSt is an ArrayList which includes all the timeStamps String b = timeSt.get(timeSt.size()-1); // This method aims finding the difference of the first and the last elements(timestamps) of the ArrayList (in seconds) long i = Long.parseLong(a); long j = Long.parseLong(b); long diff = j.getTime()- i.getTime(); System.out.println("a: " +i); System.out.println("b: " +j); </code></pre> <p>And one condition is that the statement(<code>String timeStamp = new SimpleDateFormat("ss S").format(new Date());</code>) wont be changed in class A. And an object of class B is created in class A so that it invokes the <code>dialogueDuration(timeStamp)</code> method and passes the values of time-stamps to class B.</p> <p>My problem is this subtraction does not work, it gives an error <code>cannot invoke getTime() method on the primitive type long</code>. It gives the same kind of error also for int and String types?</p> <p>Thanks a lot in advance!</p>
14,811,167
4
5
null
2013-02-11 10:17:55.45 UTC
3
2021-10-29 13:36:10.7 UTC
2014-07-25 22:46:58.44 UTC
null
64,046
null
2,052,015
null
1
11
java|datetime|arraylist|date-difference
101,047
<p>Maybe like this:</p> <pre><code>SimpleDateFormat dateFormat = new SimpleDateFormat("ss S"); Date firstParsedDate = dateFormat.parse(a); Date secondParsedDate = dateFormat.parse(b); long diff = secondParsedDate.getTime() - firstParsedDate.getTime(); </code></pre>
14,447,668
<input type="number"/> is not showing a number keypad on iOS
<p>According to <a href="http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariHTMLRef/Articles/InputTypes.html">Apple's documentation</a> when I setup an input element with a type of <code>number</code> I should get a number keypad.</p> <pre><code>&lt;input type="number"/&gt; </code></pre> <blockquote> <p><code>number</code>: A text field for specifying a number. Brings up a number pad keyboard in iOS 3.1 and later.</p> </blockquote> <p>Looks damn near impossible to mess up. However, when I view this simple fiddle on my iPhone or the simulator (both iOS6) the number keypad does not appear, and I get the standard alphabetic keyboard instead.</p> <p><a href="http://jsfiddle.net/Cy4aC/3/">http://jsfiddle.net/Cy4aC/3/</a></p> <p>What on earth could I possibly have messed up here?</p> <p><img src="https://i.stack.imgur.com/PhvHf.png" alt="enter image description here"></p>
14,447,832
6
1
null
2013-01-21 21:36:08.87 UTC
13
2020-09-02 19:11:28.02 UTC
null
null
null
null
62,076
null
1
90
ios|html
80,536
<p>You need to specify the pattern:</p> <pre><code>&lt;input type="number" pattern="\d*"/&gt; </code></pre> <p>As a <code>number</code> can be negative or with floating point, so the <kbd>-</kbd> and <kbd>.</kbd> and <kbd>,</kbd> should be available in the keyboard, unless you specify a digits only pattern.</p> <p><img src="https://i.stack.imgur.com/58b42.png" alt="enter image description here"></p>
14,414,582
Java split string to array
<p>I need help with the <code>split()</code> method. I have the following<code>String</code>: </p> <pre><code>String values = "0|0|0|1|||0|1|0|||"; </code></pre> <p>I need to put the values into an array. There are 3 possible strings: "0", "1", and ""</p> <p>My problem is, when i try to use <code>split()</code>:</p> <pre><code>String[] array = values.split("\\|"); </code></pre> <p>My values are saved only until the last 0. Seems like the part "|||" gets trimmed. What am i doing wrong?</p> <p>thanks</p>
14,414,642
4
0
null
2013-01-19 12:54:17.533 UTC
22
2014-11-14 08:38:28.947 UTC
2013-01-19 12:59:08.237 UTC
null
1,820,722
null
1,815,054
null
1
106
java|string|split
472,901
<p>This behavior is explicitly documented in <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29"><code>String.split(String regex)</code></a> (emphasis mine):</p> <blockquote> <p>This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. <strong>Trailing empty strings</strong> are therefore <strong>not included</strong> in the resulting array.</p> </blockquote> <p>If you want those trailing empty strings included, you need to use <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String,%20int%29"><code>String.split(String regex, int limit)</code></a> with a negative value for the second parameter (<code>limit</code>):</p> <pre><code>String[] array = values.split("\\|", -1); </code></pre>
42,133,894
Vue.js - How to properly watch for nested data
<p>I'm trying to understand how to properly watch for some prop variation. I have a parent component (.vue files) that receive data from an ajax call, put the data inside an object and use it to render some child component through a v-for directive, below a simplification of my implementation:</p> <pre><code>&lt;template&gt; &lt;div&gt; &lt;player v-for="(item, key, index) in players" :item="item" :index="index" :key="key""&gt; &lt;/player&gt; &lt;/div&gt; &lt;/template&gt; </code></pre> <p>... then inside <code>&lt;script&gt;</code> tag:</p> <pre><code> data(){ return { players: {} }, created(){ let self = this; this.$http.get('../serv/config/player.php').then((response) =&gt; { let pls = response.body; for (let p in pls) { self.$set(self.players, p, pls[p]); } }); } </code></pre> <p>item objects are like this:</p> <pre><code>item:{ prop: value, someOtherProp: { nestedProp: nestedValue, myArray: [{type: "a", num: 1},{type: "b" num: 6} ...] }, } </code></pre> <p>Now, inside my child "player" component I'm trying to watch for any Item's property variation and I use:</p> <pre><code>... watch:{ 'item.someOtherProp'(newVal){ //to work with changes in "myArray" }, 'item.prop'(newVal){ //to work with changes in prop } } </code></pre> <p>It works but it seems a bit tricky to me and I was wondering if this is the right way to do it. My goal is to perform some action every time <code>prop</code> changes or <code>myArray</code> gets new elements or some variation inside existing ones. Any suggestion will be appreciated.</p>
42,134,176
14
0
null
2017-02-09 10:16:36.263 UTC
141
2022-07-15 20:02:56.923 UTC
2018-07-02 22:06:32.987 UTC
null
197,606
null
2,351,052
null
1
654
javascript|vue.js|vue-component|vue-resource
504,443
<p>You can use a <a href="https://v2.vuejs.org/v2/api/#watch" rel="noreferrer">deep watcher</a> for that:</p> <pre><code>watch: { item: { handler(val){ // do stuff }, deep: true } } </code></pre> <p>This will now detect any changes to the objects in the <code>item</code> array and additions to the array itself (when used with <a href="https://v2.vuejs.org/v2/api/#Vue-set" rel="noreferrer">Vue.set</a>). Here's a JSFiddle: <a href="http://jsfiddle.net/je2rw3rs/" rel="noreferrer">http://jsfiddle.net/je2rw3rs/</a></p> <p><strong>EDIT</strong></p> <p>If you don't want to watch for every change on the top level object, and just want a less awkward syntax for watching nested objects directly, you can simply watch a <code>computed</code> instead:</p> <pre><code>var vm = new Vue({ el: '#app', computed: { foo() { return this.item.foo; } }, watch: { foo() { console.log('Foo Changed!'); } }, data: { item: { foo: 'foo' } } }) </code></pre> <p>Here's the JSFiddle: <a href="http://jsfiddle.net/oa07r5fw/" rel="noreferrer">http://jsfiddle.net/oa07r5fw/</a></p>
27,386,234
Object destructuring without var, let or const
<p>Why does object destructuring throw an error if there is no <code>var</code> keyword in front of it?</p> <pre><code>{a, b} = {a: 1, b: 2}; </code></pre> <p>throws <code>SyntaxError: expected expression, got '='</code></p> <p>The following three examples work without problems</p> <pre><code>var {a, b} = {a: 1, b: 2}; var [c, d] = [1, 2]; [e, f] = [1, 2]; </code></pre> <p>Bonus question: Why do we not need a <code>var</code> for array destructuring?</p> <p>I ran into the problem doing something like</p> <pre><code>function () { var {a, b} = objectReturningFunction(); // Now a and b are local variables in the function, right? // So why can't I assign values to them? {a, b} = objectReturningFunction(); } </code></pre>
27,386,370
4
0
null
2014-12-09 18:32:05.487 UTC
26
2022-03-16 06:33:39.31 UTC
2021-08-22 11:39:12.923 UTC
null
479,156
null
909,425
null
1
155
javascript|ecmascript-6
14,032
<p>The issue stems from the <code>{...}</code> operators having multiple meanings in JavaScript.</p> <p>When <code>{</code> appears at the start of a <em>Statement</em>, it'll always represent a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block" rel="noreferrer">block</a>, which can't be assigned to. If it appears later in the <em>Statement</em> as an <em>Expression</em>, then it'll represent an Object.</p> <p>The <code>var</code> helps make this distinction, since it can't be followed by a <em>Statement</em>, as will <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping" rel="noreferrer">grouping parenthesis</a>:</p> <pre><code>( {a, b} = objectReturningFunction() ); </code></pre> <p>From their docs: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#assignment_separate_from_declaration_2" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#assignment_separate_from_declaration_2</a></p> <blockquote> <p>Notes: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.</p> <p>{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.</p> <p>However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}</p> <p>Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.</p> </blockquote>
17,921,930
How to make angularJS ng-model work with objects in select elements?
<p>I have a problem with ng-model on a <code>select</code> element when passing an object from <code>option</code> elements. So, imagine we have an array of columns from a table called <code>columns</code> (the table's definition) and we'd like to creat some filters upon this definition</p> <pre><code>var columns = [ {name: 'Account ID', type: 'numeric'}, {name: 'Full name', type: 'text'}, {name: 'Date of birth', type: 'date'}, {name: 'Active', type: 'boolean'} // and so on ]; var filters = [{}]; </code></pre> <p>HTML:</p> <pre><code>&lt;div class="form-field" ng-repeat="filter in filters"&gt; &lt;select ng-model="filter"&gt; &lt;option value="" disabled&gt;Choose filter&lt;/option&gt; &lt;option ng-repeat="column in columns" ng-value="column"&gt;{{column.name}}&lt;/option&gt; &lt;/select&gt; &lt;input type="text" ng-model="filter.value"&gt; &lt;/div&gt; </code></pre> <p>As you can see, I'd like that <code>filter</code> to get the value of <code>column</code> and to add specific data in it, so at a certain moment, my filter could be like:</p> <pre><code>[ {name: 'Account ID', type: 'numeric', value: 123}, {name: 'Active', type: 'boolean', value: 'Yes'} ] </code></pre> <p>Anyway, I'm not sure this is the way of doing this, but I'd like to know how can I achieve this behavior, withour writing to much js code in the controller.</p> <p>I did some workaround to get this done using <code>ng-change</code>, passing the <code>filter</code> and the <code>column.name</code>, find the column in the <code>columns</code> array, get the <code>type</code> property, update the <code>filter</code>, but I really think that there is a simpler answer to this.</p>
17,922,317
1
0
null
2013-07-29 10:42:21.323 UTC
3
2018-11-28 09:37:51.593 UTC
2018-11-28 09:37:51.593 UTC
null
4,742,047
null
1,454,404
null
1
16
angularjs|angularjs-ng-repeat
44,626
<p>You can use <a href="http://docs.angularjs.org/api/ng.directive%3aselect">ng-options</a> to bind the selected object to a model:</p> <pre><code>&lt;div class="form-field" ng-repeat="filter in filters"&gt; &lt;select ng-options="column.name for column in columns" ng-model="filter.value"&gt; &lt;option value="" disabled&gt;Choose filter&lt;/option&gt; &lt;/select&gt; &lt;input type="text" ng-model="filter.value.name"&gt; &lt;/div&gt; </code></pre> <p><a href="http://plnkr.co/edit/C3ojySE0x6XbDwHkCD7u?p=preview">Plunker</a></p> <p><strong>Updated answer:</strong></p> <pre><code>&lt;div class="form-field" ng-repeat="filter in filters"&gt; &lt;select ng-options="column.name for column in columns" ng-model="filters[$index]"&gt; &lt;option value="" disabled&gt;Choose filter&lt;/option&gt; &lt;/select&gt; &lt;input type="text" ng-model="filters[$index].name"&gt; &lt;/div&gt; </code></pre>
55,807,824
describe is not defined when installing jest
<p>I installed <code>jest v24.7.1</code>in my project with:</p> <pre><code>npm install jest -D </code></pre> <p>Then I start writing some test files, However I got these eslint errors:</p> <pre><code>'describe' is not defined. eslint (no-undef) 'it' is not defined. eslint (no-undef) 'expect' is not defined. eslint (no-undef) </code></pre> <p>eslintrc.js:</p> <pre><code>module.exports = { env: { browser: true, es6: true }, extends: ["airbnb", "prettier", "prettier/react"], globals: { Atomics: "readonly", SharedArrayBuffer: "readonly" }, parserOptions: { ecmaFeatures: { jsx: true }, ecmaVersion: 2018, sourceType: "module" }, plugins: ["react"], rules: {} }; </code></pre> <p>Should I add another rule or a plugin to fix this?</p>
55,808,280
4
0
null
2019-04-23 09:08:56.11 UTC
3
2022-06-07 07:50:30.93 UTC
2019-04-25 21:13:35.653 UTC
null
2,071,697
null
6,548,980
null
1
86
jestjs|eslint|eslint-config-airbnb|eslintrc
33,632
<p>Add following line in <code>.eslintrc.js</code> file</p> <pre><code>"env": { "jest": true } </code></pre> <p>or</p> <pre><code>{ "plugins": ["jest"] }, "env": { "jest/globals": true } </code></pre> <p>For more details check <a href="https://stackoverflow.com/questions/31629389/how-to-use-eslint-with-jest">here</a>, it also define the same.</p> <p>Hope you installed <code>eslint-plugin-jest</code> package.If not kindly go through for <a href="https://www.npmjs.com/package/eslint-plugin-jest" rel="noreferrer">Documentation</a>.</p> <p>All the configuration details of <a href="https://eslint.org/docs/user-guide/configuring#specifying-environments" rel="noreferrer">Configuring ESLint</a>.</p>
30,219,877
Rxjava Android how to use the Zip operator
<p>I am having a lot of trouble understanding the zip operator in RxJava for my android project. Problem I need to be able to send a network request to upload a video Then i need to send a network request to upload a picture to go with it finally i need to add a description and use the responses from the previous two requests to upload the location urls of the video and picture along with the description to my server.</p> <p>I assumed that the zip operator would be perfect for this task as I understood we could take the response of two observables (video and picture requests) and use them for my final task. But I cant seem to get this to occur how I envision it.</p> <p>I am looking for someone to answer how this can be done conceptually with a bit of psuedo code. Thank you</p>
30,221,196
7
0
null
2015-05-13 15:56:53.753 UTC
22
2022-06-30 13:27:53.143 UTC
null
null
null
null
3,740,701
null
1
61
java|android|rx-java
85,803
<p>Zip operator strictly pairs emitted items from observables. It waits for both (or more) items to arrive then merges them. So yes this would be suitable for your needs. </p> <p>I would use <code>Func2</code> to chain the result from the first two observables. Notice this approach would be simpler if you use Retrofit since its api interface may return an observable. Otherwise you would need to create your own observable. </p> <pre><code>// assuming each observable returns response in the form of String Observable&lt;String&gt; movOb = Observable.create(...); // if you use Retrofit Observable&lt;String&gt; picOb = RetrofitApiManager.getService().uploadPic(...), Observable.zip(movOb, picOb, new Func2&lt;String, String, MyResult&gt;() { @Override public MyResult call(String movieUploadResponse, String picUploadResponse) { // analyze both responses, upload them to another server // and return this method with a MyResult type return myResult; } } ) // continue chaining this observable with subscriber // or use it for something else </code></pre>
34,940,044
How to remove all the spaces and \n\r in a String?
<p>What is the most efficient way to remove all the spaces, <code>\n</code> and <code>\r</code> in a String in Swift?</p> <p>I have tried:</p> <pre><code>for character in string.characters { } </code></pre> <p>But it's a little inconvenient.</p>
34,940,183
11
0
null
2016-01-22 06:05:15.71 UTC
9
2022-09-21 20:39:15.06 UTC
2018-02-27 10:14:06.42 UTC
null
3,825,016
null
5,824,723
null
1
49
ios|swift|string
56,836
<p>Swift 4:</p> <pre><code>let text = "This \n is a st\tri\rng" let test = String(text.filter { !" \n\t\r".contains($0) }) </code></pre> <p>Output:</p> <pre><code>print(test) // Thisisastring </code></pre> <p>While Fahri's answer is nice, I prefer it to be pure Swift ;)</p>
67,865,303
Type 'UploadMappingFileTask' property 'googleServicesResourceRoot' doesn't have a configured value
<p>After updating the classpath I can no longer build a release version of the app.</p> <pre><code>FAILURE: Build failed with an exception. * What went wrong: A problem was found with the configuration of task ':app:uploadCrashlyticsMappingFileRelease' (type 'UploadMappingFileTask'). - Type 'UploadMappingFileTask' property 'googleServicesResourceRoot' doesn't have a configured value. Reason: This property isn't marked as optional and no value has been configured. Possible solutions: 1. Assign a value to 'googleServicesResourceRoot'. 2. Mark property 'googleServicesResourceRoot' as optional. A problem was found with the configuration of task ':app:uploadCrashlyticsMappingFileRelease' (type 'UploadMappingFileTask'). - Type 'UploadMappingFileTask' property 'googleServicesResourceRoot' doesn't have a configured value. </code></pre> <p>I tried to read the changelog but no guidelines or documentation about it.</p>
67,995,305
4
0
null
2021-06-07 02:31:33.883 UTC
5
2022-07-20 13:32:45.933 UTC
2021-09-04 14:45:33.227 UTC
null
209,103
null
12,204,620
null
1
76
firebase|crashlytics|crashlytics-android
9,528
<p>To fix it, the Google Services plugin should be applied before any Firebase plugin in <code>/app/build.gradle</code>.</p> <p>This produces the error:</p> <pre><code>apply plugin: 'com.android.application' apply plugin: 'com.google.firebase.crashlytics' apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.firebase.firebase-perf' </code></pre> <p>While this does not:</p> <pre><code>apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.firebase.crashlytics' apply plugin: 'com.google.firebase.firebase-perf </code></pre> <p>Note that <code>com.google.gms.google-services</code> is <strong>ABOVE</strong> <code>com.google.firebase.crashlytics</code>.</p> <p>When you update to <code>com.google.firebase:firebase-crashlytics-gradle:2.7.0</code> and sync the changes, you are given a message stating that is the fix as follows:</p> <pre><code>Configure project :app Crashlytics could not find Google Services plugin task: processReleaseGoogleServices. Make sure com.google.gms.google-services is applied BEFORE com.google.firebase.crashlytics. If you are not using the Google Services plugin, you must explicitly declare `googleServicesResourceRoot` inputs for Crashlytics upload tasks. </code></pre>
28,331,017
Rewind an ifstream object after hitting the end of file
<p>Having a text file with a few characters (lets say 10), you can try to read 1000 characters from it.</p> <pre><code>char *buf = new char[1000]; ifstream in(&quot;in.txt&quot;); in.read(buf, 1000); </code></pre> <p>This, of course, will set the <a href="http://en.cppreference.com/w/cpp/io/ios_base/iostate" rel="noreferrer">eofbit</a> flag (and the <a href="http://en.cppreference.com/w/cpp/io/ios_base/iostate" rel="noreferrer">failbit</a> too), however, you will be able to obtain the desired characters.</p> <p>Now, suppose you want to read the file again (from the beginning):</p> <pre><code>in.seekg(0); // Sets input position indicator. in.read(buf, 100); // Try to read again. </code></pre> <p>This does not work: because if you call:</p> <pre><code>int count = in.gcount() // Charecters readed from input. </code></pre> <p>you will notice that <code>count == 0</code>. Meaning it has not read anything at all.</p> <p>Hence the question: How can you rewind the file after you get to the end of the file?</p>
28,331,018
1
0
null
2015-02-04 20:40:48.39 UTC
11
2020-10-09 14:28:04.653 UTC
2020-10-09 14:28:04.653 UTC
null
2,890,724
null
2,890,724
null
1
28
c++|io|ifstream
20,750
<h1>Solution</h1> <p>Use <a href="http://en.cppreference.com/w/cpp/io/basic_ios/clear" rel="noreferrer">clear</a> for cleaning the state of the ifstream before call <code>seekg</code>. <strong>Be sure to check first if you don't will need to know the state later.</strong></p> <pre><code>in.clear(); in.seekg(0); </code></pre> <h1>Explanation</h1> <p><a href="http://en.cppreference.com/w/cpp/io/basic_istream/seekg" rel="noreferrer">seekg</a> sets the cursor position, but doesn't <strong>clear</strong> state bit <a href="http://en.cppreference.com/w/cpp/io/ios_base/iostate" rel="noreferrer">failbit</a> so, the <a href="http://en.cppreference.com/w/cpp/io/basic_ifstream" rel="noreferrer">ifstream</a> instance &quot;thinks&quot; there is something wrong yet.</p> <p>From the standar specification:</p> <blockquote> <p><strong>std::basic_istream::seekg</strong> behaves as <a href="http://en.cppreference.com/w/cpp/concept/UnformattedInputFunction" rel="noreferrer">UnformattedInputFunction</a>, except that gcount() is not affected.</p> </blockquote> <p>And we can read in <a href="http://en.cppreference.com/w/cpp/concept/UnformattedInputFunction" rel="noreferrer">UnformattedInputFunction</a>:</p> <blockquote> <p>The following standard library functions are <strong>UnformattedInputFunctions</strong>:</p> <p><strong>basic_istream::seekg</strong>, except <strong>that it first clears eofbit</strong> and does not modify gcount</p> </blockquote> <p>In the question example if you print the state before and after the seekg you get:</p> <pre><code>cout &lt;&lt; &quot;State before seekg: &quot; &lt;&lt; in.rdstate() &lt;&lt; endl; // Prints 3 (11 in binary) failbit and eofbit activated. in.seekg(0); cout &lt;&lt; &quot;State after seekg: &quot; &lt;&lt; in.rdstate() &lt;&lt; endl; // Prints 2 (10 in binary) just failbit activated. </code></pre> <p>That's why!!</p> <p>seekg doesn't clear <a href="http://en.cppreference.com/w/cpp/io/ios_base/iostate" rel="noreferrer">failbit</a> and for some implementation reason, it doesn't works with such bit activated.</p> <h2>My guess</h2> <p>Why <code>seekg</code> does not work when <a href="http://en.cppreference.com/w/cpp/io/ios_base/iostate" rel="noreferrer">failbit</a> is activated?</p> <p>It has to do with the fact this bit is not only activated when the stream reach the end of the file. And it might be situations in which after failbit is activated, using <code>seekg</code> is error prone or might shows undefined behaviour.</p>
28,056,595
Bundle not working with rbenv
<p>I'm trying to use bundler with rbenv. I has been working until today. The only thing I may have done to break it was <code>gem pristine --all</code> or <code>gem cleanup</code> ? When trying to install bundler i get the following error.</p> <pre><code>Antarrs-MacBook-Pro:some-app antarrbyrd$ sudo gem install bundler Password: Bundler gave the error "Could not find mail-2.5.4 in any of the sources" while processing "/Users/antarrbyrd/dev/some-app/Gemfile". Perhaps you forgot to run "bundle install"? Successfully installed bundler-1.7.12 Parsing documentation for bundler-1.7.12 Done installing documentation for bundler after 3 seconds 1 gem installed Antarrs-MacBook-Pro:some-app antarrbyrd$ bundle install /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/dependency.rb:315:in `to_specs': Could not find 'bundler' (&gt;= 0) among 8 total gem(s) (Gem::LoadError) Checked in 'GEM_PATH=/Users/antarrbyrd/.gem', execute `gem env` for more information from /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/dependency.rb:324:in `to_spec' from /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_gem.rb:64:in `gem' from /usr/local/bin/bundle:22:in `&lt;main&gt;' </code></pre> <p>when i do <code>rbenv rehash</code> or <code>rbenv bundler on</code> it get this error</p> <pre><code>Bundler gave the error "Could not find mail-2.5.4 in any of the sources" while processing "/Users/antarrbyrd/dev/some-app/Gemfile". Perhaps you forgot to run "bundle install"? </code></pre> <p>~/.bash_profile</p> <pre><code>export BUNDLER_EDITOR=atom export PATH=$PATH:/usr/local/opt/android-sdk/build-tools/21.1.2 export HOMEBREW_GITHUB_API_TOKEN=... export ANDROID_HOME=/usr/local/opt/android-sdk export PATH="$HOME/.rbenv/bin:$PATH" if which rbenv &gt; /dev/null; then eval "$(rbenv init -)"; fi # Allow local Gem Managment # export GEM_HOME="$HOME/.gem" # export GEM_PATH="$HOME/.gem" # export PATH="$HOME/.gem/bin:$PATH" </code></pre> <p><code>gem env</code></p> <pre><code>RubyGems Environment: - RUBYGEMS VERSION: 2.2.2 - RUBY VERSION: 2.1.2 (2014-05-08 patchlevel 95) [x86_64-darwin14.0] - INSTALLATION DIRECTORY: /usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0 - RUBY EXECUTABLE: /usr/local/var/rbenv/versions/2.1.2/bin/ruby - EXECUTABLE DIRECTORY: /usr/local/var/rbenv/versions/2.1.2/bin - SPEC CACHE DIRECTORY: /Users/antarrbyrd/.gem/specs - RUBYGEMS PLATFORMS: - ruby - x86_64-darwin-14 - GEM PATHS: - /usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0 - /Users/antarrbyrd/.gem/ruby/2.1.0 - GEM CONFIGURATION: - :update_sources =&gt; true - :verbose =&gt; false - :backtrace =&gt; false - :bulk_threshold =&gt; 1000 - "gem" =&gt; "-n/usr/local/bin" - REMOTE SOURCES: - https://rubygems.org/ - SHELL PATH: - /usr/local/var/rbenv/versions/2.1.2/bin - /usr/local/Cellar/rbenv/0.4.0/libexec - /Users/antarrbyrd/.gem/bin - /usr/local/var/rbenv/shims - /usr/local/bin - /usr/bin - /bin - /usr/sbin - /sbin - /usr/local/var/rbenv/shims - /Users/antarrbyrd/.rbenv/bin - /Users/antarrbyrd/.rbenv/shims - /Users/antarrbyrd/.gem/bin - /usr/local/opt/android-sdk/build-tools/21.1.2 </code></pre> <p><strong><em>update</em></strong></p> <p>I reinstalled rbenv via brew and now I get the following error when running bundle install.</p> <pre><code>The `bundle' command exists in these Ruby versions: 2.1.5 </code></pre> <p><strong><em>response to Joel</em></strong></p> <pre><code>Antarrs-MacBook-Pro:myapp antarrbyrd$ command -v ruby /usr/local/var/rbenv/shims/ruby Antarrs-MacBook-Pro:myapp antarrbyrd$ command -v bundle /usr/local/bin/bundle Antarrs-MacBook-Pro:myapp antarrbyrd$ ruby -v ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin14.0] Antarrs-MacBook-Pro:myapp antarrbyrd$ bundle -v Bundler version 1.7.12 Antarrs-MacBook-Pro:myapp antarrbyrd$ </code></pre>
28,059,501
12
0
null
2015-01-20 22:49:11.31 UTC
18
2021-03-08 16:14:57.023 UTC
2015-01-21 15:19:02.473 UTC
null
504,963
null
504,963
null
1
57
ruby|bundler|rbenv
88,404
<p>Your installation is caught in a loop.</p> <p>Change to a directory that is not your app, and that doesn't have a Gemfile.</p> <p>Then do the usual <code>gem install bundle</code> (and use <code>sudo</code> if you need it)</p> <p>Then change to your app directory, and do the usual <code>bundle install</code>.</p> <p>Does that solve your issue? </p> <p>If you need more help, can run these commands then paste the results in your question?</p> <pre><code> $ command -v ruby $ command -v bundle $ ruby -v $ bundle -v </code></pre> <p>Look for any mismatch between the results and what you expect. This will help you track down what's happening. You may need to update your Gemfile Ruby version.</p> <p>(Also, you may want to consider changing from <code>rbenv</code> to <code>chruby</code> because it's better IMHO with these kinds of path issues)</p>
21,186,950
count++ and ++count, when to use which?
<p>So i came across this little incrementing method</p> <p>since highschool and univeristy I am used to this kind of method</p> <pre><code>char[] NewArray = new char[5] //I forgot how to declare an array string temp; console.writeline("Enter 5 letters) for (i=0; i&lt;5;i++) { NewArray[i] = console.readline() } </code></pre> <p>now based on this code</p> <p>I declare an array of char with 5 "spaces", then I ouput a message to the console asking the user to enter 5 values</p> <p>so i = 0, readline e.g. c</p> <p>thus BEFORE the console.readline statment, i=0, then it continues through the for loop, then returns to the beginning of the loop, incrementing i = 1 BEFORE excecuting the console.readline again</p> <p><strong>how does this differ to "++i", what will the "++i" do in the for loop?</strong></p>
21,186,994
4
0
null
2014-01-17 13:14:29.183 UTC
1
2014-01-17 13:41:10.197 UTC
null
null
null
user2699451
null
null
1
7
c#|increment
49,727
<p><code>count++</code> is post increment where <code>++count</code> is pre increment. suppose you write <code>count++</code> means value increase after execute this statement. but in case <code>++count</code> value will increase while executing this line.</p>
31,222,291
HackerRank Staircase Python
<p>I am trying to solve a problem in HackerRank and I am having an issue with my submission. My code works in PyCharm but HackerRank is not accepting my submission. </p> <p>Here is the problem I am trying to solve: <a href="https://www.hackerrank.com/challenges/staircase" rel="noreferrer">https://www.hackerrank.com/challenges/staircase</a></p> <p>Here is my code:</p> <pre><code>def staircase(num_stairs): n = num_stairs - 1 for stairs in range(num_stairs): print ' ' * n, '#' * stairs n -= 1 print '#' * num_stairs staircase(12) </code></pre> <p>Any ideas why HackerRank is not accpeting my answer?</p>
31,222,316
17
0
null
2015-07-04 15:30:17.357 UTC
3
2022-09-18 11:27:08.077 UTC
null
null
null
null
2,230,302
null
1
5
python
54,990
<p>Your output is incorrect; you print an empty line before the stairs that should not be there. Your <code>range()</code> loop starts at <code>0</code>, so you print <code>n</code> spaces and zero <code>#</code> characters on the first line.</p> <p>Start your <code>range()</code> at 1, and <code>n</code> should start at <code>num_stairs - 2</code> (as Multiple arguments to <code>print()</code> adds a space:</p> <pre><code>from __future__ import print_function def staircase(num_stairs): n = num_stairs - 2 for stairs in range(1, num_stairs): print(' ' * n, '#' * stairs) n -= 1 print('#' * num_stairs) </code></pre> <p>You can simplify this to one loop:</p> <pre><code>def staircase(num_stairs): for stairs in range(1, num_stairs + 1): print(' ' * (num_stairs - stairs) + '#' * stairs) </code></pre> <p>Note that I use concatenation now to combine spaces and <code>#</code> characters, so that in the last iteration of the loop zero spaces are printed and <code>num_stairs</code> <code>#</code> characters.</p> <p>Last but not least, you could use the <a href="https://docs.python.org/3/library/stdtypes.html#str.rjust" rel="noreferrer"><code>str.rjust()</code> method</a> (short for “right-justify”) to supply the spaces:</p> <pre><code>def staircase(num_stairs): for stairs in range(1, num_stairs + 1): print(('#' * stairs).rjust(num_stairs)) </code></pre>
6,035,215
How can I create a dynamic weekly schedule in HTML and Javascript?
<p>It's simple to create a table based layout for a weekly calendar with 7 columns for each day of the week and various rows for each hour of the week. I have no problem creating that. The hard part is filling in this table with daily 'events' dynamically (I'm not even sure how I would do this statically).</p> <p>The user will have access to a list of 'events' that they would like to add to their weekly schedule. And they need to be added dynamically to the webpage. Each event has a specific start and end time, and may occur on more than one day of the week. I'm not sure how I could possibly add these 'events' to my table layout without getting into a bunch of rowspan problems ( a lot of the events are various lengths and span different hours ). It would be easy if each event was always 1 hour long, but that's not the case. </p> <p>I was thinking of making each day a respective table with a hidden hour column. I still feel like this will result in a huge mess. Any ideas?</p>
6,035,542
1
2
null
2011-05-17 18:11:37.543 UTC
6
2017-07-23 08:22:44.78 UTC
2017-07-23 08:22:44.78 UTC
null
4,370,109
null
664,720
null
1
16
javascript|html|calendar|tabular
65,698
<p>Why reinvent the wheel? </p> <p>I think this covers all your concerns. </p> <p><a href="http://arshaw.com/fullcalendar/" rel="noreferrer">http://arshaw.com/fullcalendar/</a></p>
38,015,671
Asynchronous iterable mapping in Dart
<p>Can I map some Iterable using async mapping function? Maybe it is a bug, that this code prints list of _Future imidiately, not ints after 1 or 5 seconds?</p> <pre><code>import 'dart:async'; Future&lt;int&gt; foo(int i) { var c = new Completer(); new Timer(new Duration(seconds: 1), () =&gt; c.complete(i)); return c.future; } main() { var list = [1,2,3,4,5]; var mappedList = list.map((i) async =&gt; await foo(i)); print(mappedList); } </code></pre>
38,016,334
5
0
null
2016-06-24 14:21:09.517 UTC
1
2021-12-09 11:32:50.043 UTC
2019-11-01 12:47:29.167 UTC
null
6,509,751
null
5,182,106
null
1
46
dart
21,268
<p>The expression <code>(i) async =&gt; await foo(i)</code> still returns a future. You can use <code>Future.wait(mappedList)</code> to wait till all created futures are completed.</p>
37,885,213
Azure Service Fabric activation error
<p>The deployment of one of my apps to a <code>Service Fabric Cluster</code> failed and triggered an Unhealthy Evaluation with an error event saying: <code>There was an error during CodePackage activation.The service host terminated with exit code:3762504530</code></p> <p>However, on the node where the app is deployed, Health State indicates: <code>The application was activated successfully.</code></p> <p>Is there any way to get a more detailed report on the error event?</p>
37,887,407
1
0
null
2016-06-17 15:24:54.06 UTC
9
2018-04-27 07:21:54.223 UTC
null
null
null
null
701,193
null
1
19
azure|azure-service-fabric|azure-deployment
16,206
<p>I usually connect via RDP to the affected node and do the following things in such a case:</p> <ul> <li><p><strong>Check Console-Out / Console-Error logs</strong>: Service Fabric stores console output (if enabled via <code>&lt;ConsoleRedirection&gt;</code> in your <code>ServiceManifest.xml</code>) and errors in a log folder. On your DEV cluster, this should be <code>C:\SfDevCluster\Data\_App\Node.x\&lt;ApplicationTypeFolder&gt;\log</code>. On a default installation in Azure, it should be <code>D:\SvcFab\_App\&lt;ApplicationTypeFolder&gt;\log</code></p></li> <li><p><strong>EventLog</strong>: .NET exceptions sometimes show up in the "Application" log, but Service Fabric also has its own subfolder which might contain helpful events.</p></li> <li><p><strong>PerfView</strong>: PerfView is a very powerful tool to monitor ETW events (Event Tracing for Windows). Since .NET exceptions are logged as ETW events, PerfView might show you helpful exceptions. Here's a quick tutorial:</p> <ul> <li>Download and run <a href="https://github.com/Microsoft/perfview/blob/master/documentation/Downloading.md" rel="noreferrer">PerfView</a></li> <li>Go to "Collect -> Collect". De-Select "Merge". </li> <li>Click "Start Collection". </li> <li>Now kill your Service Fabric Service through Process Explorer, in case it is running. Moments later, Service Fabric will start it again. </li> <li>If your service is not running, re-deploy your service.</li> <li>After the service failed, press "Stop collection" in PerfView. </li> <li>Now double-click on "Events" in the left tree - this will open all recorded ETW events. </li> <li>Search for "Microsoft-Windows-DotNETRuntime/Exception/Start" and double click on it. </li> <li>You should now see all .NET exceptions that occurred, ordered by time.</li> </ul></li> </ul>
35,368,645
pandas - change df.index from float64 to unicode or string
<p>I want to change a dataframes' index (rows) from float64 to string or unicode. </p> <p>I thought this would work but apparently not:</p> <pre><code>#check type type(df.index) 'pandas.core.index.Float64Index' #change type to unicode if not isinstance(df.index, unicode): df.index = df.index.astype(unicode) </code></pre> <p>error message:</p> <pre><code>TypeError: Setting &lt;class 'pandas.core.index.Float64Index'&gt; dtype to anything other than float64 or object is not supported </code></pre>
35,368,792
3
0
null
2016-02-12 17:23:26.38 UTC
21
2022-04-14 12:49:03.217 UTC
2018-02-23 12:42:30.913 UTC
null
2,342,399
null
2,342,399
null
1
81
python|pandas|indexing|dataframe|rows
108,626
<p>You can do it that way:</p> <pre><code># for Python 2 df.index = df.index.map(unicode) # for Python 3 (the unicode type does not exist and is replaced by str) df.index = df.index.map(str) </code></pre> <p>As for why you would proceed differently from when you'd convert from int to float, that's a peculiarity of numpy (the library on which pandas is based).</p> <p>Every numpy array has a <em>dtype</em>, which is basically the <strong>machine</strong> type of its elements : in that manner, <strong>numpy deals directly with native types</strong>, not with Python objects, which explains how it is so fast. So when you are changing the dtype from int64 to float64, numpy will cast each element in the C code.</p> <p>There's also a special dtype : <em>object</em>, that will basically provide a pointer toward a Python object.</p> <p>If you want strings, you thus have to use the <em>object</em> dtype. But using <code>.astype(object)</code> would not give you the answer you were looking for : it would instead create an index with <em>object</em> dtype, but put Python float objects inside.</p> <p>Here, by using map, we convert the index to strings with the appropriate function: numpy gets the string objects and understand that the index has to have an <em>object</em> dtype, because that's the only dtype that can accomodate strings.</p>
25,790,268
How to save and retrieve contenteditable data
<p>I want to be able to change the text of some pages. Using contenteditable would be perfect for me.<BR> Problem is that I only know how to program in PHP. I have searched on the internet for hours trying to make it work, but I just don't understand the programming languages used to store the data enough to make it work.</p> <p>This is how I would like it to work:<BR></p> <ol> <li>Admin hits a button 'edit'<BR></li> <li>div becomes editable.<BR></li> <li>When the admin is ready editing, he hits a button 'save'<BR></li> <li>The data is saved to a file or database (don't really know what would be the best option).<BR></li> <li>The edited content shows up when the page is opened.<BR></li> </ol> <p>This is all I have for now:</p> <pre><code>&lt;div class=&quot;big_wrapper&quot; contenteditable&gt; PAGE CONTENT &lt;/div&gt; </code></pre> <p>I know how to make the part with converting the div to an contenteditable div when the admin hits 'edit'.<BR> My problem is that i really have no idea how to save the edited data.<BR> I also don't know if it would be hard to retrieve the data from a file, depents on the way how the data is saved. If it is saved to a database I would have no problem retrieving it, but I don't know if that is possible and if that is the best option.</p> <p>Thanks for your help,</p> <p>Samuël</p> <BR> <p><b>EDIT:</b></p> <p>@gibberish, thank you so much for your super-quick reply!<BR> I tried to make it work, but it doesn't work yet. I can not figure out what i'm doing wrong.</p> <p>Here's my code:<BR> <b>over_ons.php</b>:</p> <pre><code>&lt;div class=&quot;big_wrapper&quot; contenteditable&gt; PAGE CONTENT &lt;/div&gt; &lt;input type=&quot;button&quot; value=&quot;Send Data&quot; id=&quot;mybutt&quot;&gt; &lt;script type=&quot;text/javascript&quot;&gt; $('#mybutt').click(function(){ var myTxt = $('.big_wrapper').html(); $.ajax({ type: 'post', url: 'sent_data.php', data: 'varname=' +myTxt+ '&amp;anothervar=' +moreTxt }); }); &lt;/script&gt; </code></pre> <p><b>sent_data.php</b>:</p> <pre><code>&lt;?php session_start(); include_once('./main.php'); include($main .'connectie.php'); $tekst=$_POST['myTxt']; $query=&quot;UPDATE paginas SET inhoud='&quot; .$tekst. &quot;' WHERE id='1'&quot;; mysql_query($query); ?&gt; </code></pre> <p>Thanks again for your great help!<BR> Can you also help me to make the div editable only when the user hits a button?</p> <br/> <p><b>SOLUTION</b>:<br/></p> <p>It took me over 2 weeks to finally make everyting work. I had to learn javascript, jQuery and Ajax. But now it works flawlessly. I even added some extras for the fanciness :)<br> I would like to share how i did this if someone wants to do the same.<br><br></p> <p><b>over_ons.php</b>:</p> <pre><code>//Active page: $pagina = 'over_ons'; ?&gt; &lt;input type='hidden' id='pagina' value='&lt;?php echo $pagina; ?&gt;'&gt; &lt;!--Show active page to javascript--&gt;&lt;?php //Active user: if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){ $editor = $_SESSION['gebruikersnaam']; ?&gt; &lt;input type='hidden' id='editor' value='&lt;?php echo $editor; ?&gt;'&gt; &lt;!--Show active user to javascript--&gt;&lt;?php } ?&gt; &lt;!--Editable DIV: --&gt; &lt;div class='big_wrapper' id='editable'&gt; &lt;?php //Get eddited page content from the database $query=mysql_query(&quot;SELECT inhoud FROM paginas WHERE naam_pagina='&quot; .$pagina. &quot;'&quot;); while($inhoud_test=mysql_fetch_array($query)){ $inhoud=$inhoud_test[0]; } //Show content echo $inhoud; ?&gt; &lt;/div&gt; &lt;!--Show edit button--&gt; &lt;?php if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin') {?&gt; &lt;div id='sidenote'&gt; &lt;input type='button' value='Bewerken' id='sent_data' class='button' /&gt; &lt;div id=&quot;feedback&quot; /&gt; &lt;/div&gt; &lt;?php } </code></pre> <br> As this is a pretty long and complicated file, I tried to translate most of my comments to english.<br> If you want to translate something that in't already translated, the original language is Dutch. <br> <b>javascript.js</b>: <pre><code>//If the system is in edit mode and the user tries to leave the page, //let the user know it is not so smart to leave yet. $(window).bind('beforeunload', function(){ var value = $('#sent_data').attr('value'); //change the name of the edit button if(value == 'Verstuur bewerkingen'){ return 'Are you sure you want to leave the page? All unsaved edits will be lost!'; } }); //Make content editable $('#sent_data').click(function(){ var value = $('#sent_data').attr('value'); //change the name of the edit button if(value == 'Bewerken'){ $('#sent_data').attr('value', 'Verstuur bewerkingen'); //change the name of the edit button var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div editable $div.prop('contenteditable',!isEditable).toggleClass('editable') $('#feedback').html('&lt;p class=&quot;opvallend&quot;&gt;The content from&lt;BR&gt;this page is now&lt;BR&gt;editable.&lt;/p&gt;'); }else if(value == 'Verstuur bewerkingen'){ var pagina = $('#pagina').val(); var editor = $('#editor').val(); var div_inhoud = $(&quot;#editable&quot;).html(); $.ajax({ type: 'POST', url: 'sent_data.php', data: 'tekst=' +div_inhoud+ '&amp;pagina=' +pagina+ '&amp;editor=' +editor, success: function(data){ Change the div back tot not editable, and change the button's name $('#sent_data').attr('value', 'Bewerken'); //change the name of the edit button var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div not editable $div.prop('contenteditable',!isEditable).toggleClass('editable') //Tell the user if the edditing was succesfully $('#feedback').html(data); setTimeout(function(){ var value = $('#sent_data').attr('value'); //look up the name of the edit button if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text $('#feedback').text(''); } }, 5000); } }).fail(function() { //If there was an error, let the user know $('#feedback').html('&lt;p class=&quot;opvallend&quot;&gt;There was an error.&lt;BR&gt;Your changes have&lt;BR&gt;not been saved.&lt;BR&gt;Please try again.&lt;/p&gt;'); }); } }); </code></pre> <br> And finally,<br> <b>sent_data.php</b>: <pre><code>&lt;?php session_start(); include_once('./main.php'); include($main .'connectie.php'); //Look up witch page has to be edited $pagina=$_POST['pagina']; //Get the name of the person who eddited the page $editor=$_POST['editor']; //Get content: $tekst=$_POST['tekst']; $tekst = mysql_real_escape_string($tekst); $query=&quot;UPDATE paginas SET naam_editer='&quot; .$editor. &quot;', inhoud='&quot; .$tekst. &quot;' WHERE naam_pagina='&quot; .$pagina. &quot;'&quot;; } if(mysql_query($query)){ echo &quot;&lt;p class='opvallend'&gt;Successfully saves changes.&lt;/p&gt;&quot;; }else{ echo &quot;&lt;p class='opvallend'&gt;Saving of changes failed.&lt;BR&gt; Please try again.&lt;/p&gt;&quot;; } ?&gt; </code></pre>
25,792,681
2
0
null
2014-09-11 14:34:26.647 UTC
11
2020-10-03 10:00:01.04 UTC
2020-10-03 10:00:01.04 UTC
null
3,380,678
null
3,380,678
null
1
21
php|jquery|ajax|html|contenteditable
32,575
<p>Use a client-side language, such as JavaScript (or best, jQuery), to manage whether the input boxes could be edited.</p> <p>Use AJAX to grab the field data and fire it off to a PHP file, which would stick the data in your database.</p> <p>Here is a very simplified example of using jQuery to manage enabling/disabling the input fields:</p> <p><a href="http://jsfiddle.net/akjjj5d6/" rel="nofollow noreferrer">jsFiddle Demo</a></p> <pre><code>$('.editable').prop('disabled',true); $('.editbutt').click(function(){ var num = $(this).attr('id').split('-')[1]; $('#edit-'+num).prop('disabled',false).focus(); }); $('.editable').blur(function(){ var myTxt = $(this).val(); $.ajax({ type: 'post', url: 'some_php_file.php', data: 'varname=' +myTxt+ '&amp;anothervar=' +moreTxt }); }); </code></pre> <p><strong>PHP file: some_php_file.php</strong></p> <pre><code>&lt;?php $myVar = $_POST['varname']; $secondVar = $_POST['anothervar']; //Now, do what you want with the data in the vars </code></pre> <hr> <p>Using AJAX is quite easy. I gave a very brief example of what it would look like. Don't look in the HTML or jQuery for the <code>moreTxt</code> variable -- I added that to show how you would add a second var of data to the ajax.</p> <p>Here are some basic examples to bring you up to speed on ajax:</p> <p><a href="https://stackoverflow.com/questions/17973386/ajax-request-callback-using-jquery/17974843#17974843">AJAX request callback using jQuery</a></p> <hr> <p><strong><em>There is no short path to learning jQuery or AJAX. Read the examples and experiment.</em></strong></p> <p>You can find some excellent, free jQuery tutorials here:</p> <p><a href="http://thenewboston.com" rel="nofollow noreferrer">http://thenewboston.com</a></p> <p><a href="http://phpacademy.org" rel="nofollow noreferrer">http://phpacademy.org</a></p> <hr> <p><strong>UPDATE EDIT:</strong></p> <p>To respond to your comment inquiry:</p> <p>To send data from a DIV to a PHP file, first you need an <strong>event</strong> that triggers the code. As you mentioned, on an input field, this can be the <code>blur()</code> event, which triggers when you leave a field. On a <code>&lt;select&gt;</code>, it can be the <code>change()</code> event, which triggers when you choose a selection. But on a DIV... well, the user cannot interact with a div, right? The trigger must be something that the user <strong>does</strong>, such as clicking a button.</p> <p>So, the user clicks a button -- you can get the content of the DIV using the <code>.html()</code> command. (On input boxes and select controls, you would use <code>.val()</code>, but on DIVs and table cells you must use <code>.html()</code>. Code would look like this:</p> <p>How to send DIV content after a button clicked:</p> <p>HTML:</p> <pre><code>&lt;div class='big_wrapper' contenteditable&gt; PAGE CONTENT &lt;/div&gt; &lt;input id="mybutt" type="button" value="Send Data" /&gt; </code></pre> <p>jQuery:</p> <pre><code>$('#mybutt').click(function(){ var myTxt = $('.big_wrapper').html(); $.ajax({ type: 'post', url: 'some_php_file.php', data: 'varname=' +myTxt+ '&amp;anothervar=' +moreTxt }); }); </code></pre>
20,995,196
Pandas counting and summing specific conditions
<p>Are there single functions in pandas to perform the equivalents of <a href="http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx" rel="noreferrer">SUMIF</a>, which sums over a specific condition and <a href="http://office.microsoft.com/en-us/excel-help/countifs-function-HA010047494.aspx" rel="noreferrer">COUNTIF</a>, which counts values of specific conditions from Excel?</p> <p>I know that there are many multiple step functions that can be used for</p> <p>for example for <code>sumif</code> I can use <code>(df.map(lambda x: condition), or df.size())</code> then use <code>.sum()</code></p> <p>and for <code>countif</code> I can use <code>(groupby functions</code> and look for my answer or use a filter and the <code>.count())</code> </p> <p>Is there simple one step process to do these functions where you enter the condition and the data frame and you get the sum or counted results?</p>
20,995,428
3
0
null
2014-01-08 12:06:24.573 UTC
40
2021-04-04 13:15:10.687 UTC
2021-04-04 13:15:10.687 UTC
null
7,117,003
null
3,084,006
null
1
101
python|pandas|sum
331,499
<p>You can first make a conditional selection, and sum up the results of the selection using the <code>sum</code> function.</p> <pre><code>&gt;&gt; df = pd.DataFrame({'a': [1, 2, 3]}) &gt;&gt; df[df.a &gt; 1].sum() a 5 dtype: int64 </code></pre> <p>Having more than one condition:</p> <pre><code>&gt;&gt; df[(df.a &gt; 1) &amp; (df.a &lt; 3)].sum() a 2 dtype: int64 </code></pre> <p>If you want to do <code>COUNTIF</code>, just replace <code>sum()</code> with <code>count()</code></p>
22,875,453
FrameLayout vs RelativeLayout for overlays
<p>I need to implement an overlay (translucent) screen for my app, something similar to <a href="https://github.com/Espiandev/ShowcaseView">Showcase View</a></p> <p>My guess was to use <code>FrameLayout</code> for this usecase, because it is used to stack items on top of each other. But I was surprised to see that the above library uses <code>RelativeLayout</code>.</p> <p>My question is when to use <code>FrameLayout</code> then, if not in cases like this? What are the disadvantages if I go the <code>FrameLayout</code> way?</p>
22,875,614
1
0
null
2014-04-05 01:16:56.98 UTC
11
2019-04-09 01:00:43.61 UTC
2015-12-26 15:58:08.99 UTC
null
3,290,339
null
430,720
null
1
60
android|android-relativelayout|android-framelayout
40,403
<p>A common rule of thumb when choosing layouts is to select the combination that results in the smallest number of nested layout views.</p> <p>Specific to your question, RelativeLayout is larger and more capable than the much simpler FrameLayout. So for simple layouts, the latter is probably more efficient. But if using RelativeLayout and it's added positioning options allows you to implement your GUI in a smaller number of layout views, then that would likely be a better choice.</p> <p><a href="http://developer.android.com/training/improving-layouts/optimizing-layout.html" rel="noreferrer">Here's a page</a> that discusses some trade-offs and demonstrates some helpful tools to use when designing your layouts. It mostly talks about RelativeLayout and LinearLayout, but is also apropos to your choice between RelativeLayout and Framelayout. Just keep in mind that FrameLayout is an even simpler layout.</p> <p>Edit (2017): For even more complicated layouts, you may be able to avoid nested layouts by using ConstraintLayout.</p>
56,246,765
Formik values not updating with state
<p>Here's the template for a form I'm writing with Formik and react-bootstrap. I'm finding a very strange error: if I initialise my state with dummy data in the constructor, it works fine; but if I call setState with the exact same data in <code>componentDidMount</code> to simulate an API call, it breaks horribly. </p> <p>Specifically, I find that the state variable <code>alertVehicles</code> array can have non-zero length, but the corresponding Formik <code>values.alertVehicles</code> variable can be empty. Right now, the form as written renders no checkboxes. If I use <code>alertVehicles</code> instead of <code>values.alertVehicles</code> in my guard clause, then it blows up with an error <code>Cannot read property 'selected' of undefined</code>.</p> <pre><code>import React, {Component} from 'react'; import Form from 'react-bootstrap/Form'; import { Formik } from 'formik'; import Button from 'react-bootstrap/Button'; class Alerts extends Component { constructor(props) { super(props); this.loadAlertData = this.loadAlertData.bind(this); this.state = { alertRecipient: {}, alertId: '', alertVehicles: [] } } componentDidMount(){ this.loadAlertData(); } loadAlertData(){ // this will be an API call eventually, obviously. // if this is initialised in the constructor then everything works! this.setState( { alertRecipient: { name: 'Rob', simNumber: '0123456789', }, alertId: 1, alertVehicles: [ {id: 1, vrn: 'vehicle A', selected: true }, {id: 2, vrn: 'vehicle B', selected: false }, {id: 3, vrn: 'vehicle C', selected: true } ] }) } render() { const { alertRecipient, alertId, alertVehicles } = this.state; return ( &lt;&gt; &lt;Formik initialValues={{ alertRecipient, alertId, alertVehicles }} onSubmit={ values =&gt; { window.alert(JSON.stringify(values)) } } render={({values, handleChange, handleSubmit}) =&gt; ( &lt;Form onSubmit={handleSubmit}&gt; &lt;Form.Label&gt;Name&lt;/Form.Label&gt; &lt;Form.Control type="text" name="alertRecipient.name" value={values.alertRecipient.name} onChange={handleChange} /&gt; &lt;Form.Label&gt;Phone number&lt;/Form.Label&gt; &lt;Form.Control type="text" name="alertRecipient.simNumber" value={values.alertRecipient.simNumber} onChange={handleChange} &gt; &lt;/Form.Control&gt; &lt;Form.Label&gt;Vehicles&lt;/Form.Label&gt; { //get an error if we just use alertVehicles.length here?? values.alertVehicles.length === 0 ? null : alertVehicles.map((veh, index) =&gt; ( &lt;Form.Check type="checkbox" key={veh.id} label={veh.vrn} name={`alertVehicles[${index}].selected`} checked={values.alertVehicles[index].selected} onChange={ handleChange } /&gt; )) } &lt;Button type="submit"&gt;Save&lt;/Button&gt; &lt;/Form&gt; ) } /&gt; &lt;/&gt; ) } } export default Alerts; </code></pre> <p>I don't understand </p> <ol> <li>Why the code works when I set my dummy data in the constructor but not in <code>componentDidMount</code></li> <li>Why <code>values.alertVehicles</code> doesn't appear to be in sync with <code>alertVehicles</code>.</li> </ol> <p>Thanks in advance for any help.</p>
56,252,261
2
0
null
2019-05-21 21:45:19.263 UTC
3
2021-11-08 14:15:02.823 UTC
null
null
null
null
6,022,100
null
1
31
javascript|reactjs|react-bootstrap|formik
34,783
<p>For some reason this is Formik's default behaviour, and you need to supply the <code>enableReinitialize</code> prop to override it: <a href="https://github.com/jaredpalmer/formik/issues/811" rel="noreferrer">https://github.com/jaredpalmer/formik/issues/811</a></p>
2,954,381
Python form POST using urllib2 (also question on saving/using cookies)
<p>I am trying to write a function to post form data and save returned cookie info in a file so that the next time the page is visited, the cookie information is sent to the server (i.e. normal browser behavior).</p> <p>I wrote this relatively easily in C++ using curlib, but have spent almost an entire day trying to write this in Python, using urllib2 - and still no success.</p> <p>This is what I have so far:</p> <pre><code>import urllib, urllib2 import logging # the path and filename to save your cookies in COOKIEFILE = 'cookies.lwp' cj = None ClientCookie = None cookielib = None logger = logging.getLogger(__name__) # Let's see if cookielib is available try: import cookielib except ImportError: logger.debug('importing cookielib failed. Trying ClientCookie') try: import ClientCookie except ImportError: logger.debug('ClientCookie isn\'t available either') urlopen = urllib2.urlopen Request = urllib2.Request else: logger.debug('imported ClientCookie succesfully') urlopen = ClientCookie.urlopen Request = ClientCookie.Request cj = ClientCookie.LWPCookieJar() else: logger.debug('Successfully imported cookielib') urlopen = urllib2.urlopen Request = urllib2.Request # This is a subclass of FileCookieJar # that has useful load and save methods cj = cookielib.LWPCookieJar() login_params = {'name': 'anon', 'password': 'pass' } def login(theurl, login_params): init_cookies(); data = urllib.urlencode(login_params) txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} try: # create a request object req = Request(theurl, data, txheaders) # and open it to return a handle on the url handle = urlopen(req) except IOError, e: log.debug('Failed to open "%s".' % theurl) if hasattr(e, 'code'): log.debug('Failed with error code - %s.' % e.code) elif hasattr(e, 'reason'): log.debug("The error object has the following 'reason' attribute :"+e.reason) sys.exit() else: if cj is None: log.debug('We don\'t have a cookie library available - sorry.') else: print 'These are the cookies we have received so far :' for index, cookie in enumerate(cj): print index, ' : ', cookie # save the cookies again cj.save(COOKIEFILE) #return the data return handle.read() # FIXME: I need to fix this so that it takes into account any cookie data we may have stored def get_page(*args, **query): if len(args) != 1: raise ValueError( "post_page() takes exactly 1 argument (%d given)" % len(args) ) url = args[0] query = urllib.urlencode(list(query.iteritems())) if not url.endswith('/') and query: url += '/' if query: url += "?" + query resource = urllib.urlopen(url) logger.debug('GET url "%s" =&gt; "%s", code %d' % (url, resource.url, resource.code)) return resource.read() </code></pre> <p>When I attempt to log in, I pass the correct username and pwd,. yet the login fails, and no cookie data is saved. </p> <p>My two questions are:</p> <ul> <li>can anyone see whats wrong with the login() function, and how may I fix it?</li> <li>how may I modify the get_page() function to make use of any cookie info I have saved ?</li> </ul>
2,954,448
3
0
null
2010-06-02 01:07:00.497 UTC
18
2012-09-28 10:02:38.013 UTC
null
null
null
null
312,675
null
1
17
python|cookies|urllib2
16,886
<p>There are quite a few problems with the code that you've posted. Typically you'll want to build a custom opener which can handle redirects, https, etc. otherwise you'll run into trouble. As far as the cookies themselves so, you need to call the load and save methods on your <code>cookiejar</code>, and use one of subclasses, such as <code>MozillaCookieJar</code> or <code>LWPCookieJar</code>.</p> <p>Here's a class I wrote to login to Facebook, back when I was playing silly web games. I just modified it to use a file based cookiejar, rather than an in-memory one.</p> <pre><code>import cookielib import os import urllib import urllib2 # set these to whatever your fb account is fb_username = "[email protected]" fb_password = "secretpassword" cookie_filename = "facebook.cookies" class WebGamePlayer(object): def __init__(self, login, password): """ Start up... """ self.login = login self.password = password self.cj = cookielib.MozillaCookieJar(cookie_filename) if os.access(cookie_filename, os.F_OK): self.cj.load() self.opener = urllib2.build_opener( urllib2.HTTPRedirectHandler(), urllib2.HTTPHandler(debuglevel=0), urllib2.HTTPSHandler(debuglevel=0), urllib2.HTTPCookieProcessor(self.cj) ) self.opener.addheaders = [ ('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; ' 'Windows NT 5.2; .NET CLR 1.1.4322)')) ] # need this twice - once to set cookies, once to log in... self.loginToFacebook() self.loginToFacebook() self.cj.save() def loginToFacebook(self): """ Handle login. This should populate our cookie jar. """ login_data = urllib.urlencode({ 'email' : self.login, 'pass' : self.password, }) response = self.opener.open("https://login.facebook.com/login.php", login_data) return ''.join(response.readlines()) test = WebGamePlayer(fb_username, fb_password) </code></pre> <p>After you've set your username and password, you should see a file, <code>facebook.cookies</code>, with your cookies in it. In practice you'll probably want to modify it to check whether you have an active cookie and use that, then log in again if access is denied.</p>
2,433,966
iframe contents change event?
<p>How can I detect when the iframe content has changed and do something upon that change pseudo code below</p> <pre><code> $('#waframe').contents().change(function(){ //do stuff }); </code></pre>
2,434,336
3
0
null
2010-03-12 16:04:03.127 UTC
5
2020-02-17 12:56:33.937 UTC
null
null
null
null
234,670
null
1
26
jquery|iframe
67,863
<p>Well, the browser seems to generate a "load" event on an <code>&lt;iframe&gt;</code> element in the context of the containing page. The "load" fires when the "src" is changed; not sure whether it fires when the iframe changes itself.</p> <p><strong>edit:</strong> yes it does seem to fire when the page reloads "internally"</p> <p>Thus you might try:</p> <pre><code>$('iframe#yourId').load(function() { alert("the iframe has been loaded"); }); </code></pre>
2,619,543
How do I obtain the machine epsilon in R?
<p>Is there a constant that stores the machine epsilon in R?</p>
2,619,620
3
0
null
2010-04-12 02:23:53.777 UTC
6
2015-02-05 22:00:54.6 UTC
2010-04-12 02:39:40.913 UTC
null
29
null
239,923
null
1
46
r|numerical-methods
24,574
<p>Try <code>.Machine$double.eps</code> -- and <code>.Machine</code> which on my 32-bit Linux machine yields this:</p> <pre><code>R&gt; .Machine $double.eps [1] 2.220e-16 $double.neg.eps [1] 1.110e-16 $double.xmin [1] 2.225e-308 $double.xmax [1] 1.798e+308 $double.base [1] 2 $double.digits [1] 53 $double.rounding [1] 5 $double.guard [1] 0 $double.ulp.digits [1] -52 $double.neg.ulp.digits [1] -53 $double.exponent [1] 11 $double.min.exp [1] -1022 $double.max.exp [1] 1024 $integer.max [1] 2147483647 $sizeof.long [1] 4 $sizeof.longlong [1] 8 $sizeof.longdouble [1] 12 $sizeof.pointer [1] 4 R&gt; </code></pre>
3,051,486
Search a value for a given key in a HashMap
<p>How do you search for a key in a <code>HashMap</code>? In this program, when the user enters a key the code should arrange to search the hashmap for the corresponding value and then print it.</p> <p>Please tell me why it's not working.</p> <pre><code>import java.util.HashMap; import java.util.; import java.lang.; public class Hashmapdemo { public static void main(String args[]) { String value; HashMap hashMap = new HashMap(); hashMap.put( new Integer(1),"January" ); hashMap.put( new Integer(2) ,"February" ); hashMap.put( new Integer(3) ,"March" ); hashMap.put( new Integer(4) ,"April" ); hashMap.put( new Integer(5) ,"May" ); hashMap.put( new Integer(6) ,"June" ); hashMap.put( new Integer(7) ,"July" ); hashMap.put( new Integer(8),"August" ); hashMap.put( new Integer(9) ,"September"); hashMap.put( new Integer(10),"October" ); hashMap.put( new Integer(11),"November" ); hashMap.put( new Integer(12),"December" ); Scanner scan = new Scanner(System.in); System.out.println("Enter an integer :"); int x = scan.nextInt(); value = hashMap.get("x"); System.out.println("Value is:" + value); } } </code></pre>
3,051,491
4
1
null
2010-06-16 07:48:55.97 UTC
5
2020-07-12 13:46:30.26 UTC
2016-07-20 20:06:04.52 UTC
null
131,187
null
367,244
null
1
22
java
94,422
<p>Just call <a href="http://java.sun.com/javase/6/docs/api/java/util/HashMap.html#get(java.lang.Object)" rel="noreferrer"><code>get</code></a>:</p> <pre><code>HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); map.put("x", "y"); String value = map.get("x"); // value = "y" </code></pre>
29,088,754
Apache Spark vs Akka
<p>Could you please tell me the difference between Apache Spark and AKKA, I know that both frameworks meant to programme distributed and parallel computations, yet i don't see the link or the difference between them.</p> <p>Moreover, I would like to get the use cases suitable for each of them.</p>
29,089,468
4
0
null
2015-03-16 23:29:17.76 UTC
16
2020-05-01 16:58:39.45 UTC
2020-05-01 16:58:39.45 UTC
null
4,157,124
user4658980
null
null
1
67
apache-spark|parallel-processing|akka|distributed-computing
43,205
<p>Apache Spark is actually built on Akka. </p> <p>Akka is a general purpose framework to create reactive, distributed, parallel and resilient concurrent applications in Scala or Java. Akka uses the Actor model to hide all the thread-related code and gives you really simple and helpful interfaces to implement a scalable and fault-tolerant system easily. A good example for Akka is a real-time application that consumes and process data coming from mobile phones and sends them to some kind of storage.</p> <p>Apache Spark (not Spark Streaming) is a framework to process batch data using a generalized version of the map-reduce algorithm. A good example for Apache Spark is a calculation of some metrics of stored data to get a better insight of your data. The data gets loaded and processed on demand.</p> <p>Apache Spark Streaming is able to perform similar actions and functions on near real-time small batches of data the same way you would do it if the data would be already stored.</p> <p><strong>UPDATE APRIL 2016</strong></p> <p>From Apache Spark 1.6.0, Apache Spark is no longer relying on Akka for communication between nodes. Thanks to @EugeneMi for the comment.</p>
29,219,984
Can I store a method in a variable in Java 8?
<p>Is it possible to store a method into a variable? Something like</p> <pre><code> public void store() { SomeClass foo = &lt;getName() method&gt;; //... String value = foo.call(); } private String getName() { return &quot;hello&quot;; } </code></pre> <p>I think this is possible with lambdas but I don't know how.</p>
29,220,300
3
0
null
2015-03-23 20:43:17.47 UTC
7
2022-08-26 15:11:14.837 UTC
2022-08-26 15:11:14.837 UTC
null
2,756,409
null
4,301,564
null
1
45
java|lambda|java-8
74,494
<p>Yes, you can have a variable reference to any method. For simple methods it's usually enough to use <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html" rel="noreferrer"><code>java.util.function.*</code> classes</a>. Here's a working example:</p> <pre><code>import java.util.function.Consumer; public class Main { public static void main(String[] args) { final Consumer&lt;Integer&gt; simpleReference = Main::someMethod; simpleReference.accept(1); final Consumer&lt;Integer&gt; another = i -&gt; System.out.println(i); another.accept(2); } private static void someMethod(int value) { System.out.println(value); } } </code></pre> <p>If your method does not match any of those interfaces, you can define your own. The only requirement is that is must have a single abstract method.</p> <pre><code>public class Main { public static void main(String[] args) { final MyInterface foo = Main::test; final String result = foo.someMethod(1, 2, 3); System.out.println(result); } private static String test(int foo, int bar, int baz) { return &quot;hello&quot;; } @FunctionalInterface // Not required, but expresses intent that this is designed // as a lambda target public interface MyInterface { String someMethod(int foo, int bar, int baz); } } </code></pre>
52,556,364
What is the difference between UseHttpsRedirection and UseHsts
<p>I don't quite get the difference between <code>UseHsts</code> and <code>UseHttpsRedirection</code> in the configure section of the startup file in .net core. Could anyone explain?</p>
52,557,701
3
1
null
2018-09-28 13:21:43.413 UTC
1
2022-02-01 00:12:06.457 UTC
2018-09-28 14:43:26.183 UTC
null
86,860
null
4,954,382
null
1
31
asp.net|.net|.net-core
18,261
<p>According to the documentation you should use both together:</p> <blockquote> <p>We recommend all production ASP.NET Core web apps call:</p> <ul> <li>The HTTPS Redirection Middleware (UseHttpsRedirection) to redirect all HTTP requests to HTTPS.</li> <li>UseHsts, HTTP Strict Transport Security Protocol (HSTS).</li> </ul> </blockquote> <p><a href="https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-2.1&amp;tabs=visual-studio" rel="noreferrer">ASP.NET Core Enforce HTTPS</a></p> <p>The <code>.UseHttpsRedirection()</code> will issue HTTP response codes redirecting from http to https. The <code>.UseHsts()</code> will add the HSTS response <a href="https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-2.1&amp;tabs=visual-studio#http-strict-transport-security-protocol-hsts" rel="noreferrer">header which the client is supposed to obey.</a></p>
956,743
How to create a System.Linq.Expressions.Expression for Like?
<p>I created a filterable BindingList <a href="http://www.nablasoft.com/alkampfer/index.php/2008/11/22/extend-bindinglist-with-filter-functionality/" rel="noreferrer">from this source</a>. It works great:</p> <pre><code>list.Filter("Customer == 'Name'"); </code></pre> <p>does what it should. The internals work like a parser, that converts the expression <code>==</code> or <code>!=</code> into <code>System.Linq.Expressions.Expression</code>. In this case, <code>==</code> becomes <code>System.Linq.Expressions.Expression.Equal</code>.</p> <p>Unfortunately <code>System.Linq.Expressions.Expression</code> does not contain a like operator and I don't know how to solve this.</p> <p>The initial code looks like this:</p> <pre><code>private static Dictionary&lt;String, Func&lt;Expression, Expression, Expression&gt;&gt; binaryOpFactory = new Dictionary&lt;String, Func&lt;Expression, Expression, Expression&gt;&gt;(); static Init() { binaryOpFactory.Add("==", Expression.Equal); binaryOpFactory.Add("&gt;", Expression.GreaterThan); binaryOpFactory.Add("&lt;", Expression.LessThan); binaryOpFactory.Add("&gt;=", Expression.GreaterThanOrEqual); binaryOpFactory.Add("&lt;=", Expression.LessThanOrEqual); binaryOpFactory.Add("!=", Expression.NotEqual); binaryOpFactory.Add("&amp;&amp;", Expression.And); binaryOpFactory.Add("||", Expression.Or); } </code></pre> <p>Then I created an expression that will do what I want:</p> <pre><code>private static System.Linq.Expressions.Expression&lt;Func&lt;String, String, bool&gt;&gt; Like_Lambda = (item, search) =&gt; item.ToLower().Contains(search.ToLower()); private static Func&lt;String, String, bool&gt; Like = Like_Lambda.Compile(); </code></pre> <p>e.g.</p> <pre><code>Console.WriteLine(like("McDonalds", "donAld")); // true Console.WriteLine(like("McDonalds", "King")); // false </code></pre> <p>But <code>binaryOpFactory</code> requires this:</p> <pre><code>Func&lt;Expression, Expression, Expression&gt; </code></pre> <p>The predefined expressions seem to be exactly that:</p> <pre><code>System.Linq.Expressions.Expression.Or; </code></pre> <p>Can anyone tell me how to convert my expression?</p>
958,098
2
3
null
2009-06-05 16:10:00.67 UTC
14
2015-05-08 00:19:17.833 UTC
2015-05-08 00:19:17.833 UTC
null
6,651
null
98,491
null
1
17
c#|linq|lambda|expression
37,278
<p>Something like:</p> <pre><code>static IEnumerable&lt;T&gt; WhereLike&lt;T&gt;( this IEnumerable&lt;T&gt; data, string propertyOrFieldName, string value) { var param = Expression.Parameter(typeof(T), "x"); var body = Expression.Call( typeof(Program).GetMethod("Like", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public), Expression.PropertyOrField(param, propertyOrFieldName), Expression.Constant(value, typeof(string))); var lambda = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(body, param); return data.Where(lambda.Compile()); } static bool Like(string a, string b) { return a.Contains(b); // just for illustration } </code></pre> <hr> <p>In terms of a <code>Func&lt;Expression,Expression,Expression&gt;</code>:</p> <pre><code>static Expression Like(Expression lhs, Expression rhs) { return Expression.Call( typeof(Program).GetMethod("Like", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public) ,lhs,rhs); } </code></pre>
697,336
How do I programmatically find out my PermGen space usage?
<p>I'm trying to diagnose a <code>java.lang.OutOfMemoryError: PermGen Space</code> error when running on Sun's Hotspot JVM, and would like to know how much PermGen space my program is using at various points. Is there a way of finding out this information programmatically?</p>
697,428
2
0
null
2009-03-30 14:00:52.09 UTC
18
2014-04-10 10:52:51.937 UTC
null
null
null
simonn
4,728
null
1
25
java|memory-leaks|jvm-hotspot|permgen
9,039
<p>You can use something like this:</p> <pre><code>Iterator&lt;MemoryPoolMXBean&gt; iter = ManagementFactory.getMemoryPoolMXBeans().iterator(); while (iter.hasNext()) { MemoryPoolMXBean item = iter.next(); String name = item.getName(); MemoryType type = item.getType(); MemoryUsage usage = item.getUsage(); MemoryUsage peak = item.getPeakUsage(); MemoryUsage collections = item.getCollectionUsage(); } </code></pre> <p>This will give you all types of memory. You are interested in "Perm Gen" type.</p>
433,539
initWithFrame not called, but awakeFromNib is
<p>I am trying to subclass NSOutlineView. Here is my code:</p> <p>OutlineViewSublcass.h:</p> <pre><code>#import &lt;Cocoa/Cocoa.h&gt; @interface OutlineViewSubclass : NSOutlineView { } @end </code></pre> <p>OutlineViewSubclass.m:</p> <pre><code>#import "OutlineViewSubclass.h" @implementation OutlineViewSubclass - (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; printf("debug A\n"); return self; } - (void)awakeFromNib { printf("debug B\n"); } @end </code></pre> <p>The debug output is:</p> <pre><code>debug B </code></pre> <p>Why isn't <code>(id)initWithFrame:(NSRect)frame</code> being called?</p>
433,596
2
0
null
2009-01-11 19:56:57.143 UTC
8
2019-08-23 23:35:28.453 UTC
2015-05-23 09:01:15.147 UTC
null
471,303
Sam Lee
53,839
null
1
30
cocoa
19,576
<p>Cocoa controls implement the NSCoding protocol for unarchiving from a nib. Instead of initializing the object using initWithFrame: and then setting the attributes, the initWithCoder: method takes responsibility for setting up the control when it's loaded using the serialized attributes configured by Interface Builder. This works pretty much the same way any object is serialized using NSCoding.</p> <p>It's a little bit different if you stick a custom NSView subclass in a nib that doesn't implement NSCoding, in that case initWithFrame: will be called. In both cases awakeFromNib will be called after the object is loaded, and is usually a pretty good place to perform additional initialization in your subclasses.</p>
1,331,815
Regular Expression to match cross platform newline characters
<p>My program can accept data that has newline characters of \n, \r\n or \r (eg Unix, PC or Mac styles)</p> <p>What is the best way to construct a regular expression that will match whatever the encoding is?</p> <p>Alternatively, I could use universal_newline support on input, but now I'm interested to see what the regex would be.</p>
1,331,840
2
5
null
2009-08-26 00:54:20.84 UTC
13
2017-11-01 10:17:45.203 UTC
2011-04-14 03:21:10.013 UTC
null
527,702
null
19,391
null
1
62
python|regex|cross-platform|eol
25,371
<p>The regex I use when I want to be precise is <code>"\r\n?|\n"</code>.</p> <p>When I'm not concerned about consistency or empty lines, I use <code>"[\r\n]+"</code>, I imagine it makes my programs somewhere in the order of 0.2% faster.</p>
48,426
How could I graphically display the memory layout from a .map file?
<p>My gcc build toolchain produces a .map file. How do I display the memory map graphically?</p>
112,078
2
6
null
2008-09-07 13:26:57.503 UTC
21
2018-09-18 21:01:02.363 UTC
2017-01-21 04:57:56.59 UTC
null
1,079,354
Jeff V
445,087
null
1
65
c++|c|linker
25,345
<p>Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the <code>sections</code> and <code>symbols</code> lists).</p> <p>You can control the script by modifying these lines:</p> <pre><code>with open('t.map') as f: colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E'] total_height = 32.0 </code></pre> <p>map2html.py</p> <pre><code>from __future__ import with_statement import re class Section: def __init__(self, address, size, segment, section): self.address = address self.size = size self.segment = segment self.section = section def __str__(self): return self.section+"" class Symbol: def __init__(self, address, size, file, name): self.address = address self.size = size self.file = file self.name = name def __str__(self): return self.name #=============================== # Load the Sections and Symbols # sections = [] symbols = [] with open('t.map') as f: in_sections = True for line in f: m = re.search('^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+((\[[ 0-9]+\])|\w+)\s+(.*?)\s*$', line) if m: if in_sections: sections.append(Section(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: symbols.append(Symbol(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: if len(sections) &gt; 0: in_sections = False #=============================== # Gererate the HTML File # colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E'] total_height = 32.0 segments = set() for s in sections: segments.add(s.segment) segment_colors = dict() i = 0 for s in segments: segment_colors[s] = colors[i % len(colors)] i += 1 total_size = 0 for s in symbols: total_size += s.size sections.sort(lambda a,b: a.address - b.address) symbols.sort(lambda a,b: a.address - b.address) def section_from_address(addr): for s in sections: if addr &gt;= s.address and addr &lt; (s.address + s.size): return s return None print "&lt;html&gt;&lt;head&gt;" print " &lt;style&gt;a { color: black; text-decoration: none; font-family:monospace }&lt;/style&gt;" print "&lt;body&gt;" print "&lt;table cellspacing='1px'&gt;" for sym in symbols: section = section_from_address(sym.address) height = (total_height/total_size) * sym.size font_size = 1.0 if height &gt; 1.0 else height print "&lt;tr style='background-color:#%s;height:%gem;line-height:%gem;font-size:%gem'&gt;&lt;td style='overflow:hidden'&gt;" % \ (segment_colors[section.segment], height, height, font_size) print "&lt;a href='#%s'&gt;%s&lt;/a&gt;" % (sym.name, sym.name) print "&lt;/td&gt;&lt;/tr&gt;" print "&lt;/table&gt;" print "&lt;/body&gt;&lt;/html&gt;" </code></pre> <p>And here's a bad rendering of the HTML it outputs:</p> <p><img src="https://i.imgur.com/jsGhtBn.png" alt="Map"></p>
2,905,878
Creating SQL table using dynamic variable name
<p>I want to create backup SQL tables using variable names.</p> <p>something along the lines of </p> <pre><code>DECLARE @SQLTable Varchar(20) SET @SQLTable = 'SomeTableName' + ' ' + '20100526' SELECT * INTO quotename(@SQLTable) FROM SomeTableName </code></pre> <p>but i'm getting </p> <blockquote> <p>Incorrect syntax near '@SQLTable'.</p> </blockquote> <p>It's just part of a small script for maintence so i don't have to worry about injections.</p>
2,905,920
5
0
null
2010-05-25 15:03:02.333 UTC
5
2022-07-06 15:05:05.187 UTC
2019-01-24 16:27:07.547 UTC
null
133
null
70,903
null
1
13
sql|sql-server|database|tsql|dynamic-sql
45,342
<pre><code>DECLARE @MyTableName sysname; DECLARE @DynamicSQL nvarchar(max); SET @MyTableName = 'FooTable'; SET @DynamicSQL = N'SELECT * INTO ' + QUOTENAME(@MyTableName) + ' FROM BarTable'; EXEC sp_executesql @DynamicSQL; </code></pre>
2,709,220
How do I keep JTextFields in a Java Swing BoxLayout from expanding?
<p>I have a <code>JPanel</code> that looks something like this:</p> <pre><code>JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); ... panel.add(jTextField1); panel.add(Box.createVerticalStrut(10)); panel.add(jButton1); panel.add(Box.createVerticalStrut(30)); panel.add(jTextField2); panel.add(Box.createVerticalStrut(10)); panel.add(jButton2); ... //etc. </code></pre> <p>My problem is that the <code>JTextField</code>s become huge vertically. I want them to only be high enough for a single line, since that is all that the user can type in them. The buttons are fine (they don't expand vertically).</p> <p>Is there any way to keep the <code>JTextField</code>s from expanding? I'm pretty new to Swing, so let me know if I'm doing everything horribly wrong.</p>
2,709,451
5
0
null
2010-04-25 17:48:03.92 UTC
5
2013-01-31 16:06:46.223 UTC
null
null
null
null
105,084
null
1
23
java|swing|layout|layout-manager
38,585
<pre><code>textField = new JTextField( ... ); textField.setMaximumSize( textField.getPreferredSize() ); </code></pre>
2,392,732
SQLite, python, unicode, and non-utf data
<p>I started by trying to store strings in sqlite using python, and got the message:</p> <blockquote> <p>sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.</p> </blockquote> <p>Ok, I switched to Unicode strings. Then I started getting the message:</p> <blockquote> <p>sqlite3.OperationalError: Could not decode to UTF-8 column 'tag_artist' with text 'Sigur Rós'</p> </blockquote> <p>when trying to retrieve data from the db. More research and I started encoding it in utf8, but then 'Sigur Rós' starts looking like 'Sigur Rós'</p> <p><strong>note:</strong> My console was set to display in 'latin_1' as @John Machin pointed out.</p> <p>What gives? After reading <a href="http://bugs.python.org/issue6010" rel="noreferrer">this</a>, describing exactly the same situation I'm in, it seems as if the advice is to ignore the other advice and use 8-bit bytestrings after all.</p> <p>I didn't know much about unicode and utf before I started this process. I've learned quite a bit in the last couple hours, but I'm still ignorant of whether there is a way to correctly convert 'ó' from latin-1 to utf-8 and not mangle it. If there isn't, why would sqlite 'highly recommend' I switch my application to unicode strings?</p> <hr> <p>I'm going to update this question with a summary and some example code of everything I've learned in the last 24 hours so that someone in my shoes can have an easy(er) guide. If the information I post is wrong or misleading in any way please tell me and I'll update, or one of you senior guys can update.</p> <hr> <p><strong>Summary of answers</strong></p> <p>Let me first state the goal as I understand it. The goal in processing various encodings, if you are trying to convert between them, is to understand what your source encoding is, then convert it to unicode using that source encoding, then convert it to your desired encoding. Unicode is a base and encodings are mappings of subsets of that base. utf_8 has room for every character in unicode, but because they aren't in the same place as, for instance, latin_1, a string encoded in utf_8 and sent to a latin_1 console will not look the way you expect. In python the process of getting to unicode and into another encoding looks like:</p> <pre><code>str.decode('source_encoding').encode('desired_encoding') </code></pre> <p>or if the str is already in unicode</p> <pre><code>str.encode('desired_encoding') </code></pre> <p>For sqlite I didn't actually want to encode it again, I wanted to decode it and leave it in unicode format. Here are four things you might need to be aware of as you try to work with unicode and encodings in python.</p> <ol> <li>The encoding of the string you want to work with, and the encoding you want to get it to.</li> <li>The system encoding.</li> <li>The console encoding.</li> <li>The encoding of the source file</li> </ol> <p>Elaboration:</p> <p>(1) When you read a string from a source, it must have some encoding, like latin_1 or utf_8. In my case, I'm getting strings from filenames, so unfortunately, I could be getting any kind of encoding. Windows XP uses UCS-2 (a Unicode system) as its native string type, which seems like cheating to me. Fortunately for me, the characters in most filenames are not going to be made up of more than one source encoding type, and I think all of mine were either completely latin_1, completely utf_8, or just plain ascii (which is a subset of both of those). So I just read them and decoded them as if they were still in latin_1 or utf_8. It's possible, though, that you could have latin_1 and utf_8 and whatever other characters mixed together in a filename on Windows. Sometimes those characters can show up as boxes, other times they just look mangled, and other times they look correct (accented characters and whatnot). Moving on.</p> <p>(2) Python has a default system encoding that gets set when python starts and can't be changed during runtime. See <a href="http://www.diveintopython.org/xml_processing/unicode.html" rel="noreferrer">here</a> for details. Dirty summary ... well here's the file I added:</p> <pre><code>\# sitecustomize.py \# this file can be anywhere in your Python path, \# but it usually goes in ${pythondir}/lib/site-packages/ import sys sys.setdefaultencoding('utf_8') </code></pre> <p>This system encoding is the one that gets used when you use the unicode("str") function without any other encoding parameters. To say that another way, python tries to decode "str" to unicode based on the default system encoding.</p> <p>(3) If you're using IDLE or the command-line python, I think that your console will display according to the default system encoding. I am using pydev with eclipse for some reason, so I had to go into my project settings, edit the launch configuration properties of my test script, go to the Common tab, and change the console from latin-1 to utf-8 so that I could visually confirm what I was doing was working.</p> <p>(4) If you want to have some test strings, eg</p> <pre><code>test_str = "ó" </code></pre> <p>in your source code, then you will have to tell python what kind of encoding you are using in that file. (FYI: when I mistyped an encoding I had to ctrl-Z because my file became unreadable.) This is easily accomplished by putting a line like so at the top of your source code file:</p> <pre><code># -*- coding: utf_8 -*- </code></pre> <p>If you don't have this information, python attempts to parse your code as ascii by default, and so:</p> <pre><code>SyntaxError: Non-ASCII character '\xf3' in file _redacted_ on line 81, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details </code></pre> <p>Once your program is working correctly, or, if you aren't using python's console or any other console to look at output, then you will probably really only care about #1 on the list. System default and console encoding are not that important unless you need to look at output and/or you are using the builtin unicode() function (without any encoding parameters) instead of the string.decode() function. I wrote a demo function I will paste into the bottom of this gigantic mess that I hope correctly demonstrates the items in my list. Here is some of the output when I run the character 'ó' through the demo function, showing how various methods react to the character as input. My system encoding and console output are both set to utf_8 for this run:</p> <pre><code>'�' = original char &lt;type 'str'&gt; repr(char)='\xf3' '?' = unicode(char) ERROR: 'utf8' codec can't decode byte 0xf3 in position 0: unexpected end of data 'ó' = char.decode('latin_1') &lt;type 'unicode'&gt; repr(char.decode('latin_1'))=u'\xf3' '?' = char.decode('utf_8') ERROR: 'utf8' codec can't decode byte 0xf3 in position 0: unexpected end of data </code></pre> <p>Now I will change the system and console encoding to latin_1, and I get this output for the same input:</p> <pre><code>'ó' = original char &lt;type 'str'&gt; repr(char)='\xf3' 'ó' = unicode(char) &lt;type 'unicode'&gt; repr(unicode(char))=u'\xf3' 'ó' = char.decode('latin_1') &lt;type 'unicode'&gt; repr(char.decode('latin_1'))=u'\xf3' '?' = char.decode('utf_8') ERROR: 'utf8' codec can't decode byte 0xf3 in position 0: unexpected end of data </code></pre> <p>Notice that the 'original' character displays correctly and the builtin unicode() function works now.</p> <p>Now I change my console output back to utf_8.</p> <pre><code>'�' = original char &lt;type 'str'&gt; repr(char)='\xf3' '�' = unicode(char) &lt;type 'unicode'&gt; repr(unicode(char))=u'\xf3' '�' = char.decode('latin_1') &lt;type 'unicode'&gt; repr(char.decode('latin_1'))=u'\xf3' '?' = char.decode('utf_8') ERROR: 'utf8' codec can't decode byte 0xf3 in position 0: unexpected end of data </code></pre> <p>Here everything still works the same as last time but the console can't display the output correctly. Etc. The function below also displays more information that this and hopefully would help someone figure out where the gap in their understanding is. I know all this information is in other places and more thoroughly dealt with there, but I hope that this would be a good kickoff point for someone trying to get coding with python and/or sqlite. Ideas are great but sometimes source code can save you a day or two of trying to figure out what functions do what.</p> <p>Disclaimers: I'm no encoding expert, I put this together to help my own understanding. I kept building on it when I should have probably started passing functions as arguments to avoid so much redundant code, so if I can I'll make it more concise. Also, utf_8 and latin_1 are by no means the only encoding schemes, they are just the two I was playing around with because I think they handle everything I need. Add your own encoding schemes to the demo function and test your own input.</p> <p>One more thing: there are <a href="http://effbot.org/zone/unicode-gremlins.htm" rel="noreferrer">apparently crazy application developers</a> making life difficult in Windows.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf_8 -*- import os import sys def encodingDemo(str): validStrings = () try: print "str =",str,"{0} repr(str) = {1}".format(type(str), repr(str)) validStrings += ((str,""),) except UnicodeEncodeError as ude: print "Couldn't print the str itself because the console is set to an encoding that doesn't understand some character in the string. See error:\n\t", print ude try: x = unicode(str) print "unicode(str) = ",x validStrings+= ((x, " decoded into unicode by the default system encoding"),) except UnicodeDecodeError as ude: print "ERROR. unicode(str) couldn't decode the string because the system encoding is set to an encoding that doesn't understand some character in the string." print "\tThe system encoding is set to {0}. See error:\n\t".format(sys.getdefaultencoding()), print ude except UnicodeEncodeError as uee: print "ERROR. Couldn't print the unicode(str) because the console is set to an encoding that doesn't understand some character in the string. See error:\n\t", print uee try: x = str.decode('latin_1') print "str.decode('latin_1') =",x validStrings+= ((x, " decoded with latin_1 into unicode"),) try: print "str.decode('latin_1').encode('utf_8') =",str.decode('latin_1').encode('utf_8') validStrings+= ((x, " decoded with latin_1 into unicode and encoded into utf_8"),) except UnicodeDecodeError as ude: print "The string was decoded into unicode using the latin_1 encoding, but couldn't be encoded into utf_8. See error:\n\t", print ude except UnicodeDecodeError as ude: print "Something didn't work, probably because the string wasn't latin_1 encoded. See error:\n\t", print ude except UnicodeEncodeError as uee: print "ERROR. Couldn't print the str.decode('latin_1') because the console is set to an encoding that doesn't understand some character in the string. See error:\n\t", print uee try: x = str.decode('utf_8') print "str.decode('utf_8') =",x validStrings+= ((x, " decoded with utf_8 into unicode"),) try: print "str.decode('utf_8').encode('latin_1') =",str.decode('utf_8').encode('latin_1') except UnicodeDecodeError as ude: print "str.decode('utf_8').encode('latin_1') didn't work. The string was decoded into unicode using the utf_8 encoding, but couldn't be encoded into latin_1. See error:\n\t", validStrings+= ((x, " decoded with utf_8 into unicode and encoded into latin_1"),) print ude except UnicodeDecodeError as ude: print "str.decode('utf_8') didn't work, probably because the string wasn't utf_8 encoded. See error:\n\t", print ude except UnicodeEncodeError as uee: print "ERROR. Couldn't print the str.decode('utf_8') because the console is set to an encoding that doesn't understand some character in the string. See error:\n\t",uee print print "Printing information about each character in the original string." for char in str: try: print "\t'" + char + "' = original char {0} repr(char)={1}".format(type(char), repr(char)) except UnicodeDecodeError as ude: print "\t'?' = original char {0} repr(char)={1} ERROR PRINTING: {2}".format(type(char), repr(char), ude) except UnicodeEncodeError as uee: print "\t'?' = original char {0} repr(char)={1} ERROR PRINTING: {2}".format(type(char), repr(char), uee) print uee try: x = unicode(char) print "\t'" + x + "' = unicode(char) {1} repr(unicode(char))={2}".format(x, type(x), repr(x)) except UnicodeDecodeError as ude: print "\t'?' = unicode(char) ERROR: {0}".format(ude) except UnicodeEncodeError as uee: print "\t'?' = unicode(char) {0} repr(char)={1} ERROR PRINTING: {2}".format(type(x), repr(x), uee) try: x = char.decode('latin_1') print "\t'" + x + "' = char.decode('latin_1') {1} repr(char.decode('latin_1'))={2}".format(x, type(x), repr(x)) except UnicodeDecodeError as ude: print "\t'?' = char.decode('latin_1') ERROR: {0}".format(ude) except UnicodeEncodeError as uee: print "\t'?' = char.decode('latin_1') {0} repr(char)={1} ERROR PRINTING: {2}".format(type(x), repr(x), uee) try: x = char.decode('utf_8') print "\t'" + x + "' = char.decode('utf_8') {1} repr(char.decode('utf_8'))={2}".format(x, type(x), repr(x)) except UnicodeDecodeError as ude: print "\t'?' = char.decode('utf_8') ERROR: {0}".format(ude) except UnicodeEncodeError as uee: print "\t'?' = char.decode('utf_8') {0} repr(char)={1} ERROR PRINTING: {2}".format(type(x), repr(x), uee) print x = 'ó' encodingDemo(x) </code></pre> <p>Much thanks for the answers below and especially to @John Machin for answering so thoroughly.</p>
2,392,803
5
0
null
2010-03-06 14:15:42.63 UTC
33
2018-07-28 09:25:17.23 UTC
2018-07-28 09:25:17.23 UTC
null
296,460
null
34,410
null
1
68
python|sqlite|unicode|utf-8|python-2.x
51,296
<blockquote> <p>I'm still ignorant of whether there is a way to correctly convert 'ó' from latin-1 to utf-8 and not mangle it</p> </blockquote> <p>repr() and unicodedata.name() are your friends when it comes to debugging such problems:</p> <pre><code>&gt;&gt;&gt; oacute_latin1 = "\xF3" &gt;&gt;&gt; oacute_unicode = oacute_latin1.decode('latin1') &gt;&gt;&gt; oacute_utf8 = oacute_unicode.encode('utf8') &gt;&gt;&gt; print repr(oacute_latin1) '\xf3' &gt;&gt;&gt; print repr(oacute_unicode) u'\xf3' &gt;&gt;&gt; import unicodedata &gt;&gt;&gt; unicodedata.name(oacute_unicode) 'LATIN SMALL LETTER O WITH ACUTE' &gt;&gt;&gt; print repr(oacute_utf8) '\xc3\xb3' &gt;&gt;&gt; </code></pre> <p>If you send oacute_utf8 to a terminal that is set up for latin1, you will get A-tilde followed by superscript-3.</p> <blockquote> <p>I switched to Unicode strings.</p> </blockquote> <p>What are you calling Unicode strings? UTF-16?</p> <blockquote> <p>What gives? After reading this, describing exactly the same situation I'm in, it seems as if the advice is to ignore the other advice and use 8-bit bytestrings after all.</p> </blockquote> <p>I can't imagine how it seems so to you. The story that was being conveyed was that unicode objects in Python and UTF-8 encoding in the database were the way to go. However Martin answered the original question, giving a method ("text factory") for the OP to be able to use latin1 -- this did NOT constitute a recommendation!</p> <p><strong>Update</strong> in response to these further questions raised in a comment:</p> <blockquote> <p>I didn't understand that the unicode characters still contained an implicit encoding. Am I saying that right?</p> </blockquote> <p>No. An encoding is a mapping between Unicode and something else, and vice versa. A Unicode character doesn't have an encoding, implicit or otherwise.</p> <blockquote> <p>It looks to me like unicode("\xF3") and "\xF3".decode('latin1') are the same when evaluated with repr().</p> </blockquote> <p>Say what? It doesn't look like it to me:</p> <pre><code>&gt;&gt;&gt; unicode("\xF3") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position 0: ordinal not in range(128) &gt;&gt;&gt; "\xF3".decode('latin1') u'\xf3' &gt;&gt;&gt; </code></pre> <p>Perhaps you meant: <code>u'\xf3' == '\xF3'.decode('latin1')</code> ... this is certainly true.</p> <p>It is also true that <code>unicode(str_object, encoding)</code> does the same as <code>str_object.decode(encoding)</code> ... including blowing up when an inappropriate encoding is supplied.</p> <blockquote> <p>Is that a happy circumstance</p> </blockquote> <p>That the first 256 characters in Unicode are the same, code for code, as the 256 characters in latin1 is a good idea. Because all 256 possible latin1 characters are mapped to Unicode, it means that ANY 8-bit byte, ANY Python str object can be decoded into unicode without an exception being raised. This is as it should be.</p> <p>However there exist certain persons who confuse two quite separate concepts: "my script runs to completion without any exceptions being raised" and "my script is error-free". To them, latin1 is "a snare and a delusion".</p> <p>In other words, if you have a file that's actually encoded in cp1252 or gbk or koi8-u or whatever and you decode it using latin1, the resulting Unicode will be utter rubbish and Python (or any other language) will not flag an error -- it has no way of knowing that you have commited a silliness.</p> <blockquote> <p>or is unicode("str") going to always return the correct decoding?</p> </blockquote> <p>Just like that, with the default encoding being ascii, it will return the correct unicode if the file is actually encoded in ASCII. Otherwise, it'll blow up.</p> <p>Similarly, if you specify the correct encoding, or one that's a superset of the correct encoding, you'll get the correct result. Otherwise you'll get gibberish or an exception.</p> <p>In short: the answer is no.</p> <blockquote> <p>If not, when I receive a python str that has any possible character set in it, how do I know how to decode it?</p> </blockquote> <p>If the str object is a valid XML document, it will be specified up front. Default is UTF-8. If it's a properly constructed web page, it should be specified up front (look for "charset"). Unfortunately many writers of web pages lie through their teeth (ISO-8859-1 aka latin1, should be Windows-1252 aka cp1252; don't waste resources trying to decode gb2312, use gbk instead). You can get clues from the nationality/language of the website. </p> <p>UTF-8 is always worth trying. If the data is ascii, it'll work fine, because ascii is a subset of utf8. A string of text that has been written using non-ascii characters and has been encoded in an encoding other than utf8 will almost certainly fail with an exception if you try to decode it as utf8.</p> <p>All of the above heuristics and more and a lot of statistics are encapsulated in <a href="http://chardet.feedparser.org/" rel="noreferrer">chardet</a>, a module for guessing the encoding of arbitrary files. It usually works well. However you can't make software idiot-proof. For example, if you concatenate data files written some with encoding A and some with encoding B, and feed the result to chardet, the answer is likely to be encoding C <em>with a reduced level of confidence e.g. 0.8. Always check the confidence part of the answer</em>.</p> <p>If all else fails:</p> <p>(1) Try asking here, with a small sample from the front of your data ... <code>print repr(your_data[:400])</code> ... and whatever collateral info about its provenance that you have.</p> <p>(2) Recent Russian research into <a href="http://www.elcomsoft.com/tambourine.html?r1=pr&amp;r2=april1" rel="noreferrer">techniques for recovering forgotten passwords</a> appears to be quite applicable to deducing unknown encodings.</p> <p><strong>Update 2</strong> BTW, isn't it about time you opened up another question ?-)</p> <blockquote> <p>One more thing: there are apparently characters that Windows uses as Unicode for certain characters that aren't the correct Unicode for that character, so you may have to map those characters to the correct ones if you want to use them in other programs that are expecting those characters in the right spot.</p> </blockquote> <p>It's not Windows that's doing it; it's a bunch of crazy application developers. You might have more understandably not paraphrased but quoted the opening paragraph of the effbot article that you referred to: </p> <blockquote> <p>Some applications add CP1252 (Windows, Western Europe) characters to documents marked up as ISO 8859-1 (Latin 1) or other encodings. These characters are not valid ISO-8859-1 characters, and may cause all sorts of problems in processing and display applications.</p> </blockquote> <p>Background:</p> <p>The range U+0000 to U+001F inclusive is designated in Unicode as "C0 Control Characters". These exist also in ASCII and latin1, with the same meanings. They include such familar things as carriage return, line feed, bell, backspace, tab, and others that are used rarely.</p> <p>The range U+0080 to U+009F inclusive is designated in Unicode as "C1 Control Characters". These exist also in latin1, and include 32 characters that nobody outside unicode.org can imagine any possible use for.</p> <p>Consequently, if you run a character frequency count on your unicode or latin1 data, and you find any characters in that range, your data is corrupt. There is no universal solution; it depends on how it became corrupted. The characters <em>may</em> have the same meaning as the cp1252 characters at the same positions, and thus the effbot's solution will work. In another case that I've been looking at recently, the dodgy characters appear to have been caused by concatenating text files encoded in UTF-8 and another encoding which needed to be deduced based on letter frequencies in the (human) language the files were written in.</p>
3,197,601
White space at bottom of anchor tag
<p>I have an tag surrounding an image. I have a border set on the div that the tag is in. I have both margin and padding set to 0 but for some reason my tag is still about 3 pixels taller than my image. This leaves a bit of space between the image and the border, which destroys the look that I want to accomplish.</p> <p>What am I doing wrong? I have tested in both FireFox and Chrome with the same results. Thanks</p>
3,197,613
5
0
null
2010-07-07 18:11:55.777 UTC
17
2021-12-23 17:37:36.387 UTC
2010-07-07 18:19:14.997 UTC
null
107,768
null
107,768
null
1
69
html|css|xhtml
23,979
<p>The image is <code>display: inline</code> so it is treated like a character and sits on the baseline. The gap is caused by the space provided for the descender (which you find on letters like j, g, y and p).</p> <p>Adjust the <code>vertical-align</code> with CSS: <code>img{vertical-align: bottom}</code></p>
2,900,010
PHP and Barcode Scanners
<p>If i have a website running php and apache, what do i need to be able to attach a scanner to it? How do i get the scanner to fill in a value on one of the webforms on my page? </p>
2,900,120
6
1
null
2010-05-24 20:16:04.857 UTC
14
2019-10-14 12:17:16.277 UTC
null
null
null
null
1,377,781
null
1
14
php
29,938
<p>I just did this for an application. It's actually simple. The scanner is just another input method and is, in fact, similar to a keyboard. When you scan the barcode the data is decoded by the scanner and sent to whatever application is waiting to receive it. In the case of a web-based application it would be a form, most likely with a textarea with focus. The data would then populate the textarea just as if someone had typed the barcode's data into it. The form is then submitted and processed normally.</p> <p>Just make sure the textarea has focus or else the data will go either nowhere or to wherever focus is (which may be another form field or the address bar).</p> <p>I have yet to figure how how to get the form to auto-submit upon the entry of the barcode data as the scanner does not send event information (i.e. submit) and special characters such as tab (\t) do not seem to work. (If anyone knows how to accomplish this I am very interested in knowing how it can be done).</p>
2,475,831
Merging: Hg/Git vs. SVN
<p>I often read that Hg (and Git and...) are better at merging than SVN but I have never seen practical examples of where Hg/Git can merge something where SVN fails (or where SVN needs manual intervention). Could you post a few step-by-step lists of branch/modify/commit/...-operations that show where SVN would fail while Hg/Git happily moves on? Practical, not highly exceptional cases please...</p> <p>Some background: we have a few dozen developers working on projects using SVN, with each project (or group of similar projects) in its own repository. We know how to apply release- and feature-branches so we don't run into problems very often (i.e., we've been there, but we've learned to overcome <a href="http://hginit.com/00.html" rel="noreferrer">Joel's problems</a> of "one programmer causing trauma to the whole team" or "needing six developers for two weeks to reintegrate a branch"). We have release-branches that are very stable and only used to apply bugfixes. We have trunks that should be stable enough to be able to create a release within one week. And we have feature-branches that single developers or groups of developers can work on. Yes, they are deleted after reintegration so they don't clutter up the repository. ;)</p> <p>So I'm still trying to find the advantages of Hg/Git over SVN. I'd love to get some hands-on experience, but there aren't any bigger projects we could move to Hg/Git yet, so I'm stuck with playing with small artificial projects that only contain a few made up files. And I'm looking for a few cases where you can feel the impressive power of Hg/Git, since so far I have often read about them but failed to find them myself.</p>
2,477,089
6
6
null
2010-03-19 08:18:57.77 UTC
70
2018-08-13 11:54:17.57 UTC
2012-02-24 19:53:22.363 UTC
null
110,204
null
276,010
null
1
144
git|svn|mercurial|merge|dvcs
23,878
<p>I do not use Subversion myself, but from the <a href="http://subversion.apache.org/docs/release-notes/1.5.html#merge-tracking" rel="nofollow noreferrer">release notes for Subversion 1.5: Merge tracking (foundational)</a> it looks like there are the following differences from how merge tracking work in full-<a href="https://en.wikipedia.org/wiki/Directed_acyclic_graph" rel="nofollow noreferrer">DAG</a> version control systems like Git or Mercurial.</p> <ul> <li><p>Merging trunk to branch is different from merging branch to trunk: for some reason merging trunk to branch requires <code>--reintegrate</code> option to <code>svn merge</code>.</p> <p>In distributed version control systems like Git or Mercurial there is no <em>technical</em> difference between trunk and branch: all branches are created equal (there might be <em>social</em> difference, though). Merging in either direction is done the same way.</p></li> <li><p>You need to provide new <code>-g</code> (<code>--use-merge-history</code>) option to <code>svn log</code> and <code>svn blame</code> to take merge tracking into account.</p> <p>In Git and Mercurial merge tracking is automatically taken into account when displaying history (log) and blame. In Git you can request to follow first parent only with <code>--first-parent</code> (I guess similar option exists also for Mercurial) to "discard" merge tracking info in <code>git log</code>.</p></li> <li><p>From what I understand <code>svn:mergeinfo</code> property stores per-path information about conflicts (Subversion is changeset-based), while in Git and Mercurial it is simply commit objects that can have more than one parent.</p></li> <li><p><em>"Known Issues"</em> subsection for merge tracking in Subversion suggests that repeated / cyclic / reflective merge might not work properly. It means that with the following histories second merge might not do the right thing ('A' can be trunk or branch, and 'B' can be branch or trunk, respectively): </p> <pre> *---*---x---*---y---*---*---*---M2 &lt;-- A \ \ / --*----M1---*---*---/ &lt;-- B </pre> <p>In the case the above ASCII-art gets broken: Branch 'B' is created (forked) from branch 'A' at revision 'x', then later branch 'A' is merged at revision 'y' into branch 'B' as merge 'M1', and finally branch 'B' is merged into branch 'A' as merge 'M2'. </p> <pre> *---*---x---*-----M1--*---*---M2 &lt;-- A \ / / \-*---y---*---*---/ &lt;-- B </pre> <p>In the case the above ASCII-art gets broken: Branch 'B' is created (forked) from branch 'A' at revision 'x', it is merged into branch 'A' at 'y' as 'M1', and later merged again into branch 'A' as 'M2'.</p></li> <li><p>Subversion might not support advanced case of <a href="http://revctrl.org/CrissCrossMerge" rel="nofollow noreferrer">criss-cross merge</a>.</p> <pre> *---b-----B1--M1--*---M3 \ \ / / \ X / \ / \ / \--B2--M2--* </pre> <p>Git handles this situation just fine in practice using "recursive" merge strategy. I am not sure about Mercurial.</p></li> <li><p>In <em>"Known Issues"</em> there is warning that merge tracking migh not work with file renames, e.g. when one side renames file (and perhaps modifies it), and second side modifies file without renaming (under old name).</p> <p>Both Git and Mercurial handle such case just fine in practice: Git using <strong>rename detection</strong>, Mercurial using <strong>rename tracking</strong>.</p></li> </ul> <p>HTH</p>
3,077,242
Force download a pdf link using javascript/ajax/jquery
<p>suppose we have a pdf link "<a href="http://manuals.info.apple.com/en/iphone_user_guide.pdf" rel="noreferrer">http://manuals.info.apple.com/en/iphone_user_guide.pdf</a>"(just for example and to let u know that file is not on my server, i only have the link)...now i have to provide a button on my site that will download the file.</p> <p>i have tried various things like window.open, href etc. methods but it open the link on other window. i know thats because now all browser comes with a adobe plugin which opens it in another window, but still isnt there any way i give the user the option of download rather than opening it, through client side scripting ..</p> <p>plz help.. thanks </p>
18,983,688
7
1
null
2010-06-19 21:09:50.403 UTC
12
2022-01-17 07:43:35.233 UTC
2012-11-14 00:04:53.437 UTC
null
1,304,305
null
371,238
null
1
29
javascript
124,005
<p>Use the HTML5 &quot;download&quot; attribute</p> <pre><code>&lt;a href=&quot;iphone_user_guide.pdf&quot; download=&quot;iPhone User's Guide.PDF&quot;&gt;click me&lt;/a&gt; </code></pre> <p>2021 Update: Now supported in all major browsers! see: <a href="http://caniuse.com/#search=download" rel="nofollow noreferrer">caniuse.com/#search=download</a></p> <p>If you need to support older browsers, or you're looking for an <em>actual</em> javascript solution (for some reason) please see <a href="https://stackoverflow.com/a/29266135/1181570">lajarre's answer</a></p>
2,426,145
Oracle's lack of a Bit datatype for table columns
<p>Oracle does not support a <code>bit</code> datatype or any other type for true/false scenarios. Does one use the <code>char(1)</code> field instead by using a specific letter to denote yes / true regardless of culture specific issues?</p> <p>Instead of <code>char</code> should it be <code>Number(1,0)</code> for this instead - 0 being considered false / no, anything else being interpreted as true / yes?</p> <p>Is this viable?</p> <hr> <p>Why does Oracle not support a simple boolean type? </p>
2,426,249
9
7
null
2010-03-11 15:22:09.293 UTC
6
2020-01-11 22:34:14.25 UTC
2020-01-11 22:31:20.74 UTC
null
285,795
null
214,792
null
1
28
oracle|boolean
52,792
<p>I prefer char(1) over number(1), since with some reasonable choice of characters, it is obvious which character has which boolean meaning.</p> <p>Of course you should fight all the different varations, choose one and ensure it's use by putting check constraints on the columns.</p> <p>Although it probably is to late in your case, generating the schema from another tool often takes care at least of the consistency issue. I personally prefer hibernate for this purpose, but that is very situation specific.</p> <p>And of course that is a glaring obmission. To make it worse, PL/SQL has a boolean, but you can't use it in SQL statements.</p>
2,423,628
What's the difference between a file descriptor and file pointer?
<p>I want to know the difference between a file descriptor and file pointer.</p> <p>Also, in what scenario would you use one instead of the other?</p>
2,423,670
9
1
null
2010-03-11 09:02:44.76 UTC
70
2020-11-30 11:25:21.797 UTC
2011-11-19 04:47:56.64 UTC
null
8,331
null
284,118
null
1
141
c|file-descriptor|file-pointer
110,331
<p>A file descriptor is a low-level integer "handle" used to identify an opened file (or socket, or whatever) at the kernel level, in Linux and other Unix-like systems.</p> <p>You pass "naked" file descriptors to actual Unix calls, such as <code><a href="http://linux.die.net/man/2/read" rel="noreferrer">read()</a></code>, <code><a href="http://linux.die.net/man/2/write" rel="noreferrer">write()</a></code> and so on.</p> <p>A <code>FILE</code> pointer is a C standard library-level construct, used to represent a file. The <code>FILE</code> wraps the file descriptor, and adds buffering and other features to make I/O easier.</p> <p>You pass <code>FILE</code> pointers to standard C functions such as <code><a href="http://linux.die.net/man/3/fread" rel="noreferrer">fread()</a></code> and <code><a href="http://linux.die.net/man/3/fwrite" rel="noreferrer">fwrite()</a></code>.</p>
2,341,837
How to understand symbols in Ruby
<p>Despite reading "<a href="http://web.archive.org/web/20140314193235/http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols" rel="noreferrer">Understanding Ruby Symbols</a>", I'm still confused by the representation of the data in memory when it comes to using symbols. If a symbol, two of them contained in different objects, exist in the same memory location, then how is it that they contain <em>different</em> values? I'd have expected the same memory location to contain the same value.</p> <p>This a quote from the link:</p> <blockquote> <p>Unlike strings, symbols of the same name are initialized and exist in memory only once during a session of ruby</p> </blockquote> <p>I don't understand how it manages to differentiate the values contained in the same memory location.</p> <p>Consider this example:</p> <pre><code>patient1 = { :ruby =&gt; "red" } patient2 = { :ruby =&gt; "programming" } patient1.each_key {|key| puts key.object_id.to_s} 3918094 patient2.each_key {|key| puts key.object_id.to_s} 3918094 </code></pre> <p><code>patient1</code> and <code>patient2</code> are both hashes, that's fine. <code>:ruby</code> however is a symbol. If we were to output the following:</p> <pre><code>patient1.each_key {|key| puts key.to_s} </code></pre> <p>Then what will be output? <code>"red"</code>, or <code>"programming"</code>?</p> <p>Forgetting hashes for a second, I'm thinking a symbol is a <em>pointer</em> to a value. The questions I have are:</p> <ul> <li>Can I assign a value to a symbol?</li> <li>Is a symbol just a pointer to a variable with a value in it?</li> <li>If symbols are global, does that mean a symbol always points to one thing?</li> </ul>
2,341,938
11
2
null
2010-02-26 13:22:05.257 UTC
42
2019-03-02 01:45:24.19 UTC
2017-04-07 18:54:03.597 UTC
null
128,421
null
39,693
null
1
85
ruby|symbols
44,126
<p>Consider this:</p> <pre><code>x = :sym y = :sym (x.__id__ == y.__id__ ) &amp;&amp; ( :sym.__id__ == x.__id__) # =&gt; true x = "string" y = "string" (x.__id__ == y.__id__ ) || ( "string".__id__ == x.__id__) # =&gt; false </code></pre> <p>So, however you create a symbol object, as long as its contents are the same, it will refer to the same object in memory. This is not a problem because a symbol is an <a href="http://en.wikipedia.org/wiki/Immutable_object" rel="noreferrer">immutable object</a>. Strings are mutable.</p> <hr> <p>(In response to the comment below)</p> <p>In the original article, the value is not being stored in a symbol, it is being stored in a hash. Consider this:</p> <pre><code>hash1 = { "string" =&gt; "value"} hash2 = { "string" =&gt; "value"} </code></pre> <p>This creates six objects in the memory -- four string objects and two hash objects.</p> <pre><code>hash1 = { :symbol =&gt; "value"} hash2 = { :symbol =&gt; "value"} </code></pre> <p>This only creates five objects in memory -- one symbol, two strings and two hash objects.</p>
2,367,322
Famous eponymous programming techniques
<p>In some sports certain techniques or elements are named after the athlete who invented or first performed them&mdash;for example, <a href="http://en.wikipedia.org/wiki/Biellmann_spin" rel="noreferrer">Biellmann spin</a>.</p> <p>Is their widespread use of such names for programming techniques and idioms? What are they? To be clear, I am explicitly not asking about algorithms, which are quite often named after their creators.</p> <p>For example, one is <a href="http://en.wikipedia.org/wiki/Schwartzian_transform" rel="noreferrer">Schwartzian transform</a>, but I can't recall any more.</p>
2,367,716
18
12
2010-03-03 00:16:38.24 UTC
2010-03-02 22:25:34.47 UTC
11
2013-07-22 19:57:36.34 UTC
2010-03-03 00:42:34.323 UTC
Roger Pate
null
null
284,806
null
1
30
terminology|idioms
2,368
<ul> <li>The functional programming technique <a href="http://en.wikipedia.org/wiki/Currying" rel="nofollow noreferrer">currying</a> is named after its (re)-inventor, <a href="http://en.wikipedia.org/wiki/Haskell_Curry" rel="nofollow noreferrer">Haskell Curry</a>.</li> <li>Boolean logic is named after <a href="http://en.wikipedia.org/wiki/George_Boole" rel="nofollow noreferrer">George Boole</a></li> <li><a href="http://en.wikipedia.org/wiki/Duff%27s_device" rel="nofollow noreferrer">Duff's device</a> is pretty famous and seems to me to qualify as technique/idiom.</li> <li><p>I used to do a "<a href="http://en.wikipedia.org/wiki/John_D._Carmack" rel="nofollow noreferrer">Carmack</a>" which was referring to the "<a href="http://en.wikipedia.org/wiki/Fast_inverse_square_root" rel="nofollow noreferrer">fast inverse square root</a>" but according to the Wikipedia entry the technique was probably found by the smarties at SGI in 1990 or so.</p> <p>Even if it doesn't fit your description, it's still a pretty amazing read :)</p></li> <li><a href="http://en.wikipedia.org/wiki/Kleene_star" rel="nofollow noreferrer">Kleene closure</a>: it's the <code>*</code> operator in regular expressions. It means "0 or more of what precedes it".</li> <li>At one point in time, the <strong><a href="http://en.wikipedia.org/wiki/Karnaugh_map" rel="nofollow noreferrer">Karnaugh Map</a></strong> could have been considered a technique to facilitate programming (albeit at a low level).</li> <li><p><a href="https://en.wikipedia.org/wiki/Markov_chain" rel="nofollow noreferrer">Markov Chains</a> are named after Andrey Markov and used in programming to generate:</p> <ul> <li>Google PageRank </li> <li>Generating Spam-Mail Texts</li> <li>Mnemonic Codewords to replace IDs/Hashvalues</li> </ul></li> <li><p>The graphics world is full of eponymous techniques: </p> <ul> <li><a href="http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm" rel="nofollow noreferrer">Bresenham's line algorithm</a></li> <li><a href="http://en.wikipedia.org/wiki/B%C3%A9zier_curve" rel="nofollow noreferrer">Bézier curve</a></li> <li><a href="http://en.wikipedia.org/wiki/Gouraud_shading" rel="nofollow noreferrer">Gouraud shading</a></li> <li><a href="http://en.wikipedia.org/wiki/Phong_shading" rel="nofollow noreferrer">Phong shading</a></li> </ul></li> <li><a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle" rel="nofollow noreferrer">Fisher-Yates shuffle</a>, <em>the</em> standard way to implement an in-place random shuffle on an array.</li> </ul> <p><em>Please edit to add more if found...</em></p>
23,523,946
_ (underscore) is a reserved keyword
<p>I've just replaced <code>s</code> in the following lambda expression by <code>_</code>:</p> <pre><code>s -&gt; Integer.parseInt(s) </code></pre> <p>Eclipse compiler says:</p> <blockquote> <p>'_' should not be used as an identifier, since it is a reserved keyword from source level 1.8 on.</p> </blockquote> <p>I haven't found any explanation in the <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.9" rel="noreferrer">JLS §3.9</a> Lexical Structure / Keywords.</p>
23,525,446
3
0
null
2014-05-07 17:02:20.193 UTC
13
2018-07-11 04:28:49.427 UTC
2016-10-26 09:40:15.14 UTC
null
1,743,880
null
1,624,376
null
1
104
java|lambda|java-8
28,550
<p>The place to look is <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.1" rel="noreferrer">JLS §15.27.1. Lambda Parameters</a></p> <blockquote> <p><strong>It is a compile-time error if a lambda parameter has the name _ (that is, a single underscore character).</strong></p> <p><sup>The use of the variable name _ in any context is discouraged. Future versions of the Java programming language may reserve this name as a keyword and/or give it special semantics. </sup></p> </blockquote> <p>So the Eclipse message is misleading, especially as the same message is used for both cases, when an error is generated for a lambda parameter or when a warning is generated for any other <code>_</code> identifier.</p>
33,939,974
Make view 80% width of parent in React Native
<p>I'm creating a form in React Native and would like to make my <code>TextInput</code>s 80% of the screen width.</p> <p>With HTML and ordinary CSS, this would be straightforward:</p> <pre><code>input { display: block; width: 80%; margin: auto; } </code></pre> <p>Except that React Native doesn't support the <code>display</code> property, percentage widths, or auto margins.</p> <p>So what should I do instead? There's <a href="https://github.com/facebook/css-layout/issues/57#issuecomment-102148200" rel="noreferrer">some discussion of this problem</a> in React Native's issue tracker, but the proposed solutions seem like nasty hacks.</p>
45,306,818
10
2
null
2015-11-26 13:29:42.603 UTC
21
2020-11-30 07:34:54.793 UTC
null
null
null
null
1,709,587
null
1
130
javascript|css|reactjs|react-native
228,566
<p>As of React Native 0.42 <code>height:</code> and <code>width:</code> accept percentages. </p> <p>Use <code>width: 80%</code> in your stylesheets and it just works.</p> <ul> <li><p>Screenshot<br> <img src="https://i.stack.imgur.com/lanin.png" width="200" /> <br /></p></li> <li><p>Live Example<br> <strong><a href="https://snack.expo.io/@gollyjer/child-width-height-as-proportion-of-parent-" rel="noreferrer">Child Width/Height as Proportion of Parent</a></strong><br> <br /></p></li> <li><p>Code </p> <pre class="lang-js prettyprint-override"><code>import React from 'react'; import { Text, View, StyleSheet } from 'react-native'; const width_proportion = '80%'; const height_proportion = '40%'; const styles = StyleSheet.create({ screen: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#5A9BD4', }, box: { width: width_proportion, height: height_proportion, alignItems: 'center', justifyContent: 'center', backgroundColor: '#B8D2EC', }, text: { fontSize: 18, }, }); export default () =&gt; ( &lt;View style={styles.screen}&gt; &lt;View style={styles.box}&gt; &lt;Text style={styles.text}&gt; {width_proportion} of width{'\n'} {height_proportion} of height &lt;/Text&gt; &lt;/View&gt; &lt;/View&gt; ); </code></pre></li> </ul>
10,643,981
How to get the unparsed query string from a http request in Express
<p>I can use the below to get the query string.</p> <pre><code> var query_string = request.query; </code></pre> <p>What I need is the raw unparsed query string. How do I get that? For the below url the query string is <code>{ tt: 'gg' }</code>, I need <code>tt=gg&amp;hh=jj</code> etc....</p> <pre><code>http://127.0.0.1:8065?tt=gg Server running at http://127.0.0.1:8065 { tt: 'gg' } </code></pre>
10,644,398
4
0
null
2012-05-17 21:46:37.477 UTC
6
2020-08-11 12:13:59.23 UTC
2012-05-18 08:27:58.957 UTC
null
499,609
null
1,203,556
null
1
36
node.js|express
21,793
<p>You can use <code>node</code>'s <a href="http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost" rel="noreferrer">URL</a> module as per <a href="http://nodejs.org/api/http.html#http_message_url" rel="noreferrer">this</a> example:</p> <pre><code>require('url').parse(request.url).query </code></pre> <p>e.g.</p> <pre><code>node&gt; require('url').parse('?tt=gg').query 'tt=gg' </code></pre> <p>Or just go straight to the url and <code>substr</code> after the <code>?</code></p> <pre><code>var i = request.url.indexOf('?'); var query = request.url.substr(i+1); </code></pre> <p>(which is what <code>require('url').parse()</code> does under the hood)</p>
10,579,457
Why use arrays in VBA when there are collections?
<p>many people use extensively arrays in Excel/VBA to store a list of data. However, there is the collection object which in my view is MUCH MUCH more convenient (mainly: don't need to re/define length of the list).</p> <p>So, I am sincerely <strong>asking myself if I am missing something?</strong> Why do other people still use arrays to store a list of data? Is it simply a hangover of the past?</p>
10,580,027
3
0
null
2012-05-14 07:59:28.417 UTC
17
2015-08-03 22:55:13.447 UTC
2015-08-03 22:55:13.447 UTC
null
2,685,412
null
1,197,860
null
1
47
arrays|vba|excel
72,124
<p>Several reasons to use arrays instead of collections (or dictionaries):</p> <ul> <li>you can transfer easily array to range (and vice-versa) with <code>Range("A1:B12") = MyArray</code></li> <li>collections can store only <strong>unique</strong> keys whereas arrays can store any value</li> <li>collections have to store a couple (key, value) whereas you can store whatever in an array</li> </ul> <p>See <a href="http://www.cpearson.com/excel/vbaarrays.htm" rel="noreferrer">Chip Pearson's article</a> about arrays for a better understanding</p> <p>A better question would rather be why people would use collections over dictionaries (ok, collections are standard VBA whereas you have to <em>import</em> dictionaries)</p>
10,450,962
How can I fetch all items from a DynamoDB table without specifying the primary key?
<p>I have a table called products with primary key <code>Id</code>. I want to select all items in the table. This is the code is I'm using:</p> <pre><code>$batch_get_response = $dynamodb-&gt;batch_get_item(array( 'RequestItems' =&gt; array( 'products' =&gt; array( 'Keys' =&gt; array( array( // Key #1 'HashKeyElement' =&gt; array( AmazonDynamoDB::TYPE_NUMBER =&gt; '1'), 'RangeKeyElement' =&gt; array( AmazonDynamoDB::TYPE_NUMBER =&gt; $current_time), ), array( // Key #2 'HashKeyElement' =&gt; array( AmazonDynamoDB::TYPE_NUMBER =&gt; '2'), 'RangeKeyElement' =&gt; array( AmazonDynamoDB::TYPE_NUMBER =&gt; $current_time), ), ) ) ) )); </code></pre> <p>Is it possible to select all items without specifying the primary key? I'm using the AWS SDK for PHP.</p>
10,451,629
8
0
null
2012-05-04 14:38:21.617 UTC
9
2022-04-05 10:39:25.283 UTC
2012-05-04 15:24:16.253 UTC
null
45,773
null
273,266
null
1
67
php|amazon-dynamodb
174,986
<p><a href="http://aws.amazon.com/dynamodb/" rel="noreferrer">Amazon DynamoDB</a> provides the <a href="http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/API_Scan.html" rel="noreferrer">Scan</a> operation for this purpose, which <em>returns one or more items and its attributes by performing a full scan of a table</em>. Please be aware of the following two constraints:</p> <ul> <li><p>Depending on your table size, you may need to use pagination to retrieve the entire result set: </p> <blockquote> <p><strong>Note</strong><br> If the total number of scanned items exceeds the 1MB limit, the scan stops and results are returned to the user with a LastEvaluatedKey to continue the scan in a subsequent operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria.</p> <p>The result set is eventually consistent.</p> </blockquote></li> <li><p>The Scan operation is potentially costly regarding both performance and consumed capacity units (i.e. price), see section <em>Scan and Query Performance</em> in <a href="http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/QueryAndScan.html" rel="noreferrer">Query and Scan in Amazon DynamoDB</a>:</p> <blockquote> <p>[...] Also, as a table grows, the scan operation slows. The scan operation examines every item for the requested values, and <strong>can use up the provisioned throughput for a large table in a single operation</strong>. For quicker response times, design your tables in a way that can use the Query, Get, or BatchGetItem APIs, instead. Or, design your application to use scan operations in a way that minimizes the impact on your table's request rate. For more information, see <a href="http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/BestPractices.html" rel="noreferrer">Provisioned Throughput Guidelines in Amazon DynamoDB</a>. <em>[emphasis mine]</em></p> </blockquote></li> </ul> <p>You can find more details about this operation and some example snippets in <a href="http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/LowLevelPHPScanning.html" rel="noreferrer">Scanning Tables Using the AWS SDK for PHP Low-Level API for Amazon DynamoDB</a>, with the most simple example illustrating the operation being:</p> <pre><code>$dynamodb = new AmazonDynamoDB(); $scan_response = $dynamodb-&gt;scan(array( 'TableName' =&gt; 'ProductCatalog' )); foreach ($scan_response-&gt;body-&gt;Items as $item) { echo "&lt;p&gt;&lt;strong&gt;Item Number:&lt;/strong&gt;" . (string) $item-&gt;Id-&gt;{AmazonDynamoDB::TYPE_NUMBER}; echo "&lt;br&gt;&lt;strong&gt;Item Name: &lt;/strong&gt;" . (string) $item-&gt;Title-&gt;{AmazonDynamoDB::TYPE_STRING} ."&lt;/p&gt;"; } </code></pre>
10,543,512
How do I enumerate through a JObject?
<p>I'm trying to determine how to access the data that is in my JObject and I can't for the life of me determine how to use it.</p> <pre><code>JObject Object = (JObject)Response.Data["my_key"]; </code></pre> <p>I can print it to the console doing Console.WriteLine(Object) and I see the data, it looks like:</p> <pre><code>{ "my_data" : "more of my string data" ... } </code></pre> <p>But I have NO idea how to just iterate/enumerate through it, anyone have any ideas? I'm at such a loss right now.</p>
10,543,553
4
0
null
2012-05-10 23:30:16.193 UTC
19
2018-12-12 15:13:19.677 UTC
2012-12-21 13:26:12.447 UTC
null
41,071
null
524,481
null
1
138
c#|json|json.net
159,932
<p>If you look at <a href="http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm">the documentation for <code>JObject</code></a>, you will see that it implements <code>IEnumerable&lt;KeyValuePair&lt;string, JToken&gt;&gt;</code>. So, you can iterate over it simply using a <code>foreach</code>:</p> <pre><code>foreach (var x in obj) { string name = x.Key; JToken value = x.Value; … } </code></pre>
18,468,131
Substring with delimiter in SQL
<p>I'm trying to return a substring of the following, it's comma delimited [only one comma]</p> <pre><code>City-City-City, State-State-State </code></pre> <p>Sometimes it's only one city and state, sometimes it's more than one of either [or both]</p> <p>Basically, I need to just return the state initials pass the comma. What's the best way to do this? I'm looking into the substring function, but that doesn't seem that smart. I found a split function but it looks like overkill and I don't like to use code I don't understand.</p> <p>Ex:</p> <pre><code>Cincinnati-Middletown, OH-KY-IN Cleveland-Elyria-Mentor, OH Abilene, TX </code></pre> <p>Output:</p> <pre><code>OH-KY-IN OH TX </code></pre> <p>Thanks for the answers;I just figured it out thanks to Sonam's starting point. Here's what I got. Haven't looked into it but it seems to returning the right stuff.</p> <p><code>select substring(CBSAName,charindex(',',CBSAName)+1, LEN(CBSAName)) FROM CBSAMasterList</code></p>
18,468,239
1
3
null
2013-08-27 14:22:37.423 UTC
2
2013-08-27 14:48:55.853 UTC
2013-08-27 14:48:55.853 UTC
user1741874
null
user1741874
null
null
1
5
sql|sql-server
61,588
<pre><code>select substring('Abilene, TX',charindex(',','Abilene, TX')+2,2) </code></pre>
33,411,063
Select folder for save location
<p>I have a VBA macro with about 20 modules, which create separate spreadsheets in the workbook. They also save the individual spreadsheet created by each module of the macro into a specific folder on a shared drive. </p> <p>This is an example of a couple of lines that save the spreadsheet to the separate folder.</p> <pre><code>z = Format(DateTime.Now, "dd-MM-YYYY hhmm") wb.SaveAs "J:\AAAA\BBBB\CCCC\DDDD\mod1" &amp; z &amp; ".xlsx" Workbooks("mod1" &amp; z &amp; ".xlsx").Close savechanges:=True </code></pre> <p>However, as this file is now being shared out among a number of users, with different functions, the users now want to be able to set the location where the spreadsheets generated will be saved, on an individual basis.</p> <p>What I am looking for is some way for the macro to open a new window, and for the user to select a file path. That file path would then be stored into the macro so that each module can read the file location where it needs to be stored.</p> <p>Is this possible?</p> <p>Edit 1:</p> <p>I should have made a couple of things clearer. My apologies.</p> <p>The code above is replicated in every module. Also, all the modules are run from one overarching module, that calls the other.</p> <p>What I am looking for is a code that will allow the user to select the save location at the start of the overarching module. Eg. J\AAA\CCC\XXX. The modules, when called, will to retrieve the file path, and then save the file to that location.</p>
33,411,223
2
0
null
2015-10-29 09:59:26.46 UTC
null
2018-06-30 11:17:57.78 UTC
2015-10-29 10:27:40.907 UTC
null
4,430,536
null
4,430,536
null
1
0
vba|excel
52,127
<p>use this function:</p> <pre><code>Function GetFolder() As String Dim fldr As FileDialog Dim sItem As String Set fldr = Application.FileDialog(msoFileDialogFolderPicker) With fldr .Title = "Select a Folder" .AllowMultiSelect = False '.InitialFileName = strPath If .Show &lt;&gt; -1 Then GoTo NextCode sItem = .SelectedItems(1) End With NextCode: GetFolder = sItem Set fldr = Nothing End Function </code></pre> <p>it returns a folderpath</p>
33,190,234
WKWebView and window.open
<p>It appears that a lot of links on websites use window.open in their onclick handlers but WKWebView seems to completely ignore window.open.</p> <p>Is there a workaround for this?</p> <p>I tried setting javaScriptCanOpenWindowsAutomatically preference to true but that didn't seem to help</p>
33,198,751
1
0
null
2015-10-17 18:39:32.443 UTC
4
2018-09-30 12:38:10.24 UTC
null
null
null
null
308,444
null
1
29
ios|swift|wkwebview
20,203
<p>When a web application calls <code>window.open()</code> in JavaScript, the <code>WKWebView</code> will call the <code> - webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures: </code> method on its <code>UIDelegate</code>.</p> <p>In that delegate method you should create a new <code>WKWebView</code> with the <code>WKWebViewConfiguration</code> that is given to you. If you present this new <code>WKWebView</code> on screen, it will load with the correct content.</p> <p>This is documented in the <a href="https://developer.apple.com/library/ios/documentation/WebKit/Reference/WKUIDelegate_Ref/index.html#//apple_ref/occ/intfm/WKUIDelegate/webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:" rel="noreferrer">WKUIDelegate documentation</a>, although it is not very explicit that this is called as a result of <code>window.open()</code>.</p>
31,297,246
Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?
<p>I'm coming from iOS where it's easy and you simply use a UIViewController. However, in Android things seem much more complicated, with certain UIComponents for specific API Levels. I'm reading BigNerdRanch for Android (the book is roughly 2 years old) and they suggest I use <code>Activity</code> to host my <code>FragmentActivities</code>. However, I thought <code>Activity</code> was deprecated. </p> <p>So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I use both to host the components, and for the components themselves? Are there uses for all of these, or should I be using one or two almost exclusively?</p>
31,297,546
7
2
null
2015-07-08 15:32:32.543 UTC
111
2019-10-08 22:21:25.657 UTC
2016-07-13 09:48:07.197 UTC
null
2,040,375
null
4,867,024
null
1
314
android|android-fragments|android-activity|android-actionbaractivity|appcompatactivity
224,406
<blockquote> <p>I thought Activity was deprecated</p> </blockquote> <p>No.</p> <blockquote> <p>So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I use both to host the components, and for the components themselves? Are there uses for all of these, or should I be using one or two almost exclusively?</p> </blockquote> <p><code>Activity</code> is the baseline. Every activity inherits from <code>Activity</code>, directly or indirectly.</p> <p><code>FragmentActivity</code> is for use with the backport of fragments found in the <code>support-v4</code> and <code>support-v13</code> libraries. The native implementation of fragments was added in API Level 11, which is lower than your proposed <code>minSdkVersion</code> values. The only reason why you would need to consider <code>FragmentActivity</code> specifically is if you want to use nested fragments (a fragment holding another fragment), as that was not supported in native fragments until API Level 17.</p> <p><code>AppCompatActivity</code> is from the <code>appcompat-v7</code> library. Principally, this offers a backport of the action bar. Since the native action bar was added in API Level 11, you do not need <code>AppCompatActivity</code> for that. However, current versions of <code>appcompat-v7</code> also add a limited backport of the Material Design aesthetic, in terms of the action bar and various widgets. There are pros and cons of using <code>appcompat-v7</code>, well beyond the scope of this specific Stack Overflow answer.</p> <p><code>ActionBarActivity</code> is the old name of the base activity from <code>appcompat-v7</code>. For various reasons, they wanted to change the name. Unless some third-party library you are using insists upon an <code>ActionBarActivity</code>, you should prefer <code>AppCompatActivity</code> over <code>ActionBarActivity</code>.</p> <p>So, given your <code>minSdkVersion</code> in the 15-16 range:</p> <ul> <li><p>If you want the backported Material Design look, use <code>AppCompatActivity</code></p></li> <li><p>If not, but you want nested fragments, use <code>FragmentActivity</code></p></li> <li><p>If not, use <code>Activity</code></p></li> </ul> <p>Just adding from comment as note: <code>AppCompatActivity</code> extends <code>FragmentActivity</code>, so anyone who needs to use features of <code>FragmentActivity</code> can use <code>AppCompatActivity</code>.</p>
19,688,885
In Ansible, how do I add a line to the end of a file?
<p>I would expect this to be pretty simple. I'm using the <code>lineinfile</code> module like so:</p> <pre><code>- name: Update bashrc for PythonBrew for foo user lineinfile: dest=/home/foo/.bashrc backup=yes line="[[ -s ${pythonbrew.bashrc_path} ]] &amp;&amp; source ${pythonbrew.bashrc_path}" owner=foo regexp='^' state=present insertafter=EOF create=True </code></pre> <p>The problem I'm having is that it's replacing the last line in the file (which is <code>fi</code>) with my new line rather than appending the line. This produces a syntax error.</p> <p>Do I have the parameters correct? I've tried setting regexp to both <code>'^'</code> and <code>''</code> (blank). Is there another way to go about this?</p> <p>I'm using Ansible 1.3.3.</p>
46,088,908
2
0
null
2013-10-30 16:44:28.337 UTC
10
2020-07-10 16:13:20.833 UTC
null
null
null
null
1,093,087
null
1
46
ansible
64,910
<p>Apparently ansible has matured and now (version &gt;2.4.0) according to the <a href="http://docs.ansible.com/ansible/latest/lineinfile_module.html" rel="noreferrer">documentation</a>, The defaults when only the line is specified will append a given line to the destination file:</p> <pre><code> - name: Update bashrc for PythonBrew for foo user lineinfile: dest: /home/foo/.bashrc line: &quot;[[ -s ${pythonbrew.bashrc_path} ]] &amp;&amp; source {pythonbrew.bashrc_path}&quot; owner: foo </code></pre>
58,404,547
"Cannot read property 'match' of undefined" during Npm install
<p>I encountered error during building Jenkins</p> <p><strong>Jenkins Log</strong></p> <blockquote> <blockquote> <p>Task :api:processResources Task :api:classes Task :web:nodeSetup Task :web:npmSetup /var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/bin/npm -&gt; /var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/lib/node_modules/npm/bin/npm-cli.js /var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/bin/npx -&gt; /var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/lib/node_modules/npm/bin/npx-cli.js</p> </blockquote> <ul> <li>[email protected] added 430 packages from 832 contributors in 6.837s</li> </ul> <blockquote> <p>Task :web:npmInstall FAILED npm ERR! Cannot read property 'match' of undefined</p> </blockquote> <p>npm ERR! A complete log of this run can be found in: npm ERR!<br /> /var/lib/jenkins/.npm/_logs/2019-10-16T01_11_20_594Z-debug.log</p> <p>FAILURE: Build failed with an exception.</p> <ul> <li>What went wrong: Execution failed for task ':web:npmInstall'.</li> </ul> <blockquote> <p>Process 'command '/var/lib/jenkins/workspace/hds_v2_docker/web/.gradle/npm/npm-v6.11.2/bin/npm'' finished with non-zero exit value 1</p> </blockquote> <ul> <li><p>Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.</p> </li> <li><p>Get more help at <a href="https://help.gradle.org" rel="noreferrer">https://help.gradle.org</a></p> </li> </ul> <p>Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0. Use '--warning-mode all' to show the individual deprecation warnings. See <a href="https://docs.gradle.org/5.0/userguide/command_line_interface.html#sec:command_line_warnings" rel="noreferrer">https://docs.gradle.org/5.0/userguide/command_line_interface.html#sec:command_line_warnings</a></p> <p>BUILD FAILED in 33s</p> </blockquote> <p><strong>/var/lib/jenkins/.npm/_logs/2019-10-16T01_11_20_594Z-debug.log</strong></p> <pre><code>17 silly saveTree │ ├─┬ [email protected] 17 silly saveTree │ │ └── [email protected] 17 silly saveTree │ ├── [email protected] 17 silly saveTree │ └── [email protected] 17 silly saveTree └─┬ [email protected] 17 silly saveTree ├── [email protected] 17 silly saveTree ├── [email protected] 17 silly saveTree └── [email protected] 18 verbose stack TypeError: Cannot read property 'match' of undefined 18 verbose stack at tarballToVersion (/usr/local/lib/node_modules/npm/lib/install/inflate-shrinkwrap.js:87:20) 18 verbose stack at inflatableChild (/usr/local/lib/node_modules/npm/lib/install/inflate-shrinkwrap.js:99:22) 18 verbose stack at BB.each (/usr/local/lib/node_modules/npm/lib/install/inflate-shrinkwrap.js:55:12) 18 verbose stack at tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23) 18 verbose stack at Object.gotValue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/reduce.js:155:18) 18 verbose stack at Object.gotAccum (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/reduce.js:144:25) 18 verbose stack at Object.tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23) 18 verbose stack at Promise._settlePromiseFromHandler (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:512:31) 18 verbose stack at Promise._settlePromise (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:569:18) 18 verbose stack at Promise._settlePromiseCtx (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:606:10) 18 verbose stack at _drainQueueStep (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:142:12) 18 verbose stack at _drainQueue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:131:9) 18 verbose stack at Async._drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:147:5) 18 verbose stack at Immediate.Async.drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14) 18 verbose stack at runCallback (timers.js:810:20) 18 verbose stack at tryOnImmediate (timers.js:768:5) 19 verbose cwd /var/lib/jenkins/workspace/hds_v2_docker/web 20 verbose Linux 4.4.0-59-generic 21 verbose argv &quot;/usr/bin/node&quot; &quot;/usr/local/bin/npm&quot; &quot;install&quot; 22 verbose node v8.16.0 23 verbose npm v6.9.0 24 error Cannot read property 'match' of undefined 25 verbose exit [ 1, true ] </code></pre>
58,404,685
6
0
null
2019-10-16 01:30:40.413 UTC
8
2021-12-06 16:46:31.197 UTC
2020-10-25 23:25:28.893 UTC
null
205,229
null
2,613,170
null
1
47
node.js|npm
59,050
<p>Try removing your <code>package-lock.json</code> to see if that helps.</p> <pre><code>rm -rf package-lock.json </code></pre> <p>Edit: If the issue still persists, delete <code>node_modules</code> as well.</p> <pre><code>rm -rf node_modules </code></pre>
20,926,979
Web API 2 OWIN Bearer Token purpose of cookie?
<p>I am trying to understand the new OWIN Bearer Token authentication process in the Single Page App template in MVC 5. Please correct me if I'm wrong, for the OAuth password client authentication flow, Bearer Token authentication works by checking the http authorization request header for the Bearer access token code to see if a request is authenticated, it doesn't rely on cookie to check if a particular request is authenticated.</p> <p>According to this post:</p> <p><a href="https://blogs.msdn.microsoft.com/webdev/2013/09/20/understanding-security-features-in-the-spa-template-for-vs2013-rc/" rel="nofollow noreferrer">OWIN Bearer Token Authentication with Web API Sample</a></p> <pre class="lang-cs prettyprint-override"><code>public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { using (IdentityManager identityManager = _identityManagerFactory.CreateStoreManager()) { if (!await identityManager.Passwords.CheckPasswordAsync(context.UserName, context.Password)) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } string userId = await identityManager.Logins.GetUserIdForLocalLoginAsync(context.UserName); IEnumerable&lt;Claim&gt; claims = await GetClaimsAsync(identityManager, userId); ClaimsIdentity oAuthIdentity = CreateIdentity(identityManager, claims, context.Options.AuthenticationType); ClaimsIdentity cookiesIdentity = CreateIdentity(identityManager, claims, _cookieOptions.AuthenticationType); AuthenticationProperties properties = await CreatePropertiesAsync(identityManager, userId); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } } </code></pre> <p>The GrantReourceOwnerCredentials function not only compose the ticket with this line: context.Validated(ticket); but it also compose a cookie identity and set it to the cookie with this line: context.Request.Context.Authentication.SignIn(cookiesIdentity);</p> <p>So my questions are, what is the exact purpose of the cookie in this function? Shouldn't the AuthenticationTicket be good enough for authentication purpose?</p>
22,483,255
3
1
null
2014-01-04 21:28:39.163 UTC
19
2017-08-18 08:47:06.923 UTC
2017-08-18 08:47:06.923 UTC
null
5,919,316
null
934,650
null
1
36
asp.net-mvc-5|owin|katana|asp.net-web-api2
19,878
<p>In the SPA template there are actually two separate authentication mechanisms enabled- cookie authentication and token authentication. This enables authentication of both MVC and Web API controller actions, but requires some additional setup.</p> <p>If you look in the WebApiConfig.Register method you'll see this line of code:</p> <pre><code> config.SuppressDefaultHostAuthentication(); </code></pre> <p>That tells Web API to ignore cookie authentication, which avoids a host of problems which are explained in <a href="https://blogs.msdn.microsoft.com/webdev/2013/09/20/understanding-security-features-in-the-spa-template-for-vs2013-rc/" rel="nofollow noreferrer">the link you posted in your question</a>:</p> <blockquote> <p>"...the SPA template enables application cookie middleware as active mode as well in order to enable other scenarios like MVC authentication. So Web API will still be authenticated if the request has session cookie but without a bearer token. That’s probably not what you want as you would be venerable to CSRF attacks for your APIs. Another negative impact is that if request is unauthorized, both middleware components will apply challenges to it. The cookie middleware will alter the 401 response to a 302 to redirect to the login page. That is also not what you want in a Web API request."</p> </blockquote> <p>So now with the call to <code>config.SuppressDefaultHostAuthentication()</code> Web API calls that require authorization will ignore the cookie that is automatically sent along with the request and look for an Authorization header that begins with "Bearer". MVC controllers will continue to use cookie authentication and are ignorant of the token authentication mechanism as it's not a very good fit for web page authentication to begin with.</p>
21,901,368
Mockito verify order / sequence of method calls
<p>Is there a way to verify if a <code>methodOne</code> is called before <code>methodTwo</code> in Mockito?</p> <pre><code>public class ServiceClassA { public void methodOne(){} } public class ServiceClassB { public void methodTwo(){} } </code></pre> <hr> <pre><code>public class TestClass { public void method(){ ServiceClassA serviceA = new ServiceClassA(); ServiceClassB serviceB = new ServiceClassB(); serviceA.methodOne(); serviceB.methodTwo(); } } </code></pre>
21,901,415
5
0
null
2014-02-20 07:46:30.057 UTC
21
2021-03-11 09:33:12.363 UTC
2014-02-20 08:23:18.583 UTC
null
1,933,494
null
1,319,542
null
1
266
java|unit-testing|mockito
137,129
<p><a href="http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#inOrder(java.lang.Object...)"><code>InOrder</code></a> helps you to do that.</p> <pre><code>ServiceClassA firstMock = mock(ServiceClassA.class); ServiceClassB secondMock = mock(ServiceClassB.class); Mockito.doNothing().when(firstMock).methodOne(); Mockito.doNothing().when(secondMock).methodTwo(); //create inOrder object passing any mocks that need to be verified in order InOrder inOrder = inOrder(firstMock, secondMock); //following will make sure that firstMock was called before secondMock inOrder.verify(firstMock).methodOne(); inOrder.verify(secondMock).methodTwo(); </code></pre>
54,398,272
Override env values defined in container spec
<p>I have a configmap where I have defined the following key-value mapping in the <code>data</code> section:</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: namespace: test name: test-config data: TEST: "CONFIGMAP_VALUE" </code></pre> <p>then in the definition of my container (in the deployment / statefulset manifest) I have the following:</p> <pre><code> env: - name: TEST value: "ANOTHER_VALUE" envFrom: - configMapRef: name: test-config </code></pre> <p>When doing this I was expecting that the value from the configmap (TEST="CONFIGMAP_VALUE") will override the (default) value specified in the container spec (TEST="ANOTHER_VALUE"), but this is not the case (TEST always gets the value from the container spec). I couldn't find any relevant documentation about this - is it possible to achieve such env variable value overriding?</p>
54,398,918
1
0
null
2019-01-28 08:47:44.51 UTC
8
2021-07-09 06:53:01.663 UTC
null
null
null
null
588,264
null
1
36
deployment|kubernetes|environment-variables|containers|configmap
14,749
<p>From <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.19/#container-v1-core" rel="noreferrer">Kubernetes API reference</a>:</p> <blockquote> <p><code>envFrom</code> : List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.</p> </blockquote> <p>So above clearly states the <strong>env</strong> will take precedence than <strong>envFrom</strong>.</p> <blockquote> <p>When a key exists in multiple sources, the value associated with the last source will take precedence.</p> </blockquote> <p>So, for overriding, don't use <code>envFrom</code>, but define the value twice within <code>env</code>, see below:</p> <pre><code>apiVersion: v1 kind: ConfigMap metadata: namespace: default name: test-config data: TEST: &quot;CONFIGMAP_VALUE&quot; --- apiVersion: v1 kind: Pod metadata: name: busy namespace: default spec: containers: - name: busybox image: busybox env: - name: TEST value: &quot;DEFAULT_VAULT&quot; - name: TEST valueFrom: configMapKeyRef: name: test-config key: TEST command: - &quot;sh&quot; - &quot;-c&quot; - &gt; while true; do echo &quot;$(TEST)&quot;; sleep 3600; done </code></pre> <p>Check:</p> <pre><code>kubectl logs busy -n default CONFIGMAP_VALUE </code></pre>
35,659,178
Prevent typing in Text Field Input, Even Though Field is NOT Disabled/Read-Only
<p>Can I prevent HTML Text Field input even when my field is NOT Disabled or Read-only? I have this requirement.</p> <p>Maybe I can block all inputs via JS or jQuery? </p>
35,659,206
5
0
null
2016-02-26 18:32:58.847 UTC
7
2021-01-07 03:55:14.557 UTC
2016-02-26 18:42:05.877 UTC
null
4,281,779
null
1,005,607
null
1
28
javascript|jquery|html|disabled-input
60,659
<h2>See this <a href="https://jsfiddle.net/qsocgph2/" rel="noreferrer">fiddle</a></h2> <p>You can use jQuery for this.. You can do it as below</p> <pre><code>$('input').keypress(function(e) { e.preventDefault(); }); </code></pre> <p><strong>OR</strong></p> <p>you can just return false instead of using <code>preventDefault()</code>. See the script below</p> <pre><code>$('input').keypress(function(e) { return false }); </code></pre> <p>See the <a href="https://jsfiddle.net/qsocgph2/1/" rel="noreferrer">fiddle</a></p> <p><strong>OR</strong></p> <p>A much simplified version without Javascript would be as below. Just change your HTML as below</p> <pre><code>&lt;input type="text" onkeypress="return false;"/&gt; </code></pre> <p>See the <a href="https://jsfiddle.net/qsocgph2/2/" rel="noreferrer">fiddle</a></p>
29,901,409
How to detect if a user clicks browser back button in Angularjs
<p>I have a form-like page with some data. And want to show a popup/alert when a user clicks the browser back button, asking "if they want to go back or stay on the same page". I am using angular-ui-router's <code>$stateProvider</code> and want to bind this only to one state/view.</p>
29,901,473
4
2
null
2015-04-27 16:39:10.993 UTC
10
2021-11-01 09:57:16.557 UTC
2015-12-22 07:50:44.457 UTC
null
1,062,108
null
4,342,283
null
1
20
angularjs|angular-ui-router
46,949
<p><em>This is my previous answer for some other question, but it should be good to help you</em></p> <p>You can do it by using angular <code>$routeChangeStart</code></p> <h2>$routeChangeStart</h2> <p>Broadcasted before a route change. At this point the route services start resolving all of the dependencies needed for the route change to occur. Typically this involves fetching the view template as well as any dependencies defined in resolve route property. Once all of the dependencies are resolved $routeChangeSuccess is fired.</p> <p>The route change (and the <code>$location</code> change that triggered it) can be prevented by calling <code>preventDefault</code> method of the event. See <code>$rootScope.Scope</code> for more details about event object.</p> <hr /> <p>So please try this below code.</p> <pre><code> $scope.$on('$routeChangeStart', function (scope, next, current) { if (next.$$route.controller != &quot;Your Controller Name&quot;) { // Show here for your model, and do what you need** $(&quot;#yourModel&quot;).show(); } }); </code></pre> <h2>Update:</h2> <p>You need to write your functional work in the model popup. like</p> <p>Put some link buttons for</p> <ul> <li>Are you sure for go to prev page?</li> <li>do you want stay current page?</li> <li>Do you want logout? etc.</li> </ul> <p>then Add ng-click event for go prev page, stay current page with using <code>return false</code>, etc.</p>
8,670,001
How to launch PowerShell (not a script) from the command line
<p>I am new to PowerShell and am struggling with what I assume should be a simple operation&mdash;I am trying to launch a PowesShell window from the command line. </p> <p>If I launch a command line instance and type either <code>powershell</code> or <code>start powershell</code>, I am getting a PowerShell instance within the command line interface, i.e. the typical black background with white text. What I would like is for the typical PowerShell interface to launch&mdash;blue background with white text? I am running Windows&nbsp;XP with PowerShell 2.0 installed.</p>
8,671,671
3
0
null
2011-12-29 15:53:02.457 UTC
5
2017-06-16 22:34:12.57 UTC
2017-06-16 22:34:12.57 UTC
null
63,550
null
306,894
null
1
23
powershell|powershell-2.0
186,580
<p>Set the default console colors and fonts:</p> <p><a href="http://poshcode.org/2220">http://poshcode.org/2220</a><br> From Windows PowerShell Cookbook (O'Reilly)<br> by Lee Holmes (http://www.leeholmes.com/guide) </p> <pre><code>Set-StrictMode -Version Latest Push-Location Set-Location HKCU:\Console New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe' Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe' New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401 New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee New-ItemProperty . FaceName -type STRING -value "Lucida Console" New-ItemProperty . FontFamily -type DWORD -value 0x00000036 New-ItemProperty . FontSize -type DWORD -value 0x000c0000 New-ItemProperty . FontWeight -type DWORD -value 0x00000190 New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000 New-ItemProperty . QuickEdit -type DWORD -value 0x00000001 New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078 New-ItemProperty . WindowSize -type DWORD -value 0x00320078 Pop-Location </code></pre>
8,569,389
Add "Are you sure?" to my excel button, how can I?
<p>I have a button on my form that clears the entire 8 sheet workbook. I do want to clear it occasionally, but I would hate to do it by accident. I've tried googling it, but every result I've found assumes I have a much firmer grasp of VBA than I do. How can I make it so when the button is clicked a Dialog box pops up saying "This will erase everything! Are you sure? [Continue] [Cancel]"? Thanks.</p>
8,573,424
3
0
null
2011-12-20 00:27:04.17 UTC
6
2013-05-07 13:09:31.183 UTC
2013-05-07 13:09:31.183 UTC
null
1,760,495
null
248,547
null
1
24
vba|excel|dialog
131,813
<p>On your existing button code, simply insert this line before the procedure:</p> <pre><code>If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub </code></pre> <p>This will force it to quit if the user presses no.</p>
43,833,049
How to make fixed-content go above iOS keyboard?
<p>I can only find questions where people have the opposite problem.</p> <p>I want my fixed content to go above the iOS keyboard. Image of the problem:</p> <p><a href="https://i.stack.imgur.com/SzP7X.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/SzP7X.jpg" alt="fixed content goes below content on ios"></a></p> <p>I want iOS to behave like Android.</p> <p>Is there a simple way to achieve this?</p> <p>Parent element css:</p> <pre><code>.parent{ position:fixed; top: 0; left 0; right: 0; bottom: 0; width: 100%; height: 100%; } </code></pre> <p>Button css:</p> <pre><code>.button{ position:fixed; left 0; right: 0; bottom: 0; width: 100%; height: 5rem; } </code></pre>
71,547,560
3
0
null
2017-05-07 15:04:56.15 UTC
9
2022-09-20 01:27:05.373 UTC
2018-05-29 07:27:26.013 UTC
null
2,376,317
null
3,067,891
null
1
22
ios|css|iphone|google-chrome|safari
16,787
<p>We can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport" rel="nofollow noreferrer">VisualViewport</a> to calculate keyboard height. So we can set fixed-content pos correct.</p> <p>Small demo: <a href="https://whatwg6.github.io/pos-above-keyboard/index.html" rel="nofollow noreferrer">https://whatwg6.github.io/pos-above-keyboard/index.html</a></p> <p>Code snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const button = document.getElementById("button"); const input = document.getElementById("input"); const height = window.visualViewport.height; const viewport = window.visualViewport; window.addEventListener("scroll", () =&gt; input.blur()); window.visualViewport.addEventListener("resize", resizeHandler); function resizeHandler() { if (!/iPhone|iPad|iPod/.test(window.navigator.userAgent)) { height = viewport.height; } button.style.bottom = `${height - viewport.height + 10}px`; } function blurHandler() { button.style.bottom = "10px"; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { margin: 0; padding: 0; } #button { position: fixed; width: 100%; bottom: 10px; background-color: rebeccapurple; line-height: 40px; text-align: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="text" inputmode="decimal" value="0.99" id="input" onblur="blurHandler()" /&gt; &lt;div id="button"&gt;Button&lt;/div&gt;</code></pre> </div> </div> </p> <p>Problems: <a href="https://developers.google.com/web/updates/2017/09/visual-viewport-api#the_event_rate_is_slow" rel="nofollow noreferrer">https://developers.google.com/web/updates/2017/09/visual-viewport-api#the_event_rate_is_slow</a></p> <p>Why not innerHeight?: <a href="https://stackoverflow.com/questions/39417778/iphone-safari-not-resizing-viewport-on-keyboard-open">Iphone safari not resizing viewport on keyboard open</a></p>
231,550
Has anyone used or written an Ant task to compile (Rhino) JavaScript to Java bytecode?
<p>I'd like to use the <a href="https://developer.mozilla.org/en/Rhino_JavaScript_Compiler" rel="nofollow noreferrer">Rhino JavaScript</a> compiler to compile some JavaScript to .class bytecode files for use in a project. It seems like this should already exist, since there are groovyc, netrexxc, and jythonc tasks for Groovy, NetREXX(!) and Jython, respectively. Has anyone used or written such an Ant task, or can anyone provide some tips on how to write one?</p> <p>Ideally it would have some way to resolve dependencies among JavaScript or Java classes.</p>
231,750
3
0
null
2008-10-23 21:11:51.747 UTC
9
2011-09-12 17:26:21.57 UTC
2009-04-11 07:14:28.723 UTC
Steven Huwig
63,756
Steven Huwig
28,604
null
1
7
java|javascript|ant|rhino
5,213
<p>Why not simply use java task?</p> <pre><code>&lt;java fork="yes" classpathref="build.path" classname="org.mozilla.javascript.tools.jsc.Main" failonerror="true"&gt; &lt;arg value="-debug"/&gt; ... &lt;arg value="file.js"/&gt; &lt;/java&gt; </code></pre> <p>Any objections?</p>
19,122
Bash Pipe Handling
<p>Does anyone know how bash handles sending data through pipes?</p> <pre><code>cat file.txt | tail -20 </code></pre> <p>Does this command print all the contents of file.txt into a buffer, which is then read by tail? Or does this command, say, print the contents of file.txt line by line, and then pause at each line for tail to process, and then ask for more data? </p> <p>The reason I ask is that I'm writing a program on an embedded device that basically performs a sequence of operations on some chunk of data, where the output of one operation is send off as the input of the next operation. I would like to know how linux (bash) handles this so please give me a general answer, not specifically what happens when I run "cat file.txt | tail -20".</p> <p>EDIT: Shog9 pointed out a relevant Wikipedia Article, this didn't lead me directly to the article but it helped me find this: <a href="http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation</a> which did have the information I was looking for.</p> <hr> <p>I'm sorry for not making myself clear. Of course you're using a pipe and of course you're using stdin and stdout of the respective parts of the command. I had assumed that was too obvious to state.</p> <p>What I'm asking is how this is handled/implemented. Since both programs cannot run at once, how is data sent from stdin to stdout? What happens if the first program generates data significantly faster than the second program? Does the system just run the first command until either it's terminated or it's stdout buffer is full, and then move on to the next program, and so on in a loop until no more data is left to be processed or is there a more complicated mechanism?</p>
19,383
3
0
null
2008-08-21 00:20:34.133 UTC
13
2019-12-22 10:17:50.65 UTC
2019-12-22 10:17:50.65 UTC
Jeff V
12,258,312
num1
306
null
1
31
linux|bash|pipe|device
12,940
<p>I decided to write a slightly more detailed explanation.</p> <p>The "magic" here lies in the operating system. Both programs do start up at roughly the same time, and run at the same time (the operating system assigns them slices of time on the processor to run) as every other simultaneously running process on your computer (including the terminal application and the kernel). So, before any data gets passed, the processes are doing whatever initialization necessary. In your example, tail is parsing the '-20' argument and cat is parsing the 'file.txt' argument and opening the file. At some point tail will get to the point where it needs input and it will tell the operating system that it is waiting for input. At some other point (either before or after, it doesn't matter) cat will start passing data to the operating system using stdout. This goes into a buffer in the operating system. The next time tail gets a time slice on the processor after some data has been put into the buffer by cat, it will retrieve some amount of that data (or all of it) which leaves the buffer on the operating system. When the buffer is empty, at some point tail will have to wait for cat to output more data. If cat is outputting data much faster than tail is handling it, the buffer will expand. cat will eventually be done outputting data, but tail will still be processing, so cat will close and tail will process all remaining data in the buffer. The operating system will signal tail when their is no more incoming data with an EOF. Tail will process the remaining data. In this case, tail is probably just receiving all the data into a circular buffer of 20 lines, and when it is signalled by the operating system that there is no more incoming data, it then dumps the last twenty lines to its own stdout, which just gets displayed in the terminal. Since tail is a much simpler program than cat, it will likely spend most of the time waiting for cat to put data into the buffer.</p> <p>On a system with multiple processors, the two programs will not just be sharing alternating time slices on the same processor core, but likely running at the same time on separate cores.</p> <p>To get into a little more detail, if you open some kind of process monitor (operating system specific) like 'top' in Linux you will see a whole list of running processes, most of which are effectively using 0% of the processor. Most applications, unless they are crunching data, spend most of their time doing nothing. This is good, because it allows other processes to have unfettered access to the processor according to their needs. This is accomplished in basically three ways. A process could get to a sleep(n) style instruction where it basically tells the kernel to wait n milliseconds before giving it another time slice to work with. Most commonly a program needs to wait for something from another program, like 'tail' waiting for more data to enter the buffer. In this case the operating system will wake up the process when more data is available. Lastly, the kernel can preempt a process in the middle of execution, giving some processor time slices to other processes. 'cat' and 'tail' are simple programs. In this example, tail spends most of it's time waiting for more data on the buffer, and cat spends most of it's time waiting for the operating system to retrieve data from the harddrive. The bottleneck is the speed (or slowness) of the physical medium that the file is stored on. That perceptible delay you might detect when you run this command for the first time is the time it takes for the read heads on the disk drive to seek to the position on the harddrive where 'file.txt' is. If you run the command a second time, the operating system will likely have the contents of file.txt cached in memory, and you will not likely see any perceptible delay (unless file.txt is very large, or the file is no longer cached.)</p> <p>Most operations you do on your computer are IO bound, which is to say that you are usually waiting for data to come from your harddrive, or from a network device, etc.</p>
676,746
Custom html helpers: Create helper with "using" statement support
<p>I'm writing my first asp.net mvc application and I have a question about custom Html helpers:</p> <p>For making a form, you can use:</p> <pre><code>&lt;% using (Html.BeginForm()) {%&gt; *stuff here* &lt;% } %&gt; </code></pre> <p>I would like to do something similar with a custom HTML helper. In other words, I want to change:</p> <pre><code>Html.BeginTr(); Html.Td(day.Description); Html.EndTr(); </code></pre> <p>into:</p> <pre><code>using Html.BeginTr(){ Html.Td(day.Description); } </code></pre> <p>Is this possible?</p>
676,845
3
0
null
2009-03-24 10:04:21.363 UTC
19
2013-11-11 19:11:25.54 UTC
2011-09-22 08:28:03.017 UTC
null
41,956
Thomas Stock
72,859
null
1
39
.net|asp.net-mvc|html-helper
9,890
<p>Here is a possible reusable implementation in c# :</p> <pre><code>class DisposableHelper : IDisposable { private Action end; // When the object is created, write "begin" function public DisposableHelper(Action begin, Action end) { this.end = end; begin(); } // When the object is disposed (end of using block), write "end" function public void Dispose() { end(); } } public static class DisposableExtensions { public static IDisposable DisposableTr(this HtmlHelper htmlHelper) { return new DisposableHelper( () =&gt; htmlHelper.BeginTr(), () =&gt; htmlHelper.EndTr() ); } } </code></pre> <p>In this case, <code>BeginTr</code> and <code>EndTr</code> directly write in the response stream. If you use extension methods that return a string, you'll have to output them using :</p> <pre><code>htmlHelper.ViewContext.HttpContext.Response.Write(s) </code></pre>
6,977,177
W3C CSS grammar, syntax oddities
<p>I was having a look at the CSS syntax <a href="http://www.w3.org/TR/CSS21/syndata.html#syntax" rel="nofollow noreferrer">here</a> and <a href="http://www.w3.org/TR/CSS21/grammar.html" rel="nofollow noreferrer">here</a> and I was amazed to see both the token productions and the grammar littered with whitespace declarations. Normally whitespace is defined once in the lexer and skipped, never to be seen again. Ditto comments.</p> <p>I imagine the orientation towards user-agents rather than true compilers is part of the motivation here, and also the requirement to proceed in the face of errors, but it still seems pretty odd.</p> <p>Are real-life UAs that parse CSS really implemented according to this (these) grammars?</p> <p>EDIT: reason for the question is actually the various LESS implementations. <code>less.js</code> doesn't understand consecutive comments, and <code>lessc.exe</code> doesn't understand comments inside selectors. In this respect they are not even able to parse CSS correctly, however that is defined. So I went to see what the actual grammar of CSS was and ...</p>
7,108,177
1
3
null
2011-08-08 02:09:38.36 UTC
10
2016-03-19 21:17:00.943 UTC
2016-03-19 21:17:00.943 UTC
null
573,032
null
207,421
null
1
12
css|compiler-construction|programming-languages|grammar
2,452
<p>CSS, while similar to many programming languages, does have some <em>rare</em> instances where whitespace can be important.</p> <hr> <p>Say we have the following base markup:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; .blueborder { width:200px; height:200px; border: solid 2px #00f; } .redborder { width:100px; height:100px; margin:50px; border: solid 2px #f00; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="blueborder"&gt; &lt;div class="redborder"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>There's nothing special here, except a div inside of a div, with some styles on it so that you can see the difference between them.</p> <p>Now lets add another class and an ID to the outer div:</p> <pre><code>&lt;div class="blueborder MyClass" id="MyDiv"&gt; &lt;div class="redborder"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>If I want to give a background to the <em>outer</em> div in the following manner:</p> <pre><code>.MyClass#MyDiv { background: #ccc; } </code></pre> <p>...then the whitespace becomes important. The rule above <em>does</em> style the outer div, as it is parsed differently than the following:</p> <pre><code>.MyClass #MyDiv { background: #ccc; } </code></pre> <p>...which does NOT style the outer div.</p> <p>To see how these are parsed differently, you can look at how the selectors are tokenized:</p> <p>Example1:</p> <pre><code>.MyClass#MyDiv -&gt; DELIM IDENT HASH </code></pre> <p>Example2:</p> <pre><code>.MyClass #MyDiv -&gt; DELIM IDENT S HASH </code></pre> <p>If we were to blindly ignore whitespace (as compilers usually do), we would miss this difference.</p> <hr> <p><em>With that being said</em>, I am not implying that this grammer is good. I also have a fair amount of experience in writing grammars, and I cringe when looking at this grammar. The easiest solution would have been to add the <code>#</code> and <code>.</code> symbols into the IDENT token and then everything else becomes much easier.</p> <p>However they did not chose to do this, and the need for whitespace is an artifact of that decision.</p>