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
23,038,682
java.lang.RuntimeException: Only one Looper may be created per thread
<p>I have a simple thread that goes like this: </p> <pre><code>public class AwesomeRunnable extends Thread { Handler thisHandler = null; Handler uihandler = null; String update = null; long time = 0; public AwesomeRunnable(Handler h, long howLong) { uihandler = h; time = howLong; } public void run() { Looper.prepare(); thisHandler = new Handler(); ... </code></pre> <p><strong>EDIT: ADDED CODE THAT STARTS THE RUNNABLE</strong></p> <pre><code>public class StartCycle implements Runnable { @Override public void run() { pomodoroLeft = numPomodoro; while(pomodoroLeft &gt; 0) { pomodoroLeft--; actualSeconds = 6 * ONE_SECOND; runnable = new AwesomeRunnable(myHandler, actualSeconds); runnable.start(); waitForClock(); </code></pre> <p>It is an inner class of a main activity. <strong>This thread</strong>, however runs <strong>not on the main</strong> activity, but inside of <strong>another thread that runs</strong> on the <strong>main</strong> activity. </p> <p>Anyway, this example is <em>exactly</em> the same as <a href="http://developer.android.com/reference/android/os/Looper.html#quit%28%29">here</a>, but for some reason it gives me java.lang.RuntimeException: Only one Looper may be created per thread.</p> <p>I did not create any other loopers, at least explicitly anywhere. </p>
24,115,631
2
5
null
2014-04-13 03:10:15.917 UTC
1
2016-05-24 08:03:36.043 UTC
2014-04-13 03:40:21.917 UTC
null
3,081,519
null
3,081,519
null
1
31
java|android|multithreading
22,347
<blockquote> <p>java.lang.RuntimeException: Only one Looper may be created per thread</p> </blockquote> <p>The exception is thrown because you (or core Android code) has already called <code>Looper.prepare()</code> for the current executing thread.</p> <p>The following checks whether a Looper already exists for the current thread, if not, it creates one, thereby avoiding the <code>RuntimeException</code>.</p> <pre><code> public void run() { if (Looper.myLooper() == null) { Looper.prepare(); } thisHandler = new Handler(); .... } </code></pre>
32,017,457
How to implement a REST API Server?
<p>I am a university student with an intermediate level of C++ programming experience. <em>I would like to implement a simple REST based API for my application as quickly as possible.</em> </p> <p>I have looked at <a href="https://casablanca.codeplex.com/" rel="noreferrer">Casablanca</a> and <a href="https://libwebsockets.org/trac/libwebsockets" rel="noreferrer">libWebSockets</a> but the examples posted on their respective sites are a bit over my head. Is there any library that has more beginner oriented tutorials on creating a RESTFUL API Server in C++ ?</p> <p><strong>Note:</strong> I am aware that this question has been asked a few times in C# but the answers are over a year or two old and mostly not aimed at beginners. I hope that a new post will yield some fresh answers!</p>
32,018,952
5
6
null
2015-08-14 19:32:29.01 UTC
12
2017-12-07 13:49:51.997 UTC
2015-08-14 21:24:09.787 UTC
null
4,882,392
null
4,798,352
null
1
17
c++|api|rest
69,896
<p>Hey I also was new to the whole API game not too long ago. I found that deploying an <strong>ASP.NET Web API</strong> with Visual Studio was a great way to start. The template provided by VS (I'm using 2013) makes it really easy to create your own controllers. </p> <p>If you look up a couple tutorials on HTTP methods, you can really get the hang of molding your controller(s) to your needs. They map well to the CRUD operations which I'm sure you're looking to perform. </p> <p>You should also be able to find a library in C++ that will allow you to call each of your controller methods and pass/receive serialized JSON/XML objects. Hope this helped, good luck! :) </p>
9,090,332
Android: dynamically change ActionBar icon?
<p>I would like to dynamically change the "home" icon in the ActionBar. This is easily done in v14 with ActionBar.setIcon(...), but I can't find anyway to accomplish this in previous versions. </p>
9,203,086
4
3
null
2012-02-01 03:24:52.237 UTC
13
2015-04-11 16:18:39.913 UTC
null
null
null
null
426,493
null
1
24
android
25,296
<p>If you are using the <a href="http://developer.android.com/resources/samples/ActionBarCompat/index.html" rel="noreferrer">ActionbarCompat</a> code provided by google, you can access the home icon via the ActionBarHelperBase.java class for API v4 onwards. </p> <pre><code> //code snippet from ActionBarHelperBase.java ... private void setupActionBar() { final ViewGroup actionBarCompat = getActionBarCompat(); if (actionBarCompat == null) { return; } LinearLayout.LayoutParams springLayoutParams = new LinearLayout.LayoutParams( 0, ViewGroup.LayoutParams.MATCH_PARENT); springLayoutParams.weight = 1; // Add Home button SimpleMenu tempMenu = new SimpleMenu(mActivity); SimpleMenuItem homeItem = new SimpleMenuItem(tempMenu, android.R.id.home, 0, mActivity.getString(R.string.app_name)); homeItem.setIcon(R.drawable.ic_home_ftn); addActionItemCompatFromMenuItem(homeItem); // Add title text TextView titleText = new TextView(mActivity, null, R.attr.actionbarCompatTitleStyle); titleText.setLayoutParams(springLayoutParams); titleText.setText(mActivity.getTitle()); actionBarCompat.addView(titleText); } ... </code></pre> <p>You should be able to modify the code to the home button accessible to the activities that extend ActionBarActivity and change it that way.</p> <p>Honeycomb seems a little harder and it doesn't seem to give such easy access. At a guess, its id should also be android.R.id.home so you may be able to pull that from the view in ActionBarHelperHoneycomb.java</p>
9,537,797
R grep: Match one string against multiple patterns
<p>In R, grep usually matches a vector of multiple strings against one regexp. </p> <p><strong>Q: Is there a possibility to match a single string against multiple regexps? (without looping through each single regexp pattern)?</strong></p> <p><em>Some background:</em></p> <p>I have 7000+ keywords as indicators for several categories. I cannot change that keyword dictionary. The dictionary has following structure (keywords in col 1, numbers indicate categories where these keywords belong to):</p> <pre><code>ab 10 37 41 abbrach* 38 abbreche 39 abbrich* 39 abend* 37 abendessen* 60 63 aber 20 23 45 abermals 37 </code></pre> <p>Concatenating so many keywords with "|" is not a feasible way (and I wouldn't know which of the keywords generated the hit). Also, just reversing "patterns" and "strings" does not work, as the patterns have truncations, which wouldn't work the other way round.</p> <p>[<a href="https://stackoverflow.com/q/2180085/924912">related question</a>, other programming language]</p>
9,538,033
3
3
null
2012-03-02 17:35:57.07 UTC
14
2019-07-11 04:37:25.823 UTC
2017-05-23 12:10:39.893 UTC
null
-1
null
924,912
null
1
30
regex|r
22,769
<p>What about applying the regexpr function over a vector of keywords?</p> <pre><code>keywords &lt;- c("dog", "cat", "bird") strings &lt;- c("Do you have a dog?", "My cat ate by bird.", "Let's get icecream!") sapply(keywords, regexpr, strings, ignore.case=TRUE) dog cat bird [1,] 15 -1 -1 [2,] -1 4 15 [3,] -1 -1 -1 sapply(keywords, regexpr, strings[1], ignore.case=TRUE) dog cat bird 15 -1 -1 </code></pre> <p>Values returned are the position of the first character in the match, with <code>-1</code> meaning no match. </p> <p>If the position of the match is irrelevant, use <code>grepl</code> instead: </p> <pre><code>sapply(keywords, grepl, strings, ignore.case=TRUE) dog cat bird [1,] TRUE FALSE FALSE [2,] FALSE TRUE TRUE [3,] FALSE FALSE FALSE </code></pre> <p><strong>Update:</strong> This runs relatively quick on my system, even with a large number of keywords:</p> <pre><code># Available on most *nix systems words &lt;- scan("/usr/share/dict/words", what="") length(words) [1] 234936 system.time(matches &lt;- sapply(words, grepl, strings, ignore.case=TRUE)) user system elapsed 7.495 0.155 7.596 dim(matches) [1] 3 234936 </code></pre>
18,430,324
How to debug the error "OOM command not allowed when used memory > 'maxmemory'" in Redis?
<p>I'm getting "OOM command not allowed" when trying to set a key, <code>maxmemory</code> is set to 500M with <code>maxmemory-policy</code> "volatile-lru", I'm setting TTL for each key sent to redis.</p> <p><code>INFO</code> command returns : <code>used_memory_human:809.22M</code></p> <ol> <li>If maxmemory is set to 500M, how did I reached 809M ?</li> <li><code>INFO</code> command does not show any Keyspaces , how is it possible ? </li> <li><code>KEYS *</code> returns "(empty list or set)" ,I've tried to change db number , still no keys found.</li> </ol> <p>Here is info command output:</p> <pre><code>redis-cli -p 6380 redis 127.0.0.1:6380&gt; info # Server redis_version:2.6.4 redis_git_sha1:00000000 redis_git_dirty:0 redis_mode:standalone os:Linux 2.6.32-358.14.1.el6.x86_64 x86_64 arch_bits:64 multiplexing_api:epoll gcc_version:4.4.7 process_id:28291 run_id:229a2ee688bdbf677eaed24620102e7060725350 tcp_port:6380 uptime_in_seconds:1492488 uptime_in_days:17 lru_clock:1429357 # Clients connected_clients:1 client_longest_output_list:0 client_biggest_input_buf:0 blocked_clients:0 # Memory used_memory:848529904 used_memory_human:809.22M used_memory_rss:863551488 used_memory_peak:848529192 used_memory_peak_human:809.22M used_memory_lua:31744 mem_fragmentation_ratio:1.02 mem_allocator:jemalloc-3.0.0 # Persistence loading:0 rdb_changes_since_last_save:0 rdb_bgsave_in_progress:0 rdb_last_save_time:1375949883 rdb_last_bgsave_status:ok rdb_last_bgsave_time_sec:-1 rdb_current_bgsave_time_sec:-1 aof_enabled:0 aof_rewrite_in_progress:0 aof_rewrite_scheduled:0 aof_last_rewrite_time_sec:-1 aof_current_rewrite_time_sec:-1 aof_last_bgrewrite_status:ok # Stats total_connections_received:3 total_commands_processed:8 instantaneous_ops_per_sec:0 rejected_connections:0 expired_keys:0 evicted_keys:0 keyspace_hits:0 keyspace_misses:0 pubsub_channels:0 pubsub_patterns:0 latest_fork_usec:0 # Replication role:master connected_slaves:0 # CPU used_cpu_sys:18577.25 used_cpu_user:1376055.38 used_cpu_sys_children:0.00 used_cpu_user_children:0.00 # Keyspace redis 127.0.0.1:6380&gt; </code></pre>
18,458,713
6
0
null
2013-08-25 15:00:11.063 UTC
8
2020-09-21 17:57:14.82 UTC
2017-07-02 23:46:36.42 UTC
null
472,495
null
1,119,004
null
1
39
redis
64,729
<p>Any chance you changed the number of databases? If you use a very large number then the initial memory usage may be high</p>
18,360,118
SQL Variables as Column names in Where Clause
<p>I need some help with my SQL logic, and I've been working (and researching) this for 2 days now with zero success.</p> <p>My goal is to try an pass a variable from an ASP page to a stored procedure, which is utilizing the variable as criteria for a column name in the where clause.</p> <p>So for example (a simplified version of my query):</p> <pre><code>@strDept nvarchar(10), @strUser nvarchar(30) -- The asp page will pass f18 to @strDept &amp; Ted Lee to strUser -- f18 is the column name in my database that I need in the where. select x, y, z from table1 where @strDept in (@strUser) -- and this is the select statement, notice the where clause. </code></pre> <p>The stored procedure does execute, but it returns no values and I know its treating the @strDept as a literal nvarchar and not a column name. </p> <p>So I guess my question is, how do I get SQL Server 2005 to treat my @sqlDept variable as a column name? </p>
18,363,855
7
2
null
2013-08-21 14:25:03.407 UTC
1
2015-01-03 11:25:26.333 UTC
null
null
null
null
2,703,905
null
1
4
sql|sql-server|tsql
59,966
<p>If this is an internal company application why is everyone re-iterating and beating SQL Injection to death... Its very simple to just use Dynamic SQL. If you are comfortable that these are only internal users using this then its very simple. Here is the concept. You essentially write a SQL Statement that writes a string that is really a SQL statement and then execute it. </p> <pre><code>CREATE Procedure myDynamicProcedure @strDept nvarchar(10), @strUser nvarchar(30) as BEGIN </code></pre> <p><strong>1. Declare a variable to store the SQL Statement.</strong></p> <pre><code> DECLARE @SQL varchar(max) </code></pre> <p><strong>2. SET your @SQL Variable to be the SELECT Statement. Basically you are building it so it returns what you are wanting to write. Like this:</strong></p> <pre><code> SET @SQL = 'select x, y, z from table1 where' + @strDept + ' in ' + @strUser </code></pre> <p><strong>3. Execute the @SQL Statement and it will be exactly like you ran:</strong> SELECT x,y,z from table1 where f18 = 'Ted Lee'</p> <pre><code>EXEC (@SQL) END </code></pre>
18,456,192
Get specific objects from ArrayList when objects were added anonymously?
<p>I have created a short example of my problem. I'm creating a list of objects anonymously and adding them to an <code>ArrayList</code>. Once items are in the <code>ArrayList</code> I later come back and add more information to each object within the list. Is there a way to extract a specific object from the list if you do not know its index?</p> <p>I know only the Object's 'name' but you cannot do a <code>list.get(ObjectName)</code> or anything. What is the recommended way to handle this? I'd rather not have to iterate through the entire list every time I want to retrieve one specific object.</p> <pre><code>public class TestCode{ public static void main (String args []) { Cave cave = new Cave(); // Loop adds several Parties to the cave's party list cave.parties.add(new Party("FirstParty")); // all anonymously added cave.parties.add(new Party("SecondParty")); cave.parties.add(new Party("ThirdParty")); // How do I go about setting the 'index' value of SecondParty for example? } } class Cave { ArrayList&lt;Party&gt; parties = new ArrayList&lt;Party&gt;(); } class Party extends CaveElement{ int index; public Party(String n){ name = n; } // getter and setter methods public String toString () { return name; } } class CaveElement { String name = ""; int index = 0; public String toString () { return name + "" + index; } } </code></pre>
18,456,299
7
1
null
2013-08-27 02:54:10.877 UTC
1
2015-01-27 18:08:53 UTC
2015-01-27 18:08:53 UTC
null
1,585,868
null
1,585,868
null
1
13
java|object|arraylist
121,158
<p>Given the use of <code>List</code>, there's no way to "lookup" a value without iterating through it...</p> <p>For example...</p> <pre><code>Cave cave = new Cave(); // Loop adds several Parties to the cave's party list cave.parties.add(new Party("FirstParty")); // all anonymously added cave.parties.add(new Party("SecondParty")); cave.parties.add(new Party("ThirdParty")); for (Party p : cave.parties) { if (p.name.equals("SecondParty") { p.index = ...; break; } } </code></pre> <p>Now, this will take time. If the element you are looking for is at the end of the list, you will have to iterate to the end of the list before you find a match.</p> <p>It might be better to use a <code>Map</code> of some kind...</p> <p>So, if we update <code>Cave</code> to look like...</p> <pre><code>class Cave { Map&lt;String, Party&gt; parties = new HashMap&lt;String, Party&gt;(25); } </code></pre> <p>We could do something like...</p> <pre><code>Cave cave = new Cave(); // Loop adds several Parties to the cave's party list cave.parties.put("FirstParty", new Party("FirstParty")); // all anonymously added cave.parties.put("SecondParty", new Party("SecondParty")); cave.parties.put("ThirdParty", new Party("ThirdParty")); if (cave.parties.containsKey("SecondParty")) { cave.parties.get("SecondParty").index = ... } </code></pre> <p>Instead...</p> <p>Ultimately, this will all depend on what it is you want to achieve...</p>
18,267,091
Open a DatePickerDialog on Click of EditText takes two clicks
<p>I want to open a Calendar on the click of Edit text. After that I want to set the date which the user selects from the Calendar in the edit text. Problem is that, only when I click on the EditText for the second time then the calendar open. Please help me to resolve the issue(<code>why calendar don't open for the first time</code>).</p> <p><strong>EditText</strong> XML code</p> <pre><code>&lt;EditText android:id="@+id/dateofBirth" android:layout_width="290dp" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginTop="10dp" android:maxLines="1" android:hint="dd/mm/yyyy" /&gt; </code></pre> <p><strong>Activity</strong> Code</p> <pre><code>public void informationPopUp() { final Dialog dialog= new Dialog(MainActivity.this,R.style.Dialog_Fullscreen); dialog.setContentView(R.layout.details_dialog); dateofBirth = (EditText)dialog.findViewById(R.id.dateofBirth); dialog.show(); myCalendar = Calendar.getInstance(); final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub myCalendar.set(Calendar.YEAR, year); myCalendar.set(Calendar.MONTH, monthOfYear); myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); updateLabel(); } }; dateofBirth.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub showDialog(DATE_DIALOG_ID); } }); } private void updateLabel() { String myFormat = "MM/dd/yy"; //In which you need put here SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US); dateofBirth.setText(sdf.format(myCalendar.getTime())); } protected Dialog onCreateDialog(int id) { final Calendar now = Calendar.getInstance(); switch (id) { case DATE_DIALOG_ID: // set date picker as current date DatePickerDialog _date = new DatePickerDialog(this, date,myCalendar .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)){ @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth){ if (year &gt; now.get(Calendar.YEAR)) view.updateDate(myCalendar .get(Calendar.YEAR), myCalendar .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)); if (monthOfYear &gt; now.get(Calendar.MONTH) &amp;&amp; year == now.get(Calendar.YEAR)) view.updateDate(myCalendar .get(Calendar.YEAR), myCalendar .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)); if (dayOfMonth &gt; now.get(Calendar.DAY_OF_MONTH) &amp;&amp; year == now.get(Calendar.YEAR) &amp;&amp; monthOfYear == now.get(Calendar.MONTH)) view.updateDate(myCalendar .get(Calendar.YEAR), myCalendar .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)); } }; return _date; } return null; } </code></pre> <p>I am not understanding what I have done wrong. Please suggest a solution.</p>
18,267,997
20
11
null
2013-08-16 06:28:08.34 UTC
4
2022-02-28 11:00:23.58 UTC
2015-02-07 07:26:59.193 UTC
null
3,496,570
null
2,618,323
null
1
25
android|android-layout|android-datepicker
70,325
<p>I'll try to address your problem, but I am not completely sure about the first reason.</p> <ol> <li><p>The calendar opening only on the second click is because you are using an edittext. On the first click, your Edit Text will get focus. then the second click only calls the onClickListener.</p> <p>If you are not looking forward to edit the date set manually (using keyboard), then why not using a TextView to display the selected Date?</p></li> <li><p>The problem with the date not updating in editText is occurring because you are not setting the DateSetListener in your code. You need to set that to notify the system that a Date was set. The DateChange listener only returns the date while you are changing the date, and it doesn't appear that you are setting the date in the EditText.</p></li> </ol> <p>Try this code:</p> <pre><code> Calendar cal = Calendar.getInstance(TimeZone.getDefault()); DatePickerDialog datePicker = new DatePickerDialog(this, R.style.AppBlackTheme, datePickerListener, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); datePicker.setCancelable(false); datePicker.setTitle("Select the date"); return datePicker; } } catch (Exception e) { showMsgDialog("Exception", "An error occured while showing Date Picker\n\n" + " Error Details:\n" + e.toString(), "OK"); } return null; } private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() { // when dialog box is closed, below method will be called. public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) { String year1 = String.valueOf(selectedYear); String month1 = String.valueOf(selectedMonth + 1); String day1 = String.valueOf(selectedDay); TextView tvDt = (TextView) findViewById(R.id.tvDate); tvDt.setText(day1 + "/" + month1 + "/" + year1); } }; </code></pre> <p>In this, I am updating the date to a TextView with the ID "tvDate". I advise using a TextView instead of EditText and try this code.</p> <h2>Update</h2> <p>If you need to use EditText and load the calender in the first click, then try setting an onFocusListner to the editText instead of onClickListner.</p> <pre><code>editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus) { // Show your calender here } else { // Hide your calender here } } }); </code></pre>
19,920,052
Disable the notification panel from being pulled down
<p>I am working on a lockscreen app and I need to disable the ability to pull down the notification/status bar at the top of the screen. There is an app called Holo Locker and what this app does is when the user pulls down from the top of the screen, it just sets the bar back up to the top of the screen and making it impossible to pull the drawer down. </p> <p>I have no idea where to start. Any help would be great! Thanks!</p>
20,008,799
6
2
null
2013-11-12 02:58:01.46 UTC
15
2020-04-09 17:36:43.763 UTC
2013-11-15 05:37:44.927 UTC
null
529,691
null
1,701,764
null
1
17
android|android-notification-bar
47,063
<p>This is possible using reflection. There are plenty of problems though.</p> <p>There's no way to check if the notification panel is open, or opening. So, we'll have to rely on <code>Activity#onWindowFocusChanged(boolean)</code>. And this is where the problems begin. </p> <p>What the method does:</p> <blockquote> <p>public void onWindowFocusChanged (boolean hasFocus)</p> <p>Called when the current Window of the activity gains or loses focus. This is the best indicator of whether this activity is visible to the user.</p> </blockquote> <p>So, we'll have to figure out a way to distinguish between focus-loss due to showing of notification panel, and focus-loss because of other events.</p> <p>Some events that will trigger <code>onWindowFocusChanged(boolean)</code>:</p> <ul> <li><p>Window focus is lost when an activity is sent to background (user switching apps, or pressing the <code>home</code> button)</p></li> <li><p>Since Dialogs and PopupWindows open in their own separate windows, the activity's window focus will be lost when these are displayed. </p></li> <li><p>Another instance in which the activity's window will lose focus is when a spinner is clicked upon, displaying a PopupWindow.</p></li> </ul> <p>Your activity may not have to deal with all of these issues. The following example handles a subset of them:</p> <p>Firstly, you need the <code>EXPAND_STATUS_BAR</code> permission:</p> <pre><code>&lt;uses-permission android:name="android.permission.EXPAND_STATUS_BAR" /&gt; </code></pre> <p>Next, declare these class-scope variable in your activity:</p> <pre><code>// To keep track of activity's window focus boolean currentFocus; // To keep track of activity's foreground/background status boolean isPaused; Handler collapseNotificationHandler; </code></pre> <p>Override <code>onWindowFocusChanged(boolean)</code>:</p> <pre><code>@Override public void onWindowFocusChanged(boolean hasFocus) { currentFocus = hasFocus; if (!hasFocus) { // Method that handles loss of window focus collapseNow(); } } </code></pre> <p>Define <code>collapseNow()</code>:</p> <pre><code>public void collapseNow() { // Initialize 'collapseNotificationHandler' if (collapseNotificationHandler == null) { collapseNotificationHandler = new Handler(); } // If window focus has been lost &amp;&amp; activity is not in a paused state // Its a valid check because showing of notification panel // steals the focus from current activity's window, but does not // 'pause' the activity if (!currentFocus &amp;&amp; !isPaused) { // Post a Runnable with some delay - currently set to 300 ms collapseNotificationHandler.postDelayed(new Runnable() { @Override public void run() { // Use reflection to trigger a method from 'StatusBarManager' Object statusBarService = getSystemService("statusbar"); Class&lt;?&gt; statusBarManager = null; try { statusBarManager = Class.forName("android.app.StatusBarManager"); } catch (ClassNotFoundException e) { e.printStackTrace(); } Method collapseStatusBar = null; try { // Prior to API 17, the method to call is 'collapse()' // API 17 onwards, the method to call is `collapsePanels()` if (Build.VERSION.SDK_INT &gt; 16) { collapseStatusBar = statusBarManager .getMethod("collapsePanels"); } else { collapseStatusBar = statusBarManager .getMethod("collapse"); } } catch (NoSuchMethodException e) { e.printStackTrace(); } collapseStatusBar.setAccessible(true); try { collapseStatusBar.invoke(statusBarService); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // Check if the window focus has been returned // If it hasn't been returned, post this Runnable again // Currently, the delay is 100 ms. You can change this // value to suit your needs. if (!currentFocus &amp;&amp; !isPaused) { collapseNotificationHandler.postDelayed(this, 100L); } } }, 300L); } } </code></pre> <p>Handle activity's <code>onPause()</code> and <code>onResume()</code>:</p> <pre><code>@Override protected void onPause() { super.onPause(); // Activity's been paused isPaused = true; } @Override protected void onResume() { super.onResume(); // Activity's been resumed isPaused = false; } </code></pre> <p>Hope this is close to what you are looking for.</p> <p>Note: The flicker that happens when you slide the notification bar and hold on to it is unfortunately unavoidable. Its appearance can however be controlled/improved using 'better' values for handler-delays. This is issue is also present in the Holo Locker app.</p>
27,604,431
Handling a timer in React/Flux
<p>I'm working on an application where I want a timer to countdown from, say, 60 seconds to 0 and then change some content, after which the timer restarts again at 60.</p> <p>I have implemented this in React and Flux but since I'm new to this, I'm still running into some problems.</p> <p>I now want to add a start/stop button for the timer. I'm not sure where to put/handle the timer state.</p> <p>I have a component <code>Timer.jsx</code> which looks like this: </p> <pre><code>var React = require('react'); var AppStore = require('../stores/app-store.js'); var AppActions = require('../actions/app-actions.js'); function getTimeLeft() { return { timeLeft: AppStore.getTimeLeft() } } var Timer = React.createClass({ _tick: function() { this.setState({ timeLeft: this.state.timeLeft - 1 }); if (this.state.timeLeft &lt; 0) { AppActions.changePattern(); clearInterval(this.interval); } }, _onChange: function() { this.setState(getTimeLeft()); this.interval = setInterval(this._tick, 1000); }, getInitialState: function() { return getTimeLeft(); }, componentWillMount: function() { AppStore.addChangeListener(this._onChange); }, componentWillUnmount: function() { clearInterval(this.interval); }, componentDidMount: function() { this.interval = setInterval(this._tick, 1000); }, render: function() { return ( &lt;small&gt; ({ this.state.timeLeft }) &lt;/small&gt; ) } }); module.exports = Timer; </code></pre> <p>It retrieves a countdown duration from the store, where I simply have:</p> <p><code>var _timeLeft = 60;</code></p> <p>Now, when I want to implement a start/stop button, I feel like I should also implement this through Flux Actions, correct? So I was thinking of having something like this in my store:</p> <pre><code>dispatcherIndex: AppDispatcher.register(function(payload) { var action = payload.action; switch(action.actionType) { case AppConstants.START_TIMER: // do something break; case AppConstants.STOP_TIMER: // do something break; case AppConstants.CHANGE_PATTERN: _setPattern(); break; } AppStore.emitChange(); return true; }) </code></pre> <p>However, since my Timer component currently handles the setInterval, I don't know how to get my START/STOP_TIMER events working. Should I move the setInterval stuff from the Timer component to the Store and somehow pass this down to my component?</p> <p>Full code can be found <a href="https://github.com/cabaret/caged-system-trainer">here</a>.</p>
27,666,235
3
5
null
2014-12-22 14:15:54.783 UTC
10
2015-03-20 18:34:44.497 UTC
null
null
null
null
613,721
null
1
17
javascript|reactjs|reactjs-flux
19,845
<p>I ended up downloading your code and implementing the start/stop/reset feature you wanted. I think that's probably the best way to explain things - to show code that you can run and test along with some comments.</p> <p>I actually ended up with two implementations. I'll call them Implementation A and Implementation B. </p> <p>I thought it would be interesting to show both implementations. Hopefully it doesn't cause too much confusion.</p> <p>For the record, Implementation A is the better version.</p> <p>Here are brief descriptions of both implementations:</p> <p><strong>Implementation A</strong></p> <p>This version keeps track of the state at the App component level. The timer is managed by passing <code>props</code> to the Timer component. The timer component does keep track of it's own time left state though.</p> <p><strong>Implementation B</strong></p> <p>This version keeps track of the timer state at the the Timer component level using a TimerStore and TimerAction module to manage state and events of the component.</p> <p>The big (and probably fatal) drawback of implementation B is that you can only have one Timer component. This is due to the TimerStore and TimerAction modules essentially being Singletons.</p> <hr> <p><strong>|</strong></p> <p><strong>|</strong></p> <p><strong>Implementation A</strong></p> <p><strong>|</strong></p> <p><strong>|</strong></p> <p>This version keeps track of the state at the App component level. Most of the comments here are in the code for this version.</p> <p>The timer is managed by passing <code>props</code> to the Timer.</p> <p>Code changes listing for this implementation:</p> <ul> <li>app-constants.js</li> <li>app-actions.js</li> <li>app-store.js</li> <li>App.jsx</li> <li>Timer.jsx</li> </ul> <p><strong>app-constants.js</strong></p> <p>Here I just added a constant for reseting the timer.</p> <pre><code>module.exports = { START_TIMER: 'START_TIMER', STOP_TIMER: 'STOP_TIMER', RESET_TIMER: 'RESET_TIMER', CHANGE_PATTERN: 'CHANGE_PATTERN' }; </code></pre> <p><strong>app-actions.js</strong></p> <p>I just added a dispatch method for handling the reset timer action.</p> <pre><code>var AppConstants = require('../constants/app-constants.js'); var AppDispatcher = require('../dispatchers/app-dispatcher.js'); var AppActions = { changePattern: function() { AppDispatcher.handleViewAction({ actionType: AppConstants.CHANGE_PATTERN }) }, resetTimer: function() { AppDispatcher.handleViewAction({ actionType: AppConstants.RESET_TIMER }) }, startTimer: function() { AppDispatcher.handleViewAction({ actionType: AppConstants.START_TIMER }) }, stopTimer: function() { AppDispatcher.handleViewAction({ actionType: AppConstants.STOP_TIMER }) } }; module.exports = AppActions; </code></pre> <p><strong>app-store.js</strong></p> <p>Here is where things change a bit. I added detailed comments inline where I made changes.</p> <pre><code>var AppDispatcher = require('../dispatchers/app-dispatcher.js'); var AppConstants = require('../constants/app-constants.js'); var EventEmitter = require('events').EventEmitter; var merge = require('react/lib/Object.assign'); // I added a TimerStatus model (probably could go in its own file) // to manage whether the timer is "start/stop/reset". // // The reason for this is that reset state was tricky to handle since the Timer // component no longer has access to the "AppStore". I'll explain the reasoning for // that later. // // To solve that problem, I added a `reset` method to ensure the state // didn't continuously loop "reset". This is probably not very "Flux". // // Maybe a more "Flux" alternative is to use a separate TimerStore and // TimerAction? // // You definitely don't want to put them in AppStore and AppAction // to make your timer component more reusable. // var TimerStatus = function(status) { this.status = status; }; TimerStatus.prototype.isStart = function() { return this.status === 'start'; }; TimerStatus.prototype.isStop = function() { return this.status === 'stop'; }; TimerStatus.prototype.isReset = function() { return this.status === 'reset'; }; TimerStatus.prototype.reset = function() { if (this.isReset()) { this.status = 'start'; } }; var CHANGE_EVENT = "change"; var shapes = ['C', 'A', 'G', 'E', 'D']; var rootNotes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']; var boxShapes = require('../data/boxShapes.json'); // Added a variable to keep track of timer state. Note that this state is // managed by the *App Component*. var _timerStatus = new TimerStatus('start'); var _pattern = _setPattern(); function _setPattern() { var rootNote = _getRootNote(); var shape = _getShape(); var boxShape = _getBoxForShape(shape); _pattern = { rootNote: rootNote, shape: shape, boxShape: boxShape }; return _pattern; } function _getRootNote() { return rootNotes[Math.floor(Math.random() * rootNotes.length)]; } function _getShape() { return shapes[Math.floor(Math.random() * shapes.length)]; } function _getBoxForShape(shape) { return boxShapes[shape]; } // Simple function that creates a new instance of TimerStatus set to "reset" function _resetTimer() { _timerStatus = new TimerStatus('reset'); } // Simple function that creates a new instance of TimerStatus set to "stop" function _stopTimer() { _timerStatus = new TimerStatus('stop'); } // Simple function that creates a new instance of TimerStatus set to "start" function _startTimer() { _timerStatus = new TimerStatus('start'); } var AppStore = merge(EventEmitter.prototype, { emitChange: function() { this.emit(CHANGE_EVENT); }, addChangeListener: function(callback) { this.on(CHANGE_EVENT, callback); }, removeChangeListener: function(callback) { this.removeListener(CHANGE_EVENT, callback); }, // Added this function to get timer status from App Store getTimerStatus: function() { return _timerStatus; }, getPattern: function() { return _pattern; }, dispatcherIndex: AppDispatcher.register(function(payload) { var action = payload.action; switch(action.actionType) { case AppConstants.RESET_TIMER: // Handle reset action _resetTimer(); break; case AppConstants.START_TIMER: // Handle start action _startTimer(); break; case AppConstants.STOP_TIMER: // Handle stop action _stopTimer(); break; case AppConstants.CHANGE_PATTERN: _setPattern(); break; } AppStore.emitChange(); return true; }) }); module.exports = AppStore; </code></pre> <p><strong>App.jsx</strong></p> <p>There are numerous changes in App.jsx, specifically we have moved the state to the App component from the timer component. Again detailed comments in the code.</p> <pre><code>var React = require('react'); var Headline = require('./components/Headline.jsx'); var Scale = require('./components/Scale.jsx'); var RootNote = require('./components/RootNote.jsx'); var Shape = require('./components/Shape.jsx'); var Timer = require('./components/Timer.jsx'); // Removed AppActions and AppStore from Timer component and moved // to App component. This is done to to make the Timer component more // reusable. var AppActions = require('./actions/app-actions.js'); var AppStore = require('./stores/app-store.js'); // Use the AppStore to get the timerStatus state function getAppState() { return { timerStatus: AppStore.getTimerStatus() } } var App = React.createClass({ getInitialState: function() { return getAppState(); }, // Listen for change events in AppStore componentDidMount: function() { AppStore.addChangeListener(this.handleChange); }, // Stop listening for change events in AppStore componentWillUnmount: function() { AppStore.removeChangeListener(this.handleChange); }, // Timer component has status, defaultTimeout attributes. // Timer component has an onTimeout event (used for changing pattern) // Add three basic buttons for Start/Stop/Reset render: function() { return ( &lt;div&gt; &lt;header&gt; &lt;Headline /&gt; &lt;Scale /&gt; &lt;/header&gt; &lt;section&gt; &lt;RootNote /&gt; &lt;Shape /&gt; &lt;Timer status={this.state.timerStatus} defaultTimeout="15" onTimeout={this.handleTimeout} /&gt; &lt;button onClick={this.handleClickStart}&gt;Start&lt;/button&gt; &lt;button onClick={this.handleClickStop}&gt;Stop&lt;/button&gt; &lt;button onClick={this.handleClickReset}&gt;Reset&lt;/button&gt; &lt;/section&gt; &lt;/div&gt; ); }, // Handle change event from AppStore handleChange: function() { this.setState(getAppState()); }, // Handle timeout event from Timer component // This is the signal to change the pattern. handleTimeout: function() { AppActions.changePattern(); }, // Dispatch respective start/stop/reset actions handleClickStart: function() { AppActions.startTimer(); }, handleClickStop: function() { AppActions.stopTimer(); }, handleClickReset: function() { AppActions.resetTimer(); } }); module.exports = App; </code></pre> <p><strong>Timer.jsx</strong></p> <p>The <code>Timer</code> has many changes as well since I removed the <code>AppStore</code> and <code>AppActions</code> dependencies to make the <code>Timer</code> component more reusable. Detailed comments are in the code.</p> <pre><code>var React = require('react'); // Add a default timeout if defaultTimeout attribute is not specified. var DEFAULT_TIMEOUT = 60; var Timer = React.createClass({ // Normally, shouldn't use props to set state, however it is OK when we // are not trying to synchronize state/props. Here we just want to provide an option to specify // a default timeout. // // See http://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html) getInitialState: function() { this.defaultTimeout = this.props.defaultTimeout || DEFAULT_TIMEOUT; return { timeLeft: this.defaultTimeout }; }, // Changed this to `clearTimeout` instead of `clearInterval` since I used `setTimeout` // in my implementation componentWillUnmount: function() { clearTimeout(this.interval); }, // If component updates (should occur when setState triggered on Timer component // and when App component is updated/re-rendered) // // When the App component updates we handle two cases: // - Timer start status when Timer is stopped // - Timer reset status. In this case, we execute the reset method of the TimerStatus // object to set the internal status to "start". This is to avoid an infinite loop // on the reset case in componentDidUpdate. Kind of a hack... componentDidUpdate: function() { if (this.props.status.isStart() &amp;&amp; this.interval === undefined) { this._tick(); } else if (this.props.status.isReset()) { this.props.status.reset(); this.setState({timeLeft: this.defaultTimeout}); } }, // On mount start ticking componentDidMount: function() { this._tick(); }, // Tick event uses setTimeout. I find it easier to manage than setInterval. // We just keep calling setTimeout over and over unless the timer status is // "stop". // // Note that the Timer states is handled here without a store. You could probably // say this against the rules of "Flux". But for this component, it just seems unnecessary // to create separate TimerStore and TimerAction modules. _tick: function() { var self = this; this.interval = setTimeout(function() { if (self.props.status.isStop()) { self.interval = undefined; return; } self.setState({timeLeft: self.state.timeLeft - 1}); if (self.state.timeLeft &lt;= 0) { self.setState({timeLeft: self.defaultTimeout}); self.handleTimeout(); } self._tick(); }, 1000); }, // If timeout event handler passed to Timer component, // then trigger callback. handleTimeout: function() { if (this.props.onTimeout) { this.props.onTimeout(); } } render: function() { return ( &lt;small className="timer"&gt; ({ this.state.timeLeft }) &lt;/small&gt; ) }, }); module.exports = Timer; </code></pre> <hr> <p><strong>|</strong></p> <p><strong>|</strong></p> <p><strong>Implementation B</strong></p> <p><strong>|</strong></p> <p><strong>|</strong></p> <p>Code changes listing:</p> <ul> <li>app-constants.js</li> <li>timer-actions.js <em>(new)</em></li> <li>timer-store.js <em>(new)</em></li> <li>app-store.js</li> <li>App.jsx</li> <li>Timer.jsx</li> </ul> <p><strong>app-constants.js</strong></p> <p>These should probably go in a file named timer-constants.js since they deal with the Timer component.</p> <pre><code>module.exports = { START_TIMER: 'START_TIMER', STOP_TIMER: 'STOP_TIMER', RESET_TIMER: 'RESET_TIMER', TIMEOUT: 'TIMEOUT', TICK: 'TICK' }; </code></pre> <p><strong>timer-actions.js</strong></p> <p>This module is self-explanatory. I added three events - timeout, tick, and reset. See code for details.</p> <pre><code>var AppConstants = require('../constants/app-constants.js'); var AppDispatcher = require('../dispatchers/app-dispatcher.js'); module.exports = { // This event signals when the timer expires. // We can use this to change the pattern. timeout: function() { AppDispatcher.handleViewAction({ actionType: AppConstants.TIMEOUT }) }, // This event decrements the time left tick: function() { AppDispatcher.handleViewAction({ actionType: AppConstants.TICK }) }, // This event sets the timer state to "start" start: function() { AppDispatcher.handleViewAction({ actionType: AppConstants.START_TIMER }) }, // This event sets the timer state to "stop" stop: function() { AppDispatcher.handleViewAction({ actionType: AppConstants.STOP_TIMER }) }, // This event resets the time left and sets the state to "start" reset: function() { AppDispatcher.handleViewAction({ actionType: AppConstants.RESET_TIMER }) }, }; </code></pre> <p><strong>timer-store.js</strong></p> <p>I separated out the timer stuff from the <code>AppStore</code>. This is to make the Timer component a bit more reusable.</p> <p>The Timer store keeps track of the following state:</p> <ul> <li><strong>timer status</strong> - Can be "start" or "stop"</li> <li><strong>time left</strong> - Time left on timer</li> </ul> <p>The Timer store handles the following events:</p> <ul> <li>The timer start event sets timer status to start.</li> <li>The timer stop event sets timer status to stop.</li> <li>The tick event decrements the time left by 1</li> <li>The timer reset event sets the time left to the default and sets timer status to start</li> </ul> <p>Here is the code:</p> <pre><code>var AppDispatcher = require('../dispatchers/app-dispatcher.js'); var AppConstants = require('../constants/app-constants.js'); var EventEmitter = require('events').EventEmitter; var merge = require('react/lib/Object.assign'); var CHANGE_EVENT = "change"; var TIMEOUT_SECONDS = 15; var _timerStatus = 'start'; var _timeLeft = TIMEOUT_SECONDS; function _resetTimer() { _timerStatus = 'start'; _timeLeft = TIMEOUT_SECONDS; } function _stopTimer() { _timerStatus = 'stop'; } function _startTimer() { _timerStatus = 'start'; } function _decrementTimer() { _timeLeft -= 1; } var TimerStore = merge(EventEmitter.prototype, { emitChange: function() { this.emit(CHANGE_EVENT); }, addChangeListener: function(callback) { this.on(CHANGE_EVENT, callback); }, removeChangeListener: function(callback) { this.removeListener(CHANGE_EVENT, callback); }, getTimeLeft: function() { return _timeLeft; }, getStatus: function() { return _timerStatus; }, dispatcherIndex: AppDispatcher.register(function(payload) { var action = payload.action; switch(action.actionType) { case AppConstants.START_TIMER: _startTimer(); break; case AppConstants.STOP_TIMER: _stopTimer(); break; case AppConstants.RESET_TIMER: _resetTimer(); break; case AppConstants.TIMEOUT: _resetTimer(); break; case AppConstants.TICK: _decrementTimer(); break; } TimerStore.emitChange(); return true; }) }); module.exports = TimerStore; </code></pre> <p><strong>app-store.js</strong></p> <p>This could be named <code>pattern-store.js</code>, although you'd need to make some changes for it to be reusable. Specifically, I'm directly listening for the Timer's <code>TIMEOUT</code> action/event to trigger a pattern change. You likely don't want that dependency if you want to reuse pattern change. For example if you wanted to change the pattern by clicking a button or something.</p> <p>Aside from that, I just removed all the Timer related functionality from the <code>AppStore</code>.</p> <pre><code>var AppDispatcher = require('../dispatchers/app-dispatcher.js'); var AppConstants = require('../constants/app-constants.js'); var EventEmitter = require('events').EventEmitter; var merge = require('react/lib/Object.assign'); var CHANGE_EVENT = "change"; var shapes = ['C', 'A', 'G', 'E', 'D']; var rootNotes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']; var boxShapes = require('../data/boxShapes.json'); var _pattern = _setPattern(); function _setPattern() { var rootNote = _getRootNote(); var shape = _getShape(); var boxShape = _getBoxForShape(shape); _pattern = { rootNote: rootNote, shape: shape, boxShape: boxShape }; return _pattern; } function _getRootNote() { return rootNotes[Math.floor(Math.random() * rootNotes.length)]; } function _getShape() { return shapes[Math.floor(Math.random() * shapes.length)]; } function _getBoxForShape(shape) { return boxShapes[shape]; } var AppStore = merge(EventEmitter.prototype, { emitChange: function() { this.emit(CHANGE_EVENT); }, addChangeListener: function(callback) { this.on(CHANGE_EVENT, callback); }, removeChangeListener: function(callback) { this.removeListener(CHANGE_EVENT, callback); }, getPattern: function() { return _pattern; }, dispatcherIndex: AppDispatcher.register(function(payload) { var action = payload.action; switch(action.actionType) { case AppConstants.TIMEOUT: _setPattern(); break; } AppStore.emitChange(); return true; }) }); module.exports = AppStore; </code></pre> <p><strong>App.jsx</strong></p> <p>Here I just added some buttons for start/stop/reset. On click, a TimerAction is dispatched. So if you clicked the "stop" button, we call <code>TimerAction.stop()</code></p> <pre><code>var React = require('react'); var Headline = require('./components/Headline.jsx'); var Scale = require('./components/Scale.jsx'); var RootNote = require('./components/RootNote.jsx'); var Shape = require('./components/Shape.jsx'); var Timer = require('./components/Timer.jsx'); var TimerActions = require('./actions/timer-actions.js'); var App = React.createClass({ render: function() { return ( &lt;div&gt; &lt;header&gt; &lt;Headline /&gt; &lt;Scale /&gt; &lt;/header&gt; &lt;section&gt; &lt;RootNote /&gt; &lt;Shape /&gt; &lt;Timer /&gt; &lt;button onClick={this.handleClickStart}&gt;Start&lt;/button&gt; &lt;button onClick={this.handleClickStop}&gt;Stop&lt;/button&gt; &lt;button onClick={this.handleClickReset}&gt;Reset&lt;/button&gt; &lt;/section&gt; &lt;/div&gt; ); }, handleClickStart: function() { TimerActions.start(); }, handleClickStop: function() { TimerActions.stop(); }, handleClickReset: function() { TimerActions.reset(); } }); module.exports = App; </code></pre> <p><strong>Timer.jsx</strong></p> <p>One of the main changes is that we are using a TimerAction and TimerStore instead of the AppAction and AppStore that was used originally. The reason is to try to make the Timer component a bit more reusable.</p> <p>The Timer has the following state:</p> <ul> <li><strong>status</strong> Timer status can be "start" or "stop"</li> <li><strong>timeLeft</strong> Time left on timer</li> </ul> <p>Note that I used <code>setTimeout</code> instead of <code>setInterval</code>. I find <code>setTimeout</code> easier to manage.</p> <p>The bulk of the logic is in the <code>_tick</code> method. Basically we keep calling <code>setTimeout</code> so long as the status is "start".</p> <p>When the timer reaches zero, then we signal the <code>timeout</code> event. The TimerStore and AppStore are listening for this event.</p> <ol> <li>The TimerStore will merely reset the timer. Same the reset event.</li> <li>The AppStore will change the pattern.</li> </ol> <p>If the timer not reached zero, we subtract one second by signaling the "tick" event.</p> <p>Lastly we need to handle the case where the timer is stopped and then later started. This can be handled through the <code>componentDidUpdate</code> hook. This hook gets called when the component's state changes or the parent components gets re-rendered.</p> <p>In the <code>componentDidUpdate</code> method, we make sure to start the "ticking" only if the status is "start" and the timeout identifier is undefined. We don't want multiple setTimeouts running.</p> <pre><code>var React = require('react'); var TimerActions = require('../actions/timer-actions.js'); var TimerStore = require('../stores/timer-store.js'); function getTimerState() { return { status: TimerStore.getStatus(), timeLeft: TimerStore.getTimeLeft() } } var Timer = React.createClass({ _tick: function() { var self = this; this.interval = setTimeout(function() { if (self.state.status === 'stop') { self.interval = undefined; return; } if (self.state.timeLeft &lt;= 0) { TimerActions.timeout(); } else { TimerActions.tick(); } self._tick(); }, 1000); }, getInitialState: function() { return getTimerState(); }, componentDidMount: function() { TimerStore.addChangeListener(this.handleChange); this._tick(); }, componentWillUnmount: function() { clearTimeout(this.interval); TimerStore.removeChangeListener(this.handleChange); }, handleChange: function() { this.setState(getTimerState()); }, componentDidUpdate: function() { if (this.state.status === 'start' &amp;&amp; this.interval === undefined) { this._tick(); } }, render: function() { return ( &lt;small className="timer"&gt; ({ this.state.timeLeft }) &lt;/small&gt; ) } }); module.exports = Timer; </code></pre>
27,541,290
bug of autocorrelation plot in matplotlib‘s plt.acorr?
<p>I am plotting autocorrelation with python. I used three ways to do it: 1. pandas, 2. matplotlib, 3. statsmodels. I found the graph I got from matplotlib is not consistent with the other two. The code is:</p> <pre><code> from statsmodels.graphics.tsaplots import * # print out data print mydata.values #1. pandas p=autocorrelation_plot(mydata) plt.title('mydata') #2. matplotlib fig=plt.figure() plt.acorr(mydata,maxlags=150) plt.title('mydata') #3. statsmodels.graphics.tsaplots.plot_acf plot_acf(mydata) plt.title('mydata') </code></pre> <p>The graph is here: <a href="http://quant365.com/viewtopic.php?f=4&amp;t=33" rel="noreferrer">http://quant365.com/viewtopic.php?f=4&amp;t=33</a></p>
27,558,293
1
7
null
2014-12-18 07:29:34.357 UTC
11
2014-12-19 00:55:59.397 UTC
2014-12-18 10:50:45.343 UTC
null
3,951,977
null
3,951,977
null
1
12
python|matplotlib|pandas|statsmodels
15,225
<p>This is a result of different common definitions between statistics and signal processing. Basically, the signal processing definition assumes that you're going to handle the detrending. The statistical definition assumes that subtracting the mean is all the detrending you'll do, and does it for you.</p> <p>First off, let's demonstrate the problem with a stand-alone example:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd from statsmodels.graphics import tsaplots def label(ax, string): ax.annotate(string, (1, 1), xytext=(-8, -8), ha='right', va='top', size=14, xycoords='axes fraction', textcoords='offset points') np.random.seed(1977) data = np.random.normal(0, 1, 100).cumsum() fig, axes = plt.subplots(nrows=4, figsize=(8, 12)) fig.tight_layout() axes[0].plot(data) label(axes[0], 'Raw Data') axes[1].acorr(data, maxlags=data.size-1) label(axes[1], 'Matplotlib Autocorrelation') tsaplots.plot_acf(data, axes[2]) label(axes[2], 'Statsmodels Autocorrelation') pd.tools.plotting.autocorrelation_plot(data, ax=axes[3]) label(axes[3], 'Pandas Autocorrelation') # Remove some of the titles and labels that were automatically added for ax in axes.flat: ax.set(title='', xlabel='') plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/lwfNF.png" alt="enter image description here"></p> <p>So, why the heck am I saying that they're all correct? They're clearly different!</p> <p>Let's write our own autocorrelation function to demonstrate what <code>plt.acorr</code> is doing:</p> <pre><code>def acorr(x, ax=None): if ax is None: ax = plt.gca() autocorr = np.correlate(x, x, mode='full') autocorr /= autocorr.max() return ax.stem(autocorr) </code></pre> <p>If we plot this with our data, we'll get a more-or-less identical result to <code>plt.acorr</code> (I'm leaving out properly labeling the lags, simply because I'm lazy):</p> <pre><code>fig, ax = plt.subplots() acorr(data) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/xkiBX.png" alt="enter image description here"></p> <p>This is a perfectly valid autocorrelation. It's all a matter of whether your background is signal processing or statistics.</p> <p>This is the definition used in signal processing. The assumption is that you're going to handle detrending your data (note the <code>detrend</code> kwarg in <code>plt.acorr</code>). If you want it detrended, you'll explictly ask for it (and probably do something better than just subtracting the mean), and otherwise it shouldn't be assumed.</p> <p>In statistics, simply subtracting the mean is assumed to be what you wanted to do for detrending. </p> <p>All of the other functions are subtracting the mean of the data before the correlation, similar to this:</p> <pre><code>def acorr(x, ax=None): if ax is None: ax = plt.gca() x = x - x.mean() autocorr = np.correlate(x, x, mode='full') autocorr /= autocorr.max() return ax.stem(autocorr) fig, ax = plt.subplots() acorr(data) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/FNZ7w.png" alt="enter image description here"></p> <p>However, we still have one large difference. This one is purely a plotting convention. </p> <p>In most signal processing textbooks (that I've seen, anyway), the "full" autocorrelation is displayed, such that zero lag is in the center, and the result is symmetric on each side. R, on the other hand, has the very reasonable convention to display only one side of it. (After all, the other side is completely redundant.) The statistical plotting functions follow the R convetion, and <code>plt.acorr</code> follows what Matlab does, which is the opposite convention.</p> <p>Basically, you'd want this:</p> <pre><code>def acorr(x, ax=None): if ax is None: ax = plt.gca() x = x - x.mean() autocorr = np.correlate(x, x, mode='full') autocorr = autocorr[x.size:] autocorr /= autocorr.max() return ax.stem(autocorr) fig, ax = plt.subplots() acorr(data) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/U9R8J.png" alt="enter image description here"></p>
15,434,810
RabbitMQ "Hello World" example gives "Connection Refused"
<p>II'm trying to make the "hello world" application from here: <a href="http://www.rabbitmq.com/tutorials/tutorial-one-java.html" rel="noreferrer">RabbitMQ Hello World</a></p> <p>Here is the code of my producer class:</p> <pre><code>package com.mdnaRabbit.producer; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Channel; import java.io.IOException; public class App { private final static String QUEUE_NAME = "hello"; public static void main( String[] argv) throws IOException{ ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "Hello World!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println(" [x] Sent" + "'"); channel.close(); connection.close(); } } </code></pre> <p>And here what I get when implement this:</p> <pre><code>Exception in thread "main" java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391) at java.net.Socket.connect(Socket.java:579) at com.rabbitmq.client.ConnectionFactory.createFrameHandler(ConnectionFactory.java:445) at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:504) at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:533) at com.mdnaRabbit.producer.App.main(App.java:16) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) Process finished with exit code 1 </code></pre> <p>What is causing this?</p> <p>I found the solution to my problem here <a href="https://stackoverflow.com/questions/8939074/error-in-making-a-socket-connection">Error in making a socket connection</a></p>
15,540,476
8
3
null
2013-03-15 14:22:31.99 UTC
3
2020-11-18 17:13:26.943 UTC
2017-05-23 12:32:29.133 UTC
null
-1
null
2,082,631
null
1
21
java|exception-handling|rabbitmq
43,331
<p>To deal with it I installed RabbitMQ server. If rabbitmq-server is not installed this error will be thrown. Make sure you have installed RabbitMQ server and it's up and running by hitting <a href="http://localhost:15672/" rel="noreferrer">http://localhost:15672/</a></p>
15,460,279
How do I setup nested views in AngularJS?
<p>I have an application with various <em>screens</em>. Each screen is assigned a URL, such as <code>#</code>, <code>mails</code>, <code>contacts</code>, and so on.</p> <p>In my main HTML file I have an <code>ng-view</code> element which updates according to the route the user selects. So far, so good.</p> <p>Now some of these screens have a sub-navigation. E.g., <code>#mails</code> does have an inbox and a sent folder. They present themselfes with two columns: The sub-navigation on the left, the mails of the appropriate folder on the right.</p> <p>When you navigate to <code>#mails</code>, it shall redirect you to <code>#mails/inbox</code>, so that basically <em>inbox</em> is the default sub-view for mails.</p> <p>How could I set this up?</p> <p>The only approach I can currently think of (I am quite new to AngularJS, hence forgive me if this question is a little bit naive) is to have two views, one for <code>#mails/inbox</code>, and the other for <code>#mails/sent</code>.</p> <p>When you select a route, these views are loaded. When you select <code>#mails</code> it simply redirects you to <code>#mails/inbox</code>.</p> <p>But this means that both views must use an <code>ng-include</code> for the sub-navigation. Somehow this feels wrong to me.</p> <p>What I'd like more is to have nested views: The top one switches between screens such as mails, contacts, and so on, and the bottom one changes between sub-views such as inbox, sent, and so on.</p> <p>How would I solve this?</p>
15,495,104
2
4
null
2013-03-17 11:32:22.307 UTC
10
2016-02-10 11:45:39.773 UTC
null
null
null
null
1,333,873
null
1
39
uiview|angularjs|nested
44,923
<p><a href="https://github.com/angular-ui/ui-router">AngularJS ui-router</a> solved my issues :-)</p>
43,740,513
Typescript access dynamic property with [' '] syntax
<pre><code>export class Foo{ someproperty: string; } </code></pre> <p>I am trying to understand why, when trying to access dynamic object property I can do the following as I saw on one of the answers here:</p> <pre><code>let fooObj: foo = someObj['someproperty']; </code></pre> <p>but by doing this, I get an error.</p> <pre><code>let fooObj: foo = someObj.someproperty; </code></pre> <p>I am trying to understand, why the first method works for accessing/assigning to dynamic objects.</p> <p>Error:</p> <p><code>"someproperty does not exist on type"</code></p> <p>Question asked before here, answer by Angelo R is the one I am interested in.</p> <p><a href="https://stackoverflow.com/questions/12710905/how-do-i-dynamically-assign-properties-to-an-object-in-typescript">question</a></p>
43,740,761
2
6
null
2017-05-02 14:30:42.987 UTC
2
2022-01-29 14:22:26.147 UTC
2017-05-23 10:31:33.987 UTC
null
-1
null
2,964,415
null
1
23
javascript|typescript
39,551
<p>This is just a convention in TypeScript, available for convenience. If you want to access some arbitrary property that is not defined in the type signature of the object, you can use the <code>["foo"]</code> notation, and the type checker will not try to enforce that the instance you're accessing has such a property in its type signature.</p>
38,189,660
Two variables in Python have same id, but not lists or tuples
<p>Two variables in Python have the same <code>id</code>:</p> <pre><code>a = 10 b = 10 a is b &gt;&gt;&gt; True </code></pre> <p>If I take two <code>list</code>s:</p> <pre><code>a = [1, 2, 3] b = [1, 2, 3] a is b &gt;&gt;&gt; False </code></pre> <p>according to <a href="https://stackoverflow.com/questions/27460234/two-variables-with-the-same-list-have-different-ids-why-is-that?answertab=votes#tab-top">this link</a> Senderle answered that immutable object references have the same id and mutable objects like lists have different ids.</p> <p>So now according to his answer, tuples should have the same ids - meaning:</p> <pre><code>a = (1, 2, 3) b = (1, 2, 3) a is b &gt;&gt;&gt; False </code></pre> <p>Ideally, as tuples are not mutable, it should return <code>True</code>, but it is returning <code>False</code>!</p> <p>What is the explanation?</p>
38,189,759
4
5
null
2016-07-04 17:21:10.37 UTC
29
2020-04-20 11:07:50.063 UTC
2017-05-23 11:54:20.443 UTC
null
-1
null
6,548,439
null
1
55
python|python-3.x|tuples|identity|python-internals
17,906
<p>Immutable objects don't have the same <code>id</code>, and as a mater of fact this is not true for any type of objects that you define separately. Generally speaking, every time you define an object in Python, you'll create a new object with a new identity. However, for the sake of optimization (mostly) there are some exceptions for small integers (between -5 and 256) and interned strings, with a special length --usually less than 20 characters--<sup>*</sup> which are singletons and have the same <code>id</code> (actually one object with multiple pointers). You can check this like following:</p> <pre><code>&gt;&gt;&gt; 30 is (20 + 10) True &gt;&gt;&gt; 300 is (200 + 100) False &gt;&gt;&gt; 'aa' * 2 is 'a' * 4 True &gt;&gt;&gt; 'aa' * 20 is 'a' * 40 False </code></pre> <p>And for a custom object:</p> <pre><code>&gt;&gt;&gt; class A: ... pass ... &gt;&gt;&gt; A() is A() # Every time you create an instance you'll have a new instance with new identity False </code></pre> <p>Also note that the <code>is</code> operator will check the object's identity, not the value. If you want to check the value you should use <code>==</code>:</p> <pre><code>&gt;&gt;&gt; 300 == 3*100 True </code></pre> <p>And since there is no such optimizational or interning rule for tuples or any mutable type for that matter, if you define two same tuples in any size they'll get their own identities, hence different objects:</p> <pre><code>&gt;&gt;&gt; a = (1,) &gt;&gt;&gt; b = (1,) &gt;&gt;&gt; &gt;&gt;&gt; a is b False </code></pre> <p>It's also worth mentioning that rules of "singleton integers" and "interned strings" are true even when they've been defined within an iterator.</p> <pre><code>&gt;&gt;&gt; a = (100, 700, 400) &gt;&gt;&gt; &gt;&gt;&gt; b = (100, 700, 400) &gt;&gt;&gt; &gt;&gt;&gt; a[0] is b[0] True &gt;&gt;&gt; a[1] is b[1] False </code></pre> <hr> <p><sub> * A good and detailed article on this: <a href="http://guilload.com/python-string-interning/" rel="noreferrer">http://guilload.com/python-string-interning/</a> </sub></p>
9,402,658
Delete selected item from JList
<p>Can anyone tell me a short way to delete the selected items from my <code>JList</code>?</p> <p>I searched on google and here, but I found very many ways. Which way should I use?</p>
9,402,948
3
6
null
2012-02-22 20:46:39.05 UTC
2
2019-02-07 17:59:50.733 UTC
2015-08-21 10:02:02.587 UTC
null
4,370,109
null
1,173,452
null
1
16
java|swing|jlist
46,945
<p>As @Andreas_D said, the data centered, more abstract ListModel is the solution. This can be a <a href="http://docs.oracle.com/javase/6/docs/api/javax/swing/DefaultListModel.html" rel="noreferrer">DefaultListModel</a>. You should explicitly set the model in the JList. So (thanks to comment by @kleopatra):</p> <pre><code>DefaultListModel model = (DefaultListModel) jlist.getModel(); int selectedIndex = jlist.getSelectedIndex(); if (selectedIndex != -1) { model.remove(selectedIndex); } </code></pre> <p>There are several <code>remove...</code> methods in DefaultListModel. <em>By the way, this is a good question, as there is no immediate solution in the API (ListModel).</em></p>
8,952,688
didSelectRowAtIndexPath: not being called
<p>I have a <code>UITableView</code> as a subview of my <code>UIScrollVIew</code>, which is the main view controlled by my <code>MainViewController</code>. </p> <p>In MainViewController.h</p> <pre><code>@interface MainViewController : UIViewController &lt;UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource&gt; // other stuff here... @property (weak, nonatomic) IBOutlet UITableView *myTableView; </code></pre> <p>In MainViewController.m</p> <pre><code>@synthesize myTableView; // other stuff here... - (void)viewDidLoad { myTableView.delegate = self; myTableView.datasource = self; } // other stuff here... -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath { [self performSegueWithIdentifier:@"listAttributesSegue" sender:self]; } </code></pre> <p>I know that <code>didSelectRowAtIndexPath</code> is not being called because I have set breakpoints on both the method itself and the line of code inside it, and neither is being called. I also know that the datasource is working correctly because I have other functions which modify the cells at runtime and they are working perfectly fine. I am using the latest Xcode with iOS 5.0 set as the development target. I have searched and searched for an answer. Anyone have any ideas?</p> <p><strong>Edit:</strong> I have found the answer. I had a <code>UITapGestureRecognizer</code> set for myTableView's superView. This overrode the selection call. Credit to whoever suggested that that might be it. Your answer was deleted before I could mark it correct.</p> <p><strong>Edit 2:</strong> A lot of people have been commenting about this, so I though I would share it. If you are experiencing this problem, simply set <code>myGestureRecognizer.cancelsTouchInView</code> to <code>false</code> and everything should work fine.</p>
9,248,827
14
4
null
2012-01-21 11:40:04.94 UTC
26
2020-09-05 10:50:55.613 UTC
2014-07-08 18:21:27.4 UTC
null
1,053,564
null
1,053,564
null
1
60
iphone|ios|uitableview|didselectrowatindexpath
47,900
<p>I have found the answer. I had a UITapGestureRecognizer set for myTableView's superView. This overrode the selection call. Credit to whoever suggested that that might be it. Your answer was deleted before I could mark it correct.</p> <p>Set the <code>cancelsTouchesInView</code> property to <code>NO</code> on the gesture recogniser to allow the table view to intercept the event. </p>
5,047,406
Textbox Width Problems - ASP.NET
<p>I have a user control on a page of a website that generates a text box. The textbox has a width specified, but the text box is intermitently being shown at a much smaller width than is specified in the code. I asked the users to send me copies of the "view source" output so that I could compare good and bad results. By "intermittent", I mean similar builds - different computers. Please note that the bad results are ALWAYS displayed on the same "bad" computers (there is more than one user with this problem) and, conversely, the "good" computers (all with the same version of IE7 as the "bad" computers) always display "good" results.</p> <p>When the page is displayed correctly, the html that is sent to the browser looks like this:</p> <pre><code>&lt;input name="ShortDescription" type="text" maxlength="100" id="ShortDescription" class="content" style="width:800px;" /&gt; </code></pre> <p>and when it renders incorrectly, it looks like this:</p> <pre><code>&lt;input name="ShortDescription" type="text" maxlength="100" id="ShortDescription" class="content" /&gt; </code></pre> <p>In both cases, the ASP.NET code is:</p> <pre><code>&lt;asp:textbox id="ShortDescription" runat="server" CssClass="content" Width="800px" MaxLength="100"&gt; &lt;/asp:textbox&gt; </code></pre> <p>I am not sure why the style tag is getting dropped. The above pages were both viewed in the same browser (IE7) on different computers. The computers have a corporate build so they "should" be configured the same.</p> <p>I would appreciate any help!</p>
5,047,493
5
0
null
2011-02-18 22:51:10.997 UTC
3
2016-09-15 04:14:00.547 UTC
2011-02-18 23:03:22.293 UTC
null
602,554
null
623,863
null
1
10
asp.net|textbox|tags|coding-style
50,655
<p>Try setting the TextBox with in the CssClass, or as a style attribute parameter rather than using the Width attribute</p> <pre><code>&lt;asp:TextBox id="ShortDescription" runat="server" CssClass="content" MaxLength="100" style="width: 800px" /&gt;</code></pre> <pre><code>&lt;style&gt;.content { width: 800px }&lt/style> &lt;asp:TextBox id="ShortDescription" runat="server" CssClass="content" MaxLength="100" /&gt;</code></pre>
5,413,719
Photoshop Custom Shape to SVG path string
<p>Is there any way to get the SVG path string off a Photoshop custom shape or path? Or is there another way to get/construct similar data? I'm looking to do something similar to this:</p> <p><a href="http://raphaeljs.com/icons/" rel="noreferrer">http://raphaeljs.com/icons/</a></p>
23,337,275
5
0
null
2011-03-24 01:28:18.793 UTC
19
2019-10-29 11:34:36.863 UTC
2014-11-18 10:03:53.133 UTC
null
1,482,673
null
620,680
null
1
35
vector|svg|raphael|photoshop
60,890
<p><strong>Update:</strong> in recent versions of Photoshop, there is a built-in option to export the image as SVG, which works well on paths and custom shapes. Just do:</p> <blockquote> <p>File -> Export -> Export as... and select SVG in the file settings.</p> </blockquote> <p><strong>Original Answer:</strong></p> <p>Starting from Photoshop CC 14.2, you can create SVG files directly from Photoshop:</p> <ol> <li>Create a file named <code>generator.json</code> with the content below in your user home folder.</li> <li>Restart Photoshop and open your PSD file.</li> <li>Activate the generator: File > Generate > Image Assets.</li> <li>Rename your layer to <code>&lt;something&gt;.svg</code>.</li> <li>The svg file will be created in the assets directory next to your PSD file.</li> </ol> <p>Content for generator.json:</p> <pre><code>{ "generator-assets": { "svg-enabled": true } } </code></pre> <p>Source: <a href="http://creativedroplets.com/generate-svg-with-photoshop-cc-beta/" rel="noreferrer">http://creativedroplets.com/generate-svg-with-photoshop-cc-beta/</a></p>
5,239,997
Regex, how to match multiple lines?
<p>I'm trying to match the <code>From</code> line all the way to the end of the <code>Subject</code> line in the following:</p> <pre><code>.... From: XXXXXX Date: Tue, 8 Mar 2011 10:52:42 -0800 To: XXXXXXX Subject: XXXXXXX .... </code></pre> <p>So far I have:</p> <pre><code>/From:.*Date:.*To:.*Subject/m </code></pre> <p>But that doesn't match to the end of the subject line. I tried adding <code>$</code> but that had no effect.</p>
5,240,101
5
5
null
2011-03-09 00:19:48.61 UTC
5
2015-08-12 21:14:31.927 UTC
2015-08-12 21:14:31.927 UTC
null
664,833
null
149,080
null
1
65
ruby|regex|rubular
63,180
<p>You can use the <code>/m</code> modifier to enable multiline mode (i.e. to allow <code>.</code> to match newlines), and you can use <code>?</code> to perform non-greedy matching:</p> <pre><code>message = &lt;&lt;-MSG Random Line 1 Random Line 2 From: [email protected] Date: 01-01-2011 To: [email protected] Subject: This is the subject line Random Line 3 Random Line 4 MSG message.match(/(From:.*Subject.*?)\n/m)[1] =&gt; "From: [email protected]\nDate: 01-01-2011\nTo: [email protected]\nSubject: This is the subject line" </code></pre> <p>See <a href="http://ruby-doc.org/core/Regexp.html" rel="noreferrer">http://ruby-doc.org/core/Regexp.html</a> and search for "multiline mode" and "greedy by default".</p>
5,046,771
How to get today's Date?
<p>In other words, I want functionality that provides Joda-Time:</p> <pre><code>today = today.withTime(0, 0, 0, 0); </code></pre> <p>but without Joda-Time, only with java.util.Date.</p> <p>Methods such as .setHours() and etc. are deprecated. Is there are more correct way?</p>
5,046,816
8
4
null
2011-02-18 21:28:59.397 UTC
10
2018-11-27 23:52:58.993 UTC
2011-02-18 22:54:00.9 UTC
null
458,066
null
458,066
null
1
52
java|date
317,263
<pre><code>Date today = new Date(); today.setHours(0); //same for minutes and seconds </code></pre> <p>Since the methods are deprecated, you can do this with <code>Calendar</code>:</p> <pre><code>Calendar today = Calendar.getInstance(); today.set(Calendar.HOUR_OF_DAY, 0); // same for minutes and seconds </code></pre> <p>And if you need a <code>Date</code> object in the end, simply call <code>today.getTime()</code></p>
5,204,082
Is it possible in java make something like Comparator but for implementing custom equals() and hashCode()
<p>I have an array of objects and I want to concatenate it with another array of objects, except that objects that have same id's. That objects are used in many places in the system and don't have hash code or equals implemented. So I don't want to implement <code>hashCode()</code> and <code>equals()</code>, cause I'm afraid to break something somewhere in the system where that objects are used and I don't know about that. </p> <p>I want to put all that objects in a set, but somehow make the objects use custom <code>hashCode()</code> and <code>equals()</code>. Something like custom <code>Comparator</code>, but for equals.</p>
5,204,242
8
5
null
2011-03-05 13:27:25.297 UTC
15
2021-07-27 00:52:35.09 UTC
2018-06-06 20:42:09.71 UTC
null
632,293
null
260,894
null
1
61
java|collections|equals|hashcode
21,683
<p>Yes it is possible to do such a thing. (And people have done it.) But it won't allow you to put your objects into a <code>HashMap</code>, <code>HashSet</code>, etc. That is because the standard collection classes expect the key objects themselves to provide the <code>equals</code> and <code>hashCode</code> methods. (That is the way they are designed to work ...)</p> <p>Alternatives:</p> <ol> <li><p>Implement a wrapper class that holds an instance of the real class, and provides its own implementation of <code>equals</code> and <code>hashCode</code>.</p> </li> <li><p>Implement your own hashtable-based classes which can use a &quot;hashable&quot; object to provide equals and hashcode functionality.</p> </li> <li><p>Bite the bullet and implement <code>equals</code> and <code>hashCode</code> overrides on the relevant classes.</p> </li> </ol> <p>In fact, the 3rd option is probably the best, because your codebase most likely <em>needs</em> to to be using a consistent notion of what it means for these objects to be equal. There are other things that suggest that your code needs an overhaul. For instance, the fact that it is currently using an array of objects instead of a Set implementation to represent what is apparently supposed to be a set.</p> <p>On the other hand, maybe there was/is some real (or imagined) performance reason for the current implementation; e.g. reduction of memory usage. In that case, you should probably write a bunch of helper methods for doing operations like concatenating 2 sets represented as arrays.</p>
5,539,139
Change/Get check state of CheckBox
<p>I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.</p> <p>JavaScript function</p> <pre><code> function checkAddress() { if (checkAddress.checked == true) { alert("a"); } } </code></pre> <p>HTML</p> <pre><code>&lt;input type="checkbox" name="checkAddress" onchange="checkAddress()" /&gt; </code></pre>
5,539,186
11
0
null
2011-04-04 13:26:24.453 UTC
7
2020-02-01 08:36:58.873 UTC
2011-11-29 23:25:02.613 UTC
null
15,168
null
440,611
null
1
61
javascript|html
224,864
<p>Using <code>onclick</code> instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.</p> <p>You also need to pass the checkbox into the function:</p> <pre><code>function checkAddress(checkbox) { if (checkbox.checked) { alert("a"); } } </code></pre> <p>HTML</p> <pre><code>&lt;input type="checkbox" name="checkAddress" onclick="checkAddress(this)" /&gt; </code></pre>
5,284,646
Rank items in an array using Python/NumPy, without sorting array twice
<p>I have an array of numbers and I'd like to create another array that represents the rank of each item in the first array. I'm using Python and NumPy.</p> <p>For example:</p> <pre><code>array = [4,2,7,1] ranks = [2,1,3,0] </code></pre> <p>Here's the best method I've come up with:</p> <pre><code>array = numpy.array([4,2,7,1]) temp = array.argsort() ranks = numpy.arange(len(array))[temp.argsort()] </code></pre> <p>Are there any better/faster methods that avoid sorting the array twice?</p>
5,284,703
11
1
null
2011-03-12 18:52:11.203 UTC
36
2022-06-19 16:11:50.763 UTC
2019-05-28 14:02:38.85 UTC
null
202,229
null
401,818
null
1
137
python|sorting|numpy
121,970
<p>Use <em>advanced indexing</em> on the left-hand side in the last step:</p> <pre><code>array = numpy.array([4,2,7,1]) temp = array.argsort() ranks = numpy.empty_like(temp) ranks[temp] = numpy.arange(len(array)) </code></pre> <p>This avoids sorting twice by inverting the permutation in the last step.</p>
16,785,579
java.sql.SQLException: Io exception: Connection reset by peer: socket write error
<p>I am using oracle 11g,hibernate 3 and jsf2.I deployed my application on was7.Every thing is going well but when i try to login after 5-6 hours it is gives me error</p> <pre><code>ERROR org.hibernate.util.JDBCExceptionReporter - Io exception: Connection reset by peer: socket write error [5/28/13 11:31:25:048 IST] 00000024 SystemErr R org.hibernate.exception.GenericJDBCException: could not execute query at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126) at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.loader.Loader.doList(Loader.java:2231) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2125) at org.hibernate.loader.Loader.list(Loader.java:2120) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:361) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1148) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) </code></pre> <p>I unable to find out how this error to solve.Please help me.Thanks in advance.</p> <p>Now i have solved this problem by code but i don'nt know is it proper way or not.will you suggest me, i should continue with this solution on not.</p> <pre><code>public class ApplicationUtilityBean implements Serializable { private SessionFactory sessionFactory; private AnnotationConfiguration cfg; public String filePath; private String realPath = Config.PATH; public ApplicationUtilityBean() throws URISyntaxException { getConnection(); } public void getConnection() { URL r = this.getClass().getClassLoader().getResource("hibernate.cfg.xml"); cfg = new AnnotationConfiguration(); cfg.configure(r); String pwd = cfg.getProperty("hibernate.connection.password"); TripleDESEncryption tripledesenc = null; try { tripledesenc = new TripleDESEncryption(); } catch (Exception e) { e.printStackTrace(); } cfg.setProperty("hibernate.connection.password", tripledesenc.decrypt(pwd)); sessionFactory = cfg.buildSessionFactory(); System.out.println("cfg: " + cfg); System.out.println("sessionFactory: " + sessionFactory); } public Session getSession() { System.out.println("Going to get session"); Session session = null; try { System.out.println("cfg is: " + cfg); System.out.println("sessionFactory: " + sessionFactory); session = sessionFactory.openSession(); if(session != null){ try { Transaction trxn = session.beginTransaction(); Query queryResult = session.createSQLQuery("select * from dual"); List&lt;GTS_USER&gt;listgtsuser = queryResult.list(); } catch (Exception e) { e.printStackTrace(); System.out.println("Creating new connection............"); session.close(); sessionFactory.close(); getConnection(); session = sessionFactory.openSession(); } } } catch (Exception e) { e.printStackTrace(); } return session; } </code></pre> <p>}</p> <p>and my hibernate config file is</p> <pre><code>&lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;property name="hibernate.cache.region.factory_class"&gt;net.sf.ehcache.hibernate.EhCacheRegionFactory&lt;/property&gt; &lt;property name="hibernate.cache.use_query_cache"&gt;true&lt;/property&gt; &lt;property name="hibernate.cache.use_second_level_cache"&gt;true&lt;/property&gt; &lt;property name="hibernate.connection.driver_class"&gt;oracle.jdbc.OracleDriver&lt;/property&gt; &lt;property name="hibernate.connection.url"&gt;jdbc:oracle:thin:@xxxxxxxxx:1521:HMS&lt;/property&gt; &lt;property name="hibernate.connection.username"&gt;xxxxx&lt;/property&gt; &lt;property name="hibernate.connection.password"&gt;xxxxxxxxxxx&lt;/property&gt; &lt;property name="hibernate.connection.pool_size"&gt;10&lt;/property&gt; &lt;property name="show_sql"&gt;true&lt;/property&gt; &lt;property name="dialect"&gt;org.hibernate.dialect.OracleDialect&lt;/property&gt; &lt;property name="hibernate.hbm2ddl.auto"&gt;update&lt;/property&gt; </code></pre>
16,785,889
3
2
null
2013-05-28 06:52:52.097 UTC
2
2013-08-06 06:56:15.613 UTC
2013-08-06 06:51:16.303 UTC
null
314,291
null
2,427,229
null
1
7
java|database
39,234
<p>You are probably facing a database connection timeout. On every databases there is a timeout when a connection is open and there is no activity for a certain period. You need a connection pool manager.</p> <p>If you install <code>c3p0</code> and configure it correctly it will allow hibernate to keep your connection alive and/or re-open it when you need it.</p> <p>Here is an <a href="http://crazytechthoughts.blogspot.ca/2011/06/resolve-hibernate-connection-timeout.html" rel="noreferrer">example</a> for MySQL and Hibernate indeed but it is the same. You have to include <code>c3p0.jar</code> and also add this to your hibernade configuration file :</p> <pre><code>&lt;property name="c3p0.min_size"&gt;5&lt;/property&gt; &lt;property name="c3p0.max_size"&gt;20&lt;/property&gt; &lt;property name="c3p0.timeout"&gt;1800&lt;/property&gt; &lt;property name="c3p0.max_statements"&gt;50&lt;/property&gt; &lt;property name="hibernate.connection.provider_class"&gt;org.hibernate.connection.C3P0ConnectionProvider&lt;/property&gt; </code></pre> <p>Make sure to configure <code>c3p0.timeout</code> according to your database!</p>
41,331,631
Why command "php artisan serve" not working
<p>I started Laravel at this path:</p> <pre><code>C:\Users\Mad\Work\trunk\product\backend\v1.2.1\laravel </code></pre> <p>but it is not working, it is not starting. </p> <p>Please give me suggestions how I will do it ?</p>
41,336,685
10
3
null
2016-12-26 12:54:32.467 UTC
9
2022-01-20 13:07:50.143 UTC
2016-12-27 17:35:31.193 UTC
null
7,205,060
null
7,205,060
null
1
16
laravel|angular
84,472
<p>try</p> <pre><code>php -S localhost:8000 -t public/ </code></pre> <p>source : <a href="http://allbitsnbytes.com/posts/php-artisan-serve-not-working/" rel="noreferrer">http://allbitsnbytes.com/posts/php-artisan-serve-not-working/</a></p>
12,524,920
Set Text Color for textView Android
<p>In the string.xml file i use the following tag</p> <pre><code> &lt;string name="CodeColor" &gt;"#0000ff"&lt;/string&gt; </code></pre> <p>If I use</p> <pre><code> textview1.setTextColor(Color.RED); </code></pre> <p>it works, but when I use </p> <pre><code> textview1.setTextColor(TextViewStyles.this.getResources().getColor(R.string.CodeColor)); or textview1.setTextColor(R.string.CodeColor); </code></pre> <p>it doen't work. Any suggestions...</p> <p>Thanks in Advance</p>
12,524,948
8
0
null
2012-09-21 05:47:17.41 UTC
5
2018-07-24 12:36:20.407 UTC
null
null
null
null
928,712
null
1
9
android|colors|textview
86,739
<p>You need to create a set of styles in your xml (regularly in res/values/styles.xml)</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;color name="gray"&gt;#eaeaea&lt;/color&gt; &lt;color name="titlebackgroundcolor"&gt;#00abd7&lt;/color&gt; &lt;color name="titlecolor"&gt;#666666&lt;/color&gt; &lt;resources&gt; </code></pre> <p>In the layout files you can call to the colors or styles:</p> <pre><code>android:textColor="@color/titlecolor" </code></pre> <p>Checkout some examples:</p> <p><a href="http://developer.android.com/guide/topics/ui/themes.html">http://developer.android.com/guide/topics/ui/themes.html</a></p>
12,142,174
Run a python script with arguments
<p>I want to call a Python script from C, passing some arguments that are needed in the script.</p> <p>The script I want to use is mrsync, or <a href="http://sourceforge.net/projects/mrsync/">multicast remote sync</a>. I got this working from command line, by calling:</p> <pre><code>python mrsync.py -m /tmp/targets.list -s /tmp/sourcedata -t /tmp/targetdata </code></pre> <blockquote> <p>-m is the list containing the target ip-addresses. -s is the directory that contains the files to be synced. -t is the directory on the target machines where the files will be put.</p> </blockquote> <p>So far I managed to run a Python script without parameters, by using the following C program:</p> <pre><code>Py_Initialize(); FILE* file = fopen("/tmp/myfile.py", "r"); PyRun_SimpleFile(file, "/tmp/myfile.py"); Py_Finalize(); </code></pre> <p>This works fine. However, I can't find how I can pass these argument to the <code>PyRun_SimpleFile(..)</code> method.</p>
12,185,376
2
0
null
2012-08-27 12:40:56.677 UTC
13
2015-11-15 18:17:46.593 UTC
2012-09-03 18:50:57.613 UTC
null
458,741
null
960,585
null
1
24
python|c|eclipse
35,939
<p>Seems like you're looking for an answer using the python development APIs from Python.h. Here's an example for you that should work:</p> <pre><code>#My python script called mypy.py import sys if len(sys.argv) != 2: sys.exit("Not enough args") ca_one = str(sys.argv[1]) ca_two = str(sys.argv[2]) print "My command line args are " + ca_one + " and " + ca_two </code></pre> <p>And then the C code to pass these args:</p> <pre><code>//My code file #include &lt;stdio.h&gt; #include &lt;python2.7/Python.h&gt; void main() { FILE* file; int argc; char * argv[3]; argc = 3; argv[0] = "mypy.py"; argv[1] = "-m"; argv[2] = "/tmp/targets.list"; Py_SetProgramName(argv[0]); Py_Initialize(); PySys_SetArgv(argc, argv); file = fopen("mypy.py","r"); PyRun_SimpleFile(file, "mypy.py"); Py_Finalize(); return; } </code></pre> <p>If you can pass the arguments into your C function this task becomes even easier:</p> <pre><code>void main(int argc, char *argv[]) { FILE* file; Py_SetProgramName(argv[0]); Py_Initialize(); PySys_SetArgv(argc, argv); file = fopen("mypy.py","r"); PyRun_SimpleFile(file, "mypy.py"); Py_Finalize(); return; } </code></pre> <p>You can just pass those straight through. Now my solutions only used 2 command line args for the sake of time, but you can use the same concept for all 6 that you need to pass... and of course there's cleaner ways to capture the args on the python side too, but that's just the basic idea.</p> <p>Hope it helps!</p>
12,165,002
How to work with infinity arguments in a function (like PHP's isset())
<p>You know how PHP's <code>isset()</code> can accept multiple (no limit either) arguments?</p> <p>Like I can do:</p> <pre><code>isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc </code></pre> <p>How would I be able to do that in my own function? How would I be able to work with infinity arguments passed?</p> <p>How do they do it?</p>
12,165,045
4
0
null
2012-08-28 18:07:14.567 UTC
4
2014-11-04 13:44:55.127 UTC
2012-09-06 16:02:01.667 UTC
user849137
null
user849137
null
null
1
29
php|function|parameters|parameter-passing|param
14,633
<p><a href="http://php.net/manual/en/function.func-get-args.php"><code>func_get_args</code></a> will do what you want:</p> <pre><code>function infinite_parameters() { foreach (func_get_args() as $param) { echo "Param is $param" . PHP_EOL; } } </code></pre> <p>You can also use <code>func_get_arg</code> to get a specific parameter (it's zero-indexed):</p> <pre><code>function infinite_parameters() { echo func_get_arg(2); } </code></pre> <p>But be careful to check that you have that parameter:</p> <pre><code>function infinite_parameters() { if (func_num_args() &lt; 3) { throw new BadFunctionCallException("Not enough parameters!"); } } </code></pre> <p>You can even mix together <code>func_*_arg</code> and regular parameters:</p> <pre><code>function foo($param1, $param2) { echo $param1; // Works as normal echo func_get_arg(0); // Gets $param1 if (func_num_args() &gt;= 3) { echo func_get_arg(2); } } </code></pre> <p>But before using it, think about whether you <em>really</em> want to have indefinite parameters. Would an array not suffice?</p>
12,161,541
Work-around for failing "git svn clone" (requiring full history)
<p>I want to convert a Subversion repository sub-directory (denoted by <code>module</code> here) into a git repository with full history. There are many <code>svn copy</code> operations (Subversion people call them branches) in the history of my Subversion repository. The release policy has been that after each release or other branches created, the old URL is left unused and the new URL replaces the old one for containing the work.</p> <p>Optimally, by my reading, it seems like this should do the trick:</p> <pre><code>$ git svn clone --username=mysvnusername --authors-file=authors.txt \ --follow-parent \ http://svnserver/svn/src/branches/x/y/apps/module module </code></pre> <p>(where <code>branches/x/y/</code> depicts the newest branch). But I got an error, which looks something like this:</p> <pre><code>W: Ignoring error from SVN, path probably does not exist: (160013): Filesystem has no item: '/svn/src/!svn/bc/100/branches/x/y/apps/module' path not found W: Do not be alarmed at the above message git-svn is just searching aggressively for old history. </code></pre> <p>(<strong>Update:</strong> Adding option <code>--no-minimize-url</code> to the above does not remove the error message.)</p> <p>The directory <code>module</code> get created and populated, but the Subversion history past the newest <code>svn copy</code> commit is not imported (the git repository created ends up having just two commits when I expected hundreds).</p> <p>The question is, how to export the full Subversion history in the presence of this situation?</p> <h2>Possible Cause</h2> <ol> <li><p>Searching for the error message, I found this: <a href="https://stackoverflow.com/questions/1493052/git-svn-anonymous-checkout-fails-with-s">git-svn anonymous checkout fails with -s</a> which linked to this Subversion issue: <a href="http://subversion.tigris.org/issues/show_bug.cgi?id=3242" rel="noreferrer">http://subversion.tigris.org/issues/show_bug.cgi?id=3242</a></p> <p>What I understand by my reading, something in Subversion 1.5 changed about how the client accesses the repository. With newer Subversion, if there is no read access to some super directory of the URL path (true for me, <code>svn ls http://svnserver/svn</code> fails with <code>403 Forbidden</code>), then we fail with some Subversion operations.</p> </li> <li><p>Jeff Fairley in his answer points out that spaces in the Subversion URL might also cause this error message (confirmed by user Owen). Have a look at his solution to see how he solved the case if your <code>git svn clone</code> is failing for the same resson.</p> </li> <li><p>Dejay Clayton in his answer reveals that if the deepest subdirectory components in branch and tag svn urls are equally named (e.g. <code>.../tags/release/1.0.0</code> and <code>.../branches/release-candidates/1.0.0</code>) then this error could occur.</p> </li> </ol>
31,060,826
5
9
null
2012-08-28 14:29:24.697 UTC
11
2016-03-21 03:47:33.657 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
709,646
null
1
30
git|svn|git-svn
29,345
<p>I ran into this problem when I had identically-named subdirectories within branches or tags.</p> <p>For example, I had tags <code>candidates/1.0.0</code> and <code>releases/1.0.0</code>, and this caused the documented error because subdirectory <code>1.0.0</code> appears within both <code>candidates</code> and <code>releases</code>.</p> <p>Per <a href="http://git-scm.com/docs/git-svn" rel="noreferrer" title="git-svn docs">git-svn docs</a>:</p> <blockquote> <p>When using multiple --branches or --tags, git svn does not automatically handle name collisions (for example, if two branches from different paths have the same name, or if a branch and a tag have the same name). In these cases, use init to set up your Git repository then, before your first fetch, edit the $GIT_DIR/config file so that the branches and tags are associated with different name spaces.</p> </blockquote> <p>So while the following command failed due to similarly named <code>candidates</code> and <code>releases</code> tags:</p> <pre><code>git svn clone --authors-file=../authors.txt --no-metadata \ --trunk=/trunk --branches=/branches --tags=/candidates \ --tags=/releases --tags=/tags -r 100:HEAD \ --prefix=origin/ \ svn://example.com:3692/my-repos/path/to/project/ </code></pre> <p>the following sequence of commands did work:</p> <pre><code>git svn init --no-metadata \ --trunk=/trunk --branches=/branches --tags=/tags \ --prefix=origin/ \ 'svn://example.com:3692/my-repos/path/to/project/' git config --add svn-remote.svn.tags \ 'path/to/project/candidates/*:refs/remotes/origin/tags/Candidates/*' git config --add svn-remote.svn.tags \ 'path/to/project/releases/*:refs/remotes/origin/tags/Releases/*' git svn fetch --authors-file=../authors.txt -r100:HEAD </code></pre> <p>Note that this only worked because there were no other conflicts within <code>branches</code> and <code>tags</code>. If there were, I would have had to resolve them similarly.</p> <p>After successfully cloning the SVN repository, I then executed the following steps in order to: turn SVN tags into GIT tags; turn <code>trunk</code> into <code>master</code>; turn other references into branches; and relocate remote paths:</p> <pre><code># Make tags into true tags cp -Rf .git/refs/remotes/origin/tags/* .git/refs/tags/ rm -Rf .git/refs/remotes/origin/tags # Make other references into branches cp -Rf .git/refs/remotes/origin/* .git/refs/heads/ rm -Rf .git/refs/remotes/origin cp -Rf .git/refs/remotes/* .git/refs/heads/ # May be missing; that's okay rm -Rf .git/refs/remotes # Change 'trunk' to 'master' git checkout trunk git branch -d master git branch -m trunk master </code></pre>
12,265,421
How can I password-protect my /sidekiq route (i.e. require authentication for the Sidekiq::Web tool)?
<p>I am using sidekiq in my rails application. By Default, Sidekiq can be accessed by anybody by appending "/sidekiq" after the url. I want to password protect / authenticate only the sidekiq part. How can i do that?</p>
13,409,418
8
0
null
2012-09-04 14:16:46.963 UTC
9
2021-10-05 14:57:47.293 UTC
2015-05-07 15:49:07.707 UTC
null
190,135
null
1,337,996
null
1
61
ruby|ruby-on-rails-3|redis|rescue|sidekiq
24,335
<p>Put the following into your sidekiq initializer</p> <pre><code>require 'sidekiq' require 'sidekiq/web' Sidekiq::Web.use(Rack::Auth::Basic) do |user, password| # Protect against timing attacks: # - See https://codahale.com/a-lesson-in-timing-attacks/ # - See https://thisdata.com/blog/timing-attacks-against-string-comparison/ # - Use &amp; (do not use &amp;&amp;) so that it doesn't short circuit. # - Use digests to stop length information leaking Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(user), ::Digest::SHA256.hexdigest(ENV[&quot;SIDEKIQ_USER&quot;])) &amp; Rack::Utils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV[&quot;SIDEKIQ_PASSWORD&quot;])) end </code></pre> <p>And in the routes file:</p> <pre><code>mount Sidekiq::Web =&gt; '/sidekiq' </code></pre>
3,448,943
Best design pattern for "undo" feature
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/49755/design-pattern-for-undo-engine">Design Pattern for Undo Engine</a> </p> </blockquote> <p>In general, how do you deal with supporting an "undo" feature in your application? I have worked on web apps and desktop apps alike, and I have never really felt comfortable with any "undo" system I've made.</p>
3,448,959
3
1
null
2010-08-10 12:35:07.603 UTC
15
2010-08-10 12:45:13.477 UTC
2017-05-23 11:33:13.66 UTC
null
-1
null
402,169
null
1
23
design-patterns|undo
43,653
<p>I believe it should be <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="noreferrer">Command</a> design pattern.</p> <p>Here is <a href="http://www.codeproject.com/KB/architecture/UndoRedoPart2.aspx" rel="noreferrer">article</a> about multilevel Undo/Redo with Command pattern.</p> <p>EDIT: Here is <a href="http://www.codeproject.com/KB/architecture/UndoRedoPart3.aspx" rel="noreferrer">second</a> about multilevel Undo/Redo with Memento pattern.</p> <p>So probably it can be done with both.</p>
3,538,728
What is the difference between a background and foreground service?
<p>I am currently writing my first Android application and I keep running into references to background and foreground services. Since I intend on using a service in my application I was hoping to get a clarification between the two and how they are used.</p>
3,538,859
3
0
null
2010-08-21 20:01:49.447 UTC
11
2021-08-01 08:15:59.703 UTC
2021-08-01 08:15:59.703 UTC
null
4,057,416
null
420,377
null
1
58
android|android-service|background-service|foreground-service
68,907
<p>Perhaps this will answer your question:<br></p> <blockquote> <p>A started service can use the startForeground API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm.</p> </blockquote> <p>More info can be found <a href="http://developer.android.com/reference/android/app/Service.html" rel="noreferrer">here</a></p>
3,718,125
Notification alert similar to how stackoverflow functions
<p>How does stackoverflow create the slidedown effect to alert a user of a change ? </p>
3,718,155
4
0
null
2010-09-15 13:35:54.567 UTC
11
2014-09-16 01:35:10.87 UTC
2014-09-16 01:35:10.87 UTC
null
1,172,451
null
364,114
null
1
7
javascript|css
2,392
<p>Stack Overflow uses the <a href="http://jQuery.com" rel="noreferrer">jQuery framework</a>, which has a method to show a hidden element using a simple animation, something like:</p> <pre><code>$('#notification-bar').show('slow'); </code></pre> <p><a href="http://api.jquery.com/show/" rel="noreferrer">http://api.jquery.com/show/</a> (check out the demos).</p> <p>It is fixed to the top of the page using <code>position:fixed</code> in CSS:</p> <pre><code>#notification-bar { position:fixed; top: 0px; left: 0px; width: 100%; } </code></pre>
20,810,378
Should I mark a compiler-generated constructor as constexpr?
<p>Is there a difference between doing:</p> <pre><code>X() = default; </code></pre> <p>and</p> <pre><code>constexpr X() = default; </code></pre> <p>Default-constructing the class within constant expressions work fine, so is there a difference between these two examples? Should I use one over the other?</p>
20,810,439
1
5
null
2013-12-28 02:26:22.867 UTC
6
2013-12-28 02:47:00.7 UTC
null
null
null
null
1,935,708
null
1
33
c++|c++11
2,035
<p>Since the implicit constructor is actually <code>constexpr</code> in your case&hellip;</p> <blockquote> <p><code>[C++11: 12.1/6]:</code> <em>[..]</em> If that user-written default constructor would satisfy the requirements of a <code>constexpr</code> constructor (7.1.5), the implicitly-defined default constructor is <code>constexpr</code>. <em>[..]</em></p> <p><code>[C++11: 7.1.5/3]:</code> The definition of a <code>constexpr</code> function shall satisfy the following constraints:</p> <ul> <li>it shall not be virtual (10.3);</li> <li>its return type shall be a literal type;</li> <li>each of its parameter types shall be a literal type;</li> <li><strong>its function-body shall be</strong> <code>= delete</code>, <strong><code>= default</code></strong>, or a <em>compound-statement</em> that contains only <ul> <li>null statements,</li> <li><em>static_assert-declarations</em></li> <li><code>typedef</code> declarations and <em>alias-declarations</em> that do not define classes or enumerations,</li> <li><em>using-declarations</em>,</li> <li><em>using-directives</em>,</li> <li>and exactly one return statement;</li> </ul></li> <li>every constructor call and implicit conversion used in initializing the return value (6.6.3, 8.5) shall be one of those allowed in a constant expression (5.19).</li> </ul> </blockquote> <p>&hellip; the declarations are actually equivalent:</p> <blockquote> <p><code>[C++11: 8.4.2/2]:</code> An explicitly-defaulted function may be declared <code>constexpr</code> only if it would have been implicitly declared as <code>constexpr</code>, and may have an explicit <em>exception-specification</em> only if it is compatible (15.4) with the <em>exception-specification</em> on the implicit declaration. <strong>If a function is explicitly defaulted on its first declaration,</strong></p> <ul> <li><strong>it is implicitly considered to be <code>constexpr</code> if the implicit declaration would be</strong>,</li> <li>it is implicitly considered to have the same <em>exception-specification</em> as if it had been implicitly declared (15.4), and</li> <li>in the case of a copy constructor, move constructor, copy assignment operator, or move assignment operator, it shall have the same parameter type as if it had been implicitly declared.</li> </ul> </blockquote> <p>So do either &mdash; it doesn't matter.</p> <p>In the general case, if you definitely want a constructor to be <code>constexpr</code>, though, it may be wise to leave the keyword in so that you at least get a compiler error if it does not meet the criteria; leaving it out, you may get a non-<code>constexpr</code> constructor without realising it.</p>
22,406,478
remove blur effect on child element
<p>I have a <code>&lt;div&gt;</code> with an background-image with blur effect.</p> <pre><code>-webkit-filter: blur(3px); -moz-filter: blur(3px); -o-filter: blur(3px); -ms-filter: blur(3px); filter: blur(3px); </code></pre> <p>The only problem is that all the Child elements also get the blur effect. Is it possible to get rid of the blur effect on all the child elements??</p> <pre><code>&lt;div class="content"&gt; &lt;div class="opacity"&gt; &lt;div class="image"&gt; &lt;img src="images/zwemmen.png" alt="" /&gt; &lt;/div&gt; &lt;div class="info"&gt; a div wih all sort of information &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; .content{ float: left; width: 100%; background-image: url('images/zwemmen.png'); height: 501px; -webkit-filter: blur(3px); -moz-filter: blur(3px); -o-filter: blur(3px); -ms-filter: blur(3px); filter: blur(3px); } .opacity{ background-color: rgba(5,98,127,0.9); height:100%; overflow:hidden; } .info{ float: left; margin: 100px 0px 0px 30px; width: 410px; } </code></pre> <p><a href="http://jsfiddle.net/6V3ZW/" rel="noreferrer">http://jsfiddle.net/6V3ZW/</a></p>
22,406,621
3
4
null
2014-03-14 13:33:29.56 UTC
5
2021-08-19 06:57:07.1 UTC
null
null
null
null
3,305,290
null
1
24
html|css
58,902
<p>Create a div inside content &amp; give bg image &amp; blur effect to it. &amp; give it z-index less the the opacity div, something like this.</p> <pre><code>&lt;div class="content"&gt; &lt;div class="overlay"&gt;&lt;/div&gt; &lt;div class="opacity"&gt; &lt;div class="image"&gt; &lt;img src="images/zwemmen.png" alt="" /&gt; &lt;/div&gt; &lt;div class="info"&gt; a div wih all sort of information &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Use Css</p> <pre><code>.content{ float: left; width: 100%; } .content .overlay{ background-image: url('images/zwemmen.png'); height: 501px; -webkit-filter: blur(3px); -moz-filter: blur(3px); -o-filter: blur(3px); -ms-filter: blur(3px); filter: blur(3px); z-index:0; } .opacity{ background-color: rgba(5,98,127,0.9); height:100%; overflow:hidden; position:relative; z-index:10; } </code></pre>
22,204,836
Regex to find 3 out of 4 conditions
<p>My client has requested that passwords on their system must following a specific set of validation rules, and I'm having great difficulty coming up with a "nice" regular expression.</p> <p>The rules I have been given are...</p> <ul> <li>Minimum of 8 character</li> <li>Allow any character</li> <li>Must have at least one instance from <strong>three of the four</strong> following character types... <ol> <li>Upper case character</li> <li>Lower case character</li> <li>Numeric digit</li> <li>"Special Character"</li> </ol></li> </ul> <p>When I pressed more, "Special Characters" are literally everything else (including spaces).</p> <p>I can easily check for at least one instance for all four, using the following...</p> <pre><code>^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?\d)(?=.*?[^a-zA-Z0-9]).{8,}$ </code></pre> <p>The following works, but it's horrible and messy...</p> <pre><code>^((?=.*?[A-Z])(?=.*?[a-z])(?=.*?\d)|(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[^a-zA-Z0-9])|(?=.*?[A-Z])(?=.*?\d)(?=.*?[^a-zA-Z0-9])|(?=.*?[a-z])(?=.*?\d)(?=.*?[^a-zA-Z0-9])).{8,}$ </code></pre> <p>So you don't have to work it out yourself, the above is checking for <code>(1,2,3|1,2,4|1,3,4|2,3,4)</code> which are the 4 possible combinations of the 4 groups (where the number relates to the "types" in the set of rules).</p> <p><strong>Is there a "nicer", cleaner or easier way of doing this?</strong></p> <p>(Please note, this is going to be used in an <code>&lt;asp:RegularExpressionValidator&gt;</code> control in an ASP.NET website, so therefore needs to be a valid regex for both .NET and javascript.)</p>
22,205,697
4
7
null
2014-03-05 17:26:03.3 UTC
5
2019-02-28 14:21:24.847 UTC
2014-03-05 17:56:34.507 UTC
null
930,393
null
930,393
null
1
33
regex|passwords
12,581
<p>It's not much of a better solution, but you can reduce <code>[^a-zA-Z0-9]</code> to <code>[\W_]</code>, since a word character is all letters, digits and the underscore character. I don't think you can avoid the alternation when trying to do this in a single regex. I think you have pretty much have the best solution.</p> <p>One slight optimization is that <code>\d*[a-z]\w_*|\d*[A-Z]\w_*</code> ~> <code>\d*[a-zA-Z]\w_*</code>, so I could remove one of the alternation sets. If you only allowed 3 out of 4 this wouldn't work, but since <code>\d*[A-Z][a-z]\w_*</code> was implicitly allowed it works.</p> <pre><code>(?=.{8,})((?=.*\d)(?=.*[a-z])(?=.*[A-Z])|(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_])|(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])).* </code></pre> <p><strong>Extended version:</strong></p> <pre><code>(?=.{8,})( (?=.*\d)(?=.*[a-z])(?=.*[A-Z])| (?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_])| (?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]) ).* </code></pre> <p>Because of the fourth condition specified by the OP, this regular expression will match even unprintable characters such as new lines. If this is unacceptable then modify the set that contains <code>\W</code> to allow for more specific set of special characters.</p>
10,915,770
Localization with bean validation in JSF
<p>I made a MVC based website using JSF 2.0 and RichFaces 4. Every input text validation is been done using bean validation annotations. I am using Hibernate Validator as bean validation implementation.</p> <p>How can I display a localized message?</p> <p>If I use</p> <pre><code>@NotNull(message="&lt;h:outputText value=\"#{msg['Mymessage']}\" /&gt;") </code></pre> <p>then it literally displays <code>&lt;h:outputText value="#{msg['Mymessage']}" /&gt;</code> as message.</p> <p><img src="https://i.stack.imgur.com/quR5N.png" alt="enter image description here"></p> <p>How is this caused and how can I solve it?</p>
10,915,876
2
0
null
2012-06-06 14:00:56.55 UTC
9
2015-04-24 17:04:36.363 UTC
2012-06-06 14:11:12.043 UTC
null
157,882
null
1,346,690
null
1
10
java|jsf-2|localization|richfaces|bean-validation
8,235
<p>You should and can not put JSF tags in the message. Also, JSF's own resource bundle won't be used to resolve localized validation messages. JSR303 bean validation is a completely separate API unrelated to JSF. </p> <p>To internationalize JSR303 bean validation messages, you need to create a separate <code>ValidationMessages.properties</code> file in the classpath root which can be localized by <code>ValidationMessages_xx_XX.properties</code> files. </p> <p>E.g.</p> <pre class="lang-none prettyprint-override"><code>ERVNomView=Your message here </code></pre> <p>Which is then to be specified with <code>{key}</code> syntax.</p> <pre class="lang-java prettyprint-override"><code>@NotEmpty(message="{ERVNomView}") </code></pre> <h3>See also:</h3> <ul> <li><a href="http://jcp.org/aboutJava/communityprocess/edr/jsr303/index.html">Chapter 4.3.1.1 of the JSR303 specification</a></li> </ul>
11,088,292
No vimrc, gvimrc and .vim on mac
<p>There are no <code>.vimrc</code>, <code>.gvimrc</code> files and <code>.vim/</code> directory on my mac, and so I can't install any script. And when I create a folder <code>.vim/</code> and <code>.vim/plugin</code> and paste any script in there, it doesn't work. Sorry for my english.</p>
11,089,347
3
2
null
2012-06-18 17:51:26.343 UTC
9
2016-01-04 04:29:38.777 UTC
2012-06-18 19:33:45.51 UTC
null
630,160
null
1,464,374
null
1
13
macos|vim
28,142
<p>You <em>must</em> create those files and folder yourself:</p> <ol> <li><p>Open Terminal.app (found under <code>/Applications/Utilities/</code>).</p></li> <li><p>At the prompt, a <code>$</code>, type each of these lines followed by <code>&lt;Enter&gt;</code> (don't type the <code>$</code>):</p> <pre><code>$ touch .vimrc $ touch .gvimrc $ mkdir .vim $ open .vim </code></pre></li> <li><p>At this point, the <code>~/.vim</code> folder is open in a new Finder.app window.</p></li> </ol> <p>But I'd respectfully suggest you to get accustomed to the command-line <em>and</em> Vim's basics <em>before</em> rushing to install plugins. </p> <p><strong><em>EDIT</em></strong></p> <p>You didn't follow the instructions, no wonder the plugin doesn't work.</p> <p>You have to move <code>cvim.zip</code> into <code>~/.vim</code> and run the command <code>$ unzip cvim.zip</code> in the terminal. Read the instructions more carefully and don't let Safari expand archives automatically.</p> <p>Now that you have <code>~/.vim/c</code>, here is what you should do to go forward.</p> <p>Supposing your <code>~/.vim</code> is empty (beside your <code>~/.vim/c</code>), move <strong>the whole content</strong> of <code>~/.vim/c</code> into <code>~/.vim</code>. After this operation, your <code>~/.vim</code> folder should look like that:</p> <pre><code>+ ~/.vim + c &lt;-- your folder + c-support + (many folders and files) + doc + csupport.txt + ftplugin + c.vim + make.vim + plugin + c.vim + README.csupport </code></pre> <p>When you are done, delete <code>~/.vim/c</code> and start Vim. The plugin should be installed and working.</p> <p>If your <code>~/.vim</code> folder is <em>not</em> empty (say it already has a bunch of folders and files like <code>~/.vim/color</code>, <code>~/.vim/syntax</code>, whatever…) you'll have to move <em>manually</em> each subfolder/file from <code>~/.vim/c</code> to the right place in <code>~/.vim</code>.</p> <p><strong><em>ENDEDIT</em></strong></p>
10,889,909
DIV :after - add content after DIV
<p><a href="https://i.stack.imgur.com/ngSMr.png"><img src="https://i.stack.imgur.com/ngSMr.png" alt="Website layout"></a></p> <p>I'm designing a simple website and I have a question. I want after all <code>&lt;div&gt;</code> tags with <code>class="A"</code> to have a image separator on the bottom, right after the <code>&lt;div&gt;</code> (refer to image, section in red). I'm using the CSS operator <code>:after</code> to create the content:</p> <pre><code>.A:after { content: ""; display: block; background: url(separador.png) center center no-repeat; height: 29px; } </code></pre> <p>The problem is that the image separator is not displaying AFTER the <code>&lt;div&gt;</code>, but right after the CONTENT of the <code>&lt;div&gt;</code>, in my case I have a paragraph <code>&lt;p&gt;</code>. How do I code this so the image separator appears AFTER <code>&lt;div class="A"&gt;</code>, regardless of the height and content of div A?</p>
10,889,931
1
1
null
2012-06-04 23:54:13.42 UTC
1
2015-08-07 02:36:00.073 UTC
2015-08-07 02:36:00.073 UTC
null
875,941
null
470,664
null
1
32
css|html
138,155
<p>Position your <code>&lt;div&gt;</code> absolutely at the bottom and don't forget to give <code>div.A</code> a <code>position: relative</code> - <a href="http://jsfiddle.net/TTaMx/" rel="noreferrer">http://jsfiddle.net/TTaMx/</a></p> <pre><code> .A { position: relative; margin: 40px 0; height: 40px; width: 200px; background: #eee; } .A:after { content: " "; display: block; background: #c00; height: 29px; width: 100%; position: absolute; bottom: -29px; }​ </code></pre>
10,912,151
HttpClient get status code
<p>Using Apache HttpClient 4.1.3 and trying to get the status code from an <code>HttpGet</code>:</p> <pre><code>HttpClient client = new DefaultHttpClient(); HttpGet response = new HttpGet("http://www.example.com"); ResponseHandler&lt;String&gt; handler = new BasicResponseHandler(); String body = client.execute(response, handler); </code></pre> <p><strong>How do I extract the status code (202, 404, etc.) from the <code>body</code>?</strong> Or, if there's another way to do this in 4.1.3, what is it?</p> <p>Also, I assume a perfect/good HTTP response is an <code>HttpStatus.SC_ACCEPTED</code> but would like confirmation on that as well. Thanks in advance!</p>
10,912,260
3
0
null
2012-06-06 10:08:45.943 UTC
1
2015-08-31 21:44:05.693 UTC
2013-10-16 07:41:26.83 UTC
null
391,445
null
892,029
null
1
42
java|apache-httpclient-4.x
93,083
<p><strong>EDIT:</strong></p> <p>Try with:</p> <pre><code>HttpResponse httpResp = client.execute(response); int code = httpResp.getStatusLine().getStatusCode(); </code></pre> <p>The HttpStatus should be 200 ( <code>HttpStatus.SC_OK</code> )</p> <p>(I've read too fast the problem!)</p> <hr> <p>Try with:</p> <pre><code>GetMethod getMethod = new GetMethod("http://www.example.com"); int res = client.executeMethod(getMethod); </code></pre> <p>This should do the trick!</p>
11,455,667
Are there any offline HTML CSS JavaScript editors like JSFiddle, jsbin, codepen etc.?
<p>Are there any offline tools like JSFiddle.net to play with JavaScript, HTML, CSS <strong>without Internet</strong> in the fashion of JSFiddle.net?</p> <p><img src="https://i.stack.imgur.com/NI7nA.jpg" alt="enter image description here"></p>
11,455,779
6
11
null
2012-07-12 15:49:24.007 UTC
28
2022-02-08 05:55:38.337 UTC
2018-07-01 08:20:54.61 UTC
null
3,773,011
null
84,201
null
1
50
javascript|html|css
30,296
<p>You can install the excellent <a href="http://jsbin.com/#javascript,html,live" rel="noreferrer">JSBin</a> locally.</p> <p><a href="https://github.com/remy/jsbin/wiki/How-to-install-JS-Bin-in-your-own-environment" rel="noreferrer">https://github.com/remy/jsbin/wiki/How-to-install-JS-Bin-in-your-own-environment</a></p> <p><img src="https://i.stack.imgur.com/vxIEP.png" alt="enter image description here"></p>
13,216,554
What does wait() do on Unix?
<p>I was reading about the <code>wait()</code> function in a Unix systems book. The book contains a program which has <code>wait(NULL)</code> in it. I don't understand what that means. In other program there was</p> <pre><code>while(wait(NULL)&gt;0) </code></pre> <p>...which also made me scratch my head.</p> <p>Can anybody explain what the function above is doing?</p>
13,216,585
3
1
null
2012-11-04 06:24:42.333 UTC
5
2016-11-15 18:47:06.793 UTC
2012-11-04 06:27:26.803 UTC
null
23,897
null
1,725,372
null
1
7
c|unix|ubuntu|wait
53,004
<p>man <a href="http://linux.die.net/man/2/wait">wait(2)</a></p> <blockquote> <p>All of these system calls are used to wait for state changes in a child of the calling process, and obtain information about the child whose state has changed. A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal</p> </blockquote> <p>So <code>wait()</code> allows a process to wait until one of its child processes change its state, exists for example. If <code>waitpid()</code> is called with a process id it waits for that <em>specific</em> child process to change its state, if a <code>pid</code> is not specified, then it's equivalent to calling <code>wait()</code> and it waits for <em>any</em> child process to change its state.</p> <p>The <code>wait()</code> function returns child pid on success, so when it's is called in a loop like this:</p> <pre><code>while(wait(NULL)&gt;0) </code></pre> <p>It means wait until all child processes exit (or change state) and no more child processes are unwaited-for (or until an error occurs)</p>
12,844,137
Spring, working with @Configuration and @Bean annotations
<p>I have a code:</p> <pre><code>@Configuration public class BeanSample { @Bean(destroyMethod = "stop") public SomeBean someBean() throws Exception { return new SomeBean("somebean name1"); } class SomeBean { String name; public SomeBean(String name) { this.name = name; } public void stop() { System.out.println("stop"); } } public static void main(String[] args) throws Exception { BeanSample beanSample = new BeanSample(); SomeBean someBean1 = beanSample.someBean(); ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext( new String[] {"appContext.xml"}); SomeBean someBean2 = (SomeBean) appContext.getBean("someBean"); if (someBean1 == someBean2) System.out.println("OK"); } } </code></pre> <p>I'm expecting, once I start app, the BeanSample.getSomeBean() then SomeBean is started to be available by 'someBean'. </p> <p>Bu now I have an error: <strong>No bean named 'someBean' is defined</strong></p> <p>Actually, I dot not understand which app-context I should use to pick my beans up?</p> <p><strong>About @Configuration</strong>:</p> <p>Any reasons, why I should use @Configuration annotation here? (with this one, my IDE highlights my classes as it were Spring-related then, so it should make sense )</p> <p>-- <strong>OK: after I got an answer my code looks like this:</strong></p> <pre><code> public static void main(String[] args) throws Exception { AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(BeanSample.class); SomeBean someBean2 = (SomeBean) appContext.getBean("someBean"); if (someBean2 != null) System.out.println("OK"); } </code></pre>
12,844,221
3
0
null
2012-10-11 16:20:26.42 UTC
4
2012-10-11 17:46:41.65 UTC
2012-10-11 17:46:41.65 UTC
null
369,759
null
369,759
null
1
9
java|spring|annotations
46,478
<p>First, if you use the Java config, you have to instantiate your context like this:</p> <pre><code>new AnnotationConfigApplicationContext(BeanSample.class) </code></pre> <p>Second, the <code>@Configuration</code> annotation doesn't make a bean out of the class that is annotated. Only the <code>@Bean</code> methods are used to create beans.</p> <p>If you want to have a <code>BeanSample</code> bean too, you have to create another <code>@Bean</code> method that creates one. But then again, why would you want that? I think the a <code>@Configuration</code> class should only be used as the configuration container and not for anything else.</p> <p>Third, the default bean names for <code>@Bean</code> do not follow the conventions of property getters. The method names are used directly, meaning in your example, the bean would be named <code>getSomeBean</code> and not <code>someBean</code>. Change the method to this:</p> <pre><code>@Bean(destroyMethod = "stop") public SomeBean someBean() throws Exception { return new SomeBean("somebean name1"); } </code></pre> <p>Finally, the <code>@Configuration</code> class should not be instantiated. Its methods only serve the purpose of creating the beans. Spring will then handle their lifecycle, inject properties and so on. In contrast, if you instantiate the class and call the methods directly, the returned objects will be just normal objects that don't have anything to do with Spring.</p>
12,782,373
html select option SELECTED
<p>I have in my php</p> <pre><code>$sel = " &lt;option&gt; one &lt;/option&gt; &lt;option&gt; two &lt;/option&gt; &lt;option&gt; thre &lt;/option&gt; &lt;option&gt; four &lt;/option&gt; "; </code></pre> <p>let say I have an inline URL = <code>site.php?sel=one</code></p> <p>if I didn't saved those options in a variable, I can do it this way to make one of the option be SELECTED where value is equal to <code>$_GET[sel]</code></p> <pre><code>&lt;option &lt;?php if($_GET[sel] == 'one') echo"selected"; ?&gt; &gt; one &lt;/option&gt; &lt;option &lt;?php if($_GET[sel] == 'two') echo"selected"; ?&gt; &gt; two &lt;/option&gt; &lt;option &lt;?php if($_GET[sel] == 'three') echo"selected"; ?&gt; &gt; three &lt;/option&gt; &lt;option &lt;?php if($_GET[sel] == 'four') echo"selected"; ?&gt; &gt; four &lt;/option&gt; </code></pre> <p>but the problem is, I need to save those options in a variable because I have a lot of options and I need to call that variable many times.</p> <p>Is there a way to make that option be selected where <code>value = $_GET[sel]</code> ?</p>
12,782,476
6
3
null
2012-10-08 13:04:57.93 UTC
7
2022-08-31 16:04:36.16 UTC
2022-08-31 16:04:36.16 UTC
null
1,007,220
null
1,557,430
null
1
13
php|html|html-select
169,396
<p>Just use the array of options, to see, which option is currently selected.</p> <pre><code>$options = array( 'one', 'two', 'three' ); $output = ''; for( $i=0; $i&lt;count($options); $i++ ) { $output .= '&lt;option ' . ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '&gt;' . $options[$i] . '&lt;/option&gt;'; } </code></pre> <p><sub>Sidenote: I would define a value to be some kind of id for each element, else you may run into problems, when two options have the same string representation.</sub></p>
13,005,112
How to activate combobox on first click (Datagridview)
<p>In winforms, you need to click the combobox twice to properly activate it - the first time to focus it, the second time to actually get the dropdown list.</p> <p>How do I change this behavior so that it activates on the very first click?</p> <p>This is for DATAGRIDVIEW combobox.</p>
26,530,645
6
3
null
2012-10-22 04:53:52.467 UTC
10
2020-06-24 10:16:04.417 UTC
2018-08-20 04:50:46.443 UTC
null
647,612
null
1,455,529
null
1
43
c#|.net|winforms|datagridview|combobox
44,588
<p>I realize this is an old question, but I figured I would give my solution to anyone out there that may need to be able to do this.</p> <p>While I couldn't find any answers to do exactly this... I did find an <a href="https://stackoverflow.com/a/242760/4000801">answer</a> to a different question that helped me.</p> <p>This is my solution: </p> <pre><code>private void datagridview_CellEnter(object sender, DataGridViewCellEventArgs e) { bool validClick = (e.RowIndex != -1 &amp;&amp; e.ColumnIndex != -1); //Make sure the clicked row/column is valid. var datagridview = sender as DataGridView; // Check to make sure the cell clicked is the cell containing the combobox if(datagridview.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn &amp;&amp; validClick) { datagridview.BeginEdit(true); ((ComboBox)datagridview.EditingControl).DroppedDown = true; } } private void datagridview_CurrentCellDirtyStateChanged(object sender, EventArgs e) { datagridview.CommitEdit(DataGridViewDataErrorContexts.Commit); } </code></pre> <p><strong>The above code must be tied into the CellEnter event of the datagridview.</strong></p> <p>I hope this helps!</p> <p><strong>edit:</strong> Added a column index check to prevent crashing when the entire row is selected.</p> <p>Thanks, <a href="https://stackoverflow.com/users/1906911/up-all-night">Up All Night</a> for the above edit</p> <p><strong>edit2:</strong> Code is now to be tied to the CellEnter rather than the CellClick event.</p> <p>Thanks, <a href="https://stackoverflow.com/users/2281790/haralddutch">HaraldDutch</a> for the above edit</p> <p><strong>edit3:</strong> Any changes will committed immediately, this will save you from clicking in another cell in order to update the current combobox cell.</p>
12,740,967
How do you add pseudo classes to elements using jQuery?
<p>In CSS, when you hover your mouse over an element, you can specify views for it using the :hover pseudo class:</p> <pre><code>.element_class_name:hover { /* stuff here */ } </code></pre> <p>How can you use jquery to add or "turn on" this pseudo class? Typically in jQuery if you want to add a class you would do:</p> <pre><code>$(this).addClass("class_name"); </code></pre> <p>I have tried "hover" but this literally adds a class named "hover" to the element.</p> <p>If anyone knows what to write, please let me know! Thanks!</p>
12,741,013
4
3
null
2012-10-05 06:47:02.123 UTC
8
2020-04-21 17:01:45.17 UTC
2012-10-05 06:50:26.537 UTC
null
106,224
null
722,890
null
1
47
jquery|css|pseudo-class
68,891
<p>You can't force a certain pseudo-class to apply using jQuery. That's not how pseudo-classes (especially dynamic pseudo-classes) work, since they're designed to select based on information that cannot be expressed via the DOM (<a href="http://www.w3.org/TR/selectors/#pseudo-classes">spec</a>).</p> <p>You have to specify another class to use, then add that class using jQuery instead. Something like this:</p> <pre><code>.element_class_name:hover, .element_class_name.jqhover { /* stuff here */ } $(this).addClass("jqhover"); </code></pre> <p>Alternatively you could hunt for the <code>.element_class_name:hover</code> rule and add that class using jQuery itself, without hardcoding it into your stylesheet. It's the same principle, though.</p>
12,695,474
How to access environment variables in an Expect script?
<p>I would like to access the PATH environment variable inside an expect script.</p> <p>How can I achieve that ?</p> <p>My actual script is :</p> <pre><code>#!/usr/bin/expect set timeout 300 send "echo $PATH\r" </code></pre> <p>and its ouput is :</p> <pre><code>can't read "PATH": no such variable while executing "send "echo $PATH\r"" </code></pre>
12,699,077
4
0
null
2012-10-02 17:45:45.797 UTC
5
2022-08-18 22:17:01.427 UTC
null
null
null
null
413,301
null
1
47
environment-variables|expect
32,675
<p>Expect is an extension of <a href="http://www.tcl.tk">Tcl</a>. Tcl access enviroment variables via the global <a href="http://tcl.tk/man/tcl8.5/TclCmd/tclvars.htm#M4"><code>env</code> array</a>:</p> <pre><code>send_user "$env(PATH)\n" </code></pre>
13,112,280
Mercurial (hg) equivalent of git reset (--mixed or --soft)
<p>what would be an equivalent mercurial command (or workflow) for </p> <pre><code>git reset --mixed HEAD^ </code></pre> <p>or </p> <pre><code>git reset --soft HEAD^ </code></pre> <p>i.e. I want leave the working tree intact but get the repository back into the state it was before the last commit. Surprisingly I did not find anything useful on stackoverflow or with google.</p> <p>Note that I cannot use </p> <pre><code>hg rollback </code></pre> <p>as I've done some history rewriting using HistEdit after the last commit.</p> <p><strong>Added to clarify:</strong> After some rebasing and history editing I had ended up with A&lt;--B&lt;--C. Then I used HistEdit to squash B and C together, obtaining A&lt;--C'. Now I want to split up the commit C' (I committed the wrong files in B). I figured the easiest way to do this was to get the repository back to state A (which technically never existed in the repository because of all the rebasing and history editing before hand) and the working tree to the state of C' and then doing two commits.</p>
19,064,016
2
1
null
2012-10-28 19:36:12.74 UTC
17
2020-10-12 17:14:16.927 UTC
2012-10-28 21:27:01.463 UTC
null
371,137
null
371,137
null
1
54
mercurial
20,556
<p>The right way to replicate <code>git reset --soft HEAD^</code> (undo the current commit but keep changes in the working copy) is:</p> <pre><code>hg strip --keep -r . </code></pre> <p><code>-1</code> will only work if the commit you want to strip is the very last commit that entered the repository. <code>.</code> refers to the currently checked out commit, which is the closest equivalent Mercurial has to Git's <code>HEAD</code>.</p> <p>Note that if <code>.</code> has descendants, those will get stripped away too. If you'd like to keep the commit around, then once you have the commit ID, you can instead:</p> <pre><code>hg update .^ hg revert --all -r &lt;commit id&gt; </code></pre> <p>This will update to the commit's parent and then replace the files in the working copy with the versions at that commit.</p>
12,973,777
How to run a shell script at startup
<p>On an <a href="https://en.wikipedia.org/wiki/Amazon_S3" rel="noreferrer">Amazon S3</a> Linux instance, I have two scripts called <code>start_my_app</code> and <code>stop_my_app</code> which start and stop <em><a href="https://www.npmjs.com/package/forever" rel="noreferrer">forever</a></em> (which in turn runs my Node.js application). I use these scripts to manually start and stop my Node.js application. So far so good.</p> <p>My problem: I also want to set it up such that <code>start_my_app</code> is run whenever the system boots up. I know that I need to add a file inside <code>init.d</code> and I know how to symlink it to the proper directory within <code>rc.d</code>, but I can't figure out what actually needs to go inside the file that I place in <code>init.d</code>. I'm thinking it should be just one line, like, <code>start_my_app</code>, but that hasn't been working for me.</p>
12,973,826
22
3
null
2012-10-19 11:56:39.327 UTC
188
2022-07-22 09:31:13.857 UTC
2019-12-30 23:46:08.357 UTC
null
63,550
null
1,113,023
null
1
463
linux|node.js|init.d|forever
1,302,067
<p>The file you put in <code>/etc/init.d/</code> have to be set to executable with:</p> <pre><code>chmod +x /etc/init.d/start_my_app </code></pre> <p>As pointed out by @meetamit, if it still does not run you might have to create a symbolic link to the file in <code>/etc/rc.d/</code></p> <pre><code>ln -s /etc/init.d/start_my_app /etc/rc.d/ </code></pre> <p>Please note that on the latest versions of Debian, this will not work as your script will have to be LSB compliant (provide at least the following actions: start, stop, restart, force-reload, and status): <a href="https://wiki.debian.org/LSBInitScripts" rel="nofollow noreferrer">https://wiki.debian.org/LSBInitScripts</a></p> <p>As a note, you should always use the absolute path to files in your scripts instead of the relative one, it may solve unexpected issues:</p> <pre><code>/var/myscripts/start_my_app </code></pre> <p>Finally, make sure that you included the shebang on top of the file:</p> <pre><code>#!/bin/sh </code></pre>
16,619,274
Cuda gridDim and blockDim
<p>I get what <code>blockDim</code> is, but I have a problem with <code>gridDim. Blockdim</code> gives the size of the block, but what is <code>gridDim</code>? On the Internet it says <code>gridDim.x</code> gives the number of blocks in the x coordinate.</p> <p>How can I know what <code>blockDim.x * gridDim.x</code> gives?</p> <p>How can I know that how many <code>gridDim.x</code> values are there in the x line?</p> <p>For example, consider the code below:</p> <pre><code>int tid = threadIdx.x + blockIdx.x * blockDim.x; double temp = a[tid]; tid += blockDim.x * gridDim.x; while (tid &lt; count) { if (a[tid] &gt; temp) { temp = a[tid]; } tid += blockDim.x * gridDim.x; } </code></pre> <p>I know that <code>tid</code> starts with 0. The code then has <code>tid+=blockDim.x * gridDim.x</code>. What is <code>tid</code> now after this operation?</p>
16,619,633
4
0
null
2013-05-17 23:38:37.21 UTC
33
2022-05-18 17:56:13.47 UTC
2019-02-27 07:43:55.367 UTC
null
8,464,442
null
2,354,356
null
1
59
cuda
90,756
<ul> <li><code>blockDim.x,y,z</code> gives the number of threads in a block, in the particular direction</li> <li><code>gridDim.x,y,z</code> gives the number of blocks in a grid, in the particular direction</li> <li><code>blockDim.x * gridDim.x</code> gives the number of threads in a grid (in the x direction, in this case)</li> </ul> <p>block and grid variables can be 1, 2, or 3 dimensional. It's common practice when handling 1-D data to only create 1-D blocks and grids.</p> <p>In the CUDA documentation, these variables are defined <a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#built-in-variables" rel="nofollow noreferrer">here</a></p> <p>In particular, when the total threads in the x-dimension (<code>gridDim.x*blockDim.x</code>) is <em>less than</em> the size of the array I wish to process, then it's common practice to create a loop and have the grid of threads move through the entire array. In this case, after processing one loop iteration, each thread must then move to the next unprocessed location, which is given by <code>tid+=blockDim.x*gridDim.x;</code> In effect, the entire grid of threads is jumping through the 1-D array of data, a grid-width at a time. This topic, sometimes called a &quot;grid-striding loop&quot;, is further discussed in this <a href="https://devblogs.nvidia.com/parallelforall/cuda-pro-tip-write-flexible-kernels-grid-stride-loops/" rel="nofollow noreferrer">blog article</a>.</p> <p>You might want to consider taking an <a href="https://www.olcf.ornl.gov/cuda-training-series/" rel="nofollow noreferrer">introductory CUDA webinars</a> For example, the first 4 units. It would be 4 hours well spent, if you want to understand these concepts better.</p>
25,647,454
How to pass parameters using ui-sref in ui-router to the controller
<p>I need to pass and receive two parameters to the state I want to transit to using <code>ui-sref</code> of ui-router.</p> <p>Something like using the link below for transitioning the state to <code>home</code> with <code>foo</code> and <code>bar</code> parameters:</p> <pre><code>&lt;a ui-sref=&quot;home({foo: 'fooVal', bar: 'barVal'})&quot;&gt;Go to home state with foo and bar parameters &lt;/a&gt; </code></pre> <p>Receiving <code>foo</code> and <code>bar</code> values in a controller:</p> <pre><code>app.controller('SomeController', function($scope, $stateParam) { //.. var foo = $stateParam.foo; //getting fooVal var bar = $stateParam.bar; //getting barVal //.. }); </code></pre> <p>I get <code>undefined</code> for <code>$stateParam</code> in the controller.</p> <p>Could somebody help me understand how to get it done?</p> <p><strong>Edit:</strong></p> <pre><code>.state('home', { url: '/', views: { '': { templateUrl: 'home.html', controller: 'MainRootCtrl' }, 'A@home': { templateUrl: 'a.html', controller: 'MainCtrl' }, 'B@home': { templateUrl: 'b.html', controller: 'SomeController' } } }); </code></pre>
25,647,714
3
4
null
2014-09-03 14:50:39.583 UTC
125
2022-06-03 14:45:03.45 UTC
2022-06-03 14:45:03.45 UTC
null
6,291,976
null
411,449
null
1
378
javascript|html|angularjs|angular-ui-router|angular-ui
385,154
<p>I've created an <a href="http://plnkr.co/edit/r2JhV4PcYpKJdBCwHIWS?p=preview" rel="noreferrer">example</a> to show how to. Updated <code>state</code> definition would be:</p> <pre><code> $stateProvider .state('home', { url: '/:foo?bar', views: { '': { templateUrl: 'tpl.home.html', controller: 'MainRootCtrl' }, ... } </code></pre> <p>And this would be the controller:</p> <pre><code>.controller('MainRootCtrl', function($scope, $state, $stateParams) { //.. var foo = $stateParams.foo; //getting fooVal var bar = $stateParams.bar; //getting barVal //.. $scope.state = $state.current $scope.params = $stateParams; }) </code></pre> <p>What we can see is that the state home now has url defined as:</p> <pre><code>url: '/:foo?bar', </code></pre> <p>which means, that the params in url are expected as </p> <pre><code>/fooVal?bar=barValue </code></pre> <p>These two links will correctly pass arguments into the controller:</p> <pre><code>&lt;a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})"&gt; &lt;a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})"&gt; </code></pre> <p>Also, the controller does consume <code>$stateParams</code> instead of <code>$stateParam</code>.</p> <p>Link to doc:</p> <ul> <li><a href="https://github.com/angular-ui/ui-router/wiki/URL-Routing#url-parameters" rel="noreferrer">URL Parameters</a></li> </ul> <p>You can check it <a href="http://plnkr.co/edit/r2JhV4PcYpKJdBCwHIWS?p=preview" rel="noreferrer">here</a></p> <h3><code>params : {}</code></h3> <p>There is also <em>new</em>, more granular setting <em><code>params : {}</code></em>. As we've already seen, we can declare parameters as part of <strong><code>url</code></strong>. But with <code>params : {}</code> configuration - we can extend this definition or even introduce paramters which are not part of the url:</p> <pre><code>.state('other', { url: '/other/:foo?bar', params: { // here we define default value for foo // we also set squash to false, to force injecting // even the default value into url foo: { value: 'defaultValue', squash: false, }, // this parameter is now array // we can pass more items, and expect them as [] bar : { array : true, }, // this param is not part of url // it could be passed with $state.go or ui-sref hiddenParam: 'YES', }, ... </code></pre> <p>Settings available for params are described in the documentation of the <a href="http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider" rel="noreferrer">$stateProvider</a></p> <p>Below is just an extract</p> <ul> <li><strong>value - {object|function=}</strong>: specifies the default value for this parameter. This implicitly sets this parameter as optional...</li> <li><strong>array - {boolean=}:</strong> (default: false) If true, the param value will be treated as an array of values. </li> <li><strong>squash - {bool|string=}:</strong> squash configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value.</li> </ul> <p>We can call these params this way:</p> <pre><code>// hidden param cannot be passed via url &lt;a href="#/other/fooVal?bar=1&amp;amp;bar=2"&gt; // default foo is skipped &lt;a ui-sref="other({bar: [4,5]})"&gt; </code></pre> <p>Check it in action <a href="http://plnkr.co/edit/r2JhV4PcYpKJdBCwHIWS?p=preview" rel="noreferrer">here</a></p>
25,763,896
Running app gives 2 app icons in Android Studio
<p>I am running an app in Android Studio and it gives 2 app icons in Androi Studio.</p> <p>Also, I have moved from Eclipse to Android Studio and now I'm having trouble with how to make the color of logcat same as in Eclipse.</p> <p>My question is that there are 2 app icons when I run the app, and when I uninstall it, 2 of them have been removed. Is that normal in Android Studio? I have found that Android Studio can copy keys from Eclipse.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.mytrack.ph" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" /&gt; &lt;uses-feature android:glEsVersion="0x00020000" android:required="true"/&gt; &lt;uses-permission android:name="android.permission.READ_PHONE_STATE" /&gt; &lt;uses-permission android:name="android.permission.INTERNET"/&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt; &lt;uses-permission android:name="android.permission.VIBRATE"/&gt; &lt;uses-permission android:name="android.permission.WAKE_LOCK"/&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/&gt; &lt;!-- Google Map v.2 permissions --&gt; &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/&gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt; &lt;!-- GCM permissions --&gt; &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt; &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /&gt; &lt;permission android:name="com.example.gcm.permission.C2D_MESSAGE" android:protectionLevel="signature" /&gt; &lt;uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" /&gt; &lt;!-- Writing Persmission --&gt; &lt;uses-permission android:name="android.permission.WRITE_USER_DICTIONARY" /&gt; &lt;uses-permission android:name="android.permission.WRITE_PROFILE" /&gt; &lt;uses-permission android:name="android.permission.READ_CONTACTS"/&gt; &lt;uses-permission android:name="android.permission.READ_PROFILE"/&gt; &lt;uses-permission android:name="android.permission.READ_CONTACT"/&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" &gt; &lt;activity android:name="com.mytrack.ph.SplashActivity" android:label="@string/app_name" android:noHistory="true" android:screenOrientation="portrait" android:theme="@style/splashScreenTheme" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name="com.mytrack.ph.LoginActivity" android:label="@string/app_name" android:screenOrientation="portrait" &gt; &lt;/activity&gt; &lt;meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /&gt; &lt;meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="@string/google_map_api_key"/&gt; &lt;activity android:name="com.facebook.LoginActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:label="@string/app_name" /&gt; &lt;meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/&gt; &lt;service android:name="com.my.track.service.MyTrackService"&gt;&lt;/service&gt; &lt;receiver android:name="com.my.track.service.MyTrackGcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" &gt; &lt;intent-filter&gt; &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt; &lt;category android:name="com.my.track.service" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;service android:name="com.my.track.service.MyTrackGcmIntentService" /&gt; &lt;activity android:name="NavigationMenuActivity" android:configChanges="orientation|keyboardHidden" android:screenOrientation="portrait" android:launchMode="singleTop" android:permission="com.google.android.c2dm.permission.SEND" &gt; &gt;&lt;/activity&gt; &lt;receiver android:name="com.my.track.results.ConnectionChangeReceiver" &gt; &lt;intent-filter&gt; &lt;action android:name="android.net.conn.CONNECTIVITY_CHANGE"/&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>I though this is normal in android studio. Running an app gives 2 launcher icons. PS:</p> <p>my <code>AndroidManifest.xml</code> is inside <em>main</em> folder and I used eclipse to export to gradle build.</p> <p>Im using Android Studio 0.8.6 thanks.</p>
25,778,663
8
7
null
2014-09-10 11:11:54.997 UTC
7
2022-08-03 07:32:08.897 UTC
2018-12-08 06:52:01.87 UTC
null
10,589,041
null
3,974,048
null
1
49
android|android-studio
30,472
<p>I got it! yes at last , i have to study gradles and stuff.</p> <p>Actually I have 2 android projects inside the Project, one is a library and the other one is the main app.</p> <p>I found out that when i imported those projects Android Studio (I exported the lib to gradle build from eclipse) doesn't care if that is a lib project or a main project. (Correct me if im wrong ). </p> <p>so the only thing to make it work is to remove the <code>intent-filter</code> of that lib-android-project.</p> <p>EDIT: @all solved it ! thanks to everyone, I never knew there was another AndroidManifest.xml , i thought eclipse removed it. and i thought Exporting it to gradle will remove it because it is checked as a library.</p> <p>thanks for all your help.</p>
25,444,328
What does the smiley face ":)" mean in CSS?
<p>I spotted this CSS code in a project:</p> <pre><code>html, body { :)width: 640px;} </code></pre> <p>I have been around with CSS for a long time now but I never saw this ":)" code before. Does it mean anything or is it just a typo?</p>
25,444,600
2
8
null
2014-08-22 09:56:28.953 UTC
62
2022-09-22 19:04:02.91 UTC
2022-09-22 19:04:02.91 UTC
null
2,756,409
null
284,577
null
1
322
css
35,002
<p>From an <a href="http://www.javascriptkit.com/dhtmltutors/csshacks3.shtml" rel="noreferrer">article at javascriptkit.com</a>, that's applied for <strong>IE 7</strong> and earlier versions:</p> <blockquote> <p>if you add a non-alphanumeric character such as an asterisk (<code>*</code>) immediately before a property name, the property will be applied in IE and not in other browsers.</p> </blockquote> <p>Also there's a hack for &lt;= <strong>IE 8</strong>:</p> <pre><code>div { color: blue; /* All browsers */ color: purple\9; /* IE8 and earlier */ *color: pink; /* IE7 and earlier */ } </code></pre> <p>However that's not a good idea, they don't validate. You always feel free to work with <a href="http://msdn.microsoft.com/en-us/library/ms537512.aspx" rel="noreferrer"><strong>Conditional comments</strong></a> for targeting specific versions of <strong>IE</strong>:</p> <pre><code>&lt;!--[if lte IE 8]&gt;&lt;link rel="stylesheet" href="ie-8.css"&gt;&lt;![endif]--&gt; &lt;!--[if lte IE 7]&gt;&lt;link rel="stylesheet" href="ie-7.css"&gt;&lt;![endif]--&gt; &lt;!--[if lte IE 6]&gt;&lt;link rel="stylesheet" href="ie-6.css"&gt;&lt;![endif]--&gt; </code></pre> <p>But for those wanna see the hack in real, please open up <a href="http://forooma.com/test.html" rel="noreferrer">this page</a> in the latest version of IE you have. Then go to developer mode by doing a <kbd>F12</kbd>. In Emulation section (<kbd>ctrl</kbd>+<kbd>8</kbd>) change document mode to <code>7</code> and see what happens.</p> <p><img src="https://i.stack.imgur.com/7UQqh.jpg" alt="enter image description here"></p> <p><em>The property used in the page is <code>:)font-size: 50px;</code>.</em></p>
4,561,681
How to select row in grid AFTER load grid?
<p>Model.getSelectionModel().selectRow(0) not work ...</p>
4,561,965
2
2
null
2010-12-30 10:01:14.553 UTC
1
2010-12-30 13:13:42.147 UTC
null
null
null
null
418,507
null
1
6
extjs
41,381
<pre><code>this.store = new Ext.data.Store({ ... listeners: { load: function() { this.grid.getSelectionModel().selectFirstRow(); }, scope: this } }); this.grid = new Ext.grid.GridPanel({ ... store: this.store }); </code></pre> <p>Something like this should work, assuming this.store and this.grid exist, I'm sure you can adapt it.</p>
41,652,112
Why would C have "fake arrays"?
<p>I'm reading <a href="http://web.mit.edu/~simsong/www/ugh.pdf" rel="noreferrer"><em>The Unix haters handbook</em></a> and in chapter 9 there's something I don't really understand:</p> <blockquote> <p>C doesn’t really have arrays either. It has something that looks like an array but is really a pointer to a memory location.</p> </blockquote> <p>I can't really imagine any way to store an array in memory other than using pointers to index memory locations. How C implements "fake" arrays, anyways? Is there any veracity on this claim?</p>
41,652,311
5
11
null
2017-01-14 16:11:12.373 UTC
8
2017-01-16 05:52:07.857 UTC
2017-01-15 21:14:17.387 UTC
null
792,066
null
7,391,374
null
1
30
c|arrays
2,163
<p>I think the author’s point is that C arrays are really just a thin veneer on pointer arithmetic. The subscript operator is defined simply as <code>a[b] == *(a + b)</code>, so you can easily say <code>5[a]</code> instead of <code>a[5]</code> and do other horrible things like access the array past the last index.</p> <p>Comparing to that, a “true array” would be one that knows its own size, doesn’t let you do pointer arithmetic, access past the last index without an error, or access its contents using a different item type. In other words, a “true array” is a tight abstraction that doesn’t tie you to a single representation – it could be a linked list instead, for example.</p> <p>PS. To spare myself some trouble: I don’t really have an opinion on this, I’m just explaining the quote from the book.</p>
9,815,901
Display view above status bar?
<p>I recently saw an image of an app that was capable of displaying a view above the status bar and was also able to cover it with a view.</p> <p>I know you can get a view right below the status bar from a view with align parent top. But how would you get a view on top of the status bar??</p> <p><a href="http://tombarrasso.com/wordpress/wp-content/uploads/2012/02/ChargeBarBanner3-225x225.png">Example</a></p>
13,653,075
4
3
null
2012-03-22 03:09:40.793 UTC
10
2017-03-10 10:38:29.737 UTC
null
null
null
null
1,190,019
null
1
10
android|eclipse|view|statusbar
19,561
<p>The answer by @Sadeshkumar is incorrect for ICS and above (perhaps GB as well).</p> <p>A view created with <code>TYPE_SYSTEM_ALERT</code> and <code>FLAG_LAYOUT_IN_SCREEN</code> is covered by the <code>StatusBar</code>.</p> <p>To get an overlay on top of the <code>StatusBar</code>, you need to use <code>TYPE_SYSTEM_OVERLAY</code> instead of <code>TYPE_SYSTEM_ALERT</code>. </p> <p>The problem being then, how to get clicks/touches?</p>
9,835,863
Log user activities in ROR
<p>I have an application where there are two types of user currently, Admin and Vendor, and i want to log their activities like</p> <pre><code>"TestAdmin" viewed transaction "TestAdmin" added a new vendor "TestAdmin" edited a Transaction "TestVendor" added a new Transaction "TestAdmin" approved Transaction "TestAdmin" rejected Transaction etc... </code></pre> <p>where "TestAdmin" is an admin and "TestVendor" is a vendor</p> <p>But i m not sure what approach i should follow</p> <p>I m thinking of this </p> <p>Adding an Activity table in DB with following fields</p> <pre><code>user_id browser session_id ip_address action params </code></pre> <p>and call </p> <pre><code>before_filter :record_activity </code></pre> <p>to record all activities</p> <p>but not sure how to create messages like above</p> <p>Also i want to figure out if any error occurs and when and why, so for this i take browser fields to figure out whether code doesn't work in IE etc. but this is only one error track field.</p> <p>Please help and guide to some nice way to accomplish this. </p> <p>Thanks</p>
9,981,462
5
0
null
2012-03-23 08:11:21.727 UTC
13
2019-07-13 18:38:28.537 UTC
2012-03-23 09:20:35.593 UTC
null
839,256
null
839,256
null
1
21
ruby-on-rails
15,973
<p>Ok this is what i did...</p> <p>First create table </p> <pre><code>create_table "activity_logs", :force =&gt; true do |t| t.string "user_id" t.string "browser" t.string "ip_address" t.string "controller" t.string "action" t.string "params" t.string "note" t.datetime "created_at" t.datetime "updated_at" end </code></pre> <p>created function in application controller</p> <pre><code>def record_activity(note) @activity = Activity_Log.new @activity.user = current_user @activity.note = note @activity.browser = request.env['HTTP_USER_AGENT'] @activity.ip_address = request.env['REMOTE_ADDR'] @activity.controller = controller_name @activity.action = action_name @activity.params = params.inspect @activity.save end </code></pre> <p>then call above function from any controller needed like this....</p> <pre><code>class AccountsController &lt; ApplicationController load_and_authorize_resource # POST /accounts # POST /accounts.json def create @account = Account.new(params[:account]) respond_to do |format| if @account.save record_activity("Created new account") #This will call application controller record_activity format.js { head :ok } else format.js { render json: @account.errors, :error =&gt; true, :success =&gt; false } end end end </code></pre> <p>Hence problem solved......</p> <p>Thanks all for all their help....</p>
9,897,345
Pickle alternatives
<p>I am trying to serialize a large (~10**6 rows, each with ~20 values) list, to be used later by myself (so pickle's lack of safety isn't a concern).</p> <p>Each row of the list is a tuple of values, derived from some SQL database. So far, I have seen <code>datetime.datetime</code>, strings, integers, and NoneType, but I might eventually have to support additional data types.</p> <p>For serialization, I've considered pickle (cPickle), json, and plain text - but only pickle saves the type information: json can't serialize <code>datetime.datetime</code>, and plain text has its obvious disadvantages.</p> <p>However, cPickle is pretty slow for data this large, and I'm looking for a faster alternative.</p>
9,897,487
8
2
null
2012-03-27 20:38:41.327 UTC
8
2022-02-20 03:23:43.883 UTC
2019-07-02 16:48:06.563 UTC
null
1,079,075
null
1,032,006
null
1
33
python|serialization
38,440
<p>I think you should give <a href="http://www.pytables.org/" rel="noreferrer">PyTables</a> a look. It should be ridiculously fast, at least faster than using an RDBMS, since it's very lax and doesn't impose any read/write restrictions, plus you get a better interface for managing your data, at least compared to pickling it.</p>
10,065,287
Why is ushort + ushort equal to int?
<p>Previously today I was trying to add two ushorts and I noticed that I had to cast the result back to ushort. I thought it might've become a uint (to prevent a possible unintended overflow?), but to my surprise it was an int (System.Int32).</p> <p>Is there some clever reason for this or is it maybe because int is seen as the 'basic' integer type?</p> <p>Example:</p> <pre><code>ushort a = 1; ushort b = 2; ushort c = a + b; // &lt;- "Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists (are you missing a cast?)" uint d = a + b; // &lt;- "Cannot implicitly convert type 'int' to 'uint'. An explicit conversion exists (are you missing a cast?)" int e = a + b; // &lt;- Works! </code></pre> <p>Edit: Like GregS' answer says, the C# spec says that both operands (in this example 'a' and 'b') should be converted to int. I'm interested in the underlying reason for why this is part of the spec: why doesn't the C# spec allow for operations directly on ushort values?</p>
10,157,517
5
2
null
2012-04-08 18:32:17.413 UTC
6
2018-12-19 05:05:23.623 UTC
2018-12-19 05:05:23.623 UTC
null
2,063,755
null
319,611
null
1
35
c#|types|integer-arithmetic
20,946
<p>The simple and correct answer is "because the C# Language Specification says so".</p> <p>Clearly you are not happy with that answer and want to know "why does it say so". You are looking for "credible and/or official sources", that's going to be a bit difficult. These design decisions were made a long time ago, 13 years is a lot of dog lives in software engineering. They were made by the "old timers" as Eric Lippert calls them, they've moved on to bigger and better things and don't post answers here to provide an official source.</p> <p>It can be inferred however, at a risk of merely being credible. Any managed compiler, like C#'s, has the constraint that it needs to generate code for the .NET virtual machine. The rules for which are carefully (and quite readably) described in the CLI spec. It is the Ecma-335 spec, you can download it for free <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm" rel="noreferrer">from here</a>.</p> <p>Turn to Partition III, chapter 3.1 and 3.2. They describe the two IL instructions available to perform an addition, <code>add</code> and <code>add.ovf</code>. Click the link to Table 2, "Binary Numeric Operations", it describes what operands are permissible for those IL instructions. Note that there are just a few types listed there. byte and short as well as all unsigned types are missing. Only int, long, IntPtr and floating point (float and double) is allowed. With additional constraints marked by an x, you can't add an int to a long for example. These constraints are not entirely artificial, they are based on things you can do reasonably efficient on available hardware.</p> <p>Any managed compiler has to deal with this in order to generate valid IL. That isn't difficult, simply convert the ushort to a larger value type that's in the table, a conversion that's always valid. The C# compiler picks int, the next larger type that appears in the table. Or in general, convert any of the operands to the next largest value type so they both have the same type and meet the constraints in the table.</p> <p>Now there's a new problem however, a problem that drives C# programmers pretty nutty. The result of the addition is of the promoted type. In your case that will be int. So adding two ushort values of, say, 0x9000 and 0x9000 has a perfectly valid int result: 0x12000. Problem is: that's a value that doesn't fit back into an ushort. The value <em>overflowed</em>. But it <em>didn't</em> overflow in the IL calculation, it only overflows when the compiler tries to cram it back into an ushort. 0x12000 is truncated to 0x2000. A bewildering different value that only makes some sense when you count with 2 or 16 fingers, not with 10.</p> <p>Notable is that the add.ovf instruction doesn't deal with this problem. It is the instruction to use to automatically generate an overflow exception. But it doesn't, the actual calculation on the converted ints didn't overflow.</p> <p>This is where the real design decision comes into play. The old-timers apparently decided that simply truncating the int result to ushort was a bug factory. It certainly is. They decided that you have to acknowledge that you <em>know</em> that the addition can overflow and that it is okay if it happens. They made it <em>your</em> problem, mostly because they didn't know how to make it theirs and still generate efficient code. You have to cast. Yes, that's maddening, I'm sure you didn't want that problem either.</p> <p>Quite notable is that the VB.NET designers took a different solution to the problem. They actually made it <em>their</em> problem and didn't pass the buck. You can add two UShorts and assign it to an UShort without a cast. The difference is that the VB.NET compiler actually generates <em>extra</em> IL to check for the overflow condition. That's not cheap code, makes every short addition about 3 times as slow. But otherwise the reason that explains why Microsoft maintains <em>two</em> languages that have otherwise very similar capabilities.</p> <p>Long story short: you are paying a price because you use a type that's not a very good match with modern cpu architectures. Which in itself is a Really Good Reason to use uint instead of ushort. Getting traction out of ushort is difficult, you'll need a lot of them before the cost of manipulating them out-weighs the memory savings. Not just because of the limited CLI spec, an x86 core takes an extra cpu cycle to load a 16-bit value because of the operand prefix byte in the machine code. Not actually sure if that is still the case today, it used to be back when I still paid attention to counting cycles. A dog year ago.</p> <hr> <p>Do note that you can feel better about these ugly and dangerous casts by letting the C# compiler generate the same code that the VB.NET compiler generates. So you get an OverflowException when the cast turned out to be unwise. Use Project > Properties > Build tab > Advanced button > tick the "Check for arithmetic overflow/underflow" checkbox. Just for the Debug build. Why this checkbox isn't turned on automatically by the project template is another very mystifying question btw, a decision that was made too long ago.</p>
10,013,906
Android - zoom in/out RelativeLayout with spread/pinch
<p>I have an activity with a <code>RelativeLayout</code> and a private class in it, which extends the <code>SimpleOnScaleGestureListener</code>. In the <code>onScale</code> method of the listener I'd like to zoom in/out of the whole layout (everything the user sees) with the user spreading/pinching his fingers.</p> <p>I'd like the changes to the layout NOT to be permanent, i.e. when the spread/pinch gesture is over I'd like the layout to go back to what it was in first place (any resetting could be done in the <code>onScaleEnd</code> method of the <code>SimpleOnScaleGestureListener</code> for example).</p> <p>I've tried to implement it via calling <code>setScaleX</code> and <code>setScaleY</code> on the <code>RelativeLayout</code> and also by using a <code>ScaleAnimation</code>. Neither resulted in smooth zooming (or anything that could at all be called zooming). Is it even possible to zoom in/out a <code>RelativeLayout</code>?</p> <p>The only idea I have left would be reading a screenshot from the cache and putting it as an <code>ImageView</code> on top of the whole layout and the zoom in/out of this image via <code>setImageMatrix</code>. I have no clue, however, how to implement this.</p> <p>May layout also contains a container for a fragment, which is empty at the time the zooming is supposed to be possible. In the <code>onScaleEnd</code> gesture, the fragment is put into it's container (already implemented and working fine). Here is my layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_pinch" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" &gt; &lt;!-- Layout containing the thumbnail ImageViews --&gt; &lt;LinearLayout android:id="@+id/thumbnail_group_pui" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="horizontal" &gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tn_c1"/&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tn_c2"/&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tn_c3"/&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tn_c4"/&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tn_c5"/&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tn_c6"/&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/tn_c7"/&gt; &lt;/LinearLayout&gt; &lt;!-- Layout containing the dashed boxes --&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="152dp" android:layout_centerVertical="true" android:orientation="horizontal" &gt; &lt;ImageView android:layout_width="177dp" android:layout_height="match_parent" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:background="@drawable/dashed_box"/&gt; &lt;ImageView android:layout_width="177dp" android:layout_height="match_parent" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:background="@drawable/dashed_box"/&gt; &lt;ImageView android:layout_width="177dp" android:layout_height="match_parent" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:background="@drawable/dashed_box"/&gt; &lt;ImageView android:layout_width="177dp" android:layout_height="match_parent" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:background="@drawable/dashed_box"/&gt; &lt;ImageView android:layout_width="177dp" android:layout_height="match_parent" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:background="@drawable/dashed_box"/&gt; &lt;ImageView android:layout_width="177dp" android:layout_height="match_parent" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:background="@drawable/dashed_box"/&gt; &lt;ImageView android:layout_width="177dp" android:layout_height="match_parent" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:background="@drawable/dashed_box"/&gt; &lt;/LinearLayout&gt; &lt;!-- Container for the fragments --&gt; &lt;FrameLayout android:id="@+id/fragment_container_pui" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p><strong>EDIT</strong> I found these two related topics:<br> <a href="https://stackoverflow.com/questions/6378904/extending-relativelayout-and-overriding-dispatchdraw-to-create-a-zoomable-vie">Extending RelativeLayout, and overriding dispatchDraw() to create a zoomable ViewGroup</a><br> <a href="https://stackoverflow.com/questions/9192424/zoom-content-in-a-relativelayout">Zoom Content in a RelativeLayout</a></p> <p>I did not get the implementation, however. What other methods do I have to include in the extended class to actually scale the layout or reset it?</p>
10,029,320
4
1
null
2012-04-04 15:06:21.8 UTC
18
2022-07-22 04:52:22.053 UTC
2017-05-23 12:34:34.957 UTC
null
-1
null
1,137,282
null
1
37
android|android-layout|android-animation
55,588
<p>So I created a subclass of <code>RelativeLayout</code> as described in the above mentioned topics. It looks like this:</p> <pre><code>public class ZoomableRelativeLayout extends RelativeLayout { float mScaleFactor = 1; float mPivotX; float mPivotY; public ZoomableRelativeLayout(Context context) { super(context); // TODO Auto-generated constructor stub } public ZoomableRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public ZoomableRelativeLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } protected void dispatchDraw(Canvas canvas) { canvas.save(Canvas.MATRIX_SAVE_FLAG); canvas.scale(mScaleFactor, mScaleFactor, mPivotX, mPivotY); super.dispatchDraw(canvas); canvas.restore(); } public void scale(float scaleFactor, float pivotX, float pivotY) { mScaleFactor = scaleFactor; mPivotX = pivotX; mPivotY = pivotY; this.invalidate(); } public void restore() { mScaleFactor = 1; this.invalidate(); } } </code></pre> <p>My implementation of the <code>SimpleOnScaleGestureListener</code> looks like this:</p> <pre><code>private class OnPinchListener extends SimpleOnScaleGestureListener { float startingSpan; float endSpan; float startFocusX; float startFocusY; public boolean onScaleBegin(ScaleGestureDetector detector) { startingSpan = detector.getCurrentSpan(); startFocusX = detector.getFocusX(); startFocusY = detector.getFocusY(); return true; } public boolean onScale(ScaleGestureDetector detector) { mZoomableRelativeLayout.scale(detector.getCurrentSpan()/startingSpan, startFocusX, startFocusY); return true; } public void onScaleEnd(ScaleGestureDetector detector) { mZoomableRelativeLayout.restore(); } } </code></pre> <p>Hope this helps!</p> <h2>Update:</h2> <p>You can integrate <code>OnPinchListener</code> for your <code>ZoomableRelativelayout</code> by using <code>ScaleGestureDetector</code>:</p> <pre><code>ScaleGestureDetector scaleGestureDetector = new ScaleGestureDetector(this, new OnPinchListener()); </code></pre> <p>And you are required to bind touch listener of Zoomable layout with the touch listener of ScaleGestureDetector:</p> <pre><code>mZoomableLayout.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub scaleGestureDetector.onTouchEvent(event); return true; } }); </code></pre>
10,149,416
Numpy modify array in place?
<p>I have the following code which is attempting to normalize the values of an <code>m x n</code> array (It will be used as input to a neural network, where <code>m</code> is the number of training examples and <code>n</code> is the number of features).</p> <p>However, when I inspect the array in the interpreter after the script runs, I see that the values are not normalized; that is, they still have the original values. I guess this is because the assignment to the <code>array</code> variable inside the function is only seen within the function. </p> <p>How can I do this normalization in place? Or do I have to return a new array from the normalize function?</p> <pre><code>import numpy def normalize(array, imin = -1, imax = 1): """I = Imin + (Imax-Imin)*(D-Dmin)/(Dmax-Dmin)""" dmin = array.min() dmax = array.max() array = imin + (imax - imin)*(array - dmin)/(dmax - dmin) print array[0] def main(): array = numpy.loadtxt('test.csv', delimiter=',', skiprows=1) for column in array.T: normalize(column) return array if __name__ == "__main__": a = main() </code></pre>
10,149,508
4
0
null
2012-04-13 23:10:30.317 UTC
7
2019-03-08 21:13:32.163 UTC
null
null
null
null
155,268
null
1
40
python|arrays|numpy|in-place
40,024
<p>If you want to apply mathematical operations to a numpy array in-place, you can simply use the standard in-place operators <code>+=</code>, <code>-=</code>, <code>/=</code>, etc. So for example:</p> <pre><code>&gt;&gt;&gt; def foo(a): ... a += 10 ... &gt;&gt;&gt; a = numpy.arange(10) &gt;&gt;&gt; a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) &gt;&gt;&gt; foo(a) &gt;&gt;&gt; a array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) </code></pre> <p>The in-place version of these operations is a tad faster to boot, especially for larger arrays:</p> <pre><code>&gt;&gt;&gt; def normalize_inplace(array, imin=-1, imax=1): ... dmin = array.min() ... dmax = array.max() ... array -= dmin ... array *= imax - imin ... array /= dmax - dmin ... array += imin ... &gt;&gt;&gt; def normalize_copy(array, imin=-1, imax=1): ... dmin = array.min() ... dmax = array.max() ... return imin + (imax - imin) * (array - dmin) / (dmax - dmin) ... &gt;&gt;&gt; a = numpy.arange(10000, dtype='f') &gt;&gt;&gt; %timeit normalize_inplace(a) 10000 loops, best of 3: 144 us per loop &gt;&gt;&gt; %timeit normalize_copy(a) 10000 loops, best of 3: 146 us per loop &gt;&gt;&gt; a = numpy.arange(1000000, dtype='f') &gt;&gt;&gt; %timeit normalize_inplace(a) 100 loops, best of 3: 12.8 ms per loop &gt;&gt;&gt; %timeit normalize_copy(a) 100 loops, best of 3: 16.4 ms per loop </code></pre>
9,953,295
How to repair my mongodb?
<p>I can't seem to connect to Mongo DB, which I've installed as a Windows Service on my local machine. I've also built a little WPF application which communicates with MongoDB. The errormessage: </p> <p><em>Error: couldn't connect to server 127.0.0.1 shell/mongo.js:8 4 exception: connect failed Unclean shutdown detected.</em></p>
9,953,305
7
1
null
2012-03-31 05:33:33.227 UTC
20
2021-06-11 22:33:51.323 UTC
null
null
null
null
219,167
null
1
45
mongodb
95,966
<p>You should launch it with <code>--repair</code> flag.</p> <pre><code>mongod --repair </code></pre> <p>After repair is finished, stop this one and launch it normally. <a href="https://docs.mongodb.com/manual/reference/program/mongod/#cmdoption--repair" rel="noreferrer">Documentation on --repair option</a>.</p>
8,306,237
Android: Login with Twitter using Twitter4J
<p><strong>What I Have Tried:</strong></p> <p>I already have registered an app in twitter and got Consumer Key and Secret.Even I got various codes to login with twitter.These are what I have tried from:</p> <p><a href="http://thetechnib.blogspot.com/2011/01/android-sign-in-with-twitter.html" rel="noreferrer">http://thetechnib.blogspot.com/2011/01/android-sign-in-with-twitter.html</a></p> <p>[This link is dead, you may view an archive <a href="http://web.archive.org/web/20130121120221/http://android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application" rel="noreferrer">here</a>]<br> <s><a href="http://www.android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application" rel="noreferrer">http://www.android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application</a></s></p> <p><strong>Problem I have:</strong></p> <p>Till now,above code takes me to twitter login and let me sign in and have a PIN to complete the login process.But I have no idea how to use it to get my app working.I checked the whole code but found nothing related to pin.</p> <p>Secondly,when I registered my app on twitter,it asked for Callback URL but as it was written that its really not needed,i skipped specifying.(Even I don't know what it should be!)</p> <p>And hence,I am giving null as CallbackURL in my app.</p> <p>Can anyone suggest me,how can I use this PIN to complete login process and get user back to my app's main activity? Is it the callback url which is causing problem or something else I am doing wrong at?</p> <p>Please reply.Any help appriciated! Thanks.</p> <p><strong>EDIT :</strong></p> <p>As suggested by Frankenstein,I tried code at github.com/ddewaele/AndroidTwitterSample/downloads</p> <p>I added my consumer key and consumer secret along with callback url:</p> <pre><code>public static final String OAUTH_CALLBACK_SCHEME= "x-oauthflow-twitter"; public static final String OAUTH_CALLBACK_HOST= "callback"; public static final String OAUTH_CALLBACK_URL= OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST; </code></pre> <p>but it gives me this error: </p> <p>Logcat:</p> <pre><code>11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): Error during OAUth retrieve request token 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match. 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:239) 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189) 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69) 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:55) 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at com.ecs.android.sample.twitter.OAuthRequestTokenTask.doInBackground(OAuthRequestTokenTask.java:1) 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at android.os.AsyncTask$2.call(AsyncTask.java:185) 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 11-29 11:56:56.249: E/com.ecs.android.sample.twitter.OAuthRequestTokenTask(3081): at java.lang.Thread.run(Thread.java:1096) </code></pre> <p>Also shows me black screen when i click on TWEET button,instead of taking me to sign in screen of twitter.</p> <p>Omg,I am going to be crazy...have been trying since two days! :( please help.</p>
8,307,443
3
2
null
2011-11-29 05:21:20.443 UTC
9
2013-10-30 16:47:51.71 UTC
2013-04-23 02:42:16.327 UTC
null
427,309
null
867,603
null
1
6
android|authentication|twitter-oauth|twitter4j
17,639
<p>It's because your app is registered as a desktop client. To overwrite callback URL, your app need to be registered as a browser client.</p> <p>Try configuring a dummy callback URL (http://example.com/ or whatever you want) at https://dev.twitter.com/apps/[appid]/settings > Callback URL and your app will be recognized as a browser client.</p> <p>Then try @Frankenstein or @jamn224 code. </p>
11,991,007
jQuery get the selected dropdown value on change
<p>I'm trying to get the value of a dropdown on change (and then change the values in a second dropdown).</p> <p><strong>EDIT:</strong> Thanks for all the replies, i've updated to add the () but the code is returning nothing, not null or undefined just a blank alert window</p> <p>However when I alert it out the attr(value) is undefined.</p> <p>Any ideas on what i'm missing?</p> <p>Here is my code:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { var roomID = "0" $('.dropone').load('ajaxdropdown.aspx'); $('.droptwo').load('ajaxdropdown.aspx?drpType=room&amp;roomid=' + roomID); $('.dropone').change(function() { var ts = new Date().getTime(); alert($(this).val) $(".droptwo").empty(); $(".droptwo").load("ajaxdropdown.aspx?drpType=room&amp;roomid=" + $(this).attr("value") + "&amp;ts=" + ts); }); }); &lt;/script&gt; </code></pre>
11,991,041
6
2
null
2012-08-16 15:50:58.613 UTC
null
2020-06-12 09:11:09.793 UTC
2012-08-16 15:57:49.7 UTC
null
900,659
null
900,659
null
1
12
javascript|jquery
79,473
<p><a href="http://api.jquery.com/val/" rel="noreferrer"><code>val</code></a> is a method, not a property.</p> <p>use it like <code>val()</code></p> <p>If you are using it many places, i would assign it to a local variable and use it thereafter.</p> <p>Also you can use the <a href="http://api.jquery.com/jQuery.now/" rel="noreferrer"><code>$.now()</code></a> function to get the unique time stamp. It is equal to DategetTime();</p> <pre><code>$('.dropone').change(function() { var item=$(this);     alert(item.val()) $(".droptwo").empty();     $(".droptwo").load("ajaxdropdown.aspx?drpType=room &amp;roomid=" +item.attr("value") + "&amp;ts=" + $.now()); }); </code></pre>
11,773,433
Android Master Detail Flow Example
<p><img src="https://i.stack.imgur.com/Fbl2e.png" alt="enter image description here"></p> <p>I'm trying to implement a user interface like above and looking for a good tutorial to or code sample to learn it. Can someone help me to get this done</p>
11,773,551
2
0
null
2012-08-02 08:09:12.66 UTC
4
2013-11-08 15:14:28.86 UTC
null
null
null
null
438,877
null
1
18
android|android-layout
42,895
<p>If you are using Eclipse with ADT installed, you can create a new Activity (or Android Project) and select MasterDetailFlow as the template to be used for that activity. This will contain a Master Detail flow with a simple list of items.</p> <p><strong>EDIT</strong></p> <p>For an advanced list layout, you will need a customized ListView.</p> <p>Examples:</p> <ul> <li><a href="https://stackoverflow.com/questions/6305899/custom-listview-android">Custom ListView Android</a></li> <li><a href="http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/" rel="nofollow noreferrer">Android Custom ListView with Image and Text</a></li> </ul>
11,746,071
How to split a multi-line string containing the characters "\n" into an array of strings in bash?
<p> I have a <em>string</em> in the following format:</p> <pre class="lang-none prettyprint-override"><code>I'm\nNed\nNederlander I'm\nLucky\nDay I'm\nDusty\nBottoms </code></pre> <p>I would like to move this to an array of strings line by line such that:</p> <pre class="lang-none prettyprint-override"><code>$ echo "${ARRAY[0]}" I'm\nNed\nNederlander $ echo "${ARRAY[1]}" I'm\nLucky\nDay $ echo "${ARRAY[2]}" I'm\nDusty\nBottoms </code></pre> <p>However, I'm running into problems with the "\n" characters within the string itself. They are represented in the string as two separate characters, the backslash and the 'n', but when I try to do the array split they get interpreted as newlines. Thus typical string splitting with <code>IFS</code> does not work.</p> <p>For example:</p> <pre class="lang-none prettyprint-override"><code>$ read -a ARRAY &lt;&lt;&lt; "$STRING" $ echo "${#ARRAY[@]}" # print number of elements 2 $ echo "${ARRAY[0]}" I'mnNednNederla $ echo "${ARRAY[1]}" der </code></pre>
11,746,174
2
2
null
2012-07-31 17:48:59.417 UTC
4
2017-04-13 08:44:59.273 UTC
2017-04-13 08:44:59.273 UTC
null
1,062,281
null
446,554
null
1
22
arrays|string|bash|escaping
40,725
<p>By default, the <code>read</code> builtin allows \ to escape characters. To turn off this behavior, use the <code>-r</code> option. It is not often you will find a case where you do not want to use <code>-r</code>. </p> <pre><code>string="I'm\nNed\nNederlander I'm\nLucky\nDay I'm\nDusty\nBottoms" arr=() while read -r line; do arr+=("$line") done &lt;&lt;&lt; "$string" </code></pre> <p>In order to do this in one-line (like you were attempting with <code>read -a</code>), actually requires <code>mapfile</code> in bash v4 or higher:</p> <pre><code>mapfile -t arr &lt;&lt;&lt; "$string" </code></pre>
11,666,385
select document root using jquery
<p>I can select the body and html parts of the document using</p> <pre><code>$('body') </code></pre> <p>and</p> <pre><code>$('html') </code></pre> <p>respectively, but how do I select the document root?</p>
11,666,422
3
2
null
2012-07-26 09:31:27.29 UTC
2
2016-07-25 10:17:46.113 UTC
null
null
null
null
246,622
null
1
22
jquery|html|jquery-selectors|document-root
55,520
<p>Not sure what you mean, but to select the document you do</p> <pre><code>$(document); </code></pre> <p>To get the contents of the document I'm guessing you need the documentElement, which is just the same as the <code>&lt;html&gt;</code> tag in most enviroments.</p> <pre><code>$(document.documentElement); </code></pre>
11,661,503
Django Caching for Authenticated Users Only
<h1>Question</h1> <p>In Django, how can create a single cached version of a page (same for all users) that's only visible to authenticated users?</p> <h2>Setup</h2> <p>The pages I wish to cache are only available to authenticated users (they use <code>@login_required</code> on the view). These pages are the same for all authenticated users (e.g. no need to setup <code>vary_on_headers</code> based on unique users).</p> <p>However, I don't want these cached pages to be visible to non-authenticated users.</p> <h2>What I've tried so far</h2> <ul> <li>Page level cache (shows pages intended for logged in users to non-logged in users)</li> <li>Looked into using <code>vary_on_headers</code>, but I don't need individually cached pages for each user</li> <li>I checked out template fragment caching, but unless I'm confused, this won't meet my needs</li> <li>Substantial searching (seems that everyone wants to do the reverse)</li> </ul> <p>Thanks!</p> <h3>Example View</h3> <pre><code>@login_required @cache_page(60 * 60) def index(request): '''Display the home page''' return render(request, 'index.html') </code></pre> <h3>settings.py (relevant portion)</h3> <pre><code># Add the below for memcache MIDDLEWARE_CLASSES += ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) # Enable memcache # https://devcenter.heroku.com/articles/memcache#using_memcache_from_python CACHES = { 'default': { 'BACKEND': 'django_pylibmc.memcached.PyLibMCCache' } } </code></pre> <hr /> <h1>Solution</h1> <p>Based on the answer by @Tisho I solved this problem by</p> <ol> <li>Creating a <code>decorators.py</code> file in my app</li> <li>Adding the below code to it</li> <li>Importing the function in <code>views.py</code></li> <li>Applying it as a decorator to the views I wanted to cache for logged in users only</li> </ol> <h2>decorators.py</h2> <pre><code>from functools import wraps from django.views.decorators.cache import cache_page from django.utils.decorators import available_attrs def cache_on_auth(timeout): def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return cache_page(timeout)(view_func)(request, *args, **kwargs) else: return view_func(request, *args, **kwargs) return _wrapped_view return decorator </code></pre> <p>For logged in users, it would cache the page (or serve them the cached page) for non-logged in users, it would just give them the regular view, which was decorated with <code>@login_required</code> and would require them to login.</p>
11,703,958
5
1
null
2012-07-26 02:34:50.08 UTC
12
2022-09-01 23:50:31.46 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,006,036
null
1
23
python|django|caching|heroku|memcached
6,478
<p>The default <code>cache_page</code> decorator accepts a variable called <code>key_prefix</code>. However, it can be passed as a string parameter only. So you can write your own decorator, that will dynamically modify this <code>prefix_key</code> based on the <code>is_authenticated</code> value. Here is an example:</p> <pre><code>from django.views.decorators.cache import cache_page def cache_on_auth(timeout): def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): return cache_page(timeout, key_prefix="_auth_%s_" % request.user.is_authenticated())(view_func)(request, *args, **kwargs) return _wrapped_view return decorator </code></pre> <p>and then use it on the view:</p> <pre><code>@cache_on_auth(60*60) def myview(request) </code></pre> <p>Then, the generated cache_key will look like:</p> <pre><code>cache key: views.decorators.cache.cache_page._auth_False_.GET.123456.123456 </code></pre> <p>if the user is authenticated, and</p> <pre><code>cache key: views.decorators.cache.cache_page._auth_True_.GET.789012.789012 </code></pre> <p>if the user is not authenticated.</p>
11,923,235
scandir() to sort by date modified
<p>I'm trying to make <code>scandir();</code> function go beyond its written limits, I need more than the alpha sorting it currently supports. I need to sort the <code>scandir();</code> results to be sorted by modification date. </p> <p>I've tried a few solutions I found here and some other solutions from different websites, but none worked for me, so I think it's reasonable for me to post here.</p> <p>What I've tried so far is this:</p> <pre><code>function scan_dir($dir) { $files_array = scandir($dir); $img_array = array(); $img_dsort = array(); $final_array = array(); foreach($files_array as $file) { if(($file != ".") &amp;&amp; ($file != "..") &amp;&amp; ($file != ".svn") &amp;&amp; ($file != ".htaccess")) { $img_array[] = $file; $img_dsort[] = filemtime($dir . '/' . $file); } } $merge_arrays = array_combine($img_dsort, $img_array); krsort($merge_arrays); foreach($merge_arrays as $key =&gt; $value) { $final_array[] = $value; } return (is_array($final_array)) ? $final_array : false; } </code></pre> <p>But, this doesn't seem to work for me, it returns 3 results only, but it should return 16 results, because there are 16 images in the folder.</p>
11,923,516
4
0
null
2012-08-12 15:10:15.367 UTC
14
2021-05-21 04:01:02.103 UTC
2018-01-17 15:23:20.777 UTC
null
472,495
null
445,820
null
1
32
php|arrays|sorting|scandir
75,578
<pre><code>function scan_dir($dir) { $ignored = array('.', '..', '.svn', '.htaccess'); $files = array(); foreach (scandir($dir) as $file) { if (in_array($file, $ignored)) continue; $files[$file] = filemtime($dir . '/' . $file); } arsort($files); $files = array_keys($files); return ($files) ? $files : false; } </code></pre>
11,514,242
Add CSS3 transition expand/collapse
<p>How do I add an expand/collapse transition?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function showHide(shID) { if (document.getElementById(shID)) { if (document.getElementById(shID + '-show').style.display != 'none') { document.getElementById(shID + '-show').style.display = 'none'; document.getElementById(shID).style.display = 'block'; } else { document.getElementById(shID + '-show').style.display = 'inline'; document.getElementById(shID).style.display = 'none'; } } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.more { display: none; padding-top: 10px; } a.showLink, a.hideLink { text-decoration: none; -webkit-transition: 0.5s ease-out; background: transparent url('down.gif') no-repeat left; } a.hideLink { background: transparent url('up.gif') no-repeat left; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>Here is some text. &lt;div class="readmore"&gt; &lt;a href="#" id="example-show" class="showLink" onclick="showHide('example');return false;"&gt;Read more&lt;/a&gt; &lt;div id="example" class="more"&gt; &lt;div class="text"&gt;Here is some more text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae urna nulla. Vivamus a purus mi. In hac habitasse platea dictumst. In ac tempor quam. Vestibulum eleifend vehicula ligula, et cursus nisl gravida sit amet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.&lt;/div&gt; &lt;p&gt;&lt;a href="#" id="example-hide" class="hideLink" onclick="showHide('example');return false;"&gt;Hide&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/Bq6eK/1" rel="noreferrer">http://jsfiddle.net/Bq6eK/1</a></p>
11,837,673
5
1
null
2012-07-16 23:50:10.017 UTC
13
2019-04-01 13:42:38.127 UTC
2019-04-01 13:42:38.127 UTC
null
2,756,409
null
876,960
null
1
56
javascript|html|css
212,531
<p><a href="http://jsfiddle.net/9ccjE/" rel="noreferrer">This</a> is my solution that adjusts the height automatically:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function growDiv() { var growDiv = document.getElementById('grow'); if (growDiv.clientHeight) { growDiv.style.height = 0; } else { var wrapper = document.querySelector('.measuringWrapper'); growDiv.style.height = wrapper.clientHeight + "px"; } document.getElementById("more-button").value = document.getElementById("more-button").value == 'Read more' ? 'Read less' : 'Read more'; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#more-button { border-style: none; background: none; font: 16px Serif; color: blue; margin: 0 0 10px 0; } #grow input:checked { color: red; } #more-button:hover { color: black; } #grow { -moz-transition: height .5s; -ms-transition: height .5s; -o-transition: height .5s; -webkit-transition: height .5s; transition: height .5s; height: 0; overflow: hidden; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="button" onclick="growDiv()" value="Read more" id="more-button"&gt; &lt;div id='grow'&gt; &lt;div class='measuringWrapper'&gt; &lt;div class="text"&gt;Here is some more text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae urna nulla. Vivamus a purus mi. In hac habitasse platea dictumst. In ac tempor quam. Vestibulum eleifend vehicula ligula, et cursus nisl gravida sit amet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I used the workaround that r3bel posted: <a href="https://stackoverflow.com/questions/3149419/can-you-use-css3-to-transition-from-height0-to-the-variable-height-of-content">Can you use CSS3 to transition from height:0 to the variable height of content?</a></p>
11,880,360
How to implement a bitmask in php?
<p>I'm not sure if bitmask is the correct term. Let me explain:</p> <p>In php, the <code>error_reporting</code> function can be called multiple ways:</p> <pre><code>// Report simple running errors error_reporting(E_ERROR | E_WARNING | E_PARSE); // Reporting E_NOTICE can be good too (to report uninitialized // variables or catch variable name misspellings ...) error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); // Report all errors except E_NOTICE // This is the default value set in php.ini error_reporting(E_ALL ^ E_NOTICE); </code></pre> <p>I got the term bitmask from the php.net page <a href="http://php.net/manual/en/function.error-reporting.php">here</a></p> <p>Anyway the point of this is, I have implemented a SIMPLE method called <code>ls</code> which returns the contents of a directory.</p> <p>This function takes 3 args... ( $include_hidden = false, $return_absolute = false, $ext = false )</p> <p>So when i call the function, i set how i want the results. Whether i want the results to return hidden directories, whether i want basenames only etc.</p> <p>so when i call the function i'm writing </p> <pre><code>ls(true, false, true) ls(false, false, true) ls(true, true, true) etc... </code></pre> <p>I thought it would be much more readable if i could just flag how i want the data returned?</p> <p>so something like:</p> <pre><code>ls( INCLUDE_HIDDEN | HIDE_EXTS ); ls( SHOW_ABSOLUTE_PATHS | HIDE_EXTS ); </code></pre> <p>etc...</p> <p>How would i implement this in terms of testing which flags have been called?</p>
11,880,410
4
0
null
2012-08-09 09:26:04.07 UTC
35
2022-09-22 02:36:00.067 UTC
2014-02-25 19:10:08.46 UTC
null
321,731
null
755,692
null
1
91
php|bitmask
33,547
<p>It's quite simple actually. First a bit of code to demonstrate how it can be implemented. If you don't understand anything about what this code is doing or how it works, feel free to ask additional questions in the comments:</p> <pre><code>const FLAG_1 = 0b0001; // 1 const FLAG_2 = 0b0010; // 2 const FLAG_3 = 0b0100; // 4 const FLAG_4 = 0b1000; // 8 // Can you see the pattern? ;-) function show_flags ($flags) { if ($flags &amp; FLAG_1) { echo "You passed flag 1!&lt;br&gt;\n"; } if ($flags &amp; FLAG_2) { echo "You passed flag 2!&lt;br&gt;\n"; } if ($flags &amp; FLAG_3) { echo "You passed flag 3!&lt;br&gt;\n"; } if ($flags &amp; FLAG_4) { echo "You passed flag 4!&lt;br&gt;\n"; } } show_flags(FLAG_1 | FLAG_3); </code></pre> <p><a href="http://3v4l.org/tTZnW" rel="noreferrer">Demo</a></p> <hr> <p>Because the flags are integers, on a 32-bit platform you define up to 32 flags. On a 64-bit platform, it's 64. It is also possible to define the flags as strings, in which case the number of available flags is more or less infinite (within the bounds of system resources, of course). Here's how it works in binary (cut down to 8-bit integers for simplicity).</p> <pre><code>FLAG_1 Dec: 1 Binary: 00000001 FLAG_2 Dec: 2 Binary: 00000010 FLAG_3 Dec: 4 Binary: 00000100 // And so on... </code></pre> <p>When you combine the flags to pass them to the function, you OR them together. Let's take a look at what happens when we pass <code>FLAG_1 | FLAG_3</code></p> <pre><code> 00000001 | 00000100 = 00000101 </code></pre> <p>And when you want to see which flags were set, you AND the bitmask with the flag. So, lets take the result above and see if <code>FLAG_3</code> was set:</p> <pre><code> 00000101 &amp; 00000100 = 00000100 </code></pre> <p>...we get the value of the flag back, a non-zero integer - but if we see if <code>FLAG_2</code> was set:</p> <pre><code> 00000101 &amp; 00000010 = 00000000 </code></pre> <p>...we get zero. This means that you can simply evaluate the result of the AND operation as a boolean when checking if the value was passed.</p>
11,801,186
CMake unable to determine linker language with C++
<p>I'm attempting to run a cmake hello world program on Windows 7 x64 with both Visual Studio 2010 and Cygwin, but can't seem to get either to work. My directory structure is as follows:</p> <pre><code>HelloWorld -- CMakeLists.txt -- src/ -- -- CMakeLists.txt -- -- main.cpp -- build/ </code></pre> <p>I do a <code>cd build</code> followed by a <code>cmake ..</code>, and get an error stating that </p> <pre><code>CMake Error: CMake can not determine linker language for target:helloworld CMake Error: Cannot determine link language for target "helloworld". </code></pre> <p>However, if I change the extension of main.cpp to main.c both on my filsystem and in <code>src/CMakeLists.txt</code> everything works as expected. This is the case running from both the Visual Studio Command Prompt (Visual Studio Solution Generator) and the Cygwin Terminal (Unix Makefiles Generator).</p> <p>Any idea why this code wouldn't work?</p> <p>CMakeLists.txt</p> <pre><code>PROJECT(HelloWorld C) cmake_minimum_required(VERSION 2.8) # include the cmake modules directory set(CMAKE_MODULE_PATH ${HelloWorld_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH}) add_subdirectory(src) </code></pre> <p>src/CMakeLists.txt</p> <pre><code># Include the directory itself as a path to include directories set(CMAKE_INCLUDE_CURRENT_DIR ON) # Create a variable called helloworld_SOURCES containing all .cpp files: set(HelloWorld_SOURCES main.cpp) # Create an executable file called helloworld from sources: add_executable(hello ${HelloWorld_SOURCES }) </code></pre> <p>src/main.cpp</p> <pre><code>int main() { return 0; } </code></pre>
11,802,004
10
3
null
2012-08-03 18:19:06.08 UTC
19
2022-09-17 06:05:44.897 UTC
2012-08-03 18:31:29.267 UTC
null
374,691
null
374,691
null
1
123
c++|c|cmake
200,467
<p>Try changing</p> <pre><code>PROJECT(HelloWorld C) </code></pre> <p>into</p> <pre><code>PROJECT(HelloWorld C CXX) </code></pre> <p>or just</p> <pre><code>PROJECT(HelloWorld) </code></pre> <p>See: <a href="https://cmake.org/cmake/help/latest/command/project.html" rel="nofollow noreferrer">https://cmake.org/cmake/help/latest/command/project.html</a></p>
11,876,238
Simple Pivot Table to Count Unique Values
<p>This seems like a simple Pivot Table to learn with. I would like to do a count of unique values for a particular value I'm grouping on.</p> <p>For instance, I have this:</p> <pre><code>ABC 123 ABC 123 ABC 123 DEF 456 DEF 567 DEF 456 DEF 456 </code></pre> <p>What I want is a pivot table that shows me this:</p> <pre><code>ABC 1 DEF 2 </code></pre> <p>The simple pivot table that I create just gives me this (a count of how many rows):</p> <pre><code>ABC 3 DEF 4 </code></pre> <p>But I want the number of unique values instead.</p> <p>What I'm really trying to do is find out which values in the first column don't have the same value in the second column for all rows. In other words, "ABC" is "good", "DEF" is "bad"</p> <p>I'm sure there is an easier way to do it but thought I'd give pivot table a try...</p>
11,876,301
16
1
null
2012-08-09 03:09:56.63 UTC
44
2021-01-12 09:35:45.797 UTC
2014-03-07 04:49:47.443 UTC
null
641,067
null
1,586,422
null
1
139
excel|excel-formula|pivot-table
886,889
<p>Insert a 3rd column and in Cell <code>C2</code> paste this formula</p> <pre><code>=IF(SUMPRODUCT(($A$2:$A2=A2)*($B$2:$B2=B2))&gt;1,0,1) </code></pre> <p>and copy it down. Now create your pivot based on 1st and 3rd column. See snapshot</p> <p><img src="https://i.stack.imgur.com/B0DTk.png" alt="enter image description here"></p>
20,310,000
error: ISO C++ forbids in-class initialization of non-const static member
<p>this is the header file: employee.h</p> <pre><code>#ifndef EMPLOYEE_H #define EMPLOYEE_H #include &lt;iostream&gt; #include &lt;string&gt; using namespace std; class Employee { public: Employee(const string &amp;first, const string &amp;last) </code></pre> <p>Overloaded Constructor</p> <pre><code> : firstName(first), </code></pre> <p>firstName overloaded constructor</p> <pre><code> lastName(last) </code></pre> <p>lastName overloaded constructor </p> <pre><code> { //The constructor start ++counter; </code></pre> <p>it adds one plus per each object created; </p> <pre><code> cout &lt;&lt; "Employee constructor for " &lt;&lt; firstName &lt;&lt; ' ' &lt;&lt; lastName &lt;&lt; " called." &lt;&lt; endl; } ~Employee() { </code></pre> <p>Destructor cout &lt;&lt; "~Employee() called for " &lt;&lt; firstName &lt;&lt; ' ' &lt;&lt; lastName &lt;&lt; endl; </p> <p>Returns the first and last name of each object</p> <pre><code> --counter; </code></pre> <p>Counter minus one</p> <pre><code> } string getFirstName() const { return firstName; } string getLastName() const { return lastName; } static int getCount() { return counter; } private: string firstName; string lastName; static int counter = 0; </code></pre> <p>Here is where i got the error. But, why?</p> <pre><code>}; </code></pre> <p>principal program: employee2.cpp</p> <pre><code>#include &lt;iostream&gt; #include "employee2.h" using namespace std; int main() { cout &lt;&lt; "Number of employees before instantiation of any objects is " &lt;&lt; Employee::getCount() &lt;&lt; endl; </code></pre> <p>Here ir call te counter's value from the class</p> <pre><code> { </code></pre> <p>Start a new scope block</p> <pre><code> Employee e1("Susan", "Bkaer"); </code></pre> <p>Initialize the e1 object from Employee class</p> <pre><code> Employee e2("Robert", "Jones"); </code></pre> <p>Initialize the e2 object from Employee class</p> <pre><code> cout &lt;&lt; "Number of employees after objects are instantiated is" &lt;&lt; Employee::getCount(); cout &lt;&lt; "\n\nEmployee 1: " &lt;&lt; e1.getFirstName() &lt;&lt; " " &lt;&lt; e1.getLastName() &lt;&lt; "\nEmployee 2: " &lt;&lt; e2.getFirstName() &lt;&lt; " " &lt;&lt; e2.getLastName() &lt;&lt; "\n\n"; } </code></pre> <p>end the scope block</p> <pre><code> cout &lt;&lt; "\nNUmber of employees after objects are deleted is " &lt;&lt; Employee::getCount() &lt;&lt; endl; //shows the counter's value } //End of Main </code></pre> <p>What is the problem? I have no idea what's wrong. I have been thinking a lot, but a i do not what is wrong.</p>
20,310,041
2
5
null
2013-12-01 07:56:33.547 UTC
5
2020-03-13 22:26:59.927 UTC
null
null
null
null
3,053,929
null
1
22
c++|static|compiler-errors|standards|iso
58,558
<p>The <em>initialization</em> of the static member <code>counter</code> must not be in the header file. </p> <p>Change the line in the header file to</p> <pre><code>static int counter; </code></pre> <p>And add the following line to your employee.cpp:</p> <pre><code>int Employee::counter = 0; </code></pre> <p>Reason is that putting such an initialization in the header file would duplicate the initialization code in every place where the header is included. </p>
3,917,601
ffmpeg split avi into frames with known frame rate
<p>I posted this as comments under <a href="https://stackoverflow.com/questions/3002601/converting-avi-frames-to-jpgs-on-linux">this related thread</a>. However, they seem to have gone unnoticed =(</p> <p>I've used</p> <pre><code>ffmpeg -i myfile.avi -f image2 image-%05d.bmp </code></pre> <p>to split <code>myfile.avi</code> into frames stored as <code>.bmp</code> files. It seemed to work except not quite. When recording my video, I recorded at a rate of <code>1000fps</code> and the video turned out to be <code>2min29sec</code> long. If my math is correct, that should amount to a total of <strong>149,000 frames</strong> for the entire video. However, when I ran</p> <pre><code>ffmpeg -i myfile.avi -f image2 image-%05d.bmp </code></pre> <p>I only obtained 4472 files. How can I get the original 149k frames?</p> <p>I also tried to convert the frame rate of my original AVI to 1000fps by doing</p> <pre><code>ffmpeg -i myfile.avi -r 1000 otherfile.avi </code></pre> <p>but this didn't seem to fix my concern.</p>
3,917,648
4
0
null
2010-10-12 18:01:14.4 UTC
10
2020-12-01 07:45:42.36 UTC
2017-05-23 10:31:15.87 UTC
null
-1
null
278,793
null
1
26
linux|image-processing|ffmpeg
47,173
<pre><code>ffmpeg -i myfile.avi -r 1000 -f image2 image-%07d.png </code></pre> <p>I am not sure outputting 150k bmp files will be a good idea. Perhaps png is good enough?</p>
3,641,671
The user instance login flag is not supported on this version of SQL Server. The connection will be closed
<p>Hi I am using sql server fulll edition.</p> <p>any idea how should I solve this issue, I search on net but not found any helpful answer.</p> <p>Thanks</p>
3,641,691
4
1
null
2010-09-04 09:35:59.417 UTC
5
2010-09-04 09:39:55.417 UTC
null
null
null
null
479,291
null
1
30
asp.net
42,801
<p>SQL Server 2005(Full Version) does not support the "user instance"(automatic creation of databases from code) directive in the connection string. Its a feature of sql server express edition.</p> <p>Also if your connection string has user Instance attribute, then try removing the "User Instance=True;" </p>
3,993,759
PHP: how to get a list of classes that implement certain interface?
<p>I've got an interface</p> <pre><code>interface IModule { public function Install(); } </code></pre> <p>and some classes that implement this interface</p> <pre><code>class Module1 implements IModule { public function Install() { return true; } } class Module2 implements IModule { public function Install() { return true; } } ... class ModuleN implements IModule { public function Install() { return true; } } </code></pre> <p>How to get a list of all classes that implement this interface? I'd like to get this list with PHP.</p>
3,993,796
5
1
null
2010-10-22 03:54:56.847 UTC
11
2022-05-12 10:22:58.59 UTC
2010-10-22 04:08:12.453 UTC
null
244,415
null
244,415
null
1
48
php|oop|class
27,293
<p>You can use PHP's <a href="http://us3.php.net/manual/en/reflectionclass.implementsinterface.php" rel="noreferrer"><code>ReflectionClass::implementsInterface</code></a> and <a href="http://php.net/manual/en/function.get-declared-classes.php" rel="noreferrer"><code>get_declared_classes</code></a> functions to accomplish this:</p> <pre><code>$classes = get_declared_classes(); $implementsIModule = array(); foreach($classes as $klass) { $reflect = new ReflectionClass($klass); if($reflect-&gt;implementsInterface('IModule')) $implementsIModule[] = $klass; } </code></pre>
3,267,213
Send email from rails console
<p>I'm trying to send out some mails from the console on my production server, and they're not going out. I can't work out why. I have just your standard email setup with sendmail. When I call the Mailer.deliver_ method I get this back:</p> <pre><code>#&lt;TMail::Mail port=#&lt;TMail::StringPort:id=0x3fe1c205dbcc&gt; bodyport=#&lt;TMail::StringPort:id=0x3fe1c2059e00&gt;&gt; </code></pre> <p>Added some more info:</p> <p>So, for example, I have this line in my controller when a new user signs up, to send them a &quot;welcome&quot; email:</p> <pre><code> Mailer.deliver_signup(@user, request.host_with_port, params[:user][:password]) </code></pre> <p>This works fine. I thought that I should be able to do the same thing from the console, eg</p> <pre><code>user = User.find(1) Mailer.deliver_signup(user, &quot;mydomainname.example&quot;, &quot;password&quot;) </code></pre> <p>When I do this, I get the Tmail::StringPort object back, but the mail appears to not get sent out (i'm trying to send emails to myself to test this).</p> <p>I'm on an Ubuntu server in case that helps. thanks - max</p>
26,994,273
5
2
null
2010-07-16 16:58:37.517 UTC
18
2022-06-21 19:56:03.63 UTC
2022-06-21 19:56:03.63 UTC
null
1,145,388
null
138,557
null
1
74
ruby-on-rails|sendmail
49,425
<p>For Sending email from Rails Console first we have to execute this setting in console for action mailer settings.</p> <pre><code>ActionMailer::Base.delivery_method = :smtp ActionMailer::Base.smtp_settings = { address: 'smtp.gmail.com', port: 587, domain: 'gmail.com', authentication: 'plain', enable_starttls_auto: true, user_name: '[email protected]', password: 'yourpassword' } </code></pre> <p>After that If we execute email sending code it will deliver email.</p> <pre><code>UserMailer.activation_instructions(@user).deliver_now </code></pre>
3,633,621
How does Chrome know my geolocation?
<p>Chrome seems to be very accurate in detecting my location. How does it do it? Can you point me to the source code?</p>
3,633,675
6
1
null
2010-09-03 06:57:31.67 UTC
9
2016-03-03 15:09:15.177 UTC
2010-09-03 07:03:29.223 UTC
null
11,125
null
11,125
null
1
26
html|google-chrome|geolocation
20,915
<p>Geolocation can be calculated based on:</p> <ol> <li>GPS (if available)</li> <li>Available wi-fi networks and signal strengths</li> <li>Available cell towers and signal strengths</li> <li>IP Address lookup</li> </ol> <p>See the <a href="http://dev.w3.org/geo/api/spec-source.html" rel="noreferrer">W3C Geolocaton API</a> and <a href="http://code.google.com/apis/gears/api_geolocation.html" rel="noreferrer">Google Gears API</a> (which Chrome's/W3C Geolocation API is based on).</p> <p><a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/browser/geolocation/" rel="noreferrer">Chromium's geolocation source code</a> can be viewed online.</p>
3,932,230
Oracle: SQL query that returns rows with only numeric values
<p>I have a field (column in Oracle) called X that has values like "a1b2c3", "abc", "1ab", "123", "156"</p> <p>how do I write an sql query that returns me only the X that hold pure numerical values = no letters? from the example above would be „123“ and „156“</p> <p>select X from myTable where ...??</p>
3,932,261
6
0
null
2010-10-14 10:32:57.587 UTC
20
2021-07-21 07:07:44.847 UTC
2010-10-14 10:34:53.107 UTC
null
21,234
null
26,817
null
1
46
sql|oracle
211,871
<p>You can use the <code>REGEXP_LIKE</code> function as:</p> <pre><code>SELECT X FROM myTable WHERE REGEXP_LIKE(X, '^[[:digit:]]+$'); </code></pre> <p>Sample run:</p> <pre><code>SQL&gt; SELECT X FROM SO; X -------------------- 12c 123 abc a12 SQL&gt; SELECT X FROM SO WHERE REGEXP_LIKE(X, '^[[:digit:]]+$'); X -------------------- 123 SQL&gt; </code></pre>
3,426,089
Fill ComboBox with List of available Fonts
<p>How can I fill a combo-box with a list of all the available fonts in the system?</p>
3,426,133
7
2
null
2010-08-06 17:14:28.86 UTC
4
2020-07-04 06:35:38.093 UTC
2010-08-07 00:31:42.303 UTC
null
158,455
null
158,455
null
1
48
c#|winforms|fonts|windows-xp
47,506
<p>You can use <code>System.Drawing.FontFamily.Families</code> to get the available fonts.</p> <pre><code>List&lt;string&gt; fonts = new List&lt;string&gt;(); foreach (FontFamily font in System.Drawing.FontFamily.Families) { fonts.Add(font.Name); } // add the fonts to your ComboBox here </code></pre>
3,666,306
How to iterate UTF-8 string in PHP?
<p>How to iterate a UTF-8 string character by character using indexing?</p> <p>When you access a UTF-8 string with the bracket operator <code>$str[0]</code> the utf-encoded character consists of 2 or more elements. </p> <p>For example:</p> <pre><code>$str = "Kąt"; $str[0] = "K"; $str[1] = "�"; $str[2] = "�"; $str[3] = "t"; </code></pre> <p>but I would like to have:</p> <pre><code>$str[0] = "K"; $str[1] = "ą"; $str[2] = "t"; </code></pre> <p>It is possible with <code>mb_substr</code> but this is extremely slow, ie.</p> <pre><code>mb_substr($str, 0, 1) = "K" mb_substr($str, 1, 1) = "ą" mb_substr($str, 2, 1) = "t" </code></pre> <p>Is there another way to interate the string character by character without using <code>mb_substr</code>?</p>
3,666,326
7
8
null
2010-09-08 09:27:39.177 UTC
21
2019-09-12 19:36:24.93 UTC
null
null
null
null
139,594
null
1
52
php|utf-8
19,061
<p>Use <a href="http://www.php.net/manual/en/function.preg-split.php" rel="noreferrer">preg_split</a>. With <a href="http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php" rel="noreferrer">"u" modifier</a> it supports UTF-8 unicode.</p> <pre><code>$chrArray = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY); </code></pre>
3,989,122
Microsoft.Office.Interop.Excel really slow
<p>I am exporting a 1200 X 800 matrix (indexMatrix) to a excel file using the standard Microsoft.Office.Interop.Excel. The app works, just that it is really really really slow( even for the 100 x 100 matrix) . I also export in a text file through a TextWriter an it works almost instantly . Is there any way to export to the excel file faster? </p> <p>Here is my code :</p> <pre><code> Excel.Application xlApp=new Excel.Application(); Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; //xlApp = new Excel.ApplicationClass(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); for (int i = 0; i &lt; 800; i++) //h for (int j = 0; j &lt; 1200; j++) xlWorkSheet.Cells[i+1,j+1] =indexMatrix[i][j]; xlWorkBook.SaveAs("C:\\a.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls"); </code></pre>
3,989,452
8
0
null
2010-10-21 15:28:40.783 UTC
21
2019-11-08 06:03:53.397 UTC
2010-10-21 15:39:12.38 UTC
null
47,550
null
476,024
null
1
48
c#|excel|interop
53,045
<p>You are updating individual cells. That's going to be very slow. If you think about it, each time you update a cell, an RPC call will be marshalled to the Excel process.</p> <p>It will be <strong>much</strong> faster if you assign your two dimensional array of values to an Excel Range of the same dimensions in a single statement (one cross-process call) instead of your current 1200 x 800 = 960,000 cross-process calls.</p> <p>Something like:</p> <pre><code>// Get dimensions of the 2-d array int rowCount = indexMatrix.GetLength(0); int columnCount = indexMatrix.GetLength(1); // Get an Excel Range of the same dimensions Excel.Range range = (Excel.Range) xlWorkSheet.Cells[1,1]; range = range.get_Resize(rowCount, columnCount); // Assign the 2-d array to the Excel Range range.set_Value(Excel.XlRangeValueDataType.xlRangeValueDefault, indexMatrix); </code></pre> <p>Actually, to be pedantic, there are three cross-process calls in the above code (.Cells, .get_Resize and .set_Value), and there are two calls per iteration in your code (.Cells get and an implicit .set_Value) for a total of 1200 x 800 x 2 = 1,920,000.</p> <p><strong>Note</strong> <code>range.get_Resize</code> and <code>range.set_Value</code> were needed for an old version of the Excel interop library I was using when this post was first authored. These days you can use <code>range.Resize</code> and <code>range.Value</code> as noted in the comment by @The1nk.</p>
3,483,514
Why is client-side validation not enough?
<p>I saw <a href="http://livevalidation.com/examples" rel="noreferrer">here</a> that:</p> <blockquote> <p>As you probably already know, relying on client-side validation alone is a very bad idea. Always perform appropriate server-side validation as well.</p> </blockquote> <p>Could you explain why server-side validation is a must?</p>
3,483,524
14
5
null
2010-08-14 13:31:40.307 UTC
13
2013-08-10 14:46:45.977 UTC
2013-06-25 23:42:31.62 UTC
null
247,243
null
247,243
null
1
41
validation|server-side|client-side-validation
12,544
<p>Client-side validation - I assume you are talking about web pages here - relies on <a href="http://en.wikipedia.org/wiki/Javascript" rel="noreferrer">JavaScript</a>. </p> <p>JavaScript powered validation can be turned off in the user's browser, fail due to a scripting error, or be maliciously circumvented without much effort. </p> <p>Also, the whole process of form submission can be faked. </p> <p>Therefore, there is never a guarantee that what arrives server side, is clean and safe data. </p>
8,262,884
Python C extension: Use extension PYD or DLL?
<p>I have a Python extension written in C and I wonder if I should use the file extension DLL or PYD under Windows. (And what would I use in Linux?)</p> <p>Are there any differences (besides the filename)?</p> <p>I found <a href="http://pyfaq.infogami.com/is-a-pyd-file-the-same-as-a-dll" rel="noreferrer">an unofficial article</a>. Is this the secret of pyc? Why can't I find any official article on this topic?</p>
8,471,102
4
1
null
2011-11-24 22:03:18.203 UTC
11
2020-08-21 22:59:07.377 UTC
2011-12-15 13:17:37.92 UTC
null
667,301
null
672,848
null
1
30
python|python-c-extension|pyd
30,834
<p>pyd files are just dll files ready for python importing.</p> <p>To distinguish them from normal dlls, I recommend .pyd not .dll in windows.</p> <p>Here is the official doc about this issue:</p> <p><a href="http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll" rel="noreferrer">http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll</a></p>
7,709,928
JAXB vs DOM and SAX
<p>I have been using DOM for parsing my small xml docs for sometime.Afer reading about the JAXB (<a href="http://www.oracle.com/technetwork/articles/javase/index-140168.html" rel="noreferrer">http://www.oracle.com/technetwork/articles/javase/index-140168.html</a>), I'm planning to use JAXB instaed of DOM.</p> <p>Please let me know if this will be a right approach.</p>
7,710,721
6
0
null
2011-10-10 07:58:14.74 UTC
15
2017-07-27 21:58:42.807 UTC
2012-04-11 10:45:03.587 UTC
null
1,106,053
null
987,265
null
1
27
java|xml|performance|jaxb
56,043
<p>JAXB is not directly comparable to DOM and SAX. The Java DOM and SAX parsing APIs are lower-level APIs to parse XML documents, while JAXB (Java API for XML Binding) is a higher-level API for converting XML elements and attributes to a Java object hierarchy (and vice versa). Implementations of JAXB will most likely use a DOM or SAX parser behind the scenes to do the actual parsing of the XML input data.</p> <p>Often you'll want to convert the content of an XML document into objects in your Java program. If this is what you want to do, then JAXB will probably be easier to use and you'll need to write less code than when you would be using the DOM or SAX parsing API.</p> <p>Whether it's the right approach for your case depends on exactly what the functional and technical requirements are for your project.</p>
7,748,137
Is it possible to select text on a Windows form label?
<p>Is it possible to highlight/select part of text in a Windows Form label control? I know its possible with RTFtextbox control but that using that control would be overkill as I need to create many instances of the label.</p>
7,748,496
7
3
null
2011-10-13 00:31:30.35 UTC
4
2020-03-11 23:10:25.43 UTC
2011-10-13 01:41:59.8 UTC
null
591,656
null
934,257
null
1
71
c#|.net|asp.net|winforms|label
54,610
<p>Is it possible to select text on a Windows form label? - NO (At least no easy way without overriding Label.Paint method)</p> <p>You can easily change a TextBox for this purpose.</p> <pre><code>TextBox1.Text = "Hello, Select Me"; TextBox1.ReadOnly = true; TextBox1.BorderStyle = 0; TextBox1.BackColor = this.BackColor; TextBox1.TabStop = false; TextBox1.Multiline = True; // If needed </code></pre> <p>Don't believe? here is an example for you.</p> <p><img src="https://i.stack.imgur.com/1M4wH.png" alt="enter image description here"></p> <p><strong>Option 2 (If you just want to enable copy label text)</strong></p> <p>Double clicking on the label copies the text to clipboard. This is the default winforms Label functionality. You can <a href="https://stackoverflow.com/a/9776120/591656">add a toolTip control</a> to improve the usability if you like. </p> <p><a href="https://i.stack.imgur.com/HVnb2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HVnb2.png" alt="enter image description here"></a></p>
8,105,688
"Expected a type" error pointing to the return type of a method
<p>I've attempted to compile, but every time I do, one method throws a strange "expected a type" error. I have a method in the header:</p> <pre><code>-(ANObject *)generateSomethingForSomethingElse:(NSString *)somethingElse; </code></pre> <p>The error points at the return type for this method. I've imported <code>ANObject</code> into the header using <code>#import "ANObject.h"</code> and <code>ANObject</code> is compiling fine..</p> <p>Why is this happening?</p>
8,226,397
9
3
null
2011-11-12 16:16:06.583 UTC
12
2022-01-20 16:11:29.15 UTC
2012-02-05 23:14:13.433 UTC
null
603,977
null
1,039,540
null
1
44
objective-c|xcode|cocoa|compilation|compiler-errors
62,986
<p>This is to do with the order that the source files are compiled in. You are already probably aware that you can't call a method before it is defined (see below pseudocode):</p> <pre><code>var value = someMethod(); function someMethod() { ... } </code></pre> <p>This would cause a compile-time error because someMethod() has not yet been defined. The same is true of classes. Classes are compiled one after the other by the compiler.</p> <p>So, if you imagine all the classes being put into a giant file before compilation, you might be able to already see the issue. Let's look at the <code>Ship</code> and <code>BoatYard</code> class:</p> <pre><code>@interface BoatYard : NSObject @property (nonatomic, retain) Ship* currentShip; @end @interface Ship : NSObject @property (nonatomic, retain) NSString* name; @property (nonatomic, assign) float weight; @end </code></pre> <p>Once again, because the <code>Ship</code> class has not yet been defined, we can't refer to it yet. Solving this particular problem is pretty simple; change the compilation order and compile. I'm sure you're familliar with this screen in XCode:</p> <p><a href="https://imgur.com/lfW1J" rel="noreferrer"><img src="https://i.imgur.com/lfW1J.png" alt="" title="Hosted by imgur.com" /></a></p> <p>But are you aware that you can drag the files up and down in the list? This changes the order that the files will be compiled in. Therefore, just move the <code>Ship</code> class above the <code>BoatYard</code> class, and all is good.</p> <p>But, what if you don't want to do that, or more importantly, what if there is a circular relationship between the two objects? Let's increase the complexity of that object diagram by adding a reference to the current <code>BoatYard</code> that the <code>Ship</code> is in:</p> <pre><code>@interface BoatYard : NSObject @property (nonatomic, retain) Ship* currentShip; @end @interface Ship : NSObject @property (nonatomic, retain) BoatYard* currentBoatYard; @property (nonatomic, retain) NSString* name; @property (nonatomic, assign) float weight; @end </code></pre> <p>Oh dear, now we have a problem. These two can't be compiled side-by-side. We need a way to inform the compiler that the Ship* class really does exist. And this is why the <code>@class</code> keyword is so handy. </p> <p>To put it in layman's terms, you're saying, "Trust me man, <code>Ship</code> really does exist, and you'll see it really soon". To put it all together:</p> <pre><code>@class Ship; @interface BoatYard : NSObject @property (nonatomic, retain) Ship* currentShip; @end @interface Ship : NSObject @property (nonatomic, retain) BoatYard* currentBoatYard; @property (nonatomic, retain) NSString* name; @property (nonatomic, assign) float weight; @end </code></pre> <p>Now the compiler knows as it compiles <code>BoatYard</code>, that a <code>Ship</code> class definition will soon appear. Of course, if it doesn't, the compilation will still succeed.</p> <p>All the <code>@class</code> keyword does however is inform the compiler that the class will soon come along. It is <strong>not</strong> a replacement for <code>#import</code>. You still must import the header file, or you will not have access to any of the class internals:</p> <pre><code>@class Ship -(void) example { Ship* newShip = [[Ship alloc] init]; } </code></pre> <p>This cannot work, and will fail with an error message saying that Ship is a forward declaration. Once you <code>#import "Ship.h"</code>, then you will be able to create the instance of the object.</p>
4,259,729
Updating a date format in MySQL
<p>I am working on a table that has two formats of dates stored in a field some are in <code>mm/dd/yy</code> and the newer entries are in <code>yyyy/mm/dd</code> like they should be.</p> <p>I want to run an query like this</p> <pre><code>UPDATE table SET date_field = DATE_FORMAT(date_field, '%Y/%m/%d') WHERE date_field = DATE_FORMAT(date_field, '%m/%d/%y') </code></pre> <p>But it is just not working out. One result that I got was that it was just taking the <code>%m</code> data and turning it into the <code>%Y</code> and really messing up the data.</p> <p>Any thoughts?</p>
4,259,791
3
1
null
2010-11-23 19:01:42.667 UTC
4
2021-04-15 00:14:55.683 UTC
2021-04-15 00:14:55.683 UTC
null
814,702
null
517,905
null
1
8
mysql|date-format
50,950
<p>You want to use STR_TO_DATE function, not DATE_FORMAT. Plus, I assume you only want to update the misformed dates, so I guess you could do this :</p> <pre><code>UPDATE your_table SET date_field = DATE(STR_TO_DATE(date_field, '%m/%d/%Y')) WHERE DATE(STR_TO_DATE(date_field, '%m/%d/%Y')) &lt;&gt; '0000-00-00'; </code></pre> <p>P.S. Tables contain <em>columns</em>, not fields. And you shouldn't use a string type to hold your dates, but the DATE type</p>
4,138,277
Error in IE when manually calling event handler, given certain conditions
<h2>Preface</h2> <ul> <li>Please note, I'm not looking for a code solution, but rather insight into why this may occur.</li> <li>The error occurs in IE (tested 7 &amp; 8), but not Firefox, Chrome, Safari.</li> </ul> <h2>Description</h2> <p>When manually calling a function assigned to <code>onclick</code>, IE with throw a <code>Error: Object doesn't support this action</code> if <em>all of the following conditions</em> are met:</p> <ol> <li>You call the method directly via the element's <code>on[event]</code> property.</li> <li>You do not use <code>.call()</code> or <code>.apply()</code>.</li> <li>You pass an argument (any argument, even <code>undefined</code>).</li> <li>You attempt to assign the return value to a variable.</li> </ol> <p>Violate any one of those rules, and the call succeeds.</p> <p>The function itself appears to have nothing to do with it. An empty function gives the same result.</p> <h2>Code</h2> <pre><code>var elem = document.getElementById('test'); // simple div element. var result; // store result returned. function test_func(){}; // function declaration. // function expression behaves identically. elem.onclick = test_func; // assign test_func to element's onclick. // DIRECT CALL test_func(); // works test_func( true ); // works result = test_func(); // works result = test_func( true ); // works // DIRECT CALL, CHANGING THE CONTEXT TO THE ELEMENT test_func.call( elem ); // works test_func.call( elem, true ); // works result = test_func.call( elem ); // works result = test_func.call( elem, true ); // works ******** (surprising) // CALL VIA ELEMENT, USING .call() METHOD, CHANGING THE CONTEXT TO THE ELEMENT elem.onclick.call( elem ); // works elem.onclick.call( elem, true ); // works result = elem.onclick.call( elem ); // works result = elem.onclick.call( elem, true ); // works ******** ( very surprising) // CALL VIA ELEMENT elem.onclick(); // works elem.onclick( true ); // works result = elem.onclick(); // works result = elem.onclick( true ); // Error: Object doesn't support this action </code></pre> <h2>Summary</h2> <p>Again, I don't need a code solution. Rather I'm curious if anyone has insight into why IE is implemented this way.</p> <p>Many thanks.</p> <hr> <p><strong>EDIT:</strong> To clarify one thing, nothing with the actual function seems to make any difference. Naming parameters, not naming them, returning the argument, returning a literal value, returning undefined, all of these have no effect.</p> <p>This is likely because the function seems to never actually get called. As I noted in a comment below, the code leading up to this call runs fine, so it isn't a parsing issue either. But when the interpreter gets to this one, it sees:</p> <blockquote> <p>Variable + AssignmentOperator + DOMElement + EventHandler + CallOperator + Argument</p> </blockquote> <p>...and throws the Error. No manipulation I do seems to make any difference. A valid removal of any one of those, and the Error disappears.</p> <p>If I place add a variable to the middle of it that stores the handler, then fire it from the variable it works.</p> <pre><code>var temp = elem.onclick; result = temp( true ); // works </code></pre> <p>...but this shouldn't be much of a surprise, since it is effectively the same as the fourth version above.</p>
4,177,240
3
25
null
2010-11-09 20:30:40.173 UTC
11
2011-10-10 09:34:52.473 UTC
2010-11-10 02:14:47.193 UTC
null
113,716
null
113,716
null
1
15
javascript|internet-explorer|event-handling
3,551
<p>As to "why" it was implemented this way, there's probably no answer from the outside. A good example is when former IE developer, the inventor of innerHTML, faces <a href="http://www.ericvasilik.com/2006/07/code-karma.html" rel="nofollow">problems</a> with innerHTML itself.</p> <p>Asking why is also unnecessary because </p> <ol> <li>You don't often call event handlers with parameters explicitly</li> <li>You can work around the issue (as you stated in your question)</li> </ol> <p>Another thing to note is that your analogy is too specific. The issue is not restricted to the <em><code>assignment expression</code></em>, you can reproduce it with other types of <em><code>expressions</code></em>:</p> <pre><code>undefined === elem.onclick( true ) typeof elem.onclick( true ) elem.onclick( true ) - 1 alert(elem.onclick( true )) </code></pre>
4,184,108
python: json.dumps can't handle utf-8?
<p>Below is the test program, including a Chinese character:</p> <pre><code># -*- coding: utf-8 -*- import json j = {"d":"中", "e":"a"} json = json.dumps(j, encoding="utf-8") print json </code></pre> <p>Below is the result, look the json.dumps convert the utf-8 to the original numbers!</p> <pre><code>{"e": "a", "d": "\u4e2d"} </code></pre> <p>Why this is broken? Or anything I am wrong?</p>
4,184,289
3
4
null
2010-11-15 12:00:16.523 UTC
4
2016-06-15 20:40:50.113 UTC
null
null
null
null
197,036
null
1
21
python|json
39,559
<p>You should read <a href="http://json.org" rel="noreferrer">json.org</a>. The complete JSON specification is in the white box on the right.</p> <p>There is nothing wrong with the generated JSON. Generators are allowed to genereate either UTF-8 strings or plain ASCII strings, where characters are escaped with the <code>\uXXXX</code> notation. In your case, the Python <code>json</code> module decided for escaping, and <code>中</code> has the escaped notation <a href="http://codepoints.net/U+4e2d" rel="noreferrer"><code>\u4e2d</code></a>.</p> <p>By the way: Any conforming JSON interpreter will correctly unescape this sequence again and give you back the actual character.</p>
4,489,976
XPath to return default value if node not present
<p>Say I have a pair of XML documents</p> <pre><code>&lt;Foo&gt; &lt;Bar/&gt; &lt;Baz&gt;mystring&lt;/Baz&gt; &lt;/Foo&gt; </code></pre> <p>and</p> <pre><code>&lt;Foo&gt; &lt;Bar/&gt; &lt;/Foo&gt; </code></pre> <p>I want an XPath (Version 1.0 only) that returns "mystring" for the first document and "not-found" for the second. I tried </p> <pre><code>(string('not-found') | //Baz)[last()] </code></pre> <p>but the left hand side of the union isn't a node-set</p>
4,490,667
5
0
null
2010-12-20 13:16:08.773 UTC
9
2020-06-04 20:05:07.253 UTC
2010-12-20 13:48:13.353 UTC
null
135,624
null
135,624
null
1
17
xpath
22,878
<p>In XPath 1.0, use:</p> <pre><code>concat(/Foo/Baz, substring('not-found', 1 div not(/Foo/Baz))) </code></pre> <p>If you want to handle the posible empty <code>Baz</code> element, use:</p> <pre><code>concat(/Foo/Baz, substring('not-found', 1 div not(/Foo/Baz[node()]))) </code></pre> <p>With this input:</p> <pre><code>&lt;Foo&gt; &lt;Baz/&gt; &lt;/Foo&gt; </code></pre> <p>Result: <code>not-found</code> string data type.</p>
4,118,123
Read a very large text file into a list in clojure
<p>What is the best way to read a very large file (like a text file having 100 000 names one on each line) into a list (lazily - loading it as needed) in clojure?</p> <p>Basically I need to do all sorts of string searches on these items (I do it with grep and reg ex in shell scripts now). </p> <p>I tried adding '( at the beginning and ) at the end but apparently this method (loading a static?/constant list, has a size limitation for some reason.</p>
4,118,289
5
0
null
2010-11-07 14:23:57.563 UTC
11
2020-12-15 16:02:51.653 UTC
null
null
null
null
487,855
null
1
28
file|text|clojure
16,807
<p>You need to use <a href="http://clojuredocs.org/clojure_core/clojure.core/line-seq"><code>line-seq</code></a>. An example from clojuredocs:</p> <pre><code>;; Count lines of a file (loses head): user=&gt; (with-open [rdr (clojure.java.io/reader "/etc/passwd")] (count (line-seq rdr))) </code></pre> <p>But with a lazy list of strings, you cannot do those operations efficiently which require the whole list to be present, like sorting. If you can implement your operations as <code>filter</code> or <code>map</code> then you can consume the list lazily. Otherwise it'll be better to use an embedded database. </p> <p>Also note that you should not hold on to the head of the list, otherwise the whole list will be loaded in memory.</p> <p>Furthermore, if you need to do more than one operation, you'll need to read the file again and again. Be warned, laziness can make things difficult sometimes.</p>
4,149,415
OnScreen keyboard opens automatically when Activity starts
<p>When my Activity with a <code>ScrollView</code> layout and <code>EditText</code>s starts, the <code>EditText</code>s get focus and the Android OnScreen keyboard opens.</p> <p>How I can avoid that?</p> <p>When I was using <code>LinearLayout</code> and <code>RelativeLayout</code> without the <code>ScrollView</code> it doesn't happen.</p> <p>I've tried it this way, and it works, but it's not a good way to do it:</p> <pre><code>TextView TextFocus = (TextView) findViewById(R.id.MovileLabel); TextFocus.setFocusableInTouchMode(true); TextFocus.requestFocus(); </code></pre> <p>Next you have an example of some of my layouts with this problem, when this Activity starts, focus goes to the first <code>EditText</code>, <em>Description</em> and the Android keyboard opens automatically, this is very annoying.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ScrollView android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10px"&gt; &lt;RelativeLayout android:gravity="center_vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;TextView android:id="@+id/UserLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="13px" android:text="@string/userlabel"/&gt; &lt;TextView android:id="@+id/User" android:layout_alignBaseline="@id/UserLabel" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="test"/&gt; &lt;/RelativeLayout&gt; &lt;View android:layout_gravity="center_horizontal" android:layout_width="fill_parent" android:layout_height="1dip" android:background="#808080" android:layout_marginTop="5px" android:layout_marginBottom="12px"/&gt; &lt;RelativeLayout android:gravity="center_vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;TextView android:id="@+id/DescriptionLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/desclabel" android:layout_marginTop="13px"/&gt; &lt;EditText android:id="@+id/Description" android:layout_alignBaseline="@id/DescriptionLabel" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:width="180px"/&gt; &lt;/RelativeLayout&gt; &lt;RelativeLayout android:gravity="center_vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;TextView android:id="@+id/EmailLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/emaillabel" android:layout_marginTop="13px"/&gt; &lt;EditText android:id="@+id/Email" android:layout_alignBaseline="@+id/EmailLabel" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:width="180px"/&gt; &lt;/RelativeLayout&gt; &lt;RelativeLayout android:gravity="center_vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;TextView android:id="@+id/MovilePhoneLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/movilephonelabel" android:layout_marginTop="13px"/&gt; &lt;EditText android:id="@+id/MovilePhone" android:layout_alignBaseline="@+id/MovilePhoneLabel" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:width="180px"/&gt; &lt;/RelativeLayout&gt; &lt;View android:layout_gravity="center_horizontal" android:layout_width="fill_parent" android:layout_height="1dip" android:background="#808080" android:layout_marginTop="5px" android:layout_marginBottom="10px"/&gt; &lt;RelativeLayout android:gravity="center_vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;Button android:id="@+id/applybutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/apply" android:width="100px" android:layout_marginLeft="40dip"/&gt; &lt;Button android:id="@+id/cancelbutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/cancel" android:width="100px" android:layout_alignBaseline="@+id/applybutton" android:layout_alignParentRight="true" android:layout_marginRight="40dip"/&gt; &lt;/RelativeLayout&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; </code></pre>
4,150,363
5
1
null
2010-11-10 21:46:25.437 UTC
10
2019-06-11 05:02:19.033 UTC
2011-07-13 11:19:47.01 UTC
null
418,183
null
479,886
null
1
46
android|keyboard|focus|scrollview
35,331
<p>Android opens the OnScreenKeyboard automatically if you have an <code>EditText</code> focussed when the Activity starts.</p> <p>You can prevent that by adding following into your Activity's <code>onCreate</code> method.</p> <pre><code> getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); </code></pre>
4,131,091
dynamic_cast from "void *"
<p>According to <a href="https://stackoverflow.com/questions/3155277/cannot-dynamic-cast-void-to-templated-class">this</a>, <code>void*</code> has no RTTI information, therefore casting from <code>void*</code> is not legal and it make sense.</p> <p>If I remember correctly, <code>dynamic_cast</code> from <code>void*</code> was working on gcc. </p> <p>Can you please clarify the issue.</p>
4,131,099
6
0
null
2010-11-09 06:36:37.73 UTC
2
2020-02-25 17:43:19.9 UTC
2017-05-23 10:29:28.723 UTC
null
-1
null
135,960
null
1
42
c++|rtti|void-pointers|dynamic-cast
37,692
<p><code>dynamic_cast</code> works only on polymorphic types, i.e. classes containing virtual functions.</p> <p>In gcc you can <code>dynamic_cast</code> <strong>to</strong> <code>void*</code> but not <strong>from</strong>:</p> <pre><code>struct S { virtual ~S() {} }; int main() { S* p = new S(); void* v = dynamic_cast&lt;void*&gt;(p); S* p1 = dynamic_cast&lt;S*&gt;(v); // gives an error } </code></pre>
4,794,927
Why does this return Resource id #2?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4290108/how-do-i-echo-a-resource-id-6-from-a-mysql-response-in-php">How do i “echo” a “Resource id #6” from a MySql response in PHP?</a> </p> </blockquote> <p>I am new at php and SQL and I'm trying to make the php page list the numbers of enries in the table. I'm using this code but it returns Resource id #2:</p> <pre><code>$rt=mysql_query("SELECT COUNT(*) FROM persons"); echo mysql_error(); echo "&lt;h1&gt;Number:&lt;/h1&gt;".$rt; </code></pre>
4,794,959
7
0
null
2011-01-25 14:55:07.233 UTC
2
2011-01-25 15:16:27.79 UTC
2017-05-23 12:30:24.063 UTC
null
-1
null
551,924
null
1
11
php|sql|mysql
63,519
<p>Because you get a mysql ressource when you do a <a href="http://ch2.php.net/manual/en/function.mysql-query.php" rel="noreferrer"><code>mysql_query()</code></a>.</p> <p>Use something like <a href="http://ch2.php.net/mysql_fetch_assoc" rel="noreferrer"><code>mysql_fetch_assoc()</code></a> to get the next row. It returns an array with the column names as indices. In your case it's probably <code>COUNT(*)</code>.</p> <p>Here's a fix and some minor improvements of your snippet:</p> <pre><code>$rt = mysql_query("SELECT COUNT(*) FROM persons") or die(mysql_error()); $row = mysql_fetch_row($rt); if($row) echo "&lt;h1&gt;Number:&lt;/h1&gt;" . $row[0]; </code></pre> <p>If you need to get all rows of the resultset use this snippet:</p> <pre><code>while($row = mysql_fetch_assoc($rt)) { var_dump($row); } </code></pre>
4,656,802
midpoint between two latitude and longitude
<p>I am trying to convert the code snippet given in this <a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="noreferrer">http://www.movable-type.co.uk/scripts/latlong.html</a> into java. But I am not getting same result as that of site. Here is my code to find the midpoint between two points where their latitudes and longitudes are given</p> <pre><code>midPoint(12.870672,77.658964,12.974831,77.60935); public static void midPoint(double lat1,double lon1,double lat2,double lon2) { double dLon = Math.toRadians(lon2-lon1); double Bx = Math.cos(lat2) * Math.cos(dLon); double By = Math.cos(lat2) * Math.sin(dLon); double lat3 = Math.atan2(Math.sin(lat1)+Math.sin(lat2),Math.sqrt( (Math.cos(lat1)+Bx)*(Math.cos(lat1)+Bx) + By*By) ); double lon3 = lon1 + Math.atan2(By, Math.cos(lat1) + Bx); System.out.print(lat3 +" " + lon3 ); } </code></pre> <p>I am not sure whethe dLon is correct or not. So please help me guys to figure it out. P.S.I need to find the latitude and longitude of the midpoint</p>
4,656,937
7
0
null
2011-01-11 10:50:22.727 UTC
8
2020-12-09 07:52:48.71 UTC
2011-01-11 11:18:43.743 UTC
null
1,319,205
null
1,319,205
null
1
34
java|math|maps
41,007
<p>You need to convert to radians. Change it to the following:</p> <pre><code>public static void midPoint(double lat1,double lon1,double lat2,double lon2){ double dLon = Math.toRadians(lon2 - lon1); //convert to radians lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); lon1 = Math.toRadians(lon1); double Bx = Math.cos(lat2) * Math.cos(dLon); double By = Math.cos(lat2) * Math.sin(dLon); double lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt((Math.cos(lat1) + Bx) * (Math.cos(lat1) + Bx) + By * By)); double lon3 = lon1 + Math.atan2(By, Math.cos(lat1) + Bx); //print out in degrees System.out.println(Math.toDegrees(lat3) + " " + Math.toDegrees(lon3)); } </code></pre>
4,590,490
try/catch + using, right syntax
<p>Which one:</p> <pre><code>using (var myObject = new MyClass()) { try { // something here... } catch(Exception ex) { // Handle exception } } </code></pre> <p>OR</p> <pre><code>try { using (var myObject = new MyClass()) { // something here... } } catch(Exception ex) { // Handle exception } </code></pre>
4,590,518
9
3
null
2011-01-04 03:53:54.37 UTC
38
2020-08-03 10:14:41.983 UTC
null
null
null
null
313,421
null
1
222
c#|try-catch|using-statement
110,133
<p>I prefer the second one. May as well trap errors relating to the creation of the object as well.</p>
4,201,713
Synchronization vs Lock
<p><code>java.util.concurrent</code> API provides a class called as <code>Lock</code>, which would basically serialize the control in order to access the critical resource. It gives method such as <code>park()</code> and <code>unpark()</code>. </p> <p>We can do similar things if we can use <code>synchronized</code> keyword and using <code>wait()</code> and <code>notify() notifyAll()</code> methods. </p> <p>I am wondering which one of these is better in practice and why?</p>
4,201,734
10
1
null
2010-11-17 05:13:01.42 UTC
83
2020-08-18 18:18:11.92 UTC
2016-01-17 18:57:54.81 UTC
null
4,999,394
null
379,235
null
1
204
java|multithreading|concurrency|synchronization|java.util.concurrent
178,887
<p>If you're simply locking an object, I'd prefer to use <code>synchronized</code></p> <p>Example:</p> <pre><code>Lock.acquire(); doSomethingNifty(); // Throws a NPE! Lock.release(); // Oh noes, we never release the lock! </code></pre> <p>You have to explicitly do <code>try{} finally{}</code> everywhere.</p> <p>Whereas with synchronized, it's super clear and impossible to get wrong:</p> <pre><code>synchronized(myObject) { doSomethingNifty(); } </code></pre> <p>That said, <code>Lock</code>s may be more useful for more complicated things where you can't acquire and release in such a clean manner. I would honestly prefer to avoid using bare <code>Lock</code>s in the first place, and just go with a more sophisticated concurrency control such as a <code>CyclicBarrier</code> or a <code>LinkedBlockingQueue</code>, if they meet your needs.</p> <p>I've never had a reason to use <code>wait()</code> or <code>notify()</code> but there may be some good ones.</p>