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
31,034,847
How to find all rows with a NULL value in any column using PostgreSQL
<p>There are many <em>slightly similar</em> questions, but none solve precisely this problem. "<a href="https://stackoverflow.com/questions/14488859/find-all-rows-with-null-values-in-any-column">Find All Rows With Null Value(s) in Any Column</a>" is the closest one I could find and offers an answer for SQL Server, but I'm looking for a way to do this in PostgreSQL. </p> <p>How can I select only the rows that have NULL values in <em>any</em> column?</p> <p>I can get all the column names easily enough:</p> <pre><code>select column_name from information_schema.columns where table_name = 'A'; </code></pre> <p>but it's unclear how to check multiple column names for NULL values. Obviously this won't work:</p> <pre><code>select* from A where ( select column_name from information_schema.columns where table_name = 'A'; ) IS NULL; </code></pre> <p>And <a href="https://www.google.com/search?q=postgres+check+multiple+columns+for+null+values&amp;oq=postgres+check+multiple+columns+for+null+values&amp;aqs=chrome..69i57.22589j0j7&amp;sourceid=chrome&amp;es_sm=91&amp;ie=UTF-8#newwindow=1&amp;q=postgres+SQL+check+multiple+columns+for+null+values" rel="noreferrer">searching</a> has not turned up anything useful.</p>
31,035,052
1
2
null
2015-06-24 19:01:56.413 UTC
13
2017-06-09 23:53:58.963 UTC
2017-06-09 23:53:58.963 UTC
null
128,421
null
241,142
null
1
32
sql|postgresql
38,043
<p>You can use <code>NOT(&lt;table&gt; IS NOT NULL)</code>.</p> <p>From <a href="http://www.postgresql.org/docs/9.4/static/functions-comparison.html" rel="noreferrer">the documentation</a> :</p> <blockquote> <p>If the expression is row-valued, then IS NULL is true when the row expression itself is null or when all the row's fields are null, while IS NOT NULL is true when the row expression itself is non-null and all the row's fields are non-null.</p> </blockquote> <p>So :</p> <pre><code>SELECT * FROM t; β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ f1 β”‚ f2 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ (null) β”‚ 1 β”‚ β”‚ 2 β”‚ (null) β”‚ β”‚ (null) β”‚ (null) β”‚ β”‚ 3 β”‚ 4 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (4 rows) SELECT * FROM t WHERE NOT (t IS NOT NULL); β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ f1 β”‚ f2 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ (null) β”‚ 1 β”‚ β”‚ 2 β”‚ (null) β”‚ β”‚ (null) β”‚ (null) β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (3 rows) </code></pre>
13,350,036
C# Charts add multiple series from datatable
<p>I retrieve several datatables from my DB, which vary in size. This one of 2 is just an example.</p> <p>See the structure here! <br><img src="https://i.stack.imgur.com/iHIBF.png" alt="enter image description here"> <br> I managed to create the 2 different series and have them show up on the legend. </p> <p>My question is on how to bind that data to the respective series. The series name are created from column doman_namn and the amount of series are created from the "antal" column which holds the number of unique URLS. </p> <p><strong>QUESTION</strong> HOW TO BIND ADDY and ADDX to the chart it fails now.</p> <p>This is my code so far...</p> <pre><code>Chart1.DataSource = dt; int amountofrows = Convert.ToInt32(dt.Rows[0]["antal"].ToString()); for (int i = 0; i &lt; amountofrows; i++) { string serieName = dt.Rows[i]["doman_namn"].ToString(); Chart1.Series.Add(serieName); Chart1.Series[i].ChartType = SeriesChartType.Line; foreach(DataRow dr in dt.Rows) { try { if (String.Equals(serieName,dr["doman_namn"].ToString(), StringComparison.Ordinal)) { Chart1.Series[serieName].Points.AddY(Convert.ToDouble(dr["ranking_position"])); Chart1.Series[serieName].Points.AddY(Convert.ToDouble(dr["ranking_date"])); } } catch (Exception) { throw new InvalidOperationException("Failed when adding points"); } } } Chart1.DataBind(); Chart1.Visible = true; </code></pre> <p>CODE AFTER HELP FROM GREGOR<br></p> <pre><code>for (int i = 0; i &lt; amountofrows; i++) { string serieName = dt.Rows[i]["doman_namn"].ToString(); Chart1.Series.Add(serieName); Chart1.Series[i].ChartType = SeriesChartType.Line; Chart1.Series[serieName].XValueMember = "ranking_date"; Chart1.Series[serieName].YValueMembers = "ranking_position"; } Chart1.DataBind(); </code></pre>
13,352,323
3
2
null
2012-11-12 19:18:15.287 UTC
2
2020-10-25 15:55:53.723 UTC
2017-08-22 15:04:31.6 UTC
null
1,460,225
null
1,128,380
null
1
3
c#|charts
69,375
<p>I managed to do it myself, but you Gregor Primar pushed me in the right direction!</p> <p>What was important was that you set the valuetype for the X and Y-axis. As decimal type was not an option I used auto as type.</p> <pre><code>Chart1.DataSource = dt; int amountofrows = Convert.ToInt32(dt.Rows[0]["antal"].ToString()); for (int i = 0; i &lt; amountofrows; i++) { List&lt;string&gt; xvals = new List&lt;string&gt;(); List&lt;decimal&gt; yvals = new List&lt;decimal&gt;(); string serieName = dt.Rows[i]["doman_namn"].ToString(); Chart1.Series.Add(serieName); Chart1.Series[i].ChartType = SeriesChartType.Line; foreach(DataRow dr in dt.Rows) { try { if (String.Equals(serieName,dr["doman_namn"].ToString(), StringComparison.Ordinal)) { xvals.Add(dr["ranking_date"].ToString()); yvals.Add(Convert.ToDecimal(dr["ranking_position"].ToString())); } } catch (Exception) { throw new InvalidOperationException("Diagrammet kunde inte ritas upp"); } } try { Chart1.Series[serieName].XValueType = ChartValueType.String; Chart1.Series[serieName].YValueType = ChartValueType.Auto; Chart1.Series[serieName].Points.DataBindXY(xvals.ToArray(), yvals.ToArray()); } catch (Exception) { throw new InvalidOperationException("Kunde inte bind punkterna till Diagrammet"); } } Chart1.DataBind(); Chart1.Visible = true; </code></pre>
37,703,609
Using python Logging with AWS Lambda
<p>As the AWS documentation suggests:</p> <pre><code>import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def my_logging_handler(event, context): logger.info('got event{}'.format(event)) logger.error('something went wrong') </code></pre> <p>Now I made:</p> <pre><code>import logging logging.basicConfig(level = logging.INFO) logging.info("Hello World!") </code></pre> <p>The first snippet of code prints in the <code>Cloud Watch</code> console, but the second one no.</p> <p>I didn't see any difference as the two snippets are using the root logger.</p>
56,579,088
9
4
null
2016-06-08 13:15:55.5 UTC
20
2022-04-29 08:12:38.297 UTC
2016-06-08 15:07:46.023 UTC
null
312,444
null
312,444
null
1
113
python|amazon-web-services|logging|aws-lambda
76,941
<p>The reason that logging does not seem to work is because the AWS Lambda Python runtime <a href="https://gist.github.com/alanjds/000b15f7dcd43d7646aab34fcd3cef8c#file-awslambda-bootstrap-py-L463" rel="noreferrer">pre-configures a logging handler</a> that, depending on the version of the runtime selected, might modify the format of the message logged, and might also add some metadata to the record if available. What is <em>not</em> preconfigured though is the log-level. This means that no matter the type of log-message you try to send, it will not actually print.</p> <p>As <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-logging.html" rel="noreferrer">AWS documents themselves</a>, to correctly use the <code>logging</code> library in the AWS Lambda context, you only need to set the log-level for the root-logger:</p> <pre class="lang-py prettyprint-override"><code>import logging logging.getLogger().setLevel(logging.INFO) </code></pre> <p>If you want your Python-script to be both executable on AWS Lambda, but also with your local Python interpreter, you can check whether a handler is configured or not, and fall back to <code>basicConfig</code> (which creates the default stderr-handler) otherwise:</p> <pre class="lang-py prettyprint-override"><code>if len(logging.getLogger().handlers) &gt; 0: # The Lambda environment pre-configures a handler logging to stderr. If a handler is already configured, # `.basicConfig` does not execute. Thus we set the level directly. logging.getLogger().setLevel(logging.INFO) else: logging.basicConfig(level=logging.INFO) </code></pre>
21,216,228
PHP Manager for IIS fails to install
<p>I am trying to install PHP on IIS 8. </p> <p>Every time I start the PHP installation, PHP installs but I get the follow error:</p> <p><img src="https://i.stack.imgur.com/kUiR4.png" alt="enter image description here"></p>
32,302,012
4
4
null
2014-01-19 11:38:01.877 UTC
15
2019-07-01 10:04:29.123 UTC
2018-08-02 15:33:11.077 UTC
null
11,182
null
3,018,332
null
1
59
php|windows-10|web-platform-installer|php-manager
60,432
<p>As Abhi says: fire up regedit.exe and change the decimal value of <code>Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\MajorVersion</code> from 10 (as set by Windows 10) to e.g. 8. Installer should work now. Afterwards, you can set the value back to 10 (or whatever value your Windows env. had at first).</p> <p><strong>Tip</strong>: For quick navigation, paste the path <code>Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters</code>into the address-bar of Registry Editor and hit Enter.</p> <p>Also, for me on Windows 10, I had to enable <code>.NET Framework 3.5</code> > <code>Windows Communication Foundation HTTP Activation</code>for the installer to progress. Without this enabled, installer would just hang at step 1. Requires reboot.</p>
20,889,126
Bootstrap: adding gaps between divs
<p>If my page uses the Bootstrap class <code>row</code>, <code>col-md-x</code> and such to arrange the content, what would be the proper way to create a distance between each div containing a whole element semantically speaking?</p> <p>I am adding a div with a padding between the divs to simulate the gap, is this a good tactic or is there a better one?</p>
20,889,189
5
5
null
2014-01-02 18:15:27.85 UTC
6
2020-08-27 16:46:49.987 UTC
null
null
null
null
3,120,489
null
1
61
html|css|twitter-bootstrap
190,428
<p>Adding a padding between the divs to simulate a gap might be a hack, but why not use something Bootstrap provides. It's called offsets. But again, you can define a class in your <strong>custom.css</strong> (you shouldn't edit the core stylesheet anyway) file and add something like <code>.gap</code>. However, <code>.col-md-offset-*</code> does the job most of the times for me, allowing me to precisely leave a gap between the divs.</p> <p>As for vertical spacing, unfortunately, there isn't anything set built-in like that in Bootstrap 3, so you will have to invent your own custom class to do that. I'd usually do something like <code>.top-buffer { margin-top:20px; }</code>. This does the trick, and obviously, it doesn't have to be 20px, it can be anything you like.</p>
20,909,492
MySQL not showing databases created in phpMyAdmin
<p>I'm trying to build a database for my server in phpmyadmin but when I finish building it I can't access it using PHP and it won't show when I list the databases in MySQL. But when I create a database in mySql it shows up in phpmyadmin. Also I'm running phpmyadmin version 4.0.3, and theres a statement at the bottom of the page saying <code>The phpMyAdmin configuration storage is not completely configured, some extended features have been deactivated. To find out why click here.</code></p> <p>Thanks!</p>
20,910,882
4
7
null
2014-01-03 17:37:49.803 UTC
1
2022-05-07 07:01:41.133 UTC
null
null
null
null
1,109,115
null
1
6
php|sql|ubuntu|amazon-ec2|phpmyadmin
38,385
<p>This sounds like a permissions issue. I'd guess that your phpMyAdmin is connecting to MySQL as root (or another user with the superuser privilege) and can therefore see all databases. Your app is probably connected using a different, lower privileged user.</p> <p>Try running <code>select user();</code> from your app and from phpMyAdmin and you will know for sure.</p> <p>Assuming your app is running with a different user, you will need to add privilages for it to access the database you create. Please read the section titled <a href="https://docs.phpmyadmin.net/en/latest/privileges.html" rel="nofollow noreferrer">Assigning privileges to user for a specific database</a> in the phpMyAdmin documentation.</p>
44,217,376
Fetch API not working with localhost/127.0.0.1
<p>Just as background, I have a react app sitting on a remote EC2 Ubuntu instance. The same server also runs a Go app listening on port 8080 (port has been opened to everyone from the Security settings).</p> <p>I am trying to make a request with Fetch API, from the React app, as follows:</p> <pre><code>var bearer = 'Bearer ...' return fetch('http://localhost:8080/home', { headers: new Headers({ 'Authorization': bearer }) }) </code></pre> <p>In the console, from both Chrome and Firefox, I am getting:</p> <p><strong>TypeError: NetworkError when attempting to fetch resource</strong></p> <p>The same goes when I substitute <code>localhost</code> with <code>127.0.0.1</code>.</p> <p>Using the external IP of the EC2 instance, however, works (and triggers a CORS request - due to the 'Authorization' header - which is handled smoothly by the server).</p> <p>In the latter case, I can also see the server logging the incoming request for both OPTIONS and GET (in the former case, no logs are present for either method).</p> <p>I also tried CURL'ing from the EC2 machine to <code>localhost</code> and the request effectively goes through which leads me to think that with the Fetch API the request is not triggered at all.</p> <p>Any advice would be appreciated. If I am doing anything wrong please point me in the right direction.</p>
44,221,708
3
2
null
2017-05-27 13:22:49.077 UTC
9
2020-10-30 06:46:38.26 UTC
2020-01-12 04:06:15.267 UTC
null
441,757
null
7,119,728
null
1
15
reactjs|amazon-ec2|fetch
73,886
<p>When you write <code>localhost</code> it calls your (localhost) machine (on which the browser is present) because the <code>js</code> code is running in your browser. </p> <p>You should create a domain/sub-domain for your API endpoint and use it instead of localhost or continue to use the hard-coded IP address.</p> <p>You should also allow only your frontend website domain in the allowed origins for your backend. Ex. your website can be <code>www.example.com</code> and backend url can be <code>www.api.example.com</code>. You should allow only <code>www.example.com</code> as the <code>origin</code> which can be served through <code>www.api.example.com</code>. You will need to configure this in the backend.</p>
63,001,988
how to remove background of images in python
<p>I have a dataset that contains full width human images I want to remove all the backgrounds in those Images and just leave the full width person,</p> <p>my questions:</p> <p>is there any python code that does that ?</p> <p>and do I need to specify each time the coordinate of the person object?</p> <p><a href="https://i.stack.imgur.com/pvN1j.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pvN1j.png" alt="enter image description here" /></a></p>
63,003,020
1
1
null
2020-07-20 18:49:11.457 UTC
8
2021-06-06 13:19:21.42 UTC
null
null
null
null
13,604,953
null
1
7
python|image|opencv|image-processing|background
40,151
<p>Here is one way using Python/OpenCV.</p> <ul> <li>Read the input</li> <li>Convert to gray</li> <li>Threshold and invert as a mask</li> <li>Optionally apply morphology to clean up any extraneous spots</li> <li>Anti-alias the edges</li> <li>Convert a copy of the input to BGRA and insert the mask as the alpha channel</li> <li>Save the results</li> </ul> <br> <p>Input:</p> <p><a href="https://i.stack.imgur.com/LJJq6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LJJq6.png" alt="enter image description here" /></a></p> <pre><code>import cv2 import numpy as np # load image img = cv2.imread('person.png') # convert to graky gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # threshold input image as mask mask = cv2.threshold(gray, 250, 255, cv2.THRESH_BINARY)[1] # negate mask mask = 255 - mask # apply morphology to remove isolated extraneous noise # use borderconstant of black since foreground touches the edges kernel = np.ones((3,3), np.uint8) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # anti-alias the mask -- blur then stretch # blur alpha channel mask = cv2.GaussianBlur(mask, (0,0), sigmaX=2, sigmaY=2, borderType = cv2.BORDER_DEFAULT) # linear stretch so that 127.5 goes to 0, but 255 stays 255 mask = (2*(mask.astype(np.float32))-255.0).clip(0,255).astype(np.uint8) # put mask into alpha channel result = img.copy() result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA) result[:, :, 3] = mask # save resulting masked image cv2.imwrite('person_transp_bckgrnd.png', result) # display result, though it won't show transparency cv2.imshow(&quot;INPUT&quot;, img) cv2.imshow(&quot;GRAY&quot;, gray) cv2.imshow(&quot;MASK&quot;, mask) cv2.imshow(&quot;RESULT&quot;, result) cv2.waitKey(0) cv2.destroyAllWindows() </code></pre> <br> <p>Transparent result:</p> <p><a href="https://i.stack.imgur.com/YPOKU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YPOKU.png" alt="enter image description here" /></a></p>
2,323,505
How to keep track of model history with mapping table in Ruby on Rails?
<h2>dream</h2> <p>I'd like to keep record of when a user changes their address.</p> <p>This way, when an order is placed, it will always be able to reference the user address that was used at the time of order placement.</p> <h2>possible schema</h2> <pre><code>users ( id username email ... ) user_addresses ( id label line_1 line_2 city state zip ... ) user_addresses_map ( user_id user_address_id start_time end_time ) orders ( id user_id user_address_id order_status_id ... created_at updated_at ) </code></pre> <h2>in sql, this might look something like: [sql]</h2> <pre><code>select ua.* from orders o join users u on u.id = o.user_id join user_addressses_map uam on uam.user_id = u.id and uam.user_address_id = o.user_address_id join user_addresses ua on ua.id = uam.user_address_id and uam.start_time &lt; o.created_at and (uam.end_time &gt;= o.created_at or uam.end_time is null) ; </code></pre> <h1>edit: The Solution</h1> <p>@KandadaBoggu posted a great solution. The <strong><a href="http://github.com/laserlemon/vestal_versions" rel="noreferrer">Vestal Versions plugin</a></strong> is a <strong>great solution</strong>.</p> <p><strong>snippet below taken from <a href="http://github.com/laserlemon/vestal_versions" rel="noreferrer">http://github.com/laserlemon/vestal_versions</a></strong></p> <h2>Finally, DRY ActiveRecord versioning!</h2> <blockquote> <p><a href="http://github.com/technoweenie/acts_as_versioned" rel="noreferrer">acts_as_versioned</a> by <a href="http://github.com/technoweenie" rel="noreferrer">technoweenie</a> was a great start, but it failed to keep up with ActiveRecord’s introduction of dirty objects in version 2.1. Additionally, each versioned model needs its own versions table that duplicates most of the original table’s columns. The versions table is then populated with records that often duplicate most of the original record’s attributes. All in all, not very DRY.</p> <p><a href="http://github.com/laserlemon/vestal_versions" rel="noreferrer">vestal_versions</a> requires only one versions table (polymorphically associated with its parent models) and no changes whatsoever to existing tables. But it goes one step DRYer by storing a serialized hash of <em>only</em> the models’ changes. Think modern version control systems. By traversing the record of changes, the models can be reverted to any point in time.</p> <p>And that’s just what vestal_versions does. <strong>Not only can a model be reverted to a previous version number but also to a date or time!</strong></p> </blockquote>
2,324,231
5
2
null
2010-02-24 03:33:02.467 UTC
9
2020-12-15 15:30:57.29 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
184,600
null
1
11
ruby-on-rails|activerecord|schema
14,326
<p>Use the <a href="http://github.com/laserlemon/vestal_versions" rel="noreferrer">Vestal versions plugin</a> for this:</p> <p>Refer to <a href="http://railscasts.com/episodes/177-model-versioning" rel="noreferrer">this</a> screen cast for more details.</p> <pre><code>class Address &lt; ActiveRecord::Base belongs_to :user versioned end class Order &lt; ActiveRecord::Base belongs_to :user def address @address ||= (user.address.revert_to(updated_at) and user.address) end end </code></pre>
2,185,846
Why I can't purchase my own application on the Android market?
<p>I just uploaded my application in the market, but I'm not able to purchase it (it's a pay app).</p> <p>I saw <a href="http://market.android.com/support/bin/answer.py?hl=en&amp;answer=141659" rel="nofollow noreferrer">here</a> that it seems to be <em>made by design</em>, but then why the error message is <code>Server Error try again</code> ?</p> <p>Is there a way to bypass that ?</p>
2,185,905
5
0
null
2010-02-02 16:45:51.613 UTC
1
2014-01-08 11:32:34.523 UTC
2014-01-08 11:32:34.523 UTC
null
309,086
null
231,417
null
1
28
android|google-play
7,173
<p>Do you have an Android Developer Phone? If so, you can't purchase your own app by design. Since ADPs are unlocked, there's nothing preventing an ADP from easily pirating any app it downloads, so they are purposely cut off from downloading paid apps.</p>
1,656,727
How to generate a PHP soap client code?
<p>Is there a way to generate a PHP Soap Client from a WSDL file?</p> <p>I mean something like <code>wsdl.exe</code> or <code>svcutil.exe</code> in .net, that generates code for a class that can be the client of a service, not something like:</p> <pre><code>$WSDL = new SOAP_WSDL($wsdl_url); $client = $WSDL-&gt;getProxy(); </code></pre> <p>My problem is that I want the PHP client to be able the work with a service, even when that service doesn't expose its WSDL.</p>
1,656,763
6
0
null
2009-11-01 09:25:45.54 UTC
6
2016-03-01 00:45:00.243 UTC
2013-01-02 18:43:47.24 UTC
null
367,456
null
19,956
null
1
12
php|soap|wsdl|soap-client
48,580
<p>You can use the method [<code>generateProxyCode</code>] provided in the package SOAP_WSDL (<a href="http://pear.php.net/reference/SOAP-0.9.4/SOAP/SOAP_WSDL.html#methodgenerateProxyCode" rel="nofollow noreferrer">http://pear.php.net/reference/SOAP-0.9.4/SOAP/SOAP_WSDL.html#methodgenerateProxyCode</a>) method instead and save it to a file:</p> <pre><code>$WSDL = new SOAP_WSDL($wsdl_url); $php = $WSDL-&gt;generateProxyCode(); file_put_contents('wsdl_proxy.php', '&lt;?php ' . $php . ' ?&gt;'); require 'wsdl_proxy.php'; </code></pre>
1,587,407
Iphone device token - NSData or NSString
<p>I am receiving iPhone device token in the form of <code>NSData</code> object. When I tested my notifications script function, I have only copied that object from log and the notifications went fine. However when I try now to automatically do it, I am sending the device token as ASCII encoded string in the form of variable</p> <pre><code>self.deviceToken = [[NSString alloc] initWithData:webDeviceToken encoding:NSASCIIStringEncoding]; </code></pre> <p>The string that I am getting has some funky characters and looks similar to this <code>"Γ₯-0ΒΎfZÿ÷ʺÎUQΓΌRΓ‘qEΒͺfΓ”kΒ«"</code></p> <p>When server side script sends the notification to that token, I am not receiving anything.</p> <p>Do I need to decode something and how?</p> <p>Regardz</p>
1,587,441
6
2
null
2009-10-19 07:44:33.27 UTC
10
2016-12-06 16:07:36.763 UTC
2013-06-03 07:16:24.647 UTC
null
1,571,232
null
115,873
null
1
33
iphone|device-driver|token
28,565
<p>Ok, I found a solution. If anyone has the same problem, forget about ASCII encoding, just make the string with the following lines:</p> <pre><code>NSString *deviceToken = [[webDeviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"&lt;&gt;"]]; deviceToken = [deviceToken stringByReplacingOccurrencesOfString:@" " withString:@""]; </code></pre>
1,579,846
Django returning HTTP 301?
<p>I have a django view that returns HTTP 301 on a curl request:</p> <pre><code>grapefruit:~ pete$ curl -I http://someurl HTTP/1.1 301 MOVED PERMANENTLY Date: Fri, 16 Oct 2009 19:01:08 GMT Server: Apache/2.2.9 (Win32) mod_wsgi/2.5 Python/2.6.2 PHP/5.2.6 Location: http://someurl Content-Type: text/html; charset=utf-8 </code></pre> <p>I can't get the page's content from curl. However, if I visit the page with a browser, I see the content as expected.</p> <p>Any ideas?</p> <p>Thanks, Pete</p>
1,579,859
6
0
null
2009-10-16 19:08:35.587 UTC
13
2022-06-10 06:25:39.607 UTC
2016-06-06 15:00:43.197 UTC
null
123,201
null
123,201
null
1
71
django|curl|libcurl
37,728
<p>You are probably requesting the URL without a trailing slash, and have <code>APPEND_SLASH</code> set to True (the default) in settings.py, so Django is redirecting to the URL including a slash.</p>
2,056,628
Hot Code Replace Failed (eclipse)
<p>"Hot Code Replace Failed - add method not implemented". I get this error message every time I change something in my test class (and save it). Can't figure out what it means. Can somebody help?</p>
2,056,706
7
2
null
2010-01-13 12:41:24.637 UTC
9
2021-09-06 12:42:27.563 UTC
2013-12-02 19:28:19.717 UTC
null
125,389
null
110,028
null
1
44
eclipse|hotdeploy
61,547
<p>Possibly, you have a test which is still running (in debug mode). Try finishing all tests (you can see them in the debug view: window->show view->debug) and try again...</p>
1,981,670
Programmatically get a screenshot of a page
<p>I'm writing a specialized crawler and parser for internal use, and I require the ability to take a screenshot of a web page in order to check what colours are being used throughout. The program will take in around ten web addresses and will save them as a bitmap image.</p> <p>From there I plan to use LockBits in order to create a list of the five most used colours within the image. To my knowledge, it's the easiest way to get the colours used within a web page, but if there is an easier way to do it please chime in with your suggestions.</p> <p>Anyway, I was going to use <em><a href="http://www.acasystems.com/en/web-thumb-activex/" rel="noreferrer">ACA WebThumb ActiveX Control</a></em> until I saw the price tag. I'm also fairly new to C#, having only used it for a few months. Is there a solution to my problem of taking a screenshot of a web page in order to extract the colour scheme?</p>
2,496,277
7
6
null
2009-12-30 18:25:53.74 UTC
45
2019-08-05 14:24:44.163 UTC
2013-04-13 07:03:39.597 UTC
null
63,550
null
3,609
null
1
48
c#|screenshot|cutycapt|iecapt
60,019
<p><a href="https://screenshotlayer.com/documentation" rel="noreferrer">https://screenshotlayer.com/documentation</a> is the only free service I can find lately...</p> <p>You'll need to use HttpWebRequest to download the binary of the image. See the provided url above for details.</p> <pre><code>HttpWebRequest request = HttpWebRequest.Create("https://[url]") as HttpWebRequest; Bitmap bitmap; using (Stream stream = request.GetResponse().GetResponseStream()) { bitmap = new Bitmap(stream); } // now that you have a bitmap, you can do what you need to do... </code></pre>
2,279,471
What's the difference between 'for' and 'foreach' in Perl?
<p>I see these used interchangeably. What's the difference?</p>
2,279,497
8
1
null
2010-02-17 09:19:53.677 UTC
null
2014-10-16 07:28:39.807 UTC
2012-02-23 20:09:31.927 UTC
null
579,750
null
275,088
null
1
39
perl|loops|syntax|for-loop|foreach
13,705
<p>There is no difference. From <a href="http://perldoc.perl.org/perlsyn.html#Foreach-Loops" rel="noreferrer">perldoc perlsyn</a>:</p> <blockquote> <p>The <code>foreach</code> keyword is actually a synonym for the <code>for</code> keyword, so you can use <code>foreach</code> for readability or <code>for</code> for brevity.</p> </blockquote>
1,470,334
List all active ASP.NET Sessions
<p>How can I list (and iterate through) all current ASP.NET sessions?</p>
1,470,571
9
2
null
2009-09-24 08:04:45.513 UTC
25
2018-11-09 13:03:18.353 UTC
null
null
null
null
114,916
null
1
50
asp.net|session|session-state
66,193
<p>You can collect data about sessions in global.asax events Session_Start and Session_End (only in in-proc settings):</p> <pre><code>private static readonly List&lt;string&gt; _sessions = new List&lt;string&gt;(); private static readonly object padlock = new object(); public static List&lt;string&gt; Sessions { get { return _sessions; } } protected void Session_Start(object sender, EventArgs e) { lock (padlock) { _sessions.Add(Session.SessionID); } } protected void Session_End(object sender, EventArgs e) { lock (padlock) { _sessions.Remove(Session.SessionID); } } </code></pre> <p>You should consider use some of concurrent collections to lower the synchronization overhead. ConcurrentBag or ConcurrentDictionary. Or ImmutableList </p> <p><a href="https://msdn.microsoft.com/en-us/library/dd997373(v=vs.110).aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/dd997373(v=vs.110).aspx</a></p> <p><a href="https://msdn.microsoft.com/en-us/library/dn467185.aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/dn467185.aspx</a></p>
2,013,091
Coloured Git diff to HTML
<p>I enjoy using <code>git diff --color-words</code> to clearly see the words that have changed in a file:</p> <p><img src="https://i.stack.imgur.com/HnM4B.png" alt="Screenshot"></p> <p>However I want to share that diff with someone without git or a colour terminal for that matter. So does anyone know of a tool or trick that can convert <strong>colour escaped terminal output</strong> into HTML?</p>
2,031,457
9
0
null
2010-01-06 13:13:21.113 UTC
47
2021-05-16 19:29:07.327 UTC
2014-06-21 19:26:50.78 UTC
user456814
null
null
4,534
null
1
74
html|git|colors|diff|terminal
44,034
<pre class="lang-bash prettyprint-override"><code>wget "http://www.pixelbeat.org/scripts/ansi2html.sh" -O /tmp/ansi2html.sh chmod +x /tmp/ansi2html.sh git diff --color-words --no-index orig.txt edited.txt | \ /tmp/ansi2html.sh &gt; 2beshared.html </code></pre> <p>What I really needed was an <a href="http://en.wikipedia.org/wiki/ANSI_escape_code" rel="noreferrer">ANSI</a> to HTML converter. And I found a very decent one on <a href="http://www.pixelbeat.org/" rel="noreferrer">http://www.pixelbeat.org/</a>.</p> <p>NOTE: You might not see any coloration unless you include <code>--color</code> or <code>--color-words</code>, probably because piping causes git diff to exclude colors.</p> <p>NOTE 2: You may need to install gnu sed and awk, especially if you're on a Mac. Do so with <code>brew install gnu-sed gawk</code>. You may need to add them to your path manually, too, e.g. with <code>ln -s /usr/local/Cellar/gnu-sed/4.2.2/bin/gsed /usr/local/bin/</code>.</p>
2,334,134
How to make C# Switch Statement use IgnoreCase
<p>If I have a switch-case statement where the object in the switch is string, is it possible to do an ignoreCase compare?</p> <p>I have for instance:</p> <pre><code>string s = &quot;house&quot;; switch (s) { case &quot;houSe&quot;: s = &quot;window&quot;; } </code></pre> <p>Will <code>s</code> get the value &quot;window&quot;? How do I override the switch-case statement so it will compare the strings using ignoreCase?</p>
2,334,241
10
0
null
2010-02-25 13:07:13.19 UTC
12
2022-09-14 15:11:37.057 UTC
2020-11-05 23:44:19.467 UTC
null
1,402,846
null
141,414
null
1
100
c#|switch-statement
108,355
<p>As you seem to be aware, lowercasing two strings and comparing them is not the same as doing an ignore-case comparison. There are lots of reasons for this. For example, the Unicode standard allows text with diacritics to be encoded multiple ways. Some characters includes both the base character and the diacritic in a single code point. These characters may also be represented as the base character followed by a combining diacritic character. These two representations are equal for all purposes, and the culture-aware string comparisons in the .NET Framework will correctly identify them as equal, with either the CurrentCulture or the InvariantCulture (with or without IgnoreCase). An ordinal comparison, on the other hand, will incorrectly regard them as unequal.</p> <p>Unfortunately, <code>switch</code> doesn't do anything but an ordinal comparison. An ordinal comparison is fine for certain kinds of applications, like parsing an ASCII file with rigidly defined codes, but ordinal string comparison is wrong for most other uses.</p> <p>What I have done in the past to get the correct behavior is just mock up my own switch statement. There are lots of ways to do this. One way would be to create a <code>List&lt;T&gt;</code> of pairs of case strings and delegates. The list can be searched using the proper string comparison. When the match is found then the associated delegate may be invoked.</p> <p>Another option is to do the obvious chain of <code>if</code> statements. This usually turns out to be not as bad as it sounds, since the structure is very regular.</p> <p>The great thing about this is that there isn't really any performance penalty in mocking up your own switch functionality when comparing against strings. The system isn't going to make a O(1) jump table the way it can with integers, so it's going to be comparing each string one at a time anyway.</p> <p>If there are many cases to be compared, and performance is an issue, then the <code>List&lt;T&gt;</code> option described above could be replaced with a sorted dictionary or hash table. Then the performance may potentially match or exceed the switch statement option.</p> <p>Here is an example of the list of delegates:</p> <pre><code>delegate void CustomSwitchDestination(); List&lt;KeyValuePair&lt;string, CustomSwitchDestination&gt;&gt; customSwitchList; CustomSwitchDestination defaultSwitchDestination = new CustomSwitchDestination(NoMatchFound); void CustomSwitch(string value) { foreach (var switchOption in customSwitchList) if (switchOption.Key.Equals(value, StringComparison.InvariantCultureIgnoreCase)) { switchOption.Value.Invoke(); return; } defaultSwitchDestination.Invoke(); } </code></pre> <p>Of course, you will probably want to add some standard parameters and possibly a return type to the CustomSwitchDestination delegate. And you'll want to make better names!</p> <p>If the behavior of each of your cases is not amenable to delegate invocation in this manner, such as if differnt parameters are necessary, then you’re stuck with chained <code>if</code> statments. I’ve also done this a few times.</p> <pre><code> if (s.Equals("house", StringComparison.InvariantCultureIgnoreCase)) { s = "window"; } else if (s.Equals("business", StringComparison.InvariantCultureIgnoreCase)) { s = "really big window"; } else if (s.Equals("school", StringComparison.InvariantCultureIgnoreCase)) { s = "broken window"; } </code></pre>
8,459,988
CSS Nested Comments
<p>Is there any way to nest comments in CSS?</p> <p>For example, when I try to comment out the following two statements, the outer comment ends when it encounters the */ in the nested comment, leaving the rest of the first statement and second statement uncommented.</p> <pre><code>/* #container { width: 90%; /* nested comment here */ margin: 0 auto; } #container .class { width: 25%; } */ </code></pre> <p>I run into this problem often when I want to try out a different styling technique that involves multiple statements.</p> <p>I'm familiar with the CSS <a href="http://www.w3.org/TR/CSS2/syndata.html#comments" rel="noreferrer">specification</a> for comments and its <a href="https://stackoverflow.com/questions/2479351/why-do-comments-work-in-stylesheets-but-comments-dont">rationale</a>, but also know there's a <a href="https://stackoverflow.com/questions/442786/are-nested-html-comments-possible">workaround</a> for nesting HTML comments and am hoping there's a similar hack for CSS.</p> <p>Has anyone found a way to nest comments in CSS?</p>
8,460,194
5
2
null
2011-12-10 21:24:31.22 UTC
11
2017-06-30 03:54:36.75 UTC
2017-05-23 10:31:29.113 UTC
null
-1
null
723,007
null
1
44
css|comments
13,193
<p>CSS does not have a nestable comment syntax.</p> <p>You could instead wrap the rules in something which does nest, but will not match anything, such as a non-existent media type:</p> <pre><code>@media DISABLED { #container { width: 90%; /* nested comment here */ margin: 0 auto; } #container .class { width: 25%; } } </code></pre> <p>This does have the caveat that it will not be obviously a comment (so it will not be removed by tools that remove comments), and will cause the browser to spend time on parsing it and finding that it doesn't match. However, neither of these should be a problem for temporary development use, which is the usual reason one would want to comment out a large chunk simply.</p>
46,493,613
What is the replacement for javax.activation package in java 9?
<p>Seems like <code>javax.activation</code> package is deprecated in Java 9. Oracle migration guide proposes to use <code>--add-modules java.activation</code> option during JVM start. </p> <p>However, I would like to avoid this and replace <code>javax.activation</code> package's classes, as it is deprecated and will be removed in future java versions. I suppose, there should be some kind of alternative for <code>javax.activation</code>. If there is any available, what is it?</p>
46,493,809
6
3
null
2017-09-29 16:55:53.937 UTC
17
2021-03-31 14:46:19.557 UTC
2017-10-06 11:43:37.42 UTC
null
2,525,313
null
7,110,799
null
1
79
java|jvm|java-9|javax.activation
88,709
<p><a href="https://github.com/eclipse-ee4j/jaf" rel="noreferrer">JavaBeans Activation Framework (JAF)</a> is possibly the alternative you are looking for to the existing package.</p> <blockquote> <p>This standalone release of JAF uses a Java Platform Module System <strong><em>automatic module</em></strong> name of <strong><a href="https://docs.oracle.com/javase/9/docs/api/java.activation-summary.htmll" rel="noreferrer"><code>java.activation</code></a></strong>, to match the module name used in JDK 9. A future version will include full module metadata.</p> </blockquote> <p>The standalone APIs are supported in modular form only, via the concept of <em><a href="http://openjdk.java.net/projects/jigsaw/goals-reqs/03#upgradeable-modules" rel="noreferrer">upgradeable modules</a></em>. Using them, it's possible to use a version of that module from a later release in any phase, i.e., at compile time, build time, or runtime.</p> <hr> <p>The currently <a href="https://search.maven.org/#artifactdetails%7Ccom.sun.activation%7Cjavax.activation%7C1.2.0%7Cjar" rel="noreferrer">available version</a> for this is <code>1.2.0</code> which can be used like this: </p> <p><strong><em>Maven</em></strong> </p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;com.sun.activation&lt;/groupId&gt; &lt;artifactId&gt;javax.activation&lt;/artifactId&gt; &lt;version&gt;1.2.0&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p><strong><em>Gradle</em></strong> </p> <pre><code>compile 'com.sun.activation:javax.activation:1.2.0' </code></pre> <p><strong><em>Ivy</em></strong></p> <pre><code>&lt;dependency org="com.sun.activation" name="javax.activation" rev="1.2.0" /&gt; </code></pre>
15,752,667
WARN SqlExceptionHelper:143 - SQL Error: 0, SQLState: 08S01- SqlExceptionHelper:144 - Communications link failure
<p>I have problem with Hibernate (<strong>hibernate-core-4.1.9.Final.jar</strong>)</p> <p>Case 1: Hibernate testing inside for loop. Everything went well.</p> <pre><code>for(int i = 0; i &lt; 1500; i++){ UserDAO.getInstance.getById(1); } </code></pre> <p>Case 2: <strong>Thread.sleep()</strong> inside loop. Resulting with exception after 1 minute.</p> <pre><code> for(int i=0; i&lt;1500; i++){ UserDAO.getInstance.getById(1); Thread.sleep(60000); } </code></pre> <p>Exception:</p> <pre><code>00:20:06,447 WARN SqlExceptionHelper:143 - SQL Error: 0, SQLState: 08S01 00:20:06,448 ERROR SqlExceptionHelper:144 - Communications link failure The last packet successfully received from the server was 120,017 milliseconds ago. The last packet sent successfully to the server was 9 milliseconds ago. Exception in thread &quot;main&quot; org.hibernate.exception.JDBCConnectionException: Communications link failure The last packet successfully received from the server was 120,017 milliseconds ago. The last packet sent successfully to the server was 9 milliseconds ago. at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129) at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81) at sun.proxy.$Proxy11.executeQuery(Unknown Source) at org.hibernate.loader.Loader.getResultSet(Loader.java:2031) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1832) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1811) at org.hibernate.loader.Loader.doQuery(Loader.java:899) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341) at org.hibernate.loader.Loader.doList(Loader.java:2516) at org.hibernate.loader.Loader.doList(Loader.java:2502) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2332) at org.hibernate.loader.Loader.list(Loader.java:2327) at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:124) at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1621) at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374) at org.hibernate.internal.CriteriaImpl.uniqueResult(CriteriaImpl.java:396) at com.fit.utilities.BaseDAO.getById(BaseDAO.java:35) at com.fit.test.Testiranje.main(Testiranje.java:51) Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 120,017 milliseconds ago. The last packet sent successfully to the server was 9 milliseconds ago. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3603) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3492) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4043) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2322) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122) ... 17 more Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost. at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3052) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3503) ... 29 more </code></pre> <p>Here is my <strong>hibernate.cfg.xml</strong></p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt; &lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt; &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://xxxxxx:3306/xxxx&lt;/property&gt; &lt;property name=&quot;connection.username&quot;&gt;xxxx&lt;/property&gt; &lt;property name=&quot;connection.password&quot;&gt;xxxx&lt;/property&gt; &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt; &lt;property name=&quot;hibernate.hbm2ddl.auto&quot;&gt;update&lt;/property&gt; &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt; &lt;property name=&quot;show_sql&quot;&gt;false&lt;/property&gt; &lt;property name=&quot;hibernate.connection.pool_size&quot;&gt;1&lt;/property&gt; &lt;mapping class=&quot;com.xxx.model.xxxxx&quot; /&gt; &lt;mapping class=&quot;com.xxx.model.xxxxx&quot; /&gt; &lt;mapping class=&quot;com.xxx.model.xxxxx&quot; /&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p><strong>UPDATE:</strong> The problem is solved using C3P0 library.</p> <pre><code> &lt;!-- configuration pool via c3p0--&gt; &lt;property name=&quot;c3p0.acquire_increment&quot;&gt;1&lt;/property&gt; &lt;property name=&quot;c3p0.idle_test_period&quot;&gt;100&lt;/property&gt; &lt;!-- seconds --&gt; &lt;property name=&quot;c3p0.max_size&quot;&gt;100&lt;/property&gt; &lt;property name=&quot;c3p0.max_statements&quot;&gt;0&lt;/property&gt; &lt;property name=&quot;c3p0.min_size&quot;&gt;10&lt;/property&gt; &lt;property name=&quot;c3p0.timeout&quot;&gt;100&lt;/property&gt; &lt;!-- seconds --&gt; </code></pre>
16,504,965
2
3
null
2013-04-01 22:00:26.573 UTC
2
2020-12-02 12:09:29.66 UTC
2020-12-02 12:09:29.66 UTC
null
1,073,748
null
1,073,748
null
1
6
mysql|hibernate
38,294
<p>The problem was happening because of the small value for <code>time_out</code> variable on the MySQL server.</p> <p>In my situation, <code>time_out</code> was set to 1 minute. Using <code>C3PO</code> pooling mechanism we can optimize <code>JDBC</code>.</p> <p>Download <strong>c3p0</strong> -&gt; <a href="http://sourceforge.net/projects/c3p0/" rel="nofollow noreferrer">http://sourceforge.net/projects/c3p0/</a></p> <p>I'm using <strong>hibernate 3.0</strong>.</p> <p><strong>hibernate.cfg.xml</strong></p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt; &lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt; &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://databasehost:3306/databasename&lt;/property&gt; &lt;property name=&quot;connection.username&quot;&gt;user&lt;/property&gt; &lt;property name=&quot;connection.password&quot;&gt;psw&lt;/property&gt; &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt; &lt;property name=&quot;hibernate.hbm2ddl.auto&quot;&gt;update&lt;/property&gt; &lt;property name=&quot;show_sql&quot;&gt;false&lt;/property&gt; &lt;!-- Hibernate c3p0 settings--&gt; &lt;property name=&quot;connection.provider_class&quot;&gt;org.hibernate.connection.C3P0ConnectionProvider&lt;/property&gt; &lt;property name=&quot;hibernate.c3p0.acquire_increment&quot;&gt;3&lt;/property&gt; &lt;property name=&quot;hibernate.c3p0.idle_test_period&quot;&gt;10&lt;/property&gt; &lt;property name=&quot;hibernate.c3p0.min_size&quot;&gt;5&lt;/property&gt; &lt;property name=&quot;hibernate.c3p0.max_size&quot;&gt;75&lt;/property&gt; &lt;property name=&quot;hibernate.c3p0.max_statements&quot;&gt;10&lt;/property&gt; &lt;property name=&quot;hibernate.c3p0.timeout&quot;&gt;50&lt;/property&gt; &lt;property name=&quot;hibernate.c3p0.preferredTestQuery&quot;&gt;select 1&lt;/property&gt; &lt;property name=&quot;hibernate.c3p0.testConnectionOnCheckout&quot;&gt;true&lt;/property&gt; &lt;!-- Mapping files --&gt; &lt;mapping class=&quot;xxx.xxx.xxx.xxx&quot; /&gt; &lt;mapping class=&quot;xxx.xxx.xxx.xxx&quot; /&gt; &lt;mapping class=&quot;xxx.xxx.xxx.xxx&quot; /&gt; &lt;mapping class=&quot;xxx.xxx.xxx.xxx&quot; /&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p><strong>PersistenceManager.java</strong></p> <pre><code>import java.io.PrintStream; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; public class PersistenceManager { private static SessionFactory sessionFactory = null; private static PersistenceManager singleton = null; public static PersistenceManager getInstance() { if (singleton == null) { singleton = new PersistenceManager(); } return singleton; } public SessionFactory getSessionFactory() { if (sessionFactory == null) createSessionFactory(); return sessionFactory; } protected void createSessionFactory() { sessionFactory = new AnnotationConfiguration().configure() .buildSessionFactory(); } public void destroySessionFactory() { if (sessionFactory != null) { sessionFactory.close(); sessionFactory = null; } } } </code></pre> <p><strong>Example 1:</strong></p> <pre><code>import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; public Users Login( String username, String password) { Session session = null; try { String hql = &quot;select u from Users u where u.username like :p1 and u.password like :p2&quot;; session = PersistenceManager.getInstance().getSessionFactory().openSession(); Query q = session.createQuery(hql) .setParameter(&quot;p1&quot;, username) .setParameter(&quot;p2&quot;, password); if (q.list().size() == 0) { session.close(); return new Users(); } Users user = (Users)q.list().get(0); session.close(); return user; } catch (Exception e) { session.close(); } } </code></pre> <p><strong>Example 2:</strong></p> <pre><code>import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; public String Registration(Users u) { Session session = null; try { String hql = &quot;select u from Users u where u.username like :p1&quot;; session = PersistenceManager.getInstance().getSessionFactory().openSession(); Query q = session.createQuery(hql).setParameter(&quot;p1&quot;, u.getUsername()); if (q.list().size() == 0) { session.beginTransaction(); session.persist(u); session.getTransaction().commit(); session.close(); return new Boolean(true).toString(); } session.close(); return new Boolean(false).toString(); } catch (Exception e) { return e.toString(); } } </code></pre>
15,989,030
MySQL Error 1045, "Access denied for user 'user'@'localhost' (using password: YES)"
<p>This question seem to be asked a lot however I cannot find a definitive answer.</p> <p>I am making some webapp tests using MySQL, and at the beginning I used the <em>'root'</em> user (with a non-empty password). My root user is working fine from the apps (tested from PHP and Python's Django), from the command line, and with PHPMyAdmin.</p> <p>However I don't wanted to use the the root user, so I created another user, and I granted all privileges to the databases that user should need. (I used PHPMyAdmin logged as <em>'root'</em> for this task).</p> <p>The new user cannot log in to MySQL. Neither from the Django app, nor PHPMyAdmin, nor the command line.</p> <p>I have two possible suspicions:</p> <ol> <li><p>there is a global privilege the user lacks. (As I said, I granted all database privileges, however I have not granted any global privileges);</p></li> <li><p>the user's configured host. (<em>'root'</em> has four lines in the <em>mysql.user</em> table, for hosts <em>'localhost'</em>, <em>'my-pc-name'</em>, <em>'127.0.0.1'</em> and <em>'::1'</em>; while the new user has one line for host <em>'%'</em>)</p></li> </ol> <p>(I have double-checked the password, so I am confident this is not a password problem.)</p>
15,989,067
2
5
null
2013-04-13 14:47:58.7 UTC
1
2017-02-12 23:38:41.78 UTC
2013-04-13 14:55:53.893 UTC
null
13,508
null
2,029,629
null
1
6
mysql|mysql-error-1045
40,167
<p>% means that the new user can access the database from any host.</p> <p>However, if you supplied the CREATE USER statement would be much more useful.</p> <p>In addition, check MySQL Manual below, where it explains why a user should have both <code>@'localhost'</code> and <code>@'%'</code>:</p> <p><a href="http://dev.mysql.com/doc/refman/5.1/en/adding-users.html" rel="noreferrer">MySQL Reference Manual - Adding Users</a></p>
34,088,373
"Call to undefined function mysql_connect()" after upgrade to php-7
<p>After I upgraded <strong>php5</strong> to <strong>php7</strong>, I get an error 500 with</p> <blockquote> <p>PHP Fatal error: Uncaught Error: Call to undefined function mysql_connect()</p> </blockquote> <p>I put this into my apt sources in order to get php7 right now:</p> <blockquote> <p>deb <a href="http://packages.dotdeb.org">http://packages.dotdeb.org</a> jessie all<br /> deb-src <a href="http://packages.dotdeb.org">http://packages.dotdeb.org</a> jessie all</p> </blockquote> <p>What I basically did is:</p> <pre><code>apt-get remove php5 apt-get install php7-* </code></pre> <p><em>I'm using the current version of Debian Jessie.</em></p> <p>But I still get this. There are a lot of questions here on SO and I definitely checked them all out. But I didn't find an answer there yet.</p>
34,088,446
1
7
null
2015-12-04 12:24:58.54 UTC
9
2020-05-05 18:54:15.207 UTC
null
null
null
null
1,199,684
null
1
62
php|debian|php-7
230,265
<p>From the <a href="http://php.net/manual/en/function.mysql-connect.php" rel="noreferrer">PHP Manual</a>:</p> <blockquote> <p>Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:</p> </blockquote> <pre><code>mysqli_connect() PDO::__construct() </code></pre> <p>use <code>MySQLi</code> or <code>PDO</code></p> <pre><code>&lt;?php $con = mysqli_connect('localhost', 'username', 'password', 'database'); </code></pre>
27,763,340
DOCKER_OPTS do not work in config file /etc/default/docker
<p>I have changed <code>/etc/default/docker</code> with <code>DOCKER_OPTS="-H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock"</code> (docker version 1.4.1 in ubuntu 14.04), but it do not take any effect for me (not listening at port <code>2375</code>). It seems that docker do not read this initial config file because I found <code>export http_proxy</code> enviroment do not work too.</p> <p>Only <code>sudo docker -H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock -d</code> works.</p> <p>It really confused me!</p>
32,406,293
9
2
null
2015-01-04 07:13:48.073 UTC
11
2019-08-16 11:22:58.82 UTC
2016-06-29 18:58:14.72 UTC
null
143,224
null
4,162,734
null
1
27
ubuntu|docker|upstart|systemd
44,513
<p>According to <a href="https://docs.docker.com/install/linux/linux-postinstall/#configuring-remote-access-with-systemd-unit-file" rel="noreferrer">docker documentation</a>, The recommended way to configure the daemon flags and environment variables for your Docker daemon is to use a <strong>systemd</strong> <em>drop-in file</em>. </p> <p>So, for this specific case, do the following:</p> <ol> <li><p>Use the command <code>sudo systemctl edit docker.service</code> to open an override file for <code>docker.service</code> in a text editor.</p></li> <li><p>Add or modify the following lines, substituting your own values.</p> <pre><code>[Service] ExecStart= ExecStart=/usr/bin/dockerd -H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock </code></pre></li> <li><p>Save the file.</p></li> <li><p>Reload the <code>systemctl</code> configuration.</p> <pre><code> $ sudo systemctl daemon-reload </code></pre></li> <li><p>Restart Docker:</p> <pre><code> $ sudo systemctl restart docker.service </code></pre></li> <li><p>Check to see whether the change was honored by reviewing the output of <code>netstat</code> to confirm <code>dockerd</code> is listening on the configured port.</p> <pre><code>$ sudo netstat -lntp | grep dockerd tcp 0 0 127.0.0.1:2375 0.0.0.0:* LISTEN 3758/dockerd </code></pre></li> </ol>
27,871,226
Jackson: Deserialize to a Map<String, Object> with correct type for each value
<p>I have a class that looks like the following</p> <pre><code>public class MyClass { private String val1; private String val2; private Map&lt;String,Object&gt; context; // Appropriate accessors removed for brevity. ... } </code></pre> <p>I'm looking to be able to make the round trip with Jackson from object to JSON and back. I can serialize the object above fine and receive the following output:</p> <pre><code>{ "val1": "foo", "val2": "bar", "context": { "key1": "enumValue1", "key2": "stringValue1", "key3": 3.0 } } </code></pre> <p>The issue I'm running into is that since the values in the serialized map do not have any type information, they are not deserialized correctly. For example, in the sample above, enumValue1 should be deserialized as an enum value but is instead deserialized as a String. I've seen examples for basing what type on a variety of things, but in my scenario, I won't know what the types are (they will be user generated objects that I won't know in advance) so I need to be able to serialize the type information with the key value pair. How can I accomplish this with Jackson?</p> <p>For the record, I'm using Jackson version 2.4.2. The code I'm using to test the round trip is as follows:</p> <pre><code>@Test @SuppressWarnings("unchecked") public void testJsonSerialization() throws Exception { // Get test object to serialize T serializationValue = getSerializationValue(); // Serialize test object String json = mapper.writeValueAsString(serializationValue); // Test that object was serialized as expected assertJson(json); // Deserialize to complete round trip T roundTrip = (T) mapper.readValue(json, serializationValue.getClass()); // Validate that the deserialized object matches the original one assertObject(roundTrip); } </code></pre> <p>Since this is a Spring based project, the mapper is being created as follows:</p> <pre><code>@Configuration public static class SerializationConfiguration { @Bean public ObjectMapper mapper() { Map&lt;Class&lt;?&gt;, Class&lt;?&gt;&gt; mixins = new HashMap&lt;Class&lt;?&gt;, Class&lt;?&gt;&gt;(); // Add unrelated MixIns .. return new Jackson2ObjectMapperBuilder() .featuresToDisable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS) .dateFormat(new ISO8601DateFormatWithMilliSeconds()) .mixIns(mixins) .build(); } } </code></pre>
27,875,728
1
3
null
2015-01-09 23:58:27.367 UTC
3
2019-06-07 13:30:53.907 UTC
2019-06-07 13:30:53.907 UTC
null
1,523,648
null
618,059
null
1
35
java|json|spring|jackson
55,853
<p>I think the simplest way of achieve what you want is using:</p> <pre><code>ObjectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); </code></pre> <p>This will add type information in the serialized json.</p> <p>Here you are a running example, that you will need to adapt to Spring:</p> <pre><code>public class Main { public enum MyEnum { enumValue1 } public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); MyClass obj = new MyClass(); obj.setContext(new HashMap&lt;String, Object&gt;()); obj.setVal1("foo"); obj.setVal2("var"); obj.getContext().put("key1", "stringValue1"); obj.getContext().put("key2", MyEnum.enumValue1); obj.getContext().put("key3", 3.0); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); System.out.println(json); MyClass readValue = mapper.readValue(json, MyClass.class); //Check the enum value was correctly deserialized Assert.assertEquals(readValue.getContext().get("key2"), MyEnum.enumValue1); } } </code></pre> <p>The object will be serialized into something similar to:</p> <pre><code>[ "so_27871226.MyClass", { "val1" : "foo", "val2" : "var", "context" : [ "java.util.HashMap", { "key3" : 3.0, "key2" : [ "so_27871226.Main$MyEnum", "enumValue1" ], "key1" : "stringValue1" } ] } ] </code></pre> <p>And will be deserialized back correctly, and the assertion will pass.</p> <p>Bytheway there are more ways of doing this, please look at <a href="https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization" rel="noreferrer">https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization</a> for more info.</p> <p>I hope it will help.</p>
5,046,320
A grid layout of icon/text buttons
<p>I am attempting to create a 3 x 3 grid of items. Each Item consists of an <code>ImageView</code> on top of a <code>TextView</code>. Unfortunately, I am having issues getting everything to play nicely.</p> <p>Here is my attempt to get 2 such items side by side. The text views don't even show, and the icons are squished together (instead of evenly spaced)</p> <pre><code>&lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="1" android:gravity="center" android:paddingLeft="40px" android:paddingRight="40px" &gt; &lt;TableRow&gt; &lt;LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;ImageView android:id="@+id/usertoolsimage" android:src="@drawable/ftnicon" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;TextView android:text="User Accounts" android:gravity="right" android:padding="3dip" android:textColor="#ffffff" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;ImageView android:id="@+id/queueimage" android:src="@drawable/ftnicon" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;TextView android:text="Queue Management" android:gravity="right" android:padding="3dip" android:textColor="#ffffff" /&gt; &lt;/LinearLayout&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView android:text="test 3" android:padding="3dip" android:textColor="#ffffff" /&gt; &lt;TextView android:text="test 4" android:gravity="right" android:padding="3dip" android:textColor="#ffffff" /&gt; &lt;/TableRow&gt; &lt;/TableLayout&gt; </code></pre> <p>My goal in the end is to have a grid of clickable items where the item is an image and text for a main menu. Can anyone guide me on what layouts I should use to achieve this?</p>
5,046,586
2
0
null
2011-02-18 20:40:48.717 UTC
5
2011-10-25 14:30:49.26 UTC
2011-02-18 20:48:13.693 UTC
null
107,455
null
107,455
null
1
16
android|grid|android-layout
58,852
<p>Your best bet in my opinion would be to use the gridView that way it supports scrolling and spacing and you can be very dynamic in what each items layout and events are. Another option is to just create a lay out the images with a combination of Relative/Linear Layouts.</p> <p>GridView layout:</p> <pre><code>&lt;GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myGrid" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:numColumns="3" android:columnWidth="60dp" android:stretchMode="columnWidth" android:gravity="center" /&gt; </code></pre> <p>and then in your activity:</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); mGame.status = GameStatus.PLAYING; setContentView(R.layout.gridLayout); GridView grid = (GridView) findViewById(R.id.myGrid); grid.setAdapter(new customAdapter()); grid.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int arg2, long arg3) { //do some stuff here on click } }); } public class customAdapter extends BaseAdapter { public View getView(int position, View convertView, ViewGroup parent) { //create a basic imageview here or inflate a complex layout with //getLayoutInflator().inflate(R.layout...) ImageView i = new ImageView(this); i.setImageResource(mFams.get(position).imageId); i.setScaleType(ImageView.ScaleType.FIT_CENTER); final int w = (int) (36 * getResources().getDisplayMetrics().density + 0.5f); i.setLayoutParams(new GridView.LayoutParams(w * 2, w * 2)); return i; } public final int getCount() { return 9; } public final Family getItem(int position) { return mFams.get(position); } public final long getItemId(int position) { return position; } } </code></pre> <p>Or the basic layout using linear layouts:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;LinearLayout android:id="@+id/linearLayout1" android:layout_height="fill_parent" android:layout_weight="1" android:layout_alignParentLeft="true" android:layout_width="fill_parent" android:orientation="horizontal"&gt; &lt;ImageView&gt;...&lt;/ImageView&gt; &lt;ImageView&gt;...&lt;/ImageView&gt; &lt;ImageView&gt;...&lt;/ImageView&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/linearLayout2" android:layout_height="fill_parent" android:layout_weight="1" android:layout_alignParentLeft="true" android:layout_width="fill_parent" android:orientation="horizontal"&gt; &lt;ImageView&gt;...&lt;/ImageView&gt; &lt;ImageView&gt;...&lt;/ImageView&gt; &lt;ImageView&gt;...&lt;/ImageView&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/linearLayout3" android:layout_height="fill_parent"" android:layout_weight="1" android:layout_alignParentLeft="true" android:layout_width="fill_parent" android:orientation="horizontal"&gt; &lt;ImageView&gt;...&lt;/ImageView&gt; &lt;ImageView&gt;...&lt;/ImageView&gt; &lt;ImageView&gt;...&lt;/ImageView&gt; &lt;/LinearLayout&gt; </code></pre> <p></p>
5,405,236
How to correctly write UTF-8 strings into MySQL through JDBC interface
<p>Connect to db:</p> <pre><code>public DBSource(ConnectionInfo ci) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException { Class.forName(&quot;com.mysql.jdbc.Driver&quot;).newInstance(); String dbPath = String.format( &quot;jdbc:mysql://%s:%d/%s?user=%s&amp;password=%s&amp;characterEncoding=utf-8&amp;&quot; + &quot;useUnicode=true&quot;, ci.host, ci.port, ci.dbName, ci.user, ci.password); conn = java.sql.DriverManager.getConnection(dbPath); prepareTables(); } </code></pre> <p>Table creation code:</p> <pre><code>private void prepareTables() throws SQLException { java.sql.Statement stat = conn.createStatement(); String query = &quot;set names utf8&quot;; stat.execute(query); query = &quot;set character set utf8&quot;; stat.execute(query); query = &quot;show variables like '%char%'&quot;; stat.execute(query); java.sql.ResultSet rs = stat.getResultSet(); while (rs.next()) { String k = rs.getString(1); String v = rs.getString(2); System.out.println(k + &quot; - &quot; + v); } query = &quot;drop table if exists clt&quot;; stat.execute(query); query = &quot;create table clt&quot; + &quot;(&quot; + &quot; id bigint not null&quot; + &quot;, text varchar(50) not null&quot; + &quot;) default character set utf8&quot;; stat.execute(query); } </code></pre> <p>rows insertion:</p> <pre><code>public void visit(Insert i) throws SQLException { String query = &quot;insert into clt&quot; + &quot; (id, text) values (?, ?)&quot;; java.sql.PreparedStatement stmt = conn.prepareStatement(query); if (i.rowData.id == 12656697) { String toOut = &quot;&lt;&lt;&lt; &quot; + Long.toString(i.rowData.id) + &quot; - &quot; + i.rowData.text; System.out.println(toOut); } int it = 0; stmt.setLong(++it, i.rowData.id); stmt.setString(++it, i.rowData.text); stmt.execute(); stmt.close(); } </code></pre> <p>check data:</p> <pre><code> public void checkText() throws SQLException { java.sql.Statement stmt = conn.createStatement(); String query = &quot;select id, text from clt where id = '12656697'&quot;; stmt.execute(query); java.sql.ResultSet rs = stmt.getResultSet(); while (rs.next()) { String k = rs.getString(1); String v = rs.getString(2); String toOut = &quot;&gt;&gt;&gt; &quot; + k + &quot; - &quot; + v; System.out.println(toOut); } } </code></pre> <p>output:</p> <pre><code>character_set_client - utf8 character_set_connection - latin1 character_set_database - latin1 character_set_filesystem - binary character_set_results - utf8 character_set_server - utf8 character_set_system - utf8 character_sets_dir - /usr/share/mysql/charsets/ &lt;&lt;&lt; 12656697 - Апарати &gt;&gt;&gt; 12656697 - ??????? </code></pre> <p><strong>Problem</strong>: In table I have &quot;<em>???????????</em>&quot; symbols at the text field.</p> <p><strong>expected string is</strong>: <em>Апарати</em><br /> <strong>result</strong>: <em>???????</em></p> <p>It is some kind of <strong>magic</strong>?</p> <p>I resolved an issue... But still will appreciate if somebody can explain it to me.</p> <p>So.</p> <ol> <li>I added to my /etc/mysql/my.cnf lines suggested by Costis Aivalis<br /> result the same</li> <li>I removed lines from my code:<br /> query = &quot;set character set utf8&quot;;<br /> stat.execute(query);</li> </ol> <p><strong>it is working!!! :)</strong></p>
5,405,448
2
1
null
2011-03-23 12:28:25.19 UTC
6
2021-06-11 19:14:02.9 UTC
2021-06-11 19:14:02.9 UTC
null
626,311
null
658,346
null
1
16
java|mysql|jdbc|utf-8
47,089
<p>Ensure that your MySQL configuration encoding is defined correctly. Check your settings and the correctness of the modifications with these commands: </p> <pre><code>show variables like 'character%'; </code></pre> <p>and <code>show variables like 'collation%';</code></p> <p>Add these lines to either <strong>my.cnf</strong> or <strong>my.ini</strong>:</p> <p>For MySQL 5.1.nn, and later versions 5.5.29 you just need these two lines:</p> <pre><code>[mysqld] character-set-server = utf8 character-set-filesystem = utf8 </code></pre> <p>For MySQL 5.0.nn and older use these settings:</p> <pre><code>[client] default-character-set=utf8 </code></pre> <p><br></p> <pre><code>[mysql] default-character-set=utf8 </code></pre> <p><br></p> <pre><code>[mysqld] default-character-set=utf8 character-set-server=utf8 </code></pre> <p>It is probably more convenient to use <a href="http://www.mysql.com/products/workbench/" rel="noreferrer">MySQL-Workbench</a> for your settings. Versions 5+ are excellent.</p> <p><img src="https://i.stack.imgur.com/QtusA.png" alt="enter image description here"></p> <p>In your Java program connect like this:</p> <pre><code>con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&amp;characterEncoding=UTF-8","user","passwd"); </code></pre>
16,502,905
How to fix "'ddlAssignedTo' has a SelectedValue which is invalid because it does not exist in the list of items
<p>I load the gridview and the gridview has an edit and delete buttons.</p> <p>I click on Edit and I get, "<code>ddlAssignedTo' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value</code></p> <p>I know that I am getting this error because the value fo <code>ddlAssignedTo</code> is null - nothing exists on the db for ddlAssignedTo. </p> <p>All I was trying to do is update the current value.</p> <p>So, my issue is this, if the current value is null, how do I assign a default value for ddlAssignedTo so that if no value currently exists on the db, the default value will prevail?</p> <p>Here are some code:</p> <p>Markup:</p> <pre><code>&lt;asp:TemplateField HeaderText="Assigned To"&gt; &lt;EditItemTemplate&gt; &lt;asp:DropDownList ID="ddlAssignedTo" runat="server" DataSourceID="SubjectDataSource" DataTextField="fullname" DataValueField="empl_Id" SelectedValue='&lt;%# Bind("AssignedTo") %&gt;'&gt; &lt;asp:ListItem Value=""&gt;--Select Name--&lt;/asp:ListItem&gt; &lt;/asp:DropDownList&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="lblAssigned" runat="server" Text='&lt;% #Bind("fullname") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField &lt;asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="&lt;%$ ConnectionStrings:ConnectionString %&gt;" SelectCommand="SELECT Distinct [rownum],[reqnum], AssignedTo, (empl_first + ' ' + empl_last) fullname, [reqrecdate], [reqrecfrom], [skillsets], [application], [hoursperweek], [fromdate], [todate], [status], [statusupdate], [statusupby] FROM [requestinfo] left join employee on requestInfo.AssignedTo=employee.empl_id ORDER BY [reqnum]" UpdateCommand="INSERT INTO [requestinfo] ([reqnum], [reqrecdate], [reqrecfrom], [skillsets], [application], [hoursperweek], [fromdate], [todate], [status], [statusupdate], [statusupby],[AssignedTo]) VALUES (@reqnum, @reqrecdate, @reqrecfrom, @skillsets, @application, @hoursperweek, @fromdate, @todate, @status, @statusupdate, @statusupby,@empl_id)"&gt; &lt;DeleteParameters&gt; &lt;asp:Parameter Name="rownum" Type="Int32" /&gt; &lt;/DeleteParameters&gt; &lt;UpdateParameters&gt; &lt;asp:Parameter Name="reqnum" Type="String" /&gt; &lt;asp:Parameter DbType="DateTime" Name="reqrecdate" /&gt; &lt;asp:Parameter Name="reqrecfrom" Type="String" /&gt; &lt;asp:Parameter Name="skillsets" Type="String" /&gt; &lt;asp:Parameter Name="application" Type="String" /&gt; &lt;asp:Parameter Name="hoursperweek" Type="Int32" /&gt; &lt;asp:Parameter DbType="DateTime" Name="fromdate" /&gt; &lt;asp:Parameter DbType="DateTime" Name="todate" /&gt; &lt;asp:Parameter Name="status" Type="String" /&gt; &lt;asp:Parameter DbType="DateTime" Name="statusupdate" /&gt; &lt;asp:Parameter Name="statusupby" Type="String" /&gt; &lt;asp:Parameter Name="empl_id" Type="String" /&gt; &lt;asp:Parameter Name="rownum" Type="Int32" /&gt; &lt;/UpdateParameters&gt; &lt;/asp:SqlDataSource&gt; &lt;asp:SqlDataSource ID="SubjectDataSource" runat="server" ConnectionString="&lt;%$ ConnectionStrings:ConnectionString %&gt;" SelectCommand="SELECT empl_id, (empl_first + ' ' + empl_last) fullname FROM dbo.Employee order by empl_last"&gt; &lt;/asp:SqlDataSource&gt; </code></pre> <p>CodeBehind:</p> <pre><code>Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles GridView1.RowUpdating Dim dd As DropDownList = DirectCast(GridView1.Rows(e.RowIndex).FindControl("ddlstatus"), DropDownList) e.NewValues("status") = dd.SelectedItem.Text Dim ddAssigned As DropDownList = DirectCast(GridView1.Rows(e.RowIndex).FindControl("ddlAssignedTo"), DropDownList) If String.IsNullOrEmpty(ddAssigned.SelectedValue) Then ddAssigned.SelectedValue = "shhhh" Else e.NewValues("empl_id") = ddAssigned.SelectedValue End If SqlDataSource1.DataBind() End Sub </code></pre>
17,063,221
4
4
null
2013-05-12 00:05:24.547 UTC
1
2018-05-29 08:59:00.577 UTC
2013-05-12 09:39:57.007 UTC
null
745,969
null
935,573
null
1
7
asp.net|vb.net|gridview
38,760
<p>Take a look at the solution provided by @cosmin.onea in the question <a href="http://forums.asp.net/t/1056921.aspx/2/10" rel="nofollow noreferrer">'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items</a></p> <p>This solution sets <code>AppendDataBoundItems="true"</code> on the <code>DropDownList</code> and creates one <code>nullable</code> ListItem so that your <code>DropDownList</code> will bind even when the field in the table is null.</p> <p>Applied to the OP's problem, the following snippet would provide an option that would be selected when the AssignedTo field is null.</p> <pre><code>&lt;asp:DropDownList ID="ddlAssignedTo" runat="server" DataSourceID="SubjectDataSource" DataTextField="fullname" DataValueField="empl_Id" SelectedValue='&lt;%# Bind("AssignedTo") %&gt;' AppendDataBoundItems="true"&gt; &lt;asp:ListItem Text="Select" Value="" /&gt; &lt;/asp:DropDownList&gt; </code></pre>
16,165,666
How to determine the window size of a Gaussian filter
<p>Gaussian smoothing is a common image processing function, and for an introduction of Gaussian filtering, please refer to <a href="http://homepages.inf.ed.ac.uk/rbf/HIPR2/gsmooth.htm" rel="noreferrer">here</a>. As we can see, one parameter: standard derivation will determine the shape of Gaussian function. However, when we perform convolution with Gaussian filtering, another parameter: the window size of Gaussian filter should also be determined at the same time. For example, when we use <code>fspecial</code> function provided by MATLAB, not only the standard derivation but also the window size must be provided. Intuitively, the larger the Gaussian standard derivation is the bigger the Gaussian kernel window should. However, there is no general rule about how to set the right window size. Any ideas? Thanks!</p>
16,167,851
3
2
null
2013-04-23 09:24:40.47 UTC
10
2021-06-19 20:29:15.333 UTC
null
null
null
null
1,264,018
null
1
8
image-processing|signal-processing|matlab
37,522
<p>The <code>size</code> of the mask drives the filter amount. A larger <code>size</code>, corresponding to a larger convolution mask, will generally result in a greater degree of filtering. As a kinda trade-off for greater amounts of noise reduction, larger filters also affect the details quality of the image. </p> <p>That's as milestone. Now coming to the <code>Gaussian filter</code>, the <code>standard deviation</code> is the main parameter. If you use a 2D filter, <strong>at the edge of the mask you will probably desire the weights to approximate 0</strong>.</p> <p>To this respect, as I already said, you can choose a mask with a size which is generally <strong><em>three times</em></strong> the <code>standard deviation</code>. This way, almost the whole Gaussian bell is taken into account and at the mask's edges your weights will asymptotically tend to zero.</p> <p>I hope this helps.</p>
313,432
C++ extend a vector with another vector
<p>I'm a C/Python programmer in C++ land working with the STL for the first time.</p> <p>In Python, extending a list with another list uses the <code>.extend</code> method:</p> <pre><code>&gt;&gt;&gt; v = [1, 2, 3] &gt;&gt;&gt; v_prime = [4, 5, 6] &gt;&gt;&gt; v.extend(v_prime) &gt;&gt;&gt; print(v) [1, 2, 3, 4, 5, 6] </code></pre> <p>I currently use this algorithmic approach to extend vectors in C++:</p> <pre><code>v.resize(v.size() + v_prime.size()); copy(v_prime.begin(), v_prime.end(), v.rbegin()); </code></pre> <p>Is this the canonical way of extending vectors, or if there is a simpler way that I'm missing?</p>
313,444
7
1
null
2008-11-24 04:49:39.657 UTC
6
2022-07-25 05:02:35.383 UTC
2017-02-11 17:08:43.597 UTC
null
1,459,669
cdleary
3,594
null
1
70
c++|vector
49,756
<p>From <a href="http://www.cplusplus.com/reference/stl/vector/insert.html" rel="noreferrer">here</a></p> <pre><code>// reserve() is optional - just to improve performance v.reserve(v.size() + distance(v_prime.begin(),v_prime.end())); v.insert(v.end(),v_prime.begin(),v_prime.end()); </code></pre>
972,602
Limitations of Intel Assembly Syntax Compared to AT&T
<p>To me, Intel syntax is much easier to read. If I go traipsing through assembly forest concentrating only on Intel syntax, will I miss anything? Is there any reason I would want to switch to AT&amp;T (outside of being able to read others' AT&amp;T assembly)? My first clue is that gdb uses AT&amp;T by default.</p> <p>If this matters, my focus is only on any relation assembly and syntax may have to Linux/BSD and the C language.</p>
972,614
7
0
null
2009-06-09 21:28:04.623 UTC
33
2021-01-22 19:56:06.74 UTC
2021-01-22 19:56:06.74 UTC
null
224,132
null
115,711
null
1
93
linux|assembly|x86|att|intel-syntax
42,079
<p>There is really no advantage to one over the other. I agree though that Intel syntax is <strong>much</strong> easier to read. Keep in mind that, AFAIK, all GNU tools have the option to use Intel syntax also.</p> <p>It looks like you can make GDB use Intel syntax with this:</p> <pre> set disassembly-flavor intel </pre> <p>GCC can do Intel syntax with <code>-masm=intel</code>.</p>
582,723
How to import classes defined in __init__.py
<p>I am trying to organize some modules for my own use. I have something like this:</p> <pre><code>lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py </code></pre> <p>In <code>lib/__init__.py</code>, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in<code>__init__.py</code>. </p> <p>Rather than say:</p> <pre><code> lib/ __init__.py settings.py helperclass.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib.helperclass import Helper </code></pre> <p>I want something like this:</p> <pre><code> lib/ __init__.py #Helper defined in this file settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib import Helper </code></pre> <p>Is it possible, or do I have to separate the class into another file?</p> <h2>EDIT</h2> <p>OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py?</p> <p>The example <a href="http://docs.python.org/tutorial/modules.html" rel="noreferrer">here</a> describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?</p>
583,065
7
1
null
2009-02-24 17:35:55.93 UTC
34
2015-06-30 14:27:43.993 UTC
2009-02-24 19:39:20.017 UTC
scotty2012
53,007
scotty2012
53,007
null
1
131
python|package
173,177
<ol> <li><p>'<code>lib/</code>'s parent directory must be in <code>sys.path</code>. </p></li> <li><p>Your '<code>lib/__init__.py</code>' might look like this:</p> <pre><code>from . import settings # or just 'import settings' on old Python versions class Helper(object): pass </code></pre></li> </ol> <p>Then the following example should work:</p> <pre><code>from lib.settings import Values from lib import Helper </code></pre> <h3>Answer to the edited version of the question:</h3> <p><code>__init__.py</code> defines how your package looks from outside. If you need to use <code>Helper</code> in <code>settings.py</code> then define <code>Helper</code> in a different file e.g., '<code>lib/helper.py</code>'.</p> <pre> . | `-- import_submodule.py `-- lib |-- __init__.py |-- foo | |-- __init__.py | `-- someobject.py |-- helper.py `-- settings.py 2 directories, 6 files </pre> <p>The command:</p> <pre><code>$ python import_submodule.py </code></pre> <p>Output:</p> <pre><code>settings helper Helper in lib.settings someobject Helper in lib.foo.someobject # ./import_submodule.py import fnmatch, os from lib.settings import Values from lib import Helper print for root, dirs, files in os.walk('.'): for f in fnmatch.filter(files, '*.py'): print "# %s/%s" % (os.path.basename(root), f) print open(os.path.join(root, f)).read() print # lib/helper.py print 'helper' class Helper(object): def __init__(self, module_name): print "Helper in", module_name # lib/settings.py print "settings" import helper class Values(object): pass helper.Helper(__name__) # lib/__init__.py #from __future__ import absolute_import import settings, foo.someobject, helper Helper = helper.Helper # foo/someobject.py print "someobject" from .. import helper helper.Helper(__name__) # foo/__init__.py import someobject </code></pre>
1,091,030
How do I create, write, and read session data in CakePHP?
<p>can anyone give me an example on how to create Sessions and write data to it. I've seen syntax on how to write data to a session using write command. But how to create a session and retrieve the values in it.</p> <p>In my application, I have two data, form_id and user_id that needs to be used in all the page requests. So how do I save it as a session variable and use it across the application?</p> <p><strong>EDIT</strong></p> <pre><code>function register() { $userId=$this-&gt;User-&gt;registerUser($this-&gt;data); $this-&gt;Session-&gt;write('User.UserId',$userId); //echo "session".$this-&gt;Session-&gt;read('User.UserId'); $this-&gt;User-&gt;data=$this-&gt;data; if (!$this-&gt;User-&gt;validates()) { $this-&gt;Flash('Please enter valid inputs','/forms' ); return; } $this-&gt;Flash('User account created','/forms/homepage/'.$userId); } </code></pre> <p>How to use the session variable <strong>'User.UserId'</strong> instead of $userId in $this->Flash('User account created','/forms/homepage/'.<strong>$userId</strong>);</p> <p>And can I use this variable in all my view files,because in all the page requests I also pass the userId?</p> <p><strong>EDIT 2</strong></p> <p>I have 2 controllers,user and form. I write the userid to a session variable in the users<em>_controller. I have a view file called homepage.ctp,whose action is in the forms_controller.</em> Now how can I use the session variable defined in the users_controller in the homepage? Sorry if I am asking silly questions. I went through the cakebook,but my doubts weren't cleared. I'm also trying trial and error method of coding,so please help me.</p> <p><strong>EDIT 3</strong></p> <p>I have a session variable 'uid' which is the user id in the home page action of a controller.</p> <pre><code> $this-&gt;Session-&gt;write('uid',$this-&gt;data['Form']['created_by']); </code></pre> <p>I need the same variable in the design action method of the same controller. When I give </p> <pre><code> $uid=$this-&gt;Session-&gt;read('uid'); echo "uid: ".$uid; </code></pre> <p>the value is not echoed.</p> <p>Can't I use the session variable in the same controller?</p>
1,151,986
8
0
null
2009-07-07 08:31:23.677 UTC
2
2020-06-25 03:54:04.333 UTC
2019-08-21 11:34:01.667 UTC
null
979
null
86,038
null
1
12
session|cakephp-2.0
57,578
<p>I found out the reason why the uid wasn't being echoed(edit 3 part of the question). It is due to a silly mistake, had a white space after the end tag ?> in the controller. Now it is working fine. </p>
266,688
How do you know the correct path to use in a PHP require_once() statement
<p>As many do I have a config.php file in the root of a web app that I want to include in almost every other php file. So most of them have a line like:</p> <pre><code>require_once("config.php"); </code></pre> <p>or sometimes</p> <pre><code>require_once("../config.php"); </code></pre> <p>or even</p> <pre><code>require_once("../../config.php"); </code></pre> <p>But I never get it right the first time. I can't figure out what php is going to consider to be the current working directory when reading one of these files. It is apparently not the directory where the file containing the require_once() call is made because I can have two files in the same directory that have different paths for the config.php.</p> <p>How I have a situation where one path is correct for refreshing the page but an ajax can that updates part of the page requires a different path to the config.php in the require_once() statement;</p> <p>What's the secret? From where is that path evaluated?</p> <p>Shoot, I was afraid this wouldn't be a common problem - This is occurring under apache 2.2.8 and PHP 5.2.6 running on windows.</p>
266,775
9
0
null
2008-11-05 21:12:12.697 UTC
10
2013-12-01 01:47:50.093 UTC
2009-08-17 18:04:15.95 UTC
null
54,964
null
28,565
null
1
12
php
29,792
<p>The current working directory for PHP is the directory in which the called script file is located. If your files looked like this:</p> <pre><code>/A foo.php tar.php B/ bar.php </code></pre> <p>If you call foo.php (ex: <a href="http://example.com/foo.php" rel="noreferrer">http://example.com/foo.php</a>), the working directory will be /A/. If you call bar.php (ex: <a href="http://example.com/B/bar.php" rel="noreferrer">http://example.com/B/bar.php</a>), the working directory will be /A/B/.</p> <p>There is where it gets tricky. Let us say that foo.php is such:</p> <pre><code>&lt;?php require_once( 'B/bar.php' ); ?&gt; </code></pre> <p>And bar.php is:</p> <pre><code>&lt;?php require_once( 'tar.php'); ?&gt; </code></pre> <p>If we call foo.php, then bar.php will successfully call tar.php because tar.php and foo.php are in the same directory which happens to be the working directory. If you instead call bar.php, it will fail.</p> <p>Generally you will see either in all files:</p> <pre><code>require_once( realpath( dirname( __FILE__ ) ).'/../../path/to/file.php' ); </code></pre> <p>or with the config file:</p> <pre><code>// config file define( "APP_ROOT", realpath( dirname( __FILE__ ) ).'/' ); </code></pre> <p>with the rest of the files using:</p> <pre><code>require_once( APP_ROOT.'../../path/to/file.php' ); </code></pre>
333,367
Books/Tutorials to Learn SVG
<p>Does anyone here know SVG? If so, how did you learn it?</p> <p>Any books/tutorial pointer will be beneficial. Also I am a programmer, not a designer, so I want to pick up some skills there too.</p>
358,683
9
0
null
2008-12-02 08:40:36.007 UTC
14
2016-11-22 13:21:03.667 UTC
2011-05-13 11:26:15.71 UTC
null
56,338
versesane
38,306
null
1
13
graphics|svg
4,882
<p>I learned it developing <a href="http://www.w3.org/TR/SVGMobile12/" rel="nofollow noreferrer">SVG Tiny</a> software, mostly by reading the spec. SVG Tiny is basically a subset of full SVG and is focused on use in mobile phones and other "devices".</p> <p>Adding to the links from previous answers, <a href="http://www.kevlindev.com/tutorials/basics/index.htm" rel="nofollow noreferrer">KevLinDev</a> has a bunch of beginner-friendly tutorials.</p> <p>EDIT: Removed Ikivo Animator link, since it is now leading to an entirely different kind of site.</p>
974,964
best practice when returning smart pointers
<p>What is the best practice when returning a smart pointer, for example a boost::shared_ptr? Should I by standard return the smart pointer, or the underlying raw pointer? I come from C# so I tend to always return smart pointers, because it feels right. Like this (skipping const-correctness for shorter code): </p> <pre><code>class X { public: boost::shared_ptr&lt;Y&gt; getInternal() {return m_internal;} private: boost::shared_ptr&lt;Y&gt; m_internal; } </code></pre> <p>However I've seen some experienced coders returning the raw pointer, and putting the raw pointers in vectors. What is the right way to do it?</p>
975,011
9
0
null
2009-06-10 11:12:33.817 UTC
9
2014-05-30 11:27:03.313 UTC
2009-06-10 11:28:51.303 UTC
null
91,683
null
91,683
null
1
33
c++|boost|smart-pointers
26,669
<p>There is no "right" way. It really depends on the context.</p> <p>You can internally handle memory with a smart pointer and externally give references or raw pointers. After all, the user of your interface doesn't need to know how you manage memory internally. In a synchronous context this is safe and efficient. In an asynchronous context, there are many pitfalls.</p> <p>If you're unsure about what to do you can safely return smart pointers to your caller. The object will be deallocated when the references count reaches zero. Just make sure that you don't have a class that keeps smart pointers of objects for ever thus preventing the deallocation when needed.</p> <p>As a last note, in C++ don't overuse dynamically allocated objects. There are many cases where you don't need a pointer and can work on references and const references. That's safer and reduces the pressure on the memory allocator.</p>
1,088,648
SQL: sum 3 columns when one column has a null value?
<pre><code>SELECT sum(TotalHoursM) + (TotalHoursT) + (TotalHoursW) + (TotalHoursTH) + (TotalHoursF) AS TOTAL FROM LeaveRequest </code></pre>
1,088,655
9
1
null
2009-07-06 18:50:13.983 UTC
9
2020-06-18 15:42:26.677 UTC
2009-07-08 08:20:46.333 UTC
null
116
null
1,709,270
null
1
82
sql
230,410
<p>If the column has a 0 value, you are fine, my guess is that you have a problem with a Null value, in that case you would need to use <code>IsNull(Column, 0)</code> to ensure it is always 0 at minimum.</p>
163,591
Bash autocompletion in Emacs shell-mode
<p>In the GNOME Terminal, Bash does smart auto-completion. For example</p> <pre><code>apt-get in&lt;TAB&gt; </code></pre> <p>becomes</p> <pre><code>apt-get install </code></pre> <p>In Emacs shell-mode, this auto-completion doesn't work, even after I explicitly source <code>/etc/bash_completion</code>. The above example sticks as <code>in</code> or auto-completes with a filename in the current directory rather than a valid <code>apt-get</code> command option. Presumably, this is because Emacs is intercepting the Tab key-press. How do I enable smart auto-completion in <code>shell-mode</code>?</p>
8,152,737
9
2
null
2008-10-02 17:37:02.493 UTC
27
2020-01-16 06:59:54.9 UTC
2008-11-14 19:17:54.62 UTC
Kevin Fairchild
3,743
Chris Conway
1,412
null
1
98
bash|shell|emacs|autocomplete
30,332
<p>I know this question is three years old, but it's something that I've also been interested in solving. A Web search directed me to a piece of elisp that makes Emacs use bash for completion in shell mode. It works for me, in any case.</p> <p>Check it out at <a href="https://github.com/szermatt/emacs-bash-completion">https://github.com/szermatt/emacs-bash-completion</a> .</p>
278,439
Creating a temporary directory in Windows?
<p>What's the best way to get a temp directory name in Windows? I see that I can use <code>GetTempPath</code> and <code>GetTempFileName</code> to create a temporary file, but is there any equivalent to the Linux / BSD <a href="http://linux.die.net/man/3/mkdtemp" rel="noreferrer"><code>mkdtemp</code></a> function for creating a temporary directory?</p>
278,457
9
3
null
2008-11-10 16:50:34.673 UTC
22
2020-12-14 14:29:34.993 UTC
2012-04-27 17:21:23.11 UTC
null
168,868
Josh Kelley
25,507
null
1
150
c#|.net|windows|temporary-directory
101,620
<p>No, there is no equivalent to mkdtemp. The best option is to use a combination of <a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath" rel="noreferrer">GetTempPath</a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getrandomfilename" rel="noreferrer">GetRandomFileName</a>.</p> <p>You would need code similar to this:</p> <pre><code>public string GetTemporaryDirectory() { string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } </code></pre>
1,008,668
How secure is a HTTP POST?
<p>Is a POST secure enough to send login credentials over?</p> <p>Or is an SSL connection a <strong>must</strong>?</p>
1,008,671
14
7
null
2009-06-17 18:05:31.43 UTC
28
2020-02-22 22:33:26.61 UTC
null
null
null
null
123,908
null
1
77
security|post|httpwebrequest|xmlhttprequest
88,021
<p><strong>SSL is a must.</strong></p> <p>POST method is not more secure than GET as it also gets sent unencrypted over network.</p> <p>SSL will cover the whole HTTP communication and encrypt the HTTP data being transmitted between the client and the server.</p>
648,196
Random row from Linq to Sql
<p>What is the best (and fastest) way to retrieve a random row using Linq to SQL when I have a condition, e.g. some field must be true?</p>
648,247
14
2
null
2009-03-15 17:37:16.343 UTC
55
2017-10-08 13:44:29.117 UTC
2016-12-27 15:20:12.653 UTC
Julien Poulin
1,033,581
Julien Poulin
65,060
null
1
116
c#|.net|linq-to-sql
71,819
<p>You can do this at the database, by using a fake UDF; in a partial class, add a method to the data context:</p> <pre><code>partial class MyDataContext { [Function(Name="NEWID", IsComposable=true)] public Guid Random() { // to prove not used by our C# code... throw new NotImplementedException(); } } </code></pre> <p>Then just <code>order by ctx.Random()</code>; this will do a random ordering at the SQL-Server courtesy of <code>NEWID()</code>. i.e.</p> <pre><code>var cust = (from row in ctx.Customers where row.IsActive // your filter orderby ctx.Random() select row).FirstOrDefault(); </code></pre> <p>Note that this is only suitable for small-to-mid-size tables; for huge tables, it will have a performance impact at the server, and it will be more efficient to find the number of rows (<code>Count</code>), then pick one at random (<code>Skip/First</code>).</p> <hr> <p>for count approach:</p> <pre><code>var qry = from row in ctx.Customers where row.IsActive select row; int count = qry.Count(); // 1st round-trip int index = new Random().Next(count); Customer cust = qry.Skip(index).FirstOrDefault(); // 2nd round-trip </code></pre>
318,888
Solving "Who owns the Zebra" programmatically?
<p>Edit: this puzzle is also known as "Einstein's Riddle"</p> <p>The <a href="https://en.wikipedia.org/wiki/Zebra_Puzzle" rel="noreferrer">Who owns the Zebra</a> (you can <a href="https://www.brainzilla.com/logic/zebra/einsteins-riddle/" rel="noreferrer" title="Einstein&#39;s Riddle">try the online version here</a>) is an example of a classic set of puzzles and I bet that most people on Stack Overflow can solve it with pen and paper. But what would a programmatic solution look like?</p> <p>Based on the clues listed below...</p> <ul> <li>There are five houses.</li> <li>Each house has its own unique color.</li> <li>All house owners are of different nationalities.</li> <li>They all have different pets.</li> <li>They all drink different drinks.</li> <li>They all smoke different cigarettes.</li> <li>The English man lives in the red house.</li> <li>The Swede has a dog.</li> <li>The Dane drinks tea.</li> <li>The green house is on the left side of the white house.</li> <li>They drink coffee in the green house.</li> <li>The man who smokes Pall Mall has birds.</li> <li>In the yellow house they smoke Dunhill.</li> <li>In the middle house they drink milk.</li> <li>The Norwegian lives in the first house.</li> <li>The man who smokes Blend lives in the house next to the house with cats.</li> <li>In the house next to the house where they have a horse, they smoke Dunhill.</li> <li>The man who smokes Blue Master drinks beer.</li> <li>The German smokes Prince.</li> <li>The Norwegian lives next to the blue house.</li> <li>They drink water in the house next to the house where they smoke Blend. </li> </ul> <p>...who owns the Zebra?</p>
320,981
15
4
null
2008-11-25 21:14:26.783 UTC
115
2022-01-10 10:59:05.423 UTC
2017-02-23 12:21:03.753 UTC
Gortok
55,283
divideandconquer.se
20,444
null
1
129
language-agnostic|logic|constraint-programming|zebra-puzzle
27,323
<p>Here's a solution in Python based on constraint-programming:</p> <pre class="lang-py prettyprint-override"><code>from constraint import AllDifferentConstraint, InSetConstraint, Problem # variables colors = "blue red green white yellow".split() nationalities = "Norwegian German Dane Swede English".split() pets = "birds dog cats horse zebra".split() drinks = "tea coffee milk beer water".split() cigarettes = "Blend, Prince, Blue Master, Dunhill, Pall Mall".split(", ") # There are five houses. minn, maxn = 1, 5 problem = Problem() # value of a variable is the number of a house with corresponding property variables = colors + nationalities + pets + drinks + cigarettes problem.addVariables(variables, range(minn, maxn+1)) # Each house has its own unique color. # All house owners are of different nationalities. # They all have different pets. # They all drink different drinks. # They all smoke different cigarettes. for vars_ in (colors, nationalities, pets, drinks, cigarettes): problem.addConstraint(AllDifferentConstraint(), vars_) # In the middle house they drink milk. #NOTE: interpret "middle" in a numerical sense (not geometrical) problem.addConstraint(InSetConstraint([(minn + maxn) // 2]), ["milk"]) # The Norwegian lives in the first house. #NOTE: interpret "the first" as a house number problem.addConstraint(InSetConstraint([minn]), ["Norwegian"]) # The green house is on the left side of the white house. #XXX: what is "the left side"? (linear, circular, two sides, 2D house arrangment) #NOTE: interpret it as 'green house number' + 1 == 'white house number' problem.addConstraint(lambda a,b: a+1 == b, ["green", "white"]) def add_constraints(constraint, statements, variables=variables, problem=problem): for stmt in (line for line in statements if line.strip()): problem.addConstraint(constraint, [v for v in variables if v in stmt]) and_statements = """ They drink coffee in the green house. The man who smokes Pall Mall has birds. The English man lives in the red house. The Dane drinks tea. In the yellow house they smoke Dunhill. The man who smokes Blue Master drinks beer. The German smokes Prince. The Swede has a dog. """.split("\n") add_constraints(lambda a,b: a == b, and_statements) nextto_statements = """ The man who smokes Blend lives in the house next to the house with cats. In the house next to the house where they have a horse, they smoke Dunhill. The Norwegian lives next to the blue house. They drink water in the house next to the house where they smoke Blend. """.split("\n") #XXX: what is "next to"? (linear, circular, two sides, 2D house arrangment) add_constraints(lambda a,b: abs(a - b) == 1, nextto_statements) def solve(variables=variables, problem=problem): from itertools import groupby from operator import itemgetter # find &amp; print solutions for solution in problem.getSolutionIter(): for key, group in groupby(sorted(solution.iteritems(), key=itemgetter(1)), key=itemgetter(1)): print key, for v in sorted(dict(group).keys(), key=variables.index): print v.ljust(9), print if __name__ == '__main__': solve() </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>1 yellow Norwegian cats water Dunhill 2 blue Dane horse tea Blend 3 red English birds milk Pall Mall 4 green German zebra coffee Prince 5 white Swede dog beer Blue Master </code></pre> <p>It takes 0.6 seconds (CPU 1.5GHz) to find the solution.<br> The answer is "German owns zebra."</p> <hr> <p>To install the <a href="http://labix.org/python-constraint" rel="noreferrer"><code>constraint</code> module</a> via <code>pip</code>: pip install python-constraint</p> <p>To install manually:</p> <ul> <li><p>download: </p> <p>$ wget <a href="https://pypi.python.org/packages/source/p/python-constraint/python-constraint-1.2.tar.bz2#md5=d58de49c85992493db53fcb59b9a0a45" rel="noreferrer">https://pypi.python.org/packages/source/p/python-constraint/python-constraint-1.2.tar.bz2#md5=d58de49c85992493db53fcb59b9a0a45</a></p></li> <li><p>extract (Linux/Mac/BSD):</p> <p>$ bzip2 -cd python-constraint-1.2.tar.bz2 | tar xvf -</p></li> <li><p>extract (Windows, with <a href="http://www.7-zip.org/" rel="noreferrer">7zip</a>):</p> <p>> 7z e python-constraint-1.2.tar.bz2<br> > 7z e python-constraint-1.2.tar</p></li> <li><p>install:</p> <p>$ cd python-constraint-1.2<br> $ python setup.py install</p></li> </ul>
41,319
Checking if a list is empty with LINQ
<p>What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type <code>IEnumerable&lt;T&gt;</code> and doesn't have a Count property.</p> <p>Right now I'm tossing up between this:</p> <pre><code>if (myList.Count() == 0) { ... } </code></pre> <p>and this:</p> <pre><code>if (!myList.Any()) { ... } </code></pre> <p>My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count.</p> <p>That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list?</p> <p><strong>Edit</strong> @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this:</p> <pre><code>public static bool IsEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; list) { if (list is ICollection&lt;T&gt;) return ((ICollection&lt;T&gt;)list).Count == 0; return !list.Any(); } </code></pre>
41,324
16
4
null
2008-09-03 08:35:24.98 UTC
26
2015-05-11 15:10:42.53 UTC
2012-10-31 15:02:17.293 UTC
Matt Hamilton
1,707,081
Matt Hamilton
615
null
1
128
c#|.net|linq|list
155,173
<p>You could do this:</p> <pre><code>public static Boolean IsEmpty&lt;T&gt;(this IEnumerable&lt;T&gt; source) { if (source == null) return true; // or throw an exception return !source.Any(); } </code></pre> <p><strong>Edit</strong>: Note that simply using the .Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the .Count property of those, instead of the .Any() approach, but then fall back to .Any() if no guarantee can be made.</p>
338,667
Is there an upside down caret character?
<p>I have to maintain a large number of classic ASP pages, many of which have tabular data with no sort capabilities at all. Whatever order the original developer used in the database query is what you're stuck with.</p> <p>I want to to tack on some basic sorting to a bunch of these pages, and I'm doing it all client side with javascript. I already have the basic script done to sort a given table on a given column in a given direction, and it works well as long as the table is limited by certain conventions we follow here.</p> <p>What I want to do for the UI is just indicate sort direction with the caret character ( <code>^</code> ) and ... what? Is there a special character that is the direct opposite of a caret? The letter <code>v</code> won't quite cut it. Alternatively, is there another character pairing I can use?</p>
338,691
17
3
null
2008-12-03 21:03:02.047 UTC
50
2022-06-17 06:57:56.343 UTC
2022-02-04 15:05:03.893 UTC
Joel Coehoorn
3,043
Joel Coehoorn
3,043
null
1
318
html|sorting|user-interface|character-encoding|character
442,959
<p>There's &#9650;: <a href="http://www.fileformat.info/info/unicode/char/25b2/index.htm" rel="noreferrer">&amp;#9650;</a> and &#9660;: <a href="http://www.fileformat.info/info/unicode/char/25bc/index.htm" rel="noreferrer">&amp;#9660;</a></p>
94,101
How to type faster
<p>I've typed around 75wpm for the last few years but I've always wondered how people type +100wpm. </p> <p>I've searched but I primarily find typing tutors that teach you to type.. not teach you to type faster. So far the only tip I've come across is to learn dvorak. </p> <p>Are there exercises or tips to help break through the 75wpm wall?</p>
94,137
25
3
null
2008-09-18 16:20:46.463 UTC
21
2019-05-21 05:41:01.19 UTC
2008-09-18 16:32:25.627 UTC
Mark Biek
305
raema
17,177
null
1
25
typing|touch-typing|performance|wpm
11,649
<p>Setting yourself up in an ergonomic typing position is a good start. Take a look at the diagram <a href="http://www.yale.edu/ergo/neutral.htm" rel="noreferrer">here</a> - notice the arms in a straight line, feet on the floor, etc. </p> <p>In my experience most people tend to slow down when they get to unusual keys - numbers, symbols, punctuation, etc, so maybe some focused practice on those key combinations? practice typing out long strings of numbers and symbols, maybe try to use some Perl code as your copy-page :)</p>
285,793
What is a serialVersionUID and why should I use it?
<p>Eclipse issues warnings when a <code>serialVersionUID</code> is missing. </p> <blockquote> <p>The serializable class Foo does not declare a static final serialVersionUID field of type long</p> </blockquote> <p>What is <code>serialVersionUID</code> and why is it important? Please show an example where missing <code>serialVersionUID</code> will cause a problem.</p>
285,809
25
1
null
2008-11-12 23:24:56.797 UTC
807
2021-08-05 12:50:59.94 UTC
2015-03-17 22:44:09.937 UTC
null
260,990
askgelal
33,203
null
1
3,324
java|serialization|serialversionuid
1,084,940
<p>The docs for <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/Serializable.html" rel="noreferrer"><code>java.io.Serializable</code></a> are probably about as good an explanation as you'll get:</p> <blockquote> <p>The serialization runtime associates with each serializable class a version number, called a <code>serialVersionUID</code>, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different <code>serialVersionUID</code> than that of the corresponding sender's class, then deserialization will result in an <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InvalidClassException.html" rel="noreferrer"><code>InvalidClassException</code></a>. A serializable class can declare its own <code>serialVersionUID</code> explicitly by declaring a field named <code>serialVersionUID</code> that must be static, final, and of type <code>long</code>:</p> </blockquote> <blockquote> <pre><code>ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L; </code></pre> </blockquote> <blockquote> <p>If a serializable class does not explicitly declare a <code>serialVersionUID</code>, then the serialization runtime will calculate a default <code>serialVersionUID</code> value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is <em>strongly recommended</em> that all serializable classes explicitly declare <code>serialVersionUID</code> values, since the default <code>serialVersionUID</code> computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected <code>InvalidClassExceptions</code> during deserialization. Therefore, to guarantee a consistent <code>serialVersionUID</code> value across different java compiler implementations, a serializable class must declare an explicit <code>serialVersionUID</code> value. It is also strongly advised that explicit <code>serialVersionUID</code> declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class β€” <code>serialVersionUID</code> fields are not useful as inherited members.</p> </blockquote>
6,360,024
jQuery each() with a delay
<p>So, I would like an element to fade in and wait half a second, then fade the next in etc...</p> <p>My code:</p> <pre><code>$('.comment').each(function() { $(this).css({'opacity':0.0}).animate({ 'opacity':1.0 }, 450).delay(500); }); </code></pre> <p>I'm obviously doing something really silly.... (I hope)... My question is: Is this even possible? if not - can anyone point me in the right direction? </p> <p>Thanking you!</p>
6,360,189
5
3
null
2011-06-15 15:14:15.853 UTC
4
2016-08-16 12:43:34.097 UTC
null
null
null
null
285,178
null
1
17
javascript|jquery
43,465
<p>Or, something like this:</p> <pre><code>$.each($('.comment'), function(i, el){ $(el).css({'opacity':0}); setTimeout(function(){ $(el).animate({ 'opacity':1.0 }, 450); },500 + ( i * 500 )); }); </code></pre> <p>demo => <a href="http://jsfiddle.net/steweb/9uS56/" rel="noreferrer">http://jsfiddle.net/steweb/9uS56/</a></p>
6,782,658
How to get default gateway in Mac OSX
<p>I need to retrieve the default gateway on a Mac machine. I know that in Linux route -n will give an output from which I can easily retrieve this information. However this is not working in Mac OSX(Snow Leopard). </p> <p>I also tried <code>netstat -nr | grep 'default'</code>, but I was hoping for a cleaner output like that produced by <code>route -n</code> in Linux/Unix. <code>netstat -nr</code> lists all the interfaces and the default gateway for them.</p> <p>Any kind of suggestion or a hint in the right direction will be appreciated.</p>
7,627,059
5
2
null
2011-07-21 20:54:22.247 UTC
46
2019-12-02 11:46:53.897 UTC
2013-03-05 19:53:28.143 UTC
null
537,031
null
478,199
null
1
132
macos|routes|netstat|ifconfig
246,054
<p>You can try with:</p> <pre><code>route -n get default </code></pre> <p>It is not the same as GNU/Linux's <code>route -n</code> (or even <code>ip route show</code>) but is useful for checking the default route information. Also, you can check the route that packages will take to a particular host. E.g.</p> <pre><code>route -n get www.yahoo.com </code></pre> <p>The output would be similar to:</p> <pre><code> route to: 98.137.149.56 destination: default mask: 128.0.0.0 gateway: 5.5.0.1 interface: tun0 flags: &lt;UP,GATEWAY,DONE,STATIC,PRCLONING&gt; recvpipe sendpipe ssthresh rtt,msec rttvar hopcount mtu expire 0 0 0 0 0 0 1500 0 </code></pre> <p>IMHO <code>netstat -nr</code> is what you need. Even MacOSX's Network utility app(*) uses the output of netstat to show routing information. <img src="https://i.stack.imgur.com/6rhc4.png" alt="Network utility screenshot displaying routing table information" /></p> <p>I hope this helps :)</p> <p>(*) You can start Network utility with <code>open /Applications/Utilities/Network\ Utility.app</code></p>
6,773,866
Download file and automatically save it to folder
<p>I'm trying to make a UI for downloading files from my site. The site have zip-files and these need to be downloaded to the directory entered by the user. However, I can't succeed to download the file, it just opens up from a temporary folder.</p> <p>Code:</p> <pre><code>private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { e.Cancel = true; string filepath = null; filepath = textBox1.Text; WebClient client = new WebClient(); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadFileAsync(e.Url, filepath); } </code></pre> <p>Full sourcecode: <a href="http://en.paidpaste.com/LqEmiQ" rel="noreferrer">http://en.paidpaste.com/LqEmiQ</a></p>
6,866,340
6
10
null
2011-07-21 09:19:33.913 UTC
10
2018-03-30 08:50:49.227 UTC
2011-07-21 09:47:00.303 UTC
null
5,772,384
null
360,186
null
1
10
c#|file|download|save
145,357
<p>Why not just bypass the WebClient's file handling pieces altogether. Perhaps something similar to this:</p> <pre><code> private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { e.Cancel = true; WebClient client = new WebClient(); client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted); client.DownloadDataAsync(e.Url); } void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { string filepath = textBox1.Text; File.WriteAllBytes(filepath, e.Result); MessageBox.Show("File downloaded"); } </code></pre>
6,617,620
mysql WHERE IN array string / username
<p>Code:</p> <pre><code>$friendsArray = array("zac1987", "peter", "micellelimmeizheng1152013142"); $friendsArray2 = join(', ',$friendsArray); $query120 = "SELECT picturemedium FROM users WHERE username IN ('$friendsArray2')"; echo $query120; </code></pre> <p>This is the output :</p> <pre><code>SELECT picturemedium FROM users WHERE username IN ('zac1987, peter, micellelimmeizheng1152013142') </code></pre> <p>It fails because usernames are not wrapped by single quotes like 'zac1987', 'peter', 'mice...'. How can each username be wrapped with single quotes?</p>
6,617,658
6
0
null
2011-07-07 21:57:04.133 UTC
6
2022-02-06 06:48:18.85 UTC
2018-02-18 17:34:17.45 UTC
null
4,907,496
null
650,312
null
1
14
php|mysql|arrays
82,431
<p>Let's loop through each name one by one, escaping each.</p> <p>I'm going to recommend that you use an actual MySQL escaping function rather than just wrapping quotes around, to ensure that the data actually goes into the query correctly. (Otherwise, if I entered a name like <code>It's me!</code>, the single quote would mess up the query.) I'm going to assume here that you're using <a href="http://php.net/pdo" rel="noreferrer">PDO</a> (which you should!), but, if not, replace references to <code>PDO::quote</code> with <code>mysql_real_escape_string</code>.</p> <pre><code>foreach($friendsArray as $key =&gt; $friend) { $friendsArray[$key] = PDO::quote($friend); } $friendsArray2 = join(', ', $friendsArray); </code></pre>
6,850,276
How to convert dataURL to file object in javascript?
<p>I need to convert a dataURL to a File object in Javascript in order to send it over using AJAX. Is it possible? If yes, please tell me how.</p>
7,261,048
6
6
null
2011-07-27 19:42:09.963 UTC
38
2022-02-13 09:20:14.667 UTC
2018-07-17 14:02:48.897 UTC
null
860,857
null
733,612
null
1
71
javascript|jquery|fileapi
104,351
<p>If you need to send it over ajax, then there's no need to use a <code>File</code> object, only <code>Blob</code> and <code>FormData</code> objects are needed.</p> <p>As I sidenote, why don't you just send the base64 string to the server over ajax and convert it to binary server-side, using PHP's <code>base64_decode</code> for example? Anyway, the standard-compliant code from <a href="https://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata">this answer</a> works in Chrome 13 and WebKit nightlies:</p> <pre><code>function dataURItoBlob(dataURI) { // convert base64 to raw binary data held in a string // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this var byteString = atob(dataURI.split(',')[1]); // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to an ArrayBuffer var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i &lt; byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } //Old Code //write the ArrayBuffer to a blob, and you're done //var bb = new BlobBuilder(); //bb.append(ab); //return bb.getBlob(mimeString); //New Code return new Blob([ab], {type: mimeString}); } </code></pre> <p>Then just append the blob to a new FormData object and post it to your server using ajax:</p> <pre><code>var blob = dataURItoBlob(someDataUrl); var fd = new FormData(document.forms[0]); var xhr = new XMLHttpRequest(); fd.append("myFile", blob); xhr.open('POST', '/', true); xhr.send(fd); </code></pre>
6,840,332
Rename multiple files by replacing a particular pattern in the filenames using a shell script
<blockquote> <p>Write a simple script that will automatically rename a number of files. As an example we want the file *001.jpg renamed to user defined string + 001.jpg (ex: MyVacation20110725_001.jpg) The usage for this script is to get the digital camera photos to have file names that make some sense.</p> </blockquote> <p>I need to write a shell script for this. Can someone suggest how to begin?</p>
6,840,404
8
4
null
2011-07-27 06:38:51.08 UTC
74
2022-07-01 06:00:18.35 UTC
2013-03-23 10:47:22.867 UTC
null
488,657
null
567,797
null
1
204
shell
218,387
<p>An example to help you get off the ground.</p> <pre><code>for f in *.jpg; do mv &quot;$f&quot; &quot;$(echo &quot;$f&quot; | sed s/IMG/VACATION/)&quot;; done </code></pre> <p>In this example, I am assuming that all your image files contain the string <code>IMG</code> and you want to replace <code>IMG</code> with <code>VACATION</code>.</p> <p>The shell automatically evaluates <code>*.jpg</code> to all the matching files.</p> <p>The second argument of <code>mv</code> (the new name of the file) is the output of the <code>sed</code> command that replaces <code>IMG</code> with <code>VACATION</code>.</p> <p>If your filenames include whitespace pay careful attention to the <code>&quot;$f&quot;</code> notation. You need the double-quotes to preserve the whitespace.</p>
6,817,870
ASP.NET strange compilation error
<p>I don't know what's wrong with my machine, but it's a while that I'm getting the following strange error from ASP.NET (for all my applications).</p> <pre><code>Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: The compiler failed with error code -1073741502. Show Detailed Compiler Output: C:\Windows\SysWOW64\inetsrv&gt; "C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe" /t:library /utf8output /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\75855fbd\1e953b27\assembly\dl3\2689d6b5\f0791420_961fcc01\wnvhtmlconvert.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Entity\v4.0_4.0.0.0__b77a5c561934e089\System.Web.Entity.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\75855fbd\1e953b27\assembly\dl3\d08c81cd\4d77c01f_961fcc01\AjaxControlToolkit.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activation\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activation.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.ApplicationServices\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.ApplicationServices.dll" ......AND SO ON..... </code></pre> <p>Facts:</p> <ol> <li>Killing worker process fixes the problem temporarily</li> <li>I even reinstalled my .NET framework! It didn't work.</li> <li>Restarting IIS doesn't help</li> </ol> <p>What can cause this problem?</p>
6,929,129
20
1
null
2011-07-25 14:43:47.96 UTC
19
2019-11-27 19:37:34.667 UTC
2016-12-17 18:09:30.05 UTC
null
63,550
null
452,830
null
1
58
.net|asp.net|iis
141,196
<p>OK, after days struggling with this issue, I finally fixed it.</p> <ul> <li>Not by clearing ASP.NET temp</li> <li>Not by reinstalling the .NET framework!</li> </ul> <p>Simple!</p> <ul> <li>I changed the application pool identity from "Local system" to "ApplicationPoolIdentity"</li> </ul> <p>Apparently there was a permission error with my local system that the C# compiler (csc.exe) could not access some resources and source codes.</p> <p>In order to change your AppPool identity follow steps given here: <a href="http://learn.iis.net/page.aspx/624/application-pool-identities/" rel="noreferrer">http://learn.iis.net/page.aspx/624/application-pool-identities/</a></p>
15,683,975
IF, ELIF, ELSE in T-SQL
<p>I am working in SQL Server 2008 and trying to use a <code>IF, ELIF, ELSE</code> statement in the <code>SELECT</code> section of my code. What I want to do is the following:</p> <pre><code>IF BO.VALUE &lt; BO.REFERENCELOWERLIMIT THEN (BO.VALUE - BO.REFERENCELOWERLIMIT) #I WANT THIS TO BE NEGATIVE ELSE IF BO.REFERENCELOWERLIMIT &lt;= BO.VALUE &lt;= BO.REFERENCEUPPERLIMIT THEN BO.VALUE ELSE (BO.REFERENCEUPPERLIMIT - BO.VALUE) </code></pre> <p>The problem is that I do not understand how to do a IF, ELIF, ELSE type transaction in SQL. I have tried to search for this type of example and came across python examples...wrong language so I did a search on the MSDBN site and did not see this sort of work, just IF/ELSE.</p> <p>Thank You</p>
15,684,026
2
4
null
2013-03-28 14:06:58.4 UTC
1
2016-07-21 21:46:05.007 UTC
2013-03-28 14:08:18.993 UTC
null
330,315
null
1,510,267
null
1
13
sql-server-2008|tsql
70,017
<p>You want a <code>CASE</code> expression. <code>CASE</code> evaluates in order and the first match is what is returned in the query.</p> <pre><code>SELECT CASE WHEN BO.VALUE &lt; BO.REFERENCELOWERLIMIT THEN (BO.VALUE - BO.REFERENCELOWERLIMIT) WHEN BO.VALUE BETWEEN BO.REFERENCELOWERLIMIT AND BO.REFERENCEUPPERLIMIT THEN BO.VALUE ELSE (BO.REFERENCEUPPERLIMIT - BO.VALUE) END as MyColumnAlias ... </code></pre>
15,966,726
How to change method behaviour through reflection?
<p>I have a a static method in some legacy code, which is called by multiple clients. I obviously have no options to override it, or change behaviour through dependency injection. I am not allowed to modify the existing class.</p> <p>What I want to do now is change the behaviour (that method - with the same signature and return type) using reflection. </p> <p>Is it possible ? If not, can any design pattern rescue me ?</p> <p>Thanks !</p> <p>EDIT : There is some confusion on what can I change/modify. I cannot change any existing class/method - but I can add more classes to the project. The best I can do with the existing classes is annotate them. This is all done to avoid breaking anything in the existing code - which means a complete round of testing for a big project.</p> <p>EDIT 2 : java.lang.Instrumentation is not available for Android - or else it sounds like a good fit !</p>
15,966,918
3
5
null
2013-04-12 08:38:31.617 UTC
4
2022-03-24 10:03:55.827 UTC
2013-04-12 09:00:05.613 UTC
null
430,720
null
430,720
null
1
32
java|android|design-patterns|legacy-code
47,378
<p>Sounds like a weird requirement... </p> <p>Anyway, reflection does not allow you to change code behaviour, it can only explore current code, invoke methods and constuctors, change fields values, that kind of things.</p> <p>If you want to actually change the behaviour of a method you would have to use a bytecode manipulation library such as ASM. But this will not be very easy, probably not a good idea...</p> <p>Patterns that might help you :</p> <ul> <li>If the class is not final and you can modify the clients, extend the existing class and overload the method, with your desired behaviour. Edit : that would work only if the method were not static !</li> <li>Aspect programming : add interceptors to the method using AspectJ</li> </ul> <p>Anyway, the most logical thing to do would be to find a way to modify the existing class, work-arounds will just make your code more complicated and harder to maintain.</p> <p>Good luck.</p>
25,157,642
How to repeatedly run bash script every N seconds?
<p>I have a shell script printing some statistics like disk info, memory use and so on. But it shows information only once after the script runs and exits. Can I make this script be run repeatedly (like <code>htop</code> for example) or something like that? I want this info to be updated every 5-10 seconds.</p>
25,158,585
2
5
null
2014-08-06 10:09:49.273 UTC
10
2019-04-30 20:01:17.53 UTC
2019-04-30 20:01:17.53 UTC
null
648,658
null
3,812,402
null
1
25
linux|bash
34,273
<p>A slight improvement to my comment: if your script exits with <em>true</em> (e.g. when it ends with <code>exit 0</code>), you can run</p> <pre><code>while script; do sleep 10; done </code></pre> <p>This is the canonical way to repeat a command as long as it doesn't fail.</p>
10,278,683
How safe is it to store sessions with Redis?
<p>I'm currently using MySql to store my sessions. It works great, but it is a bit slow.</p> <p>I've been asked to use Redis, but I'm wondering if it is a good idea because I've heard that Redis delays write operations. I'm a bit afraid because sessions need to be real-time.</p> <p>Has anyone experienced such problems?</p>
10,279,573
3
10
null
2012-04-23 10:19:18.91 UTC
48
2018-03-27 04:24:41.12 UTC
2018-03-24 02:55:34.097 UTC
null
3,260,543
null
962,602
null
1
108
session|redis
76,364
<p>Redis is perfect for storing sessions. All operations are performed in memory, and so reads and writes will be fast. </p> <p>The second aspect is persistence of session state. Redis gives you a lot of flexibility in how you want to persist session state to your hard-disk. You can go through <a href="http://redis.io/topics/persistence" rel="noreferrer">http://redis.io/topics/persistence</a> to learn more, but at a high level, here are your options - </p> <ol> <li>If you cannot afford losing any sessions, set <code>appendfsync always</code> in your configuration file. With this, Redis guarantees that any write operations are saved to the disk. The disadvantage is that write operations will be slower.</li> <li>If you are okay with losing about 1s worth of data, use <code>appendfsync everysec</code>. This will give great performance with reasonable data guarantees</li> </ol>
33,312,175
matching any character including newlines in a Python regex subexpression, not globally
<p>I want to use <a href="https://docs.python.org/2/library/re.html#re.MULTILINE" rel="noreferrer"><code>re.MULTILINE</code></a> but <strong>NOT</strong> <a href="https://docs.python.org/2/library/re.html#re.DOTALL" rel="noreferrer"><code>re.DOTALL</code></a>, so that I can have a regex that includes both an "any character" wildcard and the normal <code>.</code> wildcard that doesn't match newlines.</p> <p>Is there a way to do this? What should I use to match any character in those instances that I want to include newlines?</p>
33,312,193
2
5
null
2015-10-23 22:13:37.923 UTC
13
2022-03-14 18:16:18.41 UTC
2015-11-13 13:27:03.093 UTC
null
44,330
null
44,330
null
1
87
python|regex
77,261
<p>To match a newline, or &quot;any symbol&quot; without <code>re.S</code>/<code>re.DOTALL</code>, you may use any of the following:</p> <ol> <li><p><code>(?s).</code> - the <a href="https://www.regular-expressions.info/modifiers.html" rel="noreferrer">inline modifier group</a> with <code>s</code> flag on sets a scope where all <code>.</code> patterns match any char including line break chars</p> </li> <li><p>Any of the following work-arounds:</p> </li> </ol> <pre><code>[\s\S] [\w\W] [\d\D] </code></pre> <p>The main idea is that the opposite shorthand classes inside a character class match any symbol there is in the input string.</p> <p>Comparing it to <code>(.|\s)</code> and other variations with alternation, the character class solution is much more efficient as it involves much less backtracking (when used with a <code>*</code> or <code>+</code> quantifier). Compare the small example: it takes <a href="https://regex101.com/r/pX7lM6/1" rel="noreferrer"><code>(?:.|\n)+</code></a> 45 steps to complete, and it takes <a href="https://regex101.com/r/pX7lM6/2" rel="noreferrer"><code>[\s\S]+</code></a> just 2 steps.</p> <p>See a <a href="https://ideone.com/GZEQNf" rel="noreferrer">Python demo</a> where I am matching a line starting with <code>123</code> and up to the first occurrence of <code>3</code> at the start of a line and including the rest of that line:</p> <pre class="lang-py prettyprint-override"><code>import re text = &quot;&quot;&quot;abc 123 def 356 more text...&quot;&quot;&quot; print( re.findall(r&quot;^123(?s:.*?)^3.*&quot;, text, re.M) ) # =&gt; ['123\ndef\n356'] print( re.findall(r&quot;^123[\w\W]*?^3.*&quot;, text, re.M) ) # =&gt; ['123\ndef\n356'] </code></pre>
13,765,995
ELMAH - MVC 3 - 403 - Forbidden: Access is denied
<p>I have installed <a href="https://github.com/alexanderbeletsky/elmah.mvc">Elmah for MVC</a> using NuGet, I'am able to login with success error in the db. The only problem is that I cannot access the <code>/elmah</code> URL to access the Error Log Page.</p> <p>Here part of my configuration, could you please point out if I have any misconfiguration? </p> <p>Thanks</p> <p>ERROR</p> <blockquote> <p><em>403 - Forbidden: Access is denied.<br> You do not have permission to view this directory or page using the credentials that you supplied.</em></p> </blockquote> <p>In my <code>web.config</code>:</p> <pre><code> &lt;appSettings&gt; &lt;add key="webpages:Version" value="1.0.0.0" /&gt; &lt;add key="ClientValidationEnabled" value="true" /&gt; &lt;add key="UnobtrusiveJavaScriptEnabled" value="true" /&gt; &lt;add key="elmah.mvc.disableHandler" value="false" /&gt; &lt;add key="elmah.mvc.disableHandleErrorFilter" value="false" /&gt; &lt;add key="elmah.mvc.requiresAuthentication" value="true" /&gt; &lt;add key="elmah.mvc.allowedRoles" value="Administrator" /&gt; &lt;add key="elmah.mvc.route" value="elmah" /&gt; &lt;/appSettings&gt; </code></pre> <p>In <code>global.asax</code>:</p> <pre><code> public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("elmah.axd"); routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } </code></pre>
13,766,103
3
1
null
2012-12-07 15:24:34.407 UTC
3
2019-01-11 06:11:27.85 UTC
2012-12-07 15:33:22.57 UTC
null
13,302
null
379,008
null
1
35
asp.net-mvc|elmah|elmah.mvc
15,645
<p>(This is all from the documentation/getting started)</p> <p>You don't need the following line:</p> <pre><code>routes.IgnoreRoute("elmah.axd"); </code></pre> <p>The next line takes care of it.</p> <p>Everything you need to configure is in your <code>web.config</code> file. Something like:</p> <pre><code>&lt;elmah&gt; &lt;security allowRemoteAccess="yes" /&gt; &lt;errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="mySqlConnString" /&gt; &lt;/elmah&gt; &lt;location path="elmah.axd"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow roles="Administrator" /&gt; &lt;deny users="*" /&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre> <p>Should get you going.</p>
13,761,934
Xcode derived data location
<p>Xcode keeps writing derived data to the project folder even though its set to default in the xcode project settings, its there any way to force this other than the project settings?</p>
13,762,600
1
1
null
2012-12-07 11:11:31.873 UTC
3
2016-10-13 06:59:20.78 UTC
null
null
null
null
692,770
null
1
36
ios|xcode
25,929
<p>By default Xcode stores the derived data for all projects in a single shared folder under your home directory at the following location:</p> <pre><code>~/Library/Developer/Xcode/DerivedData </code></pre> <p>Update:</p> <p>From Xcode 6, you can access or change derived data location from <strong>Preferences -> Locations Tab</strong></p> <p><img src="https://i.stack.imgur.com/v1d3x.png" alt="enter image description here"></p>
13,395,391
Z3: finding all satisfying models
<p>I am trying to retrieve all possible models for some first-order theory using Z3, an SMT solver developed by Microsoft Research. Here is a minimal working example:</p> <pre><code>(declare-const f Bool) (assert (or (= f true) (= f false))) </code></pre> <p>In this propositional case there are two satisfying assignments: <code>f-&gt;true</code> and <code>f-&gt;false</code>. Because Z3 (and SMT solvers in general) will only try to find one satisfying model, finding all solutions is not directly possible. <a href="http://research.microsoft.com/en-us/um/redmond/projects/z3/smt__command.html#smt2_next_sat_example" rel="noreferrer">Here</a> I found a useful command called <code>(next-sat)</code>, but it seems that the latest version of Z3 no longer supports this. This is bit unfortunate for me, and in general I think the command is quite useful. Is there another way of doing this?</p>
13,398,853
2
0
null
2012-11-15 10:18:06.767 UTC
16
2022-01-13 09:33:27.47 UTC
null
null
null
null
1,563,701
null
1
38
z3|smt|theorem-proving
18,928
<p>One way to accomplish this is using one of the APIs, along with the model generation capability. You can then use the generated model from one satisfiability check to add constraints to prevent previous model values from being used in subsequent satisfiability checks, until there are no more satisfying assignments. Of course, you have to be using finite sorts (or have some constraints ensuring this), but you could use this with infinite sorts as well if you don't want to find all possible models (i.e., stop after you generate a bunch).</p> <p>Here is an example using z3py (link to z3py script: <a href="http://rise4fun.com/Z3Py/a6MC">http://rise4fun.com/Z3Py/a6MC</a> ):</p> <pre><code>a = Int('a') b = Int('b') s = Solver() s.add(1 &lt;= a) s.add(a &lt;= 20) s.add(1 &lt;= b) s.add(b &lt;= 20) s.add(a &gt;= 2*b) while s.check() == sat: print s.model() s.add(Or(a != s.model()[a], b != s.model()[b])) # prevent next model from using the same assignment as a previous model </code></pre> <p>In general, using the disjunct of all the involved constants should work (e.g., <code>a</code> and <code>b</code> here). This enumerates all integer assignments for <code>a</code> and <code>b</code> (between <code>1</code> and <code>20</code>) satisfying <code>a &gt;= 2b</code>. For example, if we restrict <code>a</code> and <code>b</code> to lie between <code>1</code> and <code>5</code> instead, the output is:</p> <pre><code>[b = 1, a = 2] [b = 2, a = 4] [b = 1, a = 3] [b = 2, a = 5] [b = 1, a = 4] [b = 1, a = 5] </code></pre>
13,322,485
How to get the primary IP address of the local machine on Linux and OS X?
<p>I am looking for a command line solution that would return me the primary (first) IP address of the localhost, other than 127.0.0.1</p> <p>The solution should work at least for Linux (Debian and RedHat) and OS X 10.7+</p> <p>I am aware that <code>ifconfig</code> is available on both but its output is not so consistent between these platforms.</p>
13,322,549
31
7
null
2012-11-10 13:32:11.317 UTC
162
2021-07-25 16:44:50.47 UTC
2019-08-11 15:07:02.99 UTC
user3956566
null
null
99,834
null
1
410
bash|unix|ip|ifconfig
687,788
<p>Use <code>grep</code> to filter IP address from <code>ifconfig</code>: </p> <p><code>ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'</code></p> <p>Or with <code>sed</code>:</p> <p><code>ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'</code></p> <p>If you are only interested in certain interfaces, wlan0, eth0, etc. then:</p> <p><code>ifconfig wlan0 | ...</code></p> <p>You can alias the command in your <code>.bashrc</code> to <em>create</em> your own command called <code>myip</code> for instance.</p> <p><code>alias myip="ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'"</code></p> <p>A much simpler way is <code>hostname -I</code> (<code>hostname -i</code> for older versions of <code>hostname</code> but see comments). However, this is on Linux only. </p>
13,242,469
How to use sed/grep to extract text between two words?
<p>I am trying to output a string that contains everything between two words of a string:</p> <p>input:</p> <pre><code>"Here is a String" </code></pre> <p>output:</p> <pre><code>"is a" </code></pre> <p>Using: </p> <pre><code>sed -n '/Here/,/String/p' </code></pre> <p>includes the endpoints, but I don't want to include them.</p>
13,242,517
14
3
null
2012-11-06 00:08:45.847 UTC
73
2022-08-11 07:10:42.1 UTC
2017-05-25 04:39:00.103 UTC
null
793,796
null
1,190,650
null
1
188
string|bash|sed|grep
628,243
<pre><code>sed -e 's/Here\(.*\)String/\1/' </code></pre>
13,573,653
CSS margin terror; Margin adds space outside parent element
<p>My css margins doesn't behave the way I want or expect them to. I seems like my header margin-top affect the div-tags surrounding it.</p> <p><strong>This is what I want and expect:</strong> <img src="https://i.stack.imgur.com/Uf7E7.png" alt="What I want...."></p> <p><strong>...but this is what I end up with:</strong> <img src="https://i.stack.imgur.com/xQPuv.png" alt="What I get..."></p> <p><strong>Source:</strong></p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Margin test&lt;/title&gt; &lt;style type="text/css"&gt; body { margin:0; } #page { margin:0; background:#FF9; } #page_container { margin:0 20px; } h1 { margin:50px 0 0 0; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="page"&gt; &lt;div id="page_container"&gt; &lt;header id="branding" role="banner"&gt; &lt;hgroup&gt; &lt;h1 id="site-title"&gt;&lt;span&gt;&lt;a href="#" title="Title" rel="home"&gt;Title&lt;/a&gt;&lt;/span&gt;&lt;/h1&gt; &lt;h2 id="site-description"&gt;Description&lt;/h2&gt; &lt;/hgroup&gt; &lt;/header&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I have exaggerated the margin in this example. Default browser margin on h1-tag is somewhat smaller, and in my case I use <em>Twitter Bootstrap, with Normalizer.css</em> which sets default margin to 10px. Not that important, main point is; I can not, should not, <em>want not</em> change the margin on the h1-tag.</p> <p>I guess it is similar to my other question; <em><a href="https://stackoverflow.com/q/9519841/266642">Why does this CSS margin-top style not work?</a></em>. Question is how do I solve this specific issue?</p> <p>I have read <a href="https://stackoverflow.com/q/7742720/266642">a few threads</a> on similar problems, but haven't found any real answers and solutions. I know adding <code>padding:1px;</code> or <code>border:1px;</code> solves the problem. But that only adds new problems, since I do not want a padding nor a border on my div-tags.</p> <p>There must be a better, best practice, solution? This must be pretty common.</p>
13,573,739
8
6
null
2012-11-26 21:44:28.69 UTC
39
2022-06-22 19:38:38.973 UTC
2022-06-22 19:38:38.973 UTC
null
8,620,333
null
266,642
null
1
196
html|css|overflow|margin
111,738
<p>Add <code>overflow:auto</code> to your <code>#page</code> div.</p> <p><strong><a href="http://jsfiddle.net/j08691/464jW/">jsFiddle example</a></strong></p> <p>And check out <a href="http://www.w3.org/TR/CSS2/box.html#collapsing-margins">collapsing margins</a> while you're at it.</p>
3,847,294
Replace all characters not in range (Java String)
<p>How do you replace all of the characters in a string that do not fit a criteria. I'm having trouble specifically with the NOT operator. </p> <p>Specifically, I'm trying to remove all characters that are not a digit, I've tried this so far:</p> <pre><code>String number = "703-463-9281"; String number2 = number.replaceAll("[0-9]!", ""); // produces: "703-463-9281" (no change) String number3 = number.replaceAll("[0-9]", ""); // produces: "--" String number4 = number.replaceAll("![0-9]", ""); // produces: "703-463-9281" (no change) String number6 = number.replaceAll("^[0-9]", ""); // produces: "03-463-9281" </code></pre>
3,847,299
2
0
null
2010-10-02 19:54:36.98 UTC
8
2016-09-07 08:56:09.353 UTC
2010-10-02 20:30:23.763 UTC
null
276,101
null
84,131
null
1
29
java|regex|character-class
38,242
<p>To explain: The ^ at the start of a character class will negate that class But it has to be inside the class for that to work. The same character outside a character class is the anchor for start of string/line instead.</p> <p>You can try this instead:</p> <pre><code>"[^0-9]" </code></pre>
28,827,196
How to call a codebehind function from javascript in asp.net?
<p>I want to call a function from my code behind using javascript. I used the below code:</p> <pre><code>function fnCheckSelection() { some script; window["My"]["Namespace"]["GetPart"](null); } </code></pre> <p>...where <code>"GetPart"</code> is the function name. However, this is not working. Please help me on this.</p>
28,827,816
4
13
null
2015-03-03 08:30:45.19 UTC
2
2020-06-26 17:00:40.443 UTC
2017-12-20 17:00:37.697 UTC
null
6,530,134
null
3,355,228
null
1
15
javascript|c#|asp.net
88,764
<p>in JavaScript:</p> <pre><code> document.getElementById(&quot;btnSample&quot;).click(); </code></pre> <p>Server side control:</p> <pre><code> &lt;asp:Button runat=&quot;server&quot; ID=&quot;btnSample&quot; ClientIDMode=&quot;Static&quot; Text=&quot;&quot; style=&quot;display:none;&quot; OnClick=&quot;btnSample_Click&quot; /&gt; </code></pre> <p>C#</p> <pre><code> protected void btnSample_Click(object sender, EventArgs e) { } </code></pre> <p>It is easy way though...</p>
9,024,724
How do I put double quotes in a string in vba?
<p>I want to insert an if statement in a cell through vba which includes double quotes.</p> <p>Here is my code:</p> <pre><code>Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!B1=0,"",Sheet1!B1)" </code></pre> <p>Due to double quotes I am having issues with inserting the string. How do I handle double quotes?</p>
9,024,764
4
2
null
2012-01-26 20:18:31.9 UTC
21
2019-05-27 08:49:17.403 UTC
2019-05-27 08:49:17.403 UTC
null
2,190,175
null
793,468
null
1
150
excel|vba|double-quotes
561,777
<p>I find the easiest way is to double up on the quotes to handle a quote.</p> <pre><code>Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)" </code></pre> <p>Some people like to use CHR(34)*:</p> <pre><code>Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," &amp; CHR(34) &amp; CHR(34) &amp; ",Sheet1!A1)" </code></pre> <p>*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function. </p>
16,062,072
How to add certificate chain to keystore?
<p>I have file with chain of certificates - certificate.cer: </p> <pre><code>subject=/C... issuer=/C=US/O=VeriSign, Inc... -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- subject=/C=US/O=VeriSign, Inc... issuer=/C=US/O=VeriSign, Inc... -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- subject=/C=US/O=VeriSign, Inc... issuer=/C=US/O=VeriSign, Inc... -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- </code></pre> <p>I need to add this chain of certificates to keystore.<br> What I do: </p> <pre><code>openssl x509 -outform der -in certificate.cer -out cert.der keytool -v -importcert -alias mykey -file cert.der -keypass &lt;passwd&gt; -keystore keystore -storepass &lt;passwd&gt; -alias &lt;myalias&gt; </code></pre> <p>In result I have only 1 certificate in keystore.<br> But should have 3.<br> What could be wrong?</p> <p><strong>SOLUTION:</strong><br> CA sent me certificates in PKCS#7 format.<br> I stored them in certificate.p7b file and then successfully added them to keystore by following command: </p> <pre><code>keytool -import -trustcacerts -file certificate.p7b -keystore keystore -storepass &lt;mypasswd&gt; -alias "myalias" </code></pre>
16,062,331
3
3
null
2013-04-17 13:56:23.05 UTC
18
2022-03-04 04:19:48.503 UTC
2016-10-28 19:26:51.793 UTC
null
608,639
null
167,739
null
1
42
java|openssl|certificate|keystore|keytool
173,854
<p>From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.</p>
17,404,165
How to run a command on command prompt startup in Windows
<blockquote> <p><strong>EDIT</strong></p> <p>If you want to perform any task at computer startup or based on an event this is very helpful</p> <p><a href="http://answers.microsoft.com/en-us/windows/forum/windows_7-performance/how-to-schedule-computer-to-shut-down-at-a-certain/800ed207-f630-480d-8c92-dff2313c193b">http://answers.microsoft.com/en-us/windows/forum/windows_7-performance/how-to-schedule-computer-to-shut-down-at-a-certain/800ed207-f630-480d-8c92-dff2313c193b</a></p> </blockquote> <hr> <p><strong>Back to the question</strong></p> <p>I have two questions:</p> <ol> <li><p>I want some specific commands to be executed when I start command prompt.</p> <p>e.g. <code>cls</code> to clear my command prompt.</p></li> <li><p>I want to execute some commands in a batch file and wait for the user to enter new commands (if any).</p> <p>e.g. A batch file which will take the user to some specified folder and then wait for the user to rename/delete a file from the command prompt.</p></li> </ol> <p>How can I do it?</p>
17,404,355
6
0
null
2013-07-01 12:08:50.193 UTC
40
2021-02-26 15:41:02.02 UTC
2016-10-29 00:12:30.34 UTC
null
1,630,171
null
840,669
null
1
65
windows|cmd|command|command-prompt
118,415
<p>I found my answer: I should use the <code>/K</code> switch, using which I can enter a new command on the opened command prompt.</p> <p>E.g. <code>cmd /K cls</code> will open a command prompt for me and clear it. (Answer for question 1)</p> <p>and </p> <p><code>cmd /K MyBatchFile.bat</code> will start a command prompt, execute the batch file and stay on the command prompt and will not exit. (Answer for question 2).</p>
17,267,218
Perforce for Git users?
<p>There is a lot of "Git for Perforce users" documentation out there, but seemingly very little of the opposite.</p> <p>I have only used Git previously and recently started a job where I have to use Perforce a lot, and find myself getting very confused a lot of the time. The concepts I'm used to from Git seem not to map to Perforce at all.</p> <p>Is anyone interested in putting together a few tips for using Perforce for someone who is used to Git?</p>
17,331,274
3
0
null
2013-06-24 02:24:42.95 UTC
132
2019-03-19 13:00:25.933 UTC
null
null
null
null
242,814
null
1
175
git|perforce
52,983
<p>This something I've been working on over the past couple weeks on and off. It's still evolving, but it may be helpful. Please note I'm a Perforce employee.</p> <h1>An intro to Perforce for Git users</h1> <p>To say that moving from Git to Perforce or from Perforce to Git is non-trivial is a grand understatement. For being two tools that ostensibly do the same thing, their approach could not be more different. This brief write-up will try to help new Perforce users coming from Git understand the new world they are in.</p> <p>One brief detour before we dive in; if you prefer Git you can use Git with Perforce quite well. We provide a tool called Git Fusion that generates Git repositories that are kept in sync with the Perforce server. Git and Perforce people can live in harmony working on the same code, mostly unaffected by their co-workers choice of version control. Git Fusions 13.3 is available from the <a href="https://www.perforce.com/perforce/doc.current/manuals/git-fusion/" rel="noreferrer">Perforce web site</a>. It does need to be installed by the Perforce administrator, but if you install it you will find that its repository slicing feature can be quite handy as a Git user.</p> <p>If you can't convince your admin to install Git Fusion, Git itself comes with a Perforce binding called Git-P4 that allows you to use Git to change and submit files in a Perforce workspace. More information on that can be found at: <a href="https://git.wiki.kernel.org/index.php/GitP4" rel="noreferrer">https://git.wiki.kernel.org/index.php/GitP4</a></p> <p>Still here? Good, let's look at Perforce.</p> <h1>Some Terminology Differences to Sort Out</h1> <p>Before we get into the details we need to briefly cover a couple terminology differences between Git and Perforce.</p> <p>The first is <strong>checkout</strong>. In Git this is how you get a copy of the code from a given branch into your working area. In Perforce we call this a <strong>sync</strong> from the command line or from our GUI P4V "Get Latest Revision". Perforce uses the word <strong>checkout</strong> from P4V or <code>p4 edit</code> from the command line to mean that you plan to change a file from the version control system. In the rest of this document, I'll be using checkout in the Perforce sense of the word.</p> <p>The second is Git <strong>commit</strong> versus Perforce <strong>submit</strong>. Where you would commit in Git you will submit in Perforce. Being that all operations happen against the shared Perforce versioning service, Perforce doesn't have an equivalent for <code>git push</code>. Likewise we don't have a <code>pull</code>; the sync command from above takes care of getting files for us. There is no concept of a pure local submit in Perforce unless you choose to use our P4Sandbox tool described briefly below.</p> <h1>Key Concepts in Perforce</h1> <p>If I were to simplify Perforce to two key concepts I would focus on the depot and the workspace. A Perforce depot is a repository of files that lives in a Perforce server. A Perforce server can have any number of depots and each depot can contain any number of files. Frequently you will hear Perforce users use depot and server interchangeably, but they are different. A Perforce site may choose to have multiple servers, but most commonly all files are in one server.</p> <p>A Perforce workspace or client is an object in the system that maps a set of files in the Perforce server to a location on a user's file system. Every user has a workspace for each machine they use, and frequently users will have more than one workspace for the same machine. The most important part of a workspace is the workspace mapping or view. </p> <p>The workspace view specifies the set of files in the depot that should be mapped to the local machine. This is important because there is a good chance that you do not want all of the files that are available on the server. A workspace view lets you select just the set that you care about. It's important to note that a workspace can map content from multiple depots, but can only map content from one server.</p> <p>To compare Perforce to Git in this regard, with Git you pick and choose the set of Git repos that you are interested in. Each repo is generally tightly scoped to contain just related files. The advantage of this is there is no configuration to do on your part; you do a git clone of the things you care about and you're done. This is especially nice if you only work with one or two repositories. With Perforce you need to spend a bit of time picking and choosing the bits of code you want.</p> <p>Many Perforce shops use streams which can automatically generate a workspace view, or they generate the view using scripts or template workspaces. Equally many leave their users to generate their workspaces themselves. One advantage of being able to map a number of modules in one workspace is you can easily modify multiple code modules in one checkin; you can be guaranteed that anyone with a similar client view who syncs to your checkin will have all the code in the correct state. This can also lead to overly dependent code though; the forced separation of Git can lead to better modularity. Thankfully Perforce can also support strict modularity as well. It's all a question of how you choose to use the tool.</p> <h1>Why Workspaces?</h1> <p>I think in coming from Git it is easy to feel like the whole workspace concept is way more trouble than it is worth. Compared to cloning a few Git repos this is undoubtably true. Where workspaces shine, and the reason Perforce is still in business after all these years, is that workspaces are a fantastic way to pare down multi-million file projects for developers while still making it easy for build and release to pull all the source together from one authoritative source. Workspaces are one of the key reasons Perforce can scale as well as it does.</p> <p>Workspaces are also nice in that the layout of files in the depot and the layout on the user's machine can vary if need be. Many companies organize their depot to reflect the organization of their company so that it is easy for people to find content by business unit or project. However their build system couldn't care less about this hierarchy; the workspace allows them to remap their depot hierarchy in whatever way makes sense to their tools. I have also seen this used by companies who are using extremely inflexible build systems that require code to be in very specific configurations that are utterly confusing to humans. Workspaces allow these companies to have a source hierarchy that is human navigable while their build tools get the structure they need.</p> <p>Workspaces in Perforce are not only used to map the set of files a user wants to work with, but they are also used by the server to track exactly which revisions of each file the user has synced. This allows the system to send the correct set of files to the user when syncing without having to scan the files to see which files need to be updated. With large amounts of data this can be a sizable performance win. This is also very popular in industries that have very strict auditing rules; Perforce admins can easily track and log which developers have synced which files.</p> <p>For more information on the full power of Perforce workspaces read <a href="http://www.perforce.com/perforce/doc.current/manuals/p4guide/02_config.html" rel="noreferrer">Configuring P4</a>.</p> <h1>Explicit Checkout vs. Implicit Checkout</h1> <p>One of the biggest challenges for users moving from Git to Perforce is the concept of explicit checkout. If you are accustomed to the Git/SVN/CVS workflow of changing files and then telling the version control system to look for what you've done, it can be an extremely painful transition.</p> <p>The good news is that if you so choose you can work with a Git style workflow in Perforce. In Perforce you can set "allwrite" option on your workspace. This will tell Perforce that all files should be written to disk with the writable bit set. You may then change any file you wish without explicitly telling Perforce. To have Perforce reconcile those changes you made you can run "p4 status". It will open files for add, edit, and delete as appropriate. When working this way you will want to use "p4 update" instead of "p4 sync" to get new revisions from the server; "p4 update" checks for changes before syncing so will not clobber your local changes if you haven't run "p4 status" yet.</p> <h1>Why Explicit Checkout?</h1> <p>A question I frequently receive is "why would you ever want to use explicit checkout?" It can at first blush seem to be a crazy design decision, but explicit checkout does have some powerful benefits.</p> <p>One reason for using explicit checkout is it removes the need to scan files for content changes. While with smaller projects calculating hashes for each file to find differences is fairly cheap, many of our users have millions of files in a workspace and/or have files that are 100's of megabytes in size, if not larger. Calculating all the hashes in those cases is extremely time consuming. Explicit checkout lets Perforce know exactly which files it needs to work with. This behavior is one of the reasons Perforce is so popular in large file industries like the game, movie, and hardware industries.</p> <p>Another benefit is explicit checkout provides a form of asynchronous communication that lets developers know generally what their peers are working on, or at least where. It can let you know that you may want to avoid working in a certain area so as to avoid a needless conflict, or it can alert you to the fact that a new developer on the team has wandered into code that perhaps they don't need to be editing. My personal experience is that I tend to work either in Git or using Perforce with allwrite on projects where I'm either the only contributor or an infrequent contributor, and explicit checkout when I'm working tightly with a team. Thankfully the choice is yours.</p> <p>Explicit checkout also plays nicely with the Perforce concept of pending changelists. Pending changelists are buckets that you can put your open files into to organize your work. In Git you would potentially use different branches as buckets for organizing work. Branches are great, but sometimes it is nice to be able to organize your work into multiple named changes before actually submitting to the server. With the Perforce model of potentially mapping multiple branches or multiple projects into one workspace, pending changelists make it easy to keep separate changes organized.</p> <p>If you use an IDE for development such as Visual Studio or Eclipse I highly recommend installing a Perforce plugin for your IDE. Most IDE plugins will automatically checkout files when you start editing them, freeing you from having to do the checkout yourself.</p> <h1>Perforce Replacements For Git Features</h1> <ul> <li><code>git stash</code> ==> <code>p4 shelve</code></li> <li>git local branching ==> either Perforce shelves or task branches</li> <li><code>git blame</code> ==> <code>p4 annotate</code> or <strong>Perforce Timelapse View</strong> from the GUI </li> </ul> <h1>Working Disconnected</h1> <p>There are two options for working disconnected from the Perforce versioning service (that's our fancy term for the Perforce server).</p> <p>1) Use P4Sandbox to have full local versioning and local branching</p> <p>2) Edit files as you please and use 'p4 status' to tell Perforce what you've done</p> <p>With both the above options you can opt to use the "allwrite" setting in your workspace so that you do not have to unlock files. When working in this mode you will want to use the "p4 update" command to sync new files instead of "p4 sync". "p4 update" will check files for changes before syncing over them.</p> <h1>Perforce Quickstart</h1> <p>All the following examples will be via the command line.</p> <p>1) Configure your connection to Perforce</p> <pre><code>export P4USER=matt export P4CLIENT=demo-workspace export P4PORT=perforce:1666 </code></pre> <p>You can stick these settings in your shell config file, use <code>p4 set</code> to save them on Windows and OS X, or use a Perforce config file.</p> <p>1) Create a workspace</p> <pre><code>p4 workspace # set your root to where your files should live: Root: /Users/matt/work # in the resulting editor change your view to map the depot files you care about //depot/main/... //demo-workspace/main/... //depot/dev/... //demo-workspace/dev/... </code></pre> <p>2) Get the files from the server</p> <pre><code>cd /Users/matt/work p4 sync </code></pre> <p>3) Checkout the file you want to work on and modify it</p> <pre><code>p4 edit main/foo; echo cake &gt;&gt; main/foo </code></pre> <p>4) Submit it to the server</p> <pre><code>p4 submit -d "A trivial edit" </code></pre> <p>5) Run <code>p4 help simple</code> to see the basic commands that you will need to work with Perforce.</p>
30,572,605
ViewPager show next and before item preview on screen
<p>I want to show viewpager next and before page preview in screen. Before and next page show deep in screen and slide next page with deep animation.</p> <p>You can look this image</p> <p>How can i do it? </p> <p><img src="https://i.stack.imgur.com/f6yHc.png" alt="enter image description here"></p>
30,594,487
5
4
null
2015-06-01 11:42:31.49 UTC
23
2020-07-23 14:37:53.327 UTC
2016-02-17 13:30:11.333 UTC
null
3,800,712
null
3,800,712
null
1
40
android|android-viewpager|pager
30,340
<p>Finally, i did it :) I modify this answer <a href="https://stackoverflow.com/questions/10001503/android-carousel-like-widget-which-displays-a-portion-of-the-left-and-right-el">Android - Carousel like widget which displays a portion of the left and right elements</a></p> <p>You can look this code.</p> <pre><code>//pager settings pager.setClipToPadding(false); pager.setPageMargin(24); pager.setPadding(48, 8, 48, 8); pager.setOffscreenPageLimit(3); pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { Log.i("", "onPageScrolled: " + position); CampaignPagerFragment sampleFragment = (CampaignPagerFragment) ((CampaignPagerAdapter) pager.getAdapter()).getRegisteredFragment(position); float scale = 1 - (positionOffset * RATIO_SCALE); // Just a shortcut to findViewById(R.id.image).setScale(scale); sampleFragment.scaleImage(scale); if (position + 1 &lt; pager.getAdapter().getCount()) { sampleFragment = (CampaignPagerFragment) ((CampaignPagerAdapter) pager.getAdapter()).getRegisteredFragment(position + 1); scale = positionOffset * RATIO_SCALE + (1 - RATIO_SCALE); sampleFragment.scaleImage(scale); } } @Override public void onPageSelected(int position) { Log.i("", "onPageSelected: " + position); } @Override public void onPageScrollStateChanged(int state) { Log.i("", "onPageScrollStateChanged: " + state); if (state == ViewPager.SCROLL_STATE_IDLE) { CampaignPagerFragment fragment = (CampaignPagerFragment) ((CampaignPagerAdapter) pager.getAdapter()).getRegisteredFragment(pager.getCurrentItem()); fragment.scaleImage(1); if (pager.getCurrentItem() &gt; 0) { fragment = (CampaignPagerFragment) ((CampaignPagerAdapter) pager.getAdapter()).getRegisteredFragment(pager.getCurrentItem() - 1); fragment.scaleImage(1 - RATIO_SCALE); } if (pager.getCurrentItem() + 1 &lt; pager.getAdapter().getCount()) { fragment = (CampaignPagerFragment) ((CampaignPagerAdapter) pager.getAdapter()).getRegisteredFragment(pager.getCurrentItem() + 1); fragment.scaleImage(1 - RATIO_SCALE); } } } }); </code></pre> <hr> <pre><code>//PagerAdapter public class CampaignPagerAdapter extends FragmentStatePagerAdapter { SparseArray&lt;Fragment&gt; registeredFragments = new SparseArray&lt;Fragment&gt;(); public CampaignPagerAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return 5; } @Override public Fragment getItem(int position) { return new CampaignPagerFragment(); } @Override public Object instantiateItem(ViewGroup container, int position) { Fragment fragment = (Fragment) super.instantiateItem(container, position); registeredFragments.put(position, fragment); return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { registeredFragments.remove(position); super.destroyItem(container, position, object); } public Fragment getRegisteredFragment(int position) { return registeredFragments.get(position); } } </code></pre> <p>for ex: <a href="https://github.com/mrleolink/SimpleInfiniteCarousel" rel="noreferrer">https://github.com/mrleolink/SimpleInfiniteCarousel</a>..</p> <p>Hello, One thing that is missing sampleFragment.scaleImage(scale); It is a method created in CampaignPagerFragment and it scale the fragment rootView..</p> <p>e.g <code>public void scaleImage(float scaleX) { rootView.setScaleY(scaleX); rootView.invalidate(); }</code></p>
36,988,681
time.Time Round to Day
<p>I have a timestamp coming in, I wonder if there's a way to round it down to the start of a day in PST. For example, ts: <code>1305861602</code> corresponds to <code>2016-04-14, 21:10:27 -0700</code>, but I want to round it to a timestamp that maps to <code>2016-04-14 00:00:00 -0700</code>. I read through the time.Time doc but didn't find a way to do it.</p>
36,988,882
6
3
null
2016-05-02 18:00:03.737 UTC
9
2022-08-12 13:53:29.527 UTC
2018-08-23 06:58:00.687 UTC
null
13,860
null
2,190,546
null
1
56
go
55,562
<p>The simple way to do this is to create new <code>Time</code> using the previous one and only assigning the year month and day. It would look like this;</p> <pre><code>rounded := time.Date(toRound.Year(), toRound.Month(), toRound.Day(), 0, 0, 0, 0, toRound.Location()) </code></pre> <p>here's a play example; <a href="https://play.golang.org/p/jnFuZxruKm" rel="noreferrer">https://play.golang.org/p/jnFuZxruKm</a></p>
25,865,270
How to install Python MySQLdb module using pip?
<p>How can I install the <a href="http://mysql-python.sourceforge.net/MySQLdb.html" rel="noreferrer">MySQLdb</a> module for Python using pip?</p>
25,865,271
20
2
null
2014-09-16 09:31:57.003 UTC
94
2022-06-28 13:08:17.143 UTC
2018-04-24 19:30:19.29 UTC
null
1,228,491
null
1,228,491
null
1
339
python|mysql|pip
643,281
<p>It's easy to do, but hard to remember the correct spelling:</p> <pre><code>pip install mysqlclient </code></pre> <p>If you need 1.2.x versions (legacy Python only), use <code>pip install MySQL-python</code></p> <p>Note: Some dependencies might have to be in place when running the above command. Some hints on how to install these on various platforms:</p> <h2>Ubuntu 14, Ubuntu 16, Debian 8.6 (jessie)</h2> <pre><code>sudo apt-get install python-pip python-dev libmysqlclient-dev </code></pre> <h2>Fedora 24:</h2> <pre><code>sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc </code></pre> <h2>Mac OS</h2> <pre><code>brew install mysql-connector-c </code></pre> <p>if that fails, try</p> <pre><code>brew install mysql </code></pre>
9,193,214
Why does overflow hidden stop floating elements escaping their container?
<p>A common problem that I have with web pages is floating <code>div</code> tags creeping outside of their containers, like shown in the snippet.</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-css lang-css prettyprint-override"><code>#wrapper { border: 1px solid red; } #wrapper div { float: left; font-size: 3em; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="wrapper"&gt; &lt;div&gt;Hello World&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>There are a lot of dirty ways to fix this (i.e., inserting a <code>div</code> with <code>clear:both</code>)</p> <p>However, a much neater solution I have seen is setting the wrapper <code>div</code> with <code>overflow</code> set to <code>hidden</code>:</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-css lang-css prettyprint-override"><code>#wrapper { border: 1px solid red; overflow: hidden; } #wrapper div { float: left; font-size: 3em; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="wrapper"&gt; &lt;div&gt;Hello World&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>This works well across browsers, nice and cleanly with no additional markup. I am happy, but I have no idea <strong>WHY</strong> it works this way?</p> <p>All the documentation, I had looked at, indicates <code>overflow:hidden</code> is for hiding content, not resizing a parent to fit its children...</p> <p>Can anybody offer a explanation for this behavior?</p> <p>Thanks</p> <p>Original snippets: Live example 1: <a href="http://jsfiddle.net/ugUVa/1/" rel="nofollow noreferrer">http://jsfiddle.net/ugUVa/1/</a> Live example 2: <a href="http://jsfiddle.net/ugUVa/2/" rel="nofollow noreferrer">http://jsfiddle.net/ugUVa/2/</a></p>
9,193,270
2
3
null
2012-02-08 12:22:21.673 UTC
12
2021-09-14 02:09:02.41 UTC
2021-09-14 02:09:02.41 UTC
null
5,372,008
null
1,022,228
null
1
30
html|css
10,367
<p>It creates a <a href="https://developer.mozilla.org/en/CSS/block_formatting_context">block formatting context</a>.</p> <blockquote> <p><em>Block formatting contexts are important for the positioning (see float) and clearing (see clear) of floats. The rules for positioning and clearing of floats apply only to things within the same block formatting context. Floats do not affect the layout of things in other block formatting contexts, and clear only clears past floats in the same block formatting context.</em></p> </blockquote> <p>see also: <a href="http://www.w3.org/TR/CSS2/visuren.html#block-formatting">http://www.w3.org/TR/CSS2/visuren.html#block-formatting</a></p>
9,589,381
Remove extra line breaks after Html.fromHtml()
<p>I am trying to place html into a TextView. Everything works perfectly, this is my code.</p> <pre><code>String htmlTxt = "&lt;p&gt;Hellllo&lt;/p&gt;"; // the html is form an API Spanned html = Html.fromHtml(htmlTxt); myTextView.setText(html); </code></pre> <p>This sets my TextView with the correct html. But my problem is, having a <p> tag in the html, the result text that goes into the TextView has a "\n" at the end, so it pushes my TextView's height higher than it should be.</p> <p>Since its a Spanned variable, I can't apply regex replace to remove the "\n", and if I was to convert it into a string, then apply regex, I lose the functionality of having html anchors to work properly.</p> <p>Does anyone know any solutions to remove the ending linebreak(s) from a "Spanned" variable?</p>
10,187,511
4
5
null
2012-03-06 18:06:17.927 UTC
14
2019-01-24 14:23:19.567 UTC
2012-03-06 18:07:54.023 UTC
user658042
null
null
1,240,803
null
1
44
android|html|line-breaks|spanned
13,894
<p>Nice answer @Christine. I wrote a similar function to remove trailing whitespace from a CharSequence this afternoon:</p> <pre><code>/** Trims trailing whitespace. Removes any of these characters: * 0009, HORIZONTAL TABULATION * 000A, LINE FEED * 000B, VERTICAL TABULATION * 000C, FORM FEED * 000D, CARRIAGE RETURN * 001C, FILE SEPARATOR * 001D, GROUP SEPARATOR * 001E, RECORD SEPARATOR * 001F, UNIT SEPARATOR * @return "" if source is null, otherwise string with all trailing whitespace removed */ public static CharSequence trimTrailingWhitespace(CharSequence source) { if(source == null) return ""; int i = source.length(); // loop back to the first non-whitespace character while(--i &gt;= 0 &amp;&amp; Character.isWhitespace(source.charAt(i))) { } return source.subSequence(0, i+1); } </code></pre>
18,361,750
Correct approach to global logging
<p>What's the pattern for application logging in Go? If I've got, say, 5 goroutines I need to log from, should I... </p> <ul> <li>Create a single <code>log.Logger</code> and pass it around?</li> <li>Pass around a pointer to that <code>log.Logger</code>?</li> <li>Should each goroutine or function create a logger?</li> <li>Should I create the logger as a global variable?</li> </ul>
18,362,952
7
0
null
2013-08-21 15:35:44.81 UTC
40
2021-07-26 14:30:59.157 UTC
2021-07-26 14:30:59.157 UTC
null
1,744,107
null
200,619
null
1
143
logging|go
71,300
<blockquote> <ul> <li>Create a single log.Logger and pass it around?</li> </ul> </blockquote> <p>That is possible. A <a href="http://golang.org/pkg/log/#Logger">log.Logger</a> can be used concurrently from multiple goroutines.</p> <blockquote> <ul> <li>Pass around a pointer to that log.Logger?</li> </ul> </blockquote> <p><a href="http://golang.org/pkg/log/#New">log.New</a> returns a <code>*Logger</code> which is usually an indication that you should pass the object around as a pointer. Passing it as value would create a copy of the struct (i.e. a copy of the Logger) and then multiple goroutines might write to the same <a href="http://golang.org/pkg/io/#Writer">io.Writer</a> concurrently. That might be a serious problem, depending on the implementation of the writer.</p> <blockquote> <ul> <li>Should each goroutine or function create a logger?</li> </ul> </blockquote> <p>I wouldn't create a separate logger for each function or goroutine. Goroutines (and functions) are used for very lightweight tasks that will not justify the maintenance of a separate logger. It's probably a good idea to create a logger for each bigger component of your project. For example, if your project uses a SMTP service for sending mails, creating a separate logger for the mail service sounds like a good idea so that you can filter and turn off the output separately.</p> <blockquote> <ul> <li>Should I create the logger as a global variable?</li> </ul> </blockquote> <p>That depends on your package. In the previous mail service example, it would be probably a good idea to have one logger for each instance of your service, so that users can log failures while using the gmail mail service differently than failures that occured while using the local MTA (e.g. sendmail).</p>
18,552,901
How to merge videos by avconv?
<p>I have several chunks in folder.</p> <pre><code>0001.mp4 0002.mp4 0003.mp4 ... 0112.mp4 </code></pre> <p>I would like to merge them into full.mp4</p> <p>I tried to use:</p> <pre><code>avconv -f concat -i &lt;(printf "file '%s'\n" /root/chunk/*.mp4) -y \ -c copy /root/test/full.mp4 </code></pre> <p>Unknown input format: 'concat'</p> <pre><code>avconv -f concat -i &lt;(printf "%s|" /root/chunk/*.mp4) -y \ -c copy /root/test/full.mp4 </code></pre> <p>Unknown input format: 'concat'</p> <pre><code>avconv -i concat:`ls -ltr /root/chunk/*.mp4 | awk 'BEGIN {ORS="|"} { print $9 }'` \ -c:v copy -c:a copy /root/test/full.mp4 </code></pre> <p>In last edition only one input file was catched to output.</p> <p>How to merge all chunks from folder into full video?</p> <p>I don't want to use ffmpeg or other. Avconv only.</p>
19,314,483
10
4
null
2013-08-31 21:15:42.383 UTC
14
2019-06-24 19:00:39.687 UTC
2015-12-03 19:06:22.933 UTC
null
895,245
null
1,603,227
null
1
38
video|avconv
42,798
<pre><code>avconv -i concat:file1.mp4\|file2.mp4 -c copy output.mp4 </code></pre> <p>I don't know if works with any container's type ( worked for me with <code>AVI</code> ).</p>
14,958,543
View Pager with Universal Image Loader Out of Memory Error
<p>I am not really sure if a ViewPager with Universal Image Loader can/should be used as an alternate for a gallery like interface since I have run into an Out of Memory error while loading images from SD Card and viewing them in full screen mode. No matter what the number, it works all fine with a GridView but while viewing the images in the View Pager, each bitmap keeps eating up a lot of memory and after 10 or so images, it gives the out of memory error.</p> <p>I have seen almost all the questions that have been posted here related to the Out of Memory Error while working with the Universal Image Loader and in each one of them, there has been a configurations error as the cause.</p> <p>I dont know if I am using the wrong configurations or what but I have wasted a lot of time on it and am kind of stuck, any help/advice would be appreciated.</p> <p>The configurations for the ImageLoader:</p> <pre><code>ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) .memoryCache(new WeakMemoryCache()) .denyCacheImageMultipleSizesInMemory() .discCacheFileNameGenerator(new Md5FileNameGenerator()) .imageDownloader(new ExtendedImageDownloader(getApplicationContext())) .tasksProcessingOrder(QueueProcessingType.LIFO) // .enableLogging() // Not necessary in common .build(); </code></pre> <p>The Display Image Options are:</p> <pre><code>options = new DisplayImageOptions.Builder() .showImageForEmptyUri(R.drawable.image_for_empty_url) .resetViewBeforeLoading() .imageScaleType(ImageScaleType.IN_SAMPLE_INT) .bitmapConfig(Bitmap.Config.RGB_565) .displayer(new FadeInBitmapDisplayer(300)) .build(); </code></pre> <p>I am using the example project that was given with the library but those settings wont work either, it just crashes after some time. My guess is that there is a specific callback where I have to recycle bitmaps from the views from that are not visible.</p> <p>EDIT: I know its a memory leak, the views that are not visible are destroyed when they should be but the memory is not released as it should. Heres the implementation of the destroyItem callback, followed the tips given in different questions but still cant find the memory leak.</p> <pre><code>@Override public void destroyItem(View container, int position, Object object) { // ((ViewPager) container).removeView((View) object); Log.d("DESTROY", "destroying view at position " + position); View view = (View)object; ((ViewPager) container).removeView(view); view = null; } </code></pre>
15,053,683
7
0
null
2013-02-19 13:19:16.96 UTC
8
2016-01-21 18:35:01.687 UTC
2013-02-20 10:51:05.677 UTC
null
1,149,279
null
1,149,279
null
1
11
android|android-viewpager|out-of-memory|universal-image-loader
11,425
<p>Try to apply next suggestions:</p> <ol> <li>Use <code>ImageScaleType.EXACTLY</code></li> <li>Enable caching on disc (in display options).</li> <li>Finally try to use <code>.discCacheExtraOptions(maxImageWidthForDiscCache, maxImageHeightForDiscCache, CompressFormat.PNG, 0);</code> </li> </ol>
15,199,980
How to put an image in the center of navigationBar of a UIViewController?
<p>I have this snippet of code used in viewDidLoad of a UIViewController. I'va no errors. Images exists. I get the background but not the image. Image is a sort of logo.</p> <pre><code>if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) { /* Background of navigationBar. */ UIImage * navigationBarImage = [UIImage imageNamed:@"01_navbar_portrait.png"]; [self.navigationController.navigationBar setBackgroundImage:navigationBarImage forBarMetrics:UIBarMetricsDefault]; /* Image in navigationBar */ UIImage * logoInNavigationBar = [UIImage imageNamed:@"01_logo.png"]; UIImageView * logoView = [[UIImageView alloc] init]; [logoView setImage:logoInNavigationBar]; self.navigationController.navigationItem.titleView = logoView; } </code></pre>
15,200,267
7
2
null
2013-03-04 11:00:20.97 UTC
9
2020-04-29 11:55:55.15 UTC
null
null
null
null
1,420,625
null
1
22
ios|uinavigationbar
33,704
<p>The <code>UINavigationController</code> manages the navigation bar by looking at the <code>navigationItem</code> property of the top-most view controller on the navigation stack. So to change the view to a logo, you need to set this up in the view controller that uses the logo (i.e. the root view controller or another one that gets pushed on the stack).</p> <p>Do something like this in <code>viewDidLoad</code> of your view controller:</p> <pre><code>UIImage* logoImage = [UIImage imageNamed:@"logo.png"]; self.navigationItem.titleView = [[UIImageView alloc] initWithImage:logoImage]; </code></pre> <p>In your case, you are setting the wrong navigation item:</p> <pre><code>// Oops... self.navigationController.navigationItem.titleView = logoView; // Should be this: self.navigationItem.titleView = logoView; </code></pre>
14,948,406
How to start Postgres server?
<p>Ive actually had this problem for a while but I've finally decided to take it on. Postgres was initially installed using Brew. </p> <p>After my upgrade to OSX 10.8.2 to receive a</p> <pre><code>psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? </code></pre> <p>error when I typed the </p> <pre><code>$ psql </code></pre> <p>command. </p> <p>I see the following processes:</p> <pre><code>$ ps auxw | grep post Tulsa 59222 0.0 0.2 2483256 14808 ?? Ss Thu03PM 0:02.61 /System/Library/PrivateFrameworks/DiskImages.framework/Resources/diskimages-helper -uuid 470DA5CC-1602-4D69-855F-F365A6512F90 -post-exec 4 Tulsa 57940 0.0 0.2 2498852 13648 ?? Ss Wed10PM 0:00.61 /System/Library/PrivateFrameworks/DiskImages.framework/Resources/diskimages-helper -uuid FAFAAAB4-0F67-42C8-864E-EF8C31A42EE3 -post-exec 4 root 24447 0.0 0.1 2476468 10080 ?? Ss 8Feb13 0:03.40 /System/Library/PrivateFrameworks/DiskImages.framework/Resources/diskimages-helper -uuid CC768720-12C2-436C-9020-548C275A6B0C -post-exec 4 Tulsa 74224 0.0 0.0 2432768 596 s002 R+ 7:24PM 0:00.00 grep post $ which psql /usr/local/bin/psql $ pg_ctl start pg_ctl: no database directory specified and environment variable PGDATA unset Try "pg_ctl --help" for more information. </code></pre>
14,949,578
1
6
null
2013-02-19 01:38:46.143 UTC
12
2015-07-02 19:55:05.5 UTC
2015-07-02 19:55:05.5 UTC
null
54,964
null
1,319,172
null
1
26
postgresql|osx-lion|django-postgresql
32,173
<p>You haven't started the Postgres server. Some of the dmg packages for Postgres set it to run as a service on startup. But not however you did the install.</p> <p>You need to init a data directory, start postgres, and then go from there.</p> <pre><code>initdb /some/directory # just do this ONCE pg_ctl -D /some/directory start # many other options, e.g. logging, available here psql postgres </code></pre> <p>You can set an environment variable for the data directory and you won't need the <code>-D</code> flag later. You can look that up later.</p>
15,388,897
Google Maps inside iframe not loading
<p>I ran into a strange issue, and I don't know what the problem is. The following jQuery code is a simplified version of what I want to achieve:</p> <pre><code>var iframe = $('&lt;iframe /&gt;'); iframe.prop('src', 'https://maps.google.com/maps?q=London&amp;hl=en&amp;sll=37.0625,-95.677068&amp;sspn=46.677964,93.076172&amp;t=h&amp;hnear=London,+United+Kingdom&amp;z=10'); iframe.appendTo($('body')); // When the iframe loads: iframe.load(function() { alert(1); }); </code></pre> <p>The map is never loaded, and the <code>load()</code> event is never triggered. Chrome reports the following error:</p> <p><code>Refused to display 'https://maps.google.com/maps?q=London&amp;hl=en&amp;sll=37.0625,-95.677068&amp;sspn=46.677964,93.076172&amp;t=h&amp;hnear=London,+United+Kingdom&amp;z=10' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.</code></p> <p>How does one bypass this?</p> <p>Here's a <a href="http://jsfiddle.net/RLuYw/" rel="noreferrer"><strong>jsFiddle demo</strong></a>.</p>
15,389,189
5
0
null
2013-03-13 15:01:35.987 UTC
4
2022-08-28 14:18:00.737 UTC
2013-03-13 15:10:52.787 UTC
null
367,401
null
367,401
null
1
29
javascript|jquery|google-maps
60,449
<p>Appending <code>&amp;output=embed</code> to the end of the URL fixes the problem.</p> <p><strong>Update</strong>: Google disabled this feature, which was working at the time the answer was originally posted. This solution no longer works.</p>
14,935,755
How to get data from old offset point in Kafka?
<p>I am using zookeeper to get data from kafka. And here I always get data from last offset point. Is there any way to specify the time of offset to get old data?</p> <p>There is one option autooffset.reset. It accepts smallest or largest. Can someone please explain what is smallest and largest. Can autooffset.reset helps in getting data from old offset point instead of latest offset point?</p>
17,084,401
7
0
null
2013-02-18 11:57:47.747 UTC
19
2017-01-20 06:06:46.183 UTC
2016-12-20 16:04:12.167 UTC
null
2,893,839
null
648,626
null
1
39
apache-kafka|offset|zookeeper|apache-zookeeper
49,523
<p>The consumers belong always to a group and, for each partition, the Zookeeper keeps track of the progress of that consumer group in the partition.</p> <p>To fetch from the beginning, you can delete all the data associated with progress as Hussain refered</p> <pre><code>ZkUtils.maybeDeletePath(${zkhost:zkport}", "/consumers/${group.id}"); </code></pre> <p>You can also specify the offset of partition you want, as specified in core/src/main/scala/kafka/tools/UpdateOffsetsInZK.scala</p> <pre><code>ZkUtils.updatePersistentPath(zkClient, topicDirs.consumerOffsetDir + "/" + partition, offset.toString) </code></pre> <p>However the offset is not time indexed, but you know for each partition is a sequence.</p> <p>If your message contains a timestamp (and beware that this timestamp has nothing to do with the moment Kafka received your message), you can try to do an indexer that attempts to retrieve one entry in steps by incrementing the offset by N, and store the tuple (topic X, part 2, offset 100, timestamp) somewhere.</p> <p>When you want to retrieve entries from a specified moment in time, you can apply a binary search to your rough index until you find the entry you want and fetch from there.</p>
15,093,376
JConsole over ssh local port forwarding
<p>I'd like to be able to remotely connect to a Java service that has JMX exposed, however it is blocked by a firewall. I have tried to use ssh local port forwarding, however the connection fails. Looking at wireshark, it appears that when you try to connect with jconsole, it wants to connect via some ephemeral ports after connecting to port 9999, which are blocked by the firewall.</p> <p>Is there any way to make jconsole only connect through 9999 or use a proxy? Is <a href="https://web.archive.org/web/20150202095729/https://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx" rel="noreferrer">this article still the best solution</a>? Or, am I missing something?</p>
15,093,889
4
1
null
2013-02-26 15:47:44.153 UTC
47
2020-02-05 21:26:10.527 UTC
2019-11-12 15:16:58.2 UTC
null
-1
null
290,541
null
1
68
java|ssh|jmx
62,103
<blockquote> <p>Is there any way to make jconsole only connect through 9999 or use a proxy? Is <a href="https://web.archive.org/web/20150202095729/https://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx" rel="noreferrer">this article</a> still the best solution? Or, am I missing something?</p> </blockquote> <p>Yes, that article is about right.</p> <p>When you specify the JMX port on your server (<code>-Dcom.sun.management.jmxremote.port=####</code>), you are actually specifying <em>just</em> the registry-port for the application. When you connect it provides an additional server-port that the jconsole actually does all of its work with. To get forwarded to work, you need to know <em>both</em> the registry and server ports.</p> <p>Something like the following should work to run your application with both the registry and server ports set to 8000. See <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html" rel="noreferrer">here for more details</a>.</p> <pre><code>-Dcom.sun.management.jmxremote.port=8000 -Dcom.sun.management.jmxremote.rmi.port=8000 -Djava.rmi.server.hostname=127.0.0.1 </code></pre> <p>As an aside, my <a href="http://256stuff.com/sources/simplejmx/" rel="noreferrer">SimpleJMX library</a> allows you to set both ports easily and you can set them both to be the same port.</p> <p>So, once you know both the port(s) you need to forward, you can set up your <code>ssh</code> command. For example, if you configure the registry and server ports as 8000, you would do:</p> <pre><code>ssh -L 8000:localhost:8000 remote-host </code></pre> <p>This creates a local port 8000 which forwards to localhost:8000 on the remote-host. You can specify multiple <code>-L</code> arguments if you need to forward multiple ports. Then you can connect your jconsole to localhost:8000 and it will connect to the remote-host appropriately.</p> <p>Also, if your server has multiple interfaces, you may need to set the <code>java.rmi.server.hostname</code> variable to bind to the right interface.</p> <pre><code>-Djava.rmi.server.hostname=10.1.2.3 </code></pre>
7,954,022
Javascript Regular Expression multiple match
<p>I'm trying to use javascript to do a regular expression on a url (window.location.href) that has query string parameters and cannot figure out how to do it. In my case, there is a query string parameter can repeat itself; for example "quality", so here I'm trying to match "quality=" to get an array with the 4 values (tall, dark, green eyes, handsome): </p> <pre><code>http://www.acme.com/default.html?id=27&amp;quality=tall&amp;quality=dark&amp;quality=green eyes&amp;quality=handsome </code></pre>
7,954,044
2
1
null
2011-10-31 12:58:09.84 UTC
1
2020-04-03 05:39:12.13 UTC
2011-10-31 13:35:04.38 UTC
null
31,671
null
815,460
null
1
17
javascript|regex
46,740
<p>You can use a regex to do this.</p> <pre><code>var qualityRegex = /(?:^|[&amp;;])quality=([^&amp;;]+)/g, matches, qualities = []; while (matches = qualityRegex.exec(window.location.search)) { qualities.push(decodeURIComponent(matches[1])); } </code></pre> <p><a href="http://jsfiddle.net/alexdickson/DPJAt/">jsFiddle</a>.</p> <p>The qualities will be in <code>qualities</code>.</p>
8,305,015
When using proxy_pass, can /etc/hosts be used to resolve domain names instead of "resolver"?
<p>Can <strong>/etc/hosts</strong> be used instead of <strong>resolver</strong> when using <strong>proxy_pass</strong>?</p> <p>I need to perform a proxy_pass to the same nginx machine. Is there a way to resolve the domains using the machine's /etc/hosts file instead of specifying a DNS server thru the "resolver" property?</p> <p>This will save me the additional hops needed to reach the same server. I have tried setting up the internal IP mapped to the DNS in /etc/hosts file but nginx is still reading from the DNS server set in the <strong>resolver</strong> property. Or is there a way to make the HTTPProxy module to consider the /etc/hosts file settings?</p> <p>Thanks for any advice you could share..</p> <p>This is the same question I posted in the nginx forum: <a href="http://forum.nginx.org/read.php?11,218997" rel="noreferrer">http://forum.nginx.org/read.php?11,218997</a></p>
8,559,797
2
3
null
2011-11-29 02:14:12.553 UTC
15
2017-07-19 15:41:00.597 UTC
2011-11-30 03:07:18.217 UTC
null
255,523
null
255,523
null
1
37
url-rewriting|nginx|reverse-proxy
22,469
<p>You can get around this by installing <code>dnsmasq</code> and setting your resolver to <code>127.0.0.1</code>. Basically this uses your local DNS as a resolver, but it only resolves what it knows about (among those things is your <code>/etc/hosts</code>) and forwards the rest to your default DNS.</p>
5,370,164
disabling Devise registration for production environment only
<p>I am launching a beta site with a select group of users. I want to disable registration in the production environment only, and only for a short period of time (i.e. I don't want to nuke my registration altogether). I know I can simply hide the "sign up" link, but I suspect that hackers smarter than I can still use the RESTful routes to accomplish registrations. What's the best way to disable registration so my test/development environments still work, but production is affected? Thanks for any pointers.</p> <p>I've tried pointing named scopes in such a way that "sign_up" goes to "sign_in", but it didn't work. Here's what I've tried:</p> <pre><code>devise_scope :user do get "users/sign_in", :to =&gt; "devise/sessions#new", :as =&gt; :sign_in get "users/sign_up", :to =&gt; "devise/sessions#new", :as =&gt; :sign_up end </code></pre> <p>Ideally, we'd send the user to a "pages#registration_disabled" page or something like that. I just wanted to get something working I can play around with.</p> <p>EDIT: I've changed the model as requested, then added the following to /spec/user_spec.rb</p> <pre><code>describe "validations" do it "should fail registration if in production mode" do ENV['RAILS_ENV'] = "production" @user = Factory(:user).should_not be_valid end end </code></pre> <p>it is passing as "true" rather than false. Is there a way to mock up the production environment? I'm just spit-balling this one. </p> <p>Thanks!</p>
8,291,318
4
6
null
2011-03-20 17:27:12.597 UTC
40
2014-03-09 03:33:55.763 UTC
2011-03-20 19:58:40.637 UTC
null
366,853
null
366,853
null
1
70
ruby-on-rails|devise|registration|production-environment
28,103
<p>Since others are having the problem I'm having (see my comments). Here is exactly how I fixed it. I used murphyslaw's idea. But you also need to make sure devise uses your new controller for the registration routing, or it won't do much for you.</p> <p>Here is my controller override:</p> <pre><code>class RegistrationsController &lt; Devise::RegistrationsController def new flash[:info] = 'Registrations are not open yet, but please check back soon' redirect_to root_path end def create flash[:info] = 'Registrations are not open yet, but please check back soon' redirect_to root_path end end </code></pre> <p>I've added flash messages to inform anyone who somehow stumbles upon the registration page why it isn't working.</p> <p>Here is what is in my <code>routes.rb</code></p> <pre><code> if Rails.env.production? devise_for :users, :controllers =&gt; { :registrations =&gt; "registrations" } else devise_for :users end </code></pre> <p>The controllers hash specifies that I want it to use my overridden registrations controller.</p> <p>Anyways, I hope that saves someone some time.</p>
4,924,365
SQL to return first two columns of a table
<p>Is there any <code>SQL</code> lingo to return JUST the first two <code>columns</code> of a table <strong>WITHOUT</strong> knowing the field <strong>names</strong>?</p> <p>Something like </p> <pre><code>SELECT Column(1), Column(2) FROM Table_Name </code></pre> <p>Or do I have to go the long way around and find out the column names first? How would I do that?</p>
4,924,418
8
2
null
2011-02-07 17:26:41.46 UTC
3
2013-04-29 00:31:22.007 UTC
2013-04-29 00:31:22.007 UTC
null
135,152
null
584,776
null
1
12
sql|sql-server-2008
59,273
<p>You have to get the column names first. Most platforms support this:</p> <pre><code>select column_name,ordinal_position from information_schema.columns where table_schema = ... and table_name = ... and ordinal_position &lt;= 2 </code></pre>
41,511,568
Get the full route to current action
<p>I have a simple API with basic routing. It was setup using the default Visual Studio 2015 ASP.NET Core API template.</p> <p>I have this controller and action:</p> <pre><code>[Route("api/[controller]")] public class DocumentController : Controller { [HttpGet("info/{Id}")] public async Task&lt;Data&gt; Get(string Id) { //Logic } } </code></pre> <p>So to reach this method, I must call <code>GET /api/document/info/some-id-here</code>.</p> <p><strong>Is it possible with .NET Core, inside that method, to retrieve as a string the complete route?</strong></p> <p>So I could do for example:</p> <pre><code>var myRoute = retrieveRoute(); // myRoute = "/api/document/info/some-id-here" </code></pre>
41,512,292
4
3
null
2017-01-06 18:01:44.537 UTC
1
2021-06-30 01:13:37.807 UTC
2021-03-17 10:35:46.197 UTC
null
3,934,994
null
6,361,127
null
1
33
c#|asp.net-core|.net-core|asp.net-core-mvc
42,433
<p>You can get the complete requested url using the <strong>Request</strong> option (HttpRequest) in .Net Core.</p> <pre><code>var route = Request.Path.Value; </code></pre> <p>Your final code.</p> <pre><code>[Route("api/[controller]")] public class DocumentController : Controller { [HttpGet("info/{Id}")] public async Task&lt;Data&gt; Get(string Id) { var route = Request.Path.Value; } } </code></pre> <p><em>Result route: "/api/document/info/some-id-here"</em> //for example</p>
12,381,408
Python: Split, strip, and join in one line
<p>I'm curious if their is some python magic I may not know to accomplish a bit of frivolity </p> <p>given the line:</p> <pre><code>csvData.append(','.join([line.split(":").strip() for x in L])) </code></pre> <p>I'm attempting to split a line on <code>:</code>, trim whitespace around it, and join on <code>,</code></p> <p>problem is, since the array is returned from <code>line.split(":")</code>, the </p> <pre><code>for x in L #&lt;== L doesn't exist! </code></pre> <p>causes issues since I have no name for the array returned by <code>line.split(":")</code></p> <p>So I'm curious if there is a sexy piece of syntax I could use to accomplish this in one shot?</p> <p>Cheers!</p>
12,381,435
3
0
null
2012-09-12 04:51:01.827 UTC
3
2012-09-12 15:36:27.61 UTC
2012-09-12 15:36:27.61 UTC
null
841,721
null
841,721
null
1
13
python|join|split|list-comprehension|trim
47,658
<pre><code>&gt;&gt;&gt; line = 'a: b :c:d:e :f:gh ' &gt;&gt;&gt; ','.join(x.strip() for x in line.split(':')) 'a,b,c,d,e,f,gh' </code></pre> <p>You can also do this:</p> <pre><code>&gt;&gt;&gt; line.replace(':',',').replace(' ','') 'a,b,c,d,e,f,gh' </code></pre>
12,153,255
How to view the nearest neighbors in R?
<p>Let me start by saying I have no experience with R, KNN or data science in general. I recently found <a href="http://kaggle.com" rel="noreferrer">Kaggle</a> and have been playing around with the <a href="http://www.kaggle.com/c/digit-recognizer" rel="noreferrer">Digit Recognition</a> competition/tutorial.</p> <p>In this tutorial they provide some sample code to get you started with a basic submission:</p> <pre><code># makes the KNN submission library(FNN) train &lt;- read.csv("c:/Development/data/digits/train.csv", header=TRUE) test &lt;- read.csv("c:/Development/data/digits/test.csv", header=TRUE) labels &lt;- train[,1] train &lt;- train[,-1] results &lt;- (0:9)[knn(train, test, labels, k = 10, algorithm="cover_tree")] write(results, file="knn_benchmark.csv", ncolumns=1) </code></pre> <p>My questions are:</p> <ol> <li>How can I view the nearest neighbors that have been selected for a particular test row?</li> <li>How can I modify which of those ten is selected for my <code>results</code>?</li> </ol> <p>These questions may be too broad. If so, I would welcome any links that could point me down the right road.</p> <p>It is <strong>very</strong> possible that I have said something that doesn't make sense here. If this is the case, please correct me.</p>
12,153,565
1
0
null
2012-08-28 05:27:01.403 UTC
10
2017-03-03 20:34:58.753 UTC
2017-03-03 20:34:58.753 UTC
null
769,871
null
226,897
null
1
15
r|kaggle
19,597
<p>1) You can get the nearest neighbors of a given row like so:</p> <pre><code>k &lt;- knn(train, test, labels, k = 10, algorithm="cover_tree") indices &lt;- attr(k, "nn.index") </code></pre> <p>Then if you want the indices of the 10 nearest neighbors to row 20 in the training set:</p> <pre><code>print(indices[20, ]) </code></pre> <p>(You'll get the 10 nearest neighbors because you selected <code>k=10</code>). For example, if you run with only the first 1000 rows of the training and testing set (to make it computationally easier):</p> <pre><code>train &lt;- read.csv("train.csv", header=TRUE)[1:1000, ] test &lt;- read.csv("test.csv", header=TRUE)[1:1000, ] labels &lt;- train[,1] train &lt;- train[,-1] k &lt;- knn(train, test, labels, k = 10, algorithm="cover_tree") indices = attr(k, "nn.index") print(indices[20, ]) # output: # [1] 829 539 784 487 293 882 367 268 201 277 </code></pre> <p>Those are the indices within the training set of 1000 that are closest to the 20th row of the test set.</p> <p>2) It depends what you mean by "modify". For starters, you can get the indices of each of the 10 closest labels to each row like this:</p> <pre><code>closest.labels = apply(indices, 2, function(col) labels[col]) </code></pre> <p>You can then see the labels of the 10 closest points to the 20th training point like this:</p> <pre><code>closest.labels[20, ] # [1] 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>This indicates that all 10 of the closest points to row 20 are all in the group labeled 0. <code>knn</code> simply chooses the label by majority vote (with ties broken at random), but you could choose some kind of weighting scheme if you prefer.</p> <p>ETA: If you're interested in weighting the closer elements more heavily in your voting scheme, note that you can also get the distances to each of the k neighbors like this:</p> <pre><code>dists = attr(k, "nn.dist") dists[20, ] # output: # [1] 1238.777 1243.581 1323.538 1398.060 1503.371 1529.660 1538.128 1609.730 # [9] 1630.910 1667.014 </code></pre>
12,051,440
Create a directory in Perl for a logfile if it does not exist
<p>I have a Perl script which takes a few arguments. It is executed like this:</p> <pre><code>exec myscript.pl --file=/path/to/input/file --logfile=/path/to/logfile/logfile.log </code></pre> <p>I have the following line in the script:</p> <pre><code>open LOGFILE, "&gt;&gt;$logFilePath" or die "Can't open '$logFilePath': $!\n"; </code></pre> <p>Where <code>$logfilePath</code> is taken from the command line. If there is a path, /path/to/logfile/, but no logfile.log, it just creates it (which is the desired action). However, it fails to start if there is no such path. How can I make the script create the path for the logfile, if it does not exist prior to running the script?</p>
12,051,893
2
4
null
2012-08-21 08:58:59.897 UTC
3
2017-06-22 19:07:02.147 UTC
2017-06-22 19:07:02.147 UTC
null
63,550
null
1,546,927
null
1
17
perl|directory|mkdir
52,221
<p>Suppose you have the path to the logfile (which may or may not include the filename: <code>logfile.log</code>) in the variable <code>$full_path</code>. Then, you can create the respective directory tree if needed:</p> <pre><code>use File::Basename qw( fileparse ); use File::Path qw( make_path ); use File::Spec; my ( $logfile, $directories ) = fileparse $full_path; if ( !$logfile ) { $logfile = 'logfile.log'; $full_path = File::Spec-&gt;catfile( $full_path, $logfile ); } if ( !-d $directories ) { make_path $directories or die "Failed to create path: $directories"; } </code></pre> <p>Now, <code>$full_path</code> will contain the full path to the <code>logfile.log</code> file. The directory tree in the path will have also been created.</p>
12,241,084
How to insert data into SQL Server
<p>What the problem on my coding? I cannot insert data to ms sql.. I'm using C# as front end and MS SQL as databases...</p> <pre><code>name = tbName.Text; userId = tbStaffId.Text; idDepart = int.Parse(cbDepart.SelectedValue.ToString()); string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) " + " VALUES ('" + name + "', '" + userId +"', '" + idDepart + "');"; SqlCommand querySaveStaff = new SqlCommand(saveStaff); try { querySaveStaff.ExecuteNonQuery(); } catch { //Error when save data MessageBox.Show("Error to save on database"); openCon.Close(); Cursor = Cursors.Arrow; } </code></pre>
12,241,114
3
4
null
2012-09-03 01:34:24.08 UTC
12
2021-04-13 09:30:39.49 UTC
2012-09-03 03:50:42.657 UTC
null
76,337
null
1,642,583
null
1
25
c#|sql|sql-server
205,618
<p>You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid <a href="http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx" rel="noreferrer">SQL Injection</a>.</p> <pre><code> using(SqlConnection openCon=new SqlConnection("your_connection_String")) { string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)"; using(SqlCommand querySaveStaff = new SqlCommand(saveStaff)) { querySaveStaff.Connection=openCon; querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name; ..... openCon.Open(); querySaveStaff.ExecuteNonQuery(); } } </code></pre>
12,283,184
How is Elastic Net used?
<p>This is a beginner question on regularization with regression. Most information about Elastic Net and Lasso Regression online replicates the information from Wikipedia or the original 2005 paper by Zou and Hastie (Regularization and variable selection via the elastic net). </p> <p><strong><em>Resource for simple theory?</em></strong> Is there a simple and easy explanation somewhere about what it does, when and why reguarization is neccessary, and how to use it - for those who are not statistically inclined? I understand that the original paper is the ideal source if you can understand it, but is there somewhere that more simply the problem and solution?</p> <p><strong><em>How to use in sklearn?</em></strong> Is there a step by step example showing why elastic net is chosen (over ridge, lasso, or just simple OLS) and how the parameters are calculated? Many of the <a href="http://scikit-learn.org/0.11/auto_examples/index.html" rel="noreferrer">examples on sklearn</a> just include alpha and rho parameters directly into the prediction model, for <a href="http://scikit-learn.org/0.11/auto_examples/linear_model/plot_lasso_and_elasticnet.html" rel="noreferrer">example</a>:</p> <pre><code>from sklearn.linear_model import ElasticNet alpha = 0.1 enet = ElasticNet(alpha=alpha, rho=0.7) y_pred_enet = enet.fit(X_train, y_train).predict(X_test) </code></pre> <p>However, they don't explain how these were calculated. How do you calculate the parameters for the lasso or net?</p>
12,294,769
3
3
null
2012-09-05 13:59:32.897 UTC
21
2020-08-26 12:35:40.963 UTC
null
null
null
null
1,406,413
null
1
28
python|statistics|machine-learning|regression|scikit-learn
20,361
<p>The documentation is lacking. I created a new <a href="https://github.com/scikit-learn/scikit-learn/issues/1118">issue</a> to improve it. As Andreas said the best resource is probably <a href="http://www-stat.stanford.edu/~tibs/ElemStatLearn/">ESL II</a> freely available online as PDF.</p> <p>To automatically tune the value of alpha it is indeed possible to use <a href="http://scikit-learn.org/dev/modules/generated/sklearn.linear_model.ElasticNetCV.html#sklearn.linear_model.ElasticNetCV">ElasticNetCV</a> which will spare redundant computation as apposed to using <a href="http://scikit-learn.org/dev/modules/grid_search.html">GridSearchCV</a> in the <code>ElasticNet</code> class for tuning <code>alpha</code>. In complement, you can use a regular <code>GridSearchCV</code> for finding the optimal value of <code>rho</code>. See the docstring of <a href="http://scikit-learn.org/dev/modules/generated/sklearn.linear_model.ElasticNetCV.html#sklearn.linear_model.ElasticNetCV">ElasticNetCV</a> fore more details.</p> <p>As for Lasso vs ElasticNet, ElasticNet will tend to select more variables hence lead to larger models (also more expensive to train) but also be more accurate in general. In particular Lasso is very sensitive to correlation between features and might select randomly one out of 2 very correlated informative features while ElasticNet will be more likely to select both which should lead to a more stable model (in terms of generalization ability so new samples).</p>
24,233,084
How do I add a tuple to a Swift Array?
<p>I'm trying to add a tuple (e.g., 2-item tuple) to an array.</p> <pre><code>var myStringArray: (String,Int)[]? = nil myStringArray += ("One", 1) </code></pre> <p>What I'm getting is: <br/></p> <blockquote> <p>Could not find an overload for '+=' that accepts the supplied arguments</p> </blockquote> <p><br/> <strong>Hint:</strong> I tried to do an overload of the '+=' per reference book: <br/></p> <pre><code>@assignment func += (inout left: (String,Int)[], right: (String,Int)[]) { left = (left:String+right:String, left:Int+right+Int) } </code></pre> <p>...but haven't got it right.</p> <p>Any ideas? ...solution?</p>
25,838,682
8
9
null
2014-06-15 19:03:45.993 UTC
21
2018-03-27 03:25:05.06 UTC
2017-08-31 23:23:32.75 UTC
null
4,763,963
null
715,747
null
1
56
arrays|tuples|swift
65,976
<p>Since this is still the top answer on google for adding tuples to an array, its worth noting that things have changed slightly in the latest release. namely:</p> <p>when declaring/instantiating arrays; the type is now nested within the braces:</p> <pre><code>var stuff:[(name: String, value: Int)] = [] </code></pre> <p>the compound assignment operator, <code>+=</code>, is now used for concatenating arrays; if adding a single item, it needs to be nested in an array:</p> <pre><code>stuff += [(name: "test 1", value: 1)] </code></pre> <p>it also worth noting that when using <code>append()</code> on an array containing named tuples, you can provide each property of the tuple you're adding as an argument to <code>append()</code>:</p> <pre><code>stuff.append((name: "test 2", value: 2)) </code></pre>
37,001,004
Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."
<p>Important notice:</p> <p>If you register for testing, go to your profile settings and to your <strong>interests</strong> add <strong>delete profile</strong>.</p> <p>Trying to login with Facebook to my <a href="http://openstrategynetwork.com/" rel="noreferrer">website</a>:</p> <p>I get the following error: </p> <blockquote> <p>URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.</p> </blockquote> <p>My <code>settings</code> (Basics) in Facebook are:</p> <ul> <li>App Domains: openstrategynetwork.com</li> <li>Site URL for <code>website</code>: <a href="http://openstrategynetwork.com/" rel="noreferrer">http://openstrategynetwork.com/</a></li> </ul> <p>In the advanced tab, <code>Valid OAuth redirect URIs</code> is set to:</p> <p><code>http://openstrategynetwork.com/_oauth/facebook?close</code></p> <p>App is <code>public</code>.</p> <p>More settings (Advanced) here: <a href="https://i.stack.imgur.com/UcWaO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UcWaO.png" alt="enter image description here"></a></p> <p>App key and secret are correct. I'm using Meteor and its accounts packages. </p>
37,009,374
17
6
null
2016-05-03 09:55:03.39 UTC
26
2022-07-28 22:57:52.923 UTC
2017-08-06 08:57:28.41 UTC
null
1,240,203
null
1,240,203
null
1
148
facebook|facebook-graph-api|meteor|oauth
296,309
<p>The login with Facebook button on your site is linking to:</p> <p><code>https://www.facebook.com/v2.2/dialog/oauth?client_id=1500708243571026&amp;redirect_uri=http://openstrategynetwork.com/_oauth/facebook&amp;display=popup&amp;scope=email&amp;state=eyJsb2dpblN0eWxlIjoicG9wdXAiLCJjcmVkZW50aWFsVG9rZW4iOiIwSXhEU05XamJjU0VaQWdqcmF6SXdOUWRuRFozXzc0X19lbVhGWUJTZGNYIiwiaXNDb3Jkb3ZhIjpmYWxzZX0=</code></p> <p>Notice: <code>redirect_uri=http://openstrategynetwork.com/_oauth/facebook</code></p> <p>If you instead change the link to:</p> <p><code>redirect_uri=http://openstrategynetwork.com/_oauth/facebook?close</code></p> <p>It should work. Or, you can change the Facebook link to <code>http://openstrategynetwork.com/_oauth/facebook</code></p> <p>You can also add <code>http://localhost/_oauth/facebook</code> to the valid redirect URIs. </p> <p>Facebook requires that you whitelist redirect URIs, since otherwise people could login with Facebook for your service, and then send their access token to an attacker's server! And you don't want that to happen ;]</p>
8,870,982
How do I get a lognormal distribution in Python with Mu and Sigma?
<p>I have been trying to get the result of a <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html" rel="noreferrer">lognormal</a> distribution using <a href="http://www.scipy.org/" rel="noreferrer">Scipy</a>. I already have the Mu and Sigma, so I don't need to do any other prep work. If I need to be more specific (and I am trying to be with my limited knowledge of stats), I would say that I am looking for the cumulative function (cdf under Scipy). The problem is that I can't figure out how to do this with just the mean and standard deviation on a scale of 0-1 (ie the answer returned should be something from 0-1). I'm also not sure which method from <strong>dist</strong>, I should be using to get the answer. I've tried reading the documentation and looking through SO, but the relevant questions (like <a href="https://stackoverflow.com/questions/8747761/scipy-lognormal-distribution-parameters">this</a> and <a href="https://stackoverflow.com/questions/1154378/how-to-run-statistics-cumulative-distribution-function-and-probablity-density-fu">this</a>) didn't seem to provide the answers I was looking for.</p> <p>Here is a code sample of what I am working with. Thanks.</p> <pre><code>from scipy.stats import lognorm stddev = 0.859455801705594 mean = 0.418749176686875 total = 37 dist = lognorm.cdf(total,mean,stddev) </code></pre> <p><strong>UPDATE:</strong></p> <p>So after a bit of work and a little research, I got a little further. But I still am getting the wrong answer. The new code is below. According to R and Excel, the result should be <em>.7434</em>, but that's clearly not what is happening. Is there a logic flaw I am missing?</p> <pre><code>dist = lognorm([1.744],loc=2.0785) dist.cdf(25) # yields=0.96374596, expected=0.7434 </code></pre> <p><strong>UPDATE 2:</strong> Working lognorm implementation which yields the correct <strong>0.7434</strong> result.</p> <pre><code>def lognorm(self,x,mu=0,sigma=1): a = (math.log(x) - mu)/math.sqrt(2*sigma**2) p = 0.5 + 0.5*math.erf(a) return p lognorm(25,1.744,2.0785) &gt; 0.7434 </code></pre>
8,871,222
7
6
null
2012-01-15 15:47:59.6 UTC
20
2022-09-22 19:45:49.873 UTC
2017-05-23 12:32:35.72 UTC
null
-1
null
227,644
null
1
29
python|statistics|scipy
53,243
<p>It sounds like you want to instantiate a "frozen" distribution from known parameters. In your example, you could do something like:</p> <pre><code>from scipy.stats import lognorm stddev = 0.859455801705594 mean = 0.418749176686875 dist=lognorm([stddev],loc=mean) </code></pre> <p>which will give you a lognorm distribution object with the mean and standard deviation you specify. You can then get the pdf or cdf like this:</p> <pre><code>import numpy as np import pylab as pl x=np.linspace(0,6,200) pl.plot(x,dist.pdf(x)) pl.plot(x,dist.cdf(x)) </code></pre> <p><img src="https://i.stack.imgur.com/UF4D3.png" alt="lognorm cdf and pdf"></p> <p>Is this what you had in mind?</p>
20,514,240
What's the difference setting Embed Interop Types true and false in Visual Studio?
<p>In Visual Studio, when adding one reference to the project, the properties window has an option <code>Embed Inteop Types</code>, should we set it to <code>True</code> or <code>False</code>? What's the difference?</p> <p>Since we have a lot of projects, among some of them, reference was set to <code>False</code>, others were set to <code>True</code>, it is totally mess up. And the bulid server also have the same warnings: </p> <blockquote> <p><a href="https://stackoverflow.com/questions/8156488/what-does-reference-was-created-to-embedded-interop-assembly-mean">What does β€œreference was created to embedded interop assembly” mean?</a></p> </blockquote> <p>So we plan to change all the <code>Embed Inteop Types</code> to <code>False</code>, what risk would we get? </p>
20,515,311
2
6
null
2013-12-11 08:35:48.887 UTC
21
2021-12-26 15:46:19.797 UTC
2017-05-23 11:47:11.08 UTC
null
-1
null
3,022,229
null
1
135
c#|visual-studio
111,933
<p>This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.</p> <p>It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.</p> <p>Read more in Scott Hanselman's blog post about it and other VS improvements here: <a href="http://www.hanselman.com/blog/CLRAndDLRAndBCLOhMyWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx" rel="nofollow noreferrer">CLR and DLR and BCL, oh my! - Whirlwind Tour around .NET 4 (and Visual Studio 2010) Beta 1</a>.</p> <p>As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:</p> <ul> <li><a href="https://weblogs.asp.net/cazzu/check-your-embed-interop-types-flag-when-doing-visual-studio-extensibility-work" rel="nofollow noreferrer">Check your Embed Interop Types flag when doing Visual Studio extensibility work</a></li> <li><a href="https://blogs.iis.net/samng/the-pain-of-deploying-primary-interop-assemblies" rel="nofollow noreferrer">The Pain of deploying Primary Interop Assemblies</a></li> </ul> <p>The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.</p>
26,002,415
What does Haskell's <|> operator do?
<p>Going through Haskell's documentation is always a bit of a pain for me, because all the information you get about a function is often nothing more than just: <code>f a -&gt; f [a]</code> which could mean any number of things.</p> <p>As is the case of the <code>&lt;|&gt;</code> function.</p> <p>All I'm given is this: <code>(&lt;|&gt;) :: f a -&gt; f a -&gt; f a</code> and that it's an <em>"associative binary operation"</em>...</p> <p>Upon inspection of <code>Control.Applicative</code> I learn that it does seemingly unrelated things depending on implementation.</p> <pre><code>instance Alternative Maybe where empty = Nothing Nothing &lt;|&gt; r = r l &lt;|&gt; _ = l </code></pre> <p>Ok, so it returns right if there is no left, otherwise it returns left, gotcha.. This leads me to believe it's a "left or right" operator, which kinda makes sense given its use of <code>|</code> and <code>|</code>'s historical use as "OR"</p> <pre><code>instance Alternative [] where empty = [] (&lt;|&gt;) = (++) </code></pre> <p>Except here it just calls list's concatenation operator... Breaking my idea down...</p> <p>So what exactly is that function? What's its use? Where does it fit in in the grand scheme of things?</p>
26,002,623
4
6
null
2014-09-23 18:39:18.953 UTC
20
2021-02-22 04:55:40.46 UTC
2021-02-22 04:55:40.46 UTC
null
2,751,851
null
1,351,298
null
1
74
haskell|applicative|alternative-functor
17,548
<p>Typically it means "choice" or "parallel" in that <code>a &lt;|&gt; b</code> is either a "choice" of <code>a</code> or <code>b</code> or <code>a</code> and <code>b</code> done in parallel. But let's back up.</p> <p>Really, there is no practical meaning to operations in typeclasses like <code>(&lt;*&gt;)</code> or <code>(&lt;|&gt;)</code>. These operations are given meaning in two ways: (1) via laws and (2) via instantiations. If we are not talking about a <em>particular</em> instance of <code>Alternative</code> then only (1) is available for intuiting meaning.</p> <p>So "associative" means that <code>a &lt;|&gt; (b &lt;|&gt; c)</code> is the same as <code>(a &lt;|&gt; b) &lt;|&gt; c</code>. This is useful as it means that we only care about the <em>sequence</em> of things chained together with <code>(&lt;|&gt;)</code>, not their "tree structure".</p> <p>Other laws include identity with <code>empty</code>. In particular, <code>a &lt;|&gt; empty = empty &lt;|&gt; a = a</code>. In our intuition with "choice" or "parallel" these laws read as "a or (something impossible) must be a" or "a alongside (empty process) is just a". It indicates that <code>empty</code> is some kind of "failure mode" for an <code>Alternative</code>.</p> <p>There are other laws with how <code>(&lt;|&gt;)</code>/<code>empty</code> interact with <code>fmap</code> (from <code>Functor</code>) or <code>pure</code>/<code>(&lt;*&gt;)</code> (from <code>Applicative</code>), but perhaps the best way to move forward in understanding the meaning of <code>(&lt;|&gt;)</code> is to examine a very common example of a type which instantiates <code>Alternative</code>: a <code>Parser</code>.</p> <p>If <code>x :: Parser A</code> and <code>y :: Parser B</code> then <code>(,) &lt;$&gt; x &lt;*&gt; y :: Parser (A, B)</code> parses <code>x</code> <em>and then</em> <code>y</code> in sequence. In contrast, <code>(fmap Left x) &lt;|&gt; (fmap Right y)</code> parses <em>either</em> <code>x</code> or <code>y</code>, beginning with <code>x</code>, to try out both possible parses. In other words, it indicates a <em>branch</em> in your parse tree, a choice, or a parallel parsing universe.</p>
10,895,331
How to check multiple radio button, radio buttons having same name?
<p>I want to check multiple radio buttons, all radio buttons having same name but different ids.</p> <p>Here is my html code,</p> <pre><code> &lt;span style="float:left;margin:0 0 0 10px"&gt;Proactivity&lt;/span&gt; &lt;label for="q11" style="width:auto;margin:0 60px 0 0;padding:0;"&gt;&lt;input type="radio" id="qq[]" class="styled" value="Proactivity &gt; Poor" name="q11[]"&gt;Poor&lt;/label&gt; &lt;label for="q11" style="width:auto;margin:0 18px 0 0;padding:0;"&gt;&lt;input type="radio" id="qqa[]" class="styled" value="Proactivity &gt; Good" name="q11[]"&gt;Good&lt;/label&gt; &lt;br/&gt;&lt;br/&gt; &lt;span style="float:left;margin:0 0 0 10px"&gt;Service/support&lt;/span&gt; &lt;label for="q11" style="width:auto;margin:0 60px 0 0;padding:0;"&gt;&lt;input type="radio" id="qq[]" class="styled" value="Service/support &gt; Poor" name="q11[]"&gt;Poor&lt;/label&gt; &lt;label for="q11" style="width:auto;margin:0 18px 0 0;padding:0;"&gt;&lt;input type="radio" id="qqa[]" class="styled" value="Service/support &gt; Good" name="q11[]"&gt;Good&lt;/label&gt; &lt;br/&gt;&lt;br/&gt; &lt;span style="float:left;margin:0 0 0 10px"&gt;Provision of &lt;br /&gt;specialist skills&lt;/span&gt; &lt;label for="q11" style="width:auto;margin:0 60px 0 0;padding:0;"&gt;&lt;input type="radio" id="qq[]" class="styled" value="Provision of specialist skills &gt; Poor" name="q11[]"&gt;Poor&lt;/label&gt; &lt;label for="q11" style="width:auto;margin:0 18px 0 0;padding:0;"&gt;&lt;input type="radio" id="qqa[]" class="styled" value="Provision of specialist skills &gt; Good" name="q11[]"&gt;Good&lt;/label&gt; </code></pre>
10,895,342
6
2
null
2012-06-05 10:06:18.043 UTC
1
2015-12-11 12:22:27.827 UTC
2014-06-25 17:11:23.243 UTC
null
2,246,344
null
1,103,302
null
1
10
html|radio-button
67,069
<p>You can't. Radio buttons are there for a <strong>single choice</strong>. For multiple choices, you need checkboxes.</p>