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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17,907,445 | How to detect IE11? | <p>When I want to detect IE I use this code:</p>
<pre><code>function getInternetExplorerVersion()
{
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function checkVersion()
{
var msg = "You're not using Internet Explorer.";
var ver = getInternetExplorerVersion();
if ( ver > -1 )
{
msg = "You are using IE " + ver;
}
alert( msg );
}
</code></pre>
<p>But IE11 is returning "You're not using Internet Explorer". How can I detect it?</p> | 17,907,562 | 16 | 7 | null | 2013-07-28 10:49:00.667 UTC | 73 | 2021-06-26 08:46:40.587 UTC | 2014-02-27 23:17:53.2 UTC | null | 1,113,772 | user2591042 | null | null | 1 | 217 | internet-explorer|debugging|internet-explorer-11|browser-detection|forward-compatibility | 232,232 | <p>IE11 no longer reports as <code>MSIE</code>, according to <a href="http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.110).aspx" rel="noreferrer">this list of changes</a> it's intentional to avoid mis-detection.</p>
<p>What you can do if you <em>really</em> want to know it's IE is to detect the <code>Trident/</code> string in the user agent if <code>navigator.appName</code> returns <code>Netscape</code>, something like (the untested);</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getInternetExplorerVersion()
{
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
else if (navigator.appName == 'Netscape')
{
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
console.log('IE version:', getInternetExplorerVersion());</code></pre>
</div>
</div>
</p>
<p>Note that IE11 (afaik) still is in preview, and the user agent may change before release.</p> |
6,537,589 | Best way to copy from one array to another | <p>When I run the following code, nothing gets copied - what am I doing wrong?</p>
<p>Also, is this the best/most efficient way to copy data from one array to another?</p>
<pre><code>public class A {
public static void main(String args[]) {
int a[] = { 1, 2, 3, 4, 5, 6 };
int b[] = new int[a.length];
for (int i = 0; i < a.length; i++) {
a[i] = b[i];
}
}
}
</code></pre> | 6,537,623 | 3 | 2 | null | 2011-06-30 15:55:07.143 UTC | 8 | 2020-07-22 17:31:44.87 UTC | 2014-11-03 05:38:58.047 UTC | null | 256,196 | null | 820,437 | null | 1 | 18 | java|arrays | 150,430 | <p>I think your assignment is backwards:</p>
<p><code>a[i] = b[i];</code></p>
<p>should be:</p>
<p><code>b[i] = a[i];</code></p> |
6,317,937 | Dapper.NET and stored proc with multiple result sets | <p>Is there any way to use Dapper.NET with stored procs that return multiple result sets?</p>
<p>In my case, the first result set is a single row with a single column; if it's <code>0</code> then the call was successful, and the second result set will contain that actual rows/columns of data. (and if it was non-zero, an error occured and no second result set will be provided)</p>
<p>Any chance to handle this with Dapper.NET? So far, I'm only ever getting back that single <code>0</code> - but nothing more.</p>
<p><strong>Update:</strong> OK, it works fine - as long as the result set no. 2 is a single entity:</p>
<pre><code>Dapper.SqlMapper.GridReader reader =
_conn.QueryMultiple("sprocname", dynParams,
commandType: CommandType.StoredProcedure);
int status = reader.Read<int>().FirstOrDefault();
MyEntityType resultObj = reader.Read<MyEntityType>().FirstOrDefault();
</code></pre>
<p>Now, I have <strong>yet another</strong> requirement.</p>
<p>Dapper's multi-mapping (splitting up a single row returned from SQL Server into two separate entities) for that second result set doesn't seem to be supported as of yet (at least there doesn't seem to be an overload of <code>.Read<T></code> that can handle multi-mapping).</p>
<p>How can I get split that row into two entities?</p> | 6,317,983 | 3 | 1 | null | 2011-06-11 19:07:09.08 UTC | 19 | 2022-05-29 06:30:12.497 UTC | 2015-01-29 19:00:45.863 UTC | null | 50,776 | null | 13,302 | null | 1 | 94 | sql-server|stored-procedures|dapper|multiple-resultsets | 84,883 | <p>Have you tried the <code>QueryMultiple</code> method? It says it should:</p>
<blockquote>
<p>Execute a command that returns
multiple result sets, and access each
in turn</p>
</blockquote>
<p>You'll need to add this using statement to enable QueryMultiple .</p>
<pre><code>using Dapper; /* to add extended method QueryMultiple public static GridReader QueryMultiple(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null); */
</code></pre> |
15,753,827 | PHP calendar with recurring events from MySQL database | <p><strong>UPDATE:</strong>
Below is my original question. See my answer to see how I solved it.</p>
<hr>
<p>I am trying to populate my calendar with events from MySQL database table 'churchcal_events'. I might have one-time events for specific dates and recurring events that can be set for Every Monday, Every Other Thursday, or Every Month on Second Friday.</p>
<p>One-time events are no problem. And weekly events work (every week, every other). But an <strong>every-month-event shows only on the first month, not on the months following</strong>.</p>
<p><strong>churchcal_events table</strong> - excluding fields that are not important to this question</p>
<pre><code>+----+----------------+------------+-----------+------------+------------+
| id | name | recurring | frequency | recur_type | recur_day |
+----+----------------+------------+-----------+------------+------------+
| 1 | Test Weekly | 1 | 1 | W | Sunday |
| 2 | Test Bi-Weekly | 1 | 2 | W | Monday |
| 3 | Test Monthly | 1 | 1 | M | Friday |
+----+----------------+------------+-----------+------------+------------+
</code></pre>
<p><strong>php code</strong> - inside of a loop for each day of the month</p>
<pre><code>//query all events
$get_events = db_query("SELECT * FROM {churchcal_events}
WHERE (MONTH(date) = :month AND YEAR(date) = :year AND DAY(date) = :day) OR
(recurring = :recur AND recur_day LIKE :calendar_day)
ORDER BY starttime",
array(
':month' => $month,
':year' => $year,
':day' => $list_day,
':recur' => '1',
':calendar_day' => '%' . date('l', strtotime($month . '/' . $list_day . '/' . $year)) . '%',
));
foreach($get_events as $event) {
//see if events belong to this calendar
$calendar_assign = db_query("SELECT * FROM {churchcal_assign} WHERE event_id = :event_id AND calendar_id = :cal_id",
array(
':event_id' => $event->id,
':cal_id' => $cal_id,
));
if($calendar_assign->rowCount() > 0) {
//if recurring, see if event should be on this day
if($event->recurring == '1') {
$recur_day = $event->recur_day;
$recur_freq = $event->frequency;
$recur_type = $event->recur_type;
$recur_start = new DateTime(date('Y-m-d', strtotime($event->recur_start)));
$recur_end = new DateTime(date('Y-m-d', strtotime($event->recur_end)));
$recur_start->modify($recur_day);
$recur_interval = new DateInterval("P{$recur_freq}{$recur_type}");
$recur_period = new DatePeriod($recur_start, $recur_interval, $recur_end);
foreach($recur_period as $recur_date) {
if($recur_date->format('Ymd') == date('Ymd', strtotime($month . '/' . $list_day . '/' . $year))) {
$calendar .= calendar_event($event-id, $event->name, $event->starttime);
}
}
}
</code></pre>
<p><strong>How can I make ID '3' from the example churchcal_events table show up the first Friday of every month?</strong></p> | 15,758,346 | 1 | 7 | null | 2013-04-01 23:50:00.007 UTC | 9 | 2013-04-02 17:46:40.403 UTC | 2013-04-02 17:46:40.403 UTC | null | 879,608 | null | 879,608 | null | 1 | 11 | php|mysql | 13,970 | <p>In case anyone would like to do something similar, I will post the code that I wrote and tested within the last five hours.</p>
<p>I decided to convert my two tables into three, moving all of the recurring options to the third table:</p>
<p><strong>'churchcal_events'</strong> - there are additional fields for event info that I haven't included here</p>
<pre><code>+----+-----------+------------+------------+------------+-----------+
| id | name | date | starttime | endtime | recurring |
+----+-----------+------------+------------+------------+-----------+
| 1 | Event 1 | 2013-04-01 | 10:30:00 | 12:00:00 | 0 |
| 2 | Event 2 | | 14:00:00 | 15:00:00 | 1 |
| 3 | Event 3 | | 09:00:00 | | 1 |
| 4 | Event 4 | | 19:00:00 | 21:00:00 | 1 |
+----+-----------+------------+------------+------------+-----------+
</code></pre>
<p><strong>'churchcal_assign'</strong> - routes events to appropriate calendars (because there will be calendars for different departments throughout the website)</p>
<pre><code>+----------+-------------+
| event_id | calendar_id |
+----------+-------------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
+----------+-------------+
</code></pre>
<p><strong>'churchcal_recur_events'</strong> - Here are the rules for each event's recurrence</p>
<pre><code>+----------+-----------+------------+----------------+------------+-------------+-----------+
| event_id | frequency | recur_type | recur_day_num | recur_day | recur_start | recur_end |
+----------+-----------+------------+----------------+------------+-------------+-----------+
| 2 | 1 | Week | NULL | Sunday | NULL | NULL |
| 3 | 2 | Week | NULL | Wednesday | 2013-04-01 | NULL |
| 4 | 2 | Month | third | Friday | 2013-04-01 | NULL |
+----------+-----------+------------+----------------+------------+-------------+-----------+
</code></pre>
<p><strong>New Code (PHP)</strong> - This is in a day loop</p>
<pre><code> //query all events
$get_events = db_query("SELECT * FROM {churchcal_events ce, churchcal_recur_events cre}
WHERE (MONTH(ce.date) = :month AND YEAR(ce.date) = :year AND DAY(ce.date) = :day) OR
(ce.id = cre.event_id AND ce.recurring = :recur AND cre.recur_day = :calendar_day)
ORDER BY starttime",
array(
':month' => $month,
':year' => $year,
':day' => $list_day,
':recur' => '1',
':calendar_day' => date('l', strtotime($month . '/' . $list_day . '/' . $year)),
));
foreach($get_events as $event) {
//see if events belong to this calendar
$calendar_assign = db_query("SELECT * FROM {churchcal_assign} WHERE event_id = :event_id AND calendar_id = :cal_id",
array(
':event_id' => $event->id,
':cal_id' => $cal_id,
));
if($calendar_assign->rowCount() > 0) {
//one-time events
if(($event->recurring != '1') && ($single_event_id != $event->id)) {
$calendar .= calendar_event($event->id, $event->name, $event->starttime);
$single_event_id = $event->id;
//$calendar .= $single_event_id;
}
//monthly recurring events
if(($event->recur_type == 'Month') && ($event->recurring == '1')
//day is on or before end date
&& (($event->recur_end >= date('Y-m-d', strtotime($month . '/' . $list_day . '/' . $year))) || ($event->recur_end == '0000-00-00') || ($event->recur_end == NULL))
//day is on or after start date
&& (($event->recur_start <= date('Y-m-d', strtotime($month . '/' . $list_day . '/' . $year))) || ($event->recur_start == '0000-00-00') || ($event->recur_start == NULL))
//day is equal to date of recurrence, i.e. first friday, third monday, etc
&& ($year . date('m', strtotime($year . '/' . $month . '/' . $list_day)) . $list_day == date('Ymj', strtotime($event->recur_day_num . ' ' . $event->recur_day . ' of ' . date('F', strtotime($month . '/' . $list_day . '/' . $year)) . ' ' . $year)))
//day is in agreement with month frequency, i.e. every month, every other, etc. from start date
&& ($month % $event->frequency == date('m', strtotime($event->recur_start)) % $event->frequency)) {
$calendar .= calendar_event($event->id, $event->name, $event->starttime);
}
//weekly recurring events
if(($event->recur_type == 'Week') && ($event->recurring == '1')
//day is on or before end date
&& (($event->recur_end >= date('Y-m-d', strtotime($month . '/' . $list_day . '/' . $year))) || ($event->recur_end == '0000-00-00') || ($event->recur_end == NULL))
//day is on or after start date
&& (($event->recur_start <= date('Y-m-d', strtotime($month . '/' . $list_day . '/' . $year))) || ($event->recur_start == '0000-00-00') || ($event->recur_start == NULL))
//day is in agreement with week frequency, i.e. every week, every other, etc. from start date
&& (date('W', strtotime($month . '/' . $list_day . '/' . $year)) % $event->frequency == date('W', strtotime($event->recur_start)) % $event->frequency)) {
$calendar .= calendar_event($event->id, $event->name, $event->starttime);
}
}
}
</code></pre>
<p>If you are not creating this in a Drupal module like I am, you can replace 'db_query()' with your own database query function like PHP's default 'mysql_query()';</p> |
19,055,372 | Redirect to a subfolder in Apache virtual host file | <p>I have Joomla installed on a webserver running Ubuntu Server 12.04. The Joomla folder is located at /var/www/cms/. </p>
<p>My vhost file at /etc/apache2/sites-enabled/default has the following content:</p>
<pre><code><VirtualHost *:80>
ServerName domain.com/
Redirect permanent / https://domain.com/
</VirtualHost>
<VirtualHost *:443>
ServerAdmin webmaster@localhost
ServerName domain.com:443
DocumentRoot /var/www/cms
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
<Directory /var/www/cms>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
(...)
</VirtualHost>
</code></pre>
<p>At the moment, all the requests to domain.com and anything entered after that like domain.com/example gets directed and processed by Joomla which either redirects to a proper page or returns a custom 404 error. This all works. </p>
<p>Now, I would like to filter all the requests that go to domain.com/subfolder before they get processed by Joomla and redirect them to /var/www/subfolder (instead of my root folder at /var/www/cms/).</p>
<p>I believe the file in /etc/apache2/sites-enabled/default (seen above) is the right place to define such a redirect, however I have not been able to figure out at what position and how to achieve this.</p> | 19,055,573 | 1 | 3 | null | 2013-09-27 16:06:55.273 UTC | 6 | 2013-09-28 00:29:44.347 UTC | 2013-09-28 00:29:44.347 UTC | null | 210,916 | null | 2,824,066 | null | 1 | 23 | apache|redirect|joomla|virtualhost | 54,027 | <p>You should add to your configuration:</p>
<pre><code>Alias /subfolder /var/www/subfolder
<Directory /var/www/subfolder>
Order allow,deny
allow from all
</Directory>
</code></pre>
<p>and fit the configuration between "Directory" to your needs.</p>
<p>See the <a href="http://httpd.apache.org/docs/2.2/mod/mod_alias.html" rel="noreferrer">Apache documentation</a> to have more informations.</p> |
19,224,934 | How to set application name in a Postgresql JDBC url? | <p>I want to set the application name of the connections of my application. So when I list the rows in <code>pg_stat_activity</code> I can have a non empty <code>application_name</code> column.</p>
<p>I have setup the following JDBC url for connecting to my Postgresql database:</p>
<pre><code>jdbc:postgresql://localhost:5435/MyDB?application-name=MyApp
</code></pre>
<p>I have tried also this url with no more success.</p>
<pre><code>jdbc:postgresql://localhost:5435/MyDB?application_name=MyApp
</code></pre>
<p>What is the correct parameter name ?</p>
<p>Here is my JDBC driver version: <strong>9.1-901.jdbc4</strong></p> | 19,232,032 | 1 | 3 | null | 2013-10-07 12:28:03.213 UTC | 5 | 2018-02-09 07:40:05.13 UTC | 2015-09-25 17:23:08.123 UTC | null | 363,573 | null | 363,573 | null | 1 | 43 | postgresql|url|jdbc|postgresql-9.2 | 23,865 | <p>Looking at the <a href="http://jdbc.postgresql.org/documentation/91/connect.html#connection-parameters" rel="noreferrer">PostgreSQL JDBC 9.1 documentation, connection parameters</a>, the correct property name in the JDBC url is <code>ApplicationName</code>:</p>
<blockquote>
<p><code>ApplicationName = String</code></p>
<p>Specifies the name of the application that is using the connection. This allows a database administrator to see what applications are connected to the server and what resources they are using through views like <code>pg_stat_activity</code></p>
</blockquote>
<p>So try:</p>
<pre><code>jdbc:postgresql://localhost:5435/MyDB?ApplicationName=MyApp
</code></pre>
<p>Be aware some comments suggest that this is broken in the 9.1 version driver. Given it is a more than 5 year old version, you should upgrade to a newer version anyway. Check <a href="https://jdbc.postgresql.org/" rel="noreferrer">https://jdbc.postgresql.org/</a> for the latest version and use that.</p> |
27,764,825 | How to avoid overfitting with genetic algorithm | <p>I am facing the following problem.
I have a system able to produce a ranking of some operations according to their anomaly score. To improve the performance I implemented a genetic algorithm to perform a features selection, such that the most anomalous operations appears in the first positions. What I am doing is not exactly feature selection, because I am not using binary variables, rather float variables between 0-1, which sum is equal to 1.</p>
<p>Currently, I have a population of 200 individuals for 50 generations. I am using as the evaluation function the system itself and I evaluate the quality of the solution by using the true positive rate, counting how many anomalous operations appears in the first N positions (where N is the number of anomalous operations). Then as operator the uniform crossover and I change a valueof a cell of the individual for the mutation. Of course, every time I make a check to fix the individual such that the sum is 1. Finally I use elitism to save the best-so-far solution over the time.</p>
<p>I observed that one feature has a very high value, which is often important, but not always, and this causes very low values for the other features. I suspect that my GA is overfitting.
Can you help me to find a good stop criteria?</p> | 27,766,610 | 1 | 2 | null | 2015-01-04 11:00:02.917 UTC | 10 | 2015-01-05 09:13:38.52 UTC | 2015-01-05 09:13:38.52 UTC | null | 2,297,037 | null | 2,297,037 | null | 1 | 8 | genetic-algorithm | 4,857 | <p>Overfitting in genetic algorithms and programming is a big issue which is currently under research focus of the GP community, including myself. Most of the research is aimed at genetic programming and evolution of classification/regression models but it might also relate to your problem. There are some papers which might help you (and which I am working with too):</p>
<ul>
<li>Gonçalves, Ivo, and Sara Silva. "Experiments on controlling overfitting in genetic programming." Proceedings of the 15th Portuguese Conference on Artificial Intelligence: Progress in Artificial Intelligence, EPIA. Vol. 84. 2011.</li>
<li>Langdon, W. B. "Minimising testing in genetic programming." RN 11.10 (2011): 1.</li>
<li>Gonçalves, Ivo, et al. "Random sampling technique for overfitting control in genetic programming." Genetic Programming. Springer Berlin Heidelberg, 2012. 218-229.</li>
<li>Gonçalves, Ivo, and Sara Silva. Balancing learning and overfitting in genetic programming with interleaved sampling of training data. Springer Berlin Heidelberg, 2013.</li>
</ul>
<p>You can find the papers (the first two directly in pdf) by searching for their titles in scholar.google.com.</p>
<p>Basically, what all the papers work with, is the idea of using only a subset of the training data for directing the evolution and (randomly) changing this subset every generation (using the same subset for all individuals in one generation). Interestingly, experiments show that the smaller this subset is, the less overfitting occurs, up to the extreme of using only a single-element subset. The papers work with this idea and extend it with some tweaks (like switching between full dataset and a subset). But as I said in the beginning, all this is aimed at symbolic regression (more or less) and not feature selection.</p>
<p>I personally once tried another approach (again for symbolic regression by genetic programming) - using a subset of training data (e.g. a half) to drive the evolution (i.e. for fitness), but the "best-so-far" solution was determined using results on the remaining training data. The overfitting was much less significant.</p> |
438,618 | illegal command error code 127 in php exec function | <p>I am using this php code:</p>
<pre><code>exec("unrar e file.rar",$ret,$code);
</code></pre>
<p>and getting an error code of illegal command ie 127 ... but when I am using this command through ssh its working ... because unrar is installed on the server ... so can anyone guess why exec is not doing the right stuff?</p> | 438,625 | 7 | 3 | null | 2009-01-13 10:58:45.34 UTC | 1 | 2022-08-04 06:29:30.297 UTC | 2011-06-23 17:47:00.227 UTC | null | 454,533 | Intellex | 54,534 | null | 1 | 10 | php|exec | 40,103 | <p>Try using the direct path of the application (/usr/bin/unrar of whatever), it sounds like php can't find the application.</p> |
550,728 | Easiest way to add a text to the beginning of another text file in Command Line (Windows) | <p>What is the easiest way to add a text to the beginning of another text file in Command Line (Windows)?</p> | 550,737 | 7 | 0 | null | 2009-02-15 11:17:30.657 UTC | 6 | 2019-07-15 09:42:47.96 UTC | 2012-11-30 18:15:32.603 UTC | null | 330,315 | Slough | 40,322 | null | 1 | 39 | windows|command-line|text-files | 114,267 | <pre><code>echo "my line" > newFile.txt
type myOriginalFile.txt >> newFile.txt
type newFile.txt > myOriginalFile.txt
</code></pre>
<p>Untested.
Double >> means 'append'</p> |
700,833 | What standards does your team enforce for a major-version code deployment? | <p>I'm curious as to what sort of standards other teams make sure is in place before code ships (or deploys) out the door in major releases.</p>
<p>I'm not looking for specific answers to each, but here's an idea of what I'm trying to get an idea of.</p>
<ul>
<li>For server-based apps, do you ensure monitoring is in place? To what degree...just that it responds to ping, that it can hit all of its dependencies at any given moment, that the logic that the app actually services is sound (e.g., a service that calculates 2+2 actually returns "4")</li>
<li>Do you require automated build scripts before code is released? Meaning, any dev can walk onto a new box, yank something from source control, and start developing? Given things like an OS and IDE, of course.</li>
<li>How about automated deployment scripts, for server-based apps?</li>
<li>What level of documentation do you require for a project to be "done?"</li>
<li>Do you make dang sure you have a full-fledged backup plan for all of the major components of the system, if it's server-based?</li>
<li>Do you enforce code quality standards? Think StyleCop for .NET or cyclomatic complexity evaluations.</li>
<li>Unit testing? Integration tests? Performance load testing?</li>
<li>Do you have standards for how your application's error logging is handled? How about error notification?</li>
</ul>
<p>Again, not looking for a line-by-line punchlist of answers to anything above, necessarily. In short, <strong>what non-coding items must a code release have completed before it's officially considered "done" for your team?</strong></p> | 889,638 | 8 | 0 | null | 2009-03-31 13:03:01.207 UTC | 10 | 2009-09-21 06:25:19.05 UTC | 2009-06-01 13:32:43.953 UTC | null | 84,671 | Chris | 1,212 | null | 1 | 11 | standards|release-management | 1,000 | <p>The minimun:</p>
<ol>
<li>unit tests work</li>
<li>integration tests work</li>
<li>deploy on test stage ok</li>
<li>manual short check on test stage</li>
</ol>
<p>Better:</p>
<ol>
<li>unit tests work</li>
<li><a href="http://checkstyle.sourceforge.net/" rel="nofollow noreferrer">checkstyle</a> ok</li>
<li>integration tests work</li>
<li>metrics like <a href="http://jakarta.apache.org/jmeter/" rel="nofollow noreferrer">jmeter</a> and test coverage passed</li>
<li>deploy on test stage ok</li>
<li>some manual tests on test stage</li>
</ol>
<p>finally deploy on production stage</p>
<p>All unit and integration tests work automatically, best on a continuous integration server like <a href="http://cruisecontrol.sourceforge.net/" rel="nofollow noreferrer">CruiseControl</a> done by <a href="http://ant.apache.org/" rel="nofollow noreferrer">ant</a> or <a href="http://maven.apache.org/" rel="nofollow noreferrer">maven</a>. When developing webservices, testing with <a href="http://www.soapui.org/" rel="nofollow noreferrer">soapui</a> works fine. </p>
<p>If a database used, automatic upgrade is done (with <a href="http://www.liquibase.org/" rel="nofollow noreferrer">liquibase</a> for example) before deployment. When external services are used, addidional configuration tests are needed, to ensure URLs are ok (head request from application, database connect, wsdl get, ...).
When developing webpps, a HTML <a href="http://validator.w3.org/" rel="nofollow noreferrer">validation</a> on some pages will be usefull. A manual check of the layout (use <a href="http://browsershots.org/" rel="nofollow noreferrer">browsershots</a> for example) would be usefull.</p>
<p>(All example links for Java development)</p>
<p>And last (but not least): are all acceptance tests still passing? Is the product what the owner wants? Make a live review with him on the test system before going further!</p> |
115,115 | Test Automation with Embedded Hardware | <p><strong>Has anyone had success automating testing directly on embedded hardware?</strong></p>
<p>Specifically, I am thinking of automating a battery of unit tests for hardware layer modules. We need to have greater confidence in our hardware layer code. A lot of our projects use interrupt driven timers, ADCs, serial io, serial SPI devices (flash memory) etc..</p>
<p><strong>Is this even worth the effort?</strong></p>
<p>We typically target:</p>
<p>Processor: 8 or 16 bit microcontrollers (some DSP stuff)<br>
Language: C (sometimes c++). </p> | 115,157 | 9 | 2 | null | 2008-09-22 14:24:16.89 UTC | 21 | 2017-12-12 11:48:08.66 UTC | 2008-09-22 14:46:56.303 UTC | John | 33 | Jeff V | 445,087 | null | 1 | 25 | c++|c|unit-testing|embedded|testing-strategies | 7,813 | <p>Sure. In the automotive industry we use $100,000 custom built testers for each new product to verify the hardware and software are operating correctly.</p>
<p>The developers, however, also build a cheaper (sub $1,000) tester that includes a bunch of USB I/O, A/D, PWM in/out, etc and either use scripting on the workstation, or purpose built HIL/SIL test software such as MxVDev.</p>
<p>Hardware in the Loop (HIL) testing is probably what you mean, and it simply involves some USB hardware I/O connected to the I/O of your device, with software on the computer running tests against it.</p>
<p>Whether it's worth it depends. </p>
<p>In the high reliability industry (airplane, automotive, etc) the customer specifies very extensive hardware testing, so you have to have it just to get the bid.</p>
<p>In the consumer industry, with non complex projects it's usually not worth it.</p>
<p>With any project where there's more than a few programmers involved, though, it's <em>really</em> nice to have a nightly regression test run on the hardware - it's hard to correctly simulate the hardware to the degree needed to satisfy yourself that the software testing is enough.</p>
<p>The testing then shows immediately when a problem has entered the build.</p>
<p>Generally you perform both black box and white box testing - you have diagnostic code running on the device that allows you to spy on signals and memory in the hardware (which might just be a debugger, or might be code you wrote that reacts to messages on a bus, for instance). This would be white box testing where you can see what's happening internally (and even cause some things to happen, such as critical memory errors which can't be tested without introducing the error yourself). </p>
<p>We also run a bunch of 'black box' tests where the diagnostic path is ignored and only the I/O is stimulated/read.</p>
<p>For a much cheaper setup, you can get $100 microcontroller boards with USB and/or ethernet (such as the Atmel UC3 family) which you can connect to your device and run basic testing.</p>
<p>It's especially useful for product maintenance - when the project is done, store a few working boards, the tester, and a complete set of software on CD. When you need to make a modification or debug a problem, it's easy to set it all back up and work on it with some knowledge (after testing) that the major functionality was not affected by your changes.</p>
<p>-Adam</p> |
716,256 | Creating a circularly linked list in C#? | <p>What would be the best way to create a circularly linked list in C#. Should I derive it from the LinkedList< T> collection? I'm planning on creating a simple address book using this Linked List to store my contacts (it's gonna be a suck-y address book, but I don't care cause I'll be the only one to use it). I mainly just want to create the crucially linked list so that I can use it again in other projects.</p>
<p>If you don't think the Linked List is the right way to go let me know which way would be better.</p> | 2,670,199 | 9 | 0 | null | 2009-04-04 01:18:33.593 UTC | 7 | 2020-04-05 14:43:51.18 UTC | 2015-03-19 16:37:32.993 UTC | Lucas Aardvark | 979,293 | Lucas Aardvark | 56,555 | null | 1 | 29 | c#|linked-list|addressbook | 24,806 | <p>As most of these answers don't actually get at the substance of the question, merely the intention, perhaps this will help:</p>
<p>As far as I can tell the only difference between a Linked List and a Circular Linked List is the behavior of iterators upon reaching the end or beginning of a list. A very easy way to support the behavior of a Circular Linked List is to write an extension method for a LinkedListNode that returns the next node in the list or the first one if no such node exists, and similarly for retrieving the previous node or the last one if no such node exists. The following code should accomplish that, although I haven't tested it:</p>
<pre><code>static class CircularLinkedList {
public static LinkedListNode<T> NextOrFirst<T>(this LinkedListNode<T> current)
{
return current.Next ?? current.List.First;
}
public static LinkedListNode<T> PreviousOrLast<T>(this LinkedListNode<T> current)
{
return current.Previous ?? current.List.Last;
}
}
</code></pre>
<p>Now you can just call myNode.NextOrFirst() instead of myNode.Next and you will have all the behavior of a circular linked list. You can still do constant time removals and insert before and after all nodes in the list and the like. If there's some other key bit of a circular linked list I am missing, let me know.</p> |
371,464 | Get Component's Parent Form | <p>I have a non-visual component which manages other visual controls. </p>
<p>I need to have a reference to the form that the component is operating on, but i don't know how to get it.</p>
<p>I am unsure of adding a constructor with the parent specified as control, as i want the component to work by just being dropped into the designer.</p>
<p>The other thought i had was to have a Property of parent as a control, with the default value as 'Me'</p>
<p>any suggestions would be great</p>
<p><strong>Edit:</strong></p>
<p>To clarify, this is a <strong>component</strong>, not a <strong>control</strong>, see here :<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx" rel="noreferrer">ComponentModel.Component</a></p> | 371,829 | 10 | 0 | null | 2008-12-16 14:27:52.15 UTC | 8 | 2016-12-17 12:49:45.003 UTC | 2008-12-16 14:48:41.75 UTC | Andy | 1,500 | Andy | 1,500 | null | 1 | 27 | c#|vb.net|winforms|components | 44,897 | <p>[It is important to understand that the ISite technique below only works at design time. Because ContainerControl is public and gets assigned a value VisualStudio will write initialization code that sets it at run-time. Site is set at run-time, but you can't get ContainerControl from it]</p>
<p><a href="http://www.wiredprairie.us/journal/2004/05/finding_the_component_containe.html" rel="noreferrer">Here's an article</a> that describes how to do it for a non-visual component.</p>
<p>Basically you need to add a property ContainerControl to your component:</p>
<pre><code>public ContainerControl ContainerControl
{
get { return _containerControl; }
set { _containerControl = value; }
}
private ContainerControl _containerControl = null;
</code></pre>
<p>and override the Site property: </p>
<pre><code>public override ISite Site
{
get { return base.Site; }
set
{
base.Site = value;
if (value == null)
{
return;
}
IDesignerHost host = value.GetService(
typeof(IDesignerHost)) as IDesignerHost;
if (host != null)
{
IComponent componentHost = host.RootComponent;
if (componentHost is ContainerControl)
{
ContainerControl = componentHost as ContainerControl;
}
}
}
}
</code></pre>
<p>If you do this, the ContainerControl will be initialized to reference the containing form by the designer. The linked article explains it in more detail.</p>
<p>A good way to see how to do things is to look at the implementation of Types in the .NET Framework that have behaviour similar to what you want with a tool such as Lutz Reflector. In this case, System.Windows.Forms.ErrorProvider is a good example to look at: a Component that needs to know its containing Form.</p> |
184,782 | ASP.NET Session Timeout Testing | <p>I'm a doing some blackbox testing of a ASP.Net website and I need to test different session timeout scenarios. </p>
<p>I'm not sure they fully encapsulated session timeouts. Other then leaving a page open for 20 minutes is there an easier way to force a session timeout?</p> | 375,277 | 10 | 2 | null | 2008-10-08 20:39:59.103 UTC | 11 | 2015-05-23 16:16:07.64 UTC | null | null | null | ctrlShiftBryan | 6,161 | null | 1 | 36 | asp.net|testing|session|timeout | 42,227 | <p><strong>Decrease the timeout</strong></p>
<p>The easiest and most non-intrusive way to test this is probably to just decrease the timeout to a fairly small number, such as 3 or 5 minutes. This way you can pause for a few minutes to simulate a longer pause without worrying about application restarts or special reset code having any affect on your test results.</p>
<p>You can modify the session state timeout in a few locations - globally (in the web.config located in the config folder for the applicable .NET framework version), or just for your application.</p>
<p>To modify the timeout just for your application, you can add the following to your application's web.config:</p>
<pre><code> <system.web>
<sessionState timeout="60" />
...
</code></pre>
<p>Alternatively, you can also modify this same setting for your application through an IIS configuration dialog (I believe you still need to have a web.config defined for your application though, otherwise Edit Configuration will be disabled).</p>
<p>To access this, right-click on your web application in IIS, and navigate to Properties | ASP.NET tab | Edit Configuration | State Management tab | Session timeout (minutes).</p>
<p>Note that you can also manipulate this setting through code - if this is already being done, than the setting in the web.config file will effectively be ignored and you will need to use another technique.</p>
<p><strong>Call Session.Abandon()</strong></p>
<p>A slightly more intrusive technique than setting a low timeout would be to call Session.Abandon(). Be sure to call this from a page separate from your application though, as the session isn't actually ended until all script commands on the current page are processed.</p>
<p>My understanding is that this would be a fairly clean way to test session timeouts without actually waiting for them.</p>
<p><strong>Force an application restart</strong></p>
<p>In a default configuration of session state, you can simulate a session timeout by blowing away the sessions entirely by causing the application to restart. This can be done several ways, a few of which are listed below:</p>
<ul>
<li>Recycle the app pool through
<ul>
<li>the IIS MMC snap-in</li>
<li>the command-line (iisapp /a AppPoolID /r)</li>
<li>modifying web.config, global.asax, or a dll in the bin directory</li>
</ul></li>
<li>Restart IIS through
<ul>
<li>the IIS MMC snap-in</li>
<li>services.msc and restarting the IIS Admin service</li>
<li>the command-line (iisreset)</li>
</ul></li>
</ul>
<p>When I mention "default configuration", I mean a web application that is configured to use "InProc" session state mode. There are others modes that can actually maintain session state even if the web application is restarted (StateServer, SQLServer, Custom).</p>
<p><strong>Tamper with the state tracking mechanism</strong></p>
<p>Assuming your web application isn't configured with a "cookie-less" mode (by default, cookies will be used), you could remove the cookie containing the session ID from the client browser.</p>
<p>However, my understanding is that this isn't really simulating a time-out, as the server will still be aware of the session, it just won't see anyone using it. The request without a session ID will simply be treated as an unseen request in need of a new session, which may or may not be what you want to test.</p> |
726,122 | Best ways of parsing a URL using C? | <p>I have a URL like this:</p>
<pre><code>http://192.168.0.1:8080/servlet/rece
</code></pre>
<p>I want to parse the URL to get the values:</p>
<pre><code>IP: 192.168.0.1
Port: 8080
page: /servlet/rece
</code></pre>
<p>How do I do that?</p> | 726,168 | 10 | 1 | null | 2009-04-07 14:47:18.083 UTC | 16 | 2020-09-09 12:14:24.11 UTC | 2009-04-07 14:48:38.363 UTC | null | 1,060 | null | 84,508 | null | 1 | 38 | c|url|parsing | 62,980 | <p>Write a custom parser or use one of the string replace functions to replace the separator ':' and then use <code>sscanf()</code>.</p> |
819,336 | How to Preload Images without Javascript? | <p>On one of my HTML pages there are some large images that are shown when I mouse hover over some links and it takes time to load those images.</p>
<p>I don't want to use JavaScript to preload images. Are there any good solutions?</p> | 819,788 | 10 | 3 | null | 2009-05-04 08:55:17.837 UTC | 18 | 2022-05-12 11:10:00.467 UTC | 2022-05-12 11:07:28.073 UTC | null | 74,089 | null | 88,493 | null | 1 | 41 | html|image-preloader|link-prefetch | 67,785 | <p>From <a href="http://snipplr.com/view/2122/css-image-preloader" rel="noreferrer">http://snipplr.com/view/2122/css-image-preloader</a></p>
<blockquote>
<p>A low-tech but useful technique that uses only CSS. After placing the css in your stylesheet, insert this just below the body tag of your page: Whenever the images are referenced throughout your pages they will now be loaded from cache.</p>
</blockquote>
<pre><code>#preloadedImages
{
width: 0px;
height: 0px;
display: inline;
background-image: url(path/to/image1.png);
background-image: url(path/to/image2.png);
background-image: url(path/to/image3.png);
background-image: url(path/to/image4.png);
background-image: url();
}
</code></pre> |
77,694 | How to quickly theme a view? | <p>I've defined a view with the CCK and View 2 modules. I would like to quickly define a template specific to this view. Is there any tutorial or information on this? What are the files I need to modify?</p>
<hr>
<p><strong>Here are my findings: (Edited)</strong></p>
<p>In fact, there are two ways to theme a view: the "<strong>field</strong>" way and the "<strong>node</strong>" way. In "edit View", you can choose "<code>Row style: Node</code>", or "<code>Row style: Fields</code>".</p>
<ul>
<li>with the "<strong>Node</strong>" way, you can create a <strong>node-contentname.tpl.php</strong> which will be called for each node in the view. You'll have access to your cck field values with $field_name[0]['value']. (edit2) You can use <strong>node-view-viewname.tpl.php</strong> which will be only called for each node displayed from this view.</li>
<li>with the "<strong>Field</strong>" way, you add a views-view-field--viewname--field-name-value.tpl.php for each field you want to theme individually.</li>
</ul>
<p>Thanks to previous responses, I've used the following tools :</p>
<ul>
<li>In the 'Basic Settings' block, the 'Theme: Information' to see all the different templates you can modify.</li>
<li>The <a href="http://drupal.org/project/devel" rel="nofollow noreferrer">Devel module</a>'s "Theme developer" to quickly find the field variable names.</li>
<li><a href="http://views-help.doc.logrus.com/" rel="nofollow noreferrer">View 2 documentation</a>, especially the <a href="http://views-help.doc.logrus.com/help/views/using-theme" rel="nofollow noreferrer">"Using Theme"</a> page.</li>
</ul> | 78,158 | 10 | 3 | null | 2008-09-16 22:02:57.703 UTC | 35 | 2019-02-19 02:13:10.873 UTC | 2019-02-19 02:13:10.873 UTC | Pierre-Jean Coudert | 10,370,537 | Pierre-Jean Coudert | 8,450 | null | 1 | 85 | drupal|drupal-views|cck|drupal-theming | 91,669 | <p>In fact there are two ways to theme a view : the "<strong>field</strong>" way and the "<strong>node</strong>" way. In "edit View", you can choose "<code>Row style: Node</code>", or "<code>Row style: Fields</code>".</p>
<ul>
<li>with the "<strong>Node</strong>" way, you can create a node-contentname.tpl.php wich will be called for each node in the view. You'll have access to your cck field values with $field_name[0]['value']</li>
<li>with the "<strong>Field</strong>" way, you add a views-view-field--viewname--field-name-value.tpl.php for each field you want to theme individually.</li>
</ul>
<p>Thanks to previous responses, I've used the following tools :</p>
<ul>
<li>In the 'Basic Settings' block, the 'Theme: Information' to see all the different templates you can modify.</li>
<li>The <a href="http://drupal.org/project/devel" rel="noreferrer">Devel module</a>'s "Theme developer" to quickly find the field variable names.</li>
<li><a href="http://views-help.doc.logrus.com/" rel="noreferrer">View 2 documentation</a>, especially the <a href="http://views-help.doc.logrus.com/help/views/using-theme" rel="noreferrer">"Using Theme"</a> page.</li>
</ul> |
234,458 | Do polymorphism or conditionals promote better design? | <p>I recently stumbled across <a href="http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-decided-to.html" rel="noreferrer">this entry in the google testing blog</a> about guidelines for writing more testable code. I was in agreement with the author until this point:</p>
<blockquote>
<p>Favor polymorphism over conditionals: If you see a switch statement you should think polymorphisms. If you see the same if condition repeated in many places in your class you should again think polymorphism. Polymorphism will break your complex class into several smaller simpler classes which clearly define which pieces of the code are related and execute together. This helps testing since simpler/smaller class is easier to test.</p>
</blockquote>
<p>I simply cannot wrap my head around that. I can understand using polymorphism instead of RTTI (or DIY-RTTI, as the case may be), but that seems like such a broad statement that I can't imagine it actually being used effectively in production code. It seems to me, rather, that it would be easier to add additional test cases for methods which have switch statements, rather than breaking down the code into dozens of separate classes.</p>
<p>Also, I was under the impression that polymorphism can lead to all sorts of other subtle bugs and design issues, so I'm curious to know if the tradeoff here would be worth it. Can someone explain to me exactly what is meant by this testing guideline?</p> | 234,491 | 12 | 0 | null | 2008-10-24 17:19:46.617 UTC | 27 | 2013-03-13 15:49:58.697 UTC | 2010-09-30 13:23:47.89 UTC | null | 14,302 | sqook | 14,302 | null | 1 | 39 | c++|oop|tdd|polymorphism | 14,019 | <p>Actually this makes testing and code easier to write.</p>
<p>If you have one switch statement based on an internal field you probably have the same switch in multiple places doing slightly different things. This causes problems when you add a new case as you have to update all the switch statements (if you can find them).</p>
<p>By using polymorphism you can use virtual functions to get the same functionality and because a new case is a new class you don't have to search your code for things that need to be checked it is all isolated for each class.</p>
<pre><code>class Animal
{
public:
Noise warningNoise();
Noise pleasureNoise();
private:
AnimalType type;
};
Noise Animal::warningNoise()
{
switch(type)
{
case Cat: return Hiss;
case Dog: return Bark;
}
}
Noise Animal::pleasureNoise()
{
switch(type)
{
case Cat: return Purr;
case Dog: return Bark;
}
}
</code></pre>
<p>In this simple case every new animal causes requires both switch statements to be updated.<br>
You forget one? What is the default? BANG!!</p>
<p>Using polymorphism </p>
<pre><code>class Animal
{
public:
virtual Noise warningNoise() = 0;
virtual Noise pleasureNoise() = 0;
};
class Cat: public Animal
{
// Compiler forces you to define both method.
// Otherwise you can't have a Cat object
// All code local to the cat belongs to the cat.
};
</code></pre>
<p>By using polymorphism you can test the Animal class.<br>
Then test each of the derived classes separately.</p>
<p>Also this allows you to ship the Animal class (<strong>Closed for alteration</strong>) as part of you binary library. But people can still add new Animals (<strong>Open for extension</strong>) by deriving new classes derived from the Animal header. If all this functionality had been captured inside the Animal class then all animals need to be defined before shipping (Closed/Closed).</p> |
234,341 | Should I always make my java-code thread-safe, or for performance-reasons do it only when needed? | <p>If I create classes, that are used at the moment only in a single thread, should I make them thread-safe, even if I don't need that at the moment? It could be happen, that I later use this class in multiple threads, and at that time I could get race conditions and may have a hard time to find them if I didn't made the class thread-safe in the first place. Or should I make the class not thread-safe, for better performance? But premature optimization is evil.</p>
<p>Differently asked: Should I make my classes thread-safe if needed (if used in multiple threads, otherwise not) or should I optimize this issue then needed (if I see that the synchronization eats up an important part of processing time)?</p>
<p>If I choose one of the both ways, are there methods to reduce the disadvantages? Or exists a third possibility, that I should use?</p>
<p><strong>EDIT</strong>: I give the reason this question came up to my mind. At our company we have written a very simple user-management that writes the data into property-files. I used it in a web-app and after some work on it I got strange errors, that the user-management forgot about properties of users(including name and password) and roles. That was very annoying but not consistently reproducible, so I think it was race condition. Since I synchronized all methods reading and writing from/on disk, the problem disappeared. So I thought, that I probably could have been avoided all the hassle, if we had written the class with synchronization in the first place?</p>
<p><strong>EDIT 2</strong>: As I look over the tips of Pragmatic Programmer, I saw tip #41: Always Design for Concurrency. This doesn't say that all code should be thread-safe, but it says the design should have the concurrency in mind.</p> | 235,903 | 13 | 1 | null | 2008-10-24 16:49:34.29 UTC | 9 | 2012-03-08 06:43:34.363 UTC | 2011-08-08 19:24:53.28 UTC | Mnementh | 7,671 | Mnementh | 21,005 | null | 1 | 28 | java|multithreading|performance|concurrency|thread-safety | 5,533 | <p>Start from the data. Decide which data is explicitly shared and protect it. If at all possible, encapsulate the locking with the data. Use pre-existing thread-safe concurrent collections.</p>
<p>Whenever possible, use immutable objects. Make attributes final, set their values in the constructors. If you need to "change" the data consider returning a new instance. Immutable objects don't need locking. </p>
<p>For objects that are not shared or thread-confined, do not spend time making them thread-safe. </p>
<p>Document the expectations in the code. The JCIP annotations are the best pre-defined choice available. </p> |
264,962 | How to search a string in String array | <p>I need to search a string in the string array. I dont want to use any for looping in it</p>
<pre><code>string [] arr = {"One","Two","Three"};
string theString = "One"
</code></pre>
<p>I need to check whether theString variable is present in arr.</p> | 265,181 | 15 | 0 | null | 2008-11-05 12:12:19.777 UTC | 12 | 2020-07-26 19:53:53.927 UTC | 2019-04-09 11:56:12.317 UTC | balaweblog | 2,584,786 | balaweblog | 22,162 | null | 1 | 83 | c#|asp.net | 402,884 | <p>Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string</p>
<pre><code> string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
</code></pre> |
619,856 | Interface defining a constructor signature? | <p>It's weird that this is the first time I've bumped into this problem, but:</p>
<p>How do you define a constructor in a C# interface?</p>
<p><strong>Edit</strong><br>
Some people wanted an example (it's a free time project, so yes, it's a game)</p>
<p>IDrawable<br>
+Update<br>
+Draw</p>
<p>To be able to Update (check for edge of screen etc) and draw itself it will always need a <code>GraphicsDeviceManager</code>. So I want to make sure the object has a reference to it. This would belong in the constructor.</p>
<p>Now that I wrote this down I think what I'm implementing here is <code>IObservable</code> and the <code>GraphicsDeviceManager</code> should take the <code>IDrawable</code>...
It seems either I don't get the XNA framework, or the framework is not thought out very well.</p>
<p><strong>Edit</strong><br>
There seems to be some confusion about my definition of constructor in the context of an interface. An interface can indeed not be instantiated so doesn't need a constructor. What I wanted to define was a signature to a constructor. Exactly like an interface can define a signature of a certain method, the interface could define the signature of a constructor.</p> | 41,685,659 | 16 | 1 | null | 2009-03-06 18:13:27.02 UTC | 74 | 2020-10-23 10:22:07.943 UTC | 2012-07-14 19:52:03.21 UTC | boris callens | 389,966 | boris callens | 11,333 | null | 1 | 614 | c#|interface|constructor | 393,134 | <p>As already well noted, you can't have constructors on an Interface. But since this is such a highly ranked result in Google some 7 years later, I thought I would chip in here - specifically to show how you could use an abstract base class in tandem with your existing Interface and maybe cut down on the amount of refactoring needed in the future for similar situations. This concept has already been hinted at in some of the comments but I thought it would be worth showing how to actually do it.</p>
<p>So you have your main interface that looks like this so far:</p>
<pre><code>public interface IDrawable
{
void Update();
void Draw();
}
</code></pre>
<p>Now create an abstract class with the constructor you want to enforce. Actually, since it's now available since the time you wrote your original question, we can get a little fancy here and use generics in this situation so that we can adapt this to other interfaces that might need the same functionality but have different constructor requirements:</p>
<pre><code>public abstract class MustInitialize<T>
{
public MustInitialize(T parameters)
{
}
}
</code></pre>
<p>Now you'll need to create a new class that inherits from both the IDrawable interface and the MustInitialize abstract class:</p>
<pre><code>public class Drawable : MustInitialize<GraphicsDeviceManager>, IDrawable
{
GraphicsDeviceManager _graphicsDeviceManager;
public Drawable(GraphicsDeviceManager graphicsDeviceManager)
: base (graphicsDeviceManager)
{
_graphicsDeviceManager = graphicsDeviceManager;
}
public void Update()
{
//use _graphicsDeviceManager here to do whatever
}
public void Draw()
{
//use _graphicsDeviceManager here to do whatever
}
}
</code></pre>
<p>Then just create an instance of Drawable and you're good to go:</p>
<pre><code>IDrawable drawableService = new Drawable(myGraphicsDeviceManager);
</code></pre>
<p>The cool thing here is that the new Drawable class we created still behaves just like what we would expect from an IDrawable.</p>
<p>If you need to pass more than one parameter to the MustInitialize constructor, you can create a class that defines properties for all of the fields you'll need to pass in.</p> |
1,188,129 | Replace URLs in text with HTML links | <p>Here is a design though: For example is I put a link such as</p>
<blockquote>
<p><a href="http://example.com" rel="noreferrer">http://example.com</a></p>
</blockquote>
<p>in <strong>textarea</strong>. How do I get PHP to detect it’s a <code>http://</code> link and then print it as</p>
<pre><code>print "<a href='http://www.example.com'>http://www.example.com</a>";
</code></pre>
<p><em>I remember doing something like this before however, it was not fool proof it kept breaking for complex links.</em></p>
<p>Another good idea would be if you have a link such as</p>
<blockquote>
<p><a href="http://example.com/test.php?val1=bla&val2blablabla%20bla%20bla.bl" rel="noreferrer">http://example.com/test.php?val1=bla&val2blablabla%20bla%20bla.bl</a></p>
</blockquote>
<p>fix it so it does</p>
<pre><code>print "<a href='http://example.com/test.php?val1=bla&val2=bla%20bla%20bla.bla'>";
print "http://example.com/test.php";
print "</a>";
</code></pre>
<p>This one is just an after thought.. stackoverflow could also probably use this as well :D</p>
<p>Any Ideas</p> | 1,188,652 | 17 | 1 | null | 2009-07-27 13:20:41.65 UTC | 39 | 2020-07-30 00:17:01.343 UTC | 2014-11-09 23:16:50.79 UTC | null | 1,091,442 | null | 109,815 | null | 1 | 57 | php|regex|url|preg-replace|linkify | 70,540 | <p>Let's look at the requirements. You have some user-supplied plain text, which you want to display with hyperlinked URLs.</p>
<ol>
<li>The "http://" protocol prefix should be optional.</li>
<li>Both domains and IP addresses should be accepted.</li>
<li>Any valid top-level domain should be accepted, e.g. .aero and .xn--jxalpdlp.</li>
<li>Port numbers should be allowed.</li>
<li>URLs must be allowed in normal sentence contexts. For instance, in "Visit stackoverflow.com.", the final period is not part of the URL.</li>
<li>You probably want to allow "https://" URLs as well, and perhaps others as well.</li>
<li>As always when displaying user supplied text in HTML, you want to prevent <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="nofollow noreferrer">cross-site scripting</a> (XSS). Also, you'll want ampersands in URLs to be <a href="http://www.htmlhelp.com/tools/validator/problems.html#amp" rel="nofollow noreferrer">correctly escaped</a> as &amp;.</li>
<li>You probably don't need support for IPv6 addresses.</li>
<li><strong>Edit</strong>: As noted in the comments, support for email-adresses is definitely a plus.</li>
<li><strong>Edit</strong>: Only plain text input is to be supported – HTML tags in the input should not be honoured. (The Bitbucket version supports HTML input.)</li>
</ol>
<p><strong>Edit</strong>: Check out <a href="https://github.com/kwi-dk/UrlLinker" rel="nofollow noreferrer">GitHub</a> for the latest version, with support for email addresses, authenticated URLs, URLs in quotes and parentheses, HTML input, as well as an updated TLD list.</p>
<p>Here's my take:</p>
<pre><code><?php
$text = <<<EOD
Here are some URLs:
stackoverflow.com/questions/1188129/pregreplace-to-detect-html-php
Here's the answer: http://www.google.com/search?rls=en&q=42&ie=utf-8&oe=utf-8&hl=en. What was the question?
A quick look at http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax is helpful.
There is no place like 127.0.0.1! Except maybe http://news.bbc.co.uk/1/hi/england/surrey/8168892.stm?
Ports: 192.168.0.1:8080, https://example.net:1234/.
Beware of Greeks bringing internationalized top-level domains: xn--hxajbheg2az3al.xn--jxalpdlp.
And remember.Nobody is perfect.
<script>alert('Remember kids: Say no to XSS-attacks! Always HTML escape untrusted input!');</script>
EOD;
$rexProtocol = '(https?://)?';
$rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
$rexPort = '(:[0-9]{1,5})?';
$rexPath = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
// Solution 1:
function callback($match)
{
// Prepend http:// if no protocol specified
$completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
return '<a href="' . $completeUrl . '">'
. $match[2] . $match[3] . $match[4] . '</a>';
}
print "<pre>";
print preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&",
'callback', htmlspecialchars($text));
print "</pre>";
</code></pre>
<ul>
<li>To properly escape < and & characters, I throw the whole text through htmlspecialchars before processing. This is not ideal, as the html escaping can cause misdetection of URL boundaries.</li>
<li>As demonstrated by the "And remember.Nobody is perfect." line (in which remember.Nobody is treated as an URL, because of the missing space), further checking on valid top-level domains might be in order.</li>
</ul>
<p><strong>Edit</strong>: The following code fixes the above two problems, but is quite a bit more verbose since I'm more or less re-implementing <code>preg_replace_callback</code> using <code>preg_match</code>.</p>
<pre><code>// Solution 2:
$validTlds = array_fill_keys(explode(" ", ".aero .asia .biz .cat .com .coop .edu .gov .info .int .jobs .mil .mobi .museum .name .net .org .pro .tel .travel .ac .ad .ae .af .ag .ai .al .am .an .ao .aq .ar .as .at .au .aw .ax .az .ba .bb .bd .be .bf .bg .bh .bi .bj .bm .bn .bo .br .bs .bt .bv .bw .by .bz .ca .cc .cd .cf .cg .ch .ci .ck .cl .cm .cn .co .cr .cu .cv .cx .cy .cz .de .dj .dk .dm .do .dz .ec .ee .eg .er .es .et .eu .fi .fj .fk .fm .fo .fr .ga .gb .gd .ge .gf .gg .gh .gi .gl .gm .gn .gp .gq .gr .gs .gt .gu .gw .gy .hk .hm .hn .hr .ht .hu .id .ie .il .im .in .io .iq .ir .is .it .je .jm .jo .jp .ke .kg .kh .ki .km .kn .kp .kr .kw .ky .kz .la .lb .lc .li .lk .lr .ls .lt .lu .lv .ly .ma .mc .md .me .mg .mh .mk .ml .mm .mn .mo .mp .mq .mr .ms .mt .mu .mv .mw .mx .my .mz .na .nc .ne .nf .ng .ni .nl .no .np .nr .nu .nz .om .pa .pe .pf .pg .ph .pk .pl .pm .pn .pr .ps .pt .pw .py .qa .re .ro .rs .ru .rw .sa .sb .sc .sd .se .sg .sh .si .sj .sk .sl .sm .sn .so .sr .st .su .sv .sy .sz .tc .td .tf .tg .th .tj .tk .tl .tm .tn .to .tp .tr .tt .tv .tw .tz .ua .ug .uk .us .uy .uz .va .vc .ve .vg .vi .vn .vu .wf .ws .ye .yt .yu .za .zm .zw .xn--0zwm56d .xn--11b5bs3a9aj6g .xn--80akhbyknj4f .xn--9t4b11yi5a .xn--deba0ad .xn--g6w251d .xn--hgbk6aj7f53bba .xn--hlcj6aya9esc7a .xn--jxalpdlp .xn--kgbechtv .xn--zckzah .arpa"), true);
$position = 0;
while (preg_match("{\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))}", $text, &$match, PREG_OFFSET_CAPTURE, $position))
{
list($url, $urlPosition) = $match[0];
// Print the text leading up to the URL.
print(htmlspecialchars(substr($text, $position, $urlPosition - $position)));
$domain = $match[2][0];
$port = $match[3][0];
$path = $match[4][0];
// Check if the TLD is valid - or that $domain is an IP address.
$tld = strtolower(strrchr($domain, '.'));
if (preg_match('{\.[0-9]{1,3}}', $tld) || isset($validTlds[$tld]))
{
// Prepend http:// if no protocol specified
$completeUrl = $match[1][0] ? $url : "http://$url";
// Print the hyperlink.
printf('<a href="%s">%s</a>', htmlspecialchars($completeUrl), htmlspecialchars("$domain$port$path"));
}
else
{
// Not a valid URL.
print(htmlspecialchars($url));
}
// Continue text parsing from after the URL.
$position = $urlPosition + strlen($url);
}
// Print the remainder of the text.
print(htmlspecialchars(substr($text, $position)));
</code></pre> |
478,722 | What is the best way to calculate a checksum for a file that is on my machine? | <p>I'm on a Windows machine and I want to run a checksum on the MySQL distribution I just got. It looks like there are products to download, an unsupported Microsoft tool, and probably other options. I'm wondering if there is a consensus for the best tool to use. This may be a really easy question, I've just never run a checksum routine before.</p> | 478,728 | 20 | 1 | null | 2009-01-26 02:48:35.053 UTC | 50 | 2021-01-13 13:59:52.793 UTC | null | null | null | Bialecki | 2,484 | null | 1 | 89 | windows|checksum | 225,389 | <p>Any MD5 will produce a good checksum to verify the file. Any of the files listed at the bottom of this page will work fine. <a href="http://en.wikipedia.org/wiki/Md5sum" rel="noreferrer">http://en.wikipedia.org/wiki/Md5sum</a></p> |
34,447,827 | Valid usage of Optional type in Java 8 | <p>Is this a valid (intended) usage of Optional type in Java 8?</p>
<pre><code>String process(String s) {
return Optional.ofNullable(s).orElseGet(this::getDefault);
}
</code></pre> | 34,458,582 | 4 | 12 | null | 2015-12-24 05:40:30.333 UTC | 9 | 2019-01-20 01:27:00.283 UTC | 2019-01-20 01:27:00.283 UTC | null | 1,298,028 | null | 1,298,028 | null | 1 | 11 | java|functional-programming|java-8|monads|option-type | 2,873 | <p>I'll take another swing at this.</p>
<p>Is this a valid usage? Yes, in the narrow sense that it compiles and produces the results that you're expecting.</p>
<p>Is this intended usage? No. Now, sometimes things find usefulness beyond what they were originally for, and if this works out, great. But for <code>Optional</code>, we have found that usually things don't work out very well.</p>
<p><a href="https://stackoverflow.com/users/3553087/brian-goetz">Brian Goetz</a> and I discussed some of the issues with <code>Optional</code> in our JavaOne 2015 talk, <em>API Design With Java 8 Lambdas and Streams</em>:</p>
<ul>
<li><a href="https://youtu.be/MFzlgAuanU0" rel="noreferrer">link to video</a></li>
<li><a href="https://stuartmarks.files.wordpress.com/2015/10/con6851-api-design-v2.pdf" rel="noreferrer">link to slides</a></li>
</ul>
<p>The primary use of <code>Optional</code> is as follows: (slide 36)</p>
<blockquote>
<p>Optional is intended to provide a <em>limited</em> mechanism for library method <em>return types</em> where there is a clear need to represent "no result," and where using <code>null</code> for that is overwhelmingly <em>likely to cause errors</em>.</p>
</blockquote>
<p>The ability to chain methods from an <code>Optional</code> is undoubtedly very cool, and in some cases it reduces the clutter from conditional logic. But quite often this doesn't work out. A typical code smell is, instead of the code using method chaining to <em>handle</em> an <code>Optional</code> returned from some method, it <em>creates</em> an <code>Optional</code> from something that's nullable, in order to chain methods and avoid conditionals. Here's an example of that in action (also from our presentation, slide 42):</p>
<pre><code>// BAD
String process(String s) {
return Optional.ofNullable(s).orElseGet(this::getDefault);
}
// GOOD
String process(String s) {
return (s != null) ? s : getDefault();
}
</code></pre>
<p>The method that uses <code>Optional</code> is longer, and most people find it more obscure than the conventional code. Not only that, it creates extra garbage for no good reason.</p>
<p>Bottom line: just because you <em>can</em> do something doesn't mean that you <em>should</em> do it.</p> |
6,345,840 | What's the best way to initialise and use constants across Python classes? | <p>Here's how I am declaring constants and using them across different Python classes:</p>
<pre><code># project/constants.py
GOOD = 1
BAD = 2
AWFUL = 3
# project/question.py
from constants import AWFUL, BAD, GOOD
class Question:
def __init__(self):
...
</code></pre>
<p>Is the above a good way to store and use contant values? I realise that after a while, the constants file can get pretty big and I could explicitly be importing 10+ of those constants in any given file.</p> | 6,345,909 | 4 | 2 | null | 2011-06-14 15:13:00.05 UTC | 6 | 2018-10-16 19:43:42.687 UTC | 2018-10-16 19:43:42.687 UTC | null | 117,642 | null | 117,642 | null | 1 | 59 | python | 63,543 | <p>why not just use</p>
<pre><code>import constants
def use_my_constants():
print constants.GOOD, constants.BAD, constants.AWFUL
</code></pre>
<p>From the python zen:</p>
<blockquote>
<p>Namespaces are good. Lets do more of those!</p>
</blockquote>
<p><strong>EDIT:</strong> Except, when you do quote, you should include a reference and check it, because as others have pointed out, it should read:</p>
<blockquote>
<p>Namespaces are one honking great idea -- let's do more of those!</p>
</blockquote>
<p>This time, I actually copied it from the source: <a href="http://www.python.org/dev/peps/pep-0020/">PEP 20 -- The Zen of Python</a></p> |
6,993,365 | Convert string Date into timestamp in Android? | <p>I want to convert my date (which is in String format), e.g. 13-09-2011, into Timestamp. I used below code but I got the 2011-09-13 00:00:00.0
as a result. But I want Timestamp like,1312828200000 format.</p>
<p>I cannot understand how to convert that.</p>
<p>My code:</p>
<pre><code>String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " +timeStampDate);
</code></pre> | 6,993,420 | 6 | 1 | null | 2011-08-09 08:30:42.133 UTC | 7 | 2021-09-17 13:25:03.47 UTC | 2017-10-02 19:43:56.443 UTC | null | 3,885,376 | null | 872,475 | null | 1 | 33 | android|timestamp | 65,084 | <p>If you use <code>getTime()</code> of <code>Date</code> object you will get time in millisecond.
No need to use <code>Timestamp</code> to get your result. </p>
<pre><code>String str_date="13-09-2011";
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = (Date)formatter.parse(str_date);
System.out.println("Today is " +date.getTime());
</code></pre>
<p>The above code will print something like <code>1312828200000</code> you need and this is long value.</p> |
6,411,397 | How to check iOS app size before upload | <p>I would like to be able to check the size of my app before submitting to the app store. More specifically I need to know whether it will be below the magic 20 MB, to allow cellular downloads, since the app is created for a festival.</p> | 6,411,466 | 9 | 2 | null | 2011-06-20 12:50:16.55 UTC | 5 | 2019-09-15 00:39:43.21 UTC | 2011-06-20 12:51:28.72 UTC | null | 41,761 | null | 625,481 | null | 1 | 50 | iphone|ios|xcode|3g | 35,215 | <p>The install file downloaded from the App Store will vary based on the device and what thinning is done to your app. An ad hoc distribution .ipa file will give an estimate of how big the install file from the App Store will be. Archive your app in Xcode, then make an ad hoc distribution. If you turn off app thinning while making this file you'll see the biggest your install file could be. If you turn on app thinning and generate all the variations of .ipa files you'll see all the different install file sizes. </p>
<p>To see an even more accurate answer to this question, submit your app to TestFlight. In the TestFlight app on your devices you can see the size of the app by checking the app details. Check it on multiple devices, it will vary if the app thinning process considers your devices sufficiently different and uses different assets from your app archive. </p>
<p>Below is my original answer:</p>
<p>In Xcode 4: Once your app is ready for distribution, archive the app. In the Organizer, select the Archives tab. Select your app in the left hand column. Select the latest archive in the right hand column. Hit the Share... button in the top section. Save the file as an .ipa. Check file size in the Finder.</p> |
6,355,096 | How to create EditText with cross(x) button at end of it? | <p>Is there any widget like <code>EditText</code> which contains a cross button, or is there any property for <code>EditText</code> by which it is created automatically? I want the cross button to delete whatever text written in <code>EditText</code>.</p> | 6,355,178 | 17 | 3 | null | 2011-06-15 08:40:20.543 UTC | 67 | 2021-10-08 02:44:00.897 UTC | 2013-10-24 16:55:47.197 UTC | null | 1,713,149 | null | 731,284 | null | 1 | 236 | android|android-edittext | 188,861 | <p>Use the following layout:</p>
<pre><code><FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="9dp"
android:padding="5dp">
<EditText
android:id="@+id/calc_txt_Prise"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:layout_marginTop="20dp"
android:textSize="25dp"
android:textColor="@color/gray"
android:textStyle="bold"
android:hint="@string/calc_txt_Prise"
android:singleLine="true" />
<Button
android:id="@+id/calc_clear_txt_Prise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_gravity="right|center_vertical"
android:background="@drawable/delete" />
</FrameLayout>
</code></pre>
<p>You can also use the button's id and perform whatever action you want on its onClickListener method.</p> |
45,465,016 | How do I get the active window on Gnome Wayland? | <p><strong>Background:</strong> I'm working on a piece of software called <a href="https://github.com/ActivityWatch/activitywatch" rel="noreferrer">ActivityWatch</a> that logs what you do on your computer. Basically an attempt at addressing some of the issues with: RescueTime, selfspy, arbtt, etc. </p>
<p>One of the core things we do is log information about the active window (class and title). In the past, this has been done using on Linux using xprop and now python-xlib without issue.</p>
<p><strong>But now we have a problem:</strong> Wayland is on the rise, and as far as I can see Wayland has no notion of an active window. So my fear is that we will have to implement support for each and every desktop environment available for Wayland (assuming they'll provide the capability to get information about the active window at all). </p>
<p>Hopefully they'll eventually converge and have some common interface to get this done, but I'm not holding my breath...</p>
<p>I've been <a href="https://github.com/ActivityWatch/aw-watcher-window/issues/18" rel="noreferrer">anticipating this issue</a>. But today we got our <a href="https://github.com/ActivityWatch/activitywatch/issues/92" rel="noreferrer">first user request for Wayland support</a> by an actual Wayland user. As larger distros are adopting Wayland as the default display server protocol (Fedora 25 is already using it, Ubuntu will switch in 17.10 which is coming soon) the situation is going to get more critical over time.</p>
<p>Relevant issues for ActivityWatch:</p>
<ul>
<li><a href="https://github.com/ActivityWatch/aw-watcher-window/issues/18" rel="noreferrer">https://github.com/ActivityWatch/aw-watcher-window/issues/18</a></li>
<li><a href="https://github.com/ActivityWatch/activitywatch/issues/92" rel="noreferrer">https://github.com/ActivityWatch/activitywatch/issues/92</a></li>
</ul>
<p>There are other applications like ActivityWatch that would require the same functionality (RescueTime, arbtt, selfspy, etc.), they don't seem to support Wayland right now and I can't find any details about them planning to do so.</p>
<p><strong>I'm now interested in implementing support for Gnome to start off with</strong> and follow up with others as the path becomes more clear.</p>
<p>A similar question concerning Weston has been asked here: <a href="https://stackoverflow.com/questions/26802683/get-the-list-of-active-windows-in-wayland-weston?rq=1">get the list of active windows in wayland weston</a></p>
<p><strong>Edit:</strong> I asked in #wayland on Freenode, got the following reply:</p>
<pre class="lang-none prettyprint-override"><code>15:20:44 ErikBjare Hello everybody. I'm working on a piece of self-tracking software called ActivityWatch (https://github.com/ActivityWatch/activitywatch). I know this isn't exactly the right place to ask, but I was wondering if anyone knew anything about getting the active window in any Wayland-using DE.
15:20:57 ErikBjare Created a question on SO: https://stackoverflow.com/questions/45465016/how-do-i-get-the-active-window-on-gnome-wayland
15:21:25 ErikBjare Here's the issue in my repo for it: https://github.com/ActivityWatch/activitywatch/issues/92
15:22:54 ErikBjare There are a bunch of other applications that depend on it (RescueTime, selfspy, arbtt, ulogme, etc.) so they'd need it as well
15:24:23 blocage ErikBjare, in the core protocol you cannot know which windnow has the keyboard or cursor focus
15:24:39 blocage ErikBjare, in the wayland core protocol *
15:25:10 blocage ErikBjare, you can just know if your window has the focus or not, it a design choise
15:25:23 blocage avoid client spying each other
15:25:25 ErikBjare blocage: I'm aware, that's my reason for concern. I'm not saying it should be included or anything, but as it looks now every DE would need to implement it themselves if these kind of applications are to be supported
15:25:46 ErikBjare So wondering if anyone knew the teams working with Wayland on Gnome for example
15:26:11 ErikBjare But thanks for confirming
15:26:29 blocage ErikBjare, DE should create a custom extension, or use D-bus or other IPC
15:27:31 blocage ErikBjare, I guess some compositor are around here, but I do not know myself if there is such extension already
15:27:44 blocage compositor developers *
15:28:36 ErikBjare I don't think there is (I've done quite a bit of searching), so I guess I need to catch the attention of some DE developers
15:29:16 ErikBjare Thanks a lot though
15:29:42 ErikBjare blocage: Would you mind if I shared logs of our conversation in the issue?
15:30:05 blocage just use it :) it's public
15:30:19 ErikBjare ty :)
</code></pre>
<p><strong>Edit 2:</strong> Filed an <a href="https://bugzilla.gnome.org/show_bug.cgi?id=788511" rel="noreferrer">enhancement issue in the Gnome bugtracker</a>.</p>
<p><strong>tl;dr:</strong> How do I get the active window on Gnome when using Wayland?</p> | 64,030,239 | 3 | 6 | null | 2017-08-02 15:28:07.98 UTC | 14 | 2020-09-24 09:49:06.787 UTC | 2017-10-04 12:06:13.573 UTC | null | 965,332 | null | 965,332 | null | 1 | 52 | python|gnome|gnome-3|wayland | 8,215 | <p>The two previous answers are outdated, this is the current state of querying appnames and titles of windows in (Gnome) Wayland.</p>
<ol>
<li>A Gnome-specific JavaScript API which can be accessed over DBus</li>
<li>The wlr-foreign-toplevel-management Wayland protocol (unfortunately not implemented by Gnome)</li>
</ol>
<p>The Gnome-specific API will likely break between Gnome versions, but it works. It is heavily dependent on Gnome internal API to work so there is no chance of it becoming a standard API. There is <a href="https://github.com/ActivityWatch/aw-watcher-window/pull/46" rel="noreferrer">a PR on aw-watcher-window to add this</a>, but it needs some clean-up and afk-support if that's possible.</p>
<p>The <a href="https://github.com/swaywm/wlr-protocols/blob/master/unstable/wlr-foreign-toplevel-management-unstable-v1.xml" rel="noreferrer">wlr-foreign-toplevel-management</a> protocol is (at the time of writing this) implemented by the Sway, Mir, Phosh and Wayfire compositors. Together with the idle.xml protocol which is pretty widely implemented by wayland compositors there's a complete implementation with afk-detection for ActivityWatch in <a href="https://github.com/activitywatch/aw-watcher-window-wayland" rel="noreferrer">aw-watcher-window-wayland</a>. I've been in discussions with sway/rootston developers about whether wayland appnames and X11 wm_class is interchangeable and both Sway and Phosh use these interchangeably now so there should no longer be any distinguishable differences between Wayland and XWayland windows in the API anymore.</p>
<p>I have not researched if KWin has some API similar to Gnome Shell to fetch appnames and titles, but it does at least not implement wlr-foreign-toplevel-management.</p> |
15,658,475 | How do I make a batch file run strings as commands? | <p>I want to make a batch file to circumvent some cmd problems on my computer, but for that I need to be able to take String user input and run it as a command.</p>
<p>Basically what I want to be able to do is type in a command when the batch file asks for input, and have the computer run that command, similar to python's os module (class?)</p> | 15,658,580 | 4 | 0 | null | 2013-03-27 12:11:54.167 UTC | 7 | 2015-09-12 00:37:55.47 UTC | 2014-05-01 08:13:17.49 UTC | null | 1,193,596 | null | 1,543,167 | null | 1 | 36 | windows|batch-file|cmd | 63,255 | <p>Simply assign the string to a variable, then "execute" the variable as though it was a program</p>
<p>eg </p>
<pre><code>set myvar=ECHO Hello, World!
%myvar%
</code></pre> |
15,724,357 | Using Boost with Emscripten | <p>I have a c++ project I would like to convert to a web application. For this purpose, I would like to use Emscripten to build the project.</p>
<p>The project uses some external libraries. I managed to compile or find the JavaScript version of most libraries and now I am stuck with the Boost ones. Actually I do not even know how to start for Boost: they use a boostrap script to generate the files to build the libraries. It is possible to pass the toolset to this script but Emscripten is obviously not supported.</p>
<p>My project uses the following parts of Boost: Thread, Regex, FileSystem, Signals, System. How can I compile these libraries using Emscripten?</p>
<p><strong>Edit</strong></p>
<p>Following the answer of npclaudiu, I bootstrapped the library with the gcc toolkit, then I edited <code>project-config.jam</code> to configure the compiler, replacing:</p>
<pre><code># Compiler configuration. This definition will be used unless
# you already have defined some toolsets in your user-config.jam
# file.
if ! gcc in [ feature.values <toolset> ]
{
using gcc ;
}
</code></pre>
<p>with</p>
<pre><code># Compiler configuration. This definition will be used unless
# you already have defined some toolsets in your user-config.jam
# file.
if ! gcc in [ feature.values <toolset> ]
{
using gcc : : "/full/path/to/em++" ;
}
</code></pre>
<p>Now, typing <code>./b2</code> effectively builds the libraries. Boost.Signals and Boost.System compile well. The others have some errors.</p>
<p>Boost.Thread complains:</p>
<pre><code>libs/thread/src/pthread/thread.cpp:503:27: error: use of undeclared identifier 'pthread_yield'
BOOST_VERIFY(!pthread_yield());
^
</code></pre>
<p>Boost.Regex complains a lot about CHAR_BIT to be undeclared but it seems to be a problem in emscripten:</p>
<pre><code>In file included from libs/regex/build/../src/c_regex_traits.cpp:28:
In file included from ./boost/regex/v4/c_regex_traits.hpp:26:
In file included from ./boost/regex/v4/regex_workaround.hpp:35:
/path/to/emscripten/system/include/libcxx/vector:1989:92: error: use of undeclared identifier 'CHAR_BIT'
static const unsigned __bits_per_word = static_cast<unsigned>(sizeof(__storage_type) * CHAR_BIT);
^
</code></pre>
<p>Boost.FileSystem seems to fail due to emscripten too:</p>
<pre><code>In file included from libs/filesystem/src/windows_file_codecvt.cpp:21:
/path/to/emscripten/system/include/libcxx/cwchar:117:9: error: no member named 'FILE' in the global namespace
using ::FILE;
~~^
</code></pre> | 15,732,854 | 6 | 3 | null | 2013-03-30 22:47:20.397 UTC | 19 | 2020-05-08 11:16:17.993 UTC | 2013-03-31 08:46:05.843 UTC | null | 1,171,783 | null | 1,171,783 | null | 1 | 38 | javascript|c++|boost|emscripten | 13,053 | <p>I finally managed to compile the needed libraries with emscripten. Here are the steps I followed.</p>
<h1>Changes in emscripten</h1>
<p>Edit <code>system/include/libcxx/climits</code> to add the following definitions (see <a href="http://github.com/kripken/emscripten/issues/531" rel="noreferrer">http://github.com/kripken/emscripten/issues/531</a>):</p>
<pre><code>#ifndef CHAR_BIT
# define CHAR_BIT __CHAR_BIT__
#endif
#ifndef CHAR_MIN
# define CHAR_MIN (-128)
#endif
#ifndef CHAR_MAX
# define CHAR_MAX 127
#endif
#ifndef SCHAR_MIN
# define SCHAR_MIN (-128)
#endif
#ifndef SCHAR_MAX
# define SCHAR_MAX 127
#endif
#ifndef UCHAR_MAX
# define UCHAR_MAX 255
#endif
#ifndef SHRT_MIN
# define SHRT_MIN (-32767-1)
#endif
#ifndef SHRT_MAX
# define SHRT_MAX 32767
#endif
#ifndef USHRT_MAX
# define USHRT_MAX 65535
#endif
#ifndef INT_MAX
# define INT_MAX __INT_MAX__
#endif
#ifndef INT_MIN
# define INT_MIN (-INT_MAX-1)
# define INT_MIN (-INT_MAX-1)
#endif
#ifndef UINT_MAX
# define UINT_MAX (INT_MAX * 2U + 1)
#endif
#ifndef LONG_MAX
# define LONG_MAX __LONG_MAX__
#endif
#ifndef LONG_MIN
# define LONG_MIN (-LONG_MAX-1)
#endif
#ifndef ULONG_MAX
# define ULONG_MAX (LONG_MAX * 2UL + 1)
#endif
</code></pre>
<p>Add the following line in <code>system/include/libcxx/cwchar</code></p>
<pre><code>#include <cstdio>
</code></pre>
<h1>Compiling Boost as shared libraries</h1>
<p>As suggested by npclaudiu, bootstrap the library using the gcc toolkit. Then edit <code>project-config.jam</code> to configure the compiler and replace:</p>
<pre><code># Compiler configuration. This definition will be used unless
# you already have defined some toolsets in your user-config.jam
# file.
if ! gcc in [ feature.values <toolset> ]
{
using gcc ;
}
</code></pre>
<p>with</p>
<pre><code># Compiler configuration. This definition will be used unless
# you already have defined some toolsets in your user-config.jam
# file.
if ! gcc in [ feature.values <toolset> ]
{
using gcc : : "/full/path/to/emscripten/em++" ;
}
</code></pre>
<p>Force <code>BOOST_HAS_SCHER_YIELD</code> in <code>boost/config/posix_features.hpp</code>, around the line 67.</p>
<p>Then compile the libraries: <code>./b2 thread regex filesystem signals system</code></p>
<h1>Compiling Boost as static libraries</h1>
<p>Do all the above steps, then edit <code>tools/build/v2/tools/gcc.jam</code> and replace:</p>
<pre><code>toolset.flags gcc.archive .AR $(condition) : $(archiver[1]) ;
</code></pre>
<p>with</p>
<pre><code>toolset.flags gcc.archive .AR $(condition) : "/full/path/to/emscripten/emar" ;
</code></pre>
<p>and</p>
<pre><code>toolset.flags gcc.archive .RANLIB $(condition) : $(ranlib[1]) ;
</code></pre>
<p>with</p>
<pre><code>toolset.flags gcc.archive .RANLIB $(condition) :
"/full/path/to/emscripten/emranlib" ;
</code></pre>
<p>Compile the libraries: <code>./b2 link=static variant=release threading=single runtime-link=static thread signals system filesystem regex</code></p> |
15,961,253 | C: correct usage of strtok_r | <p>How can I use strtok_r instead of strtok to do this?</p>
<pre><code>char *pchE = strtok(NULL, " ");
</code></pre>
<p>Now I'm trying to use <code>strtok_r</code> properly... But sometimes I get problems with the <code>strtol</code>.
I have a thread that I execute 10 times (at the same time).</p>
<pre><code>char *savedEndd1;
char *nomeClass = strtok_r(lineClasses, " ", &savedEndd1);
char *readLessonS = strtok_r (NULL, " ", &savedEndd1);
char *readNTurma = strtok_r(NULL, " ", &savedEndd1);
if (readNTurma==NULL)
printf("CLASS STRTOL begin %s %s\n",nomeClass, readLessonS );
int numberNTurma = strtol(readNTurma, NULL, 10);
</code></pre>
<p>And I'm catching that <code>readNTurma == NULL</code> several times... Why is that? Cant understand why it comes <code>NULL</code>?</p> | 15,961,298 | 4 | 1 | null | 2013-04-12 00:41:33.183 UTC | 7 | 2019-05-11 08:20:49.407 UTC | 2014-03-29 08:14:44.557 UTC | null | 6,244 | null | 2,233,124 | null | 1 | 41 | c|char|strtok | 106,547 | <p>The <a href="http://linux.die.net/man/3/strtok_r" rel="noreferrer">documentation</a> for strtok_r is quite clear.</p>
<blockquote>
<p>The strtok_r() function is a reentrant version strtok(). The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.</p>
<p>On the first call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored. In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.</p>
</blockquote>
<p>So you'd have code like</p>
<pre><code>char str[] = "Hello world";
char *saveptr;
char *foo, *bar;
foo = strtok_r(str, " ", &saveptr);
bar = strtok_r(NULL, " ", &saveptr);
</code></pre> |
50,975,793 | Telegram get chat messages /posts - python Telethon | <p>I am using Telethon and Python 3.6xx</p>
<p>Been able to retreive message from groups, no problem but when it comes to channels I am stuck. </p>
<pre><code>dialogs = client(get_dialogs)
for chat in dialogs.chats:
getmessage = client.get_messages(chat.id, limit=400)
for message in getmessage:
print(message.message)
</code></pre>
<p>I've searched the telethon documentation but most answers were in response to the old <code>get_message_history</code>.</p>
<p>When I'm trying with the following <code>chat.id = 1097988869</code> (news.bitcoin.com) I'm getting an error below (for groups the <code>chat.id</code> works fine):</p>
<blockquote>
<p>PeerIdInvalidError: An invalid Peer was used. Make sure to pass the right peer type</p>
</blockquote> | 50,989,741 | 3 | 2 | null | 2018-06-21 18:58:25.053 UTC | 5 | 2021-01-23 03:07:23.797 UTC | 2018-06-25 12:12:10.623 UTC | null | 2,858,407 | null | 1,449,677 | null | 1 | 23 | python|telethon | 54,982 | <p>update :</p>
<p>in the new version of Telethon, @Lonami answer is best and use it.</p>
<p>############################################################</p>
<p>you can use this code for get messages :</p>
<pre><code>client = TelegramClient('session_name',
api_id,
api_hash,
update_workers=1,
spawn_read_thread=False)
assert client.connect()
if not client.is_user_authorized():
client.send_code_request(phone_number)
me = client.sign_in(phone_number, input('Enter code: '))
channel_username='tehrandb' # your channel
channel_entity=client.get_entity(channel_username)
posts = client(GetHistoryRequest(
peer=channel_entity,
limit=100,
offset_date=None,
offset_id=0,
max_id=0,
min_id=0,
add_offset=0,
hash=0))
# messages stored in `posts.messages`
</code></pre> |
10,608,539 | Error importing HoloEverywhere | <p>First of all, I am new with Android.
I am doing an app, and I am implementing a library called <a href="http://holoeverywhere.com/">HoloEverywhere</a>.
This library use in the themes.xml the library ActionBar Sherlock. I have imported to my workspace ActionBar Sherlock and I have added it to HoloEverywhere.
Next, I have added HoloEverywhere to my project, but when I try to use it, I have an error (I tried to use a button): </p>
<pre><code>The following classes could not be instantiated:
- com.WazaBe.HoloEverywhere.ButtonHolo (Open Class, Show Error Log)
See the Error Log (Window > Show View) for more details.
Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse.
</code></pre>
<p>I put the path of the class in my layout, like this:</p>
<pre><code><com.WazaBe.HoloEverywhere.ButtonHolo
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text" />
</code></pre>
<p>How I can solve this problem and use this library in my project?. Thanks :)
PS. Sorry for my english, I know it is not very good.</p> | 10,888,882 | 4 | 3 | null | 2012-05-15 20:38:38.15 UTC | 24 | 2014-01-03 01:30:10.357 UTC | 2012-09-26 22:37:08.917 UTC | null | 812,698 | null | 1,397,152 | null | 1 | 14 | android|themes|actionbarsherlock|android-holo-everywhere | 12,717 | <p><strong>Follow the steps below(taken from blog <a href="http://androidfragments.blogspot.in/2011/10/how-to-use-actionbar-sherlock.html" rel="noreferrer">here</a>) to add <code>ActionBarSherlock</code></strong></p>
<ol>
<li><a href="http://actionbarsherlock.com/" rel="noreferrer">Download</a> the .zip/.tgz and extract it </li>
<li>Go to eclipse and choose <code>File->New-> Android Project</code> </li>
<li>Select <code>Create project from existing source</code> and then <code>browse</code> to the <code>library</code> folder inside extracted <code>AndroidBarSherlock</code> folder</li>
<li>Build Target should be the latest(14 or15), but your minSdkVersion can be less (7 or 8) </li>
<li>Press <code>Finish</code> </li>
<li>Right click on the newly created project and go to <code>Properties</code>. </li>
<li>Under the <code>Android</code> heading, you should see a section for <code>Library</code> with a checkbox <code>IsLibrary</code>. Make sure that's checked. </li>
<li>Right click -> Properies on the project in which you wish to add <code>AndroidBarSherlock</code> under the <code>Android</code> heading and the <code>Library</code> section choose <code>Add</code>. </li>
<li>You should see the <code>ActionBarSherlock</code> library, add this to your project </li>
<li>Lastly, if you were using the <em>compatibility support</em> , you need to delete that <em>jar</em> since it's included in ActionBarSherlock.</li>
</ol>
<p><strong>Follow the steps below to add <a href="https://github.com/Prototik/HoloEverywhere" rel="noreferrer">HoloEverywhere</a></strong></p>
<ol>
<li><a href="https://github.com/Prototik/HoloEverywhere" rel="noreferrer">Download</a> Zip from GitHub to your computer</li>
<li>UnZip the folder</li>
<li>Go to eclipse and choose <code>File->New-> Android Project</code> </li>
<li>Select <code>Create project from existing source</code> and then <code>browse</code> to the <code>HoloEverywhereLib</code> folder inside extracted folder</li>
<li>Press <code>Finish</code> </li>
<li>Right click on the newly created project and go to <code>Properties</code>. </li>
<li>Under the <code>Android</code> heading, you should see a section for <code>Library</code> with a checkbox <code>IsLibrary</code>. Make sure that's checked and press <code>Add</code> and previously added library <code>ActionBarSherlock</code>.</li>
</ol>
<p><strong>Follow these steps to add <code>HoloEverywhere</code> to your project</strong></p>
<ol>
<li>Create a new Android project</li>
<li>Right Click on project -> Properties -> Android -> Add, add both <code>ActionBarSherlock</code> and <code>HoloEverywhere</code></li>
<li><p>Change the <code>Android Manifest</code> to following </p>
<p><code><application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Holo.Theme"></code></p></li>
<li><p>Edit you <code>main.xml</code> to include Holo theme widgets.</p></li>
<li><p>Change your <code>activity</code> as follows</p>
<pre><code>public class ChkActionBarSherlock extends SherlockActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
</code></pre></li>
</ol> |
10,850,184 | iOS: Image get rotated 90 degree after saved as PNG representation data | <p>I have researched enough to get this working but not able to fix it. After taking picture from camera as long as I have image stored as UIImage, it's fine but as soon as I stored this image as PNG representation, its get rotated 90 degree.</p>
<p>Following is my code and all things I tried:</p>
<pre><code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info valueForKey:UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(NSString*)kUTTypeImage])
{
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
delegate.originalPhoto = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSLog(@"Saving photo");
[self saveImage];
NSLog(@"Fixing orientation");
delegate.fixOrientationPhoto = [self fixOrientation:[UIImage imageWithContentsOfFile:[delegate filePath:imageName]]];
NSLog(@"Scaling photo");
delegate.scaledAndRotatedPhoto = [self scaleAndRotateImage:[UIImage imageWithContentsOfFile:[delegate filePath:imageName]]];
}
[picker dismissModalViewControllerAnimated:YES];
[picker release];
}
- (void)saveImage
{
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSData *imageData = UIImagePNGRepresentation(delegate.originalPhoto);
[imageData writeToFile:[delegate filePath:imageName] atomically:YES];
}
</code></pre>
<p>Here fixOrientation and scaleAndRotateImage functions taken from <a href="https://stackoverflow.com/questions/9324130/iphoneimage-captured-from-camera-rotate-90-degree-automatically">here</a> and <a href="https://stackoverflow.com/questions/10071313/image-taken-in-portrait-is-distorted-when-viewed-in-landscape">here</a> respectively. They works fine and rotate image when I apply them on UIImage but doesn't work if I save image as PNG representation and apply them.</p>
<p>Please refere the following picture after executing above functions:</p>
<p><img src="https://i.stack.imgur.com/up4hy.png" alt="The first photo is original, second is saved, and third and fourth after applying fixorientation and scaleandrotate functions on saved image"></p> | 10,850,379 | 8 | 5 | null | 2012-06-01 12:23:12.497 UTC | 19 | 2020-01-28 13:16:19.88 UTC | 2017-05-23 10:31:31.273 UTC | null | -1 | null | 587,736 | null | 1 | 46 | iphone|uiimage|image-rotation|ios5.1|landscape-portrait | 53,879 | <p>Starting with iOS 4.0 when the camera takes a photo it does not rotate it before saving, it </p>
<p>simply sets a rotation flag in the EXIF data of the JPEG.If you save a UIImage as a JPEG, it </p>
<p>will set the rotation flag.PNGs do not support a rotation flag, so if you save a UIImage as a </p>
<p>PNG, it will be rotated incorrectly and not have a flag set to fix it. So if you want PNG </p>
<p>images you must rotate them yourself, for that check this <a href="https://stackoverflow.com/questions/3554244/uiimagepngrepresentation-issues">link</a>.</p> |
13,553,009 | Find the element with highest occurrences in an array [java] | <p>I have to find the element with highest occurrences in a double array.
I did it like this:</p>
<pre><code>int max = 0;
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if (array[i]==array[j])
count++;
}
if (count >= max)
max = count;
}
</code></pre>
<p>The program works, but it is too slow! I have to find a better solution, can anyone help me?</p> | 13,553,026 | 13 | 0 | null | 2012-11-25 16:32:08.787 UTC | 1 | 2022-08-20 07:08:09.813 UTC | 2015-01-16 14:58:16.843 UTC | null | 408,351 | null | 1,851,402 | null | 1 | 9 | java | 67,182 | <p><strong>Update:</strong> </p>
<ul>
<li>As Maxim pointed out, using <a href="http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html" rel="noreferrer">HashMap</a> would be a more appropriate choice than <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html" rel="noreferrer">Hashtable</a> here.</li>
<li>The assumption here is that you are not concerned with concurrency. If synchronized access is needed, use <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="noreferrer">ConcurrentHashMap</a> instead.</li>
</ul>
<hr>
<p>You can use a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html" rel="noreferrer">HashMap</a> to count the occurrences of each unique element in your double array, and that would:</p>
<ul>
<li>Run in linear <strong>O(n)</strong> time, and </li>
<li>Require <strong>O(n)</strong> space</li>
</ul>
<p><strong>Psuedo code</strong> would be something like this:</p>
<ul>
<li>Iterate through all of the elements of your array once: <strong>O(n)</strong>
<ul>
<li>For each element visited, check to see if its key already exists in the HashMap: <strong>O(1), amortized</strong></li>
<li>If it does not (first time seeing this element), then add it to your HashMap as [key: this element, value: 1]. <strong>O(1)</strong></li>
<li>If it does exist, then increment the value corresponding to the key by 1. <strong>O(1), amortized</strong></li>
</ul></li>
<li>Having finished building your HashMap, iterate through the map and find the key with the highest associated value - and that's the element with the highest occurrence. <strong>O(n)</strong></li>
</ul>
<p><strong>A partial code solution</strong> to give you an idea how to use HashMap:</p>
<pre><code>import java.util.HashMap;
...
HashMap hm = new HashMap();
for (int i = 0; i < array.length; i++) {
Double key = new Double(array[i]);
if ( hm.containsKey(key) ) {
value = hm.get(key);
hm.put(key, value + 1);
} else {
hm.put(key, 1);
}
}
</code></pre>
<p>I'll leave as an exercise for how to iterate through the HashMap afterwards to find the key with the highest value; but if you get stuck, just add another comment and I'll get you more hints =)</p> |
13,715,456 | create a UIImageView that crops an image and displays only 100w 100h at 50x and 200y | <p>I am trying to create a box that pops up in my xcode app that just displays an image of that size. I have the following</p>
<pre><code>UIImageView *newView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"beach.jpg"]];
</code></pre>
<p>but this creates the full size image and just shows it. How would I only show it as 100w by 100h at 50 over and 200 down? Would I use CGRect?</p>
<p>Also, can I make it so that clicking it causes it to disappear?</p>
<p><strong>edit #1</strong>
I don't want to resize down the image - would rather just pull the 100 squared pixels and place them in a frame.</p> | 13,715,487 | 3 | 2 | null | 2012-12-05 02:41:09.323 UTC | 9 | 2018-03-17 21:39:38.29 UTC | 2017-10-06 20:02:43.103 UTC | null | 3,885,376 | null | 152,825 | null | 1 | 26 | ios|uiimageview | 24,846 | <p>Please try using the following code. </p>
<pre><code>MyImageview.contentMode = UIViewContentModeScaleAspectFill;
MyImageview.clipsToBounds = YES;
</code></pre> |
13,376,483 | How to solve svn error E155010? | <p>My working copy is in an inconsistent status:</p>
<pre><code>$ svn status
svn: E155037: Previous operation has not finished; run 'cleanup' if it was interrupted
$ svn cleanup
svn: E155010: The node '<myprojectpath>/libs/armeabi/gdbserver' was not found.
</code></pre>
<p>I'm stucked on it. There is a solution to solve this?
Thanks.</p> | 13,492,107 | 7 | 2 | null | 2012-11-14 09:53:52.477 UTC | 4 | 2019-02-02 09:26:39.93 UTC | null | null | null | null | 1,122,966 | null | 1 | 27 | svn | 57,245 | <p>I had the same problem and I found that is quite simple to solve (in my case).
Open a console and go to the folder presenting the problem (in you case <code><myprojectpath>/libs/armeabi/gdbserver</code>).</p>
<p>Run <code>svn up</code>. It will show you a line presenting the same error <code>svn: E155010:...</code>.</p>
<pre><code>lore@loreLaptop ~/workspace/Ng
$ svn up
Updating '.':
svn: E155010: The node '/home/lore/workspace/Ng/.classpath' was not found.
</code></pre>
<p>Run <code>svn cleanup</code>.</p>
<pre><code>lore@loreLaptop ~/workspace/Ng
$ svn cleanup
</code></pre>
<p>Run <code>svn up</code> again: a menu will be showed allowing you to edit/resolve/accept/... a particular configuration:</p>
<pre><code>lore@loreLaptop ~/workspace/Ng
$ svn up
Updating '.':
Conflict for property 'svn:ignore' discovered on '/home/lore/workspace/Ng'.
Select: (p) postpone, (df) diff-full, (e) edit,
(s) show all options: s
(e) edit - change merged file in an editor
(df) diff-full - show all changes made to merged file
(r) resolved - accept merged version of file
(dc) display-conflict - show all conflicts (ignoring merged version)
(mc) mine-conflict - accept my version for all conflicts (same)
(tc) theirs-conflict - accept their version for all conflicts (same)
(mf) mine-full - accept my version of entire file (even non-conflicts)
(tf) theirs-full - accept their version of entire file (same)
(p) postpone - mark the conflict to be resolved later
(l) launch - launch external tool to resolve conflict
(s) show all - show this list
Select: (p) postpone, (df) diff-full, (e) edit,
(s) show all options: e
Select: (p) postpone, (df) diff-full, (e) edit, (r) resolved,
(s) show all options: r
U .
Updated to revision 193.
Summary of conflicts:
Skipped paths: 2
</code></pre>
<p>Run <code>svn up</code> to be sure that the conflict is resolved:</p>
<pre><code>lore@loreLaptop ~/workspace/Ng
$ svn up
Updating '.':
At revision 193.
Summary of conflicts:
Skipped paths: 2
</code></pre>
<p>That's all. Hope could be useful for someone.</p> |
13,245,996 | Pass row number as variable in excel sheet | <p>Suppose I have: </p>
<ol>
<li>a value of 5 in <code>B1</code></li>
<li>I want to pass the number (5) in <code>B1</code> as a row variable, which will be read in conjunction with column <code>A</code> into another cell (say <code>C1</code>) as "=A(B1)" i.e. "=A5"</li>
</ol>
<p>How would I do this?</p> | 13,246,021 | 3 | 2 | null | 2012-11-06 07:01:39.357 UTC | 9 | 2012-11-06 14:17:51.383 UTC | 2012-11-06 10:44:03.27 UTC | null | 641,067 | null | 1,784,818 | null | 1 | 52 | excel|excel-formula | 190,613 | <p>Assuming your row number is in <code>B1</code>, you can use <code>INDIRECT</code>:</p>
<pre><code>=INDIRECT("A" & B1)
</code></pre>
<p>This takes a cell reference as a string (in this case, the concatenation of <code>A</code> and the value of <code>B1</code> - 5), and returns the value at that cell.</p> |
13,688,238 | JavaScript style.display="none" or jQuery .hide() is more efficient? | <pre><code>document.getElementById("elementId").style.display="none"
</code></pre>
<p>is used in JavaScript to hide an element. But in jQuery,</p>
<pre><code>$("#elementId").hide();
</code></pre>
<p>is used for the same purpose. Which way is more efficient? I have seen a comparison between two jQuery function <code>.hide()</code> and <code>.css("display","none")</code> <a href="https://stackoverflow.com/q/4396983/1774964">here</a>.</p>
<p>But my problem is whether pure JavaScript is more efficient than jQuery?</p> | 13,688,269 | 4 | 1 | null | 2012-12-03 17:08:06.733 UTC | 15 | 2012-12-03 17:19:45.953 UTC | 2017-05-23 12:09:45.677 UTC | null | -1 | null | 1,774,964 | null | 1 | 86 | javascript|jquery|css|performance | 347,388 | <p>Talking about efficiency:</p>
<pre><code>document.getElementById( 'elemtId' ).style.display = 'none';
</code></pre>
<hr>
<p>What jQuery does with its <code>.show()</code> and <code>.hide()</code> methods is, that it remembers the <em>last state</em> of an element. That can come in handy sometimes, but since you asked about efficiency that doesn't matter here.</p> |
3,984,254 | Send users to a pre-filled Amazon cart checkout | <p>I'm working on a site that will create pre-set packages of items. To start, I'm using Amazon to test the idea, pulling some affiliate sales, and then I'll fulfill orders myself if the idea deems successful. </p>
<p>My goal is to have a "buy now" type button, and upon clicking, the user will arrive at an Amazon checkout now page, with a cart pre-filled with items of my choosing, and my affiliate number.</p>
<p>I'm a PHP developer, so if a solution must be language specific, that's the language to go with. If it's more of a conceptual answer, or if there's an API for this, that works too. </p>
<p>Thanks in advance.</p> | 6,169,262 | 2 | 5 | null | 2010-10-21 04:21:16.2 UTC | 9 | 2017-06-07 00:48:15.723 UTC | 2010-10-21 14:58:42.117 UTC | null | 190,902 | null | 190,902 | null | 1 | 7 | php|e-commerce|amazon-web-services|amazon | 15,401 | <p>You may use link that contains ASINs and their quantity. It doesn't add items to someone's cart but confirms to add to cart.</p>
<pre class="lang-none prettyprint-override"><code>URL:
http://www.amazon.com/gp/aws/cart/add.html
Parameters:
- AssociateTag
- ASIN.<number> <number> starts at 1
- Quantity.<number> one quantity parameter for each ASIN parameter
Example (parameters separated by line break for visibility):
http://www.amazon.com/gp/aws/cart/add.html
?AssociateTag=your-tag
&ASIN.1=B003IXYJYO
&Quantity.1=2
&ASIN.2=B0002KR8J4
&Quantity.2=1
&ASIN.3=B0002ZP18E
&Quantity.3=1
&ASIN.4=B0002ZP3ZA
&Quantity.4=2
</code></pre>
<p>One line example: <a href="https://www.amazon.com/gp/aws/cart/add.html?AssociateTag=your-tag&ASIN.1=B003IXYJYO&Quantity.1=2&ASIN.2=B0002KR8J4&Quantity.2=1&ASIN.3=B0002ZP18E&Quantity.3=1&ASIN.4=B0002ZP3ZA&Quantity.4=2&ASIN.5=B004J2JG6O&Quantity.5=1" rel="noreferrer">https://www.amazon.com/gp/aws/cart/add.html?AssociateTag=your-tag&ASIN.1=B003IXYJYO&Quantity.1=2&ASIN.2=B0002KR8J4&Quantity.2=1&ASIN.3=B0002ZP18E&Quantity.3=1&ASIN.4=B0002ZP3ZA&Quantity.4=2&ASIN.5=B004J2JG6O&Quantity.5=1</a></p>
<p>ASINs are found in the product's page URL or by searching for "ASIN" on the product page. <a href="https://www.amazon.ca/gp/help/customer/display.html?nodeId=200576730" rel="noreferrer">More details here</a></p> |
3,861,782 | SQL Server error "Implicit conversion of because the collation of the value is unresolved due to a collation conflict." | <p>I getting this error while developing stored procedure</p>
<blockquote>
<p>Implicit conversion of varchar value to varchar cannot be performed because the collation of the value is unresolved due to a collation conflict.</p>
</blockquote>
<p>statement is like this</p>
<pre><code>Select City COLLATE DATABASE_DEFAULT AS Place, State, Country FROM DEPT1
UNION ALL
Select '' AS Place, 'Arizona' As State, Country FROM DEPT2
</code></pre>
<p>but If If do this it also give same error</p>
<pre><code> Select City COLLATE DATABASE_DEFAULT AS Place, State, Country FROM DEPT1
UNION ALL
Select '' COLLATE DATABASE_DEFAULT AS Place, 'Arizona' As State, Country FROM DEPT2
</code></pre>
<p>Actually this code is written by some one else and am just editing the code, do not know why he added COLLATE DATABASE_DEFAULT but If I remove it also gives the same error</p>
<blockquote>
<p>Implicit conversion of varchar value to varchar cannot be performed because the collation of the value is unresolved due to a collation conflict.</p>
</blockquote> | 3,861,790 | 2 | 0 | null | 2010-10-05 07:53:24.097 UTC | 3 | 2021-08-18 15:45:36.863 UTC | 2021-08-18 15:45:36.863 UTC | null | 792,066 | null | 228,755 | null | 1 | 30 | sql-server|tsql | 74,912 | <p>You'd need COLLATE in both places most likely.</p>
<pre><code>Select City COLLATE DATABASE_DEFAULT AS Place, State, Country FROM DEPT1
UNION ALL
Select '' COLLATE DATABASE_DEFAULT AS Place, 'Arizona' As State, Country FROM DEPT2
</code></pre>
<p>Edit: You may need it on every string if you get it in one places</p>
<pre><code>Select
City COLLATE DATABASE_DEFAULT AS Place,
State COLLATE DATABASE_DEFAULT AS State,
Country COLLATE DATABASE_DEFAULT AS Country
FROM DEPT1
UNION ALL
Select
'' COLLATE DATABASE_DEFAULT,
'Arizona' COLLATE DATABASE_DEFAULT ,
Country COLLATE DATABASE_DEFAULT
FROM DEPT2
</code></pre>
<p>Edit2:</p>
<p>It happens because your column collation is probably different to your database collation. So "City" has one collation but string constants have another.</p> |
29,462,374 | how to remove sessions in Laravel 5 | <p>I am trying to remove a basic session but it's not removing. Here's the code</p>
<p><em>welcome.blade.php</em></p>
<pre><code>@if(Session::has('key'))
{{ Session::get('key')}}
<a href="logout">Sign Out</a>
@else
please signin
@endif
</div>
</code></pre>
<p>I don't know how to remove session. Here's the one I used but it's not working <code>route.php</code></p>
<pre><code>Route::get('/logout', function() {
$vv = Session::forget('key');
if($vv)
{
return "signout";
}
});
</code></pre> | 29,486,652 | 5 | 3 | null | 2015-04-05 21:22:34.57 UTC | 2 | 2019-04-08 12:50:57.25 UTC | 2017-12-19 13:51:31.62 UTC | null | 2,289,953 | null | 4,751,037 | null | 1 | 20 | php|laravel-5 | 75,076 | <p>You should use this method</p>
<pre><code> Route::get('/logout', function() {
Session::forget('key');
if(!Session::has('key'))
{
return "signout";
}
});
</code></pre> |
14,930,785 | Accessing a div tag from codebehind | <p>I am Working in asp.net and c#. I have a <code>div</code> tag in my application with <code>class="something"</code>.I need to access this <strong>something</strong> class in codebehind.How can i do that..</p>
<p><strong>Code</strong>:</p>
<pre><code> <div class="something">
//somecode
<div>
</code></pre>
<p><strong>Note</strong>:I want access <strong>Something</strong> class in codebehind.</p> | 14,930,896 | 7 | 0 | null | 2013-02-18 06:40:36.13 UTC | null | 2017-07-12 15:29:00.397 UTC | null | null | null | null | 2,049,195 | null | 1 | 7 | c#|asp.net | 48,005 | <p>Give <code>ID</code> and attribute <code>runat='server'</code> as :</p>
<pre><code><div class="something" ID="mydiv" runat="server">
//somecode
<div>
</code></pre>
<p>Codebehind:</p>
<p>You can modify your <strong><code>something</code></strong> styles here.</p>
<pre><code>mydiv.Style.Add("display", "none");
</code></pre> |
15,354,089 | Get date and time picker value from a single dialog fragment and set it in EditText | <p>I am working on an application in which the user can set the date and time. I want to set the date and time in a single dialog fragment and set it to edit text. Is it possible to use a date and time picker in 1 dialog fragment? If it is, how do you do it?
Currently I am getting the time from the dialog fragment and then setting it to the <code>EditText</code>.</p>
<p>My code is</p>
<pre><code>LaterTextView=(TextView)findViewById(R.id.PickUp_later_TextView);
LaterTextView.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
// set time picker as current time
return new TimePickerDialog(this, timePickerListener, hour, minute,
false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
// set current time into TextView
setDate_time_EditTExt.setText(new StringBuilder().append(pad(hour))
.append(":").append(pad(minute)));
}
};
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
</code></pre>
<p>I want to set the date and time from the same dialog fragment.</p> | 15,355,666 | 3 | 0 | null | 2013-03-12 05:39:43.63 UTC | 13 | 2015-10-29 12:20:47.457 UTC | 2014-06-08 19:28:04.217 UTC | null | 2,598,115 | null | 1,822,884 | null | 1 | 8 | android|datepicker|datetimepicker|timepicker | 22,009 | <p><strong>Date Picker</strong> and <strong>Time Picker</strong> both <em>in single dialog</em>. check this code.</p>
<p><strong>main_Activity.java</strong></p>
<pre><code>@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
custom = new CustomDateTimePicker(this,
new CustomDateTimePicker.ICustomDateTimeListener() {
@Override
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName,
int hour24, int hour12, int min, int sec,
String AM_PM) {
((TextView) findViewById(R.id.lablel))
.setText(calendarSelected
.get(Calendar.DAY_OF_MONTH)
+ "/" + (monthNumber+1) + "/" + year
+ ", " + hour12 + ":" + min
+ " " + AM_PM);
}
@Override
public void onCancel() {
}
});
/**
* Pass Directly current time format it will return AM and PM if you set
* false
*/
custom.set24HourFormat(false);
/**
* Pass Directly current data and time to show when it pop up
*/
custom.setDate(Calendar.getInstance());
findViewById(R.id.button_date).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
custom.showDialog();
}
});
}
CustomDateTimePicker custom;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
</code></pre>
<p><strong>CustomDateTimePicker.java</strong></p>
<pre><code>public class CustomDateTimePicker implements OnClickListener {
private DatePicker datePicker;
private TimePicker timePicker;
private ViewSwitcher viewSwitcher;
private final int SET_DATE = 100, SET_TIME = 101, SET = 102, CANCEL = 103;
private Button btn_setDate, btn_setTime, btn_set, btn_cancel;
private Calendar calendar_date = null;
private Activity activity;
private ICustomDateTimeListener iCustomDateTimeListener = null;
private Dialog dialog;
private boolean is24HourView = true, isAutoDismiss = true;
private int selectedHour, selectedMinute;
public CustomDateTimePicker(Activity a,
ICustomDateTimeListener customDateTimeListener) {
activity = a;
iCustomDateTimeListener = customDateTimeListener;
dialog = new Dialog(activity);
dialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
View dialogView = getDateTimePickerLayout();
dialog.setContentView(dialogView);
}
public View getDateTimePickerLayout() {
LinearLayout.LayoutParams linear_match_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout.LayoutParams linear_wrap_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams frame_match_wrap = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams button_params = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
LinearLayout linear_main = new LinearLayout(activity);
linear_main.setLayoutParams(linear_match_wrap);
linear_main.setOrientation(LinearLayout.VERTICAL);
linear_main.setGravity(Gravity.CENTER);
LinearLayout linear_child = new LinearLayout(activity);
linear_child.setLayoutParams(linear_wrap_wrap);
linear_child.setOrientation(LinearLayout.VERTICAL);
LinearLayout linear_top = new LinearLayout(activity);
linear_top.setLayoutParams(linear_match_wrap);
btn_setDate = new Button(activity);
btn_setDate.setLayoutParams(button_params);
btn_setDate.setText("Set Date");
btn_setDate.setId(SET_DATE);
btn_setDate.setOnClickListener(this);
btn_setTime = new Button(activity);
btn_setTime.setLayoutParams(button_params);
btn_setTime.setText("Set Time");
btn_setTime.setId(SET_TIME);
btn_setTime.setOnClickListener(this);
linear_top.addView(btn_setDate);
linear_top.addView(btn_setTime);
viewSwitcher = new ViewSwitcher(activity);
viewSwitcher.setLayoutParams(frame_match_wrap);
datePicker = new DatePicker(activity);
timePicker = new TimePicker(activity);
timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
selectedHour = hourOfDay;
selectedMinute = minute;
}
});
viewSwitcher.addView(timePicker);
viewSwitcher.addView(datePicker);
LinearLayout linear_bottom = new LinearLayout(activity);
linear_match_wrap.topMargin = 8;
linear_bottom.setLayoutParams(linear_match_wrap);
btn_set = new Button(activity);
btn_set.setLayoutParams(button_params);
btn_set.setText("Set");
btn_set.setId(SET);
btn_set.setOnClickListener(this);
btn_cancel = new Button(activity);
btn_cancel.setLayoutParams(button_params);
btn_cancel.setText("Cancel");
btn_cancel.setId(CANCEL);
btn_cancel.setOnClickListener(this);
linear_bottom.addView(btn_set);
linear_bottom.addView(btn_cancel);
linear_child.addView(linear_top);
linear_child.addView(viewSwitcher);
linear_child.addView(linear_bottom);
linear_main.addView(linear_child);
return linear_main;
}
public void showDialog() {
if (!dialog.isShowing()) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
selectedHour = calendar_date.get(Calendar.HOUR_OF_DAY);
selectedMinute = calendar_date.get(Calendar.MINUTE);
timePicker.setIs24HourView(is24HourView);
timePicker.setCurrentHour(selectedHour);
timePicker.setCurrentMinute(selectedMinute);
datePicker.updateDate(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DATE));
dialog.show();
btn_setDate.performClick();
}
}
public void setAutoDismiss(boolean isAutoDismiss) {
this.isAutoDismiss = isAutoDismiss;
}
public void dismissDialog() {
if (!dialog.isShowing())
dialog.dismiss();
}
public void setDate(Calendar calendar) {
if (calendar != null)
calendar_date = calendar;
}
public void setDate(Date date) {
if (date != null) {
calendar_date = Calendar.getInstance();
calendar_date.setTime(date);
}
}
public void setDate(int year, int month, int day) {
if (month < 12 && month >= 0 && day < 32 && day >= 0 && year > 100
&& year < 3000) {
calendar_date = Calendar.getInstance();
calendar_date.set(year, month, day);
}
}
public void setTimeIn24HourFormat(int hourIn24Format, int minute) {
if (hourIn24Format < 24 && hourIn24Format >= 0 && minute >= 0
&& minute < 60) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = true;
}
}
public void setTimeIn12HourFormat(int hourIn12Format, int minute,
boolean isAM) {
if (hourIn12Format < 13 && hourIn12Format > 0 && minute >= 0
&& minute < 60) {
if (hourIn12Format == 12)
hourIn12Format = 0;
int hourIn24Format = hourIn12Format;
if (!isAM)
hourIn24Format += 12;
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = false;
}
}
public void set24HourFormat(boolean is24HourFormat) {
is24HourView = is24HourFormat;
}
public interface ICustomDateTimeListener {
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName, int hour24,
int hour12, int min, int sec, String AM_PM);
public void onCancel();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case SET_DATE:
btn_setTime.setEnabled(true);
btn_setDate.setEnabled(false);
viewSwitcher.showNext();
break;
case SET_TIME:
btn_setTime.setEnabled(false);
btn_setDate.setEnabled(true);
viewSwitcher.showPrevious();
break;
case SET:
if (iCustomDateTimeListener != null) {
int month = datePicker.getMonth();
int year = datePicker.getYear();
int day = datePicker.getDayOfMonth();
calendar_date.set(year, month, day, selectedHour,
selectedMinute);
iCustomDateTimeListener.onSet(dialog, calendar_date,
calendar_date.getTime(), calendar_date
.get(Calendar.YEAR),
getMonthFullName(calendar_date.get(Calendar.MONTH)),
getMonthShortName(calendar_date.get(Calendar.MONTH)),
calendar_date.get(Calendar.MONTH), calendar_date
.get(Calendar.DAY_OF_MONTH),
getWeekDayFullName(calendar_date
.get(Calendar.DAY_OF_WEEK)),
getWeekDayShortName(calendar_date
.get(Calendar.DAY_OF_WEEK)), calendar_date
.get(Calendar.HOUR_OF_DAY),
getHourIn12Format(calendar_date
.get(Calendar.HOUR_OF_DAY)), calendar_date
.get(Calendar.MINUTE), calendar_date
.get(Calendar.SECOND), getAMPM(calendar_date));
}
if (dialog.isShowing() && isAutoDismiss)
dialog.dismiss();
break;
case CANCEL:
if (iCustomDateTimeListener != null)
iCustomDateTimeListener.onCancel();
if (dialog.isShowing())
dialog.dismiss();
break;
}
}
/**
* @param date
* date in String
* @param fromFormat
* format of your <b>date</b> eg: if your date is 2011-07-07
* 09:09:09 then your format will be <b>yyyy-MM-dd hh:mm:ss</b>
* @param toFormat
* format to which you want to convert your <b>date</b> eg: if
* required format is 31 July 2011 then the toFormat should be
* <b>d MMMM yyyy</b>
* @return formatted date
*/
public static String convertDate(String date, String fromFormat,
String toFormat) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromFormat);
Date d = simpleDateFormat.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
simpleDateFormat = new SimpleDateFormat(toFormat);
simpleDateFormat.setCalendar(calendar);
date = simpleDateFormat.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
private String getMonthFullName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getMonthShortName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getWeekDayFullName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private String getWeekDayShortName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private int getHourIn12Format(int hour24) {
int hourIn12Format = 0;
if (hour24 == 0)
hourIn12Format = 12;
else if (hour24 <= 12)
hourIn12Format = hour24;
else
hourIn12Format = hour24 - 12;
return hourIn12Format;
}
private String getAMPM(Calendar calendar) {
String ampm = (calendar.get(Calendar.AM_PM) == (Calendar.AM)) ? "AM"
: "PM";
return ampm;
}
private void resetData() {
calendar_date = null;
is24HourView = true;
}
public static String pad(int integerToPad) {
if (integerToPad >= 10 || integerToPad < 0)
return String.valueOf(integerToPad);
else
return "0" + String.valueOf(integerToPad);
}
}
</code></pre>
<p><strong>activity_main.xml</strong></p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/lablel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
android:textColor="#000"
android:textSize="20dp"
tools:context=".MainActivity" />
<Button
android:id="@+id/button_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/lablel"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:text="Date Time Picker" />
</RelativeLayout>
</code></pre>
<p><img src="https://i.stack.imgur.com/OzvjX.png" alt="enter image description here"></p> |
22,008,487 | How to concatenate columns with Laravel 4 Eloquent? | <p>I have a table called <code>tenantdetails</code> which contains</p>
<pre><code>Tenant_Id | First_Name | Last_Name | ........
</code></pre>
<p>and I want to retrieve <code>First_Name</code> and <code>Last Name</code> as one column via the concatenation function of MySQL. So I write in my <code>controller</code> as follows</p>
<pre><code>$tenants = Tenant::orderBy('First_Name')->lists('CONCAT(`First_Name`," ",`Last_Name`)','Tenant_Id');
</code></pre>
<p>But results the following error:</p>
<blockquote>
<pre><code> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '`," ",`First_Name`)`,
`Id` from `tenantdetails` order by `F' at line 1
(SQL: select `CONCAT(`First_Name`," ",`Last_Name`)`, `Id`
from `tenantdetails` order by `First_Name` asc).
</code></pre>
</blockquote>
<p>How can we avoid the backticks while calling a function of MySQL in Laravel Eloquent. I am interested only in Eloquent (not in fluent query). Thanks in advance.</p>
<p><strong>Update</strong></p>
<p>Thanks to @Andreyco for helping me. We can achieve this in a more elegant way using Laravel models, as below:<br></p>
<p>In our <code>model</code>:</p>
<pre><code>public function getTenantFullNameAttribute()
{
return $this->attributes['First_Name'] .' '. $this->attributes['Last_Name'];
}
</code></pre>
<p>and in our <code>controller</code>:</p>
<pre><code>$tenants = Tenant::orderBy('First_Name')->get();
$tenants = $tenants->lists('TenantFullName', 'Tenant_Id');
</code></pre> | 22,008,586 | 5 | 3 | null | 2014-02-25 08:29:02.7 UTC | 17 | 2021-02-03 08:49:12.907 UTC | 2014-11-21 02:55:15.797 UTC | null | 2,945,630 | null | 1,960,474 | null | 1 | 43 | php|mysql|laravel|laravel-4 | 70,562 | <pre><code>Tenant::select('Tenant_Id', DB::raw('CONCAT(First_Name, " ", Last_Name) AS full_name'))
->orderBy('First_Name')
->lists('full_name', 'Tenant_Id');
</code></pre> |
37,588,017 | Fallback background-image if default doesn't exist | <p>I want to set an image as a background, however the image name might be either <code>bg.png</code> or <code>bg.jpg</code>.</p>
<p>Is there any non-javascript way to create a fallback to an alternative image if the default background doesn't exist?</p>
<pre><code>body{
background: url(bg.png);
background-size: 100% 100%;
width: 100vw;
height: 100vh;
margin: 0;
}
</code></pre> | 37,588,482 | 5 | 3 | null | 2016-06-02 09:36:53.713 UTC | 4 | 2022-06-03 15:05:40.397 UTC | 2016-06-02 10:01:54.133 UTC | null | 2,030,321 | null | 3,694,045 | null | 1 | 47 | html|css|background | 42,078 | <p>You can use multiple backgrounds if there is no transparency involved and they occupy all available space or have the same size:</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>div{
background-image: url('http://placehold.it/1000x1000'), url('http://placehold.it/500x500');
background-repeat:no-repeat;
background-size: 100%;
height:200px;
width:200px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code></pre>
</div>
</div>
</p>
<p>If the first doesn't exit, the second will be displayed.</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>div{
background-image: url('http://placehol/1000x1000'), url('http://placehold.it/500x500');
background-repeat:no-repeat;
background-size: 100%;
height:200px;
width:200px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code></pre>
</div>
</div>
</p> |
19,593,989 | Create Remote Desktop with WebRTC | <p>is possible create a remote desktop app between browsers with WebRTC (or maybe with Node.JS if possible)?</p>
<p>I see the Google Chrome have this extension, but i need create a remote desktop app to my helpdesk software.</p> | 20,063,100 | 3 | 3 | null | 2013-10-25 15:33:16.113 UTC | 10 | 2018-04-14 11:02:54.333 UTC | null | null | null | null | 2,920,612 | null | 1 | 20 | node.js|webrtc | 31,730 | <p>Try chrome's <a href="http://developer.chrome.com/extensions/desktopCapture.html" rel="noreferrer">desktopCapture</a> experimental extension API. You can test <a href="https://chrome.google.com/webstore/detail/webrtc-desktop-sharing/nkemblooioekjnpfekmjhpgkackcajhg" rel="noreferrer">this chrome extension</a>!</p>
<h2>Updated at: Oct 06, 2015</h2>
<p><a href="https://github.com/muaz-khan/Chrome-Extensions" rel="noreferrer">desktopCapture API</a> in Chrome or <a href="https://github.com/muaz-khan/Firefox-Extensions" rel="noreferrer">screen capturing API</a> in Firefox doesn't provides remote-desktop-access or remote-desktop-control.</p>
<p>Both API providers generates stateless screen; and remote users can merely view the screen.</p>
<p><strong>Here is a browser-based VNC client:</strong></p>
<blockquote>
<p>VNC client using HTML5 (Web Sockets, Canvas) with encryption (wss://) support. <a href="http://novnc.com" rel="noreferrer">http://novnc.com</a></p>
<p>Source code: <a href="https://github.com/kanaka/noVNC" rel="noreferrer">https://github.com/kanaka/noVNC</a></p>
</blockquote>
<p>You can easily switch from WebSockets to WebRTC data channels.</p> |
17,391,811 | How to execute in PHP interactive mode | <p>I am new to PHP, and I just wanted to run PHP in a command prompt (interactive mode).</p>
<p>So I typed this code:</p>
<pre><code>`php -v`
`<?php`
`echo 7;`
`?>`
</code></pre>
<p>But I do not know how to execute it, because when I press <kbd>Enter</kbd> cmd expects me to continue writing the code. I searched on php.net and some other forums, but I didn't find anything. So is there a function key or something to display the result?</p> | 21,893,501 | 2 | 1 | null | 2013-06-30 15:12:28.063 UTC | 3 | 2018-07-24 16:00:24.68 UTC | 2018-07-24 15:57:49.557 UTC | null | 63,550 | null | 1,952,567 | null | 1 | 28 | php|command-line | 32,724 | <p><kbd>Ctrl</kbd>+<kbd>d</kbd> will trigger an end-of-file condition and cause the script to be executed.</p>
<p>See also <a href="https://stackoverflow.com/questions/14792842/how-does-the-interactive-php-shell-work">How does the interactive php shell work?</a></p>
<blockquote>
<blockquote>
<p>Interactive Shell and Interactive Mode are not the same thing, despite
the similar names and functionality.</p>
<p>If you type php -a and get a response of 'Interactive Shell' followed by a php> prompt, you have interactive shell available (PHP
was compiled with readline support). If instead you get a response of
'Interactive mode enabled', you DO NOT have interactive shell
available and this article does not apply to you.</p>
</blockquote>
<p>So if you get only "Interactive mode enabled", then you'll only be
able to type in PHP code and then when you're done, send PHP an EOF to
execute it.</p>
</blockquote>
<p>"EOF" means "end-of-file".</p> |
17,290,256 | Get google map link with latitude/longitude | <p>I want to get google map link that show title/content in marker that located at latitude/longitude. </p>
<p>so parameters are title, content, latitude , longitude .
Result is a link like this
<a href="https://maps.google.com/?ie=UTF8&ll=xxx,xxx&title=xxx&content=xxx">https://maps.google.com/?ie=UTF8&ll=xxx,xxx&title=xxx&content=xxx</a> </p>
<p>I searched google and don't find answer, event in google API.</p> | 17,291,577 | 8 | 1 | null | 2013-06-25 06:08:53.447 UTC | 11 | 2021-05-05 05:52:31.757 UTC | 2013-08-14 08:48:41.623 UTC | null | 569,101 | null | 1,564,579 | null | 1 | 39 | google-maps | 137,465 | <p>I've tried doing the request you need using an iframe to show the result for latitude, longitude, and zoom needed:</p>
<pre><code><iframe
width="300"
height="170"
frameborder="0"
scrolling="no"
marginheight="0"
marginwidth="0"
src="https://maps.google.com/maps?q='+YOUR_LAT+','+YOUR_LON+'&hl=es&z=14&amp;output=embed"
>
</iframe>
<br />
<small>
<a
href="https://maps.google.com/maps?q='+data.lat+','+data.lon+'&hl=es;z=14&amp;output=embed"
style="color:#0000FF;text-align:left"
target="_blank"
>
See map bigger
</a>
</small>
</code></pre> |
17,317,465 | jQuery textbox change event doesn't fire until textbox loses focus? | <p>I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.</p>
<p>HTML:</p>
<pre><code><input type="text" id="textbox" />
</code></pre>
<p>JS:</p>
<pre><code>$("#textbox").change(function() {alert("Change detected!");});
</code></pre>
<p>See <a href="http://jsfiddle.net/K682b/" rel="noreferrer">demo on JSFiddle</a></p>
<p>My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...</p>
<pre><code>$("#textbox").keyup(function() {alert("Keyup detected!");});
</code></pre>
<p>...but it's a known fact that the keyup event isn't fired on right-click-and-paste.</p>
<p>Any workaround? Is having both listeners going to cause any problems?</p> | 17,317,620 | 7 | 1 | null | 2013-06-26 10:21:53.767 UTC | 37 | 2016-12-09 00:00:46.907 UTC | 2016-12-09 00:00:46.907 UTC | null | 1,372,621 | null | 979,621 | null | 1 | 139 | jquery|events|textbox | 176,467 | <p>Binding to both events is the typical way to do it. You can also bind to the paste event.</p>
<p>You can bind to multiple events like this:</p>
<pre><code>$("#textbox").on('change keyup paste', function() {
console.log('I am pretty sure the text box changed');
});
</code></pre>
<p>If you wanted to be pedantic about it, you should also bind to mouseup to cater for dragging text around, and add a <code>lastValue</code> variable to ensure that the text actually did change: </p>
<pre><code>var lastValue = '';
$("#textbox").on('change keyup paste mouseup', function() {
if ($(this).val() != lastValue) {
lastValue = $(this).val();
console.log('The text box really changed this time');
}
});
</code></pre>
<p>And if you want to be <code>super duper</code> pedantic then you should use an interval timer to cater for auto fill, plugins, etc:</p>
<pre><code>var lastValue = '';
setInterval(function() {
if ($("#textbox").val() != lastValue) {
lastValue = $("#textbox").val();
console.log('I am definitely sure the text box realy realy changed this time');
}
}, 500);
</code></pre> |
18,731,693 | Undefined index with PHP sessions | <p>I'm new to PHP and am even more of a beginner when it comes to sessions. I have my index.php page, which is where users can register and login. The forms are posting to validate.php and loginvalidate.php pages, respectively for registering and logging in.</p>
<p>I have these errors on index.php when I load it:</p>
<p>1) Notice: Undefined index: registered
2) Notice: Undefined index: neverused</p>
<p>I have tried modifying my text in many ways but I never got to solve the errors.</p>
<p>Index.php</p>
<pre><code> <?php
if ($_SESSION['registered'] != NULL){
echo $_SESSION['registered'];
}
if ($_SESSION['badlogin'] != NULL){
echo $_SESSION['badlogin'];
}
if ($_SESSION['neverused'] != NULL) {
echo $_SESSION['neverused'];
}
?>
</code></pre>
<p>Validate.php (after submitting register form)</p>
<pre><code> if (mysqli_num_rows($result) > 0) { //IF THERE IS A PASSWORD FOR THAT EMAIL IN DATABASE
$_SESSION['registered'] = "Email is already registered.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
</code></pre>
<p>Loginvalidate.php (after submitting login form)</p>
<pre><code>if ($numrows!=0) //IF THERE IS A PASSWORD FOR THAT EMAIL IN THE DATABASE
{
if ($row['password'] == $password) { //IF THE PASSWORD MATCHES USER INPUT
header('Location: homepage.php');
echo "lol";
exit();
}
else{
$_SESSION['badlogin'] = "Email/password combination not valid.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
}
else { //THERE IS NO PASSWORD FOR THAT EMAIL, SO THAT EMAIL IS NOT REGISTERED
$_SESSION['neverused'] = "Email is not registered.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
</code></pre>
<p>Okay so my script does what it is intended to do. The only thing that I can't solve is these session errors. Do you see any misuse of sessions? Of course, I have started the sessions in all of my .php files.</p>
<p>Also, note that I am aware that there is no protection from hackers. This is only for a future prototype that won't contain any important data.</p> | 18,731,795 | 2 | 0 | null | 2013-09-11 02:24:45.133 UTC | 1 | 2017-12-27 17:16:30.273 UTC | null | null | null | null | 2,203,884 | null | 1 | 13 | php|session|if-statement|header | 101,866 | <p>The reason for these errors is that you're trying to read an array key that doesn't exist. The <a href="http://php.net/manual/en/function.isset.php">isset()</a> function is there so you can test for this. Something like the following for each element will work a treat; there's no need for null checks as you never assign null to an element:</p>
<pre><code>// check that the 'registered' key exists
if (isset($_SESSION['registered'])) {
// it does; output the message
echo $_SESSION['registered'];
// remove the key so we don't keep outputting the message
unset($_SESSION['registered']);
}
</code></pre>
<p>You could also use it in a loop:</p>
<pre><code>$keys = array('registered', 'badlogin', 'neverused');
//iterate over the keys to test
foreach($keys as $key) {
// test if $key exists in the $_SESSION global array
if (isset($_SESSION[$key])) {
// it does; output the value
echo $_SESSION[$key];
// remove the key so we don't keep outputting the message
unset($_SESSION[$key]);
}
}
</code></pre> |
18,391,231 | setting a static variable in java | <p>I am new to java hence probably a very noob question:</p>
<p>I have a class</p>
<pre><code>public class Foo{
private static String foo;
private String bar;
public Foo(String bar){
this.bar = bar;
}
}
</code></pre>
<p>Now before I instantiate any object for class Foo, I want to set that static variable foo.
which will be used in the class..
How do i do this?</p>
<p>Also, please correct my understanding. value of foo will be same across all the objects, hence it does make sense to declare it as static ? right?</p> | 18,391,254 | 3 | 2 | null | 2013-08-22 21:35:32.307 UTC | 0 | 2013-08-22 21:47:19.57 UTC | null | null | null | null | 902,885 | null | 1 | 10 | java | 43,423 | <pre><code>public class Foo{
private static String foo = "initial value";
private String bar;
public Foo(String bar){
this.bar = bar;
}
}
</code></pre>
<p>Since the value will be the same across all objects, <code>static</code> is the right thing to use. If the value is not only <code>static</code> but also never changing, then you should do this instead:</p>
<pre><code>public class Foo{
private static final String FOO = "initial value";
private String bar;
public Foo(String bar){
this.bar = bar;
}
}
</code></pre>
<p>Notice how the capitalization changed there? That's the java convention. "Constants" are NAMED_LIKE_THIS.</p> |
26,058,792 | Correct fitting with scipy curve_fit including errors in x? | <p>I'm trying to fit a histogram with some data in it using <code>scipy.optimize.curve_fit</code>. If I want to add an error in <code>y</code>, I can simply do so by applying a <code>weight</code> to the fit. But how to apply the error in <code>x</code> (i. e. the error due to binning in case of histograms)?</p>
<p>My question also applies to errors in <code>x</code> when making a linear regression with <code>curve_fit</code> or <code>polyfit</code>; I know how to add errors in <code>y</code>, but not in <code>x</code>.</p>
<p>Here an example (partly from the <a href="http://matplotlib.org/examples/pylab_examples/histogram_demo_extended.html" rel="noreferrer">matplotlib documentation</a>):</p>
<pre><code>import numpy as np
import pylab as P
from scipy.optimize import curve_fit
# create the data histogram
mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)
# define fit function
def gauss(x, *p):
A, mu, sigma = p
return A*np.exp(-(x-mu)**2/(2*sigma**2))
# the histogram of the data
n, bins, patches = P.hist(x, 50, histtype='step')
sigma_n = np.sqrt(n) # Adding Poisson errors in y
bin_centres = (bins[:-1] + bins[1:])/2
sigma_x = (bins[1] - bins[0])/np.sqrt(12) # Binning error in x
P.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
# fitting and plotting
p0 = [700, 200, 25]
popt, pcov = curve_fit(gauss, bin_centres, n, p0=p0, sigma=sigma_n, absolute_sigma=True)
x = np.arange(100, 300, 0.5)
fit = gauss(x, *popt)
P.plot(x, fit, 'r--')
</code></pre>
<p>Now, this fit (when it doesn't fail) does consider the y-errors <code>sigma_n</code>, but I haven't found a way to make it consider <code>sigma_x</code>. I scanned a couple of threads on the scipy mailing list and found out how to use the <code>absolute_sigma</code> value and a post on Stackoverflow about <a href="https://stackoverflow.com/questions/19116519/scipy-optimize-curvefit-asymmetric-error-in-fit">asymmetrical errors</a>, but nothing about errors in both directions. Is it possible to achieve?</p> | 26,085,136 | 1 | 3 | null | 2014-09-26 11:45:16.497 UTC | 17 | 2015-03-19 17:19:52.173 UTC | 2017-05-23 12:08:43.78 UTC | null | -1 | null | 2,525,159 | null | 1 | 20 | python|numpy|scipy|curve-fitting | 29,240 | <p><code>scipy.optmize.curve_fit</code> uses standard non-linear least squares optimization and therefore only minimizes the deviation in the response variables. If you want to have an error in the independent variable to be considered you can try <code>scipy.odr</code> which uses orthogonal distance regression. As its name suggests it minimizes in both independent and dependent variables.</p>
<p>Have a look at the sample below. The <code>fit_type</code> parameter determines whether <code>scipy.odr</code> does full ODR (<code>fit_type=0</code>) or least squares optimization (<code>fit_type=2</code>). </p>
<p><strong>EDIT</strong></p>
<p>Although the example worked it did not make much sense, since the y data was calculated on the noisy x data, which just resulted in an unequally spaced indepenent variable. I updated the sample which now also shows how to use <code>RealData</code> which allows for specifying the standard error of the data instead of the weights.</p>
<pre><code>from scipy.odr import ODR, Model, Data, RealData
import numpy as np
from pylab import *
def func(beta, x):
y = beta[0]+beta[1]*x+beta[2]*x**3
return y
#generate data
x = np.linspace(-3,2,100)
y = func([-2.3,7.0,-4.0], x)
# add some noise
x += np.random.normal(scale=0.3, size=100)
y += np.random.normal(scale=0.1, size=100)
data = RealData(x, y, 0.3, 0.1)
model = Model(func)
odr = ODR(data, model, [1,0,0])
odr.set_job(fit_type=2)
output = odr.run()
xn = np.linspace(-3,2,50)
yn = func(output.beta, xn)
hold(True)
plot(x,y,'ro')
plot(xn,yn,'k-',label='leastsq')
odr.set_job(fit_type=0)
output = odr.run()
yn = func(output.beta, xn)
plot(xn,yn,'g-',label='odr')
legend(loc=0)
</code></pre>
<p><img src="https://i.stack.imgur.com/JK9xX.png" alt="fit to noisy data"></p> |
26,398,020 | When assigning attributes, you must pass a hash as an argument | <p>I am following Agile Web Development with Rails 4. Chapter Cart 9 Cart Creation. When I want to update a cart, I get the following Error Notification: When assigning attributes, you must pass a hash as an arguments. CartController#update.</p>
<pre><code>class CartsController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:show, :edit, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
def index
@carts = Cart.all
end
def show
end
def new
@cart = Cart.new
end
def edit
end
def create
@cart = Cart.new(cart_params)
respond_to do |format|
if @cart.save
format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
format.json { render :show, status: :created, location: @cart }
else
format.html { render :new }
format.json { render json: @cart.errors, status: :unprocessable_entity }
end
end
end
def update
@cart = Cart.find(params[:id])
respond_to do |format|
if @cart.update_attributes(params[:cart])
format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }
format.json { render :show, status: :ok, location: @cart }
else
format.html { render :edit }
format.json { render json: @cart.errors, status: :unprocessable_entity }
end
end
end
def destroy
@cart.destroy if @cart.id == session[:card_id]
session[:card_id] = nil
respond_to do |format|
format.html { redirect_to store_url, notice: 'Your cart is currently empty.' }
format.json { head :no_content }
end
end
private
def set_cart
@cart = Cart.find(params[:id])
end
def cart_params
params[:cart]
end
def invalid_cart
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to store_url, notice: 'Invalid cart'
end
end
</code></pre> | 26,398,586 | 2 | 3 | null | 2014-10-16 06:55:43.337 UTC | 2 | 2014-10-16 07:55:45.533 UTC | 2014-10-16 07:23:19.43 UTC | null | 1,144,203 | null | 3,332,378 | null | 1 | 18 | ruby-on-rails | 43,925 | <p>Your params is probably an instance of <a href="http://api.rubyonrails.org/classes/ActionController/Parameters.html">ActionController::Parameters</a></p>
<p>If so, you need to permit the attributes you want to use, like so:</p>
<pre><code>def cart_params
params.require(:cart).permit(:attribute1, :attribute2, :attribute3)
end
</code></pre> |
23,409,610 | How to use default iOS images? | <p>I know how to use images in iOS application. But I don't know how to use default images like share or bookmark icons which are mention in developer site.</p>
<p>I want to use them. Do I need to download those set of images or those are available in Xcode?</p>
<p>If we have to download them, where I can get those icons?</p> | 23,409,966 | 5 | 4 | null | 2014-05-01 14:21:12.563 UTC | 15 | 2022-08-30 09:54:26.54 UTC | 2019-12-18 22:49:48.203 UTC | null | 1,265,393 | null | 861,204 | null | 1 | 51 | ios7|icons | 68,194 | <p>Developers haven't direct access to these images. I mean that you can't initialise image object like this: </p>
<pre><code>UIImage *image = [UIImage imageNamed:@"name_of_system_image"];
</code></pre>
<p>But you can display some of images by using system types. For example you could init <code>UIBarButtonItem</code> with system types that provides standard icons:<br>
<a href="https://developer.apple.com/library/ios/documentation/uikit/reference/UIBarButtonItem_Class/Reference/Reference.html#//apple_ref/occ/instm/UIBarButtonItem/initWithBarButtonSystemItem:target:action:" rel="noreferrer">- (id)initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem target:(id)target action:(SEL)action</a></p>
<p>Where <code>UIBarButtonSystemItem</code> provides such types: </p>
<blockquote>
<p>UIBarButtonSystemItemDone,
UIBarButtonSystemItemCancel,<br>
UIBarButtonSystemItemEdit,<br>
UIBarButtonSystemItemSave,<br>
UIBarButtonSystemItemAdd,<br>
UIBarButtonSystemItemFlexibleSpace,<br>
UIBarButtonSystemItemFixedSpace,<br>
UIBarButtonSystemItemCompose,<br>
UIBarButtonSystemItemReply,<br>
UIBarButtonSystemItemAction,<br>
UIBarButtonSystemItemOrganize,<br>
UIBarButtonSystemItemBookmarks,<br>
UIBarButtonSystemItemSearch,<br>
UIBarButtonSystemItemRefresh,<br>
UIBarButtonSystemItemStop,<br>
UIBarButtonSystemItemCamera,<br>
UIBarButtonSystemItemTrash,<br>
UIBarButtonSystemItemPlay,<br>
UIBarButtonSystemItemPause,<br>
UIBarButtonSystemItemRewind,<br>
UIBarButtonSystemItemFastForward,<br>
UIBarButtonSystemItemUndo,<br>
UIBarButtonSystemItemRedo,<br>
UIBarButtonSystemItemPageCurl</p>
</blockquote> |
51,836,634 | Readonly struct vs classes | <p>Assuming you only have immutable types
and you have all your code up to date to C# 7.3 and your methods are using the <code>in</code> keyword for inputs</p>
<p>Why would you ever use a class instead of a readonly struct?</p>
<p>The downside of using structs was that copying was expensive, but assuming you prevent any copy (defensive compiler copy or expressed by code), readonly structs allow you to only copy the reference (as classes do) and avoid heap allocation and pressure on the garbage collector.</p>
<p>Excluding special cases (which I guess it could be a very large object that won't fit on the stack) would you use readonly struct as first choice normally?</p>
<p>The case I am interested in is where they are used as data containers.</p> | 51,836,759 | 1 | 10 | null | 2018-08-14 08:07:33.677 UTC | 5 | 2018-08-14 11:51:11.603 UTC | 2018-08-14 09:13:11.677 UTC | null | 4,388,177 | null | 4,388,177 | null | 1 | 36 | c#|.net | 5,484 | <p>structs should not be looked on as "cheap objects"; they have similar feature sets that are overlapping in some areas and disjoint in others. For example:</p>
<ul>
<li>structs can't participate in polymorphism</li>
<li>you can't treat a struct as an instance of an interface without boxing it (caveat: "constrained call", but that only works in some scenarios)</li>
<li>a lot of library APIs <em>won't work well</em> (or possibly at all) with structs - they expect mutable POCOs; you'll <em>probably</em> want to use a library to get data from a database, serialize it, or render it in a UI - all of these things choke a bit with structs</li>
<li>structs don't work well with some patterns, such as tree or sibling relationships (a <code>Foo</code> can't contain a <code>Foo</code> if it is a struct) - there are others</li>
<li>structs, and immutable types generally, can be awkward to work with</li>
</ul>
<p>Also, note that until very recently ("ref returns" and "ref locals") it was very hard to achieve some parts of "readonly structs allow you to only copy the reference"; this is now much simpler.</p>
<p>But frankly, in most scenarios POCOs are <em>just easier to work with</em>, and are fine for most application-code scenarios.</p>
<p>There are certainly times when structs are an amazing choice. It just isn't <em>every time</em>. I <em>would</em> however, support the notion that if you're going to use a <code>struct</code>, it should be either a <code>readonly struct</code> (by default) or a <code>ref struct</code> (if you know why you're doing it); mutable non-<code>ref</code> structs are a recipe for pain.</p> |
4,882,837 | Access columns of a table by index instead of name in SQL Server stored procedure | <p>Is there a way to access columns by their index within a stored procedure in SQL Server?</p>
<p>The purpose is to compute lots of columns. I was reading about cursors, but I do not know how to apply them.</p>
<p>Let me explain my problem:</p>
<p>I have a row like:</p>
<pre><code>field_1 field_2 field_3 field_4 ...field_d Sfield_1 Sfield_2 Sfield_3...Sfield_n
1 2 3 4 d 10 20 30 n
</code></pre>
<p>I need to compute something like <code>(field_1*field1) - (Sfield_1* Sfiled_1) / more...</code></p>
<p>So the result is stored in a table column d times.</p>
<p>So the result is a <code>d column * d row</code> table.</p>
<p>As the number of columns is variable, I was considering making dynamic SQL, getting the names of columns in a string and splitting the ones I need, but this approach makes the problem harder. I thought getting the column number by index could make life easier.</p> | 4,883,109 | 3 | 1 | null | 2011-02-03 05:33:06.66 UTC | 1 | 2016-10-27 08:40:21.563 UTC | 2011-03-09 00:44:22.023 UTC | null | 496,830 | null | 265,519 | null | 1 | 8 | sql|sql-server|tsql|sql-server-2008|ordinal | 61,799 | <p>First, as <a href="https://stackoverflow.com/users/135152/omg-ponies">OMG Ponies</a> stated, you cannot reference columns by their ordinal position. This is not an accident. The SQL specification is not built for dynamic schema either in DDL or DML.</p>
<p>Given that, I have to wonder why you have your data structured as you do. A sign of a mismatch between schema and the problem domain rears itself when you try to extract information. When queries are incredibly cumbersome to write, it is an indication that the schema does not properly model the domain for which it was designed. </p>
<p>However, be that as it may, given what you have told us, an alternate solution would be something like the following: (I'm assuming that <code>field_1*field1</code> was meant to be <code>field_1 * field_1</code> or <code>field_1</code> squared or <code>Power( field_1, 2 )</code> )</p>
<pre><code>Select 1 As Sequence, field_1 As [Field], Sfield_1 As [SField], Sfiled_1 As [SFiled]
Union All Select 2, field_2, Sfield_2, Sfiled_2
...
Union All Select n, field_n, Sfield_n, Sfiled_n
</code></pre>
<p>Now your query looks like:</p>
<pre><code>With Inputs As
(
Select 1 As Sequence, field_1 As [Field], Sfield_1 As [SField], Sfiled_1 As [SFiled]
Union All Select 2, field_2, Sfield_2, Sfiled_2
....
)
, Results As
(
Select Case
When Sequence = 1 Then Power( [Field], 2 ) - ( [SField] * [SFiled] )
Else 1 / Power( [Field], 2 ) - ( [SField] * [SFiled] )
End
As Result
From Inputs
)
Select Exp( Sum( Log( Result ) ) )
From Results
</code></pre> |
25,932,761 | Fragment PopBackStack | <p>I am getting a strange problem, while using Fragments and popping back them out.</p>
<p>I have one Fragment Activity:</p>
<p>Step1: I am attaching one Fragment in the onCreate of that Activity in the Starting named Fragment A as:</p>
<p><strong>This is the onCreate of Fragment Activity</strong></p>
<pre><code>@Override
protected void onCreate(Bundle savedBundleState) {
super.onCreate(savedBundleState);
setContentView(R.layout.activity_base_new);
Fragement_Home home = new Fragement_Home();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().add(R.id.frameContent, home).addToBackStack("home").commit();
}
</code></pre>
<p>Step:2 After that I attached replaced the Fragment with the following code:</p>
<pre><code>Fragment_More moreFragment = new Fragment_More();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.frameContent, moreFragment).addToBackStack("more").commit();
</code></pre>
<p>Step 3: After that again I added one more Fragment on Fragment_More in the same way:</p>
<pre><code>Fragment_AboutRockstand termsConditions = new Fragment_AboutRockstand();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frameContent, termsConditions).addToBackStack("about_rockstand").commit();
</code></pre>
<p>and here is my Fragment's Activity onBackPressedButton Lisetener:</p>
<pre><code>@Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
Fragment f = fm.findFragmentById(R.id.frameContent);
if(fm.getBackStackEntryCount() > 1){
fm.popBackStack();
} else{
finish();
}
}
</code></pre>
<p><strong>Here is the Problem which I am getting:</strong></p>
<p>When I press back from Step 3, it gives me previous fragment successfully as described by onBackPressed, it will popbackstack and will take me to the previous Fragment. But from the Fragment_More, when I press back again, it shows me blank FRAGMENT content. It never shows the First Fragment which I had added on Step 1 in the OnCreate of the Activity.</p>
<p>Please comment. What I am doing wrong ?</p>
<p>Thanks</p> | 25,933,537 | 3 | 3 | null | 2014-09-19 11:21:23.133 UTC | 8 | 2020-02-14 08:48:48.47 UTC | null | null | null | null | 1,114,329 | null | 1 | 20 | android|android-fragments|back-stack|onbackpressed | 51,215 | <p>You should not add your first fragment to the backstack, as pressing the return key will just reverse the action you did. So if you replace a fragment and you press back, it will reverse the replace you did. But if you press back on an '<code>.add()</code>' fragmenttransaction, it will simply remove it and show you a blank page. So i think removing the first fragment from the backstack should do the trick. Try it out and let me know!</p>
<pre><code>@Override
protected void onCreate(Bundle savedBundleState) {
super.onCreate(savedBundleState);
setContentView(R.layout.activity_base_new);
Fragement_Home home = new Fragement_Home();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().add(R.id.frameContent, home).commit();
}
</code></pre>
<p><strong>EXAMPLE:</strong></p>
<p>So let's say you have two fragments called <strong>A</strong> & <strong>B</strong> </p>
<p>If you <code>.add()</code> fragment <strong>A</strong> to the page, and "<code>addToBackStack()</code>" ( = save reverse of the action ) you will have saved the REMOVE fragment <strong>A</strong> as action when you click on back.</p>
<p>If you <code>.replace()</code> fragment <strong>A</strong> by fragment <strong>B</strong>, and also "<code>addToBackStack()</code>" you will have saved the remove <strong>B</strong> and add <strong>A</strong> as action when you click on back.</p>
<p>So you see why it's not good practice to add your first fragmenttransaction to the backstack? It will just result in removing fragment <strong>A</strong> by pressing back, resulting in a blank page. Hope this is enough info.</p>
<p>Also, once you have removed the <code>addToBackStack()</code> to your first fragment, you don't need to override <code>onBackPressed()</code> because it will work how it is supposed to. It will just finish the activity when there is nothing left in the backstack without showing you that blank page first.</p> |
25,851,086 | Most useful (productive) shortcuts in Qt Creator | <p>What is the your most useful and productive keyboard shortcut in Qt Creator?</p>
<p>Following the trend of great questions asked about <a href="https://stackoverflow.com/questions/1266862/most-useful-shortcut-in-eclipse-cdt">Eclipse CDT</a>, <a href="https://stackoverflow.com/questions/1218390/what-is-your-most-productive-shortcut-with-vim">vim</a>, <a href="https://stackoverflow.com/questions/294167/what-are-the-most-useful-intellij-idea-keyboard-shortcuts">Intellij IDEA</a>.</p> | 25,851,104 | 2 | 3 | null | 2014-09-15 15:02:54.867 UTC | 8 | 2016-07-14 15:32:36.55 UTC | 2017-05-23 10:29:17.767 UTC | null | -1 | null | 243,912 | null | 1 | 19 | c++|qt|keyboard-shortcuts|qt-creator | 11,056 | <p>Comment/uncomment lines (select text and press). With this shortcut you can simply comment very large piece of code and uncomment it in future:</p>
<p><kbd>Ctrl</kbd> + <kbd>/</kbd></p>
<p>Autocomplete:</p>
<p><kbd>Ctrl</kbd> + <kbd>Space</kbd></p>
<p>History of clipboard. You get popup menu with all text which you pasted in Qt Creator and if you choose something and press Enter you paste this formatted text into your code</p>
<p><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>V</kbd></p> |
60,120,909 | Axios 400 Bad request in React | <p>I have read every issue on here regarding Axios 400 bad request and I can't find a solution. I have a function I am calling during useEffect that firstly gets data from my API and then later based on other factors may need to POST back to the API. </p>
<p>the GET call works perfect, but the POST call keeps failing. </p>
<pre><code>const home = match.homeTeam.team_name
const homeScore = null
const away = match.awayTeam.team_name
const awayScore = null
const gameID = match.fixture_id
const result = ""
const points = null
const teamName = userInfo.state.teamName
const date = match.event_date
const status = match.statusShort
const realHomeScore = null
const realAwayScore = null
const homeLogo = match.homeTeam.logo
const awayLogo = match.awayTeam.logo
axios.post('/picks/add/', { home, homeScore, away, awayScore, gameID, result, points, teamName, date, status, realHomeScore, realAwayScore, homeLogo, awayLogo })
.then((result) => {
console.log(result.data);
})
.catch((error) => {
console.log(error);
})
</code></pre>
<p>I have checked my payload in Network and it's sending exactly what I want. </p>
<p>I get the following error message in my Catch:</p>
<pre><code>Error: Request failed with status code 400
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
</code></pre>
<p>The route works fine in Postman, and the POSTS I make in there match up exactly with the payload in my requests on the web. But for some reason they fail.</p>
<p>Does this have to do with making two requests to the same API within the same function? My first request is in an Await so it runs and finishes before the rest of the function goes. </p>
<p>Any input would be greatly appreciated, thanks!</p> | 60,121,117 | 1 | 4 | null | 2020-02-07 20:51:42.707 UTC | 4 | 2021-10-08 14:26:21.917 UTC | null | null | null | null | 10,189,694 | null | 1 | 9 | node.js|reactjs|express|mongoose|axios | 50,007 | <p>You could <code>console.log(error.response)</code> in your catch block to get a more human-readable object. </p>
<p>Edit: <code>axios</code> errors come in three types: <code>message</code>, <code>request</code> and <code>response</code>. To make sure you are handling all possible errors, you could use a conditional block:</p>
<pre><code>if (error.response){
//do something
}else if(error.request){
//do something else
}else if(error.message){
//do something other than the other two
}
</code></pre> |
18,623,069 | Excel - Conditional Formatting - Cell not blank and equals 0 | <p>I'm trying to check if a cell is:</p>
<ol>
<li>blank, and if false (not blank) </li>
<li><p>If value equals 0. I have tried:</p>
<p>=IF( NOT( ISBLANK($D:$D) ) & $D:$D=0 ,TRUE,FALSE)</p>
<p>=IF( AND( NOT( ISBLANK($D:$D) ),$D:$D=0) ,TRUE,FALSE)</p></li>
</ol>
<p>I am use <strong>Excel 2013</strong> with <em>Conditional Formatting</em> rule: <strong>Use a formula to determine which cells to format</strong> > <strong>Format values where this formula is true</strong></p>
<p>What am I doing wrong? The problem is, the <code>IF($D:$D=0)</code> recognises cells with value <strong>0</strong> and those which are <strong>blank</strong> as <em>true</em>. I only want it to recognise 0 values. Not blank.</p> | 18,623,206 | 5 | 0 | null | 2013-09-04 20:20:56.427 UTC | 1 | 2017-06-08 06:57:01.637 UTC | 2013-09-04 23:12:42.71 UTC | null | 2,232,869 | null | 2,232,869 | null | 1 | 13 | excel|formatting|conditional|formula | 61,261 | <p>I think this is what you're looking for:</p>
<pre><code>=AND(COUNTBLANK($D1)=0,$D1=0)
</code></pre>
<p>Note that when you apply it to the whole column, each cell will only look at its respective row. You'll want to keep the reference of $D1 instead of using $D:$D</p> |
27,642,016 | Execute code in Launch Screen | <p>Xcode allows to create launch screen in <code>.xib</code> files via Interface Builder. Is it possible to execute some code with the xib, just like in usual view controllers? It would be great if we can set different text/images/etc while app launching. </p> | 27,642,160 | 4 | 6 | null | 2014-12-24 20:45:26.403 UTC | 10 | 2020-09-30 07:05:37.683 UTC | 2014-12-24 21:22:57.09 UTC | null | 1,104,384 | null | 2,894,363 | null | 1 | 34 | ios|xcode|user-interface|xib | 19,814 | <p>No, it's not possible.</p>
<p>When launch screen is being displayed your app will be in loading state.</p>
<p>Even the <code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions</code> will not be completely executed while the launch screen is displayed.</p>
<p>So it's clear that, you don't have any access to your app and so at this point you can't execute any code.</p> |
15,112,125 | How to test multiple variables for equality against a single value? | <p>I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:</p>
<pre><code>x = 0
y = 1
z = 3
mylist = []
if x or y or z == 0:
mylist.append("c")
if x or y or z == 1:
mylist.append("d")
if x or y or z == 2:
mylist.append("e")
if x or y or z == 3:
mylist.append("f")
</code></pre>
<p>which would return a list of:</p>
<pre><code>["c", "d", "f"]
</code></pre> | 15,112,149 | 30 | 8 | null | 2013-02-27 12:26:23.243 UTC | 181 | 2022-07-18 23:51:34.923 UTC | 2022-05-22 19:22:13.967 UTC | null | 365,102 | null | 1,877,442 | null | 1 | 805 | python|if-statement|comparison|match|boolean-logic | 463,006 | <p>You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:</p>
<pre><code>if x == 1 or y == 1 or z == 1:
</code></pre>
<p><code>x</code> and <code>y</code> are otherwise evaluated on their own (<code>False</code> if <code>0</code>, <code>True</code> otherwise).</p>
<p>You can shorten that using a containment test against <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="noreferrer">a tuple</a>:</p>
<pre><code>if 1 in (x, y, z):
</code></pre>
<p>or better still:</p>
<pre><code>if 1 in {x, y, z}:
</code></pre>
<p>using <a href="https://docs.python.org/3/tutorial/datastructures.html#sets" rel="noreferrer">a <code>set</code></a> to take advantage of the constant-cost membership test (i.e. <code>in</code> takes a fixed amount of time whatever the left-hand operand is).</p>
<h3>Explanation</h3>
<p>When you use <code>or</code>, python sees each side of the operator as <em>separate</em> expressions. The expression <code>x or y == 1</code> is treated as first a boolean test for <code>x</code>, then if that is False, the expression <code>y == 1</code> is tested.</p>
<p>This is due to <a href="http://docs.python.org/3/reference/expressions.html#operator-precedence" rel="noreferrer">operator precedence</a>. The <code>or</code> operator has a lower precedence than the <code>==</code> test, so the latter is evaluated <em>first</em>.</p>
<p>However, even if this were <em>not</em> the case, and the expression <code>x or y or z == 1</code> was actually interpreted as <code>(x or y or z) == 1</code> instead, this would still not do what you expect it to do.</p>
<p><code>x or y or z</code> would evaluate to the first argument that is 'truthy', e.g. not <code>False</code>, numeric 0 or empty (see <a href="http://docs.python.org/3/reference/expressions.html#boolean-operations" rel="noreferrer">boolean expressions</a> for details on what Python considers false in a boolean context).</p>
<p>So for the values <code>x = 2; y = 1; z = 0</code>, <code>x or y or z</code> would resolve to <code>2</code>, because that is the first true-like value in the arguments. Then <code>2 == 1</code> would be <code>False</code>, even though <code>y == 1</code> would be <code>True</code>.</p>
<p>The same would apply to the inverse; testing multiple values against a single variable; <code>x == 1 or 2 or 3</code> would fail for the same reasons. Use <code>x == 1 or x == 2 or x == 3</code> or <code>x in {1, 2, 3}</code>.</p> |
15,454,995 | PopupMenu with icons | <p>Of course we are dealing here with SDK 11 and above.</p>
<p>I intend to do something similar to this:
<img src="https://i.stack.imgur.com/axspH.jpg" alt="enter image description here"></p>
<p>Next to each <strong>item</strong> in that <code>PopupMenu</code>, I would like to place an <strong>icon</strong>.</p>
<p>I created an <code>XML</code> file and placed it in <code>/menu</code>:</p>
<pre><code><menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_one"
android:title="Sync"
android:icon="@android:drawable/ic_popup_sync"
/>
<item
android:id="@+id/action_two"
android:title="About"
android:icon="@android:drawable/ic_dialog_info"
/>
</menu>
</code></pre>
<p>As you noticed, in the xml file I am defining the icons I want, however, when the popup menu shows, it is showing them without the icons. What should I do to make those 2 icons appear?</p> | 15,455,081 | 12 | 1 | null | 2013-03-16 21:38:58.227 UTC | 35 | 2020-04-24 22:50:39.27 UTC | null | null | null | null | 1,836,670 | null | 1 | 73 | android|popupmenu | 98,951 | <p>I would implement it otherwise:</p>
<p>Create a <code>PopUpWindow</code> layout:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llSortChangePopup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/sort_popup_background"
android:orientation="vertical" >
<TextView
android:id="@+id/tvDistance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/distance"
android:layout_weight="1.0"
android:layout_marginLeft="20dp"
android:paddingTop="5dp"
android:gravity="center_vertical"
android:textColor="@color/my_darker_gray" />
<ImageView
android:layout_marginLeft="11dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sort_popup_devider"
android:contentDescription="@drawable/sort_popup_devider"/>
<TextView
android:id="@+id/tvPriority"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/priority"
android:layout_weight="1.0"
android:layout_marginLeft="20dp"
android:gravity="center_vertical"
android:clickable="true"
android:onClick="popupSortOnClick"
android:textColor="@color/my_black" />
<ImageView
android:layout_marginLeft="11dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sort_popup_devider"
android:contentDescription="@drawable/sort_popup_devider"/>
<TextView
android:id="@+id/tvTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/time"
android:layout_weight="1.0"
android:layout_marginLeft="20dp"
android:gravity="center_vertical"
android:clickable="true"
android:onClick="popupSortOnClick"
android:textColor="@color/my_black" />
<ImageView
android:layout_marginLeft="11dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sort_popup_devider"
android:contentDescription="@drawable/sort_popup_devider"/>
<TextView
android:id="@+id/tvStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/status"
android:layout_weight="1.0"
android:layout_marginLeft="20dp"
android:gravity="center_vertical"
android:textColor="@color/my_black"
android:clickable="true"
android:onClick="popupSortOnClick"
android:paddingBottom="10dp"/>
</LinearLayout>
</code></pre>
<p>and also create the <code>PopUpWindow</code> in your <code>Activity</code>: </p>
<pre><code> // The method that displays the popup.
private void showStatusPopup(final Activity context, Point p) {
// Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.llStatusChangePopup);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.status_popup_layout, null);
// Creating the PopupWindow
changeStatusPopUp = new PopupWindow(context);
changeStatusPopUp.setContentView(layout);
changeStatusPopUp.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
changeStatusPopUp.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
changeStatusPopUp.setFocusable(true);
// Some offset to align the popup a bit to the left, and a bit down, relative to button's position.
int OFFSET_X = -20;
int OFFSET_Y = 50;
//Clear the default translucent background
changeStatusPopUp.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
changeStatusPopUp.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y + OFFSET_Y);
}
</code></pre>
<p>finally pop it up <code>onClick</code> of a button or anything else:</p>
<pre><code> imTaskStatusButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
int[] location = new int[2];
currentRowId = position;
currentRow = v;
// Get the x, y location and store it in the location[] array
// location[0] = x, location[1] = y.
v.getLocationOnScreen(location);
//Initialize the Point with x, and y positions
point = new Point();
point.x = location[0];
point.y = location[1];
showStatusPopup(TasksListActivity.this, point);
}
});
</code></pre>
<p>A Good example for <code>PopUpWindow</code>:</p>
<p><a href="http://androidresearch.wordpress.com/2012/05/06/how-to-create-popups-in-android/" rel="noreferrer">http://androidresearch.wordpress.com/2012/05/06/how-to-create-popups-in-android/</a></p> |
15,439,853 | Get local href value from anchor (a) tag | <p>I have an anchor tag that has a local href value, and a JavaScript function that uses the href value but directs it to a slightly different place than it would normally go. The tag looks like</p>
<pre><code><a onclick="return follow(this);" href="sec/IF00.html"></a>
</code></pre>
<p>and a JavaScript function that looks like</p>
<pre><code>baseURL = 'http://www.someotherdomain.com/';
function follow(item) {
location.href = baseURL + item.href;
}
</code></pre>
<p>I would expect that <code>item.href</code> would just return a short string of "sec/IF00.html", but instead it returns the full href, "http://www.thecurrentdomain.com/sec/IF00.html". Is there a way that I can pull out just the short href as put in the anchor <code><a></code> tag? Or do I lose that by natural HTML behavior?</p>
<p>I suppose I could use a string manipulation to do this, but it gets tricky because my local page may actually be "http://www.thecurrentdomain.com/somedir/somepath/sec/IF00.html", and my href field may or may not have a subdirectory in it (for ex <code>href="page.html"</code> vs. <code>href="sub/page.html"</code>), so I cannot always just remove every thing before the last slash.</p>
<p>You may wonder why I am requesting this, and it is because it will just make the page a lot cleaner. If it is not possible to get just the short href (as put in the anchor <code><a></code> tag), then I could probably just insert an extra field into the tag, like <code>link="sec/IF00.html"</code>, but again, that would be a little messier.</p> | 15,439,946 | 6 | 0 | null | 2013-03-15 18:39:23.61 UTC | 41 | 2020-10-31 06:15:15.417 UTC | null | null | null | null | 1,733,377 | null | 1 | 188 | javascript|html|href | 407,192 | <p>The below code gets the full path, where the anchor points:</p>
<pre><code>document.getElementById("aaa").href; // http://example.com/sec/IF00.html
</code></pre>
<p>while the one below gets the value of the <code>href</code> attribute:</p>
<pre><code>document.getElementById("aaa").getAttribute("href"); // sec/IF00.html
</code></pre> |
23,765,821 | java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet error | <p>Not sure why am I getting this error. Lots of similar questions here but none have worked for me till now.</p>
<p>My ivy file is</p>
<pre><code><ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
<info
organisation=""
module="knoxWeb"
status="integration">
</info>
<dependencies>
<dependency org="org.springframework" name="spring-core" rev="4.0.3.RELEASE"/>
<dependency org="org.springframework" name="spring-context" rev="4.0.3.RELEASE"/>
<dependency org="org.springframework" name="spring-web" rev="4.0.3.RELEASE"/>
<dependency org="org.springframework" name="spring-webmvc" rev="4.0.3.RELEASE"/>
<dependency org="org.springframework" name="spring-beans" rev="4.0.3.RELEASE"/>
</dependencies>
</ivy-module>
</code></pre>
<p>and my web.xml is</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Knox Web Interface</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
</code></pre>
<p>I have resolved ivy. Still getting the error. Also i can see the Class in my eclipse.</p>
<p><img src="https://i.stack.imgur.com/lPhJg.png" alt="enter image description here"></p>
<p>I am really stuck at this. Any help or suggestion is appreciated. </p>
<p>PS : I also tried adding <code>< dependency org="org.springframework" name="spring" rev="2.5.6"/></code> but ivy does not resolve. I get</p>
<pre><code>Some projects fail to be resolved
Impossible to resolve dependencies of #TestWebProject;working@BLT430LT3201C
download failed: com.oracle.toplink#toplink;10.1.3!toplink.jar
unresolved dependency: com.oracle#oc4j;1.0: not found
unresolved dependency: com.oracle#toplink-essentials;2.41: not found
unresolved dependency: javax.ejb#ejb;3.0: not found
download failed: com.bea.wlplatform#commonj-twm;1.1!commonj-twm.jar
unresolved dependency: jexcelapi#jxl;2.6.6: not found
download failed: javax.jms#jms;1.1!jms.jar
download failed: javax.faces#jsf-api;1.1!jsf-api.jar
download failed: javax.resource#connector;1.0!connector.jar
</code></pre>
<p>Not sure if this has anything to do with above problem. I am searching <a href="http://mvnrepository.com/artifact/org.springframework" rel="nofollow noreferrer">http://mvnrepository.com/artifact/org.springframework</a> for all dependency info.</p>
<p>My project structure is</p>
<p><img src="https://i.stack.imgur.com/7z1ML.png" alt="enter image description here"></p>
<p>WEB-INF/lib directory is empty.</p>
<p>Source : <a href="http://opensourceforgeeks.blogspot.in/2014/05/javalangclassnotfoundexception.html" rel="nofollow noreferrer">http://opensourceforgeeks.blogspot.in/2014/05/javalangclassnotfoundexception.html</a></p> | 23,766,404 | 1 | 8 | null | 2014-05-20 16:58:49.36 UTC | 4 | 2017-11-19 06:07:21.143 UTC | 2017-11-19 06:07:21.143 UTC | null | 2,396,539 | null | 2,396,539 | null | 1 | 6 | java|eclipse|spring|spring-mvc|ivy | 51,876 | <p>Thanks a lot guys for your valuable comments. You are all right. Jar files must be in <code>WEB-INF/lib</code>. Or you can tell Eclipse that it can find the jars in additional location and not just <code>WEB-INF/lib</code>.</p>
<p>How do we do that?</p>
<ul>
<li>Right click the project and select properties. Now go to Deployment Assembly.</li>
</ul>
<p><img src="https://i.stack.imgur.com/eEozA.png" alt="enter image description here"></p>
<ul>
<li>Now select Add and select Java build path entries.</li>
</ul>
<p><img src="https://i.stack.imgur.com/oySvk.png" alt="enter image description here"></p>
<ul>
<li>Ivy option is automatically populated. Select that.</li>
</ul>
<p><img src="https://i.stack.imgur.com/PoOwB.png" alt="enter image description here"></p>
<ul>
<li>And you are done.Select Apply and ok. Classnotfound Exception vanishes. </li>
</ul>
<p><img src="https://i.stack.imgur.com/kQUCn.png" alt="enter image description here"></p> |
8,771,413 | Overlay Color Blend in OpenGL ES / iOS / Cocos2d | <p>I'm trying to apply BlendModes to a GreyScale image in order to have reusable static resources </p>
<p>I've been searching in the internet for hours and I did my own tests but I didn't find any solution.</p>
<p>I started with this image:</p>
<p><img src="https://i.stack.imgur.com/rLWJe.png" alt="enter image description here"></p>
<p>And the basic idea was to draw a rectangle over it in a certain color and apply a blending mode to the image only where the alpha is 1.0</p>
<p>Here is the Code (this is part of a Cocos2d project although I think it can be applied to generic OGL ES):</p>
<pre><code>-(void)draw
{
[super draw];
glBlendColor(0,255,0,255);
glBlendFunc(GL_ZERO, GL_SRC_COLOR);
glColor4ub(255, 0, 255, 255);
glLineWidth(2);
CGPoint vertices2[] = { ccp(0,100), ccp(100,100), ccp(100,0) };
[ DrawingHelper drawPolygonWithPoints:vertices2 points:3 closePolygon:YES];
}
</code></pre>
<p>*Draw helper is the logic to draw the triangle.</p>
<pre><code>+(void)drawPolygonWithPoints:(CGPoint *)poli points:(int)points closePolygon:(BOOL)closePolygon
{
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, poli);
if( closePolygon )
glDrawArrays(GL_TRIANGLE_FAN, 0, points);
else
glDrawArrays(GL_LINE_STRIP, 0, points);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);
}
</code></pre>
<p>And here some results:</p>
<p><img src="https://i.stack.imgur.com/Luqjx.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/fgSIW.png" alt="enter image description here"></p>
<p>As you can see is a good approximation but this two images has error: </p>
<p><strong>OpenGL error 0x0502 in -[EAGLView swapBuffers]</strong></p>
<p>My Questions are:</p>
<ol>
<li>How can I remove or fix this error?</li>
<li>How can keep only the alpha of the image (shield) and apply the blend overlay color?</li>
</ol>
<p>[Update]This is an example of what I would like (with the correct blends):</p>
<p><img src="https://i.stack.imgur.com/ow3IC.png" alt="enter image description here"></p> | 8,771,768 | 1 | 4 | null | 2012-01-07 17:01:49.573 UTC | 9 | 2012-01-08 03:55:09.3 UTC | 2012-01-08 03:55:09.3 UTC | null | 44,729 | null | 210,631 | null | 1 | 7 | iphone|ios|opengl-es|cocos2d-iphone | 9,919 | <blockquote>
<p>apply a blending mode to the image only where the alpha is 1.0</p>
</blockquote>
<p>This sounds like an application for alpha testing. Only that I'd first draw the rectangle and then make the alpha test fail for equal 1.0 (or greater than 0.99 to allow for some margin). This doesn't require blending.</p>
<hr>
<h3>Edit for updated question</h3>
<p>Desired results:</p>
<blockquote>
<p><img src="https://i.stack.imgur.com/whPfJ.png" alt="enter image description here"></p>
</blockquote>
<p>I think you mixed up Multiply and Overlay captions up there.</p>
<p>In all those cases this is done using either </p>
<ul>
<li><code>glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GEQUAL, 0.995);</code> // not using 1.0 for some margin</li>
</ul>
<p>or</p>
<ul>
<li><code>glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);</code></li>
</ul>
<p>The effects are not created by setting the blend function or mode, but by texture environment or shader.</p>
<p>The "<em>Overlay</em>" (actually multiply) effect corresponds to the GL_MODULATE texture environment mode. Or in terms of a shader <code>gl_FragColor = texture2D(...) * color;</code>.</p>
<p>"<em>Lighten</em>" is <code>min(texture2D(...), color);</code></p>
<p>"<em>Multiply</em>" (actually overlay) is <code>gl_FragColor = 1. - (1.-color*texture2D(...))*(1.-color);</code></p>
<p>"<em>Soft Light</em>" is <code>gl_FragColor = (1. - (1.-texture2D(...))*(1.-color))*k + b;</code> (k and b choosen parameters).</p> |
8,735,798 | Title case a string containing one or more last names while handling names with apostrophes | <p>I want to standardize a user-supplied string. I'd like the first letter to be capitalized for the name and if they have entered two last names, then capitalize the first and second names. For example, if someone enters:</p>
<pre><code>marriedname maidenname
</code></pre>
<p>It would convert this to <code>Marriedname Maidenname</code> and so on if there is more than two names.</p>
<p>The other scenario is when someone has an apostrophe in their name. If someone enters:</p>
<pre><code>o'connell
</code></pre>
<p>This would need to convert to <code>O'Connell</code>.</p>
<p>I was using:</p>
<pre><code>ucfirst(strtolower($last_name));
</code></pre>
<p>However, as you can tell that wouldn't work for all the scenarios.</p> | 8,735,824 | 11 | 5 | null | 2012-01-04 23:50:44.503 UTC | 11 | 2022-09-15 06:46:24.387 UTC | 2021-08-13 07:56:02.22 UTC | null | 2,943,403 | null | 1,048,676 | null | 1 | 47 | php|string|title-case|humanize|ucfirst | 85,037 | <p>This will capitalize all word's first letters, and letters immediately after an apostrophe. It will make all other letters lowercase. It should work for you:</p>
<pre><code>str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($last_name))));
</code></pre> |
31,039,513 | How can I skip code signing for development builds in Xcode? | <p>Whenever I build my Xcode project, after compiling all my code, it takes <em>forever</em> to finish "signing product." (I believe it's because the project includes about 200 MB of resources that need signing.) I would like to skip the code signing during development, so the build can finish faster. How can I do this?</p> | 31,985,749 | 5 | 6 | null | 2015-06-25 00:54:56.533 UTC | 10 | 2021-01-10 12:25:33.01 UTC | 2020-05-30 20:13:08.31 UTC | null | 5,175,709 | null | 1,455,016 | null | 1 | 58 | xcode|macos|code-signing|codesign|build-settings | 45,610 | <p>To turn the code signing off, go to your project and target "Build Settings", search for "Code Signing Identity" change its value to "Don't Code Sign" in both of them.</p>
<p><strong>To make this effective you need to change this value in the Project and all of the Targets separately.</strong></p> |
31,017,261 | Require User to click google's new recaptcha before form submission | <p>I am using google's new recaptcha inside my form (HTML5):
<a href="https://www.google.com/recaptcha" rel="nofollow noreferrer">https://www.google.com/recaptcha</a></p>
<p>Is there a way to check and mark recaptcha as required before form submission?
I want to validate this on client-side instead of server side. That way, I don't have to go back to the form and warn the user about not entering anything for the captcha.</p>
<p>Any javascript that I can use to check whether users enter anything in recaptcha?</p> | 31,019,293 | 6 | 9 | null | 2015-06-24 03:47:43.893 UTC | 6 | 2022-03-31 17:34:36.17 UTC | 2022-03-31 15:35:49.263 UTC | null | 16,496,357 | null | 1,030,436 | null | 1 | 24 | javascript|php|forms|recaptcha | 41,592 | <p>You can check the textarea field with id <code>g-recaptcha-response</code>. You can do as following:</p>
<pre><code>$("form").submit(function(event) {
var recaptcha = $("#g-recaptcha-response").val();
if (recaptcha === "") {
event.preventDefault();
alert("Please check the recaptcha");
}
});
</code></pre>
<p>Hope this helps you.</p> |
4,930,439 | Call jQuery Ajax Request Each X Minutes | <p>How can I call an Ajax Request in a specific time Period?
Should I use Timer Plugin or does jQuery have a plugin for this?</p> | 4,930,470 | 8 | 1 | null | 2011-02-08 07:04:18.063 UTC | 24 | 2021-07-31 13:43:34.63 UTC | 2015-08-11 12:01:30.663 UTC | null | 1,276,636 | null | 369,161 | null | 1 | 60 | ajax|jquery|timer | 130,997 | <p>You can use the built-in javascript setInterval.</p>
<pre><code>var ajax_call = function() {
//your jQuery ajax code
};
var interval = 1000 * 60 * X; // where X is your every X minutes
setInterval(ajax_call, interval);
</code></pre>
<p>or if you are the more terse type ...</p>
<pre><code>setInterval(function() {
//your jQuery ajax code
}, 1000 * 60 * X); // where X is your every X minutes
</code></pre> |
5,137,497 | Find the current directory and file's directory | <p>How do I determine:</p>
<ol>
<li>the current directory (where I was in the terminal when I ran the Python script), and</li>
<li>where the Python file I am executing is?</li>
</ol> | 5,137,509 | 13 | 0 | null | 2011-02-28 01:51:21.12 UTC | 593 | 2022-06-06 03:38:11.89 UTC | 2022-06-06 03:38:11.89 UTC | null | 365,102 | null | 374,797 | null | 1 | 2,802 | python|directory | 4,194,086 | <p>To get the full path to the directory a Python file is contained in, write this in that file:</p>
<pre><code>import os
dir_path = os.path.dirname(os.path.realpath(__file__))
</code></pre>
<p>(Note that the incantation above won't work if you've already used <code>os.chdir()</code> to change your current working directory, since the value of the <code>__file__</code> constant is relative to the current working directory and is not changed by an <code>os.chdir()</code> call.)</p>
<hr>
<p>To get the current working directory use </p>
<pre><code>import os
cwd = os.getcwd()
</code></pre>
<hr>
<p>Documentation references for the modules, constants and functions used above:</p>
<ul>
<li>The <a href="https://docs.python.org/library/os.html"><code>os</code></a> and <a href="https://docs.python.org/library/os.path.html#module-os.path"><code>os.path</code></a> modules.</li>
<li>The <a href="https://docs.python.org/reference/datamodel.html"><code>__file__</code></a> constant</li>
<li><a href="https://docs.python.org/library/os.path.html#os.path.realpath"><code>os.path.realpath(path)</code></a> (returns <em>"the canonical path of the specified filename, eliminating any symbolic links encountered in the path"</em>)</li>
<li><a href="https://docs.python.org/library/os.path.html#os.path.dirname"><code>os.path.dirname(path)</code></a> (returns <em>"the directory name of pathname <code>path</code>"</em>)</li>
<li><a href="https://docs.python.org/library/os.html#os.getcwd"><code>os.getcwd()</code></a> (returns <em>"a string representing the current working directory"</em>)</li>
<li><a href="https://docs.python.org/library/os.html#os.chdir"><code>os.chdir(path)</code></a> (<em>"change the current working directory to <code>path</code>"</em>)</li>
</ul> |
12,176,170 | How can I click on a button using Selenium WebDriver with Java? | <p>The following is the HTML code for button:</p>
<pre><code><span>
<button class="buttonLargeAlt" onclick="javascript:submitCheckout(this.form);"type="submit">Checkout</button>
</span>
</code></pre>
<p>I tried <code>driver.findElement(By.xpath("//span[contains(.,'Checkout')]")).click();</code></p>
<p>It is not working...</p>
<p>Any other ideas? There are 2 buttons with same name on the page.</p> | 12,180,694 | 6 | 0 | null | 2012-08-29 10:45:23.41 UTC | null | 2020-09-15 12:57:56.49 UTC | 2013-11-28 09:40:12.17 UTC | null | 617,450 | null | 1,629,833 | null | 1 | 6 | java|selenium|selenium-webdriver|automated-tests | 83,379 | <p>Try: </p>
<pre><code>//span/button[text()='Checkout' and @class='buttonLargeAlt']
</code></pre>
<p>or</p>
<pre><code>//span/button[text()='Checkout'][1]
</code></pre>
<p>Also, if you know which of the 2 buttons you need to click, you can try:</p>
<pre><code>//span/button[text()='Checkout'][1]
</code></pre>
<p>Where <code>[1]</code> is the first button found with a text of <code>'Checkout'</code></p> |
12,367,571 | How to get Session Id In C# | <p>what is the correct way to get session id in C#</p>
<pre><code>String sessionId ;
sessionId = Session.SessionID;
</code></pre>
<p>or</p>
<pre><code> string sessionId = Request["http_cookie"];
sessionId = sessionId.Substring(sessionId.Length - 24);
</code></pre>
<p>Actually i am totally new to C# and just jumped in a project where i find the second code and by Google i found the first code so anyone please tell me what is the actual code to be used</p> | 12,367,642 | 1 | 1 | null | 2012-09-11 10:20:14.693 UTC | 1 | 2012-09-11 10:26:27.15 UTC | 2012-09-11 10:23:10.583 UTC | null | 336,648 | null | 478,076 | null | 1 | 24 | c#|sessionid | 83,830 | <p>correct way is: </p>
<pre><code>HttpContext.Current.Session.SessionID
</code></pre> |
12,426,810 | eclipse won't start - no java virtual machine was found | <p>Eclipse was running fine yesterday (and has been since I installed it about a year ago). Now all the sudden I'm getting the following error on startup:</p>
<pre><code>"A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found after searching the following locations:
C:\Program Files\eclipse\jre\bin\javaw.exe
javaw.exe in your current PATH"
</code></pre>
<p>I have not changed anyhing Eclipse/Java related on my machine but a Windows update was applied to my machine yesterday, so maybe that has something to do with it (but I don't see anything that would affect Java). I've looked at all the other posts about adding something to your PATH or adding the -vm option to the Eclipse ini (couldn't get this to work) or copying the jre folder to eclipse\jre (this worked but doesn't seem like a good long term solution). So I'm really trying to figure out how to get things back to the "default" setup without messing stuff up.</p>
<p>I'm running <code>Windows 7, Eclipse Helios and Java 1.6.0_26.</code></p> | 12,426,948 | 23 | 4 | null | 2012-09-14 14:44:48.27 UTC | 22 | 2022-06-28 16:22:40.023 UTC | 2012-09-14 15:31:00.02 UTC | null | 24,396 | null | 1,090,009 | null | 1 | 103 | eclipse|java | 446,306 | <p>Two ways to work around this .</p>
<ul>
<li><p><strong>Recommended way</strong> : In your <code>eclipse.ini</code> file make sure you are
pointing -vm to your jdk installation. More on this <a href="http://wiki.eclipse.org/Eclipse.ini#-vm_value:_Windows_Example" rel="noreferrer">here</a>. Make sure to add <code>-vm</code> before the <code>-vmargs</code> section.</p></li>
<li><p>Pass in the <code>vm</code> flag from command line. <a href="http://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F#Find_the_JVM" rel="noreferrer">http://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F#Find_the_JVM</a></p></li>
</ul>
<p><em>Note</em> : Eclipse DOES NOT consult the JAVA_HOME environment variable.</p> |
12,514,197 | Convert a Git folder to a submodule retrospectively? | <p>Quite often it is the case that you're writing a project of some kind, and after a while it becomes clear that some component of the project is actually useful as a standalone component (a library, perhaps). If you've had that idea from early on, then there's a fair chance that most of that code is in its own folder.</p>
<p>Is there a way to convert one of the sub directories in a Git project to a submodule?</p>
<p>Ideally this would happen such that all of the code in that directory is removed from the parent project, and the submodule project is added in its place, with all the appropriate history, and such that all the parent project commits point to the correct submodule commits.</p> | 12,515,629 | 8 | 3 | null | 2012-09-20 13:55:38.693 UTC | 50 | 2022-09-23 09:42:30.423 UTC | 2020-05-23 07:03:03.827 UTC | null | 775,954 | null | 210,945 | null | 1 | 141 | git|git-submodules | 30,230 | <p>To isolate a subdirectory into its own repository, use <code>filter-branch</code> on a clone of the original repository:</p>
<pre><code>git clone <your_project> <your_submodule>
cd <your_submodule>
git filter-branch --subdirectory-filter 'path/to/your/submodule' --prune-empty -- --all
</code></pre>
<p>It's then nothing more than deleting your original directory and adding the submodule to your parent project.</p> |
18,899,011 | Rails 4 migration: how to reorder columns | <p>I learned that <code>add_column</code> has an <code>:after</code> option to set where the column gets inserted. Too bad I learned about it :after adding a bunch.</p>
<p>How can I write a migration to simply reorder columns? </p> | 18,900,396 | 1 | 7 | null | 2013-09-19 15:33:35.063 UTC | 11 | 2020-10-30 10:39:13.197 UTC | 2013-09-20 15:20:41.223 UTC | null | 1,141,918 | null | 1,141,918 | null | 1 | 42 | ruby-on-rails|ruby|migration|ruby-on-rails-4 | 16,372 | <p>When using MySQL, you can call <code>change_column</code>, but you have to repeat the column type (just copy and paste it from your other migration):</p>
<pre><code>def up
change_column :your_table, :some_column, :integer, after: :other_column
end
</code></pre>
<p>Or if you have to reorder multiple columns in one table:</p>
<pre><code>def up
change_table :your_table do |t|
t.change :some_column, :integer, after: :other_column
# ...
end
end
</code></pre>
<p><code>change_column</code> calls <code>ALTER TABLE</code> under the hood. From the MySQL <a href="http://dev.mysql.com/doc/refman/5.1/en/alter-table.html" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>You can also use <code>FIRST</code> and <code>AFTER</code> in <code>CHANGE</code> or <code>MODIFY</code> operations to
reorder columns within a table.</p>
</blockquote>
<p>Note that this approach doesn't work with PostgreSQL. (see <a href="https://wiki.postgresql.org/wiki/Alter_column_position" rel="noreferrer">Alter column positions</a>)</p> |
43,074,622 | Question Mark (?) after session variable reference - What does that mean | <p>I have had a code snippet comes to modify. In there i found this such syntax.</p>
<pre><code>Session("LightBoxID")?.ToString()
</code></pre>
<p>I didn't understand what is that Question mark <strong>(?)</strong> there means. No googling helped me about any hint</p> | 43,074,748 | 2 | 7 | null | 2017-03-28 16:09:40.98 UTC | 7 | 2021-03-30 10:27:52.637 UTC | 2017-03-28 16:46:29.473 UTC | null | 477,420 | null | 954,093 | null | 1 | 31 | c#|asp.net|vb.net | 31,353 | <p>It performs a null-check on <code>Session("LightBoxID")</code> before attempting to call <code>.ToString()</code> on it.</p>
<p>MS Docs: <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-" rel="nofollow noreferrer">Null-conditional operators <code>?.</code> and <code>?[]</code></a></p> |
24,260,717 | Does a vector assignment invalidate the `reserve`? | <p>Suppose I write</p>
<pre><code>std::vector<T> littleVector(1);
std::vector<T> bigVector;
bigVector.reserve(100);
bigVector = littleVector;
</code></pre>
<p>Does the standard say that <code>bigVector</code> will still have 100 elements reserved? Or would I experience memory reallocation if I were to <code>push_back</code> 99 elements? Perhaps it even varies between STL implementations.</p>
<p>This was previously discussed <a href="https://stackoverflow.com/questions/2663170/stdvector-capacity-after-copying">here</a> but no Standard references were given.</p> | 24,266,689 | 3 | 8 | null | 2014-06-17 09:52:07.793 UTC | 8 | 2014-06-17 14:40:11.697 UTC | 2017-05-23 12:23:12.783 UTC | null | -1 | null | 3,415,258 | null | 1 | 35 | c++|language-lawyer | 1,851 | <p>Unfortunately, the standard underspecifies behavior on allocator-aware sequence container assignment, and indeed is strictly speaking inconsistent.</p>
<p>We know (from Table 28 and from 23.2.1p7) that if <code>allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value</code> is <code>true</code> then the allocator is replaced on copy assignment. Further, from Tables 96 and 99 we find that the <em>complexity</em> of copy assignment is <em>linear</em>, and the <em>post-condition</em> on operation <code>a = t</code> is that <code>a == t</code>, i.e. (Table 96) that <code>distance(a.begin(), a.end()) == distance(t.begin(), t.end()) && equal(a.begin(), a.end(), t.begin())</code>. From 23.2.1p7, after copy assignment, if the allocator propagates, then <code>a.get_allocator() == t.get_allocator()</code>.</p>
<p>With regard to vector capacity, 23.3.6.3 <strong>[vector.capacity]</strong> has:</p>
<blockquote>
<p>5 - <em>Remarks:</em> Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to <code>reserve()</code> until the time when an insertion would make the size of the vector greater than the value of <code>capacity()</code>.</p>
</blockquote>
<p>If we take <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#341">library DR341</a> as a guide to reading the Standard:</p>
<blockquote>
<p>However, the wording of 23.3.6.3 [vector.capacity]paragraph 5 prevents the capacity of a vector being reduced, following a call to reserve(). This invalidates the idiom, as swap() is thus prevented from reducing the capacity. [...]</p>
</blockquote>
<p>DR341 was resolved by adding paragraphs into 23.3.6.3:</p>
<blockquote>
<p><code>void swap(vector<T,Allocator>& x);</code><br/>
7 - <em>Effects:</em> Exchanges the contents and <code>capacity()</code> of <code>*this</code> with that of <code>x</code>.<br/>
8 - <em>Complexity:</em> Constant time.</p>
</blockquote>
<p>The conclusion is that from the point of view of the Library committee, operations only modify <code>capacity()</code> if mentioned under 23.3.6.3. Copy assignment is not mentioned under 23.3.6.3, and thus does not modify <code>capacity()</code>. (Move assignment has the same issue, especially considering the proposed resolution to <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#2321">Library DR2321</a>.)</p>
<p>Clearly, this is a defect in the Standard, as copy assignment propagating unequal allocators <em>must</em> result in reallocation, contradicting 23.3.6.3p5.</p>
<p>We can expect and hope this defect to be resolved in favour of:</p>
<ul>
<li>non-reduced <code>capacity()</code> on non-allocator-modifying copy assignment;</li>
<li>unspecified <code>capacity()</code> on allocator-modifying copy assignment;</li>
<li>non-reduced <code>capacity()</code> on non-allocator-propagating move assignment;</li>
<li>source-container <code>capacity()</code> on allocator-propagating move assignment.</li>
</ul>
<p>However, in the current situation and until this is clarified you would do well not to depend on any particular behavior. Fortunately, there is a simple workaround that is guaranteed not to reduce <code>capacity()</code>:</p>
<pre><code>bigVector.assign(littleVector.begin(), littleVector.end());
</code></pre> |
24,305,830 | Java auto increment id | <p>I am doing some coding in Java, but it doesn't work:</p>
<pre><code>public class job
{
private static int count = 0;
private int jobID;
private String name;
private boolean isFilled;
public Job(, String title, ){
name = title;
isFilled = false;
jobID = ++count;
}
}
</code></pre>
<p>I need to auto-increment the Id when a new entry is created. </p> | 24,305,983 | 4 | 8 | null | 2014-06-19 11:46:39.81 UTC | 6 | 2014-06-19 13:48:50.633 UTC | 2014-06-19 13:48:50.633 UTC | null | 3,061,020 | null | 3,061,020 | null | 1 | 7 | java | 113,390 | <p>Try this:
</p>
<pre><code>public class Job {
private static final AtomicInteger count = new AtomicInteger(0);
private final int jobID;
private final String name;
private boolean isFilled;
public Job(String title){
name = title;
isFilled = false;
jobID = count.incrementAndGet();
}
</code></pre> |
18,994,609 | How to 'git pull' into a branch that is not the current one? | <p>When you run <code>git pull</code> on the <code>master</code> branch, it typically pulls from <code>origin/master</code>. I am in a different branch called <code>newbranch</code>, but I need to run a command that does a <code>git pull</code> from <code>origin/master</code> into <code>master</code> but I cannot run <code>git checkout</code> to change the selected branch until after the pull is complete. Is there a way to do this?</p>
<p>To give some background, the repository stores a website. I have made some changes in <code>newbranch</code> and deployed them by switching the website to <code>newbranch</code>. Now those changes have been merged upstream into the <code>master</code> branch, I am trying to switch the website back to the <code>master</code> branch as well. At this point, <code>newbranch</code> and <code>origin/master</code> are identical, but <code>master</code> is lagging behind <code>origin/master</code> and needs to be updated. The problem is, if I do it the traditional way:</p>
<pre><code>$ git checkout master
# Uh oh, production website has now reverted back to old version in master
$ git pull
# Website is now up to date again
</code></pre>
<p>I need to achieve the same as above (<code>git checkout master && git pull</code>), but without changing the working directory to an earlier revision during the process.</p> | 18,995,157 | 8 | 8 | null | 2013-09-25 01:10:19.033 UTC | 29 | 2019-08-23 12:21:06.693 UTC | 2017-01-17 12:29:49.047 UTC | null | 2,642,204 | null | 308,237 | null | 1 | 158 | git|branch|git-branch | 111,603 | <p>You've got a worktree you don't want to touch, so use another one. Clone is cheap, it's built for this.</p>
<pre><code>git fetch origin master # nice linear tree
git clone . ../wip -b master # wip's `origin/master` is my `master`
cd ../wip # .
git pull origin origin/master # merge origin's origin/master
git push origin master # job's done, turn it in.
cd ../main
rm -rf ../wip # wip was pushed here, wip's done
git checkout master # payload
</code></pre>
<p>The problem with all the other answers here is, they don't actually do the pull. If you need the merge or rebase you've got pull set up for, you need another worktree and the above procedure. Otherwise just <code>git fetch; git checkout -B master origin/master</code> will do.</p> |
11,229,986 | Get string character by index | <p>I know how to work out the index of a certain character or number in a string, but is there any predefined method I can use to give me the character at the <em>nth</em> position? So in the string "foo", if I asked for the character with index 0 it would return "f".</p>
<p>Note - in the above question, by "character" I don't mean the char data type, but a letter or number in a string. The important thing here is that I don't receive a char when the method is invoked, but a string (of length 1). And I know about the substring() method, but I was wondering if there was a neater way.</p> | 11,230,042 | 12 | 7 | null | 2012-06-27 15:37:11.237 UTC | 45 | 2022-01-23 08:30:39.267 UTC | 2022-01-23 08:30:39.267 UTC | null | 466,862 | null | 1,175,276 | null | 1 | 270 | java|string | 1,065,926 | <p>The method you're looking for is <code>charAt</code>. Here's an example:</p>
<pre><code>String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f
</code></pre>
<p>For more information, see the <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int)" rel="noreferrer">Java documentation on <code>String.charAt</code></a>. If you want another simple tutorial, <a href="https://www.tutorialspoint.com/java/java_string_charat.htm" rel="noreferrer">this one</a> or <a href="https://www.homeandlearn.co.uk/java/charAt.html" rel="noreferrer">this one</a>.</p>
<p>If you don't want the result as a <code>char</code> data type, but rather as a string, you would use the <code>Character.toString</code> method:</p>
<pre><code>String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f
</code></pre>
<p>If you want more information on the <code>Character</code> class and the <code>toString</code> method, I pulled my info from <a href="https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html#toString%28char%29" rel="noreferrer">the documentation on Character.toString</a>.</p> |
12,985,692 | How To Create Custom User Role in Wordpress | <p>I have to create a Reviewer (custom) role for users in WordPress , how can I create a custom rule ? </p> | 12,990,173 | 4 | 2 | null | 2012-10-20 05:54:15.723 UTC | 11 | 2016-09-16 18:46:32.247 UTC | 2012-10-20 16:05:32.383 UTC | null | 741,747 | null | 1,400,218 | null | 1 | 15 | wordpress | 37,726 | <p>You can use <a href="http://codex.wordpress.org/Function_Reference/add_role" rel="noreferrer">add role</a> function like</p>
<pre><code><?php add_role( $role, $display_name, $capabilities ); ?>
</code></pre>
<p>Example</p>
<pre><code>add_role('basic_contributor', 'Basic Contributor', array(
'read' => true, // True allows that capability
'edit_posts' => true,
'delete_posts' => false, // Use false to explicitly deny
));
</code></pre>
<p>Also <a href="http://camwebdesign.com/techniques/wordpress-create-custom-roles-and-capabilities/" rel="noreferrer">see this tutorial (custom rule discussed)</a> and <a href="http://www.im-web-gefunden.de/wordpress-plugins/role-manager/" rel="noreferrer"><s>this plugin too if you don't want to write any code.</s></a></p> |
12,980,648 | Map HTML to JSON | <p>I'm attempting map HTML into JSON with structure intact. Are there any libraries out there that do this or will I need to write my own? I suppose if there are no html2json libraries out there I could take an xml2json library as a start. After all, html is only a variant of xml anyway right?</p>
<p><strong>UPDATE:</strong> Okay, I should probably give an example. What I'm trying to do is the following. Parse a string of html:</p>
<pre><code><div>
<span>text</span>Text2
</div>
</code></pre>
<p>into a json object like so:</p>
<pre><code>{
"type" : "div",
"content" : [
{
"type" : "span",
"content" : [
"Text2"
]
},
"Text2"
]
}
</code></pre>
<p><strong>NOTE</strong>: In case you didn't notice the tag, I'm looking for a solution in Javascript </p> | 12,984,095 | 5 | 11 | null | 2012-10-19 18:52:35.28 UTC | 36 | 2021-12-14 16:08:15.077 UTC | 2016-03-03 18:08:56.243 UTC | null | 3,576,214 | null | 1,333,809 | null | 1 | 74 | javascript|html|json | 126,725 | <p>I just wrote this function that does what you want; try it out let me know if it doesn't work correctly for you:</p>
<pre><code>// Test with an element.
var initElement = document.getElementsByTagName("html")[0];
var json = mapDOM(initElement, true);
console.log(json);
// Test with a string.
initElement = "<div><span>text</span>Text2</div>";
json = mapDOM(initElement, true);
console.log(json);
function mapDOM(element, json) {
var treeObject = {};
// If string convert to document Node
if (typeof element === "string") {
if (window.DOMParser) {
parser = new DOMParser();
docNode = parser.parseFromString(element,"text/xml");
} else { // Microsoft strikes again
docNode = new ActiveXObject("Microsoft.XMLDOM");
docNode.async = false;
docNode.loadXML(element);
}
element = docNode.firstChild;
}
//Recursively loop through DOM elements and assign properties to object
function treeHTML(element, object) {
object["type"] = element.nodeName;
var nodeList = element.childNodes;
if (nodeList != null) {
if (nodeList.length) {
object["content"] = [];
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].nodeType == 3) {
object["content"].push(nodeList[i].nodeValue);
} else {
object["content"].push({});
treeHTML(nodeList[i], object["content"][object["content"].length -1]);
}
}
}
}
if (element.attributes != null) {
if (element.attributes.length) {
object["attributes"] = {};
for (var i = 0; i < element.attributes.length; i++) {
object["attributes"][element.attributes[i].nodeName] = element.attributes[i].nodeValue;
}
}
}
}
treeHTML(element, treeObject);
return (json) ? JSON.stringify(treeObject) : treeObject;
}
</code></pre>
<p>Working example: <a href="http://jsfiddle.net/JUSsf/" rel="noreferrer">http://jsfiddle.net/JUSsf/</a> (Tested in Chrome, I can't guarantee full browser support - you will have to test this).</p>
<p>It creates an object that contains the tree structure of the HTML page in the format you requested and then uses <code>JSON.stringify()</code> which is included in most modern browsers (IE8+, Firefox 3+ .etc); If you need to support older browsers you can include <a href="http://www.json.org/js.html" rel="noreferrer">json2.js</a>.</p>
<p>It can take either a DOM element or a <code>string</code> containing valid XHTML as an argument (I believe, I'm not sure whether the <code>DOMParser()</code> will choke in certain situations as it is set to <code>"text/xml"</code> or whether it just doesn't provide error handling. Unfortunately <code>"text/html"</code> has poor browser support).</p>
<p>You can easily change the range of this function by passing a different value as <code>element</code>. Whatever value you pass will be the root of your JSON map.</p> |
13,152,927 | How to use radio on change event? | <p>I have two radio button
on change event i want change button How it is possible?
My Code </p>
<pre><code><input type="radio" name="bedStatus" id="allot" checked="checked" value="allot">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer">Transfer
</code></pre>
<p>Script</p>
<pre><code><script>
$(document).ready(function () {
$('input:radio[name=bedStatus]:checked').change(function () {
if ($("input[name='bedStatus']:checked").val() == 'allot') {
alert("Allot Thai Gayo Bhai");
}
if ($("input[name='bedStatus']:checked").val() == 'transfer') {
alert("Transfer Thai Gayo");
}
});
});
</script>
</code></pre> | 13,152,970 | 11 | 2 | null | 2012-10-31 07:09:53.89 UTC | 79 | 2022-08-06 20:01:53.08 UTC | 2018-11-01 06:07:11.947 UTC | null | 1,653,919 | null | 1,653,919 | null | 1 | 590 | jquery|jquery-ui | 1,080,608 | <p>You can use <code>this</code> which refers to the current <code>input</code> element.</p>
<pre><code>$('input[type=radio][name=bedStatus]').change(function() {
if (this.value == 'allot') {
// ...
}
else if (this.value == 'transfer') {
// ...
}
});
</code></pre>
<p><a href="http://jsfiddle.net/4gZAT/" rel="noreferrer">http://jsfiddle.net/4gZAT/</a></p>
<p>Note that you are comparing the value against <code>allot</code> in both if statements and <code>:radio</code> selector is deprecated.</p>
<p>In case that you are not using jQuery, you can use the <code>document.querySelectorAll</code> and <code>HTMLElement.addEventListener</code> methods:</p>
<pre><code>var radios = document.querySelectorAll('input[type=radio][name="bedStatus"]');
function changeHandler(event) {
if ( this.value === 'allot' ) {
console.log('value', 'allot');
} else if ( this.value === 'transfer' ) {
console.log('value', 'transfer');
}
}
Array.prototype.forEach.call(radios, function(radio) {
radio.addEventListener('change', changeHandler);
});
</code></pre> |
17,119,075 | Do you have to put Task.Run in a method to make it async? | <p>I'm trying to understand async await in the simplest form. I want to create a very simple method that adds two numbers for the sake of this example, granted, it's no processing time at all, it's just a matter of formulating an example here.</p>
<h3>Example 1</h3>
<pre><code>private async Task DoWork1Async()
{
int result = 1 + 2;
}
</code></pre>
<h3>Example 2</h3>
<pre><code>private async Task DoWork2Async()
{
Task.Run( () =>
{
int result = 1 + 2;
});
}
</code></pre>
<p>If I await <code>DoWork1Async()</code> will the code run synchronously or asynchronously?</p>
<p>Do I need to wrap the sync code with <code>Task.Run</code> to make the method awaitable AND asynchronous so as not to block the UI thread?</p>
<p>I'm trying to figure out if my method is a <code>Task</code> or returns <code>Task<T></code> do I need to wrap the code with <code>Task.Run</code> to make it asynchronous.</p>
<p>I see examples on the net where people are awaiting code that has nothing async within and not wrapped in a <code>Task.Run</code> or <code>StartNew</code>.</p> | 17,119,610 | 3 | 1 | null | 2013-06-15 00:28:22.563 UTC | 169 | 2022-04-21 08:38:54.697 UTC | 2022-04-21 08:38:54.697 UTC | null | 5,446,749 | null | 167,451 | null | 1 | 356 | c#|.net-4.5|async-await|c#-5.0 | 387,297 | <p>First, let's clear up some terminology: "asynchronous" (<code>async</code>) means that it may yield control back to the calling thread before it starts. In an <code>async</code> method, those "yield" points are <code>await</code> expressions.</p>
<p>This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".</p>
<p>To futher confuse the issue, <code>async</code> is very different than "awaitable"; there are some <code>async</code> methods whose return types are not awaitable, and many methods returning awaitable types that are not <code>async</code>.</p>
<p>Enough about what they <em>aren't</em>; here's what they <em>are</em>:</p>
<ul>
<li>The <code>async</code> keyword allows an asynchronous method (that is, it allows <code>await</code> expressions). <code>async</code> methods may return <code>Task</code>, <code>Task<T></code>, or (if you must) <code>void</code>.</li>
<li>Any type that follows a certain pattern can be awaitable. The most common awaitable types are <code>Task</code> and <code>Task<T></code>.</li>
</ul>
<p>So, if we reformulate your question to "how can I run an operation <em>on a background thread</em> in a way that it's awaitable", the answer is to use <code>Task.Run</code>:</p>
<pre><code>private Task<int> DoWorkAsync() // No async because the method does not need await
{
return Task.Run(() =>
{
return 1 + 2;
});
}
</code></pre>
<p>(But this pattern is a poor approach; see below).</p>
<p>But if your question is "how do I create an <code>async</code> method that can yield back to its caller instead of blocking", the answer is to declare the method <code>async</code> and use <code>await</code> for its "yielding" points:</p>
<pre><code>private async Task<int> GetWebPageHtmlSizeAsync()
{
var client = new HttpClient();
var html = await client.GetAsync("http://www.example.com/");
return html.Length;
}
</code></pre>
<p>So, the basic pattern of things is to have <code>async</code> code depend on "awaitables" in its <code>await</code> expressions. These "awaitables" can be other <code>async</code> methods or just regular methods returning awaitables. Regular methods returning <code>Task</code>/<code>Task<T></code> <em>can</em> use <code>Task.Run</code> to execute code on a background thread, or (more commonly) they can use <code>TaskCompletionSource<T></code> or one of its shortcuts (<code>TaskFactory.FromAsync</code>, <code>Task.FromResult</code>, etc). I <strong>don't</strong> recommend wrapping an entire method in <code>Task.Run</code>; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a <code>Task.Run</code>:</p>
<pre><code>private int DoWork()
{
return 1 + 2;
}
private void MoreSynchronousProcessing()
{
// Execute it directly (synchronously), since we are also a synchronous method.
var result = DoWork();
...
}
private async Task DoVariousThingsFromTheUIThreadAsync()
{
// I have a bunch of async work to do, and I am executed on the UI thread.
var result = await Task.Run(() => DoWork());
...
}
</code></pre>
<p>I have an <a href="http://blog.stephencleary.com/2012/02/async-and-await.html" rel="noreferrer"><code>async</code>/<code>await</code> intro</a> on my blog; at the end are some good followup resources. The MSDN docs for <code>async</code> are unusually good, too.</p> |
10,150,723 | Use a variable with "LIKE %" (e.g. "variable%") in PL/SQL? | <p>The question is similar to using <strong>LIKE</strong> in <strong>SQL *PLUS</strong>, where a select statement contains a <strong>LIKE</strong> clause as follows:</p>
<pre><code>select * from sometable where somecolumn LIKE 'something%';
</code></pre>
<p>How could one use the same within a cursor? I tried using the following:</p>
<pre><code> cursor c is select * from sometable where somecolumn like 'something%';
</code></pre>
<p><em>same as above</em> </p>
<p>EDIT: I need to get <strong>something</strong> as a parameter, meaning, the select statement is executed within a stored procedure.</p>
<p><strong>EDIT 2:</strong> </p>
<pre><code>create procedure proc1 (search VARCHAR) is
cursor c is select student_name from students where student_name like 'search%';
</code></pre>
<p>--I know using 'search%' retrieves student names containing 'the key search', but is there any other way to use such a variable.</p>
<pre><code>do something;
end;
</code></pre>
<p>In short, I need to select student names containing a value that is passed as a parameter; this may not be the whole name, and may suffice enough to be used within a like clause.</p> | 10,151,185 | 1 | 5 | null | 2012-04-14 03:21:33.59 UTC | 1 | 2017-08-24 09:04:42.537 UTC | 2012-04-14 04:29:47.88 UTC | user166390 | null | null | 980,411 | null | 1 | 10 | sql|oracle|plsql|sqlplus | 103,241 | <p>As per my understanding to your issue, you are using variable <code>search</code> within quotes. Put your variable outside the quotes, e.g.:</p>
<pre><code> create or replace procedure PROC1(search VARCHAR2)
IS
cursor test_cur(search IN VARCHAR2)
IS
SELECT student_name
FROM student
WHERE student_name LIKE search||'%'; --you're putting you variable within quotes
v_temp_var student.student_name%TYPE;
BEGIN
OPEN test_cur(search);
LOOP
FETCH test_cur INTO v_temp_var;
EXIT WHEN test_cur%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(v_temp_var);
END LOOP;
CLOSE test_cur;
END test;
</code></pre> |
10,073,893 | How to compare dates in hibernate | <p>In my Data base dates are as <code>2012-04-09 04:02:53</code> <code>2012-04-09 04:04:51</code> <code>2012-04-08 04:04:51</code>, etc, I need to retrieve data which have current date in there date field. I mean i need to match only <code>2012-04-09'</code> . How can i do it using hibernate criteria.</p> | 10,074,111 | 8 | 0 | null | 2012-04-09 13:26:09.013 UTC | 2 | 2018-12-06 21:37:37.02 UTC | null | null | null | null | 527,699 | null | 1 | 17 | java|spring|hibernate | 56,412 | <p>Use <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/criterion/Restrictions.html#between%28java.lang.String,%20java.lang.Object,%20java.lang.Object%29">Restrictions.between()</a> to generate a where clause which the date column is between '2012-04-09 00:00:00' and '2012-04-09 23:59:59' </p>
<pre><code>SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fromDate = df.parse("2012-04-09 00:00:00");
Date toDate = df.parse("2012-04-09 23:59:59");
criteria.add(Restrictions.between("dateField", fromDate, toDate));
</code></pre>
<p>Please note that all the properties used in the Criteria API is the Java property name , but not the actual column name.</p>
<hr>
<p>Update: Get fromDate and toDate for the current date using JDK only</p>
<pre><code>Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date fromDate = calendar.getTime();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date toDate = calendar.getTime();
criteria.add(Restrictions.between("dateField", fromDate, toDate));
</code></pre> |
9,846,683 | How to install Colorama in Python? | <p>I downloaded the colorama module for python and I double clicked the setup.py. The screen flashed, but when I try to import the module, it always says 'No Module named colorama'</p>
<p>I copied and pasted the folder under 'C:\Python26\Lib\site-packages' and tried to run the setup from there. Same deal. Am I doing something wrong?</p>
<p>Thanks,
Mike</p> | 9,846,712 | 11 | 7 | null | 2012-03-23 21:27:21.443 UTC | 3 | 2022-01-18 20:33:54.547 UTC | 2021-08-19 19:56:14.577 UTC | null | 9,997,212 | null | 820,088 | null | 1 | 17 | python|colorama | 131,037 | <p>Python packages are installed using setup.py by entering the following command from a command line:</p>
<pre><code>python setup.py install
</code></pre> |
10,057,651 | How can I check whether a field exists or not in MongoDB? | <p>I have created some documents and managed to make some simple queries but I can't create a query that would find documents where a field just exists.</p>
<p>For example suppose this is a document:</p>
<pre><code>{ "profile_sidebar_border_color" : "D9B17E" ,
"name" : "???? ???????" , "default_profile" : false ,
"show_all_inline_media" : true , "otherInfo":["text":"sometext", "value":123]}
</code></pre>
<p>Now I want a query that will bring all the documents where the text in <code>otherInfo</code> has something in it.</p>
<p>If there is no text, then the <code>otherInfo</code> will just be like that: <code>"otherInfo":[]</code></p>
<p>So I want to check the existence of the <code>text</code> field in <code>otherInfo</code>.</p>
<p>How can I achieve this?</p> | 10,057,955 | 4 | 0 | null | 2012-04-07 19:31:49.48 UTC | 9 | 2019-03-25 10:46:57.757 UTC | 2019-03-25 10:46:57.757 UTC | null | 6,139,527 | null | 1,183,263 | null | 1 | 20 | java|mongodb | 52,929 | <p>You can use the <code>$exists</code> operator in combination with the <code>.</code> notation. The bare query in the mongo-shell should look like this:</p>
<pre><code>db.yourcollection.find({ 'otherInfo.text' : { '$exists' : true }})
</code></pre>
<p>And a test case in Java could look like this:</p>
<pre><code> BasicDBObject dbo = new BasicDBObject();
dbo.put("name", "first");
collection.insert(dbo);
dbo.put("_id", null);
dbo.put("name", "second");
dbo.put("otherInfo", new BasicDBObject("text", "sometext"));
collection.insert(dbo);
DBObject query = new BasicDBObject("otherInfo.text", new BasicDBObject("$exists", true));
DBCursor result = collection.find(query);
System.out.println(result.size());
System.out.println(result.iterator().next());
</code></pre>
<p>Output:</p>
<pre><code>1
{ "_id" : { "$oid" : "4f809e72764d280cf6ee6099"} , "name" : "second" , "otherInfo" : { "text" : "sometext"}}
</code></pre> |
10,203,856 | Grails : How I do mock other methods of a class under test which might be called internally during testing | <p>I am writing a test for methodA() in a service class similar to the one given below.</p>
<pre><code>Class SampleService {
def methodA(){
methodB()
}
def methodB(){
}
}
</code></pre>
<p>When I test methodA(), I need to be able to mock the call to methodB() when testing methodA(). I am using version 2.0.x of grails. In the 1.3.x distributions, I would write a self mock like this </p>
<pre><code>def sampleServiceMock = mockFor(SampleService)
sampleServiceMock.demand.methodB { -> }
</code></pre>
<p>But this doesn't work in the 2.0.x versions. I was wondering what are the other ways of mocking methodB() when testing methodA() </p> | 10,210,857 | 2 | 1 | null | 2012-04-18 06:19:02.96 UTC | 8 | 2012-04-18 13:52:52.043 UTC | null | null | null | null | 18,548 | null | 1 | 20 | testing|grails|groovy|mocking|tdd | 16,590 | <p>For this kind of problem I actually avoid mocks and use the built-in groovyProxy ability to cast a map of closures as a proxy object. This gives you an instance with some methods overridden, but others passed through to the real class:</p>
<pre><code>class SampleService {
def methodA() {
methodB()
}
def methodB() {
return "real method"
}
}
def mock = [methodB: {-> return "mock!" }] as SampleService
assert "mock!" == mock.methodA()
assert "real method" == new SampleService().methodA()
</code></pre>
<p>I like that only changes an instance, can be done in a single line, and doesn't mess with the metaclass of anything outside of that instance that needs to be cleaned up.</p> |
10,214,947 | Upload files using input type="file" field with .change() event not always firing in IE and Chrome | <p>I have simple piece of code to upload files:</p>
<pre><code>$(document).ready(function () {
$(".attachmentsUpload input.file").change(function () {
$('form').submit();
});
});
<form class="attachmentsUpload" action="/UploadHandler.ashx" method="post" enctype="multipart/form-data">
<input type="file" class="file" name="file" />
</form>
</code></pre>
<p>While I click on input and then select a file in dialog box, I'm submitting this file using ajax. This is not important part here. Important part is, that while I select the same file second time in the dialog box, just after submitting the first file, the .change() event does not fire in IE and Chrome. But while I choose different file, the event fires and works properly. Under Firefox it is firing all the time.</p>
<p>How to workaround this, to work as expected (as in Firefox) ?</p> | 10,215,055 | 2 | 4 | null | 2012-04-18 17:44:46.033 UTC | 9 | 2018-02-02 11:47:35.423 UTC | 2012-04-18 18:03:46.163 UTC | null | 270,315 | null | 270,315 | null | 1 | 23 | javascript|jquery|internet-explorer|firefox|google-chrome | 76,577 | <h3>Description</h3>
<p>This happens because the value of the input field (the selected filepath) does not change if you select the same file again.</p>
<p>You can set the value in the <code>onChange()</code> event to an empty string and submit your form only if the value is not empty. Have a look at my sample and this <a href="http://jsfiddle.net/TmUmG/" rel="noreferrer">jsFiddle Demonstration</a>.</p>
<h3>Sample</h3>
<pre><code>$(".attachmentsUpload input.file").change(function () {
if ($(".attachmentsUpload input.file").val() == "") {
return;
}
// your ajax submit
$(".attachmentsUpload input.file").val("");
});
</code></pre>
<h2>Update</h2>
<p>This, for any reason, does not work in IE9. You can replace the element to reset them.
<strong>In this case you need jQuery <code>live()</code> to bind the event, because your input field will dynamically (re)created.</strong>
This will work in all browsers.</p>
<p>I found this solution on the stackoverflow answer <a href="https://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery">Clearing input type='file' using jQuery</a></p>
<pre><code>$(".attachmentsUpload input.file").live("change", function () {
if ($(".attachmentsUpload input.file").val() == "") {
return;
}
// get the inputs value
var fileInputContent = $(".attachmentsUpload input.file").val();
// your ajax submit
alert("submit value of the file input field=" + fileInputContent);
// reset the field
$(".attachmentsUpload input.file").replaceWith('<input type="file" class="file" name="file" />');
});
</code></pre>
<h3>More Information</h3>
<ul>
<li><a href="http://api.jquery.com/live/" rel="noreferrer">jQuery.live()</a></li>
<li><a href="http://api.jquery.com/replaceWith/" rel="noreferrer">jQuery.replaceWith()</a></li>
</ul>
<h2>Check out my updated <a href="http://jsfiddle.net/TmUmG/1/" rel="noreferrer">jsFiddle</a></h2>
<p><strong>Note:</strong> <a href="http://api.jquery.com/live/" rel="noreferrer"><code>live</code></a> is now <strong>removed</strong> from later versions of jQuery. Please use <a href="http://api.jquery.com/on/" rel="noreferrer"><code>on</code></a> instead of <code>live</code>.</p> |
9,743,717 | Background position, margin-top? | <p>I currently have my background set to top right as:</p>
<pre><code>#thedivstatus {
background-image: url("imagestatus.gif");
background-position: right top;
background-repeat: no-repeat;
}
</code></pre>
<p><strong><em>BUT!</em></strong> I need to add a <code>margin-top:50px;</code> from where its rendering via above. Could anyone give me a suggestion? </p>
<p>Thanks</p> | 9,743,746 | 4 | 2 | null | 2012-03-16 19:56:52.117 UTC | 3 | 2022-02-22 12:27:39.713 UTC | 2018-01-28 02:11:05.523 UTC | null | 973,397 | null | 973,397 | null | 1 | 25 | css | 127,088 | <p>If you mean you want the background image itself to be offset by 50 pixels from the top, like a background margin, then just switch out the <code>top</code> for <code>50px</code> and you're set.</p>
<pre><code>#thedivstatus {
background-image: url("imagestatus.gif");
background-position: right 50px;
background-repeat: no-repeat;
}
</code></pre> |
9,702,201 | Xcode compiles my App, but can't run it in the simulator | <p>when i compile my app, Xcode just says "Attaching to Projectname..." and gets stuck there.
The debugger just prints this out:</p>
<blockquote>
<p>error: failed to attach to process ID 0</p>
</blockquote>
<p>I tried to clean & build again and it still doesn't work out. I googled but couldn't find anything helpful.
How can I fix this problem? Thank You!</p> | 12,504,712 | 20 | 3 | null | 2012-03-14 12:42:47.027 UTC | 10 | 2017-03-17 02:26:24.187 UTC | null | null | null | null | 1,043,495 | null | 1 | 54 | ios5|ios-simulator|xcode4.3 | 26,049 | <p>The solution for me was to delete everything Xcode has generated earlier:</p>
<ul>
<li>the App on the Simulator...if this is not possible because you cant
reach the Homescreen, you can delete the App directly under
<code>~/Library/Application Support/iPhoneSimulator/6.0/Applications</code></li>
<li>delete the Derived Data in the Organizer under Projects or directly
in <code>~/Library/Developer/Xcode/DerivedData</code></li>
<li>clean the Build Folder by choosing "Product" in the MenuBar and click
while you press the Alt-key on "Clean Build Folder"</li>
<li>Restart Xcode</li>
</ul> |
10,014,271 | Generate Random Color distinguishable to Humans | <p>I am trying to randomly generate a color in hex in javascript.</p>
<p>However the colors generated are almost indistinguishable from eachother.<br>
Is there a way to improve it?</p>
<hr>
<p>Here is the code I am using:</p>
<pre><code>function randomColor(){
var allowed = "ABCDEF0123456789", S = "#";
while(S.length < 7){
S += allowed.charAt(Math.floor((Math.random()*16)+1));
}
return S;
}
</code></pre>
<hr>
<p>I heard something about <em>HSL</em> and <em>HSV</em> color model but can't get
it to work in my code. Please help.</p>
<p>Thanks in Advance</p> | 10,014,969 | 10 | 9 | null | 2012-04-04 15:26:39.543 UTC | 27 | 2021-02-05 02:30:26.34 UTC | 2016-02-10 17:31:36.35 UTC | null | 104,380 | user1231969 | null | null | 1 | 69 | javascript|jquery | 73,049 | <p>You could use a fixed set of colors, such as the ones listed in the <a href="https://github.com/jquery/jquery-color" rel="noreferrer">jquery.color.js plugin</a>.</p>
<p>List of colors from jquery.color.js plugin:</p>
<pre><code>Colors = {};
Colors.names = {
aqua: "#00ffff",
azure: "#f0ffff",
beige: "#f5f5dc",
black: "#000000",
blue: "#0000ff",
brown: "#a52a2a",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgrey: "#a9a9a9",
darkgreen: "#006400",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkviolet: "#9400d3",
fuchsia: "#ff00ff",
gold: "#ffd700",
green: "#008000",
indigo: "#4b0082",
khaki: "#f0e68c",
lightblue: "#add8e6",
lightcyan: "#e0ffff",
lightgreen: "#90ee90",
lightgrey: "#d3d3d3",
lightpink: "#ffb6c1",
lightyellow: "#ffffe0",
lime: "#00ff00",
magenta: "#ff00ff",
maroon: "#800000",
navy: "#000080",
olive: "#808000",
orange: "#ffa500",
pink: "#ffc0cb",
purple: "#800080",
violet: "#800080",
red: "#ff0000",
silver: "#c0c0c0",
white: "#ffffff",
yellow: "#ffff00"
};
</code></pre>
<p>The rest is simply <a href="https://stackoverflow.com/questions/2532218/pick-random-property-from-a-javascript-object">picking a random property from a Javascript object</a>.</p>
<pre><code>Colors.random = function() {
var result;
var count = 0;
for (var prop in this.names)
if (Math.random() < 1/++count)
result = prop;
return result;
};
</code></pre>
<p>Using <code>Colors.random()</code> might get you a human-readable color. I even powered an example below.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function(){
Colors = {};
Colors.names = {
aqua: "#00ffff",
azure: "#f0ffff",
beige: "#f5f5dc",
black: "#000000",
blue: "#0000ff",
brown: "#a52a2a",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgrey: "#a9a9a9",
darkgreen: "#006400",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkviolet: "#9400d3",
fuchsia: "#ff00ff",
gold: "#ffd700",
green: "#008000",
indigo: "#4b0082",
khaki: "#f0e68c",
lightblue: "#add8e6",
lightcyan: "#e0ffff",
lightgreen: "#90ee90",
lightgrey: "#d3d3d3",
lightpink: "#ffb6c1",
lightyellow: "#ffffe0",
lime: "#00ff00",
magenta: "#ff00ff",
maroon: "#800000",
navy: "#000080",
olive: "#808000",
orange: "#ffa500",
pink: "#ffc0cb",
purple: "#800080",
violet: "#800080",
red: "#ff0000",
silver: "#c0c0c0",
white: "#ffffff",
yellow: "#ffff00"
};
Colors.random = function() {
var result;
var count = 0;
for (var prop in this.names)
if (Math.random() < 1/++count)
result = prop;
return { name: result, rgb: this.names[result]};
};
var $placeholder = $(".placeholder");
$placeholder.click(function(){
var color = Colors.random();
$placeholder.css({'background-color': color.rgb});
$("#color").html("It's " + color.name);
});
})();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.placeholder {
width: 150px;
height: 150px;
border: 1px solid black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="placeholder"></div>
<span id="color">Click the square above.</span></code></pre>
</div>
</div>
</p> |
10,099,422 | Flushing footer to bottom of the page, twitter bootstrap | <p>I am generally familiar with the technique of flushing a footer using css.</p>
<p>But I am having some trouble getting this approach to work for Twitter bootstrap, most likely due to the fact that Twitter bootstrap is responsive in nature. Using Twitter bootstrap I am not able to get the footer to flush to the bottom of the page using the approach described in the above blog post.</p> | 12,701,056 | 35 | 6 | null | 2012-04-11 03:31:04.757 UTC | 151 | 2021-08-24 08:31:07.647 UTC | 2019-01-22 15:46:49.39 UTC | null | 4,298,200 | null | 482,506 | null | 1 | 339 | css|twitter-bootstrap|footer | 675,685 | <p>Found the snippets <a href="http://bootstrapfooter.codeplex.com/" rel="noreferrer">here</a> works really well for bootstrap </p>
<p>Html:</p>
<pre><code><div id="wrap">
<div id="main" class="container clear-top">
<p>Your content here</p>
</div>
</div>
<footer class="footer"></footer>
</code></pre>
<p>CSS:</p>
<pre><code>html, body {
height: 100%;
}
#wrap {
min-height: 100%;
}
#main {
overflow:auto;
padding-bottom:150px; /* this needs to be bigger than footer height*/
}
.footer {
position: relative;
margin-top: -150px; /* negative value of footer height */
height: 150px;
clear:both;
padding-top:20px;
}
</code></pre> |
9,901,082 | What is this JavaScript "require"? | <p>I'm trying to get JavaScript to read/write to a PostgreSQL database. I found this <a href="https://github.com/brianc/node-postgres" rel="noreferrer">project</a> on GitHub. I was able to get the following sample code to run in Node.</p>
<pre><code>var pg = require('pg'); //native libpq bindings = `var pg = require('pg').native`
var conString = "tcp://postgres:1234@localhost/postgres";
var client = new pg.Client(conString);
client.connect();
//queries are queued and executed one after another once the connection becomes available
client.query("CREATE TEMP TABLE beatles(name varchar(10), height integer, birthday timestamptz)");
client.query("INSERT INTO beatles(name, height, birthday) values($1, $2, $3)", ['Ringo', 67, new Date(1945, 11, 2)]);
client.query("INSERT INTO beatles(name, height, birthday) values($1, $2, $3)", ['John', 68, new Date(1944, 10, 13)]);
//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text, (optional) parameter values, and (optional) query name
client.query({
name: 'insert beatle',
text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)",
values: ['George', 70, new Date(1946, 02, 14)]
});
//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
client.query({
name: 'insert beatle',
values: ['Paul', 63, new Date(1945, 04, 03)]
});
var query = client.query("SELECT * FROM beatles WHERE name = $1", ['John']);
//can stream row results back 1 at a time
query.on('row', function(row) {
console.log(row);
console.log("Beatle name: %s", row.name); //Beatle name: John
console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
console.log("Beatle height: %d' %d\"", Math.floor(row.height/12), row.height%12); //integers are returned as javascript ints
});
//fired after last row is emitted
query.on('end', function() {
client.end();
});
</code></pre>
<p>Next I tried to make it run on a webpage, but nothing seemed to happen. I checked on the JavaScript console and it just says "require not defined".</p>
<p>So what is this "require"? Why does it work in Node but not in a webpage?</p>
<p>Also, before I got it to work in Node, I had to do <code>npm install pg</code>. What's that about? I looked in the directory and didn't find a file pg. Where did it put it, and how does JavaScript find it?</p> | 9,901,097 | 7 | 8 | null | 2012-03-28 04:18:58.647 UTC | 245 | 2022-02-22 11:24:38.133 UTC | 2021-09-15 08:36:08.433 UTC | null | 16,316,260 | null | 209,512 | null | 1 | 675 | javascript|database|postgresql|node.js | 991,990 | <blockquote>
<p>So what is this "require?" </p>
</blockquote>
<p><a href="https://nodejs.org/api/modules.html#modules_require" rel="noreferrer"><code>require()</code></a> is not part of the standard JavaScript API. But in Node.js, it's a built-in function with a special purpose: <a href="https://nodejs.org/api/modules.html#modules_modules" rel="noreferrer">to load modules</a>.</p>
<p>Modules are a way to split an application into separate files instead of having all of your application in one file. This concept is also present in other languages with minor differences in syntax and behavior, like C's <code>include</code>, Python's <code>import</code>, and so on.</p>
<p>One big difference between Node.js modules and browser JavaScript is how one script's code is accessed from another script's code.</p>
<ul>
<li><p>In browser JavaScript, scripts are added via the <code><script></code> element. When they execute, they all have direct access to the global scope, a "shared space" among all scripts. Any script can freely define/modify/remove/call anything on the global scope.</p></li>
<li><p>In Node.js, each module has its own scope. A module cannot directly access things defined in another module unless it chooses to expose them. To expose things from a module, they must be assigned to <code>exports</code> or <code>module.exports</code>. For a module to access another module's <code>exports</code> or <code>module.exports</code>, <em>it must use <code>require()</code></em>.</p></li>
</ul>
<p>In your code, <code>var pg = require('pg');</code> loads the <a href="https://www.npmjs.com/package/pg" rel="noreferrer"><code>pg</code></a> module, a PostgreSQL client for Node.js. This allows your code to access functionality of the PostgreSQL client's APIs via the <code>pg</code> variable.</p>
<blockquote>
<p>Why does it work in node but not in a webpage?</p>
</blockquote>
<p><code>require()</code>, <code>module.exports</code> and <code>exports</code> are APIs of a module system that is specific to Node.js. Browsers do not implement this module system. </p>
<blockquote>
<p>Also, before I got it to work in node, I had to do <code>npm install pg</code>. What's that about?</p>
</blockquote>
<p><a href="https://www.npmjs.com/" rel="noreferrer">NPM</a> is a package repository service that hosts published JavaScript modules. <a href="https://docs.npmjs.com/cli/install" rel="noreferrer"><code>npm install</code></a> is a command that lets you download packages from their repository.</p>
<blockquote>
<p>Where did it put it, and how does Javascript find it?</p>
</blockquote>
<p>The npm cli puts all the downloaded modules in a <code>node_modules</code> directory where you ran <code>npm install</code>. Node.js has very detailed documentation on <a href="https://nodejs.org/api/modules.html#modules_all_together" rel="noreferrer">how modules find other modules</a> which includes finding a <code>node_modules</code> directory.</p> |
7,770,870 | Are Decimal 'dtypes' available in NumPy? | <p>Are Decimal <a href="https://numpy.org/doc/stable/reference/arrays.dtypes.html" rel="nofollow noreferrer">data type objects</a> (dtypes) available in NumPy?</p>
<pre><code>>>> import decimal, numpy
>>> d = decimal.Decimal('1.1')
>>> s = [['123.123','23'],['2323.212','123123.21312']]
>>> ss = numpy.array(s, dtype=numpy.dtype(decimal.Decimal))
>>> a = numpy.array(s, dtype=float)
>>> type(d)
<class 'decimal.Decimal'>
>>> type(ss[1,1])
<class 'str'>
>>> type(a[1,1])
<class 'numpy.float64'>
</code></pre>
<p>I suppose numpy.array doesn't support every dtype, but I sort of thought that it would at least let a dtype propagate as far as it could as long as the right operations were defined. Am I missing something? Is there some way for this to work?</p> | 7,771,210 | 3 | 3 | null | 2011-10-14 16:47:58.843 UTC | 4 | 2022-04-25 11:22:14.98 UTC | 2022-04-25 10:54:31.5 UTC | null | 63,550 | null | 287,238 | null | 1 | 34 | python|numpy | 56,291 | <h2><em>Important caveat: this is a bad answer</em></h2>
<p>You would probably do best to skip to the next answer.</p>
<hr/>
<p>It seems that <code>Decimal</code> is available:</p>
<pre><code>>>> import decimal, numpy
>>> d = decimal.Decimal('1.1')
>>> a = numpy.array([d,d,d],dtype=numpy.dtype(decimal.Decimal))
>>> type(a[1])
<class 'decimal.Decimal'>
</code></pre>
<p>I'm not sure exactly what you are trying to accomplish. Your example is more complicated than is necessary for simply creating a decimal NumPy array.</p> |
8,219,639 | Stop cursor from jumping to end of input field in javascript replace | <p>I'm using a regular expression to strip invalid characters out of an text input area in javascript (running in IE). I run the replace function on every keyup event. However, this makes the cursor jump to the end of the text box after each keypress, which makes inline editing impossible. </p>
<p>Here is it in action:</p>
<p><a href="http://jsbin.com/ifufuv/2" rel="noreferrer">http://jsbin.com/ifufuv/2</a></p>
<p>Does anyone know how to make it so the cursor does not jump to the end of the input box?</p> | 8,219,711 | 3 | 2 | null | 2011-11-21 22:49:18.2 UTC | 10 | 2018-07-27 22:15:00.613 UTC | null | null | null | null | 104,998 | null | 1 | 44 | javascript|replace | 38,747 | <p>You'll have to manually put the cursor back where you want it. For IE9, set <code>.selectionStart</code> and <code>.selectionEnd</code> (or use <code>.setSelectionRange(start, end)</code>). For IE8 and earlier, use <code>.createTextRange()</code> and call <code>.moveStart()</code> on the text range.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.