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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,056,518 | Number of items in Redis set | <p>What's the easiest way to getting the number (count) of items in Redis set? Preferably without the need to dump whole set and count the lines... So far, I have found only BITCOUNT, which I have not found that useful...</p> | 18,056,612 | 2 | 0 | null | 2013-08-05 10:58:57.193 UTC | 5 | 2020-06-30 09:00:04.813 UTC | null | null | null | null | 729,403 | null | 1 | 48 | count|redis|set | 34,020 | <p>The SCARD command returns the cardinality (i.e. number of items) of a Redis set.</p>
<p><a href="http://redis.io/commands/scard" rel="noreferrer">http://redis.io/commands/scard</a></p>
<p>There is a similar command (ZCARD) for sorted sets.</p> |
17,696,653 | How to auto merge Git branches prior to a Jenkins build? | <p>How to auto merge Git branches prior to a Jenkins build?</p>
<p>I have 2 builds, one for branch <code>master</code> and one for production.</p>
<p>I would like to do Git merge <code>origin/master</code> when I do the production build.</p> | 17,913,099 | 3 | 1 | null | 2013-07-17 09:54:51.677 UTC | 6 | 2021-05-12 02:46:55.34 UTC | 2021-01-26 12:13:50.467 UTC | null | 452,775 | null | 1,900,290 | null | 1 | 25 | jenkins | 51,828 | <p>That's supported by the latest Git Plugin on Jenkins. Just set <code>Checkout/merge to local branch</code> to <code>production</code> under the Advanced settings for Git in the Job configuration.</p>
<p>Then set the <code>Branches to build</code> to master, or just leave it blank to have Jenkins try and merge and build each other branch it finds to production.</p>
<p>It will do one <code>merge/build</code> for each branch. It can also push the merged branch back to the source it pulled from.</p>
<p>Check this out:<br />
<a href="https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin#GitPlugin-AdvancedFeatures" rel="nofollow noreferrer">https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin#GitPlugin-AdvancedFeatures</a></p> |
54,358,107 | Gradle: Could not determine java version from '11.0.2' | <p>I ran the following comment:</p>
<pre><code>./gradlew app:installDebug
</code></pre>
<p>only to be met with the log:</p>
<pre><code>FAILURE: Build failed with an exception.
* What went wrong:
Could not determine java version from '11.0.2'.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
* Get more help at https://help.gradle.org
</code></pre>
<p>My version of gradle is 5.1.1:</p>
<pre><code>------------------------------------------------------------
Gradle 5.1.1
------------------------------------------------------------
Build time: 2019-01-10 23:05:02 UTC
Revision: 3c9abb645fb83932c44e8610642393ad62116807
Kotlin DSL: 1.1.1
Kotlin: 1.3.11
Groovy: 2.5.4
Ant: Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM: 11.0.2 (Oracle Corporation 11.0.2+9-LTS)
OS: Mac OS X 10.13.6 x86_64
</code></pre>
<p>I'm not sure how to proceed (I tried upgrading/downgrading, but nothing has worked so far).</p>
<p><strong>UPDATE:</strong> When I ran <code>./gradlew --version</code>, I got the following:</p>
<pre><code>FAILURE: Build failed with an exception.
* What went wrong:
Could not determine java version from '11.0.2'.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
* Get more help at https://help.gradle.org
</code></pre>
<p>My <code>.../gradle/wrapper/gradle-wrapper.properties</code> contains the following including <code>distributionUrl=.../gradle-4.1-rc-1-all.zip</code>:</p>
<pre><code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-rc-1-all.zip
</code></pre> | 54,359,875 | 28 | 6 | null | 2019-01-25 02:17:18.277 UTC | 29 | 2022-08-25 12:10:03.757 UTC | 2021-09-30 22:32:40.343 UTC | null | 4,575,793 | null | 3,611,375 | null | 1 | 203 | java|gradle|gradlew | 306,351 | <p>There are two different Gradle applications in your system.</p>
<ol>
<li><p>the <strong>system-wide Gradle</strong><br />
This application is invoked by <code>gradle (arguments)</code>.</p>
</li>
<li><p>the <strong>gradle-wrapper</strong><br />
The gradle-wrapper is specific to every project and can only be invoked inside the project's directory, using the command <code>./gradlew (arguments)</code>.</p>
</li>
</ol>
<p>Your system-wide gradle version is <strong>5.1.1</strong> (as the OP explained in the comments, running the command <code>gradle --version</code> returned version 5.1.1).</p>
<p>However, the failure is the result of a call to the gradle-wrapper (<code>./gradlew</code>). Could you check your project's gradle wrapper version? To do that, execute <code>./gradlew --version</code> inside your project's folder, in the directory where the gradlew and gradlew.bat files are.</p>
<p><strong>Update 1:</strong><br />
As running <code>./gradlew --version</code> failed, you can manually check your wrapper's version by opening the file:</p>
<blockquote>
<p>(project's root folder)/gradle/wrapper/gradle-wrapper.properties</p>
</blockquote>
<p>with a simple text editor. The "distributionUrl" inside should tell us what the wrapper's version is.</p>
<p><strong>Update 2:</strong>
As per the OP's updated question, the gradle-wrapper's version is <strong>4.1RC1</strong>.<br />
Gradle <a href="https://docs.gradle.org/5.0/release-notes.html#java-11-runtime-support" rel="noreferrer">added support for JDK 11 in Gradle 5.0</a>. Hence since 4.1RC does not support running on JDK 11 this is definitely a problem.</p>
<p>The obvious way, would be to update your project's gradle-wrapper to version 5.0.<br />
However, before updating, try running <code>gradle app:installDebug</code>. This will use your system-wide installed Gradle whose version is 5.1.1 and supports running on Java 11. If this works, then your buildscript (file build.gradle) is not affected by any breaking changes between v.4.1RC1 and v.5.1.1 and you can then update your wrapper by executing from the command line inside your project's folder: <code>gradle wrapper --gradle-version=5.1.1</code> [*].</p>
<p>If <code>gradle app:installDebug</code> fails to execute correctly, then maybe you need to upgrade your Gradle buildscript. For updating from v.4.1RC1 to 5.1.1, the Gradle project provides a guide (<a href="https://docs.gradle.org/current/userguide/upgrading_version_4.html" rel="noreferrer">1</a>, <a href="https://docs.gradle.org/current/userguide/upgrading_version_5.html" rel="noreferrer">2</a>) with breaking changes and deprecated features between minor releases, so that you can update gradually to the latest version.</p>
<p>Alternatively, if for some reason you can't or don't want to upgrade your Gradle buildscript, you can always choose to downgrade your Java version to one that Gradle 4.1RC1 supports running on.</p>
<p>[*] As <a href="https://stackoverflow.com/a/54493187/4575793">correctly pointed out in the answer by @lupchiazoem</a>, use <code>gradle wrapper --gradle-version=5.1.1</code> (and not <code>./gradlew</code> as I had originally posted there by mistake). The reason is Gradle runs on Java. You can update your gradle-wrapper using any working Gradle distribution, either your system-wide installed Gradle or the gradle-wrapper itself. However, in this case your wrapper is not compatible with your installed Java version, so you do have to use the system-wide Gradle (aka <code>gradle</code> and not <code>./gradlew</code>).</p> |
22,952,516 | How to perform 0 to 1 Normalization in excel | <p>I have an excel file with a column containing some numbers i need to normalize the distribution between 0 and 1 using this formula x-min(distribution)/max(distribution)-min(distribution). any help will be appreciated.</p> | 22,952,594 | 1 | 3 | null | 2014-04-09 03:58:46.12 UTC | 6 | 2016-08-14 18:17:33.74 UTC | null | null | null | null | 3,415,874 | null | 1 | 29 | excel|normalization | 115,493 | <p>Try this:</p>
<pre><code>=(G9-MIN($G$9:$G:$12))/(MAX($G$9:$G$12)-MIN($G$9:$G$12))
</code></pre> |
2,329,492 | Box stacking problem | <p>I found this famous dp problem in many places, but I can not figure out how to solve.</p>
<blockquote>
<p>You are given a set of n types of
rectangular 3-D boxes, where the i^th
box has height h(i), width w(i) and
depth d(i) (all real numbers). You
want to create a stack of boxes which
is as tall as possible, but you can
only stack a box on top of another box
if the dimensions of the 2-D base of
the lower box are each strictly larger
than those of the 2-D base of the
higher box. Of course, you can rotate
a box so that any side functions as
its base. It is also allowable to use
multiple instances of the same type of
box.</p>
</blockquote>
<p>This problem seems too complicated for me to figure out the steps. As it is 3D, I get three sequence of height, width and depth. But as it is possible to exchange 3 dimension the problem becomes more complicated for me. So please someone explain the steps to solve the problem when there is no swapping and then how to do it when swapping. I became tired about the problem. So please, please someone explain the solution easy way.</p> | 2,329,685 | 5 | 2 | null | 2010-02-24 21:02:41.257 UTC | 33 | 2016-04-17 17:01:38.54 UTC | 2010-02-24 22:45:35.233 UTC | null | 228,208 | null | 168,394 | null | 1 | 31 | algorithm|dynamic-programming | 25,006 | <p>I think you can solve this using the dynamic programming <b>longest increasing subsequence</b> algorithm: <a href="http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence" rel="noreferrer">http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence</a></p>
<p>Accounting for the rotations is easy enough: for every tower all you have to check is what happens if you use its height as the length of the base and its width as the height and what happens if you use it in the natural way. For example:</p>
<pre><code>=============
= =
= =
= = L
= H =
= =
= =
=============
W
</code></pre>
<p>Becomes something like (yeah, I know it looks nothing like it should, just follow the notations): </p>
<pre><code>==================
= =
= =
= W = L
= =
= =
==================
H
</code></pre>
<p>So for each block you actually have 3 blocks representing its possible rotations. Adjust your blocks array according to this, then sort by decreasing base area and just apply the DP LIS algorithm to the get the maximum height. </p>
<p>The adapted recurrence is: D[i] = maximum height we can obtain if the last tower must be i.</p>
<pre><code>D[1] = h(1);
D[i] = h(i) + max(D[j] | j < i, we can put block i on top of block j)
Answer is the max element of D.
</code></pre>
<p>See a video explaning this here: <a href="http://people.csail.mit.edu/bdean/6.046/dp/" rel="noreferrer">http://people.csail.mit.edu/bdean/6.046/dp/</a> </p> |
1,807,298 | Configuring Automapper in Bootstrapper violates Open-Closed Principle? | <p>I am configuring Automapper in the Bootstrapper and I call the <code>Bootstrap()</code> in the <code>Application_Start()</code>, and I've been told that this is wrong because I have to modify my <code>Bootstrapper</code> class each time I have to add a new mapping, so I am violating the Open-Closed Principle.</p>
<p>How do you think, do I really violate this principle?</p>
<pre><code>public static class Bootstrapper
{
public static void BootStrap()
{
ModelBinders.Binders.DefaultBinder = new MyModelBinder();
InputBuilder.BootStrap();
ConfigureAutoMapper();
}
public static void ConfigureAutoMapper()
{
Mapper.CreateMap<User, UserDisplay>()
.ForMember(o => o.UserRolesDescription,
opt => opt.ResolveUsing<RoleValueResolver>());
Mapper.CreateMap<Organisation, OrganisationDisplay>();
Mapper.CreateMap<Organisation, OrganisationOpenDisplay>();
Mapper.CreateMap<OrganisationAddress, OrganisationAddressDisplay>();
}
}
</code></pre> | 1,810,728 | 5 | 0 | null | 2009-11-27 07:49:32.84 UTC | 35 | 2011-11-25 17:23:46.373 UTC | 2010-10-17 13:59:04.687 UTC | null | 265,143 | null | 112,100 | null | 1 | 36 | .net|automapper|bootstrapping|solid-principles|open-closed-principle | 10,021 | <p>I would argue that you are violating two principles: the single responsibility principle (SRP) and the open/closed principle (OCP).</p>
<p>You are violating the SRP because the bootstrapping class have more than one reason to change: if you alter model binding or the auto mapper configuration.</p>
<p>You would be violating the OCP if you were to add additional bootstrapping code for configuring another sub-component of the system.</p>
<p>How I usually handle this is that I define the following interface.</p>
<pre><code>public interface IGlobalConfiguration
{
void Configure();
}
</code></pre>
<p>For each component in the system that needs bootstrapping I would create a class that implements that interface.</p>
<pre><code>public class AutoMapperGlobalConfiguration : IGlobalConfiguration
{
private readonly IConfiguration configuration;
public AutoMapperGlobalConfiguration(IConfiguration configuration)
{
this.configuration = configuration;
}
public void Configure()
{
// Add AutoMapper configuration here.
}
}
public class ModelBindersGlobalConfiguration : IGlobalConfiguration
{
private readonly ModelBinderDictionary binders;
public ModelBindersGlobalConfiguration(ModelBinderDictionary binders)
{
this.binders = binders;
}
public void Configure()
{
// Add model binding configuration here.
}
}
</code></pre>
<p>I use Ninject to inject the dependencies. <code>IConfiguration</code> is the underlying implementation of the static <code>AutoMapper</code> class and <code>ModelBinderDictionary</code> is the <code>ModelBinders.Binder</code> object. I would then define a <code>NinjectModule</code> that would scan the specified assembly for any class that implements the <code>IGlobalConfiguration</code> interface and add those classes to a composite.</p>
<pre><code>public class GlobalConfigurationModule : NinjectModule
{
private readonly Assembly assembly;
public GlobalConfigurationModule()
: this(Assembly.GetExecutingAssembly()) { }
public GlobalConfigurationModule(Assembly assembly)
{
this.assembly = assembly;
}
public override void Load()
{
GlobalConfigurationComposite composite =
new GlobalConfigurationComposite();
IEnumerable<Type> types =
assembly.GetExportedTypes().GetTypeOf<IGlobalConfiguration>()
.SkipAnyTypeOf<IComposite<IGlobalConfiguration>>();
foreach (var type in types)
{
IGlobalConfiguration configuration =
(IGlobalConfiguration)Kernel.Get(type);
composite.Add(configuration);
}
Bind<IGlobalConfiguration>().ToConstant(composite);
}
}
</code></pre>
<p>I would then add the following code to the Global.asax file.</p>
<pre><code>public class MvcApplication : HttpApplication
{
public void Application_Start()
{
IKernel kernel = new StandardKernel(
new AutoMapperModule(),
new MvcModule(),
new GlobalConfigurationModule()
);
Kernel.Get<IGlobalConfiguration>().Configure();
}
}
</code></pre>
<p>Now my bootstrapping code adheres to both SRP and OCP. I can easily add additional bootstrapping code by creating a class that implements the <code>IGlobalConfiguration</code> interface and my global configuration classes only have one reason to change.</p> |
1,364,360 | Testing Paypal subscription IPN | <p>I'd like to test paypal subscription IPNs, both the ones received when a subscription is created, and the ones sent later with the next payment (such as monthly if the subscription is $x per month).</p>
<p>However I'd prefer not to wait a month or a day to receive the second IPN. Is there a way to have an IPN sent quicker, such as hourly, using paypal or their sandbox?</p>
<p>On the documentation it says you can only specify years, months, days, and weeks as the subscription period.</p> | 1,364,465 | 5 | 1 | null | 2009-09-01 20:00:20.727 UTC | 18 | 2015-09-29 03:05:10.367 UTC | 2009-09-01 20:26:01.61 UTC | null | 49,153 | null | 49,153 | null | 1 | 37 | paypal|paypal-subscriptions|paypal-sandbox | 17,358 | <p>It used to be that the period specified in days would be treated by the test server as minutes so you'd be called every 3 minutes when specified 'd3'. I think they removed this and I'm not aware of any replacement feature to test subscriptions. </p> |
2,250,775 | Force InnoDB to recheck foreign keys on a table/tables? | <p>I have a set of <code>InnoDB</code> tables that I periodically need to maintain by removing some rows and inserting others. Several of the tables have foreign key constraints referencing other tables, so this means that the table loading order is important. To insert the new rows without worrying about the order of the tables, I use:</p>
<pre><code>SET FOREIGN_KEY_CHECKS=0;
</code></pre>
<p>before, and then:</p>
<pre><code>SET FOREIGN_KEY_CHECKS=1;
</code></pre>
<p>after. </p>
<p>When the loading is complete, I'd like to check that the data in the updated tables still hold referential integrity--that the new rows don't break foreign key constraints--but it seems that there's no way to do this.</p>
<p>As a test, I entered data that I was sure violated foreign key constraints, and upon re-enabling the foreign key checks, mysql produced no warnings or errors.</p>
<p>If I tried to find a way to specify the table loading order, and left the foreign key checks on during the loading process, this would not allow me to load data in a table that has a self-referencing foreign key constraint, so this would not be an acceptable solution.</p>
<p>Is there any way to force InnoDB to verify a table's or a database's foreign key constraints?</p> | 5,977,191 | 5 | 2 | null | 2010-02-12 09:31:43.503 UTC | 43 | 2020-05-24 01:09:07.927 UTC | 2015-12-29 05:28:51.363 UTC | null | 3,787,519 | null | 211,029 | null | 1 | 74 | mysql|foreign-keys|innodb | 21,840 | <pre><code>DELIMITER $$
DROP PROCEDURE IF EXISTS ANALYZE_INVALID_FOREIGN_KEYS$$
CREATE
PROCEDURE `ANALYZE_INVALID_FOREIGN_KEYS`(
checked_database_name VARCHAR(64),
checked_table_name VARCHAR(64),
temporary_result_table ENUM('Y', 'N'))
LANGUAGE SQL
NOT DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE TABLE_SCHEMA_VAR VARCHAR(64);
DECLARE TABLE_NAME_VAR VARCHAR(64);
DECLARE COLUMN_NAME_VAR VARCHAR(64);
DECLARE CONSTRAINT_NAME_VAR VARCHAR(64);
DECLARE REFERENCED_TABLE_SCHEMA_VAR VARCHAR(64);
DECLARE REFERENCED_TABLE_NAME_VAR VARCHAR(64);
DECLARE REFERENCED_COLUMN_NAME_VAR VARCHAR(64);
DECLARE KEYS_SQL_VAR VARCHAR(1024);
DECLARE done INT DEFAULT 0;
DECLARE foreign_key_cursor CURSOR FOR
SELECT
`TABLE_SCHEMA`,
`TABLE_NAME`,
`COLUMN_NAME`,
`CONSTRAINT_NAME`,
`REFERENCED_TABLE_SCHEMA`,
`REFERENCED_TABLE_NAME`,
`REFERENCED_COLUMN_NAME`
FROM
information_schema.KEY_COLUMN_USAGE
WHERE
`CONSTRAINT_SCHEMA` LIKE checked_database_name AND
`TABLE_NAME` LIKE checked_table_name AND
`REFERENCED_TABLE_SCHEMA` IS NOT NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
IF temporary_result_table = 'N' THEN
DROP TEMPORARY TABLE IF EXISTS INVALID_FOREIGN_KEYS;
DROP TABLE IF EXISTS INVALID_FOREIGN_KEYS;
CREATE TABLE INVALID_FOREIGN_KEYS(
`TABLE_SCHEMA` VARCHAR(64),
`TABLE_NAME` VARCHAR(64),
`COLUMN_NAME` VARCHAR(64),
`CONSTRAINT_NAME` VARCHAR(64),
`REFERENCED_TABLE_SCHEMA` VARCHAR(64),
`REFERENCED_TABLE_NAME` VARCHAR(64),
`REFERENCED_COLUMN_NAME` VARCHAR(64),
`INVALID_KEY_COUNT` INT,
`INVALID_KEY_SQL` VARCHAR(1024)
);
ELSEIF temporary_result_table = 'Y' THEN
DROP TEMPORARY TABLE IF EXISTS INVALID_FOREIGN_KEYS;
DROP TABLE IF EXISTS INVALID_FOREIGN_KEYS;
CREATE TEMPORARY TABLE INVALID_FOREIGN_KEYS(
`TABLE_SCHEMA` VARCHAR(64),
`TABLE_NAME` VARCHAR(64),
`COLUMN_NAME` VARCHAR(64),
`CONSTRAINT_NAME` VARCHAR(64),
`REFERENCED_TABLE_SCHEMA` VARCHAR(64),
`REFERENCED_TABLE_NAME` VARCHAR(64),
`REFERENCED_COLUMN_NAME` VARCHAR(64),
`INVALID_KEY_COUNT` INT,
`INVALID_KEY_SQL` VARCHAR(1024)
);
END IF;
OPEN foreign_key_cursor;
foreign_key_cursor_loop: LOOP
FETCH foreign_key_cursor INTO
TABLE_SCHEMA_VAR,
TABLE_NAME_VAR,
COLUMN_NAME_VAR,
CONSTRAINT_NAME_VAR,
REFERENCED_TABLE_SCHEMA_VAR,
REFERENCED_TABLE_NAME_VAR,
REFERENCED_COLUMN_NAME_VAR;
IF done THEN
LEAVE foreign_key_cursor_loop;
END IF;
SET @from_part = CONCAT('FROM ', '`', TABLE_SCHEMA_VAR, '`.`', TABLE_NAME_VAR, '`', ' AS REFERRING ',
'LEFT JOIN `', REFERENCED_TABLE_SCHEMA_VAR, '`.`', REFERENCED_TABLE_NAME_VAR, '`', ' AS REFERRED ',
'ON (REFERRING', '.`', COLUMN_NAME_VAR, '`', ' = ', 'REFERRED', '.`', REFERENCED_COLUMN_NAME_VAR, '`', ') ',
'WHERE REFERRING', '.`', COLUMN_NAME_VAR, '`', ' IS NOT NULL ',
'AND REFERRED', '.`', REFERENCED_COLUMN_NAME_VAR, '`', ' IS NULL');
SET @full_query = CONCAT('SELECT COUNT(*) ', @from_part, ' INTO @invalid_key_count;');
PREPARE stmt FROM @full_query;
EXECUTE stmt;
IF @invalid_key_count > 0 THEN
INSERT INTO
INVALID_FOREIGN_KEYS
SET
`TABLE_SCHEMA` = TABLE_SCHEMA_VAR,
`TABLE_NAME` = TABLE_NAME_VAR,
`COLUMN_NAME` = COLUMN_NAME_VAR,
`CONSTRAINT_NAME` = CONSTRAINT_NAME_VAR,
`REFERENCED_TABLE_SCHEMA` = REFERENCED_TABLE_SCHEMA_VAR,
`REFERENCED_TABLE_NAME` = REFERENCED_TABLE_NAME_VAR,
`REFERENCED_COLUMN_NAME` = REFERENCED_COLUMN_NAME_VAR,
`INVALID_KEY_COUNT` = @invalid_key_count,
`INVALID_KEY_SQL` = CONCAT('SELECT ',
'REFERRING.', '`', COLUMN_NAME_VAR, '` ', 'AS "Invalid: ', COLUMN_NAME_VAR, '", ',
'REFERRING.* ',
@from_part, ';');
END IF;
DEALLOCATE PREPARE stmt;
END LOOP foreign_key_cursor_loop;
END$$
DELIMITER ;
CALL ANALYZE_INVALID_FOREIGN_KEYS('%', '%', 'Y');
DROP PROCEDURE IF EXISTS ANALYZE_INVALID_FOREIGN_KEYS;
SELECT * FROM INVALID_FOREIGN_KEYS;
</code></pre>
<p>You can use this stored procedure to check the all database for invalid foreign keys.
The result will be loaded into <code>INVALID_FOREIGN_KEYS</code> table.
Parameters of <code>ANALYZE_INVALID_FOREIGN_KEYS</code>:</p>
<ol>
<li>Database name pattern (LIKE style)</li>
<li>Table name pattern (LIKE style)</li>
<li><p>Whether the result will be temporary. It can be: <code>'Y'</code>, <code>'N'</code>, <code>NULL</code>.</p>
<ul>
<li>In case of <code>'Y'</code> the <code>ANALYZE_INVALID_FOREIGN_KEYS</code> result table will be temporary table.
The temporary table won't be visible for other sessions.
You can execute multiple <code>ANALYZE_INVALID_FOREIGN_KEYS(...)</code> stored procedure parallelly with temporary result table.</li>
<li>But if you are interested in the partial result from an other session, then you must use <code>'N'</code>, then execute <code>SELECT * FROM INVALID_FOREIGN_KEYS;</code> from an other session.</li>
<li><p>You must use <code>NULL</code> to skip result table creation in transaction, because MySQL executes implicit commit in transaction for <code>CREATE TABLE ...</code> and <code>DROP TABLE ...</code>, so the creation of result table would cause problem in transaction. In this case you must create the result table yourself out of <code>BEGIN; COMMIT/ROLLBACK;</code> block:</p>
<pre><code>CREATE TABLE INVALID_FOREIGN_KEYS(
`TABLE_SCHEMA` VARCHAR(64),
`TABLE_NAME` VARCHAR(64),
`COLUMN_NAME` VARCHAR(64),
`CONSTRAINT_NAME` VARCHAR(64),
`REFERENCED_TABLE_SCHEMA` VARCHAR(64),
`REFERENCED_TABLE_NAME` VARCHAR(64),
`REFERENCED_COLUMN_NAME` VARCHAR(64),
`INVALID_KEY_COUNT` INT,
`INVALID_KEY_SQL` VARCHAR(1024)
);
</code></pre>
<p>Visit MySQL site about implicit commit: <a href="http://dev.mysql.com/doc/refman/5.6/en/implicit-commit.html">http://dev.mysql.com/doc/refman/5.6/en/implicit-commit.html</a></p></li>
</ul></li>
</ol>
<p>The <code>INVALID_FOREIGN_KEYS</code> rows will contain only the name of invalid database, table, column. But you can see the invalid referring rows with the execution of value of <code>INVALID_KEY_SQL</code> column of <code>INVALID_FOREIGN_KEYS</code> if there is any.</p>
<p>This stored procedure will be very fast if there are indexes on the referring columns (aka. foreign index) and on the referred columns (usually primary key).</p> |
1,809,484 | Git: how to reverse-merge a commit? | <p>With SVN it is easy to reverse-merge a commit, but how to do that with Git?</p> | 1,809,552 | 5 | 3 | null | 2009-11-27 15:54:07.7 UTC | 27 | 2022-06-17 06:52:08.887 UTC | null | null | null | null | 209,706 | null | 1 | 154 | git|merge | 139,579 | <p>To create a new commit that 'undoes' the changes of a past commit, use:</p>
<pre><code>$ git revert <commit-hash>
</code></pre>
<p>It's also possible to actually remove a commit from an arbitrary point in the past by rebasing and then resetting, but you really don't want to do that if you have already pushed your commits to another repository (or someone else has pulled from you).</p>
<p>If your previous commit is a merge commit you can run this command</p>
<pre><code>$ git revert -m 1 <commit-hash>
</code></pre>
<p>See <a href="https://schacon.github.io/git/howto/revert-a-faulty-merge.txt" rel="nofollow noreferrer">schacon.github.io/git/howto/revert-a-faulty-merge.txt</a> for proper ways to re-merge an un-merged branch</p> |
2,047,942 | How to resolve javax.mail.AuthenticationFailedException issue? | <p>I am doing a <code>sendMail</code> <code>Servlet</code> with <code>JavaMail</code>. I have <code>javax.mail.AuthenticationFailedException</code> on my output. Can anyone please help me out? Thanks.</p>
<p>sendMailServlet code:</p>
<pre><code>try {
String host = "smtp.gmail.com";
String from = "[email protected]";
String pass = "pass";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
Address fromAddress = new InternetAddress(from);
Address toAddress = new InternetAddress("[email protected]");
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.setSubject("Testing JavaMail");
message.setText("Welcome to JavaMail");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
message.saveChanges();
Transport.send(message);
transport.close();
}catch(Exception ex){
out.println("<html><head></head><body>");
out.println("ERROR: " + ex);
out.println("</body></html>");
}
</code></pre>
<p>Output on GlassFish 2.1:</p>
<pre><code>DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP 36sm10907668yxh.13
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587
EHLO platform-4cfaca
250-mx.google.com at your service, [203.126.159.130]
250-SIZE 35651584
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250 PIPELINING
DEBUG SMTP: Found extension "SIZE", arg "35651584"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO platform-4cfaca
250-mx.google.com at your service, [203.126.159.130]
250-SIZE 35651584
250-8BITMIME
250-AUTH LOGIN PLAIN
250-ENHANCEDSTATUSCODES
250 PIPELINING
DEBUG SMTP: Found extension "SIZE", arg "35651584"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
aWpveWNlbGVvbmdAZ21haWwuY29t
334 UGFzc3dvcmQ6
MTIzNDU2Nzhf
235 2.7.0 Accepted
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
</code></pre> | 2,048,570 | 6 | 1 | null | 2010-01-12 09:41:28.923 UTC | 13 | 2021-06-25 05:29:37.267 UTC | 2012-08-21 16:54:20.523 UTC | null | 204,701 | null | 177,623 | null | 1 | 17 | java|jakarta-mail|smtp-auth | 130,565 | <p>You need to implement a custom <a href="http://java.sun.com/products/javamail/javadocs/javax/mail/class-use/Authenticator.html" rel="noreferrer"><code>Authenticator</code></a></p>
<pre><code>import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
class GMailAuthenticator extends Authenticator {
String user;
String pw;
public GMailAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
</code></pre>
<p>Now use it in the <a href="http://java.sun.com/products/javamail/javadocs/javax/mail/Session.html" rel="noreferrer"><code>Session</code></a></p>
<pre><code>Session session = Session.getInstance(props, new GMailAuthenticator(username, password));
</code></pre>
<p>Also check out the <a href="http://java.sun.com/products/javamail/FAQ.html" rel="noreferrer">JavaMail FAQ</a></p> |
1,415,438 | How to find rows in one table that have no corresponding row in another table | <p>I have a 1:1 relationship between two tables. I want to find all the rows in table A that don't have a corresponding row in table B. I use this query:</p>
<pre><code>SELECT id
FROM tableA
WHERE id NOT IN (SELECT id
FROM tableB)
ORDER BY id desc
</code></pre>
<p>id is the primary key in both tables. Apart from primary key indices, I also have a index on tableA(id desc).</p>
<p>Using H2 (Java embedded database), this results in a full table scan of tableB. I want to avoid a full table scan.</p>
<p>How can I rewrite this query to run quickly? What index should I should?</p> | 1,415,448 | 6 | 1 | null | 2009-09-12 16:04:48.107 UTC | 15 | 2020-07-28 08:32:34.653 UTC | 2009-09-12 16:11:46.17 UTC | null | 135,152 | null | 2,959 | null | 1 | 75 | sql|optimization|h2 | 108,674 | <pre><code>select tableA.id from tableA left outer join tableB on (tableA.id = tableB.id)
where tableB.id is null
order by tableA.id desc
</code></pre>
<p>If your db knows how to do index intersections, this will only touch the primary key index</p> |
1,692,538 | What is the difference between primary, unique and foreign key constraints, and indexes? | <p>What is the difference between <code>primary</code>, <code>unique</code> and <code>foreign key constraints</code>, and <code>indexes</code>? </p>
<p>I work on <code>Oracle 10g</code> and <code>SQL Server 2008</code></p> | 1,692,554 | 7 | 0 | null | 2009-11-07 09:25:06.003 UTC | 16 | 2019-02-23 01:17:33.58 UTC | 2018-03-23 07:22:44.12 UTC | null | 3,876,565 | null | 43,907 | null | 1 | 26 | sql-server|database|oracle|constraints|indexing | 126,788 | <p>Primary Key and Unique Key are Entity integrity constraints</p>
<p>Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist and no null values are entered.</p>
<p>Unique key constraint is used to prevent the duplication of key values within the rows of a table and allow null values. (In oracle one null is not equal to another null).</p>
<ul>
<li>KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any structure on your data so they are used only for speeding up queries.</li>
<li>UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to speed up queries, UNIQUE indexes can be used to enforce structure on data, because the database system does not allow this distinct values rule to be broken when inserting or updating data. Your database system may allow a UNIQUE index on columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (NULL is considered not equal to itself), though this is probably undesirable depending on your application.</li>
<li>PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a way to uniquely identify any row in the table, so it shouldn't be used on any columns which allow NULL values. Your PRIMARY index should always be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.</li>
<li>FULLTEXT indexes are different to all of the above, and their behaviour differs more between database systems. Unlike the above three, which are typically b-tree (allowing for selecting, sorting or ranges starting from left most column) or hash (allowing for selection starting from left most column), FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause.</li>
</ul>
<p>see <a href="https://stackoverflow.com/questions/707874/differences-between-index-primary-unique-fulltext-mysql">Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?</a></p> |
2,091,599 | Tools to generate a database diagram/ER diagram from existing Oracle database? | <p>Looking for tools (windows platform) to genereate ER diagram (or similar) from an existing Oracle database.<br/>
Any good tools out there that are free to use or low cost?</p> | 2,093,412 | 9 | 2 | null | 2010-01-19 06:39:22.817 UTC | 14 | 2014-07-10 23:00:05.21 UTC | 2011-11-15 17:31:36.82 UTC | null | 146,325 | null | 49,544 | null | 1 | 19 | oracle|data-modeling|reverse-engineering|documentation-generation|er-diagram | 92,490 | <p>I few years ago, I used Data Architect, part of Power Designer from Sybase. It's a little pricy, but it's excellent. And it makes a fine distinction between the physical (SQL) model of data and the ER model of data. It keeps both models side by side.</p>
<p>If you are not too concerned about the difference between SQL and ER, and you just want a diagram, here's something I did once when I needed a diagram in a big hurry. </p>
<p>Crank up MS Access with a new empty database. Set up table links to all the tables in the schema, or just the ones you want to diagram. Use the "Relationships" tool in Access to create lines between the foreign keys and the primary keys they refer to. Classify these relationships as to many-to-many or many-to-one. </p>
<p>In the Access relationships view, move the boxes around until the diagram is pretty. Print.</p> |
1,388,018 | Attaching an event to multiple elements at one go | <p>Say I have the following :</p>
<pre><code>var a = $("#a");
var b = $("#b");
//I want to do something as such as the following :
$(a,b).click(function () {/* */}); // <= does not work
//instead of attaching the handler to each one separately
</code></pre>
<p>Obviously the above does not work because in the <code>$</code> function, the second argument is the <a href="http://docs.jquery.com/Core/jQuery#expressioncontext" rel="nofollow noreferrer"><code>context</code></a>, not another element.</p>
<p>So how can I attach the event to both the elements at one go ?</p>
<hr>
<p><strong>[Update]</strong></p>
<p><a href="https://stackoverflow.com/questions/1388018/jquery-attaching-an-event-to-multiple-elements-at-one-go/1388087#1388087">peirix</a> posted an interesting snippet in which he combines elements with the <code>&</code> sign; But something I noticed this : </p>
<pre><code>$(a & b).click(function () { /* */ }); // <= works (event is attached to both)
$(a & b).attr("disabled", true); // <= doesn't work (nothing happens)
</code></pre>
<p>From what you can see above, apparently, the combination with the <code>&</code> sign works only when attaching events...?</p> | 1,388,054 | 9 | 2 | null | 2009-09-07 07:31:44.503 UTC | 18 | 2013-11-30 03:03:25.507 UTC | 2017-05-23 11:53:16.803 UTC | null | -1 | null | 44,084 | null | 1 | 52 | javascript|jquery|events | 38,942 | <p>The <a href="http://docs.jquery.com/Traversing/add#expr" rel="noreferrer">jQuery add method</a> is what you want:</p>
<blockquote>
<p>Adds more elements, matched by the given expression, to the set of matched elements</p>
</blockquote>
<pre><code>var a = $("#a");
var b = $("#b");
var combined = a.add(b)
</code></pre> |
2,323,778 | How to debug web workers | <p>I have been working with web workers in HTML 5 and am looking for ways to debug them. Ideally something like the firebug or chrome debuggers. Does anyone have any good solution to this. with no access to the console or DOM its kind of hard to debug iffy code</p> | 4,985,794 | 12 | 7 | null | 2010-02-24 04:59:40.753 UTC | 9 | 2021-04-08 10:07:41.84 UTC | null | null | null | null | 280,050 | null | 1 | 79 | javascript|html|google-chrome|firebug | 49,985 | <p>As a fast solution on the missing console.log, you can just use <code>throw JSON.stringify({data:data})</code></p> |
1,637,762 | Test if string is URL encoded in PHP | <p>How can I test if a string is URL encoded?</p>
<p>Which of the following approaches is better?</p>
<ul>
<li>Search the string for characters which would be encoded, which aren't, and if any exist then its not encoded, or </li>
<li>Use something like this which I've made:</li>
</ul>
<pre><code>
function is_urlEncoded($string){
$test_string = $string;
while(urldecode($test_string) != $test_string){
$test_string = urldecode($test_string);
}
return (urlencode($test_string) == $string)?True:False;
}
$t = "Hello World > how are you?";
if(is_urlEncoded($sreq)){
print "Was Encoded.\n";
}else{
print "Not Encoded.\n";
print "Should be ".urlencode($sreq)."\n";
}
</code></pre>
<p>The above code works, but not in instances where the string has been doubly encoded, as in these examples:</p>
<ul>
<li><code>$t = "Hello%2BWorld%2B%253E%2Bhow%2Bare%2Byou%253F";</code></li>
<li><code>$t = "Hello+World%2B%253E%2Bhow%2Bare%2Byou%253F";</code></li>
</ul> | 1,637,819 | 13 | 2 | null | 2009-10-28 14:50:20.857 UTC | 3 | 2021-10-26 09:30:15.393 UTC | 2015-09-10 23:30:01.183 UTC | null | 1,832,942 | null | 175,407 | null | 1 | 26 | php|testing|url-encoding | 115,535 | <p>You'll never know for sure if a string is URL-encoded or if it was supposed to have the sequence <code>%2B</code> in it. Instead, it probably depends on where the string came from, i.e. if it was hand-crafted or from some application.</p>
<blockquote>
<p>Is it better to search the string for characters which would be encoded, which aren't, and if any exist then its not encoded.</p>
</blockquote>
<p>I think this is a better approach, since it would take care of things that have been done programmatically (assuming the application would not have left a non-encoded character behind).</p>
<p>One thing that will be confusing here... Technically, the <code>%</code> "should be" encoded if it will be present in the final value, since it is a special character. You might have to combine your approaches to look for should-be-encoded characters as well as validating that the string decodes successfully if none are found.</p> |
6,710,461 | Can I play a youtube video in a UIWebView inline (not fullscreen)? | <p>I have looked everywhere on how to do this and haven't found an answer yet.
Is it possible to play a youtube video in a UIWebView on an iPhone inline, i.e. not fullscreen?
I know that the iPhone doesn't support flash, but youtube supports html5 and has h.264 videos doesn't it? shouldn't I be able to do this then?</p>
<p>I have set allowsInlineMediaPlayback to YES, but still it plays fullscreen.</p> | 15,189,889 | 3 | 3 | null | 2011-07-15 16:48:51.303 UTC | 13 | 2017-05-26 16:35:38.097 UTC | null | null | null | null | 581,530 | null | 1 | 16 | uiwebview|youtube|inline | 22,570 | <p>Yes you can, you need to set property on UIWebView</p>
<pre><code> webView.allowsInlineMediaPlayback=YES;
</code></pre>
<p>And you need to add &playsinline=1 to YouTube iframe embedding code.</p>
<pre><code> <iframe webkit-playsinline width="200" height="200" src="https://www.youtube.com/embed/GOiIxqcbzyM?feature=player_detailpage&playsinline=1" frameborder="0"></iframe>
</code></pre>
<p>Tested on iPhone 4S running iOS 6.1.2 works like a charm.</p> |
6,902,149 | Listing include_directories in CMake | <p>I have a cmake build in which I'm searching for a bunch of dependencies, i.e. I have many instances of:</p>
<pre><code>FIND_PACKAGE(SomePackage)
if(SOMEPACKAGE_FOUND)
include_directories(${SOMEPACKAGE_INCLUDE_DIR})
link_libraries(${SOMEPACKAGE_LIBRARIES})
endif(SOMEPACKAGE_FOUND)
</code></pre>
<p>Now, I want to add a custom command to build a precompiled header file, but to do this I need to know all of the paths added by my <code>include_directories</code> calls. How can I get a list of these directories (preferably with the proper -I/path/to/directory format) so that I can add them to my custom command?</p> | 6,904,431 | 3 | 0 | null | 2011-08-01 17:33:49.487 UTC | 20 | 2022-09-20 06:27:49.71 UTC | null | null | null | null | 237,092 | null | 1 | 71 | cmake | 78,486 | <p>You can use the get_property command to retrieve the value of the directory property
<code>INCLUDE_DIRECTORIES</code></p>
<p>Something like this:</p>
<pre><code>get_property(dirs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES)
foreach(dir ${dirs})
message(STATUS "dir='${dir}'")
endforeach()
</code></pre>
<p>The value of this directory property only tracks the include_directories commands that have occurred previously in the same CMakeLists file, or that have been inherited from previous occurrences in a parent CMakeLists file. If your find_package and include_directories commands are scattered about throughout many subdirectories, this becomes a challenging issue.</p>
<p>If you get to that point, you may consider overriding the include_directories command with your own function or macro and track the values passed to it yourself. Or, simply accumulate them in a global property or an internal cache variable alongside each call to include_directories.</p>
<p>See the documentation here:</p>
<p><a href="https://cmake.org/cmake/help/latest/command/get_property.html" rel="nofollow noreferrer">https://cmake.org/cmake/help/latest/command/get_property.html</a></p>
<p><a href="https://cmake.org/cmake/help/latest/prop_dir/INCLUDE_DIRECTORIES.html" rel="nofollow noreferrer">https://cmake.org/cmake/help/latest/prop_dir/INCLUDE_DIRECTORIES.html</a></p> |
6,681,145 | How can I arrange an arbitrary number of ggplots using grid.arrange? | <p><strong><em>This is cross-posted on the ggplot2 google group</em></strong></p>
<p>My situation is that I'm <a href="https://github.com/briandk/granova/blob/dev/R/granova.contr.ggplot.R" rel="noreferrer" title="Click here to see the development repository for our graphical analysis of variance package in R">working on a function</a> that outputs an arbitrary number of plots (depending upon the input data supplied by the user). The function returns a list of n plots, and I'd like to lay those plots out in 2 x 2 formation. I'm struggling with the simultaneous problems of:</p>
<ol>
<li>How can I allow the flexibility to be handed an arbitrary (n) number of plots?</li>
<li>How can I also specify I want them laid out 2 x 2</li>
</ol>
<p>My current strategy uses <code>grid.arrange</code> from the <code>gridExtra</code> package. It's probably not optimal, especially since, and this is key, <em>it totally doesn't work</em>. Here's my commented sample code, experimenting with three plots:</p>
<pre><code>library(ggplot2)
library(gridExtra)
x <- qplot(mpg, disp, data = mtcars)
y <- qplot(hp, wt, data = mtcars)
z <- qplot(qsec, wt, data = mtcars)
# A normal, plain-jane call to grid.arrange is fine for displaying all my plots
grid.arrange(x, y, z)
# But, for my purposes, I need a 2 x 2 layout. So the command below works acceptably.
grid.arrange(x, y, z, nrow = 2, ncol = 2)
# The problem is that the function I'm developing outputs a LIST of an arbitrary
# number plots, and I'd like to be able to plot every plot in the list on a 2 x 2
# laid-out page. I can at least plot a list of plots by constructing a do.call()
# expression, below. (Note: it totally even surprises me that this do.call expression
# DOES work. I'm astounded.)
plot.list <- list(x, y, z)
do.call(grid.arrange, plot.list)
# But now I need 2 x 2 pages. No problem, right? Since do.call() is taking a list of
# arguments, I'll just add my grid.layout arguments to the list. Since grid.arrange is
# supposed to pass layout arguments along to grid.layout anyway, this should work.
args.list <- c(plot.list, "nrow = 2", "ncol = 2")
# Except that the line below is going to fail, producing an "input must be grobs!"
# error
do.call(grid.arrange, args.list)
</code></pre>
<p>As I am wont to do, I humbly huddle in the corner, eagerly awaiting the sagacious feedback of a community far wiser than I. Especially if I'm making this harder than it needs to be.</p> | 6,681,386 | 3 | 3 | null | 2011-07-13 15:10:44.887 UTC | 42 | 2013-08-05 03:56:05.557 UTC | null | null | null | null | 180,626 | null | 1 | 93 | r|ggplot2 | 34,401 | <p>You're ALMOST there! The problem is that <code>do.call</code> expects your args to be in a named <code>list</code> object. You've put them in the list, but as character strings, not named list items. </p>
<p>I think this should work:</p>
<pre><code>args.list <- c(plot.list, 2,2)
names(args.list) <- c("x", "y", "z", "nrow", "ncol")
</code></pre>
<p>as Ben and Joshua pointed out in the comments, I could have assigned names when I created the list:</p>
<pre><code>args.list <- c(plot.list,list(nrow=2,ncol=2))
</code></pre>
<p>or </p>
<pre><code>args.list <- list(x=x, y=y, z=x, nrow=2, ncol=2)
</code></pre> |
6,533,582 | Advantage of using 0x01 instead of 1 for an integer variable? | <p>Recently I came across a line like this </p>
<blockquote>
<p>public final static int DELETION_MASK = 0x01;</p>
</blockquote>
<p>why is it not like </p>
<blockquote>
<p>public final static int DELETION_MASK = 1;</p>
</blockquote>
<p>Is there any advantage in using the first approach other than 0xA and upper limit hexadecimals can be converted with ease?? In this case its just a constant representing 1. </p> | 6,533,619 | 4 | 1 | null | 2011-06-30 10:46:18.483 UTC | 5 | 2014-07-15 23:27:19.89 UTC | 2014-06-13 18:36:27.663 UTC | null | 2,864,740 | null | 413,636 | null | 1 | 22 | java|hex | 41,317 | <p>While there is not a difference in the code produced by the compiler, bit masks are traditionally written using the hexadecimal notation, because it's significantly easier for a human to convert to a binary form. Another common convention is to include the leading zeros when the length of the field is known. E.g. for a C <code>int</code> field, it's common to write:</p>
<pre><code>#define MASK 0x0000ffff
</code></pre>
<p>In addition, hexadecimal constants indicate to the programmer that it's <em>probably</em> a bit mask, or a value that will be somehow involved in bitwise operations and should probably be treated specially.</p>
<p>As a bonus, hexadecimal notations may also avoid issues with negative numbers: <code>0xffffffff</code> is in fact a negative number (<code>-1</code> to be exact). Rather than juggling with the sign and 2's-complement numbers you can just specify the mask in hexadecimal and be done with it.</p>
<hr>
<p>Since Java 7 you can also use <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html" rel="noreferrer"><em>binary literals</em></a> which makes it even easier for a human to understand which bits are set in a bit mask. And binary literals may make use of <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/underscores-literals.html" rel="noreferrer">underscores</a> to put the bits into separate groups.</p>
<p>That means that the following is also valid:</p>
<pre><code>public final static int DELETION_MASK = 0b0000_0001;
</code></pre> |
5,481,623 | Python dynamically add decorator to class' methods by decorating class | <p>say I have a class:</p>
<pre><code>class x:
def first_x_method(self):
print 'doing first_x_method stuff...'
def second_x_method(self):
print 'doing second_x_method stuff...'
</code></pre>
<p>and this decorator</p>
<pre><code>class logger:
@staticmethod
def log(func):
def wrapped(*args, **kwargs):
try:
print "Entering: [%s] with parameters %s" % (func.__name__, args)
try:
return func(*args, **kwargs)
except Exception, e:
print 'Exception in %s : %s' % (func.__name__, e)
finally:
print "Exiting: [%s]" % func.__name__
return wrapped
</code></pre>
<p>how would I write another decorator <code>otherdecorator</code> so that:</p>
<pre><code>@otherdecorator(logger.log)
class x:
def first_x_method(self):
print 'doing x_method stuff...'
def first_x_method(self):
print 'doing x_method stuff...'
</code></pre>
<p>the same as </p>
<pre><code>class x:
@logger.log
def first_x_method(self):
print 'doing first_x_method stuff...'
@logger.log
def second_x_method(self):
print 'doing second_x_method stuff...'
</code></pre>
<p>or in fact replace </p>
<pre><code>@otherdecorator(logger.log)
class x:
</code></pre>
<p>with </p>
<pre><code>@otherdecorator
class x:
</code></pre>
<p>where otherdecorator contains all the functionality
(I'm not a python person so be gentle)</p> | 5,481,729 | 2 | 2 | null | 2011-03-30 03:43:19.94 UTC | 10 | 2019-04-16 12:03:39.48 UTC | null | null | null | null | 30,225 | null | 1 | 10 | python|aop|decorator | 13,340 | <p>Unless there is a definite reason to use a class as a decorator, I think it is usually easier to use functions to define decorators.</p>
<p>Here is one way to create a class decorator <code>trace</code>, which decorates all methods of a class with the <code>log</code> decorator:</p>
<pre><code>import inspect
def log(func):
def wrapped(*args, **kwargs):
try:
print("Entering: [%s] with parameters %s" % (func.__name__, args))
try:
return func(*args, **kwargs)
except Exception as e:
print('Exception in %s : %s' % (func.__name__, e))
finally:
print("Exiting: [%s]" % func.__name__)
return wrapped
def trace(cls):
# https://stackoverflow.com/a/17019983/190597 (jamylak)
for name, m in inspect.getmembers(cls, lambda x: inspect.isfunction(x) or inspect.ismethod(x)):
setattr(cls, name, log(m))
return cls
@trace
class X(object):
def first_x_method(self):
print('doing first_x_method stuff...')
def second_x_method(self):
print('doing second_x_method stuff...')
x = X()
x.first_x_method()
x.second_x_method()
</code></pre>
<p>yields:</p>
<pre><code>Entering: [first_x_method] with parameters (<__main__.X object at 0x7f19e6ae2e80>,)
doing first_x_method stuff...
Exiting: [first_x_method]
Entering: [second_x_method] with parameters (<__main__.X object at 0x7f19e6ae2e80>,)
doing second_x_method stuff...
Exiting: [second_x_method]
</code></pre> |
5,536,856 | Ignore one "misspelling" in Vim | <p>Is there a way to tell Vim not to highlight a word once? For example, in "the password is abc123", I don't want to add <em>abc123</em> to the wordlist, but still wouldn't like the big red rectangle around it.</p>
<p>Clarification: I'm looking for a command that makes the spell checker ignore the current word (or last misspelling).</p> | 5,539,945 | 2 | 2 | null | 2011-04-04 09:47:46.657 UTC | 9 | 2011-05-17 09:41:07.69 UTC | 2011-05-17 09:41:07.69 UTC | null | 63,550 | null | 403,390 | null | 1 | 27 | vim|spell-checking | 6,484 | <p>When your cursor is positioned on a word that is highlighted as misspelled you can add it to your wordlist by pressing <a href="http://vimdoc.sourceforge.net/htmldoc/spell.html#zg" rel="noreferrer"><code>zg</code></a>. Vim allows you to load more than one wordlist at a time, which makes it possible to have (for example) a global wordlist, and a project specific wordlist.</p>
<p>By default, when you run <code>zg</code> it will add the current word to the first <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#'spellfile'" rel="noreferrer">spellfile</a> it finds in your runtime path for the current encoding. In my case, that turns out to be <code>~/.vim/spell/en.utf-8.add</code> when I'm working with UTF-8 encoding. Try running the following commands:</p>
<pre><code>:setlocal spellfile+=~/.vim/spell/en.utf-8.add
:setlocal spellfile+=oneoff.utf-8.add
</code></pre>
<p>That will set you up so that <code>zg</code> (or <code>1zg</code>) adds the current word to your default spellfile. But running <code>2zg</code> would add the current word to a file called <code>oneoff.utf-8.add</code>, in the same directory as the file that you are working on. If the file doesn't exist, Vim will try to create it for you.</p>
<p>When you open the file again in the future, you will have to run the same two commands to make Vim check the <code>oneoff.utf-8.add</code> spellfile. Unfortunately, Vim does not allow you to set the spellfile option in a <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#modeline" rel="noreferrer">modeline</a>, so if you want to run these commands automatically when the file opens, you would have to find some other way. <a href="https://stackoverflow.com/questions/456792/vim-apply-settings-on-files-in-directory">This question</a> includes a few ideas on how you might proceed.</p> |
5,444,880 | When I "Build for archive" in Xcode 4, where does the file go? | <p>When I "Build for archive" in Xcode 4, where does the file go? As in, where on my computer is the archived app saved?</p>
<p>Thanks</p> | 5,445,044 | 2 | 0 | null | 2011-03-26 19:49:44.23 UTC | 3 | 2014-07-16 16:14:03.49 UTC | null | null | null | null | 636,866 | null | 1 | 33 | xcode|ios|xcodebuild | 25,147 | <p>It depends on your build location goes (see Xcode > Preferences ... > Locations).</p>
<p>Note that "Build for Archive" doesn't archive your work in the "Archive Location" you enter there ... it just builds it as if it was being archived (so with the same pre/post-scripts being run, the right Configuration, and in your normal building location). To actually archive your work, you need to select plain old "Archive" instead of "Build for Archive".</p>
<p>Hope this helps.</p> |
5,227,688 | Max length of mediumtext? | <p>What's the max length/number of chars in a mediumtext mysql field?</p> | 5,227,752 | 2 | 0 | null | 2011-03-08 02:35:44.87 UTC | 3 | 2013-09-10 12:18:37.98 UTC | null | null | null | null | 49,153 | null | 1 | 41 | mysql | 65,444 | <p>While I think this question should have been answered by a simple Google search, I can't, realistically, vote to close under any of the existing options. As such I choose to offer an answer instead, in order that, hopefully, it won't be asked again and, if it is, subsequent questions may be closed as duplicates.</p>
<p>The <a href="http://www.htmlite.com/mysql003.php" rel="noreferrer">maximum length of a 'mediumtext' field, in MySQL, is</a>:</p>
<blockquote>
<p>A string with a maximum length of 16,777,215 characters.</p>
</blockquote>
<p>Or, <a href="http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html" rel="noreferrer">according to the docs</a>:</p>
<blockquote>
<p>L + 3 bytes, where L < 2<sup>24</sup></p>
</blockquote> |
16,490,325 | How to handle a query with special characters / (forward slash) and \ (backslash) | <p>I have a table where a column allows special characters like '/' (forward slash) and '' (back slash).</p>
<p>Now when I try to search such records from table, I am unable to get those.</p>
<p>For example: abc\def or abc/def</p>
<p>I am generating a search query like:</p>
<pre><code>select * from table1_1 where column10 like '%abc\def%'
</code></pre>
<p>It is returning 0 rows, but actually there is 1 record existing that should be returned. How do I write the query in this case?</p> | 28,310,845 | 6 | 1 | null | 2013-05-10 20:28:47.417 UTC | 3 | 2022-01-03 22:00:57.373 UTC | 2022-01-03 22:00:29.887 UTC | null | 2,756,409 | null | 198,166 | null | 1 | 11 | mysql|plsql | 48,964 | <p>The trick is to double escape ONLY the backslash; for string escapes only a single escape is needed.</p>
<p>For example</p>
<ul>
<li>The single quote <code>'</code> only needs escaping once <code>LIKE '%\'%'</code></li>
<li>But to query backslash <code>\</code> you need to double escape to <code>LIKE '%\\\\%'</code></li>
<li>If you wanted to query backslash+singlequote <code>\'</code> then <code>LIKE '%\\\\\'%'</code> (with 5 backslashes)</li>
</ul>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like" rel="nofollow noreferrer" title="source">Explanation Source</a>
excerpt:</p>
<blockquote>
<p>Because MySQL uses C escape syntax in strings (for example, “\n” to
represent a newline character), you must <strong>double any “\”</strong> that you use
in LIKE strings. For example, to search for “\n”, specify it as “\n”.
To search for “\”, specify it as “\\”; this is because the
backslashes are <strong>stripped once by the parser and again when the pattern
match is made</strong>, leaving a single backslash to be matched against.</p>
</blockquote> |
1,340,128 | Overriding ToString() of List<MyClass> | <p>I have a class MyClass, and I would like to override the method ToString() of instances of List:</p>
<pre><code>class MyClass
{
public string Property1 { get; set; }
public int Property2 { get; set; }
/* ... */
public override string ToString()
{
return Property1.ToString() + "-" + Property2.ToString();
}
}
</code></pre>
<p>I would like to have the following:</p>
<pre><code>var list = new List<MyClass>
{
new MyClass { Property1 = "A", Property2 = 1 },
new MyClass { Property1 = "Z", Property2 = 2 },
};
Console.WriteLine(list.ToString()); /* prints: A-1,Z-2 */
</code></pre>
<p>Is it possible to do so? Or I would have to subclass List<MyClass> to override the method ToString() in my subclass? Can I solve this problem using extension methods (ie, is it possible to override a method with an extension method)?</p>
<p>Thanks!</p> | 1,340,145 | 7 | 1 | null | 2009-08-27 10:18:37.19 UTC | 6 | 2014-10-22 10:05:20.95 UTC | null | null | null | null | 150,339 | null | 1 | 28 | c#|string|extension-methods|overriding|tostring | 30,407 | <p>You'll need to subclass to override any method. The point of generics is to say that you want the same behaviour regardless of the type of T. If you want different behaviour for a specific type of T then you are breaking that contract and will need to write your own class:</p>
<pre><code>public class MyTypeList : List<MyClass>
{
public override string ToString()
{
return ...
}
}
</code></pre>
<hr>
<p>Edited to add:</p>
<p>No, you can't override a method by creating an extension, but you could create a new method with a different signature that is specific to this list type:</p>
<pre><code>public static string ExtendedToString(this List<MyClass> list)
{
return ....
}
</code></pre>
<p>Used with</p>
<pre><code>List<MyClass> myClassList = new List<MyClass>
string output = myClassList.ExtendedToString();
</code></pre>
<p>I still think you're better off subclassing though...</p> |
987,761 | How do you reconcile IDisposable and IoC? | <p>I'm finally wrapping my head around IoC and DI in C#, and am struggling with some of the edges. I'm using the Unity container, but I think this question applies more broadly. </p>
<p>Using an IoC container to dispense instances that implement IDisposable freaks me out! How are you supposed to know if you should Dispose()? The instance might have been created just for you (and therefor you should Dispose() it), or it could be an instance whose lifetime is managed elsewhere (and therefor you'd better not). Nothing in the code tells you, and in fact this could change based on configuration!!! This seems deadly to me. </p>
<p>Can any IoC experts out there describe good ways to handle this ambiguity?</p> | 987,803 | 7 | 1 | null | 2009-06-12 16:48:43.71 UTC | 17 | 2015-03-05 13:49:41.09 UTC | null | null | null | null | 63,513 | null | 1 | 42 | c#|inversion-of-control|unity-container|idisposable | 11,918 | <p><a href="http://code.google.com/p/autofac/" rel="nofollow noreferrer">AutoFac</a> handles this by allowing the creation of a nested container. When the container is finished with, it automatically disposes of all IDisposable objects within it. More <a href="http://autofac.readthedocs.org/en/latest/lifetime/index.html" rel="nofollow noreferrer">here</a>.</p>
<blockquote>
<p>.. As you resolve services, Autofac tracks disposable (IDisposable) components that are resolved. <em>At the end of the unit of work, you dispose of the associated lifetime scope and Autofac will automatically clean up/dispose of the resolved services.</em></p>
</blockquote> |
699,648 | Entity Framework: Re-finding objects recently added to context | <p>I am using the entity framework and I'm having a problem with "re-finding" objects I just created... basically it goes like this: </p>
<pre><code>string theId = "someId";
private void Test()
{
using(MyEntities entities = new MyEntities())
{
EntityObject o = new EntityObject();
o.Id = theId;
entities.AddToEntityObject(o);
CallSomeOtherMethod(entities);
}
}
void CallSomeOtherMethod(MyEntities ents)
{
EntityObject search = ents.EntityObject.FirstOrDefault(o => o.Id == theId);
if(search == null)
{
Console.WriteLine("wha happened???");
}
}
</code></pre>
<p>(no guarantee the code works btw - it's all from my head)</p>
<p>Why doesn't the query "find" the EntityObject that was just created?</p>
<p>If I call SaveChanges() after the AddToEntityObject it works (which doesn't surprise me) but why doesn't it pull from the cache properly?</p>
<p>I'm still green on this stuff so I'm hoping that there's some really easy thing that I'm just overlooking...</p>
<p>Thanks</p> | 699,704 | 7 | 0 | null | 2009-03-31 00:58:01.09 UTC | 13 | 2019-10-24 05:30:28.557 UTC | 2009-04-19 07:23:24.137 UTC | null | 14,444 | dovh | 44,714 | null | 1 | 51 | entity-framework | 22,521 | <p>This happens because ents.EntityObject.WhatEver always queries the datasource. This is a design decision. They do it this way, because else they would have to execute the query against the datasource, against the local cache and then merge the results. As one of the developers pointed out in a blog (cannot remember where exactly) they were unable to handle this consistently.</p>
<p>As you can imagine there are a lot of corner an edge cases you have to handle properly. You could just find a id you created locally, created by someone else in the database. This would force you to be prepared to handle conflicts on (almost) every query. Maybe they could have made methods to query the local cache and methods to query the datasource, but that is not to smart, too.</p>
<p>You may have a look at <a href="http://code.msdn.microsoft.com/EFLazyLoading" rel="noreferrer">Transparent Lazy Loading for Entity Framework</a>. This replaces the normal code generator and you get entities that populate their related entity collections and entity references automatically on access. This avoids all the</p>
<pre><code>if (!Entity.ReleatedEntities.IsLoaded)
{
Entity.RelatedEntities.Load();
}
</code></pre>
<p>code fragments. And you can query the collections because they are always implicitly loaded. But this solution is not perfect, too. There are some issues. For example, if you create a new entity and access a collection of related entities, you will get an exception because the code is unable to retrieve the related entities from the database. There is also an issue concerning data binding and may be some more I am not aware of.</p>
<p>The good thing is that you get the source code and are able to fix the issues yourself and I am going to examine the first issue if I find some time. But I am quite sure that it will not be that easy to fix, because I expect some case were just not hitting the database if the entity has just been created is not the expected behavior. </p> |
758,036 | Predict next event occurrence, based on past occurrences | <p>I'm looking for an algorithm or example material to study for predicting future events based on known patterns. Perhaps there is a name for this, and I just don't know/remember it. Something this general may not exist, but I'm not a master of math or algorithms, so I'm here asking for direction. </p>
<p>An example, as I understand it would be something like this: </p>
<p>A static event occurs on January 1st, February 1st, March 3rd, April 4th. A simple solution would be to average the days/hours/minutes/something between each occurrence, add that number to the last known occurrence, and have the prediction. </p>
<p>What am I asking for, or what should I study? </p>
<p>There is no particular goal in mind, or any specific variables to account for. This is simply a personal thought, and an opportunity for me to learn something new. </p> | 758,124 | 8 | 0 | null | 2009-04-16 21:03:57.217 UTC | 11 | 2018-10-18 23:05:55.277 UTC | 2009-04-16 21:52:59.207 UTC | null | 31,615 | null | 26,196 | null | 1 | 17 | algorithm|language-agnostic|prediction | 10,661 | <p>I think some topics that might be worth looking into include <a href="http://en.wikipedia.org/wiki/Numerical_analysis" rel="nofollow noreferrer">numerical analysis</a>, specifically <a href="http://en.wikipedia.org/wiki/Numerical_analysis#Interpolation.2C_extrapolation.2C_and_regression" rel="nofollow noreferrer">interpolation, extrapolation, and regression</a>.</p> |
1,104,274 | Scala as the new Java? | <p>I just started exploring Scala in my free time. </p>
<p>I have to say that so far I'm very impressed. Scala sits on top of the JVM, seamlessly integrates with existing Java code and has many features that Java doesn't. </p>
<p>Beyond learning a new language, what's the downside to switching over to Scala?</p> | 1,104,634 | 9 | 9 | 2009-07-09 14:34:19.07 UTC | 2009-07-09 14:34:19.07 UTC | 9 | 2022-07-17 17:03:33.58 UTC | null | null | null | null | 43,222 | null | 1 | 33 | java|scala | 5,204 | <p>Well, the downside is that you have to be prepared for Scala to be a bit rough around the edges: </p>
<ul>
<li>you'll get the odd cryptic Scala compiler internal error</li>
<li>the IDE support isn't quite as good as Java (neither is the debugging support) </li>
<li>there will be breaks to backwards compatibility in future releases (although these will be limited) </li>
</ul>
<p>You also have to take some risk that Scala as a language will fizzle out.</p>
<p>That said, <strong>I don't think you'll look back</strong>! My experiences are positive overall; the IDE's are useable, you get used to what the cryptic compiler errors mean and, whilst your Scala codebase is small, a backwards-compatibility break is not a major hassle.</p>
<p>It's worth it for <code>Option</code>, the <em>monad</em> functionality of the collections, <em>closures</em>, the <em>actors</em> model, extractors, covariant types etc. It's an awesome language.</p>
<p>It's also of great <em>personal</em> benefit to be able to approach problems from a different angle, something that the above constructs allow and encourage.</p> |
804,123 | const unsigned char * to std::string | <p>sqlite3_column_text returns a const unsigned char*, how do I convert this to a std::string? I've tried std::string(), but I get an error.</p>
<p>Code:</p>
<pre><code>temp_doc.uuid = std::string(sqlite3_column_text(this->stmts.read_documents, 0));
</code></pre>
<p>Error:</p>
<pre><code>1>.\storage_manager.cpp(109) : error C2440: '<function-style-cast>' : cannot convert from 'const unsigned char *' to 'std::string'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
</code></pre> | 804,131 | 9 | 0 | null | 2009-04-29 20:28:18.883 UTC | 13 | 2018-07-30 17:53:21.24 UTC | null | null | null | null | 95,183 | null | 1 | 53 | c++|std | 73,610 | <p>You could try:</p>
<pre><code>temp_doc.uuid = std::string(reinterpret_cast<const char*>(
sqlite3_column_text(this->stmts.read_documents, 0)
));
</code></pre>
<p>While <code>std::string</code> could have a constructor that takes <code>const unsigned char*</code>, apparently it does not.</p>
<p>Why not, then? You could have a look at this somewhat related question: <a href="https://stackoverflow.com/questions/277655/why-do-c-streams-use-char-instead-of-unsigned-char">Why do C++ streams use char instead of unsigned char?</a></p> |
690,419 | Build and Version Numbering for Java Projects (ant, cvs, hudson) | <p>What are current best-practices for systematic build numbering and version number management in Java projects? Specifically:</p>
<ul>
<li><p>How to manage build numbers systematically in a distributed development environment</p></li>
<li><p>How to maintain version numbers in source / available to the runtime application</p></li>
<li><p>How to properly integrate with source repository</p></li>
<li><p>How to more automatically manage version numbers vs. repository tags</p></li>
<li><p>How to integrate with continuous build infrastructure</p></li>
</ul>
<p>There are quite a number of tools available, and ant (the build system we're using) has a task that will maintain a build number, but it's not clear how to manage this with multiple, concurrent developers using CVS, svn, or similar.</p>
<p>[EDIT]</p>
<p>Several good and helpful partial or specific answers have appeared below, so I'll summarize a few of them. It sounds to me like there is not really a strong "best practice" on this, rather a collection of overlapping ideas. Below, find my summaries and some resulting questions that folks might try to answer as follow-ups. [New to stackoverflow... please provide comments if I'm doing this wrong.]</p>
<ul>
<li><p>If you are using SVN, versioning of a specific checkout comes along for the ride. Build numbering can exploit this to create a unique build number that identifies the specific checkout/revision. [CVS, which we are using for legacy reasons, doesn't provide quite this level of insight... manual intervention with tags gets you part way there.]</p></li>
<li><p>If you are using maven as your build system, there is support for producing a version number from the SCM, as well as a release module for automatically producing releases. [We can't use maven, for a variety of reasons, but this helps those who can. [Thanks to <a href="https://stackoverflow.com/users/83674/marcelo-morales">marcelo-morales</a>]]</p></li>
<li><p>If you are using <a href="http://ant.apache.org" rel="noreferrer">ant</a> as your build system, the following task description can help produce a Java .properties file capturing build information, which can then be folded into your build in a number of ways. [We expanded on this idea to include hudson-derived information, thanks <a href="https://stackoverflow.com/users/79194/marty-lamb">marty-lamb</a>].</p></li>
<li><p>Ant and maven (and hudson and cruise control) provide easy means for getting build numbers into a .properties file, or into a .txt/.html file. Is this "safe" enough to keep it from being tampered with intentionally or accidentally? Is it better to compile it into a "versioning" class at build time?</p></li>
<li><p>Assertion: Build numbering should be defined/enacted in a continuous integration system like <a href="http://hudson-ci.org/" rel="noreferrer">hudson</a>. [Thanks to <a href="https://stackoverflow.com/users/83674/marcelo-morales">marcelo-morales</a>] We have taken this suggestion, but it does crack open the release engineering question: How does a release happen? Are there multiple buildnumbers in a release? Is there a meaningful relationship between buildnumbers from differing releases?</p></li>
<li><p>Question: What is the objective behind a build number? Is it used for QA? How? Is it used primarily by developers to disambiguate between multiple builds during development, or more for QA to determine what build an end-user got? If the goal is reproducibility, in theory this is what a release version number should provide -- why doesn't it? (please answer this as a part of your answers below, it will help illuminate the choices you have made/suggested...)</p></li>
<li><p>Question: Is there a place for build numbers in manual builds? Is this so problematic that EVERYONE should be using a CI solution?</p></li>
<li><p>Question: Should build numbers be checked in to the SCM? If the goal is reliably and unambiguously identifying a particular build, how to cope with a variety of continuous or manual build systems that may crash/restart/etc... </p></li>
<li><p>Question: Should a build number be short and sweet (i.e., monotonically increasing integer) so that it's easy to stick into file names for archival, easy to refer to in communication, etc... or should it be long and full of usernames, datestamps, machine names, etc?</p></li>
<li><p>Question: Please provide details about how the assignment of build numbers fits into your larger automated release process. Yes, maven lovers, we know this is done and done, but not all of us have drunk the kool-aid quite yet...</p></li>
</ul>
<p>I'd really like to flesh this out into a complete answer, at least for the concrete example of our cvs/ant/hudson setup, so someone could build a complete strategy based on this question. I'll mark as "The Answer" anyone who can give a soup-to-nuts description for this particular case (including cvs tagging scheme, relevant CI config items, and release procedure that folds the build number into the release such that it's programmatically accessible.) If you want to ask/answer for another particular configuration (say, svn/maven/cruise control) I'll link to the question from here. --JA</p>
<p>[EDIT 23 Oct 09]
I accepted the top-voted answer because I think it's a reasonable solution, while several of the other answers also include good ideas. If someone wants to take a crack at synthesizing some of these with <a href="https://stackoverflow.com/users/79194/marty-lamb">marty-lamb</a>'s, I'll consider accepting a different one. The only concern I have with marty-lamb's is that it doesn't produce a reliably serialized build number -- it depends on a local clock at the builder's system to provide unambiguous build numbers, which isn't great.</p>
<p>[Edit Jul 10]</p>
<p>We now include a class like the below. This allows the version numbers to be compiled into the final executable. Different forms of the version info are emitted in logging data, long-term archived output products, and used to trace our (sometimes years-later) analysis of output products to a specific build.</p>
<pre><code>public final class AppVersion
{
// SVN should fill this out with the latest tag when it's checked out.
private static final String APP_SVNURL_RAW =
"$HeadURL: svn+ssh://user@host/svnroot/app/trunk/src/AppVersion.java $";
private static final String APP_SVN_REVISION_RAW = "$Revision: 325 $";
private static final Pattern SVNBRANCH_PAT =
Pattern.compile("(branches|trunk|releases)\\/([\\w\\.\\-]+)\\/.*");
private static final String APP_SVNTAIL =
APP_SVNURL_RAW.replaceFirst(".*\\/svnroot\\/app\\/", "");
private static final String APP_BRANCHTAG;
private static final String APP_BRANCHTAG_NAME;
private static final String APP_SVNREVISION =
APP_SVN_REVISION_RAW.replaceAll("\\$Revision:\\s*","").replaceAll("\\s*\\$", "");
static {
Matcher m = SVNBRANCH_PAT.matcher(APP_SVNTAIL);
if (!m.matches()) {
APP_BRANCHTAG = "[Broken SVN Info]";
APP_BRANCHTAG_NAME = "[Broken SVN Info]";
} else {
APP_BRANCHTAG = m.group(1);
if (APP_BRANCHTAG.equals("trunk")) {
// this isn't necessary in this SO example, but it
// is since we don't call it trunk in the real case
APP_BRANCHTAG_NAME = "trunk";
} else {
APP_BRANCHTAG_NAME = m.group(2);
}
}
}
public static String tagOrBranchName()
{ return APP_BRANCHTAG_NAME; }
/** Answers a formatter String descriptor for the app version.
* @return version string */
public static String longStringVersion()
{ return "app "+tagOrBranchName()+" ("+
tagOrBranchName()+", svn revision="+svnRevision()+")"; }
public static String shortStringVersion()
{ return tagOrBranchName(); }
public static String svnVersion()
{ return APP_SVNURL_RAW; }
public static String svnRevision()
{ return APP_SVNREVISION; }
public static String svnBranchId()
{ return APP_BRANCHTAG + "/" + APP_BRANCHTAG_NAME; }
public static final String banner()
{
StringBuilder sb = new StringBuilder();
sb.append("\n----------------------------------------------------------------");
sb.append("\nApplication -- ");
sb.append(longStringVersion());
sb.append("\n----------------------------------------------------------------\n");
return sb.toString();
}
}
</code></pre>
<p>Leave comments if this deserves to become a wiki discussion.</p> | 693,169 | 9 | 2 | null | 2009-03-27 16:18:51.3 UTC | 98 | 2016-02-18 12:22:36.49 UTC | 2017-05-23 12:26:03.74 UTC | andersoj | -1 | andersoj | 83,695 | null | 1 | 137 | java|build|build-process|versioning | 93,662 | <p>For several of my projects I capture the subversion revision number, time, user who ran the build, and some system information, stuff them into a .properties file that gets included in the application jar, and read that jar at runtime.</p>
<p>The ant code looks like this:</p>
<pre class="lang-xml prettyprint-override"><code><!-- software revision number -->
<property name="version" value="1.23"/>
<target name="buildinfo">
<tstamp>
<format property="builtat" pattern="MM/dd/yyyy hh:mm aa" timezone="America/New_York"/>
</tstamp>
<exec executable="svnversion" outputproperty="svnversion"/>
<exec executable="whoami" outputproperty="whoami"/>
<exec executable="uname" outputproperty="buildsystem"><arg value="-a"/></exec>
<propertyfile file="path/to/project.properties"
comment="This file is automatically generated - DO NOT EDIT">
<entry key="buildtime" value="${builtat}"/>
<entry key="build" value="${svnversion}"/>
<entry key="builder" value="${whoami}"/>
<entry key="version" value="${version}"/>
<entry key="system" value="${buildsystem}"/>
</propertyfile>
</target>
</code></pre>
<p>It's simple to extend this to include whatever information you might want to add.</p> |
415,192 | Best way to create a simple python web service | <p>I've been using python for years, but I have little experience with python web programming. I'd like to create a very simple web service that exposes some functionality from an existing python script for use within my company. It will likely return the results in csv. What's the quickest way to get something up? If it affects your suggestion, I will likely be adding more functionality to this, down the road.</p> | 415,338 | 9 | 2 | null | 2009-01-06 02:17:54.343 UTC | 52 | 2013-05-02 19:48:28.46 UTC | null | null | null | Jeremy Cantrell | 18,866 | null | 1 | 141 | python|web-services | 202,467 | <p>Have a look at <a href="http://werkzeug.pocoo.org/" rel="noreferrer">werkzeug</a>. Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules.</p>
<p>It includes lots of cool tools to work with http and has the advantage that you can use it with wsgi in different environments (cgi, fcgi, apache/mod_wsgi or with a plain simple python server for debugging). </p> |
106,820 | What is Java EE? | <p>I realize that literally it translates to Java Enterprise Edition. But what I'm asking is what does this really mean? When a company requires Java EE experience, what are they really asking for? Experience with EJBs? Experience with Java web apps? </p>
<p>I suspect that this means something different to different people and the definition is subjective.</p> | 106,847 | 9 | 11 | null | 2008-09-20 02:29:30.773 UTC | 102 | 2017-08-02 14:23:49.38 UTC | 2016-02-14 14:57:08.817 UTC | shs | 472,495 | shs | 292 | null | 1 | 228 | jakarta-ee | 165,750 | <p>Java EE is actually a collection of technologies and APIs for the Java platform designed to support "Enterprise" Applications which can generally be classed as large-scale, distributed, transactional and highly-available applications designed to support mission-critical business requirements. </p>
<p>In terms of what an employee is looking for in specific techs, it is quite hard to say, because the playing field has kept changing over the last five years. It really is about the <em>class</em> of problems that are being solved more than anything else. Transactions and distribution are key.</p> |
203,376 | Unit Testing Framework for Oracle PL/SQL? | <p>I've seen the question (and answer) when posed for <a href="https://stackoverflow.com/questions/202940/unit-tests-framework-for-databases">MS SQL Server</a>, though I don't yet know of one for Oracle and PL/SQL. Are there xUnit style testing frameworks for Oracle's PL/SQL? What are they?</p> | 203,381 | 10 | 1 | null | 2008-10-15 00:58:07.63 UTC | 11 | 2018-02-25 22:56:15.203 UTC | 2017-05-23 12:26:29.837 UTC | null | -1 | Kyle Burton | 19,784 | null | 1 | 24 | sql|oracle|unit-testing|plsql | 18,914 | <p>The most commonly used is probably <a href="http://utplsql.org/" rel="nofollow noreferrer">utPLSQL</a></p>
<p>The original author of this toolkit now works for Quest, which has a <a href="http://www.quest.com/code-tester-for-oracle/" rel="nofollow noreferrer">commercial PL/SQL unit testing application</a>.</p> |
205,087 | jQuery .ready in a dynamically inserted iframe | <p>We are using jQuery <a href="http://jquery.com/demo/thickbox/" rel="noreferrer">thickbox</a> to dynamically display an iframe when someone clicks on a picture. In this iframe, we are using <a href="http://devkick.com/lab/galleria/demo_01.htm" rel="noreferrer">galleria</a> a javascript library to display multiple pictures.</p>
<p>The problem seems to be that <code>$(document).ready</code> in the iframe seems to be fired too soon and the iframe content isn't even loaded yet, so galleria code is not applied properly on the DOM elements. <code>$(document).ready</code> seems to use the iframe parent ready state to decide if the iframe is ready.</p>
<p>If we extract the function called by document ready in a separate function and call it after a timeout of 100 ms. It works, but we can't take the chance in production with a slow computer.</p>
<pre><code>$(document).ready(function() { setTimeout(ApplyGalleria, 100); });
</code></pre>
<p>My question: which jQuery event should we bind to to be able to execute our code when the dynamic iframe is ready and not just it's a parent?</p> | 205,221 | 10 | 3 | null | 2008-10-15 15:09:22.577 UTC | 73 | 2020-05-23 06:59:07.203 UTC | 2011-05-30 21:37:20.68 UTC | null | 63,550 | EtienneT | 9,140 | null | 1 | 190 | javascript|jquery|iframe|thickbox|galleria | 356,886 | <p>I answered a similar question (see <a href="https://stackoverflow.com/questions/164085/javascript-callback-when-iframe-is-finished-loading">Javascript callback when IFRAME is finished loading?</a>).
You can obtain control over the iframe load event with the following code:</p>
<pre><code>function callIframe(url, callback) {
$(document.body).append('<IFRAME id="myId" ...>');
$('iframe#myId').attr('src', url);
$('iframe#myId').load(function() {
callback(this);
});
}
</code></pre>
<p>In dealing with iframes I found good enough to use load event instead of document ready event.</p> |
1,284,666 | Sessions and uploadify | <p>I'm using uploadify, and i can't set sessions in my php files, my script looks like this:</p>
<pre><code> $("#uploadify").uploadify({
'uploader' : '/extra/flash/uploadify.swf',
'script' : '/admin/uploads/artistsphotos',
'scriptData' : {'PHPSESSID' : '<?= session_id(); ?>'},
'cancelImg' : '/images/cancel.png',
'folder' : '/img/artists',
'queueID' : 'fileQueue',
'auto' : false,
'multi' : true,
'onComplete' : function(a, b, c, d, e){
},
'onAllComplete': function(event,data){
$bla = $('#art').find(':selected',this);
$fi = $bla.val();
$.ajax({
type: "POST",
url: "/admin/uploads/artistsphotosupload",
data: "artist="+$fi,
success: function(msg){
console.log(msg);
}
});
}
});
</code></pre>
<p>And in php if i try:</p>
<pre><code>$_SESSION['name'] = 'something';
</code></pre>
<p>I can't access it in another file.and i have session_start(); activated
Any solutions?</p> | 1,284,710 | 11 | 2 | null | 2009-08-16 16:20:14.863 UTC | 11 | 2017-05-26 16:25:36.7 UTC | null | null | null | null | 58,839 | null | 1 | 19 | php|jquery|session|uploadify | 19,618 | <p>Usually the session ID won't be read from POST.
You could do this:</p>
<pre><code>$_COOKIE['PHPSESSID'] = $_POST['PHPSESSID'];
session_start();
</code></pre> |
1,282,639 | Switch Git branch without files checkout | <p>Is it possible in Git to switch to another branch without checking out all files?</p>
<p>After switching branch I need to delete all files, regenerate them, commit and switch back. So checking out files is just a waste of time (and there are about 14,000 files - it is a long operation).</p>
<p>To make everything clear:</p>
<p>I need all this to upload <a href="http://toy.github.com/rb/" rel="noreferrer">documentation</a> to GitHub.</p>
<p>I have a repository with the <em>gh-pages</em> branch. When I rebuild documentation locally, I copy it to the repository directory, commit and push to GitHub. But I was not happy, because I had two copies of documentation locally. And I decided to create an empty branch and after committing, switch to empty and delete files. But switching back is a long operation - so I asked this question.</p>
<p>I know that I can just leave on the <em>gh-pages</em> branch and delete files, but I don't like dirty working trees.</p> | 1,282,894 | 11 | 3 | null | 2009-08-15 19:32:01.48 UTC | 54 | 2020-08-19 12:31:22.403 UTC | 2019-12-04 13:16:56.073 UTC | null | 63,550 | null | 96,823 | null | 1 | 131 | git|branch|git-checkout | 60,044 | <p>Yes, you can do this.</p>
<pre><code>git symbolic-ref HEAD refs/heads/otherbranch
</code></pre>
<p>If you need to commit on this branch, you'll want to reset the index too otherwise you'll end up committing something based on the last checked out branch.</p>
<pre><code>git reset
</code></pre> |
599,288 | Cross-browser window resize event - JavaScript / jQuery | <p>What is the correct (modern) method for tapping into the window resize event that works in Firefox, <a href="http://en.wikipedia.org/wiki/WebKit" rel="noreferrer">WebKit</a>, and Internet Explorer?</p>
<p>And can you turn both scrollbars on/off?</p> | 2,969,091 | 11 | 5 | null | 2009-03-01 05:12:09.7 UTC | 76 | 2017-10-06 10:31:39.773 UTC | 2011-02-03 18:56:06.75 UTC | null | 63,550 | Bruno Tyndall | 36,590 | null | 1 | 241 | javascript|jquery|cross-browser|resize | 269,819 | <p>jQuery has a <a href="http://api.jquery.com/resize/" rel="noreferrer">built-in method</a> for this:</p>
<pre><code>$(window).resize(function () { /* do something */ });
</code></pre>
<p>For the sake of UI responsiveness, you might consider using a setTimeout to call your code only after some number of milliseconds, as shown in the following example, inspired by <a href="http://snipplr.com/view/6284/jquery--window-on-resize-event/" rel="noreferrer">this</a>:</p>
<pre><code>function doSomething() {
alert("I'm done resizing for the moment");
};
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(doSomething, 100);
});
</code></pre> |
67,103 | What is the best way to improve performance of NHibernate? | <p>I have an application that uses NHibernate as its ORM and sometimes it experiences performance issues due to how the data is being accessed by it. What kind of things can be done to improve the performance of NHibernate? (Please limit to one recommendation per answer)</p> | 67,479 | 12 | 0 | null | 2008-09-15 21:22:52.957 UTC | 30 | 2017-05-12 10:45:08.847 UTC | 2009-02-25 18:01:42.6 UTC | Ray Vega | 4,872 | Ray Vega | 4,872 | null | 1 | 61 | .net|performance|nhibernate|orm|data-access-layer | 29,168 | <p>The first and most dramatic performance problem that you can run into with NHibernate is if you are creating a new session factory for every session you create. Only one session factory instance should be created for each application execution and all sessions should be created by that factory.</p>
<p>Along those lines, you should continue using the same session as long as it makes sense. This will vary by application, but for most web applications, a single session per request is recommended. If you throw away your session frequently, you aren't gaining the benefits of its cache. Intelligently using the session cache can change a routine with a linear (or worse) number of queries to a constant number without much work. </p>
<p>Equally important is that you want to make sure that you are lazy loading your object references. If you are not, entire object graphs could be loaded for even the most simple queries. There are only certain reasons not to do this, but it is always better to start with lazy loading and switch back as needed.</p>
<p>That brings us to eager fetching, the opposite of lazy loading. While traversing object hierarchies or looping through collections, it can be easy to lose track of how many queries you are making and you end up with an exponential number of queries. Eager fetching can be done on a per query basis with a FETCH JOIN. In rare circumstances, such as if there is a particular pair of tables you always fetch join, consider turning off lazy loading for that relationship.</p>
<p>As always, SQL Profiler is a great way to find queries that are running slow or being made repeatedly. At my last job we had a development feature that counted queries per page request as well. A high number of queries for a routine is the most obvious indicator that your routine is not working well with NHibernate. If the number of queries per routine or request looks good, you are probably down to database tuning; making sure you have enough memory to store execution plans and data in the cache, correctly indexing your data, etc.</p>
<p>One tricky little problem we ran into was with SetParameterList(). The function allows you to easily pass a list of parameters to a query. NHibernate implemented this by creating one parameter for each item passed in. This results in a different query plan for every number of parameters. Our execution plans were almost always getting released from the cache. Also, numerous parameters can significantly slow down a query. We did a custom hack of NHibernate to send the items as a delimited list in a single parameter. The list was separated in SQL Server by a table value function that our hack automatically inserted into the IN clause of the query. There could be other land mines like this depending on your application. SQL Profiler is the best way to find them.</p> |
262,816 | When would you call java's thread.run() instead of thread.start()? | <p>When would you call Java's <code>thread.run()</code> instead of <code>thread.start()</code>?</p> | 262,840 | 14 | 4 | null | 2008-11-04 18:21:09.237 UTC | 29 | 2017-11-22 20:27:53.133 UTC | 2017-11-22 20:27:53.133 UTC | null | 2,370,483 | Beds | 1,348 | null | 1 | 110 | java|multithreading|concurrency | 74,702 | <p>You might want to call run() in a particular unit test that is concerned strictly with functionality and not with concurrency.</p> |
1,185,524 | How do I trim whitespace? | <p>Is there a Python function that will trim whitespace (spaces and tabs) from a string?</p>
<p>So that given input <code>" \t example string\t "</code> becomes <code>"example string"</code>.</p> | 1,185,529 | 15 | 7 | null | 2009-07-26 20:54:38.63 UTC | 172 | 2022-06-22 04:15:54.28 UTC | 2022-05-21 08:59:38.437 UTC | null | 5,730,279 | null | 104,060 | null | 1 | 1,190 | python|string|whitespace|trim|strip | 1,223,556 | <p>For whitespace on both sides, use <a href="https://docs.python.org/3/library/stdtypes.html#str.strip" rel="noreferrer"><code>str.strip</code></a>:</p>
<pre><code>s = " \t a string example\t "
s = s.strip()
</code></pre>
<p>For whitespace on the right side, use <a href="https://docs.python.org/3/library/stdtypes.html#str.rstrip" rel="noreferrer"><code>str.rstrip</code></a>:</p>
<pre><code>s = s.rstrip()
</code></pre>
<p>For whitespace on the left side, use <a href="https://docs.python.org/3/library/stdtypes.html#str.lstrip" rel="noreferrer"><code>str.lstrip</code></a>:</p>
<pre><code>s = s.lstrip()
</code></pre>
<p>You can provide an argument to strip arbitrary characters to any of these functions, like this:</p>
<pre><code>s = s.strip(' \t\n\r')
</code></pre>
<p>This will strip any space, <code>\t</code>, <code>\n</code>, or <code>\r</code> characters from both sides of the string.</p>
<p>The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try <a href="https://docs.python.org/3/library/re.html#re.sub" rel="noreferrer"><code>re.sub</code></a>:</p>
<pre><code>import re
print(re.sub('[\s+]', '', s))
</code></pre>
<p>That should print out:</p>
<pre><code>astringexample
</code></pre> |
763,745 | How to get text box value in JavaScript | <p>I am trying to use JavaScript to get the value from an HTML text box but value is not coming after white space </p>
<p>For example:</p>
<pre><code><input type="text" name="txtJob" value="software engineer">
</code></pre>
<p>I only get: "software" from the above. I am using a script like this:</p>
<pre><code>var jobValue = document.getElementById('txtJob').value
</code></pre>
<p>How do I get the full value: "software engineer"?</p> | 764,711 | 16 | 0 | null | 2009-04-18 16:41:24.99 UTC | 23 | 2021-02-07 01:16:49.54 UTC | 2017-07-23 11:41:46.753 UTC | null | 438,581 | null | 84,761 | null | 1 | 104 | javascript|html | 820,408 | <p>+1 Gumbo: ‘id’ is the easiest way to access page elements. IE (pre version 8) will return things with a matching ‘name’ if it can't find anything with the given ID, but this is a bug.</p>
<blockquote>
<p>i am getting only "software".</p>
</blockquote>
<p>id-vs-name won't affect this; I suspect what's happened is that (contrary to the example code) you've forgotten to quote your ‘value’ attribute:</p>
<pre><code><input type="text" name="txtJob" value=software engineer>
</code></pre> |
808,062 | x=x+1 vs. x +=1 | <p>I'm under the impression that these two commands result in the same end, namely incrementing X by 1 but that the latter is probably more efficient.</p>
<p>If this is not correct, please explain the diff.</p>
<p>If it is correct, why should the latter be more efficient? Shouldn't they both compile to the same IL?</p>
<p>Thanks.</p> | 808,114 | 17 | 6 | null | 2009-04-30 17:15:39.43 UTC | 6 | 2009-05-01 11:51:46.767 UTC | 2009-04-30 19:00:07.12 UTC | null | 6,782 | null | 109,676 | null | 1 | 32 | vb.net|performance|operators | 26,366 | <p>From the <a href="http://msdn.microsoft.com/en-us/library/f6z5yhhs.aspx" rel="noreferrer">MSDN library for +=</a>: </p>
<blockquote>
<p>Using this operator is almost the same as specifying result = result + expression, except that result is only evaluated once.</p>
</blockquote>
<p>So they are not identical and that is why x += 1 will be more efficient.</p>
<p><strong>Update:</strong> I just noticed that my MSDN Library link was to the JScript page instead of the <a href="http://msdn.microsoft.com/en-us/library/s7s8d7f4.aspx" rel="noreferrer">VB page</a>, which does not contain the same quote.</p>
<p>Therefore upon further research and testing, that answer does not apply to VB.NET. I was wrong. Here is a sample console app:</p>
<pre><code>Module Module1
Sub Main()
Dim x = 0
Console.WriteLine(PlusEqual1(x))
Console.WriteLine(Add1(x))
Console.WriteLine(PlusEqual2(x))
Console.WriteLine(Add2(x))
Console.ReadLine()
End Sub
Public Function PlusEqual1(ByVal x As Integer) As Integer
x += 1
Return x
End Function
Public Function Add1(ByVal x As Integer) As Integer
x = x + 1
Return x
End Function
Public Function PlusEqual2(ByVal x As Integer) As Integer
x += 2
Return x
End Function
Public Function Add2(ByVal x As Integer) As Integer
x = x + 2
Return x
End Function
End Module
</code></pre>
<p>IL for both PlusEqual1 and Add1 are indeed identical:</p>
<pre><code>.method public static int32 Add1(int32 x) cil managed
{
.maxstack 2
.locals init (
[0] int32 Add1)
L_0000: nop
L_0001: ldarg.0
L_0002: ldc.i4.1
L_0003: add.ovf
L_0004: starg.s x
L_0006: ldarg.0
L_0007: stloc.0
L_0008: br.s L_000a
L_000a: ldloc.0
L_000b: ret
}
</code></pre>
<p>The IL for PlusEqual2 and Add2 are nearly identical to that as well:</p>
<pre><code>.method public static int32 Add2(int32 x) cil managed
{
.maxstack 2
.locals init (
[0] int32 Add2)
L_0000: nop
L_0001: ldarg.0
L_0002: ldc.i4.2
L_0003: add.ovf
L_0004: starg.s x
L_0006: ldarg.0
L_0007: stloc.0
L_0008: br.s L_000a
L_000a: ldloc.0
L_000b: ret
}
</code></pre> |
576,265 | Convert NSDate to NSString | <p>How do I convert, <code>NSDate</code> to <code>NSString</code> so that only the year in <strong>@"yyyy"</strong> format is output to the string?</p> | 930,786 | 19 | 0 | null | 2009-02-23 01:18:24.413 UTC | 74 | 2021-11-28 17:31:01.313 UTC | 2018-11-07 13:57:29.003 UTC | null | 12,484 | null | 40,106 | null | 1 | 258 | objective-c|swift|nsstring|nsdate | 325,868 | <p>How about...</p>
<pre><code>NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
//Optionally for time zone conversions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
//unless ARC is active
[formatter release];
</code></pre>
<p><strong>Swift 4.2 :</strong></p>
<pre><code>func stringFromDate(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
return formatter.string(from: date)
}
</code></pre> |
553,463 | jQuery AJAX Character Encoding | <p>I'm currently coding a French website. There's a schedule page, where a link on the side can be used to load another day's schedule.</p>
<p>Here's the JS I'm using to do this:</p>
<pre><code> <script type="text/javascript">
function load(y) {
$.get(y,function(d) {
$("#replace").html(d);
mod();
});
}
function mod() {
$("#dates a").click(function() {
y = $(this).attr("href");
load(y);
return false;
});
}
mod();
</script>
</code></pre>
<p>The actual AJAX works like a charm. My problem lies with the response to the request.</p>
<p>Because it is a French website, there are many accented letters. I'm using the ISO-8859-15 charset for that very reason. However, in the response to my AJAX request, the accents are becoming ?'s because the character encoding seems to be changed back to UTF-8.</p>
<p>How do I avoid this? I've already tried adding some PHP at the top of the requested documents to set the character set:</p>
<pre><code><?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>
</code></pre>
<p>But that doesn't seem to work either. Any thoughts?</p>
<p>Also, while any of you are looking here...why does the rightmost column seem to become smaller when a new page is loaded, causing the table to distort and each <code><li></code> within the <code><td></code> to wrap to the next line?</p>
<p>Cheers</p> | 553,472 | 23 | 0 | null | 2009-02-16 14:30:49.807 UTC | 29 | 2020-04-26 23:01:43.177 UTC | 2014-02-12 10:42:26.243 UTC | null | 906,523 | Salty | 50,548 | null | 1 | 60 | jquery|ajax|character-encoding | 349,970 | <p>UTF-8 is supposed to handle all accents and foreign chars - why not use it on your data source? </p>
<p><strong>EDIT</strong><br>
[<a href="https://web.archive.org/web/20090220110811/http://blog.yoavfarhi.com/test.html" rel="noreferrer">Archive copy of the test file.</a>] with your data </p>
<p>Everything should be UTF-8 in the first place. I loaded the files in notepad++, converted to utf-8 and manually changed the charactes to accents were needed. Once done everything's working like a charm.</p>
<p>BTW, unless your server is defined to php-process .html files, the files you're loading with ajax aren't getting your iso charset. If you insist on using the iso charset, request a php file instead of an html file, and define the charset in the header (not in the file itself)</p> |
805,547 | How do I sort an NSMutableArray with custom objects in it? | <p>What I want to do seems pretty simple, but I can't find any answers on the web. I have an <code>NSMutableArray</code> of objects, and let's say they are 'Person' objects. I want to sort the <code>NSMutableArray</code> by Person.birthDate which is an <code>NSDate</code>.</p>
<p>I think it has something to do with this method:</p>
<pre><code>NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];
</code></pre>
<p>In Java I would make my object implement Comparable, or use Collections.sort with an inline custom comparator...how on earth do you do this in Objective-C?</p> | 805,589 | 27 | 0 | null | 2009-04-30 06:10:56.923 UTC | 515 | 2021-06-07 14:32:11.3 UTC | 2017-11-28 13:57:32.313 UTC | null | 63,550 | null | 6,044 | null | 1 | 1,314 | ios|objective-c|sorting|cocoa-touch|nsmutablearray | 480,645 | <h2>Compare method</h2>
<p>Either you implement a compare-method for your object:</p>
<pre><code>- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
}
NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
</code></pre>
<h2>NSSortDescriptor (better)</h2>
<p>or usually even better:</p>
<pre><code>NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
</code></pre>
<p>You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/Reference/Reference.html" rel="noreferrer">the documentation</a>.</p>
<h2>Blocks (shiny!)</h2>
<p>There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:</p>
<pre><code>NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(Person *a, Person *b) {
return [a.birthDate compare:b.birthDate];
}];
</code></pre>
<h1>Performance</h1>
<p>The <code>-compare:</code> and block-based methods will be quite a bit faster, in general, than using <code>NSSortDescriptor</code> as the latter relies on KVC. The primary advantage of the <code>NSSortDescriptor</code> method is that it provides a way to define your sort order using data, rather than code, which makes it easy to e.g. set things up so users can sort an <code>NSTableView</code> by clicking on the header row.</p> |
812,717 | Is there any reason to use C instead of C++ for embedded development? | <h2>Question</h2>
<p>I have two compilers on my hardware C++ and C89</p>
<p>I'm thinking about using C++ with classes but without polymorphism (to avoid vtables).
The main reasons I’d like to use C++ are:</p>
<ul>
<li>I prefer to use “inline” functions instead of macro definitions.</li>
<li>I’d like to use namespaces as I prefixes clutter the code.</li>
<li>I see C++ a bit type safer mainly because of templates, and verbose casting.</li>
<li>I really like overloaded functions and constructors (used for automatic casting).</li>
</ul>
<p>Do you see any reason to stick with C89 when developing for very limited hardware (4kb of RAM)?</p>
<h2>Conclusion</h2>
<p>Thank you for your answers, they were really helpful! </p>
<p>I thought the subject through and I will stick with C mainly because:</p>
<ol>
<li>It is easier to predict actual code in C and this is really important if you have only 4kb of ram. </li>
<li>My team consists mainly of C developers, so advanced C++ features won't be frequently used.</li>
<li>I've found a way to inline functions in my C compiler (C89).</li>
</ol>
<p>It is hard to accept one answer as you provided so many good answers.
Unfortunately I can't create a wiki and accept it, so I will choose one answer that made me think most.</p> | 815,197 | 29 | 8 | null | 2009-05-01 18:51:58.893 UTC | 48 | 2021-10-30 03:08:33.173 UTC | 2014-09-19 19:28:46.843 UTC | null | 679,692 | null | 80,869 | null | 1 | 93 | c++|c|embedded|c89 | 56,360 | <p>Two reasons for using C over C++:</p>
<ol>
<li>For a lot of embedded processors, either there is no C++ compiler, or you have to pay extra for it.</li>
<li>My experience is that a signficant proportion of embedded software engineers have little or no experience of C++ -- either because of (1), or because it tends not to be taught on electronic engineeering degrees -- and so it would be better to stick with what they know.</li>
</ol>
<p>Also, the original question, and a number of comments, mention the 4 Kb of <em>RAM</em>. For a typical embedded processor, the amount of RAM is (mostly) unrelated to the code size, as the code is stored, and run from, flash.</p>
<p>Certainly, the amount of code storage space is something to bear in mind, but as new, more capacious, processors appear on the market, it's less of an issue than it used to be for all but the most cost-sensitive projects.</p>
<p>On the use of a subset of C++ for use with embedded systems: there is now a <a href="http://www.misra-cpp.com/" rel="noreferrer">MISRA C++</a> standard, which may be worth a look.</p>
<p><strong>EDIT:</strong> See also <a href="https://stackoverflow.com/questions/1223710">this question</a>, which led to a debate about C vs C++ for embedded systems.</p> |
600,293 | How to check if a number is a power of 2 | <p>Today I needed a simple algorithm for checking if a number is a power of 2.</p>
<p>The algorithm needs to be:</p>
<ol>
<li>Simple</li>
<li>Correct for any <code>ulong</code> value.</li>
</ol>
<p>I came up with this simple algorithm:</p>
<pre><code>private bool IsPowerOfTwo(ulong number)
{
if (number == 0)
return false;
for (ulong power = 1; power > 0; power = power << 1)
{
// This for loop used shifting for powers of 2, meaning
// that the value will become 0 after the last shift
// (from binary 1000...0000 to 0000...0000) then, the 'for'
// loop will break out.
if (power == number)
return true;
if (power > number)
return false;
}
return false;
}
</code></pre>
<p>But then I thought: How about checking if log<sub>2</sub> x is an exactly a round number? When I checked for 2^63+1, <code>Math.Log()</code> returned exactly 63 because of rounding. So I checked if 2 to the power 63 is equal to the original number and it is, because the calculation is done in <code>double</code>s and not in exact numbers.</p>
<pre><code>private bool IsPowerOfTwo_2(ulong number)
{
double log = Math.Log(number, 2);
double pow = Math.Pow(2, Math.Round(log));
return pow == number;
}
</code></pre>
<p>This returned <code>true</code> for the given wrong value: <code>9223372036854775809</code>.</p>
<p>Is there a better algorithm?</p> | 600,306 | 30 | 4 | null | 2009-03-01 19:01:29.753 UTC | 279 | 2022-05-14 03:13:45.407 UTC | 2021-12-14 19:49:59.59 UTC | user4237459 | 225,647 | configurator | 9,536 | null | 1 | 689 | c#|algorithm|math | 351,252 | <p>There's a simple trick for this problem:</p>
<pre><code>bool IsPowerOfTwo(ulong x)
{
return (x & (x - 1)) == 0;
}
</code></pre>
<p>Note, this function will report <code>true</code> for <code>0</code>, which is not a power of <code>2</code>. If you want to exclude that, here's how:</p>
<pre><code>bool IsPowerOfTwo(ulong x)
{
return (x != 0) && ((x & (x - 1)) == 0);
}
</code></pre>
<h3>Explanation</h3>
<p>First and foremost the bitwise binary & operator from MSDN definition:</p>
<blockquote>
<p>Binary & operators are predefined for the integral types and bool. For
integral types, & computes the logical bitwise AND of its operands.
For bool operands, & computes the logical AND of its operands; that
is, the result is true if and only if both its operands are true.</p>
</blockquote>
<p>Now let's take a look at how this all plays out:</p>
<p>The function returns boolean (true / false) and accepts one incoming parameter of type unsigned long (x, in this case). Let us for the sake of simplicity assume that someone has passed the value 4 and called the function like so:</p>
<pre><code>bool b = IsPowerOfTwo(4)
</code></pre>
<p>Now we replace each occurrence of x with 4:</p>
<pre><code>return (4 != 0) && ((4 & (4-1)) == 0);
</code></pre>
<p>Well we already know that 4 != 0 evals to true, so far so good. But what about:</p>
<pre><code>((4 & (4-1)) == 0)
</code></pre>
<p>This translates to this of course:</p>
<pre><code>((4 & 3) == 0)
</code></pre>
<p>But what exactly is <code>4&3</code>?</p>
<p>The binary representation of 4 is 100 and the binary representation of 3 is 011 (remember the & takes the binary representation of these numbers). So we have:</p>
<pre><code>100 = 4
011 = 3
</code></pre>
<p>Imagine these values being stacked up much like elementary addition. The <code>&</code> operator says that if both values are equal to 1 then the result is 1, otherwise it is 0. So <code>1 & 1 = 1</code>, <code>1 & 0 = 0</code>, <code>0 & 0 = 0</code>, and <code>0 & 1 = 0</code>. So we do the math:</p>
<pre><code>100
011
----
000
</code></pre>
<p>The result is simply 0. So we go back and look at what our return statement now translates to:</p>
<pre><code>return (4 != 0) && ((4 & 3) == 0);
</code></pre>
<p>Which translates now to:</p>
<pre><code>return true && (0 == 0);
</code></pre>
<pre><code>return true && true;
</code></pre>
<p>We all know that <code>true && true</code> is simply <code>true</code>, and this shows that for our example, 4 is a power of 2.</p> |
6,764,197 | SQL to Query text in access with an apostrophe in it | <p>I am trying to query a name (Daniel O'Neal) in column names <code>tblStudents</code> in an Access database, however Access reports a syntax error with the statement:</p>
<pre><code>Select * from tblStudents where name like 'Daniel O'Neal'
</code></pre>
<p>due to the apostrophe in the name.</p>
<p>How do I overcome this?</p> | 6,764,230 | 5 | 0 | null | 2011-07-20 15:12:33.9 UTC | 8 | 2021-02-17 09:39:43.357 UTC | 2021-02-17 09:39:43.357 UTC | null | 636,987 | null | 825,996 | null | 1 | 33 | sql|ms-access | 144,426 | <p>You escape <strong><code>'</code></strong> by doubling it, so:</p>
<pre><code>Select * from tblStudents where name like 'Daniel O''Neal'
</code></pre>
<p>Note that if you're accepting "Daniel O'Neal" from user input, the broken quotation is a serious security issue. You should always sanitize the string or use parametrized queries.</p> |
6,995,129 | How to get a jqGrid selected row cells value | <p>Does anyone know how to get the cells value of the selected row of JQGrid ? i m using mvc with JQGrid, i want to access the value of the hidden column of the selected row ?</p> | 6,995,271 | 6 | 1 | null | 2011-08-09 11:01:30.253 UTC | 8 | 2020-05-27 13:17:26.627 UTC | 2015-03-04 18:47:39.43 UTC | null | 219,406 | null | 2,560,942 | null | 1 | 35 | jquery|asp.net-mvc|jqgrid|jqgrid-asp.net | 178,940 | <p>First you can get the <code>rowid</code> of the selected row with respect of <code>getGridParam</code> method and <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options" rel="noreferrer">'selrow'</a> as the parameter and then you can use <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods" rel="noreferrer">getCell</a> to get the cell value from the corresponding column:</p>
<pre><code>var myGrid = $('#list'),
selRowId = myGrid.jqGrid ('getGridParam', 'selrow'),
celValue = myGrid.jqGrid ('getCell', selRowId, 'columnName');
</code></pre>
<p>The <code>'columnName'</code> should be the same name which you use in the <code>'name'</code> property of the <code>colModel</code>. If you need values from many column of the selected row you can use <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods" rel="noreferrer">getRowData</a> instead of <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods" rel="noreferrer">getCell</a>.</p> |
6,716,748 | How to change a TextView's text by pressing a Button | <p>I want to change the of a <code>TextView</code> by pressing a <code>Button</code>, but don't understand how to do it properly.</p>
<p>This is part of my layout:</p>
<pre><code><TextView android:id="@+id/counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change text!" />
</code></pre>
<p>And this is my activity:</p>
<pre><code>public class Click extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
// ???
}
});
}
}
</code></pre>
<p>What should I put inside <code>onClick()</code> method?</p> | 6,716,760 | 7 | 0 | null | 2011-07-16 10:22:22.56 UTC | 2 | 2016-02-16 14:50:12.317 UTC | 2012-02-11 06:27:26.987 UTC | null | 272,770 | null | 272,770 | null | 1 | 11 | android|button|textview | 71,227 | <ol>
<li>Find the textview by id</li>
<li>Change the text by invoking <code>yourTextView.setText("New text");</code></li>
</ol>
<p>Refer <a href="https://developer.android.com/reference/android/view/View.html#findViewById(int)" rel="noreferrer"><code>findViewById</code></a> and <a href="https://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)" rel="noreferrer"><code>setText</code></a> methods.</p> |
6,685,457 | Header file inclusion static analysis tools? | <p>A colleague recently revealed to me that a single source file of ours includes over 3,400 headers during compile time. We have over 1,000 translation units that get compiled in a build, resulting in a huge performance penalty over headers that surely aren't all used.</p>
<p>Are there any static analysis tools that would be able to shed light on the trees in such a forest, specifically giving us the ability to decide which ones we should work on paring out?</p>
<p><strong>UPDATE</strong></p>
<p>Found some interesting information on the cost of including a header file (and the types of include guards to optimize its inclusion) <a href="http://bobarcher.org/software/include/index.html" rel="nofollow noreferrer">here</a>, originating from <a href="https://stackoverflow.com/questions/6686836/how-expensive-it-is-for-the-compiler-to-process-an-include-guarded-header">this question</a>.</p> | 6,685,693 | 8 | 3 | null | 2011-07-13 20:48:44.867 UTC | 12 | 2017-04-02 04:56:22.81 UTC | 2017-05-23 11:54:22.003 UTC | null | -1 | null | 153,535 | null | 1 | 27 | c++|c|static-analysis|header-files | 9,826 | <p>The output of <code>gcc -w -H <file></code> might be useful (If you parse it and put some counts in) the <code>-w</code> is there to suppress all warnings, which might be awkward to deal with.</p>
<p>From the gcc docs:</p>
<blockquote>
<p>-H</p>
<p>Print the name of each header file used, in addition to other normal activities. Each name is indented to show how deep in the
<code>#include</code> stack it is. Precompiled header files are also printed,
even if they are found to be invalid; an invalid precompiled header
file is printed with <code>...x</code> and a valid one with <code>...!</code>.</p>
</blockquote>
<p>The output looks like this:</p>
<pre><code>. /usr/include/unistd.h
.. /usr/include/features.h
... /usr/include/bits/predefs.h
... /usr/include/sys/cdefs.h
.... /usr/include/bits/wordsize.h
... /usr/include/gnu/stubs.h
.... /usr/include/bits/wordsize.h
.... /usr/include/gnu/stubs-64.h
.. /usr/include/bits/posix_opt.h
.. /usr/include/bits/environments.h
... /usr/include/bits/wordsize.h
.. /usr/include/bits/types.h
... /usr/include/bits/wordsize.h
... /usr/include/bits/typesizes.h
.. /usr/lib/x86_64-linux-gnu/gcc/x86_64-linux-gnu/4.5.2/include/stddef.h
.. /usr/include/bits/confname.h
.. /usr/include/getopt.h
. /usr/include/stdio.h
.. /usr/lib/x86_64-linux-gnu/gcc/x86_64-linux-gnu/4.5.2/include/stddef.h
.. /usr/include/libio.h
... /usr/include/_G_config.h
.... /usr/lib/x86_64-linux-gnu/gcc/x86_64-linux-gnu/4.5.2/include/stddef.h
.... /usr/include/wchar.h
... /usr/lib/x86_64-linux-gnu/gcc/x86_64-linux-gnu/4.5.2/include/stdarg.h
.. /usr/include/bits/stdio_lim.h
.. /usr/include/bits/sys_errlist.h
Multiple include guards may be useful for:
/usr/include/bits/confname.h
/usr/include/bits/environments.h
/usr/include/bits/predefs.h
/usr/include/bits/stdio_lim.h
/usr/include/bits/sys_errlist.h
/usr/include/bits/typesizes.h
/usr/include/gnu/stubs-64.h
/usr/include/gnu/stubs.h
/usr/include/wchar.h
</code></pre> |
6,950,960 | How can I set the JDK NetBeans runs on? | <p>I have the older NetBeans 6.7, NetBeans 6.9, and NetBeans 7.0, which used to run on jdk1.6.0_21 and jdk1.6.0_25. Now I've removed those JDKs and only have jdk1.6.0_26 and jdk1.7.0 left, but I still want to keep the older versions of NetBeans, but now when I run them, I get this message:</p>
<blockquote>
<p>"Cannot locate java installation in specified jdkhome C:\Program Files (x86)\Java\jdk1.6.0_25 <br />
Do you want to try to use default version?"</p>
</blockquote>
<p>I tried to find where it's looking for the "jdk1.6.0_25", and updated a few configuration files in "C:\Program Files (x86)\NetBeans 6.7" and "C:\Users\USER.nbi\registry.xml", and yet the message keeps coming. Where and what do I need to change to point it to <code>C:\Program Files (x86)\Java\jdk1.6.0_26</code>?</p> | 6,958,342 | 9 | 0 | null | 2011-08-05 03:06:27.453 UTC | 56 | 2022-07-10 13:34:18.343 UTC | 2021-10-04 10:59:50.71 UTC | null | 63,550 | null | 32,834 | null | 1 | 223 | java|netbeans | 314,101 | <p>Thanks to <a href="https://stackoverflow.com/questions/6950960/how-can-i-set-the-jdk-netbeans-runs-on/6951067#6951067">Kasun Gajasinghe's tip</a>, I found the solution in the "suggested" link. Update the following file (replace <strong>7.x</strong> with your NetBeans version):</p>
<pre class="lang-none prettyprint-override"><code>C:\Program Files\NetBeans 7.x\etc\netbeans.conf
</code></pre>
<p>Change the following line to point it where your Java installation is:</p>
<pre class="lang-none prettyprint-override"><code>netbeans_jdkhome="C:\Program Files\Java\jdk1.7xxxxx"
</code></pre>
<p>You may need administrator privileges to edit <code>netbeans.conf</code>.</p> |
6,921,827 | Best way to populate a <SELECT> box with TimeZones | <p>I need to display a timezone selector as a user control, which always seems easier than it really is. Internally, I store everything with a DateTimeZone Identifier, as that seems to be the smartest way to have the level of accuracy I need, as this project bridges real-world times as it is tied to terrestrial media.</p>
<p>What I don't want to do is present a select box with 300+ time zones, nor do I want to create faked timezone offsets with something like 'UTC-8' (which loses not only DST info, but the actual dates that the DST falls on).</p>
<p>In the end, I'll need a select with options containing the proper TZD Identifiers, something like this (the bracketed #s aren't necessary, just for potential end-user illustration):</p>
<pre><code><select>
<option value="America/Los_Angeles">Los Angeles [UTC-7 | DST]</option>
...
</select>
</code></pre>
<p>Does anyone have any pointers for building this list? All of the solutions I've googled have been problematic in one way or another.</p>
<hr>
<p>I've added a bounty in case that might entice somebody to share a nicer answer with us. : )</p> | 7,022,536 | 12 | 6 | null | 2011-08-03 04:58:42.14 UTC | 24 | 2019-07-18 22:15:36.92 UTC | 2011-08-10 10:37:51.003 UTC | null | 754,393 | null | 754,393 | null | 1 | 44 | php | 25,575 | <pre><code>function formatOffset($offset) {
$hours = $offset / 3600;
$remainder = $offset % 3600;
$sign = $hours > 0 ? '+' : '-';
$hour = (int) abs($hours);
$minutes = (int) abs($remainder / 60);
if ($hour == 0 AND $minutes == 0) {
$sign = ' ';
}
return $sign . str_pad($hour, 2, '0', STR_PAD_LEFT) .':'. str_pad($minutes,2, '0');
}
$utc = new DateTimeZone('UTC');
$dt = new DateTime('now', $utc);
echo '<select name="userTimeZone">';
foreach(DateTimeZone::listIdentifiers() as $tz) {
$current_tz = new DateTimeZone($tz);
$offset = $current_tz->getOffset($dt);
$transition = $current_tz->getTransitions($dt->getTimestamp(), $dt->getTimestamp());
$abbr = $transition[0]['abbr'];
echo '<option value="' .$tz. '">' .$tz. ' [' .$abbr. ' '. formatOffset($offset). ']</option>';
}
echo '</select>';
</code></pre>
<p>The above will output all of the timezones in select menu with the following format:</p>
<pre><code><select name="userTimeZone">
<option value="America/Los_Angeles">America/Los_Angeles [PDT -7]</option>
</select>
</code></pre> |
45,460,896 | Why do Consumers accept lambdas with statement bodies but not expression bodies? | <p>The following code surprisingly is compiling successfully:</p>
<pre><code>Consumer<String> p = ""::equals;
</code></pre>
<p>This too:</p>
<pre><code>p = s -> "".equals(s);
</code></pre>
<p>But this is fails with the error <code>boolean cannot be converted to void</code> as expected:</p>
<pre><code>p = s -> true;
</code></pre>
<p>Modification of the second example with parenthesis also fails:</p>
<pre><code>p = s -> ("".equals(s));
</code></pre>
<p>Is it a bug in Java compiler or is there a type inference rule I don't know about?</p> | 45,461,066 | 3 | 5 | null | 2017-08-02 12:27:40.407 UTC | 15 | 2018-01-16 13:43:58.437 UTC | 2017-08-02 13:10:10.38 UTC | null | 1,898,563 | null | 2,865,757 | null | 1 | 62 | java|lambda|java-8|type-inference | 6,523 | <p>First, it's worth looking at what a <code>Consumer<String></code> actually is. <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html" rel="noreferrer">From the documentation</a>:</p>
<blockquote>
<p>Represents an operation that <strong>accepts a single input argument and
returns no result</strong>. Unlike most other functional interfaces, Consumer
is expected to operate via side-effects.</p>
</blockquote>
<p>So it's a function that accepts a String and returns nothing.</p>
<pre><code>Consumer<String> p = ""::equals;
</code></pre>
<p>Compiles successfully because <code>equals</code> can take a String (and, indeed, any Object). The result of equals is just ignored.*</p>
<pre><code>p = s -> "".equals(s);
</code></pre>
<p>This is exactly the same, but with different syntax. The compiler knows not to add an implicit <code>return</code> because a <code>Consumer</code> should not return a value. It <em>would</em> add an implicit <code>return</code> if the lambda was a <code>Function<String, Boolean></code> though.</p>
<pre><code>p = s -> true;
</code></pre>
<p>This takes a String (<code>s</code>) but because <code>true</code> is an expression and not a statement, the result cannot be ignored in the same way. The compiler <em>has to</em> add an implicit <code>return</code> because an expression can't exist on its own. Thus, this <em>does</em> have a return: a boolean. Therefore it's not a <code>Consumer</code>.**</p>
<pre><code>p = s -> ("".equals(s));
</code></pre>
<p>Again, this is an <em>expression</em>, not a statement. Ignoring lambdas for a moment, you will see the line <code>System.out.println("Hello");</code> will similarly fail to compile if you wrap it in parentheses.</p>
<hr>
<p>*From <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-LambdaBody" rel="noreferrer">the spec</a>:</p>
<blockquote>
<p>If the body of a lambda is a statement expression (that is, an expression that would be allowed to stand alone as a statement), it is compatible with a void-producing function type; any result is simply discarded.</p>
</blockquote>
<p>**From <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.3" rel="noreferrer">the spec</a> (thanks, <a href="https://stackoverflow.com/users/1059372/eugene">Eugene</a>):</p>
<blockquote>
<p>A lambda expression is congruent with a [void-producing] function type if ...
the lambda body is either a statement expression
(<a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.8" rel="noreferrer">§14.8</a>)
or a void-compatible block.</p>
</blockquote> |
51,386,600 | How to automate a power query in VBA? | <p>I have data in sheet 1. Normally I go to power query and do my transformations, then close, and load to an existing sheet 2.</p>
<p>I would like to automate this using VBA, where I can just run my power query automatically and populate the transformation to sheet 2.</p>
<p>Macro recorder doesn't seem to allow me to record the steps. And there isn't much online about doing this.</p>
<p>Trying some simpler code:</p>
<pre><code>Sub LoadToWorksheetOnly()
'Sub LoadToWorksheetOnly(query As WorkbookQuery, currentSheet As Worksheet)
' The usual VBA code to create ListObject with a Query Table
' The interface is not new, but looks how simple is the conneciton string of Power Query:
' "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & query.Name
query = Sheets("Sheet6").Range("A1").value 'here is where my query from power query is. I put the text from power query avanced editor in another sheet cell.
currentSheet = ActiveSheet.Name
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & query.Name _
, Destination:=Sheets("target").Range("$A$1")).QueryTable
.CommandType = xlCmdDefault
.CommandText = Array("SELECT * FROM [" & query.Name & "]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = False
.Refresh BackgroundQuery:=False
End With
End Sub
</code></pre>
<p>Here is my issue when trying to load to new sheet manually.</p>
<p><a href="https://i.stack.imgur.com/GSIGK.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/GSIGK.jpg" alt="enter image description here" /></a></p> | 51,641,109 | 3 | 19 | null | 2018-07-17 16:48:37.963 UTC | 10 | 2021-12-23 13:05:57.52 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 10,065,931 | null | 1 | 22 | excel|vba|powerquery | 69,246 | <p>It would be easier to set your query up using the built-in tools, not VBA. It is <strong>NOT</strong> that you can't, as it seems at least one other answerer has misunderstood my point, it is just easier with the in-built, optimized, tools, and a lot faster to alter than continually copying your data elsewhere, escaping "", tracking back M language errors etc. You can then run that query via VBA.</p>
<p>You load your data via the appropriate method which can be from file, looping files in a folder, web, database.... the list goes on. You can import from external sources as well as load from internal. Have a look <a href="https://support.office.com/en-us/article/import-data-from-external-data-sources-power-query-be4330b3-5356-486c-a168-b68e9e616f5a" rel="nofollow noreferrer">here</a> for more information on loading from external sources.</p>
<p>Once you have secured your source and it is loaded you will be presented with the query editor where you can perform your transformation <a href="https://support.office.com/en-us/article/edit-query-step-settings-power-query-3e221afc-c764-4cd9-9a96-a5a5a7688e46?ui=en-US&rs=en-US&ad=US" rel="nofollow noreferrer">steps</a>.</p>
<p>The point being that as you perform your steps using the UI, M code is written in the background and forms the basis of a re-usable query provided you don't change the source format or location. If you do, it is an easy edit to update the appropriate data source in the UI.</p>
<p>In your case, when you have performed your steps and have a query as you wish you then close and load to sheet2.</p>
<p>At this step, the first time you are setting this up you will select sheet 2 as your close and load destination:</p>
<p><a href="https://i.stack.imgur.com/NntsQm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NntsQm.png" alt="Close and load" /></a></p>
<p>NB: When you select existing sheet, ensure Sheet 2 already exists and you can manually edit Sheet2! in front of the suggested range.</p>
<hr />
<p>You are experiencing issues because you keep trying to recreate all of this with code.</p>
<p>Don't. Set it up using the UI and load to sheet2. From then on, either open the query editor to edit the steps and/or refresh the query to load the existing sheet2 with new/refreshed data.</p>
<hr />
<p>Some of the available methods for refreshing your query:</p>
<p>The query will be refreshed by VBA/Manual refreshes to the sheet it resides in (Sheet2), or to the workbook itself e.g. <code>Sheet2.Calculate</code> , <code>ThisWorkbook.RefreshAll</code>, manually pressing the refresh workbook button in the data tab (these are all overkill really)</p>
<p><a href="https://i.stack.imgur.com/4ruW9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4ruW9.png" alt="Refresh all tab" /></a></p>
<p>More targeted methods:</p>
<p>VBA for the query table in sheet 2:</p>
<pre><code>ThisWorkbook.Worksheets("Sheet2").ListObjects(1).QueryTable.Refresh BackgroundQuery:=False
</code></pre>
<p>Change the above to the appropriate table etc.</p>
<p>Right clicking in the querytable itself and selecting refresh:</p>
<p><a href="https://i.stack.imgur.com/B28cm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B28cm.png" alt="Refresh" /></a></p>
<p>Click on the refresh button in the workbook queries window on the right hand side for the query in question (icon with green circling arrows)</p>
<p><a href="https://i.stack.imgur.com/EUreo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EUreo.png" alt="Refresh" /></a></p>
<hr />
<p>The <a href="https://www.excelguru.ca/blog/2014/10/22/refresh-power-query-with-vba/" rel="nofollow noreferrer">Ken Pulls</a> VBA way (minor edit from me)</p>
<pre><code>Option Explicit
Public Sub UpdatePowerQueries()
' Macro to update my Power Query script(s)
Dim lTest As Long, cn As WorkbookConnection
On Error Resume Next
For Each cn In ThisWorkbook.Connections
lTest = InStr(1, cn.OLEDBConnection.Connection, "Provider=Microsoft.Mashup.OleDb.1", vbTextCompare)
If Err.Number <> 0 Then
Err.Clear
Exit For
End If
If lTest > 0 Then cn.Refresh
Next cn
On Error GoTo 0
End Sub
</code></pre>
<hr />
<p>There shouldn't be any real need for you to do all of this work via VBA. You may have some tricky data manipulation you feel more comfortable doing with VBA and then having PowerQuery access that processed data as source. You can fire off the whole lot by having a subroutine that calls the processing routine and then uses one of the VBA command methods listed above. There are more methods and I will add them when I have more time.</p>
<hr />
<p>Calculations:</p>
<p>If you have calculations that depend on the PowerQuery output you have 4 obvious immediate options:</p>
<ol>
<li>Add these calculations where possible into PowerQuery. It supports calculated columns, user defined functions and lots more.</li>
<li>Add the PowerQuery output to the data model and use the data model to perform calculations including calculated fields. This will give you access to time intelligence functions as well.</li>
<li>Use VBA to add the calculations to the appropriate areas in sheet 2 if the range changes on refresh</li>
<li>If range doesn't change on refresh simply put your formulas out of the way.</li>
</ol> |
15,926,697 | What is the "less than followed by dash" (<-) operator in Golang? | <p>What is the <code><-</code> operator in go language? Have seen this in many code snippets related to Go but what is the meaning of it?</p> | 15,983,335 | 3 | 0 | null | 2013-04-10 13:05:47.56 UTC | 7 | 2021-11-25 16:25:35.08 UTC | 2021-11-25 16:25:35.08 UTC | null | 1,063,716 | null | 2,343,179 | null | 1 | 36 | go | 12,192 | <p>You've already got answers, but here goes.</p>
<p>Think of a channel as a message queue.</p>
<p>If the channel is on the right of the left arrow (<-) operator, it means to dequeue an entry. Saving the entry in a variable is optional</p>
<pre><code>e <- q
</code></pre>
<p>If the channel is on the left of the left arrow operator, it means to enqueue an entry.</p>
<pre><code>q <- e
</code></pre>
<p>Further note about "dequeue" (receive) without storing in a variable: it can be used on a non-buffered queue to implement something like a "wait/notify" operation in Java: One coroutine is blocked waiting to dequeue/receive a signal, then another coroutine enqueues/sends that signal, the content of which is unimportant. (alternately, the sender could be blocked until the receiver pulls out the message)</p> |
15,648,814 | sqlalchemy.exc.ArgumentError: Can't load plugin: sqlalchemy.dialects:driver | <p>I am trying to run <code>alembic</code> migration and when I run </p>
<pre><code>alembic revision --autogenerate -m "Added initial tables"
</code></pre>
<p>It fails saying</p>
<pre><code>sqlalchemy.exc.ArgumentError: Can't load plugin: sqlalchemy.dialects:driver
</code></pre>
<p>the database url is </p>
<pre><code>postgresql+psycopg2://dev:passwd@localhost/db
</code></pre>
<p>and I even have <code>psycopg2</code> installed in my virtualenv</p>
<pre><code>$yolk -l
Flask-Login - 0.1.3 - active
Flask-SQLAlchemy - 0.16 - active
Flask - 0.9 - active
Jinja2 - 2.6 - active
Mako - 0.7.3 - active
MarkupSafe - 0.15 - active
Python - 2.7.2 - active development (/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload)
SQLAlchemy - 0.8.0 - active
Werkzeug - 0.8.3 - active
alembic - 0.4.2 - active
antiorm - 1.1.1 - active
appscript - 1.0.1 - active
distribute - 0.6.27 - active
envoy - 0.0.2 - active
osascript - 0.0.4 - active
pep8 - 1.4.5 - active
pip - 1.1 - active
psycopg2 - 2.4.6 - active
wsgiref - 0.1.2 - active development (/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7)
yolk - 0.4.3 - active
</code></pre>
<p>Whay could be causing this issue?</p> | 15,664,644 | 11 | 1 | null | 2013-03-26 22:44:13.547 UTC | 3 | 2021-12-13 15:25:57.25 UTC | null | null | null | null | 379,235 | null | 1 | 48 | python|sqlalchemy|psycopg2|alembic | 97,085 | <p>Here's how to produce an error like that:</p>
<pre><code>>>> from sqlalchemy import *
>>> create_engine("driver://")
Traceback (most recent call last):
... etc
sqlalchemy.exc.ArgumentError: Can't load plugin: sqlalchemy.dialects:driver
</code></pre>
<p>so I'd say you aren't actually using the postgresql URL you think you are - you probably are calling upon a default-generated alembic.ini somewhere.</p> |
15,843,581 | How to correctly iterate through getElementsByClassName | <p>I am Javascript beginner.</p>
<p>I am initing web page via the <code>window.onload</code>, I have to find bunch of elements by their class name (<code>slide</code>) and redistribute them into different nodes based on some logic. I have function <code>Distribute(element)</code> which takes an element as input and does the distribution. I want to do something like this (as outlined for example <a href="https://stackoverflow.com/questions/5179798/javascript-getelementsbyclassname-always-returns-none">here</a> or <a href="https://stackoverflow.com/questions/3871547/js-iterating-over-result-of-getelementsbyclassname-using-array-foreach">here</a>):</p>
<pre><code>var slides = getElementsByClassName("slide");
for(var i = 0; i < slides.length; i++)
{
Distribute(slides[i]);
}
</code></pre>
<p>however this does not do the magic for me, because <code>getElementsByClassName</code> does not actually return array, but a <a href="https://developer.mozilla.org/en-US/docs/DOM/NodeList" rel="noreferrer"><code>NodeList</code></a>, which is... </p>
<p><strong>...this is my speculation...</strong></p>
<p>...being changed inside function <code>Distribute</code> (the DOM tree is being changed inside this function, and cloning of certain nodes happen). <code>For-each</code> loop structure does not help either.</p>
<p>The variable slides act's really un-deterministicaly, through every iteration it changes it's length and order of elements wildly.</p>
<p>What is the correct way to iterate through NodeList in my case? I was thinking about filling some temporary array, but am not sure how to do that...</p>
<h2><strong>EDIT:</strong></h2>
<p>important fact I forgot to mention is that there might be one slide inside another, this is actually what changes the <code>slides</code> variable as I have just found out thanks to user <a href="https://stackoverflow.com/users/42585/alohci">Alohci</a>.</p>
<p>The solution for me was to clone each element into an array first and pass the array ono-by-one into <code>Distribute()</code> afterwards.</p> | 15,843,940 | 9 | 11 | null | 2013-04-05 21:07:52.263 UTC | 35 | 2022-05-02 05:53:15.153 UTC | 2017-05-23 10:31:17.15 UTC | null | -1 | null | 2,217,769 | null | 1 | 169 | javascript|html|dom | 266,607 | <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/NodeList" rel="noreferrer">According to MDN</a>, the way to retrieve an item from a <code>NodeList</code> is:</p>
<pre><code>nodeItem = nodeList.item(index)
</code></pre>
<p>Thus:</p>
<pre><code>var slides = document.getElementsByClassName("slide");
for (var i = 0; i < slides.length; i++) {
Distribute(slides.item(i));
}
</code></pre>
<p>I haven't tried this myself (the normal <code>for</code> loop has always worked for me), but give it a shot.</p> |
10,425,569 | RadioGroup with two columns which have ten RadioButtons | <p>I have a <code>RadioGroup</code> and I want to align buttons next to each other in two columns and five rows and I am unable to achieve it. Things I have tried:</p>
<ol>
<li><code>RelativeLayout</code> -> Outside <code>RadioGroup</code> -> Inside <code>RadioGroup</code>.
All <code>RadioButtons</code> are selected, but I want only one to be selected.</li>
<li><code>RadioGroup</code> : orientation</li>
<li>Span, stretchcolumns</li>
<li><code>TableRow</code></li>
<li><code>TableLayout</code></li>
</ol>
<p>Please let me know how create one <code>RadioGroup</code> and have two columns and many <code>RadioButtons</code> within.</p> | 10,425,792 | 13 | 3 | null | 2012-05-03 05:23:27.313 UTC | 4 | 2022-08-08 16:16:27.907 UTC | 2012-06-19 13:05:35.43 UTC | null | 493,939 | null | 923,503 | null | 1 | 30 | android|radio-button|radio-group | 38,504 | <p>You can simulate that <code>RadioGroup</code> to make it look like you have only one. For example you have <code>rg1</code> and <code>rg2</code>(<code>RadioGroups</code> with orientation set to <code>vertical</code>(the two columns)). To setup those <code>RadioGroups</code>:</p>
<pre><code>rg1 = (RadioGroup) findViewById(R.id.radioGroup1);
rg2 = (RadioGroup) findViewById(R.id.radioGroup2);
rg1.clearCheck(); // this is so we can start fresh, with no selection on both RadioGroups
rg2.clearCheck();
rg1.setOnCheckedChangeListener(listener1);
rg2.setOnCheckedChangeListener(listener2);
</code></pre>
<p>To select only one <code>RadioButton</code> in those <code>RadioGroups</code> the listeners above will be:</p>
<pre><code>private OnCheckedChangeListener listener1 = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId != -1) {
rg2.setOnCheckedChangeListener(null); // remove the listener before clearing so we don't throw that stackoverflow exception(like Vladimir Volodin pointed out)
rg2.clearCheck(); // clear the second RadioGroup!
rg2.setOnCheckedChangeListener(listener2); //reset the listener
Log.e("XXX2", "do the work");
}
}
};
private OnCheckedChangeListener listener2 = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId != -1) {
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(listener1);
Log.e("XXX2", "do the work");
}
}
};
</code></pre>
<p>To get the checked <code>RadioButton</code> from the <code>RadioGroups</code> you could do:</p>
<pre><code>int chkId1 = rg1.getCheckedRadioButtonId();
int chkId2 = rg2.getCheckedRadioButtonId();
int realCheck = chkId1 == -1 ? chkId2 : chkId1;
</code></pre>
<p>If you use the <code>check()</code> method of the <code>RadioGroup</code> you have to remember to call <code>clearCheck()</code> on the other <code>Radiogroup</code>.</p> |
10,709,464 | Create an inline SQL table on the fly (for an excluding left join) | <p>Let's assume the following:</p>
<p>Table A</p>
<pre><code>id | value
----------
1 | red
2 | orange
5 | yellow
10 | green
11 | blue
12 | indigo
20 | violet
</code></pre>
<p>I have a list of id's (<code>10, 11, 12, 13, 14</code>) that can be used to look up id's in this table. This list of id's is generated in my frontend.</p>
<p>Using purely SQL, I need to select the id's from this list (<code>10, 11, 12, 13, 14</code>) that do not have entries in Table A (joining on the 'id' column). The result should be the resultset of id's <code>13</code> and <code>14</code>.</p>
<p>How can I accomplish this using only SQL? (Also, I'd like to avoid using a stored procedure if possible)</p>
<p>The only approach I can think of is something that would create an inline SQL table on the fly to temporarily hold my list of id's. However, I have no idea how to do this. Is this possible? Is there a better way?</p>
<p>Thanks! :)</p> | 10,709,493 | 5 | 4 | null | 2012-05-22 20:12:40.257 UTC | 13 | 2021-06-17 04:03:43.473 UTC | 2021-06-17 04:03:43.473 UTC | null | 114,558 | null | 114,558 | null | 1 | 47 | mysql|sql|rdbms | 50,664 | <p>You can create an "inline table" with a <a href="http://dev.mysql.com/doc/en/union.html"><code>UNION</code></a> subquery:</p>
<pre><code>(
SELECT 10 AS id
UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14
-- etc.
) AS inline_table
</code></pre> |
25,413,239 | Custom UITableViewCell programmatically using Swift | <p>Hey all I am trying to create a custom <code>UITableViewCell</code>, but I see nothing on the simulator. Can you help me please.</p>
<p>I can see the label only if I <code>var labUserName = UILabel(frame: CGRectMake(0.0, 0.0, 130, 30));</code></p>
<p>but it overlaps the cell. I don't understand, Auto Layout should know the preferred size/minimum size of each cell?</p>
<p>Thanks</p>
<pre><code>import Foundation
import UIKit
class TableCellMessages: UITableViewCell {
var imgUser = UIImageView();
var labUserName = UILabel();
var labMessage = UILabel();
var labTime = UILabel();
override init(style: UITableViewCellStyle, reuseIdentifier: String) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
imgUser.layer.cornerRadius = imgUser.frame.size.width / 2;
imgUser.clipsToBounds = true;
contentView.addSubview(imgUser)
contentView.addSubview(labUserName)
contentView.addSubview(labMessage)
contentView.addSubview(labTime)
//Set layout
var viewsDict = Dictionary <String, UIView>()
viewsDict["image"] = imgUser;
viewsDict["username"] = labUserName;
viewsDict["message"] = labMessage;
viewsDict["time"] = labTime;
//Image
//contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[image(100)]-'", options: nil, metrics: nil, views: viewsDict));
//contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[image(100)]-|", options: nil, metrics: nil, views: viewsDict));
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[username]-[message]-|", options: nil, metrics: nil, views: viewsDict));
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[username]-|", options: nil, metrics: nil, views: viewsDict));
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[message]-|", options: nil, metrics: nil, views: viewsDict));
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
</code></pre> | 25,433,668 | 3 | 6 | null | 2014-08-20 19:47:51.14 UTC | 29 | 2020-08-31 23:11:38.54 UTC | 2017-11-20 21:06:16.13 UTC | null | 2,852,849 | null | 2,217,746 | null | 1 | 43 | ios|uitableview|swift|custom-controls | 96,325 | <p>Let's make a few assumptions:</p>
<p>You have an iOS8 project with a <code>Storyboard</code> that contains a single <code>UITableViewController</code>. Its <code>tableView</code> has a unique prototype <code>UITableViewCell</code> with custom style and identifier: "cell".</p>
<p>The <code>UITableViewController</code> will be linked to Class <code>TableViewController</code>, the <code>cell</code> will be linked to Class <code>CustomTableViewCell</code>.</p>
<p>You will then be able to set the following code (updated for Swift 2):</p>
<p><em>CustomTableViewCell.swift:</em></p>
<pre><code>import UIKit
class CustomTableViewCell: UITableViewCell {
let imgUser = UIImageView()
let labUserName = UILabel()
let labMessage = UILabel()
let labTime = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
imgUser.backgroundColor = UIColor.blueColor()
imgUser.translatesAutoresizingMaskIntoConstraints = false
labUserName.translatesAutoresizingMaskIntoConstraints = false
labMessage.translatesAutoresizingMaskIntoConstraints = false
labTime.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(imgUser)
contentView.addSubview(labUserName)
contentView.addSubview(labMessage)
contentView.addSubview(labTime)
let viewsDict = [
"image": imgUser,
"username": labUserName,
"message": labMessage,
"labTime": labTime,
]
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[image(10)]", options: [], metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[labTime]-|", options: [], metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[username]-[message]-|", options: [], metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[username]-[image(10)]-|", options: [], metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[message]-[labTime]-|", options: [], metrics: nil, views: viewsDict))
}
}
</code></pre>
<p><em>TableViewController.swift:</em></p>
<pre><code>import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Auto-set the UITableViewCells height (requires iOS8+)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell
cell.labUserName.text = "Name"
cell.labMessage.text = "Message \(indexPath.row)"
cell.labTime.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .ShortStyle, timeStyle: .ShortStyle)
return cell
}
}
</code></pre>
<hr>
<p>You will expect a display like this (iPhone landscape):
<img src="https://i.stack.imgur.com/HLAjN.png" alt="enter image description here"></p> |
46,192,280 | Detect if the device is iPhone X | <p>My iOS app uses a custom height for the <code>UINavigationBar</code> which leads to some problems on the new iPhone X. </p>
<p>Does someone already know how to <strong>reliable</strong> detect programmatically (in Objective-C) if an app is running on iPhone X?</p>
<p><strong>EDIT:</strong></p>
<p>Of course checking the size of the screen is possible, however, I wonder if there is some "build in" method like <code>TARGET_OS_IPHONE</code> to detect iOS...</p>
<pre><code>if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
if (screenSize.height == 812)
NSLog(@"iPhone X");
}
</code></pre>
<p><strong>EDIT 2:</strong></p>
<p>I do not think, that my question is a duplicate of the linked question. Of course, there are methods to "measure" different properties of the current device and to use the results to decide which device is used. However, this was not the actual point of my question as I tried to emphasize in my first edit. </p>
<p>The actual question is: <strong>"Is it possible to directly detect if the current device is an iPhone X (e.g. by some SDK feature) or do I have to use indirect measurements"</strong>?</p>
<p>By the answers given so far, I assume that the answer is "No, there is no direct methods. Measurements are the way to go". </p> | 46,192,822 | 38 | 11 | null | 2017-09-13 08:12:05.523 UTC | 146 | 2022-07-22 10:47:27.417 UTC | 2018-03-21 06:09:04.18 UTC | null | 3,359,299 | null | 777,861 | null | 1 | 282 | ios|objective-c|iphone|iphone-x | 220,322 | <p>Based on your question, the answer is no. There are no direct methods. For more information you can get the information here:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/11197509/how-to-get-device-make-and-model-on-ios/11197770#11197770">How to get device make and model on iOS?</a></li>
</ul>
<p>and</p>
<ul>
<li><a href="https://stackoverflow.com/questions/27775779/how-to-check-screen-size-of-iphone-4-and-iphone-5-programmatically-in-swift">how to check screen size of iphone 4 and iphone 5 programmatically in swift</a></li>
</ul>
<p>The iPhone X height is 2436 px</p>
<p>From <a href="https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions" rel="noreferrer">Device Screen Sizes and resolutions</a>:</p>
<p><a href="https://i.stack.imgur.com/JcCJp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JcCJp.png" alt="enter image description here" /></a></p>
<p>From <a href="https://kapeli.com/cheat_sheets/iOS_Design.docset/Contents/Resources/Documents/index" rel="noreferrer">Device Screen Sizes and Orientations</a>:</p>
<p><a href="https://i.stack.imgur.com/d0x04.png" rel="noreferrer"><img src="https://i.stack.imgur.com/d0x04.png" alt="enter image description here" /></a></p>
<p><strong>Swift 3 and later</strong>:</p>
<pre><code>if UIDevice().userInterfaceIdiom == .phone {
switch UIScreen.main.nativeBounds.height {
case 1136:
print("iPhone 5 or 5S or 5C")
case 1334:
print("iPhone 6/6S/7/8")
case 1920, 2208:
print("iPhone 6+/6S+/7+/8+")
case 2436:
print("iPhone X/XS/11 Pro")
case 2688:
print("iPhone XS Max/11 Pro Max")
case 1792:
print("iPhone XR/ 11 ")
default:
print("Unknown")
}
}
</code></pre>
<p><strong>Objective-C</strong>:</p>
<pre><code>if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
switch ((int)[[UIScreen mainScreen] nativeBounds].size.height) {
case 1136:
printf("iPhone 5 or 5S or 5C");
break;
case 1334:
printf("iPhone 6/6S/7/8");
break;
case 1920:
case 2208:
printf("iPhone 6+/6S+/7+/8+");
break;
case 2436:
printf("iPhone X/XS/11 Pro");
break;
case 2688:
printf("iPhone XS Max/11 Pro Max");
break;
case 1792:
printf("iPhone XR/ 11 ");
break;
default:
printf("Unknown");
break;
}
}
</code></pre>
<p><strong>Xamarin.iOS</strong>:</p>
<pre><code>if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) {
if ((UIScreen.MainScreen.Bounds.Height * UIScreen.MainScreen.Scale) == 1136) {
Console.WriteLine("iPhone 5 or 5S or 5C");
} else if ((UIScreen.MainScreen.Bounds.Height * UIScreen.MainScreen.Scale) == 1334) {
Console.WriteLine("iPhone 6/6S/7/8");
} else if ((UIScreen.MainScreen.Bounds.Height * UIScreen.MainScreen.Scale) == 1920 || (UIScreen.MainScreen.Bounds.Height * UIScreen.MainScreen.Scale) == 2208) {
Console.WriteLine("iPhone 6+/6S+/7+/8+");
} else if ((UIScreen.MainScreen.Bounds.Height * UIScreen.MainScreen.Scale) == 2436) {
Console.WriteLine("iPhone X, XS, 11 Pro");
} else if ((UIScreen.MainScreen.Bounds.Height * UIScreen.MainScreen.Scale) == 2688) {
Console.WriteLine("iPhone XS Max, 11 Pro Max");
} else if ((UIScreen.MainScreen.Bounds.Height * UIScreen.MainScreen.Scale) == 1792) {
Console.WriteLine("iPhone XR, 11");
} else {
Console.WriteLine("Unknown");
}
}
</code></pre>
<p>Based on your question as follow:</p>
<p>Or use <code>screenSize.height</code> as float <code>812.0f</code> not int <code>812</code>.</p>
<pre><code>if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
// 812.0 on iPhone X, XS
// 896.0 on iPhone XS Max, XR.
if (screenSize.height >= 812.0f)
NSLog(@"iPhone X");
}
</code></pre>
<p>For more information you can refer the following page in iOS Human Interface Guidelines:</p>
<ul>
<li><a href="https://developer.apple.com/ios/human-interface-guidelines/visual-design/adaptivity-and-layout/" rel="noreferrer">Adaptivity and Layout - Visual Design - iOS - Human Interface Guidelines</a></li>
</ul>
<p><strong>Swift</strong>:</p>
<p>Detect with <code>topNotch</code>:</p>
<blockquote>
<p>If anyone considering using notch to detect iPhoneX, mind that on "landscape" its same for all iPhones.</p>
</blockquote>
<pre><code>var hasTopNotch: Bool {
if #available(iOS 13.0, *) {
return UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.safeAreaInsets.top ?? 0 > 20
}else{
return UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0 > 20
}
return false
}
</code></pre>
<p><strong>Objective-C</strong>:</p>
<pre><code>- (BOOL)hasTopNotch {
if (@available(iOS 13.0, *)) {
return [self keyWindow].safeAreaInsets.top > 20.0;
}else{
return [[[UIApplication sharedApplication] delegate] window].safeAreaInsets.top > 20.0;
}
return NO;
}
- (UIWindow*)keyWindow {
UIWindow *foundWindow = nil;
NSArray *windows = [[UIApplication sharedApplication]windows];
for (UIWindow *window in windows) {
if (window.isKeyWindow) {
foundWindow = window;
break;
}
}
return foundWindow;
}
</code></pre>
<p><strong>UPDATE</strong>:</p>
<p>Do not use the <code>userInterfaceIdiom</code> property to identify the device type, as the <a href="https://developer.apple.com/documentation/uikit/uidevice/1620037-userinterfaceidiom" rel="noreferrer">documentation for userInterfaceIdiom</a> explains:</p>
<blockquote>
<p>For universal applications, you can use this property to tailor the behavior of your application for a specific type of device. For example, iPhone and iPad devices have different screen sizes, so you might want to create different views and controls based on the type of the current device.</p>
</blockquote>
<p>That is, this property is just used to identify the running app's view style. However, the iPhone app (not the universal) could be installed in iPad device via App store, in that case, the <code>userInterfaceIdiom</code> will return the <code>UIUserInterfaceIdiomPhone</code>, too.</p>
<p>The right way is to get the machine name via <code>uname</code>. Check the following for details:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/11197509/how-to-get-device-make-and-model-on-ios/11197770#11197770">How to get device make and model on iOS?</a></li>
</ul> |
8,316,940 | JavaScript Appending another Div data on Div Tag Dynamically | <p>I want to append the content of an already defined "old div" tag to the "new div" tag dynamically but its not working. The code i tried is attached below.
And one more question, how to remove that appended div tag dynamically?</p>
<pre><code><html>
<head>
<script type="text/javascript">
function add() {
var i = document.getElementById( 'old' );
var d = document.getElementById( 'new' );
d.appendChild( i );
}
</script>
</head>
<body>
<div id="old">
Content of old div
</div>
<div id="new">
</div>
<button onclick="add()">Add</button>
</body>
</html>
</code></pre> | 8,316,977 | 2 | 1 | null | 2011-11-29 20:00:08.33 UTC | 9 | 2011-11-29 20:06:22.97 UTC | null | null | null | null | 1,067,051 | null | 1 | 1 | javascript | 30,859 | <p>ok I solved it. There was some error in my code. Its working now. </p>
<pre><code> <html>
<head>
<script type="text/javascript">
function add() {
var i = document.getElementById( 'old' );
var d = document.createElement( 'div' );
d.id = "new1";
d.innerHTML = i.innerHTML ;
var p = document.getElementById('new');
p.appendChild(d);
}
function removeLocation() {
var d = document.getElementById( 'new1' );
var p = document.getElementById('new');
p.removeChild(d);
}
</script>
</head>
<body>
<div id="old">
Content of old div
</div>
<hr/>
<div id="new">
</div>
<hr/>
<button onclick="add();">Add</button><br>
<button onclick="removeLocation();">Remove</button>
</body>
</html>
</code></pre> |
53,154,898 | Why do projects use the -I include switch given the dangers? | <p>Reading the fine print of the <code>-I</code> switch in GCC, I'm rather shocked to find that using it on the command line overrides system includes. From the <a href="https://gcc.gnu.org/onlinedocs/cpp/Invocation.html#Invocation" rel="noreferrer">preprocessor docs</a></p>
<blockquote>
<p><em>"You can use <code>-I</code> to override a system header file, substituting your own version, since these directories are searched before the standard system header file directories."</em></p>
</blockquote>
<p>They don't seem to be lying. On two different Ubuntu systems with GCC 7, if I create a file <code>endian.h</code>:</p>
<pre><code>#error "This endian.h shouldn't be included"
</code></pre>
<p>...and then in the same directory create a <code>main.cpp</code> (or main.c, same difference):</p>
<pre><code>#include <stdlib.h>
int main() {}
</code></pre>
<p>Then compiling with <code>g++ main.cpp -I. -o main</code> (or clang, same difference) gives me:</p>
<pre><code>In file included from /usr/include/x86_64-linux-gnu/sys/types.h:194:0,
from /usr/include/stdlib.h:394,
from /usr/include/c++/7/cstdlib:75,
from /usr/include/c++/7/stdlib.h:36,
from main.cpp:1:
./endian.h:1:2: error: #error "This endian.h shouldn't be included"
</code></pre>
<p>So stdlib.h includes this types.h file, which on line 194 just says <code>#include <endian.h></code>. My apparent misconception (and perhaps that of others) was that the angle brackets would have prevented this, but -I is stronger than I'd thought.</p>
<p>Though not strong <em>enough</em>, because you can't even fix it by sticking /usr/include in on the command line first, because:</p>
<blockquote>
<p><em>"If a standard system include directory, or a directory specified with <code>-isystem</code>, is also specified with <code>-I</code>, the <code>-I</code> option is ignored. The directory is still searched but as a system directory at its normal position in the system include chain."</em></p>
</blockquote>
<p>Indeed, the verbose output for <code>g++ -v main.cpp -I/usr/include -I. -o main</code> leaves /usr/include at the bottom of the list:</p>
<pre><code>#include "..." search starts here:
#include <...> search starts here:
.
/usr/include/c++/7
/usr/include/x86_64-linux-gnu/c++/7
/usr/include/c++/7/backward
/usr/lib/gcc/x86_64-linux-gnu/7/include
/usr/local/include
/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed
/usr/include/x86_64-linux-gnu
/usr/include
</code></pre>
<p>Color me surprised. I guess to make this a question:</p>
<p><strong>What legitimate reason is there for most projects to use <code>-I</code> considering this extremely serious issue?</strong> You can override arbitrary headers on systems based on incidental name collisions. Shouldn't pretty much everyone be using <code>-iquote</code> instead?</p> | 53,155,014 | 4 | 6 | null | 2018-11-05 12:56:53.83 UTC | 8 | 2018-11-05 15:57:02.12 UTC | 2018-11-05 14:17:41.433 UTC | null | 211,160 | null | 211,160 | null | 1 | 32 | c++|c|gcc|clang|include-path | 3,942 | <p>What legitimate reasons are there for <code>-I</code> over <code>-iquote</code>? <code>-I</code> is standardized (at least by <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/c99.html" rel="noreferrer">POSIX</a>) while <code>-iquote</code> isn't. (Practically, I'm using <code>-I</code> because tinycc (one of the compilers I want my project to compile with) doesn't support <code>-iquote</code>.)</p>
<p>How do projects manage with <code>-I</code> given the dangers? You'd have the includes wrapped in a directory and use -I to add the directory containing that directory.</p>
<ul>
<li>filesystem: <code>includes/mylib/endian.h</code></li>
<li>command line: <code>-Iincludes</code></li>
<li>C/C++ file: <code>#include "mylib/endian.h" //or <mylib/endian.h></code></li>
</ul>
<p>With that, as long as you don't clash on the <code>mylib</code> name, you don't clash (at least as far header names are concerned).</p> |
13,697,115 | JavaFX tableview colors | <p>i need create JavaFx TableView with multicolor rows (color1 for low priority, color2 for medium priority etc.). I have created CellFactory</p>
<pre><code>public class TaskCellFactory implements Callback<TableColumn, TableCell> {
@Override
public TableCell call(TableColumn p) {
TableCell cell = new TableCell<Task, Object>() {
@Override
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : getString());
setGraphic(null);
TableRow currentRow = getTableRow();
Task currentTask = currentRow == null ? null : (Task)currentRow.getItem();
if(currentTask != null){
Priority priority = currentTask.getPriority();
clearPriorityStyle();
if(!isHover() && !isSelected() && !isFocused()){
setPriorityStyle(priority);
}
}
}
@Override
public void updateSelected(boolean upd){
super.updateSelected(upd);
System.out.println("is update");
}
private void clearPriorityStyle(){
ObservableList<String> styleClasses = getStyleClass();
styleClasses.remove("priorityLow");
styleClasses.remove("priorityMedium");
styleClasses.remove("priorityHigh");
}
private void setPriorityStyle(Priority priority){
switch(priority){
case LOW:
getStyleClass().add("priorityLow");
break;
case MEDIUM:
getStyleClass().add("priorityMedium");
break;
case HIGH:
getStyleClass().add("priorityHigh");
break;
}
System.out.println(getStyleClass());
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
};
return cell;
} }
</code></pre>
<p>and css</p>
<pre><code>.priorityLow{ -fx-background-color: palegreen; }
.priorityMedium{ -fx-background-color: skyblue;}
.priorityHigh{ -fx-background-color: palevioletred;}
</code></pre>
<p>But i still need highlight selected rows. How can i do that?</p> | 13,698,718 | 1 | 0 | null | 2012-12-04 06:12:49.087 UTC | 11 | 2020-10-22 20:51:39.313 UTC | 2014-05-12 19:46:50.35 UTC | null | 1,624,376 | null | 1,874,698 | null | 1 | 15 | java|tableview|javafx | 22,564 | <p>Instead of setting the background color for the entire cell in your css, just set the -fx-control-inner-background. Then you will have the default accent, hover and focus rings still available. Also remove the if statement around your <code>setPriorityStyle</code> call of course.</p>
<p>If you also want to override things like the default accent (selected) color or the hover color, you can also do this as in the css below - not sure if the highlight overrides are really recommended though, guess it would depend on your app and desired user experience.</p>
<pre><code>.priorityLow {
-fx-control-inner-background: palegreen;
-fx-accent: derive(-fx-control-inner-background, -40%);
-fx-cell-hover-color: derive(-fx-control-inner-background, -20%);
}
.priorityMedium {
-fx-control-inner-background: skyblue;
-fx-accent: derive(-fx-control-inner-background, -40%);
-fx-cell-hover-color: derive(-fx-control-inner-background, -20%);
}
.priorityHigh {
-fx-control-inner-background: palevioletred;
-fx-accent: derive(-fx-control-inner-background, -40%);
-fx-cell-hover-color: derive(-fx-control-inner-background, -20%);
}
</code></pre>
<p><img src="https://i.stack.imgur.com/wxIck.png" alt="rowhighlight" /></p>
<hr />
<p>Detailed styling information for JavaFX can be found in the default <a href="http://hg.openjdk.java.net/openjfx/2.2/master/rt/raw-file/tip/javafx-ui-controls/src/com/sun/javafx/scene/control/skin/caspian/caspian.css" rel="nofollow noreferrer">caspian.css stylesheet</a> for JavaFX 2.2 and the <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html" rel="nofollow noreferrer">JavaFX 2 CSS reference guide</a>. To find caspian.css for your version of JavaFX you can unjar <code>jfxrt.jar</code> (sometimes found in the jre/lib directory).</p>
<p><strong>Update</strong></p>
<p>The default stylesheet for JavaFX is now named <code>modena.css</code> rather than <code>caspian.css</code>.</p> |
13,640,188 | Error converting text to lowercase with tm_map(..., tolower) | <p>I tried using the <code>tm_map</code>. It gave the following error. How can I get around this?</p>
<pre><code> require(tm)
byword<-tm_map(byword, tolower)
Error in UseMethod("tm_map", x) :
no applicable method for 'tm_map' applied to an object of class "character"
</code></pre> | 13,640,262 | 4 | 2 | null | 2012-11-30 06:35:41.49 UTC | 10 | 2016-09-30 19:05:41.477 UTC | 2016-09-30 19:05:41.477 UTC | null | 561,731 | null | 1,847,296 | null | 1 | 48 | r|tm|lowercase|term-document-matrix | 66,459 | <p>Use the base R function <code>tolower()</code>:</p>
<pre><code>tolower(c("THE quick BROWN fox"))
# [1] "the quick brown fox"
</code></pre> |
13,433,116 | $routeParams doesn't work in resolve function | <p>I'm using <a href="https://stackoverflow.com/questions/11972026/delaying-angularjs-route-change-until-model-loaded-to-prevent-flicker">this</a> technique to load data. So I have created the following resolve function: </p>
<pre><code>NoteController.resolve = {
note: function($routeParams, Note) {
return Note.get($routeParams.key);
}
}
</code></pre>
<p>The problems is that <code>$routeParams.key</code> is <code>undefined</code> at the moment of <code>resolve</code> function execution. Is it correct/bug? How can I fix it?</p> | 13,433,335 | 1 | 0 | null | 2012-11-17 17:48:04.337 UTC | 29 | 2015-05-20 14:48:34.387 UTC | 2017-05-23 12:18:12.49 UTC | null | -1 | null | 716,027 | null | 1 | 138 | angularjs | 29,641 | <p>You need to use <code>$route.current.params.key</code> instead. The <code>$routeParams</code> is updated only <em>after</em> a route is changed. So your code should look along those lines:</p>
<pre><code>NoteController.resolve = {
note: function($route, Note) {
return Note.get($route.current.params.key);
}
}
</code></pre> |
39,523,474 | What is the difference between an expression and a statement in Java? | <p>I'm a beginner for Java, and I want to know the difference between expressions and statements in Java?</p> | 39,523,498 | 2 | 4 | null | 2016-09-16 03:48:56.603 UTC | 10 | 2017-01-15 21:44:41.753 UTC | 2016-09-16 05:31:43.953 UTC | null | 56,737 | null | 689,464 | null | 1 | 41 | java | 20,570 | <p>This is an example : </p>
<p><code>b + 1</code> is an expression while <code>a = b + 1;</code> is a statement. A statement consists of expressions. </p>
<p>This is not specific to the Java language. Many languages use this kind of grammar e.g. <code>C, C++, Basic</code> etc (not <code>SQL</code>).</p> |
24,287,024 | How to enforce loading order of spring configuration classes? | <p>I'm working with spring-boot on a multi module project (maven). Each module has it's own @Configuration class. Basically I do have the following layout</p>
<p>Module foo-embedded (runs just calls the SpringApplication.run()) method:</p>
<pre><code>@Configuration
@EnableAutoConfiguration
@ComponentScan("de.foobar.rootpackage")
@Import({ApplicationConfig.class, RepositoryConfig.class, SecurityConfig.class})
public class FooApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(FooApplication.class, args);
}
}
</code></pre>
<p>Module foo-common (contains all beans and spring-data-jpa initialization config)</p>
<pre><code>@Configuration
@EnableJpaRepositories
@EnableTransactionManagement(entityManagerFactoryRef="entityManagerFactory")
public class RepositoryConfig {
@Bean(destroyMethod = "shutdown")
public DataSource getDataSource() {
// returning a Hikari CP here
}
@Bean(name = "entityManagerFactory") // overriding spring boots default
public EntityManagerFactory getEntityManagerFactory() {
// returning a new LocalEntityManagerFactoryBean here
}
}
</code></pre>
<p>Module foo-security (containing spring-securiy configuration and related domain classes), which has a maven dependency on foo-common</p>
<pre><code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// configuring HTTP security and defining my UserDetailsService Bean
}
</code></pre>
<p>When I start the application using the FooApplication class, everything works as expected. The above mentioned UserDetailsServiceImpl get's autowired with my UserRepository which is being created through the @EnableJpaRepositories annotation.</p>
<p>Since I want to write some integration tests I've added a test clss to one of my modules.</p>
<p>Module foo-media (containing some domain related stuff plus test cases for that module)</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {RepositoryConfig.class, SecurityConfig.class})
@WebAppConfiguration
@IntegrationTest
public class DirectoryIntegrationTest {
// my test code
}
</code></pre>
<p>When I run the test it seems that the SecurityConfiguration get's loaded before the RepositoryConfig.class does. Since the security config defined the UserServiceImpl which must be autowired, the test fails to start with a</p>
<pre><code>NoSuchBeanDefinitionException telling me: No qualifying bean of type [com.foo.rootpackage.security.repository.UserRepository]
</code></pre>
<p>I already tried to add <code>@DependsOn("UserRepository")</code> at the bean definition of <code>UserDetailsService</code>, telling me that spring can't find a bean by that name.</p>
<p>Any hints or help would be greatly appreciated! Thanks in advance! </p>
<p>---- <strong>EDIT</strong> (since I was asked to provide more code) ----</p>
<p>For testing I do not use the actual RepositoryConfig.class, but have a TestRepositoryConfig.class in the common module. Looking like this</p>
<pre><code>@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", basePackages = "de.foobar.rootpackage")
public class TestRepositoryConfig extends RepositoryConfig {
@Bean
@Override
public DataSource getDataSource() {
// returning the ds for testing
}
}
</code></pre> | 24,302,591 | 2 | 3 | null | 2014-06-18 13:35:31.933 UTC | 5 | 2014-11-07 16:56:12.8 UTC | 2014-06-19 08:49:27.243 UTC | null | 406,714 | null | 406,714 | null | 1 | 22 | java|spring|maven|spring-boot | 50,188 | <p>So I was able to solve this. As it pointed out it had nothing to do with the loading order of the configuration classes (which was my first thought).</p>
<p>As you may notice, the only Configuration that had a <code>@ComponentScan</code> annotation was the FooApplication.class
Spring was not able to find the Repositories, as it didn't know where to look for. Providing the basePackages attribute like this: </p>
<pre><code>@EnableJpaRepositories(basePackages = "de.foobar.rootpackage")
</code></pre>
<p>at the TestRepositoryConfig.class did the trick here.</p> |
3,514,237 | ref and out in C++/CLI | <p>I know that the C++/CLI code </p>
<pre><code>void foo(Bar^% x);
</code></pre>
<p>transforms into</p>
<pre><code>Void foo(ref Bar x);
</code></pre>
<p>What is the C++/CLI code that becomes</p>
<pre><code>Void foo(out Bar x);
</code></pre>
<p>?</p> | 6,329,344 | 2 | 0 | null | 2010-08-18 16:19:11.97 UTC | 7 | 2011-06-13 13:05:41.703 UTC | null | null | null | null | 373,025 | null | 1 | 30 | .net|c++-cli|pass-by-reference | 18,519 | <p>You can use the OutAttribute:</p>
<pre><code>using namespace System::Runtime::InteropServices;
void foo([Out] Bar^% x);
</code></pre> |
3,652,233 | Arduino Bootloader | <p>Can someone please explain how the <a href="http://code.google.com/p/arduino/source/browse/tags/0019/hardware/arduino/bootloaders/atmega/ATmegaBOOT_168.c" rel="noreferrer">Arduino bootloader</a> works? I'm not looking for a high level answer here, I've read the code and I get the gist of it. </p>
<p>There's a bunch of protocol interaction that happens between the Arduino IDE and the bootloader code, ultimately resulting in a number of inline assembly instructions that self-program the flash with the program being transmitted over the serial interface. </p>
<p>What I'm not clear on is on line 270:</p>
<pre><code>void (*app_start)(void) = 0x0000;
</code></pre>
<p>...which I recognize as the declaration, and initialization to NULL, of a function pointer. There are subsequent calls to app_start in places where the bootloader is intended to delegate to execution of the user-loaded code. </p>
<p>Surely, somehow <code>app_start</code> needs to get a non-NULL value at some point for this to all come together. I'm not seeing that in the bootloader code... is it magically linked by the program that gets loaded by the bootloader? I presume that main of the bootloader is the entry point into software after a reset of the chip. </p>
<p>Wrapped up in the 70 or so lines of assembly must be the secret decoder ring that tells the main program where app_start really is? Or perhaps it's some implicit knowlege being taken advantage of by the Arduino IDE? All I know is that if someone doesn't change app_start to point somewhere other than 0, the bootloader code would just spin on itself forever... so what's the trick?</p>
<p><strong>Edit</strong></p>
<p>I'm interested in trying to port the bootloader to an Tiny AVR that doesn't have separate memory space for boot loader code. As it becomes apparent to me that the bootloader code relies on certain fuse settings and chip support, I guess what I'm really interested in knowing is what does it take to port the bootloader to a chip that doesn't have those fuses and hardware support (but still has self-programming capability)?</p> | 3,655,529 | 2 | 1 | null | 2010-09-06 14:30:41.45 UTC | 10 | 2014-05-08 23:10:45.553 UTC | 2010-09-06 15:12:34.573 UTC | null | 212,215 | null | 212,215 | null | 1 | 30 | arduino|avr|bootloader | 9,723 | <h3>On NULL</h3>
<p>Address 0 does not a null pointer make. A "null pointer" is something more abstract: a special value that applicable functions should recognize as being invalid. C says the special value is 0, and while the <em>language</em> says dereferencing it is "undefined behavior", in the simple world of microcontrollers it usually has a very well-defined effect.</p>
<h3>ATmega Bootloaders</h3>
<p>Normally, on reset, the AVR's program counter (PC) is initialized to 0, thus the microcontroller begins executing code at address 0.</p>
<p>However, if the Boot Reset Fuse ("BOOTRST") is set, the program counter is instead initialized to an address of a block at the upper end of the memory (where that is depends on how the fuses are set, see <a href="http://www.atmel.com/dyn/resources/prod_documents/doc2545.pdf" rel="noreferrer">a datasheet</a> (PDF, 7 MB) for specifics). The code that begins there can do anything—if you really wanted you could put your own program there if you use an ICSP (bootloaders generally can't overwrite themselves).</p>
<p>Often though, it's a special program—a <strong>bootloader</strong>—that is able to <em>read data from an external source</em> (often via UART, I<sup>2</sup>C, CAN, etc.) to <em>rewrite program code</em> (stored in internal or external memory, depending on the micro). The bootloader will typically look for a "special event" which can literally be anything, but for development is most conveniently something on the data bus it will pull the new code from. (For production it might be a special logic level on a pin as it can be checked nearly-instantly.) If the bootloader sees the special event, it can enter bootloading-mode, where it will reflash the program memory, otherwise it passes control off to user code.</p>
<p>As an aside, the point of the bootloader fuse and upper memory block is to allow the use of a bootloader with <em>no</em> modifications to the original software (so long as it doesn't extend all the way up into the bootloader's address). Instead of flashing with just the original HEX and desired fuses, one can flash the original HEX, bootloader, and modified fuses, and presto, bootloader added.</p>
<p>Anyways, in the case of the Arduino, which I believe uses the protocol from the <a href="http://www.atmel.com/tools/STK500.aspx" rel="noreferrer">STK500</a>, it attempts to communicate over the UART, and if it gets either no response in the allotted time:</p>
<pre><code>uint32_t count = 0;
while(!(UCSRA & _BV(RXC))) { // loops until a byte received
count++;
if (count > MAX_TIME_COUNT) // 4 seconds or whatever
app_start();
}
</code></pre>
<p>or if it errors too much by getting an unexpected response:</p>
<pre><code>if (++error_count == MAX_ERROR_COUNT)
app_start();
</code></pre>
<p>It passes control back to the main program, located at 0. In the Arduino source seen above, this is done by calling <code>app_start();</code>, defined as <code>void (*app_start)(void) = 0x0000;</code>.</p>
<p>Because it's couched as a C function call, before the PC hops over to 0, it will push the current PC value onto the stack which also contains other variables used in the bootloader (e.g. <code>count</code> and <code>error_count</code> from above). Does this steal RAM from your program? Well, after the PC is set to 0, the operations that are executed blatantly "violate" what a proper C function (that would eventually return) should do. Among other initialization steps, it resets the stack pointer (effectively obliterating the call stack and all local variables), reclaiming RAM. Global/static variables are initialized to 0, the address of which can freely overlap with whatever the bootloader was using because the bootloader and user programs were compiled independently.</p>
<p>The only lasting effects from the bootloader are modifications to hardware (peripheral) registers, which a good bootloader won't leave in a detrimental state (turning on peripherals that might waste power when you try to sleep). It's generally good practice to also fully initialize peripherals you will use, so even if the bootloader did something strange you'll set it how you want.</p>
<h3>ATtiny Bootloaders</h3>
<p>On ATtinys, as you mentioned, there is no luxury of the bootloader fuses or memory, so your code will always start at address 0. You might be able to put your bootloader into some higher pages of memory and point your RESET vector at it, then whenever you receive a new hex file to flash with, take the command that's at address 0:1, replace it with the bootloader address, then store the replaced address somewhere else to call for normal execution. (If it's an <code>RJMP</code> ("<em>relative</em> jump") the value will obviously need to be recalculated)</p> |
4,016,067 | What's a 3D doing in this HTML? | <p>I'm trying to duplicate a mailer I got into my gmail by taking a look at its code. I see a lot of this in multiple source viewers:</p>
<pre><code> <td style=3D"border-bottom: 1px dotted rgb(153,157, 147); border-top: 1px solid rgb(28, 140, 78);" width=3D"90">=A0</td>
<td style=3D"border-bottom: 1px dotted rgb(153,157, 147); border-top: 1px solid rgb(28, 140, 78);" align=3D"right" width=3D"110">
</code></pre>
<p>Is 3D some sort of mail rendering thing I don't know about?</p> | 4,016,098 | 2 | 1 | null | 2010-10-25 15:23:59.47 UTC | 44 | 2021-04-12 19:21:30.827 UTC | null | null | null | null | 356,746 | null | 1 | 305 | html|css|html-email | 119,409 | <p>It's an email encoding system called "<a href="http://en.wikipedia.org/wiki/Quoted-printable" rel="noreferrer">quoted-printable</a>", which allows non-ASCII characters to be represented as ASCII for email transportation.</p>
<p>In quoted-printable, any non-standard email octets are represented as an <code>=</code> sign followed by two hex digits representing the octet's value. Of course, to represent a plain <code>=</code> in email, it needs to be represented using quoted-printable encoding too: 3D are the hex digits corresponding to <code>=</code>'s ASCII value (61).</p> |
3,796,106 | How to use printf with NSString | <p>I need to use something like <code>NSLog</code> but without the timestamp and newline character, so I'm using <code>printf</code>. How can I use this with <code>NSString</code>?</p> | 3,796,111 | 2 | 0 | null | 2010-09-26 00:23:39.197 UTC | 8 | 2018-06-19 14:45:05.697 UTC | 2012-08-13 14:47:57.107 UTC | null | 220,819 | null | 404,020 | null | 1 | 66 | objective-c|cocoa-touch|nsstring|printf|nslog | 47,249 | <p>You can convert an <code>NSString</code> into a <code>UTF8</code> string by calling the <code>UTF8String</code> method:</p>
<pre><code>printf("%s", [string UTF8String]);
</code></pre> |
28,500,066 | How to deploy SpringBoot Maven application with Jenkins ? | <p>I have a Spring Boot application which runs on embedded Tomcat servlet container <code>mvn spring-boot:run</code> . And I don’t want to deploy the project as separate war to standalone Tomcat. </p>
<p>Whenever I push code to BitBucket/Github, a hook runs and triggers Jenkins job (runs on Amazon EC2) to deploy the application. </p>
<p>The Jenkins job has a post build action: <code>mvn spring-boot:run</code>, the problem is that the job hangs when post build action finished. </p>
<p>There should be another way to do this. Any help would be appreciated.</p> | 28,501,714 | 5 | 5 | null | 2015-02-13 12:51:44.933 UTC | 11 | 2019-05-31 18:40:44.58 UTC | null | null | null | null | 473,749 | null | 1 | 25 | maven|tomcat|jenkins|spring-boot|microservices | 31,364 | <p>The problem is that Jenkins <a href="https://wiki.jenkins-ci.org/display/JENKINS/Spawning+processes+from+build">doesn't handle spawning child process from builds very well</a>. Workaround suggested by @Steve in the comment (<code>nohup</code>ing) didn't change the behaviour in my case, but a simple workaround was to <em>schedule</em> app's start by using the <code>at</code> unix command:</p>
<pre><code>> echo "mvn spring-boot:run" | at now + 1 minutes
</code></pre>
<p>This way Jenkins successfully completes the job without timing out.</p>
<hr>
<p>If you end up running your application from a <code>.jar</code> file via <code>java -jar app.jar</code> be aware that <a href="https://github.com/spring-projects/spring-boot/issues/1106">Boot breaks if the .jar file is overwritten</a>, you'll need to make sure the application is stopped before copying the artifact. If you're using <code>ApplicationPidListener</code> you can verify that the application is running (and stop it if it is) by adding execution of this command:</p>
<pre><code>> test -f application.pid && xargs kill < application.pid || echo 'App was not running, nothing to stop'
</code></pre> |
28,482,833 | Understanding the collapse clause in openmp | <p>I came across an OpenMP code that had the collapse clause, which was new to me. I'm trying to understand what it means, but I don't think I have fully grasped it's implications; One definition that I found is:</p>
<blockquote>
<p><a href="https://computing.llnl.gov/tutorials/openMP/">COLLAPSE</a>: Specifies how many loops in a nested loop should be collapsed into one large iteration space and divided according to the schedule clause. The sequential execution of the iterations in all associated loops determines the order of the iterations in the collapsed iteration space.</p>
</blockquote>
<p>I thought I understood what that meant, so I tried the follwoing simple program:</p>
<pre><code>int i, j;
#pragma omp parallel for num_threads(2) private(j)
for (i = 0; i < 4; i++)
for (j = 0; j <= i; j++)
printf("%d %d %d\n", i, j, omp_get_thread_num());
</code></pre>
<p>Which produced</p>
<pre><code>0 0 0
1 0 0
1 1 0
2 0 0
2 1 0
2 2 1
3 0 1
3 1 1
3 2 1
3 3 1
</code></pre>
<p>I then added the <code>collapse(2)</code> clause. I expected to have the same result in the first two columns but now have an equal number of <code>0</code>'s and <code>1</code>'s in the last column.
But I got</p>
<pre><code>0 0 0
1 0 0
2 0 1
3 0 1
</code></pre>
<p>So my questions are:</p>
<ol>
<li>What is happening in my code?</li>
<li>Under what circumstances should I use <code>collapse</code>?</li>
<li>Can you provide an example that shows the difference between using <code>collapse</code> and not using it?</li>
</ol> | 28,483,812 | 2 | 6 | null | 2015-02-12 16:35:46.063 UTC | 12 | 2019-01-21 15:26:11.75 UTC | 2019-01-21 15:26:11.75 UTC | null | 417,501 | null | 1,072,062 | null | 1 | 42 | c|openmp | 58,600 | <p>
The problem with your code is that the iterations of the inner loop depend on the outer loop. According to the OpenMP specification under the description of the section on binding and the <code>collapse</code> clause:</p>
<blockquote>
<p>If execution of any associated loop changes any of the values used to compute any
of the iteration counts, then the behavior is unspecified.</p>
</blockquote>
<p>You can use collapse when this is not the case for example with a square loop</p>
<pre class="lang-c prettyprint-override"><code>#pragma omp parallel for private(j) collapse(2)
for (i = 0; i < 4; i++)
for (j = 0; j < 100; j++)
</code></pre>
<p>In fact this is a good example to show when to use collapse. The outer loop only has four iterations. If you have more than four threads then some will be wasted. But when you collapse the threads will distribute among 400 iterations which is likely to be much greater than the number of threads. Another reason to use collapse is if the load is not well distributed. If you only used four iterations and the fourth iteration took most of the time the other threads wait. But if you use 400 iterations the load is likely to be better distributed.</p>
<p>You can fuse a loop by hand for the code above like this</p>
<pre class="lang-c prettyprint-override"><code>#pragma omp parallel for
for(int n=0; n<4*100; n++) {
int i = n/100; int j=n%100;
</code></pre>
<p><a href="https://stackoverflow.com/questions/18749493/openmp-drastically-slows-down-for-loop/18763554#18763554">Here</a> is an example showing how to fuse a triply fused loop by hand.</p>
<p>Finally, <a href="https://stackoverflow.com/questions/24013832/fusing-a-triangle-loop-for-parallelization-calculating-sub-indices">here</a> is an example showing how to fuse a triangular loop which <code>collapse</code> is not defined for.</p>
<hr>
<p>Here is a solution that maps a rectangular loop to the triangular loop in the OPs question. This can be used to fuse the OPs triangular loop.</p>
<pre class="lang-c prettyprint-override"><code>//int n = 4;
for(int k=0; k<n*(n+1)/2; k++) {
int i = k/(n+1), j = k%(n+1);
if(j>i) i = n - i -1, j = n - j;
printf("(%d,%d)\n", i,j);
}
</code></pre>
<p>This works for any value of n.</p>
<p>The map for the OPs question goes from</p>
<pre class="lang-c prettyprint-override"><code>(0,0),
(1,0), (1,1),
(2,0), (2,1), (2,2),
(3,0), (3,1), (3,2), (3,3),
</code></pre>
<p>to</p>
<pre class="lang-c prettyprint-override"><code>(0,0), (3,3), (3,2), (3,1), (3,0),
(1,0), (1,1), (2,2), (2,1), (2,0),
</code></pre>
<p>For odd values of n the map is not exactly a rectangle but the formula still works.</p>
<p>For example n = 3 gets mapped from </p>
<pre class="lang-c prettyprint-override"><code>(0,0),
(1,0), (1,1),
(2,0), (2,1), (2,2),
</code></pre>
<p>to </p>
<pre class="lang-c prettyprint-override"><code>(0,0), (2,2), (2,1), (2,0),
(1,0), (1,1),
</code></pre>
<p>Here is code to test this</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
int main(void) {
int n = 4;
for(int i=0; i<n; i++) {
for(int j=0; j<=i; j++) {
printf("(%d,%d)\n", i,j);
}
}
puts("");
for(int k=0; k<n*(n+1)/2; k++) {
int i = k/(n+1), j = k%(n+1);
if(j>i) i = n - i - 1, j = n - j;
printf("(%d,%d)\n", i,j);
}
}
</code></pre> |
9,472,254 | Setting Emacs 24 color theme from .emacs | <p>I have the following code in my .emacs:</p>
<pre class="lang-lisp prettyprint-override"><code>(if (null window-system)
(progn
(require 'color-theme)
(color-theme-initialize)
(color-theme-simple-1)))
</code></pre>
<p>When I open Emacs on the console, I can verify that the <code>progn</code> block runs (by a <code>(message "Got here.")</code>), and I see a flash that suggests that the color theme was loaded, but if it was loaded, it is overridden by something else. If, after loading, I open my .emacs file and submit the block above using <code>C-x C-e</code>, it works. I've tried doing:</p>
<pre class="lang-lisp prettyprint-override"><code>(add-hook 'after-init-hook
(lambda ()
(progn
(require 'color-theme)
(color-theme-initialize)
(color-theme-simple-1))))
</code></pre>
<p>but that acts the same.</p>
<p>It may be relevant that I'm using Emacs 24, and that this code is not in my .emacs, but in ~/Dropbox/.emacs, which is loaded from my .emacs.</p>
<hr>
<p>An additional note: I've tried <code>M-x customize-themes</code>, but none of those work acceptably on the console. They either produce a nearly unreadable light theme, or most of the text is invisible.</p> | 9,472,367 | 2 | 2 | null | 2012-02-27 21:04:04.153 UTC | 17 | 2015-03-27 15:26:15.96 UTC | 2012-03-23 16:25:04.437 UTC | null | 708,434 | null | 21,778 | null | 1 | 32 | emacs|dot-emacs|emacs24 | 50,771 | <p>Emacs 24 has built-in theming, which doesn't use statements like <code>(require 'color-theme)</code>. As Drew points out in the comments, <a href="http://www.emacswiki.org/emacs/ColorTheme">there are differences</a> between color themes and custom themes, and the new direction is towards the latter. Try <code>M-x customize-themes</code> to take a look. From .emacs, you can do things like <code>(load-theme 'wombat t)</code>.</p>
<h1><em>But</em>...</h1>
<p>It may still be going wrong for you. One thing that can mess it up like this is changing the face -- maybe in the custom-set-faces part of your .emacs file. Emacs's interactive customization automatically includes the color information (both background <em>and</em> foreground) of whatever theme you happen to be using at the time you set it, so this can definitely make trouble with color themes. If that is what's causing it, you can just set the particular attribute you care about with something like</p>
<pre class="lang-lisp prettyprint-override"><code>(set-face-attribute 'default nil :height 120)
</code></pre>
<p>That will change the font size without changing the colors.</p> |
29,725,880 | How to use break or continue with Laravel Eloquent Collection's each method? | <p>How to use break or continue with Laravel Eloquent Collection's each method.
My code is this:</p>
<pre><code>$objectives->each(function($objective) {
Collection::make($objective)->each(function($action) {
Collection::make($action)->each(function($success_indicator) {
Collection::make($success_indicator)->each(function($success_indicator) {
echo 'hi';
continue;
});
});
});
});
</code></pre> | 29,725,939 | 3 | 2 | null | 2015-04-19 04:43:30.533 UTC | 3 | 2022-01-11 12:36:19.653 UTC | null | null | null | null | 3,568,919 | null | 1 | 47 | php|laravel|collections|eloquent|laravel-5 | 45,548 | <p>To <code>continue</code>, just <code>return</code> out of the inner function. To <code>break</code>, well..</p>
<p>If you're using Laravel 5.1+, you can return <code>false</code> to break the loop:</p>
<pre class="lang-php prettyprint-override"><code>$objectives->each(function($objective) {
collect($objective)->each(function($action) {
collect($action)->each(function($success_indicator) {
collect($success_indicator)->each(function($success_indicator) {
if ($condition) return false;
});
});
});
});
</code></pre>
<p>For older version of Laravel, use a regular <code>foreach</code> loop:</p>
<pre class="lang-php prettyprint-override"><code>$objectives->each(function($objective) {
foreach ($objective as $action) {
foreach ($action as $success_indicators) {
foreach ($success_indicators as $success_indicator) {
echo 'hi';
break;
}
}
}
});
</code></pre> |
16,217,627 | String.split() at a meta character + | <p>I'm making a simple program that will deal with equations from a String input of the equation
When I run it, however, I get an exception because of trying to replace the " +" with a " +" so i can split the string at the spaces. How should I go about using </p>
<p>the string replaceAll method to replace these special characters? Below is my code</p>
<p><em>Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^</em></p>
<pre><code> public static void parse(String x){
String z = "x^2+2=2x-1";
String[] lrside = z.split("=",4);
System.out.println("Left side: " + lrside[0] + " / Right Side: " + lrside[1]);
String rightside = lrside[0];
String leftside = lrside[1];
rightside.replaceAll("-", " -");
rightside.replaceAll("+", " +");
leftside.replaceAll("-", " -"); leftside.replaceAll("+", " +");
List<String> rightt = Arrays.asList(rightside.split(" "));
List<String> leftt = Arrays.asList(leftside.split(" "));
System.out.println(leftt);
System.out.println(rightt);
</code></pre> | 16,217,659 | 4 | 1 | null | 2013-04-25 14:34:57.447 UTC | 10 | 2021-02-03 16:30:04.74 UTC | null | null | null | null | 2,258,066 | null | 1 | 34 | java|string|special-characters | 65,033 | <p><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29" rel="noreferrer"><code>replaceAll</code></a> accepts a regular expression as its first argument. </p>
<p><code>+</code> is a special character which denotes a quantifier meaning <em>one or more occurrences</em>. Therefore it should be escaped to specify the literal character <code>+</code>:</p>
<pre><code>rightside = rightside.replaceAll("\\+", " +");
</code></pre>
<p>(Strings are immutable so it is necessary to assign the variable to the result of <code>replaceAll</code>);</p>
<p>An alternative to this is to use a <a href="http://docs.oracle.com/javase/tutorial/essential/regex/char_classes.html" rel="noreferrer">character class</a> which removes the metacharacter status:</p>
<pre><code>rightside = rightside.replaceAll("[+]", " +");
</code></pre>
<p>The simplest solution though would be to use the <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29" rel="noreferrer"><code>replace</code></a> method which uses non-regex <code>String</code> literals:</p>
<pre><code>rightside = rightside.replace("+", " +");
</code></pre> |
60,561,851 | An error occurred while accessing the Microsoft.Extensions.Hosting services when do first migrations | <p>I don't understand what wrong.
I tried to make a simple crud in .net core mvc with a very simple model which has few fields.</p>
<p>These are my models:</p>
<pre><code> public class Employee
{
[Key] public int EmployeeId { get; set; }
[Required] public string FistName { get; set; }
[Required] public string LastName { get; set; }
public int PositionId { get; set; }
public virtual Position Position { get; set; }
}
public class Position
{
[Key]
public int PositionId { get; set; }
public string PositionName { get; set; }
public ICollection<Employee> Employees { get; set; }
}
</code></pre>
<p>then I made app context:</p>
<pre><code>public class EmployeeContext : DbContext
{
public EmployeeContext(DbContextOptions<EmployeeContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Position> Positions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.HasOne(e => e.Position)
.WithMany()
.HasForeignKey(e => e.PositionId);
}
}
</code></pre>
<p>and registered context in Startup.cs:</p>
<pre><code> public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<EmployeeContext>(item =>item.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
</code></pre>
<p>may be need one more file code of .csproj and program.cs</p>
<pre><code><Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net461</TargetFramework>
<DebugType>full</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.CookiePolicy" Version="2.2.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="3.1.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.1" />
</ItemGroup>
</Project>
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
</code></pre>
<p>then I tried to do first migrate, but I see a very strange error
Add-Migration FirstInit -verbose</p>
<pre><code>Using project 'Crud'.
Using startup project 'Crud'.
Build started...
Build succeeded.
C:\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.2\tools\net461\win-x86\ef.exe migrations add FirstInit --json --verbose --no-color --prefix-output --assembly C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe --startup-assembly C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe --project-dir C:\source\repos\Crud\Crud\ --language C# --working-dir C:\source\repos\Crud --root-namespace Crud
Using assembly 'Crud'.
Using startup assembly 'Crud'.
Using application base 'C:\source\repos\Crud\Crud\bin\Debug\net461'.
Using working directory 'C:\source\repos\Crud\Crud'.
Using root namespace 'Crud'.
Using project directory 'C:\source\repos\Crud\Crud\'.
Using configuration file 'C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe.config'.
Using assembly 'Crud'.
Using startup assembly 'Crud'.
Using application base 'C:\source\repos\Crud\Crud\bin\Debug\net461'.
Using working directory 'C:\source\repos\Crud\Crud'.
Using root namespace 'Crud'.
Using project directory 'C:\source\repos\Crud\Crud\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
System.TypeLoadException: There is no implementation of the GetItem method in the type "Microsoft.AspNetCore.Mvc.Razor.Internal.FileProviderRazorProjectFileSystem" from assembly "Microsoft.AspNetCore.Mvc.Razor, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60".
в Microsoft.Extensions.DependencyInjection.MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngineServices(IServiceCollection services)
в Microsoft.Extensions.DependencyInjection.MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder builder)
в Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddMvc(IServiceCollection services)
в Crud.Startup.ConfigureServices(IServiceCollection services) в C:\source\repos\Crud\Crud\Startup.cs:строка 38
--- End the stack trace from the previous location where the exception occurred ---
в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
в Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
в Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
в Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
в Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: There is no implementation of the GetItem method in the type "Microsoft.AspNetCore.Mvc.Razor.Internal.FileProviderRazorProjectFileSystem" from assembly "Microsoft.AspNetCore.Mvc.Razor, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60".
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'EmployeeContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'EmployeeContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 ---> System.MissingMethodException:There are no parameterless constructors defined for this object..
в System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
в System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
в System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
в System.Activator.CreateInstance(Type type, Boolean nonPublic)
в System.Activator.CreateInstance(Type type)
в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
--- End trace of internal exception stack ---
в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
в Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
в Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
в Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
в Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
в Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'EmployeeContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
</code></pre>
<p>What's wrong with these 3 lines?</p> | 60,602,620 | 8 | 7 | null | 2020-03-06 10:10:45.46 UTC | 4 | 2022-09-22 21:36:04.747 UTC | 2021-02-18 22:47:04.7 UTC | null | 214,143 | null | 12,947,311 | null | 1 | 40 | c#|.net|entity-framework|migration|crud | 57,331 | <p>EF calls CreateWebHostBuilder or BuildWebHost without running Main. So Iconfiguration is null.</p>
<p>Create new class which inherited from <strong>IDesignTimeDbContextFactory</strong> .</p>
<pre><code>public class YourDbContext : DbContext
{
//Dbcontext implementation
}
public class YourDbContextFactory : IDesignTimeDbContextFactory<YourDbContext>
{
public YourDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<YourDbContext>();
optionsBuilder.UseSqlServer("your connection string");
return new YourDbContext(optionsBuilder.Options);
}
}
</code></pre>
<p>You are using a new <strong>.net core EF</strong> which uses <code>IHostBuilder</code>.(in an older version like yours the provider is IWebHostBuilder).</p>
<p>The tools first try to obtain the service provider by invoking the <code>Program.CreateHostBuilder()</code>, calling <code>Build()</code>, then accessing the Services property.</p>
<p>You can learn more about Design-time DbContext Creation from <a href="https://docs.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli" rel="nofollow noreferrer">Here</a></p>
<p>It may happen from a condition in your startup file or while you are injecting. for example, you have a flag that checks if some variable in <code>appsettings</code> is true to use inmemory database instance.</p>
<p>EF needs to build the model and use the DbContext without starting the application. When EF invokes methods, your config services are still null that's why you get an error.</p>
<p><strong>Make sure you have installed the package</strong></p>
<blockquote>
<p>Microsoft.EntityFrameworkCore.Tools</p>
</blockquote> |
17,533,104 | Restarting a program after exception | <p>I have a program that queries an API every few seconds. Each response triggers a few functions which themselves make some calls to websites and such -- calls that I don't want to blindly trust to succeed. If I catch an exception in <code>foo()</code>, for example, or even in a function that <code>foo()</code> calls, is it possible to restart the program entirely in the except block? Essentially, I want to call <code>queryRepeatedly()</code> upon an exception in one of its sub-functions, without keeping the previous call on the stack.</p>
<p>Of course, I could return marker values and solve this another way, but the program is structured in a way such that the above approach seems much simpler and cleaner.</p>
<pre><code># Sample "main" function that I want to call
def queryRepeatedly():
while True:
foo()
bar()
baz()
time.sleep(15)
def foo():
# do something
try:
foo2() # makes a urllib2 call that I don't trust
except:
#restart queryRepeatedly
queryRepeatedly()
</code></pre> | 17,533,149 | 4 | 3 | null | 2013-07-08 18:02:43.653 UTC | 10 | 2022-07-20 02:49:19.09 UTC | 2022-06-22 20:50:46.197 UTC | null | 3,750,257 | null | 2,407,869 | null | 1 | 19 | python|function | 45,074 | <p>To restart anything, just use a <code>while</code> loop <em>outside</em> the <code>try</code>. For example:</p>
<pre><code>def foo():
while True:
try:
foo2()
except:
pass
else:
break
</code></pre>
<hr />
<p>And if you want to pass the exception up the chain, just do this in the outer function instead of the inner function:</p>
<pre><code>def queryRepeatedly():
while True:
while True:
try:
foo()
bar()
baz()
except:
pass
else:
break
time.sleep(15)
def foo():
foo2()
</code></pre>
<hr />
<p>All that indentation is a little hard to read, but it's easy to refactor this:</p>
<pre><code>def queryAttempt()
foo()
bar()
baz()
def queryOnce():
while True:
try:
queryAttempt()
except:
pass
else:
break
def queryRepeatedly():
while True:
queryOnce()
time.sleep(15)
</code></pre>
<hr />
<p>But if you think about it, you can also merge the two <code>while</code> loops into one. The use of <code>continue</code> may be a bit confusing, but see if you like it better:</p>
<pre><code>def queryRepeatedly():
while True:
try:
foo()
bar()
baz()
except:
continue
time.sleep(15)
</code></pre> |
24,873,117 | AngularJS change url with $location | <p>I'm trying to change the URL with AngularJS,
but not with a redirect, just change the URL
after an event.</p>
<p>What I need is this:</p>
<p><code>www.myurl.com/inbox/1</code> to this <code>www.myurl.com/inbox/25</code></p>
<p>In other words, just change the last Id.</p>
<p>I'm trying to do this:</p>
<p><code>$location.path('/inbox/'+id);</code></p>
<p>But what I'm getting is this:</p>
<p><code>www.myurl.com/inbox/1#/inbox/25</code></p> | 28,142,661 | 3 | 4 | null | 2014-07-21 19:27:34.99 UTC | 1 | 2020-06-30 08:12:19.867 UTC | null | null | null | null | 2,220,256 | null | 1 | 23 | angularjs|url|location | 58,208 | <p>Angular enforces the idea of one page web app. Browsers don't take any actions on change of anything after '#' value. So the best practice is to add variable attributes in url after '#' value which will keep the base url and attribute look clean on browser's address bar as well as solve your problem. My advice is to keep username, page no. , or any specific attribute id after '#' value.
In your case you should use something like above said</p>
<h2>www.myUrl.com/#/inbox/25</h2>
<p>or </p>
<h2>www.myUrl.com/inbox/#/25</h2> |
24,585,661 | Numpy element wise division not working as expected | <p>From the docs, here is how element division works normally</p>
<pre><code>a1 = np.array([8,12,14])
b1 = np.array([4,6,7])
a1/b1
array([2, 2, 2])
</code></pre>
<p>Which works. I am trying the same thing, I think, on different arrays and it doesn't. For two 3-dim vectors it is returning a 3x3 matrix. I even made sure their "shape is same" but no difference.</p>
<pre><code>>> t
array([[ 3.17021277e+00],
[ 4.45795858e-15],
[ 7.52842809e-01]])
>> s
array([ 1.00000000e+00, 7.86202619e+02, 7.52842809e-01])
>> t/s
array([[ 3.17021277e+00, 4.03231011e-03, 4.21098897e+00],
[ 4.45795858e-15, 5.67024132e-18, 5.92149984e-15],
[ 7.52842809e-01, 9.57568432e-04, 1.00000000e+00]])
t/s.T
array([[ 3.17021277e+00, 4.03231011e-03, 4.21098897e+00],
[ 4.45795858e-15, 5.67024132e-18, 5.92149984e-15],
[ 7.52842809e-01, 9.57568432e-04, 1.00000000e+00]])
</code></pre> | 24,585,761 | 1 | 6 | null | 2014-07-05 10:53:11.733 UTC | 1 | 2018-09-14 08:39:17.92 UTC | null | null | null | null | 696,668 | null | 1 | 10 | python|numpy | 48,706 | <p>This is because the shapes of your two arrays are
t.shape = (3,1) and s.shape=(3,). So the broadcasting rules apply: They state that if the two dimensions are equal, then do it element-wise, if they are not the same it will fail unless one of them is one, an this is where it becomes interesting: In this case the array with the dimension of one will iterate the operation over all elements of the other dimension.</p>
<p>I guess what you want to do would be</p>
<pre><code>t[:,0] / s
</code></pre>
<p>or</p>
<pre><code>np.squeeze(t) / s
</code></pre>
<p>Both of which will get rid of the empty first dimension in t. This really is not a bug it is a feature! because if you have two vectors and you want to do an operation between all elements you do exactly that:</p>
<pre><code>a = np.arange(3)
b = np.arange(3)
</code></pre>
<p>element-wise you can do now:</p>
<pre><code>a*b = [0,1,4]
</code></pre>
<p>If you would want to do have this operation performed between all elements you can insert these dimensions of size one like so:</p>
<pre><code>a[np.newaxis,:] * b[:,np.newaxis]
</code></pre>
<p>Try it out! It really is a convenient concept, although I do see how this is confusing at first.</p> |
22,081,991 | rmarkdown: pandoc: pdflatex not found | <p>When I use the render{rmarkdown} to produce pdf file from .Rmd file on my Mac, an error message says</p>
<p><code>pandoc: pdflatex not found. pdflatex is needed for pdf output.
Error: pandoc document conversion failed</code> </p>
<p>However when I check with </p>
<pre><code>pdflatex -v
</code></pre>
<p>I got</p>
<pre><code>pdfTeX 3.1415926-2.4-1.40.13 (TeX Live 2012)
kpathsea version 6.1.0
Copyright 2012 Peter Breitenlohner (eTeX)/Han The Thanh (pdfTeX).
There is NO warranty. Redistribution of this software is
covered by the terms of both the pdfTeX copyright and
the Lesser GNU General Public License.
For more information about these matters, see the file
named COPYING and the pdfTeX source.
Primary author of pdfTeX: Peter Breitenlohner (eTeX)/Han The Thanh (pdfTeX).
Compiled with libpng 1.5.10; using libpng 1.5.10
Compiled with zlib 1.2.7; using zlib 1.2.7
Compiled with xpdf version 3.03
</code></pre>
<p>The pdflatex is installed in my machine.</p>
<p>Can anyone help to tell how can I tell R where to find the pdflatex?</p>
<p>Many thanks!</p> | 22,487,657 | 7 | 2 | null | 2014-02-27 22:30:17.993 UTC | 15 | 2021-08-04 07:27:08.303 UTC | 2014-02-28 11:27:59.22 UTC | null | 821,436 | null | 1,675,044 | null | 1 | 69 | r|macos|pandoc|pdflatex|r-markdown | 87,748 | <p><a href="https://tex.stackexchange.com/questions/163849/mavericks-upgrade-screwed-up-my-pdflatex-command-not-found">This answer on TexExchange might help</a>.</p>
<p>I found I was having issues with <code>pdflatex</code> "missing" after I upgraded to OS X Mavericks (e.g. when checking package builds in RStudio I was getting an <code>error tools::texi2pdf pdflatex missing</code> message).</p>
<ol>
<li><p>Check that <code>/usr/texbin</code> exists.<br>
In terminal:</p>
<pre><code>cd /usr/texbin
</code></pre></li>
<li><p>If "No such file or directory" then you will need to create a symbolic link to your installation's texbin. Mine was in <code>/Library/TeX/Distributions/.DefaultTeX/Contents/Programs/texbin</code><br>
In terminal:</p>
<pre><code>ln -s /Library/TeX/Distributions/.DefaultTeX/Contents/Programs/texbin /usr/texbin
</code></pre></li>
<li><p>In terminal, check the result of <code>echo $PATH</code>. Make sure that <code>/usr/texbin</code> is present. If it isn't present, then you need to add <code>/usr/texbin</code> to your <code>PATH</code> variable.</p></li>
</ol>
<p>If you find yourself having to mess with the <code>PATH</code> variable, installing the latest version of <a href="http://tug.org/mactex/" rel="noreferrer">MacTex</a> might be a better solution.</p>
<p><strong>UPDATE:</strong> OS X 10.11 El Capitan no longer allows writes to <code>/usr</code> so the latest version of MacTeX (2015) now writes a link to <code>/Library/TeX/texbin</code> instead of <code>/usr/texbin</code> on this system.</p> |
27,317,517 | Make division by zero equal to zero | <p>How can I ignore <code>ZeroDivisionError</code> and make <code>n / 0 == 0</code>?</p> | 27,317,595 | 10 | 5 | null | 2014-12-05 13:57:50.87 UTC | 15 | 2022-08-26 03:58:38.09 UTC | 2014-12-05 14:12:14.103 UTC | null | 400,617 | null | 908,703 | null | 1 | 55 | python|division|zero | 156,348 | <p>Check if the denominator is zero before dividing. This avoids the overhead of catching the exception, which may be more efficient if you expect to be dividing by zero a lot.</p>
<pre><code>def weird_division(n, d):
return n / d if d else 0
</code></pre> |
26,944,274 | ValueError: dict contains fields not in fieldnames | <p>Can someone help me with this. </p>
<p>I have my Select query</p>
<pre><code>selectAttendance = """SELECT * FROM table """
</code></pre>
<p>And I want the content of my select query and include a header when I download the csv file,
So I did this query:</p>
<pre><code>with open(os.path.join(current_app.config['UPLOAD_FOLDER'], 'csv.csv'), 'wb') as csvfile:
writer = csv.DictWriter(csvfile,fieldnames = ["Bio_Id","Last_Name","First_Name","late","undertime","total_minutes", "total_ot", "total_nsd", "total_absences"], delimiter = ';')
writer.writeheader()
writer.writerow(db.session.execute(selectAttendance))
db.session.commit()
</code></pre>
<p>but it gives me this error</p>
<pre><code>**ValueError: dict contains fields not in fieldnames**
</code></pre>
<p>I want to have like this output in my downloaded csv file:</p>
<pre><code>Bio_Id Last_Name First_Name late undertime total_minutes total_ot total_nsd total_absences
1 Joe Spark 1 1 2 1 1 1
</code></pre>
<p>Thank you in advance.</p> | 26,944,519 | 4 | 6 | null | 2014-11-15 09:04:17.89 UTC | 6 | 2022-04-08 13:43:29.28 UTC | 2014-11-15 09:31:32.12 UTC | null | 4,060,681 | null | 4,060,681 | null | 1 | 48 | python|csv | 59,862 | <p>As the error states: the dictionary that comes from the query contains more key than the field names you specified in the DictWriter constructor.</p>
<p>One solution would be to filter that in advance, something like this:</p>
<pre><code>field_names = ["Bio_Id","Last_Name", ...]
writer = csv.DictWriter(csvfile,fieldnames=field_names , delimiter = ';')
writer.writeheader()
data = {key: value for key, value in db.session.execute(selectAttendance).items()
if key in field_names}
writer.writerow(data)
</code></pre>
<p>Another solution could be to construct the query using only those fields:</p>
<pre><code>query = 'SELECT %s FROM table' % ', '.join(field_names)
</code></pre>
<p>However, Tim Pietzcker's answer is the best.</p> |
44,833,817 | MongoDB Full and Partial Text Search | <p><strong>Env:</strong></p>
<ul>
<li>MongoDB (3.2.0) with Mongoose</li>
</ul>
<hr />
<p><strong>Collection:</strong></p>
<ul>
<li>users</li>
</ul>
<hr />
<p><strong>Text Index creation:</strong></p>
<pre><code> BasicDBObject keys = new BasicDBObject();
keys.put("name","text");
BasicDBObject options = new BasicDBObject();
options.put("name", "userTextSearch");
options.put("unique", Boolean.FALSE);
options.put("background", Boolean.TRUE);
userCollection.createIndex(keys, options); // using MongoTemplate
</code></pre>
<hr />
<p><strong>Document:</strong></p>
<ul>
<li>{"name":"LEONEL"}</li>
</ul>
<hr />
<p><strong>Queries:</strong></p>
<ul>
<li><code>db.users.find( { "$text" : { "$search" : "LEONEL" } } )</code> => FOUND</li>
<li><code>db.users.find( { "$text" : { "$search" : "leonel" } } )</code> => FOUND (search caseSensitive is false)</li>
<li><code>db.users.find( { "$text" : { "$search" : "LEONÉL" } } )</code> => FOUND (search with diacriticSensitive is false)</li>
<li><code>db.users.find( { "$text" : { "$search" : "LEONE" } } )</code> => FOUND (Partial search)</li>
<li><code>db.users.find( { "$text" : { "$search" : "LEO" } } )</code> => NOT FOUND (Partial search)</li>
<li><code>db.users.find( { "$text" : { "$search" : "L" } } )</code> => NOT FOUND (Partial search)</li>
</ul>
<p>Any idea why I get 0 results using as query "LEO" or "L"?</p>
<p>Regex with Text Index Search is not allowed.</p>
<pre><code>db.getCollection('users')
.find( { "$text" : { "$search" : "/LEO/i",
"$caseSensitive": false,
"$diacriticSensitive": false }} )
.count() // 0 results
db.getCollection('users')
.find( { "$text" : { "$search" : "LEO",
"$caseSensitive": false,
"$diacriticSensitive": false }} )
.count() // 0 results
</code></pre>
<hr />
<p><strong>MongoDB Documentation:</strong></p>
<ul>
<li><a href="https://docs.mongodb.com/v3.2/text-search/" rel="noreferrer">Text Search</a></li>
<li><a href="https://docs.mongodb.com/manual/reference/operator/query/text/" rel="noreferrer">$text</a></li>
<li><a href="https://docs.mongodb.com/manual/core/index-text/" rel="noreferrer">Text Indexes</a></li>
<li><a href="https://jira.mongodb.org/browse/SERVER-15090" rel="noreferrer">Improve Text Indexes to support partial word match</a></li>
</ul> | 45,416,195 | 11 | 4 | null | 2017-06-29 19:50:51.737 UTC | 32 | 2021-03-23 00:57:33.023 UTC | 2021-01-15 14:43:35.05 UTC | null | 171,933 | null | 2,953,261 | null | 1 | 89 | mongodb|mongodb-query|aggregation-framework|spring-data-mongodb|full-text-indexing | 102,796 | <p>As at MongoDB 3.4, the <a href="https://docs.mongodb.com/manual/text-search/" rel="noreferrer">text search</a> feature is designed to support case-insensitive searches on text content with language-specific rules for stopwords and stemming. Stemming rules for <a href="https://docs.mongodb.com/manual/reference/text-search-languages/" rel="noreferrer">supported languages</a> are based on standard algorithms which generally handle common verbs and nouns but are unaware of proper nouns.</p>
<p>There is no explicit support for partial or fuzzy matches, but terms that stem to a similar result may appear to be working as such. For example: "taste", "tastes", and tasteful" all stem to "tast". Try the <a href="http://snowballstem.org/demo.html" rel="noreferrer">Snowball Stemming Demo</a> page to experiment with more words and stemming algorithms.</p>
<p>Your results that match are all variations on the same word "LEONEL", and vary only by case and diacritic. Unless "LEONEL" can be stemmed to something shorter by the rules of your selected language, these are the only type of variations that will match.</p>
<p>If you want to do efficient partial matches you'll need to take a different approach. For some helpful ideas see:</p>
<ul>
<li><a href="http://ilearnasigoalong.blogspot.com.au/2013/10/efficient-techniques-for-fuzzy-and.html" rel="noreferrer">Efficient Techniques for Fuzzy and Partial matching in MongoDB</a> by John Page</li>
<li><a href="https://web.archive.org/web/20170609122132/http://jam.sg/blog/efficient-partial-keyword-searches/" rel="noreferrer">Efficient Partial Keyword Searches</a> by James Tan</li>
</ul>
<p>There is a relevant improvement request you can watch/upvote in the MongoDB issue tracker: <a href="https://jira.mongodb.org/browse/SERVER-15090" rel="noreferrer">SERVER-15090: Improve Text Indexes to support partial word match</a>.</p> |
17,235,101 | Scrapy crawler in Cron job | <p>I want to execute my scrapy crawler from cron job .</p>
<p>i create bash file getdata.sh where scrapy project is located with it's spiders</p>
<pre><code>#!/bin/bash
cd /myfolder/crawlers/
scrapy crawl my_spider_name
</code></pre>
<p>My crontab looks like this , I want to execute it in every 5 minute</p>
<pre><code> */5 * * * * sh /myfolder/crawlers/getdata.sh
</code></pre>
<p>but it don't works , whats wrong , where is my error ? </p>
<p>when I execute my bash file from terminal sh /myfolder/crawlers/getdata.sh it works fine</p> | 17,235,906 | 7 | 1 | null | 2013-06-21 12:18:57.107 UTC | 11 | 2019-07-13 08:31:49.01 UTC | null | null | null | null | 283,192 | null | 1 | 25 | ubuntu|cron|scrapy|crontab|cron-task | 16,765 | <p>I solved this problem including PATH into bash file </p>
<pre><code>#!/bin/bash
cd /myfolder/crawlers/
PATH=$PATH:/usr/local/bin
export PATH
scrapy crawl my_spider_name
</code></pre> |
17,198,112 | Handling openURL: with Facebook and Google | <p>user in my app can login using 2 services : Facebook or Google</p>
<p>everything works fine, however, in the :</p>
<pre><code>- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation: (id)annotation {
...
}
</code></pre>
<p>i should decide to call the Facebook callback or Google callback</p>
<p>if the user has the apps, its easy, than i decide by the sourceApplication
but when not (no native Facebook account linked in, no FB app, no GooglePlus app), it links to the browser :( and i dont know if it is comming from Facebook or Google</p>
<p><strong>is there a way how to decide what to call? like</strong></p>
<pre><code>- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation: (id)annotation {
// how to decide?
if (facebook) {
return [FBSession.activeSession handleOpenURL:url];
} else if (google) {
return [GPPURLHandler handleURL:url sourceApplication:sourceApplication annotation:annotation];
}
}
</code></pre> | 29,256,843 | 10 | 0 | null | 2013-06-19 18:00:14.987 UTC | 2 | 2021-12-07 14:24:25.3 UTC | 2013-06-19 18:44:35.707 UTC | null | 2,487,322 | null | 533,422 | null | 1 | 33 | ios|facebook|cocoa-touch|oauth-2.0 | 13,752 | <p>We don't need to Explicitly check the URL, the code below does it:</p>
<pre><code>- (BOOL)application: (UIApplication *)application openURL: (NSURL *)url sourceApplication: (NSString *)sourceApplication annotation: (id)annotation
{
if ([GPPURLHandler handleURL:url sourceApplication:sourceApplication annotation:annotation]) {
return YES;
}else if([FBAppCall handleOpenURL:url sourceApplication:sourceApplication]){
return YES;
}
return NO;
}
</code></pre> |
17,301,683 | How to replace a value with the output of a command in a text file? | <p>I have a file that contains:</p>
<pre class="lang-php prettyprint-override"><code><?php return 0;
</code></pre>
<p>I want to replace in bash, the value <code>0</code> by the current timestamp.</p>
<p>I know I can get the current timestamp with:</p>
<pre class="lang-sh prettyprint-override"><code>date +%s
</code></pre>
<p>And I can replace strings with <code>sed</code>:</p>
<pre class="lang-sh prettyprint-override"><code>sed 's/old/new/g' input.txt > output.txt
</code></pre>
<p>But how to combine the two to achieve what I want? Solutions not involving <code>sed</code> and <code>date</code> are welcome as well, as long as they only use shell tools.</p> | 17,301,724 | 2 | 0 | null | 2013-06-25 15:41:42.003 UTC | 4 | 2019-01-02 10:53:34.547 UTC | null | null | null | null | 759,866 | null | 1 | 33 | bash|replace|sed | 43,712 | <p>In general, do use this syntax:</p>
<pre><code>sed "s/<expression>/$(command)/" file
</code></pre>
<p>This will look for <code><expression></code> and replace it with the output of <code>command</code>.</p>
<hr>
<p>For your specific problem, you can use the following:</p>
<pre><code>sed "s/0/$(date +%s)/g" input.txt > output.txt
</code></pre>
<p>This replaces any <code>0</code> present in the file with the output of the command <code>date +%s</code>. Note you need to use double quotes to make the command in <code>$()</code> be interpreted. Otherwise, you would get a literal <code>$(date +%s)</code>.</p>
<p>If you want the file to be updated automatically, add <code>-i</code> to the sed command: <code>sed -i "s/...</code>. This is called in-place editing.</p>
<hr>
<h3>Test</h3>
<p>Given a file with this content:</p>
<pre><code><?php return 0;
</code></pre>
<p>Let's see what it returns:</p>
<pre><code>$ sed "s/0/$(date +%s)/g" file
<?php return 1372175125;
</code></pre> |
17,136,794 | FoldLeft using FoldRight in scala | <p>While going through <a href="http://www.manning.com/bjarnason/" rel="noreferrer">Functional Programming in Scala</a>, I came across this question:</p>
<blockquote>
<p>Can you right foldLeft in terms of foldRight? How about the other way
around?</p>
</blockquote>
<p>In solution provided by the authors they have provided an implementation as follows:</p>
<pre><code>def foldRightViaFoldLeft_1[A,B](l: List[A], z: B)(f: (A,B) => B): B =
foldLeft(l, (b:B) => b)((g,a) => b => g(f(a,b)))(z)
def foldLeftViaFoldRight[A,B](l: List[A], z: B)(f: (B,A) => B): B =
foldRight(l, (b:B) => b)((a,g) => b => g(f(b,a)))(z)
</code></pre>
<p>Can somebody help me trace through this solution and make me understand how this actually gets the foldl implemented in terms of foldr and vice-versa?</p>
<p>Thanks</p> | 17,137,030 | 4 | 3 | null | 2013-06-16 19:14:56.167 UTC | 15 | 2019-03-10 13:53:53.91 UTC | null | null | null | null | 207,072 | null | 1 | 37 | scala|functional-programming|currying|fold|higher-order-functions | 8,089 | <p>Let's have a look at</p>
<pre><code>def foldLeftViaFoldRight[A,B](l: List[A], z: B)(f: (B,A) => B): B =
foldRight(l, (b:B) => b)((a,g) => b => g(f(b,a)))(z)
</code></pre>
<p>(the other fold is similar). The trick is that during the right fold operation, we don't build the final value of type <code>B</code>. Instead, we build a function from <code>B</code> to <code>B</code>. The fold step takes a value of type <code>a: A</code> and a function <code>g: B => B</code> and produces a new function <code>(b => g(f(b,a))): B => B</code>. This function can be expressed as a composition of <code>g</code> with <code>f(_, a)</code>:</p>
<pre><code> l.foldRight(identity _)((a,g) => g compose (b => f(b,a)))(z);
</code></pre>
<p>We can view the process as follows: For each element <code>a</code> of <code>l</code> we take the partial application <code>b => f(b,a)</code>, which is a function <code>B => B</code>. Then, we <a href="https://en.wikipedia.org/wiki/Function_composition">compose</a> all these functions in such a way that the function corresponding to the rightmost element (with which we start the traversal) is at far left in the composition chain. Finally, we apply the big composed function on <code>z</code>. This results in a sequence of operations that starts with the leftmost element (which is at far right in the composition chain) and finishes with the right most one.</p>
<p><strong>Update:</strong> As an example, let's examine how this definition works on a two-element list. First, we'll rewrite the function as</p>
<pre><code>def foldLeftViaFoldRight[A,B](l: List[A], z: B)
(f: (B,A) => B): B =
{
def h(a: A, g: B => B): (B => B) =
g compose ((x: B) => f(x,a));
l.foldRight(identity[B] _)(h _)(z);
}
</code></pre>
<p>Now let's compute what happens when we pass it <code>List(1,2)</code>:</p>
<pre><code>List(1,2).foldRight(identity[B] _)(h _)
= // by the definition of the right fold
h(1, h(2, identity([B])))
= // expand the inner `h`
h(1, identity[B] compose ((x: B) => f(x, 2)))
=
h(1, ((x: B) => f(x, 2)))
= // expand the other `h`
((x: B) => f(x, 2)) compose ((x: B) => f(x, 1))
= // by the definition of function composition
(y: B) => f(f(y, 1), 2)
</code></pre>
<p>Applying this function to <code>z</code> yields</p>
<pre><code>f(f(z, 1), 2)
</code></pre>
<p>as required.</p> |
17,288,859 | Using memset for integer array in C | <pre><code>char str[] = "beautiful earth";
memset(str, '*', 6);
printf("%s", str);
Output:
******ful earth
</code></pre>
<p>Like the above use of memset, can we initialize only a few integer array index values to 1 as given below?</p>
<pre><code>int arr[15];
memset(arr, 1, 6);
</code></pre> | 17,288,891 | 10 | 5 | null | 2013-06-25 03:51:15.827 UTC | 26 | 2022-08-07 03:39:26.077 UTC | 2019-11-27 18:29:24.33 UTC | null | 63,550 | null | 1,762,571 | null | 1 | 52 | c|memset | 124,568 | <p>No, you cannot use <code>memset()</code> like this. The <a href="http://linux.die.net/man/3/memset" rel="noreferrer">manpage</a> says (emphasis mine):</p>
<blockquote>
<p>The <code>memset()</code> function fills the first <code>n</code> <strong>bytes</strong> of the memory area pointed to by <code>s</code> with the constant byte <code>c</code>.</p>
</blockquote>
<p>Since an <code>int</code> is usually 4 bytes, this won't cut it.</p>
<hr>
<p>If you (<em>incorrectly!!</em>) try to do this:</p>
<pre><code>int arr[15];
memset(arr, 1, 6*sizeof(int)); //wrong!
</code></pre>
<p>then the first 6 <code>int</code>s in the array will actually be set to 0x01010101 = 16843009.</p>
<p>The only time it's ever really acceptable to write over a "blob" of data with non-byte datatype(s), is <code>memset(thing, 0, sizeof(thing));</code> to "zero-out" the whole struture/array. This works because NULL, 0x00000000, 0.0, are all completely zeros.</p>
<hr>
<p>The solution is to use a <code>for</code> loop and set it yourself:</p>
<pre><code>int arr[15];
int i;
for (i=0; i<6; ++i) // Set the first 6 elements in the array
arr[i] = 1; // to the value 1.
</code></pre> |
17,394,356 | How can I make a bash command run periodically? | <p>I want to execute a script and have it run a command every x minutes.</p>
<p>Also any general advice on any resources for learning bash scripting could be really cool. I use Linux for my personal development work, so bash scripts are not totally foreign to me, I just haven't written any of my own from scratch.</p> | 17,394,383 | 8 | 2 | null | 2013-06-30 20:04:57.063 UTC | 17 | 2020-11-05 14:17:56.34 UTC | 2016-03-03 20:22:51.953 UTC | null | 1,788,806 | null | 62,983 | null | 1 | 75 | bash | 89,712 | <p>If you want to run a command periodically, there's 3 ways :</p>
<ul>
<li>using the <code>crontab</code> command ex. <code>* * * * * command</code> (run every minutes)</li>
<li>using a loop like : <code>while true; do ./my_script.sh; sleep 60; done</code> (not precise)</li>
<li>using <a href="https://wiki.archlinux.org/index.php/Systemd/Timers" rel="noreferrer">systemd timer</a></li>
</ul>
<p>See <a href="https://en.wikipedia.org/wiki/Cron" rel="noreferrer">cron</a></p>
<p>Some pointers for best bash scripting practices :</p>
<p><a href="http://mywiki.wooledge.org/BashFAQ" rel="noreferrer">http://mywiki.wooledge.org/BashFAQ</a><br>
Guide: <a href="http://mywiki.wooledge.org/BashGuide" rel="noreferrer">http://mywiki.wooledge.org/BashGuide</a><br>
ref: <a href="http://www.gnu.org/software/bash/manual/bash.html" rel="noreferrer">http://www.gnu.org/software/bash/manual/bash.html</a><br>
<a href="http://wiki.bash-hackers.org/" rel="noreferrer">http://wiki.bash-hackers.org/</a><br>
USE MORE QUOTES!: <a href="http://www.grymoire.com/Unix/Quote.html" rel="noreferrer">http://www.grymoire.com/Unix/Quote.html</a><br>
Scripts and more: <a href="http://www.shelldorado.com/" rel="noreferrer">http://www.shelldorado.com/</a> </p> |
17,540,088 | Add the values on ArrayList in Android | <p>I have develop one application. Here i have to add the value on <code>ArrayList</code>. if i have to click <code>Button</code> means that value have to add on that <code>ArrayList</code>. I have to click another <code>Button</code> means that added list is displaying. How can i do? Please give me solution.</p>
<p><strong>These are my values:</strong></p>
<pre><code> product_id = getIntent().getStringExtra("id");
product_title = getIntent().getStringExtra("title");
product_image = getIntent().getStringExtra("image");
product_price = getIntent().getStringExtra("price");
product_desc = getIntent().getStringExtra("description");
arrayList = new ArrayList<String>();
arrayList.add(product_title);
arrayList.add(product_price);
arrayList.add(product_id);
arrayList.add(product_image);
arrayList.add(product_desc);
</code></pre>
<p>I have to add these values on <code>ArrayList</code> while clicking the <code>Button</code>:</p>
<pre><code> valueaddlist = (Button) findViewById(R.id.valueaddlist);
valueaddlist.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Intent intent = new Intent(this,AddedListProducts.class);
intent.putExtra("WishListProducts", arrayList);
startActivity(intent);
}
</code></pre>
<p>In the <code>AddedListProducts</code> have to displaying all added products list.</p>
<p>How can i do ?
please give me solution for these ?</p>
<p><strong>EDIT:</strong></p>
<p>This is my AddedListProducts class code:</p>
<pre><code>wishlist_products = (ListView) findViewById(R.id.wishlist_products);
if(getIntent().getExtras() !=null){
WishListProducts = (ArrayList<String>) getIntent().getExtras().getSerializable("WishListProducts");
System.out.println(WishListProducts);
wishlistproductsAdapter = new WishListAdapter(this,WishListProducts);
wishlist_products.setAdapter(wishlistproductsAdapter);
}
</code></pre>
<p>In these arraylist am getting values.how can i set the value on adapter file and UI.</p>
<p>This is my adapter file code:</p>
<pre><code> public class WishListAdapter extends BaseAdapter{
WishListAdapter mListViewAdapter;
private Activity mActivity;
private ArrayList<String> mwishlistProducts;
public ImageLoader mImageLoader;
private static LayoutInflater inflater=null;
public WishListAdapter(Activity activity, ArrayList<String> products) {
mActivity = activity;
this.mwishlistProducts=products;
inflater = (LayoutInflater)mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
class ViewHolder{
private ImageView productImageView;
private TextView productTitleView;
private TextView productPriceView;
private TextView productDescView;
public ViewHolder(ImageView productImageView, TextView productTitleView,TextView productPriceView,TextView productDescView) {
super();
this.productImageView = productImageView;
this.productTitleView = productTitleView;
this.productPriceView = productPriceView;
this.productDescView = productDescView;
}
} // ViewHolder-class
public int getCount() {
return mwishlistProducts.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
final String wishlistproductList = mwishlistProducts.get(position);
if( convertView == null )
{
convertView = inflater.inflate(R.layout.list_product, null);
ImageView productImage=(ImageView)convertView.findViewById(R.id.productimage);
TextView productTitle = (TextView)convertView.findViewById(R.id.producttitle);
TextView productPrice = (TextView)convertView.findViewById(R.id.productprice);
TextView productDesc = (TextView)convertView.findViewById(R.id.productdescription);
holder = new ViewHolder(productImage,productTitle,productPrice,productDesc);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
holder.productTitleView.setText();
holder.productPriceView.setText();
holder.productDescView.setText();
mImageLoader=new ImageLoader();
mImageLoader.DisplayImage();
return convertView;
}
}
</code></pre>
<p>In these holder file what i have to set ????</p>
<p>How can i set that arraylist value here.please help me yaar..</p>
<p><strong>EDIT:</strong></p>
<p>More products is displaying on one listview.
Now i have to click one list item means its go to detail description page.here i have to click button means that product detail value is adding and have to display on AddedListProducts Page.</p>
<p>now i ll go to back and click another product means click button means that product detail also added and have to display on AddedListProducts page with that old added products...</p>
<p>i have to add products from that listview and go to next page and clicking button means have to display that all added products on AddedListProducts page.how can i do ???</p>
<p>Above code ly displaying last added product ly.I want to display all added products on that list.</p> | 17,540,328 | 2 | 3 | null | 2013-07-09 04:44:11.897 UTC | null | 2013-07-09 05:50:45.29 UTC | 2013-07-09 05:50:45.29 UTC | null | 2,218,667 | null | 2,218,667 | null | 1 | -6 | java|android|arraylist | 39,559 | <p>After getting value from intent:</p>
<pre><code>ArrayList<String> arrayList = new ArrayList<String>();
valueaddlist = (Button) findViewById(R.id.valueaddlist);
valueaddlist.setOnClickListener(new OnClickListener() {
public void onClick(View v){
arrayList.add(product_id);
arrayList.add(product_title);
arrayList.add(product_image);
arrayList.add(product_price);
arrayList.add(product_desc);
}
valuedisplaylist = (Button) findViewById(R.id.valuedisplaylist);
valuedisplaylist.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Intent intent = new Intent(this,AddedListProducts.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) arrayList);
startActivity(intent);
}
</code></pre>
<p>May be this will help you.</p>
<p>In your second activity get the arraylist like :</p>
<pre><code> ArrayList<String> ar1=getIntent().getExtras().getStringArrayList("arrayList"); ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ar1);
lv.setAdapter(arrayAdapter);
</code></pre>
<p>Then have a look at this question to display arraylist: <a href="https://stackoverflow.com/questions/5070830/populating-a-listview-using-arraylist">Populating a ListView using an ArrayList?</a></p> |
30,705,370 | "Gtk-WARNING **: Locale not supported by C library. Using the fallback 'C' locale." on OS X | <h3>Background information:</h3>
<p>I use Mac OSX Yosemite.</p>
<p>I've installed <code>gtk+</code> using <code>brew install gtk+</code> and fixed the errors using <code>export PKG_CONFIG_PATH=/opt/X11/lib/pkgconfig</code>.</p>
<p>I've build my program using <code>make</code> but when I try to run it I get a warning like this:</p>
<pre><code>(process:16182): Gtk-WARNING **: Locale not supported by C library.
Using the fallback 'C' locale.
</code></pre>
<h2>Problem: I cannot find any solutions for OS X for this particular problem.</h2>
<h3>What I've learnt so far:</h3>
<ol>
<li><p>In this thread (<a href="https://stackoverflow.com/questions/20366533/gtk-warning-locale-not-supported-by-c-library-while-using-several-python-mo">Gtk-WARNING **: Locale not supported by C library. while using several Python modules (mayavi, spectral)</a>) they suggests using: <blockquote> <code>ipython --pylab=wx</code> instead of <code>ipython --pylab=osx</code></blockquote>
but I've got no idea how python can be related to my problem (my program is written in C - the same applies to <code>gtk+</code> I guess)</p></li>
<li><p>You can find a lot of threads on this issue like this one: (<a href="https://askubuntu.com/questions/359753/gtk-warning-locale-not-supported-by-c-library-when-starting-apps-from-th">Gtk-WARNING **: Locale not supported by C library. when starting apps from the commandline</a>) but they mainly refer to Linux and/or Ubuntu. <br>Most of the answers use a command like this sooner or later:</p>
<pre><code> sudo dpkg-reconfigure locales
</code></pre>
<p>But there is no <code>dpkg</code> on OS X.</p></li>
</ol> | 30,892,121 | 1 | 4 | null | 2015-06-08 09:21:06.247 UTC | 2 | 2019-09-18 12:22:28.687 UTC | 2018-11-06 09:20:00.277 UTC | null | 4,694,621 | null | 4,694,621 | null | 1 | 8 | c|macos|gtk|locale | 40,368 | <p>The issue here is that the environment variable <code>LANG</code> is not set, because I've mixed settings for Polish and English in the <em>Language and Region</em> section in <em>System Preferences</em>.</p>
<p>Quoting <a href="https://stackoverflow.com/users/1312143">@KenThomases</a> who helped me a lot with this problem:</p>
<blockquote>
<p>There's not going to be any C library locale defined for the English language in Poland (i.e. en_PL.UTF-8). That's why Terminal is not setting LANG for you in your shells, even though you have "Set locale environment variables on startup" enabled. </p>
</blockquote>
<p>You can read the in-depth solution here:<br>
<a href="https://stackoverflow.com/questions/30832012/is-it-bad-that-lang-and-lc-all-are-empty-when-running-locale-a-on-mac-osx-yos/30832995?noredirect=1#comment49822529_30832995">Is it bad that LANG and LC_ALL are empty when running `locale -a` on OS X Yosemite?</a></p> |
36,803,389 | Async pipe does not fill object data into template | <p>Can anyone help me see if there is a syntax error here in my template? It does not give error, but does not fill in data into the template either:</p>
<pre class="lang-html prettyprint-override"><code><div *ngIf="(hero | async)">
<h2>{{hero}}</h2>
<h2>{{hero.name}} details!</h2>
<div>
<label>_id: </label>{{hero._id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name" />
</div>
<button (click)="goBack()">Back</button>
</div>
</code></pre>
<p>Component code</p>
<pre class="lang-js prettyprint-override"><code>export class HeroDetailComponent implements OnInit {
errorMessage: string;
@Input() hero: Observable<Hero>;
constructor(
private _heroService: HeroService,
private _routeParams: RouteParams
) {}
ngOnInit() {
let _id = +this._routeParams.get('_id');
this._heroService.loadHero(_id);
this.hero = this._heroService.hero$;
this.hero.subscribe(data =>
console.log(data)
);
}
}
</code></pre>
<p>The <code>console.log(data)</code> prints:</p>
<blockquote>
<p>Object {_id: 11, name: "Mr. Nice"}</p>
</blockquote>
<p>which means that the data is correctly retrieved.</p>
<p>The <code><div></code> block also shows up, which mean <code>*ngIf</code> sees the object as non-empty.</p>
<p><code><h2>{{hero}}</h2></code> shows <code>[object Object]</code>.</p>
<p>But why the <code>{{hero.name}}</code> is not showing?</p> | 36,806,047 | 6 | 2 | null | 2016-04-22 21:12:26.493 UTC | 8 | 2022-05-11 09:59:25.02 UTC | 2022-05-10 23:24:11.783 UTC | null | 2,990,390 | null | 1,794,925 | null | 1 | 29 | angular|angular2-template | 36,832 | <p>Objects are a bit tricky with the async pipe. With an Observable that contains an array, we can use NgFor and create a local template variable (<code>hero</code> below) that gets assigned each item of the array after the async pipe extracts the array from the Observable. We can then use that variable elsewhere in the template:</p>
<pre><code><div *ngFor="let hero of heroes | async">
{{hero.name}}
</div>
<!-- we can't use hero here, outside the NgFor div -->
</code></pre>
<p>But with an Observable that contains a single object, I'm not aware of any way to create a local template variable that will reference that object. Instead, we need to do something more complicated:</p>
<pre><code><div>{{(hero | async)?.name}}</div>
</code></pre>
<p>And we would need to repeat that for each property of the object we want to display. (The above line assumes that component property <code>hero</code> is an Observable.)</p>
<p>It is probably easier to assign the object (that is inside the Observable, <code>hero$</code> below) to a property of the component, using component logic:</p>
<pre><code>this._heroService.hero$.subscribe(data => this.hero = data.json());
</code></pre>
<p>and then use NgIf or the <a href="https://angular.io/docs/ts/latest/guide/template-syntax.html#!#elvis" rel="noreferrer">Elvis/safe navigation operator</a> to display the data in the view:</p>
<pre><code><div *ngIf="hero">{{hero.name}}</div>
<!-- or -->
<div>{{hero?.name}}</div>
</code></pre> |
26,365,339 | AngularJS and getting window scroll position in controller | <p>I'm having some trouble understanding how to get the scroll position of window within my controller, so I can build logic around it.</p>
<p>From all the questions and answers I've been reading the most accepted answer seems to be to write a directive that calculates the scroll position, stick that directive on an element, and that's it.</p>
<p>However, when you want to do something along the lines of:</p>
<pre><code>if (scrollY > 100 ){
$scope.showMenu = true;
}
if (scrollY > 500) {
$scope.showFooter = true;
}
</code></pre>
<p>This approach doesn't seem to work, because the calculated position in the directive can't be accessed from the controller. What would be the right 'Angular' way of doing this, which would still allow slightly more complicated logic to be executed from the controller?</p> | 35,975,308 | 3 | 3 | null | 2014-10-14 16:08:37.793 UTC | null | 2019-06-23 18:15:31.247 UTC | 2018-08-17 12:45:20.22 UTC | null | 742,775 | null | 453,746 | null | 1 | 12 | javascript|angularjs|scroll | 41,213 | <p>According to @RobKohr comment, here's a optimized approach using <code>.on('scroll')</code> and <code>$scope.$apply</code> to update a scope element on scroll.</p>
<pre><code>$document.on('scroll', function() {
// do your things like logging the Y-axis
console.log($window.scrollY);
// or pass this to the scope
$scope.$apply(function() {
$scope.pixelsScrolled = $window.scrollY;
})
});
</code></pre> |
23,442,621 | Ant: Class not found: javac1.8 | <p>I am trying to build a project using Ant in eclipse. I right-clicked on build.xml > Run As > Ant Build. However, I am getting the following error:</p>
<pre><code>BUILD FAILED
C:\Users\David\eclipse\test-project\build.xml:26: Class not found: javac1.8
</code></pre>
<p>and also a warning:</p>
<pre><code>compile:
[javac] C:\Users\David\eclipse\test-project\build.xml:26: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
</code></pre>
<p>As I read in other posts that this might be due to having an ant version that is too old or not having set the environment variables correctly here is all the info:</p>
<pre><code>C:\>java -version
java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)
C:\>ant -version
Apache Ant(TM) version 1.9.3 compiled on December 23 2013
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.8.0_05
C:\>echo %JRE_HOME%
C:\Program Files\Java\jre8
</code></pre>
<p>EDIT:
Here is the whole build.xml, line 26 is the javac tag:</p>
<pre><code><?xml version="1.0"?>
<project name="test-project" default="main" basedir=".">
<!-- Sets variables which can later be used. -->
<!-- The value of a property is accessed via ${} -->
<property name="src.dir" location="src" />
<property name="build.dir" location="bin" />
<property name="dist.dir" location="dist" />
<property name="docs.dir" location="docs" />
<!-- Deletes the existing build, docs and dist directory-->
<target name="clean">
<delete dir="${build.dir}" />
<delete dir="${docs.dir}" />
<delete dir="${dist.dir}" />
</target>
<!-- Creates the build, docs and dist directory-->
<target name="makedir">
<mkdir dir="${build.dir}" />
<mkdir dir="${docs.dir}" />
<mkdir dir="${dist.dir}" />
</target>
<!-- Compiles the java code (including the usage of library for JUnit -->
<target name="compile" depends="clean, makedir">
<javac srcdir="${src.dir}" destdir="${build.dir}">
</javac>
</target>
<!-- Creates Javadoc -->
<target name="docs" depends="compile">
<javadoc packagenames="src" sourcepath="${src.dir}" destdir="${docs.dir}">
<!-- Define which files / directory should get included, we include all -->
<fileset dir="${src.dir}">
<include name="**" />
</fileset>
</javadoc>
</target>
<!--Creates the deployable jar file -->
<target name="jar" depends="compile">
<jar destfile="${dist.dir}\test-project1.jar" basedir="${build.dir}">
<manifest>
<attribute name="Main-Class" value="test.Main" />
</manifest>
</jar>
</target>
<target name="main" depends="compile, jar, docs">
<description>Main target</description>
</target>
</project>
</code></pre> | 24,058,383 | 6 | 9 | null | 2014-05-03 09:31:44.83 UTC | 8 | 2015-02-27 14:26:53.647 UTC | 2014-05-03 09:43:36.89 UTC | null | 1,763,230 | null | 1,763,230 | null | 1 | 27 | java|eclipse|ant | 49,874 | <p>The version of Ant bundled with your version of Eclipse is not compatible with Java 1.8.</p>
<p>Go to the <a href="http://ant.apache.org/bindownload.cgi" rel="noreferrer">Ant download page</a>, and extract the latest version somewhere appropriate onto your filesystem.</p>
<p>In Eclipse, go to <code>Window > Preferences > Ant > Runtime</code>, click the <code>Ant Home...</code> button, and select the location that you extracted the newly downloaded Ant to.</p> |
5,356,443 | Adding elements in a set | <p>I have to create a course with some undergraduate and postgraduate students, then extract from the course all postgraduate students with “Ismael Bento” as their supervisor using the method getPostgraduates() and use the class Notifier to send them a message(print the text and recipient).
However, nothing gets printed... My guess is that there is something wrong with my getPostgraduates() method.</p>
<p>Here is the main method:</p>
<pre><code>package students;
import java.util.*;
public class ProgrammingTest {
public static void main (String[] args){
Academic rr = new Academic("Ricardo Rodriguez");
Academic ib = new Academic("Ismael Bento");
Set<Student> students = new HashSet<Student>();
Undergraduate ug1 = new Undergraduate("gg4", "Greg","gg4@", rr);
Undergraduate ug2 = new Undergraduate("pr3", "Pete","pr3@", ib);
Postgraduate pg1 = new Postgraduate("te2", "Ted", "te2@", rr);
Postgraduate pg2 = new Postgraduate("yj34", "Yao", "yj34@", ib);
Postgraduate pg3 = new Postgraduate("jj8", "Jack", "jj8@", ib);
students.add(ug1);
students.add(ug2);
students.add(pg1);
students.add(pg2);
students.add(pg3);
Course c1 = new Course("c1", students);
Set<? extends Notifiable> n = c1.getPostgraduates("Ismael Bento");
Notifier notifier = new Notifier(n);
notifier.doNotifyAll("You have been notified!");
}
}
</code></pre>
<p>and the course class:</p>
<pre><code>package students;
import java.util.*;
public class Course {
private Set<Student> students;
private String name;
public Course (String name, Set<Student> students){
this.name = name;
this.students = students;
}
public Set<Postgraduate> getPostgraduates(String nameOfSupervisor){
Set<Postgraduate> postgraduates = new HashSet<Postgraduate>();
for(Postgraduate p : postgraduates) {
if (p.getSupervisor().equals(nameOfSupervisor)){
postgraduates.add(p);
}
}
return postgraduates;
}
}
</code></pre>
<p>and the notifier class:</p>
<pre><code>package students;
import java.util.Iterator;
import java.util.Set;
public class Notifier {
Set<? extends Notifiable> notifiables;
public Notifier (Set<? extends Notifiable> n) {
notifiables = n;
}
public void doNotifyAll(String message) {
Iterator<? extends Notifiable> i = notifiables.iterator();
while(i.hasNext()){
i.next().notify();
}
}
}
</code></pre> | 5,356,572 | 3 | 6 | null | 2011-03-18 18:43:40.547 UTC | 2 | 2011-03-18 19:41:15.247 UTC | 2011-03-18 19:41:15.247 UTC | null | 640,072 | null | 640,072 | null | 1 | 4 | java|hashset | 47,217 | <p>The problem is indeed in <code>getPostgraduates()</code>. This reason for this is that you only ever compare against the object <code>postgraduate</code>, which is initialized with null-values. You should run through the whole set of students, and check for postgraduates with the supervisor you are looking for instead. </p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.