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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
46,821,027 | Set mat-menu style | <p>Im having alot of trouble with this, and the apparent solutions aren't working or im doing something wrong (probably the latter).</p>
<p>I want to style my <code>mat-menu</code> and the <code>mat-menu-item</code>'s, ive tried doing this:</p>
<pre><code>::ng-deep .mat-menu{
background-color:red;
}
</code></pre>
<p>But it doesnt work, my menu looks like this (nothing abornomal)</p>
<pre><code><mat-menu #infoMenu="matMenu">
<button mat-menu-item>
<mat-icon>dialpad</mat-icon>
<span>Resume</span>
</button>
<button mat-menu-item>
<mat-icon>voicemail</mat-icon>
<span>Portfolio</span>
</button>
<button mat-menu-item>
<mat-icon>notifications_off</mat-icon>
<span>References</span>
</button>
<button mat-menu-item>
<mat-icon>notifications_off</mat-icon>
<span>Contact</span>
</button>
</mat-menu>
</code></pre>
<p>I have also tried /deep/ but I know that shouldn't work and in fact should be depreciated in Angular 4 but I did it to test, I am not sure how to style the elements at this point.</p> | 46,821,161 | 5 | 6 | null | 2017-10-19 00:05:01.157 UTC | 2 | 2021-01-12 21:50:33.013 UTC | null | null | null | null | 1,948,659 | null | 1 | 17 | css|angular|sass|angular-material2 | 53,969 | <p><strong>app.component.ts</strong></p>
<pre><code>import { Component, ViewEncapsulation ... } from '@angular/core';
@Component({
...
encapsulation: ViewEncapsulation.None
})
export class AppComponent {
constructor() { }
}
</code></pre>
<p><strong>my.component.css</strong></p>
<pre><code>.mat-menu-content {
background-color: 'red' !important;
}
</code></pre>
<p>I typically use this to style the height and overflow css, but the general idea should still stand for background-color. Please note that there may be other overlaying divs with background-colors, but you should be able to access them in this way by their <code>.mat-menu-<item name></code> css and change children items in the same manner.</p> |
54,312,225 | Which data.table syntax for left join (one column) to prefer | <p>How should I start thinking about which syntax I prefer?</p>
<p>My criteria is efficiency (this is number one) and also readability/maintainability.</p>
<p>This</p>
<pre><code>A <- B[A, on = .(id)] # very concise!
</code></pre>
<p>Or that</p>
<pre><code>A[B, on = .(id), comment := i.comment]
</code></pre>
<p>Or even (as PoGibas suggests):</p>
<pre><code>A <- merge(A, B, all.x = TRUE)
</code></pre>
<p>For completeness then a more basic way is to use <code>match()</code>:</p>
<pre><code>A[, comment := B[chmatch(A[["id"]], id), comment]]
</code></pre>
<p>Example data:</p>
<pre><code>library(data.table)
A <- data.table(id = letters[1:10], amount = rnorm(10)^2)
B <- data.table(id = c("c", "d", "e"), comment = c("big", "slow", "nice"))
</code></pre> | 54,313,203 | 1 | 6 | null | 2019-01-22 16:10:21.407 UTC | 17 | 2021-06-15 10:34:35.497 UTC | 2021-06-15 10:34:35.497 UTC | null | 4,552,295 | null | 4,552,295 | null | 1 | 12 | r|data.table | 4,120 | <p>I prefer the "update join" idiom for efficiency and maintainability:**</p>
<pre><code>DT[WHERE, v := FROM[.SD, on=, x.v]]
</code></pre>
<p>It's an extension of what is shown in <code>vignette("datatable-reference-semantics")</code> under "Update some rows of columns by reference - <em>sub-assign</em> by reference". Once there is a vignette available on joins, that should also be a good reference.</p>
<p>This is efficient since it only uses the rows selected by <code>WHERE</code> and modifies or adds the column in-place, instead of making a new table like the more concise left join <code>FROM[DT, on=]</code>.</p>
<p>It makes my code more readable since I can easily see that the point of the join is to add column <code>v</code>; and I don't have to think through "left"/"right" jargon from SQL or whether the number of rows is preserved after the join. </p>
<p>It is useful for code maintenance since if I later want to find out how <code>DT</code> got a column named <code>v</code>, I can search my code for <code>v :=</code>, while <code>FROM[DT, on=]</code> obscures which new columns are being added. Also, it allows the <code>WHERE</code> condition, while the left join does not. This may be useful, for example, if <a href="https://stackoverflow.com/a/33981955/1191259">using <code>FROM</code> to "fill" NAs in an existing column <code>v</code></a>. </p>
<hr>
<p>Compared with the other update join approach <code>DT[FROM, on=, v := i.v]</code>, I can think of two advantages. First is the option of using the <code>WHERE</code> clause, and second is transparency through warnings when there are problems with the join, like duplicate matches in <code>FROM</code> conditional on the <code>on=</code> rules. Here's an illustration extending the OP's example:</p>
<pre><code>library(data.table)
A <- data.table(id = letters[1:10], amount = rnorm(10)^2)
B2 <- data.table(
id = c("c", "d", "e", "e"),
ord = 1:4,
comment = c("big", "slow", "nice", "nooice")
)
# left-joiny update
A[B2, on=.(id), comment := i.comment, verbose=TRUE]
# Calculated ad hoc index in 0.000s elapsed (0.000s cpu)
# Starting bmerge ...done in 0.000s elapsed (0.000s cpu)
# Detected that j uses these columns: comment,i.comment
# Assigning to 4 row subset of 10 rows
# my preferred update
A[, comment2 := B2[A, on=.(id), x.comment]]
# Warning message:
# In `[.data.table`(A, , `:=`(comment2, B2[A, on = .(id), x.comment])) :
# Supplied 11 items to be assigned to 10 items of column 'comment2' (1 unused)
id amount comment comment2
1: a 0.20000990 <NA> <NA>
2: b 1.42146573 <NA> <NA>
3: c 0.73047544 big big
4: d 0.04128676 slow slow
5: e 0.82195377 nooice nice
6: f 0.39013550 <NA> nooice
7: g 0.27019768 <NA> <NA>
8: h 0.36017876 <NA> <NA>
9: i 1.81865721 <NA> <NA>
10: j 4.86711754 <NA> <NA>
</code></pre>
<p>In the left-join-flavored update, you silently get the final value of <code>comment</code> even though there are two matches for <code>id == "e"</code>; while in the other update, you get a helpful warning message (upgraded to <a href="https://github.com/Rdatatable/data.table/pull/3310" rel="noreferrer">an error in a future release</a>). Even turning on <code>verbose=TRUE</code> with the left-joiny approach is not informative -- it says there are four rows being updated but doesn't say that one row is being updated twice.</p>
<hr>
<p>I find that this approach works best when my data is arranged into a set of tidy/relational tables. A good reference on that is <a href="https://www.jstatsoft.org/article/view/v059i10" rel="noreferrer">Hadley Wickham's paper</a>.</p>
<p>** In this idiom, the <code>on=</code> part should be filled in with the join column names and rules, like <code>on=.(id)</code> or <code>on=.(from_date >= dt_date)</code>. Further join rules can be passed with <code>roll=</code>, <code>mult=</code> and <code>nomatch=</code>. See <code>?data.table</code> for details. Thanks to @RYoda for noting this point in the comments. </p>
<p>Here is a more complicated example from Matt Dowle explaining <code>roll=</code>: <a href="https://stackoverflow.com/questions/42379658/find-time-to-nearest-occurrence-of-particular-value-for-each-row">Find time to nearest occurrence of particular value for each row</a></p>
<p>Another related example: <a href="https://stackoverflow.com/questions/34598139/left-join-using-data-table/34600831#34600831">Left join using data.table</a></p> |
20,924,554 | Import data from Excel Wizard automatically detects data types | <p>Hello I'm trying to import data from excel file <code>(xls)</code> to new <code>SQL table</code> so I use <code>Import and Export data 32/bit</code> to achieve that. When I load the excel file it automatically detects data types of columns. e.g. column with phone numbers is as data type to new table <code>float</code> and in excel is as Double(15) when I try to change the <code>float</code> to <code>nvarchar</code> </p>
<p>I get this :</p>
<blockquote>
<p>Found 2 unknown column type conversion(s)
You have selected to skip 1 potential lost column conversion(s)
You have selected to skip 3 safe column conversion(s)</p>
</blockquote>
<p>And I'm not allowed to continue with export.</p>
<p>Is there any way to change the data types when trying to import them?</p>
<p>Thank you for your time.</p>
<p>These data are set as <code>text</code> data type in excel
Sample data from one of the columns in excel:</p>
<pre><code>5859031783
5851130582
8811014190
</code></pre>
<p>This is what I get:</p>
<p><img src="https://i.stack.imgur.com/SIth5.jpg" alt="enter image description here"></p> | 20,925,192 | 2 | 10 | null | 2014-01-04 17:57:20.493 UTC | 3 | 2021-04-16 15:44:39.77 UTC | 2014-01-04 19:00:03.903 UTC | null | 2,538,352 | null | 2,538,352 | null | 1 | 12 | sql|sql-server|excel|sql-import-wizard | 44,987 | <p>Select the Column in your Excel sheet and change the data type to text </p>
<p><img src="https://i.stack.imgur.com/ZxZsU.png" alt="enter image description here"></p>
<p>Then go to your sql server open import-export wizard and do all the steps of select source data and bla bla when you get to the point of <code>Mapping Column</code>, it will select <code>Float</code> data type by default, You will have to change it to <code>NVARCHAR(N)</code> in my test I changed it to NVARCHAR(400), it gave me a warning that I might lose some data as I am converting data from 1 datatyep to another.</p>
<p><img src="https://i.stack.imgur.com/iN4Px.png" alt="enter image description here"></p>
<p>When you get to the <code>Data Type Mapping</code> page make sure you select Convert checkbox. and stop the process of failure of as appropriate.</p>
<p><img src="https://i.stack.imgur.com/71JrH.png" alt="enter image description here"></p>
<p>Going through all these steps finally got my data in the destination table with the same <code>Warning</code> that I have converted some data n bla bla after all microsoft worries too much :)</p>
<p><img src="https://i.stack.imgur.com/8uvi6.png" alt="enter image description here"></p>
<p><strong>Finally Data in Sql-Server Table</strong></p>
<pre><code>βββββββββ¦βββββββββββββ¦ββββββββββ¦βββββββββββββββββ¦βββββββββββββββ
β Name β City β Country β Phone β Float_Column β
β ββββββββ¬βββββββββββββ¬ββββββββββ¬βββββββββββββββββ¬βββββββββββββββ£
β Shaun β London β UK β 04454165161665 β 5859031783 β
β Mark β Newyork β USA β 16846814618165 β 8811014190 β
β Mike β Manchester β UK β 04468151651651 β 5851130582 β
βββββββββ©βββββββββββββ©ββββββββββ©βββββββββββββββββ©βββββββββββββββ
</code></pre> |
23,183,931 | Maven Java EE Configuration | <p>In my maven project, I have this Effective POM:</p>
<pre><code><?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>spring</groupId>
<artifactId>example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>example</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>2.1.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.0.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.3.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.3.RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>http://repo.maven.apache.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>http://repo.maven.apache.org/maven2</url>
</pluginRepository>
</pluginRepositories>
<build>
<sourceDirectory>C:\Users\Kleber\Downloads\Projetos\example\src\main\java</sourceDirectory>
<scriptSourceDirectory>C:\Users\Kleber\Downloads\Projetos\example\src\main\scripts</scriptSourceDirectory>
<testSourceDirectory>C:\Users\Kleber\Downloads\Projetos\example\src\test\java</testSourceDirectory>
<outputDirectory>C:\Users\Kleber\Downloads\Projetos\example\target\classes</outputDirectory>
<testOutputDirectory>C:\Users\Kleber\Downloads\Projetos\example\target\test-classes</testOutputDirectory>
<resources>
<resource>
<directory>C:\Users\Kleber\Downloads\Projetos\example\src\main\resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>C:\Users\Kleber\Downloads\Projetos\example\src\test\resources</directory>
</testResource>
</testResources>
<directory>C:\Users\Kleber\Downloads\Projetos\example\target</directory>
<finalName>example-0.0.1-SNAPSHOT</finalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.3</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-5</version>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<version>2.0</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>TomcatServer</server>
<path>/webappExample</path>
<username>user001</username>
<password>123</password>
</configuration>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.4.1</version>
<executions>
<execution>
<id>default-clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<id>default-install</id>
<phase>install</phase>
<goals>
<goal>install</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>default-resources</id>
<phase>process-resources</phase>
<goals>
<goal>resources</goal>
</goals>
</execution>
<execution>
<id>default-testResources</id>
<phase>process-test-resources</phase>
<goals>
<goal>testResources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>default-test</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<executions>
<execution>
<id>default-testCompile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
<execution>
<id>default-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<executions>
<execution>
<id>default-war</id>
<phase>package</phase>
<goals>
<goal>war</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.7</version>
<executions>
<execution>
<id>default-deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.0</version>
<executions>
<execution>
<id>default-site</id>
<phase>site</phase>
<goals>
<goal>site</goal>
</goals>
<configuration>
<outputDirectory>C:\Users\Kleber\Downloads\Projetos\example\target\site</outputDirectory>
<reportPlugins>
<reportPlugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</reportPlugin>
</reportPlugins>
</configuration>
</execution>
<execution>
<id>default-deploy</id>
<phase>site-deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
<configuration>
<outputDirectory>C:\Users\Kleber\Downloads\Projetos\example\target\site</outputDirectory>
<reportPlugins>
<reportPlugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</reportPlugin>
</reportPlugins>
</configuration>
</execution>
</executions>
<configuration>
<outputDirectory>C:\Users\Kleber\Downloads\Projetos\example\target\site</outputDirectory>
<reportPlugins>
<reportPlugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</reportPlugin>
</reportPlugins>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<outputDirectory>C:\Users\Kleber\Downloads\Projetos\example\target\site</outputDirectory>
</reporting>
</project>
</code></pre>
<p>In this moment, in the Markers tab on my Eclipse IDE, this error is being presented:</p>
<pre><code>Description Resource Path Location Type
Dynamic Web Module 3.0 requires Java 1.6 or newer. example line 1 Maven Java EE Configuration Problem
One or more constraints have not been satisfied. example line 1 Maven Java EE Configuration Problem
</code></pre>
<p>I try fix this configuration in the Build path from my project (In Properties/Java Build Path), but when I run Maven > Update Project, the value for this option returned to the previous one.</p>
<p>Where I should change this option to fix this error?</p> | 23,184,418 | 12 | 2 | null | 2014-04-20 15:05:50.113 UTC | 9 | 2019-08-07 06:12:39.147 UTC | null | null | null | null | 2,692,962 | null | 1 | 18 | java|eclipse|maven | 98,440 | <ol>
<li>Go to project <code>Build Path</code> and change the Java Library version to <code>1.7</code></li>
<li>Go to Eclipse Preferences -> Java -> Compiler -> Change compliance level to <code>1.7</code> <br /></li>
<li>Right click on project -> Properties -> Project Facets</li>
<li>Uncheck <code>Dynamic Web Module</code> and click <b>Apply</b> (also uncheck <code>JavaServer Faces</code> if you had that)</li>
<li>Change the <code>Java</code> facet version to <code>1.7</code> and click <b>Apply</b></li>
<li>Add the <code>Dyanmic Web Module v3.0</code>, apply. </li>
</ol>
<p>Eclipse's facets configuration is buggy. Make sure you keep hitting <code>Apply</code> between checking and unchecking of facets.</p>
<p><b>Links:</b>
<li><a href="https://stackoverflow.com/questions/18122336/cannot-change-version-of-project-facet-dynamic-web-module-to-3-0">Cannot change version of project facet Dynamic Web Module to 3.0?</a>
<li><a href="https://www.myeclipseide.com/PNphpBB2-viewtopic-t-29707.html" rel="noreferrer">Change version of project facet Dynamic Web Module to 2.5 </a></p> |
1,398,453 | Why & When should I use SPARSE COLUMN? (SQL SERVER 2008) | <p>After going thru some tutorials on SQL Server 2008's new feature "SPARSE COLUMN", I have found that it doesn't take any space if the column value is 0 or NULL but when there is a value, it takes 4 times the space a regular(non sparse) column holds.</p>
<p>If my understanding is correct, then why I will go for that at the time of database design?
And if I use that, then at what situation will I be?</p>
<p>Also out of curiosity, how does no space get reserved when a column is defined as sparse column (I mean to say, what is the internal implementation for that?)</p> | 1,401,378 | 5 | 2 | null | 2009-09-09 09:04:47.683 UTC | 13 | 2019-08-15 00:27:33.06 UTC | 2019-08-15 00:27:33.06 UTC | null | 6,368,697 | null | 111,663 | null | 1 | 70 | sql|sql-server|database-design|sql-server-2008 | 41,125 | <p>A sparse column doesn't use <strong>4x the amount of space</strong> to store a value, it uses a (fixed) <strong>4 extra bytes</strong> per non-null value. (As you've already stated, a NULL takes 0 space.)</p>
<ul>
<li><p>So a non-null value stored in a <em>bit</em> column would be 1 bit + 4 bytes = 4.125 bytes. But if 99% of these are NULL, it is still a net savings.</p></li>
<li><p>A non-null value stored in a <em>GUID (UniqueIdentifier)</em> column is 16 bytes + 4 bytes = 20 bytes. So if only 50% of these are NULL, that's still a net savings.</p></li>
</ul>
<p>So the "expected savings" depends strongly on what <em>kind</em> of column we're talking about, and your estimate of what ratio will be null vs non-null. Variable width columns (varchars) are probably a little more difficult to predict accurately.</p>
<p>This <a href="http://msdn.microsoft.com/en-us/library/cc280604.aspx" rel="noreferrer">Books Online Page</a> has a table showing <em>what percentage</em> of different data types would need to be null for you to end up with a benefit.</p>
<p>So <em>when</em> should you use a Sparse Column? When you expect a significant percentage of the rows to have a NULL value. Some examples that come to mind:</p>
<ul>
<li>A "<strong>Order Return Date</strong>" column in an order table. You would hope that a very small percent of sales would result in returned products.</li>
<li>A "<strong>4th Address</strong>" line in an Address table. Most mailing addresses, even if you need a Department name and a "Care Of" probably don't need 4 separate lines.</li>
<li>A "<strong>Suffix</strong>" column in a customer table. A fairly low percent of people have a "Jr." or "III" or "Esquire" after their name.</li>
</ul> |
2,213,109 | java.util.Timer: Is it deprecated? | <p>I read in a comment to <a href="https://stackoverflow.com/questions/2212848/how-to-genarate-random-numbers/2212887#2212887">this answer</a> and in many other questions about scheduling (sorry, no references) that <code>java.util.Timer</code> is deprecated. I really hope not since I'm using it as the light way to schedule things in Java (and it works nicely). But if it's deprecated, I'll look elsewhere. <strong>However, a quick look at the <a href="http://java.sun.com/javase/6/docs/api/" rel="nofollow noreferrer">API docs for 1.6</a> doesn't say anything about it being deprecated.</strong> It's not even mentioned in Sun's <a href="http://java.sun.com/javase/6/docs/api/deprecated-list.html" rel="nofollow noreferrer">Deprecated List</a>.</p>
<p><strong>Is it officially deprecated<sup>*</sup> and if so, what should I use instead?</strong></p>
<hr>
<p><sup>*</sup> On the other hand, <strong>if it's not deprecated,</strong> could people stop badmouthing this innocent and brilliantly-implemented set-o-classes?</p> | 38,749,177 | 6 | 4 | null | 2010-02-06 12:44:50.85 UTC | 10 | 2017-10-10 15:13:42.993 UTC | 2017-05-23 11:45:36.47 UTC | null | -1 | null | 8,047 | null | 1 | 18 | java|timer | 15,353 | <p>There is <a href="https://bugs.openjdk.java.net/browse/JDK-8154799" rel="nofollow noreferrer">[JDK-8154799] deprecate Timer and TimerTask</a> in the JDKβs bug tracker and in mid-2016 <a href="http://openjdk.java.net/jeps/277" rel="nofollow noreferrer">JEP 277</a> stated that <code>java.util.Timer</code> (and <code>TimerTask</code>) would be deprecated in JDK 9.</p>
<blockquote>
<p>Several Java SE APIs will have a @Deprecated annotation added,
updated, or removed. Some examples of such changes are listed below.</p>
<p>[β¦]</p>
<ul>
<li>add @Deprecated to <code>java.util.Timer</code> and <code>TimerTask</code></li>
</ul>
</blockquote>
<p>However, in the JDK 9 release, those classes are not deprecated (deprecated classes can be found in the <a href="http://download.java.net/java/jdk9/docs/api/deprecated-list.html#class" rel="nofollow noreferrer">Deprecated List</a>).</p> |
2,104,403 | iPhone UITableView - Delete Button | <p>I am using the 'swipe to delete' functionality of the <code>UITableView</code>.</p>
<p>The problem is I am using a customised <code>UITableViewCell</code> which is created on a per item basis in</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
</code></pre>
<p>I need to alter the position of the delete button (simply to move it around 10px to the left), how would I go about doing this?</p>
<p>Here is my existing code for creating the cell:</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"cellForRowAtIndexPath");
#if USE_CUSTOM_DRAWING
const NSInteger TOP_LABEL_TAG = 1001;
const NSInteger BOTTOM_LABEL_TAG = 1002;
UILabel *topLabel;
UILabel *bottomLabel;
#endif
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
//
// Create the cell.
//
cell =
[[[UITableViewCell alloc]
initWithFrame:CGRectZero
reuseIdentifier:CellIdentifier]
autorelease];
#if USE_CUSTOM_DRAWING
const CGFloat LABEL_HEIGHT = 20;
UIImage *image = [UIImage imageNamed:@"trans_clock.png"];
//
// Create the label for the top row of text
//
topLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT),
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:topLabel];
//
// Configure the properties for the text that are the same on every row
//
topLabel.tag = TOP_LABEL_TAG;
topLabel.backgroundColor = [UIColor clearColor];
topLabel.textColor = fontColor;
topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
//
// Create the label for the top row of text
//
bottomLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT) + LABEL_HEIGHT,
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:bottomLabel];
//
// Configure the properties for the text that are the same on every row
//
bottomLabel.tag = BOTTOM_LABEL_TAG;
bottomLabel.backgroundColor = [UIColor clearColor];
bottomLabel.textColor = fontColor;
bottomLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
bottomLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize] - 2];
//
// Create a background image view.
//
cell.backgroundView =
[[[UIImageView alloc] init] autorelease];
cell.selectedBackgroundView =
[[[UIImageView alloc] init] autorelease];
#endif
}
#if USE_CUSTOM_DRAWING
else
{
topLabel = (UILabel *)[cell viewWithTag:TOP_LABEL_TAG];
bottomLabel = (UILabel *)[cell viewWithTag:BOTTOM_LABEL_TAG];
}
topLabel.text = @"Example Text";
topLabel.textColor = fontColor;
bottomLabel.text = @"More Example Text";
bottomLabel.textColor = fontColor;
//
// Set the background and selected background images for the text.
// Since we will round the corners at the top and bottom of sections, we
// need to conditionally choose the images based on the row index and the
// number of rows in the section.
//
UIImage *rowBackground;
UIImage *selectionBackground;
NSInteger sectionRows = [aTableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];
if (row == 0 && row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:@"topAndBottomRow.png"];
selectionBackground = [UIImage imageNamed:@"topAndBottomRowSelected.png"];
}
else if (row == 0)
{
rowBackground = [UIImage imageNamed:@"topRow.png"];
selectionBackground = [UIImage imageNamed:@"topRowSelected.png"];
}
else if (row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:@"bottomRow.png"];
selectionBackground = [UIImage imageNamed:@"bottomRowSelected.png"];
}
else
{
rowBackground = [UIImage imageNamed:@"middleRow.png"];
selectionBackground = [UIImage imageNamed:@"middleRowSelected.png"];
}
((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
cell.imageView.image = [UIImage imageNamed:@"Example_Image.png"];
#else
cell.text = @"Example";
#endif
return cell;
}
</code></pre> | 2,210,761 | 6 | 0 | null | 2010-01-20 19:47:54.693 UTC | 36 | 2015-07-06 11:24:34.747 UTC | 2015-07-06 11:24:34.747 UTC | null | 4,370,109 | null | 199,510 | null | 1 | 27 | iphone|uitableview | 39,187 | <p>Iwat's code doesn't work for me. But this works.</p>
<pre>- (void)willTransitionToState:(UITableViewCellStateMask)state {
[super willTransitionToState:state];
if ((state & UITableViewCellStateShowingDeleteConfirmationMask) == UITableViewCellStateShowingDeleteConfirmationMask) {
for (UIView *subview in self.subviews) {
if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellDeleteConfirmationControl"]) {
subview.hidden = YES;
subview.alpha = 0.0;
}
}
}
}
- (void)didTransitionToState:(UITableViewCellStateMask)state {
[super didTransitionToState:state];
if (<strong>state == UITableViewCellStateShowingDeleteConfirmationMask || state == UITableViewCellStateDefaultMask</strong>) {
for (UIView *subview in self.subviews) {
if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellDeleteConfirmationControl"]) {
<strong>UIView *deleteButtonView = (UIView *)[subview.subviews objectAtIndex:0];
CGRect f = deleteButtonView.frame;
f.origin.x -= 20;
deleteButtonView.frame = f;</strong>
subview.hidden = NO;
[UIView beginAnimations:@"anim" context:nil];
subview.alpha = 1.0;
[UIView commitAnimations];
}
}
}
}</pre> |
1,363,650 | JavaScript moving element in the DOM | <p>Let's say I have three <code><div></code> elements on a page. How can I swap positions of the first and third <code><div></code>? jQuery is fine.</p> | 1,363,659 | 7 | 0 | null | 2009-09-01 17:23:41.913 UTC | 27 | 2021-07-24 22:38:52.277 UTC | 2009-09-01 18:36:53.467 UTC | null | 58,808 | null | 11,574 | null | 1 | 113 | javascript|jquery|dom | 162,389 | <p>Trivial with <a href="http://docs.jquery.com/Manipulation/insertAfter#selector" rel="noreferrer">jQuery</a></p>
<pre><code>$('#div1').insertAfter('#div3');
$('#div3').insertBefore('#div2');
</code></pre>
<p>If you want to do it repeatedly, you'll need to use different selectors since the divs will retain their ids as they are moved around.</p>
<pre><code>$(function() {
setInterval( function() {
$('div:first').insertAfter($('div').eq(2));
$('div').eq(1).insertBefore('div:first');
}, 3000 );
});
</code></pre> |
2,146,763 | Using continue in a switch statement | <p>I want to jump from the middle of a <code>switch</code> statement, to the loop statement in the following code:</p>
<pre><code>while (something = get_something())
{
switch (something)
{
case A:
case B:
break;
default:
// get another something and try again
continue;
}
// do something for a handled something
do_something();
}
</code></pre>
<p>Is this a valid way to use <code>continue</code>? Are <code>continue</code> statements ignored by <code>switch</code> statements? Do C and C++ differ on their behaviour here?</p> | 2,146,824 | 7 | 7 | null | 2010-01-27 12:24:21.247 UTC | 16 | 2019-10-08 13:38:55.863 UTC | 2011-07-10 11:33:07.527 UTC | null | 149,482 | null | 149,482 | null | 1 | 120 | c++|c|switch-statement|break|continue | 152,072 | <p>It's fine, the <code>continue</code> statement relates to the enclosing loop, and your code should be equivalent to (avoiding such jump statements):</p>
<pre><code>while (something = get_something()) {
if (something == A || something == B)
do_something();
}
</code></pre>
<p>But if you expect <code>break</code> to exit the loop, as your comment suggest (it always tries again with another something, until it evaluates to false), you'll need a different structure.</p>
<p>For example:</p>
<pre><code>do {
something = get_something();
} while (!(something == A || something == B));
do_something();
</code></pre> |
1,954,273 | fclose return value check | <p>Is it required to check the return value of fclose? If we have successfully opened a file, what are the chances that it may fail to close?</p>
<p>Thanks!</p>
<p>Regards,
Jay</p> | 1,954,305 | 11 | 3 | null | 2009-12-23 17:42:48.18 UTC | 6 | 2020-05-25 09:41:22.867 UTC | 2009-12-23 17:54:30.903 UTC | null | 21,441 | null | 236,222 | null | 1 | 32 | c|file-io | 23,266 | <p>When you <code>fwrite</code> to a file, it may not actually write anything, it may stay in a buffer (inside the FILE object). Calling <code>fflush</code> would actually write it to disk. <strong>That operation may fail</strong>, for example if you just ran out of disk space, or there is some other I/O error.</p>
<p><code>fclose</code> flushes the buffers implicitly too, so it may fail for the same reasons.</p> |
2,116,718 | SVN Error: Can't convert string from native encoding to 'UTF-8' | <p>I've got a post-commit hook script that performs a SVN update of a working copy when commits are made to the repository.</p>
<p>When users commit to the repository from their Windows machines using TortoiseSVN they get the following error:</p>
<pre><code>post-commit hook failed (exit code 1) with output:
svn: Error converting entry in directory '/home/websites/devel/website/guides/Images' to UTF-8
svn: Can't convert string from native encoding to 'UTF-8':
svn: Teneriffa-S?\195?\188d.jpg
</code></pre>
<p>The file in question above is: <code>Teneriffa-SΓΌd.jpg</code> notice the accented u. This is because the site is German and the files have been spelt in German.</p>
<p>When executing a update on the working copy at the Linux command-line no errors are encountered. The above error only exists when the post-commit hook is executed via a commit by a Windows SVN client.</p>
<p>Questions:</p>
<ol>
<li>Why would SVN try to change the encoding of a file?</li>
<li>Are filenames allowed to contain chars that are outside the Windows standard ASCII ones?</li>
</ol>
<hr>
<p>Update:</p>
<p>It turns out that the file in question's filename correctly displays as <code>Teneriffa-SΓΌd.jpg</code> when viewed from a Windows machine (via Samba) but when I view the filename from the Linux server (using SSH and PuTTY) where the file resides I get <code>Teneriffa-SΓΒΌd.jpg</code></p> | 2,116,854 | 11 | 2 | null | 2010-01-22 10:56:55.763 UTC | 12 | 2016-08-19 15:58:43.28 UTC | 2010-01-22 11:43:02.803 UTC | null | 248,848 | null | 248,848 | null | 1 | 43 | linux|svn|version-control | 67,429 | <ol>
<li>It does not change the encoding of the file. It changes the encoding of the filename (to something that every client can hopefully understand).</li>
<li>Allowed by whom ? NTFS uses 16-bit code points, and Windows can expose the file names in various encodings, based on how you ask for it (it will try to convert them to the encoding you ask for). Now... That bit (how you ask) depends on the specific svn client you use. It sounds to me like a bug in TortoiseSVN.</li>
</ol>
<p>Edit to add:</p>
<p>Ugh. I misunderstood the symptoms. the svn server stores everything in utf-8 (and it seems that it did that successfully).</p>
<p>The post-commit hook is the bit that fails to convert from UTF-8. If I understand what you're saying correctly, the post-commit hook on the server triggers an svn update to a shared drive (the svn server therefore starts an svn client to itself...) ? This means that the configuration that needs to be fixed is the one for the client <em>on the server</em>.
<strike>Check the LANG / LC_ALL on the environment executing the svn server.</strike>. As it happens, the hooks are run in a <a href="http://svnbook.red-bean.com/en/1.1/ch05s02.html#svn-ch-5-sect-2.1" rel="noreferrer">vacuum environment</a> (see Tip). So you should set the variable in the hook itself.</p>
<p>See also <a href="http://svnbook.red-bean.com/en/1.2/svn.advanced.l10n.html" rel="noreferrer">this page</a> for info on how svn handles localisation</p> |
2,051,959 | Is it better to wrap code into an 'IF' statement, or is it better to 'short circuit' the function and return? | <p>I'm doing some coding in JavaScript, and I am having a lot of instances where I have to check some stuff before I proceed. I got into the habit of returning early in the function, but I'm not sure if I am doing this right. I am not sure if it have an impact on the complexity of my code as it grows.</p>
<p>I want to know from more experienced JavaScript coders, what is a better general practice out of the following two examples. Or is it irrelevant, and they are both OK ways of writing this particular IF block?</p>
<p>1) Returning Early or "Short Circuit" as I call it (Guard Clause).</p>
<pre><code>ServeAlcohol = function(age)
{
if(age < 19)
return;
//...Code here for serving alcohol.....
}
</code></pre>
<p>..Or...</p>
<p>2) Wrap code into an IF statement.</p>
<pre><code>ServeAlcohol = function(age)
{
if(age >= 19)
{
//...Code here for serving alcohol.....
}
}
</code></pre> | 2,051,993 | 12 | 7 | null | 2010-01-12 20:05:40.22 UTC | 4 | 2012-05-15 20:38:37.077 UTC | 2010-01-15 17:32:06.083 UTC | null | 66,803 | null | 66,803 | null | 1 | 37 | javascript|coding-style | 4,096 | <p>Usually I have input-validation return right away. Imagine if you had a bunch of conditionals, you'd get a mess of nested <code>if</code>s right away.</p>
<p>Generally once I get past input validation I avoid multiple returns, but for validation I return right away. Keeps it cleaner IMHO.</p> |
8,570,470 | In browser trusted application Silverlight 5 | <p>With the new Silverlight 5, we can now have an In-Browser elevated-trust application.
However, I'm experiencing some problems to deploy the application. </p>
<p>When I am testing the application from Visual Studio, everything works fine because it automatically gives every right if the website is hosted on the local machine (localhost, 127.0.0.1).</p>
<p>I saw on MSDN that I have to follow 3 steps to make it work on any website:</p>
<ol>
<li>Signed the XAP β I did it following the Microsoft tutorial</li>
<li>Install the Trusted publishers certificate store β I did it too following the Microsoft Tutorial</li>
<li>Adding a Registry key with the value <code>AllowElevatedTrustAppsInBrowser</code>.</li>
</ol>
<p>The third step is the one I am the most unsure about. Do we need to add this registry key on the local machine or on the server? Is there any automatic function in Silverlight to add this key or is it better to make a batch file?</p>
<p>Even with those three steps, the application is still not working when called from another url than localhost.</p>
<p>Does anybody have successfully implemented an in-browser elevated-trust application? Do you see what I'm doing wrong?</p>
<p>Sources: </p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/gg192793(v=VS.96).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/gg192793(v=VS.96).aspx</a></li>
<li><a href="http://pitorque.de/MisterGoodcat/post/Silverlight-5-Tidbits-Trusted-applications.aspx" rel="noreferrer">http://pitorque.de/MisterGoodcat/post/Silverlight-5-Tidbits-Trusted-applications.aspx</a></li>
</ul> | 10,991,295 | 5 | 2 | null | 2011-12-20 03:32:30.653 UTC | 11 | 2013-09-12 08:58:52.497 UTC | 2012-09-10 09:40:30.73 UTC | null | 58,792 | null | 1,038,954 | null | 1 | 9 | silverlight|elevated-privileges | 15,878 | <p>There are lots of great resources describing this process, including the ones mentioned in responses here. I wanted to document the steps that worked for us. (Silverlight 5.1.10411.0)</p>
<p>Here are the steps that we took to enable In-Browser Trusted Applications:</p>
<ol>
<li>Sign the Xap file with code signing key.</li>
<li>Install public code signing key into "Certificates->Current User->Trusted Publishers"</li>
<li>Set the DWORD registry key AllowElevatedTrustAppsInBrowser = 1 at <pre>SL 64 bit path: HKLM\Software\Wow6432Node\Microsoft\Silverlight</pre><pre>SL 32 bit path: HKLM\Software\Microsoft\Silverlight</pre></li>
<li>Open the Silverlight project in a text editor and verify the following entries exist: <pre><code><RequireInBrowserElevation>true</RequireInBrowserElevation>
<InBrowserSettingsFile>Properties\InBrowserSettings.xml</InBrowserSettingsFile>
</code></pre></li>
<li>Check that the Properties\InBrowserSettings.xml exists and contains: <pre><code><InBrowserSettings>
<InBrowserSettings.SecuritySettings>
<SecuritySettings ElevatedPermissions="Required" />
</InBrowserSettings.SecuritySettings>
</InBrowserSettings>
</code></pre></li>
</ol>
<p>Note:</p>
<ul>
<li>If you use a self signed certificate while testing, you will also need to install it into "Certificates->Current User->Trusted Root Certification Authorities". (Buy one before you go into production)</li>
<li>Once you sign a XAP file you cannot unzip and modify it as doing so breaks the signing (it must be resigned).</li>
<li>Don't forget to clear your browser cache if you are caching the xap file.</li>
<li>This worked on Windows 7 and Windows 8 Release Preview (desktop mode) with IE, Chrome, Firefox and Safari.</li>
</ul> |
17,966,860 | PhpStorm how to refresh folder content or whole project tree | <p>This may be a dumb question, but I can not find an option to refresh folder content in project tree (PhpStorm IDE).
Is this (really basic) feature missing?</p>
<p>I know, that content is refreshed automatically, but in some types of folders, where files are generated and changed often this does not work.</p> | 17,970,001 | 5 | 1 | null | 2013-07-31 09:40:18.11 UTC | 5 | 2022-06-21 08:07:02.327 UTC | 2013-07-31 12:07:26.293 UTC | null | 238,845 | null | 647,822 | null | 1 | 80 | php|phpstorm | 38,729 | <p>right click on the folder and then synchronize 'nameOfFolder' to refresh a specific folder</p> |
17,845,809 | 'C:\Program' is not recognized error | <p>I've recently tried changing my environment variables to set paths to javac.exe (among other things). It was working fine until, all of a sudden, I started getting this error. For example, I declared a JAVA_HOME variable to be </p>
<p><code>C:\Program Files\Java\jdk1.7.0_25</code></p>
<p>After which, I add </p>
<p><code>%JAVA_HOME%\bin</code></p>
<p>to the PATH variable, but this gives me an error:</p>
<blockquote>
<p>'C:\Program' is not recognized as an internal or external command, operable command or batch file.</p>
</blockquote>
<p>This error makes it seem like it's running into problems with the space in "Program Files". This is weird, though, since it wasn't doing this for a good while, then started. Further, there are other variables with spaces in them that work just fine. I've tried deleting the variable and recreating it, putting quotes around JAVA_HOME (which goes to the correct path, but does not find javac.exe correctly)..</p>
<p>Any tips on what I might do?</p>
<p>This is on Windows 7.</p>
<p>EDIT:</p>
<p>The environment variables were set by going Control Panel > Advanced System Settings > Environment Variables. The value of the variables were set by copying the address of the folder I want through an Explorer window. I added it to the PATH environment variable by appending the address with a space between the preceding variable and a semicolon at the end, as such: </p>
<p><code>C:\Users\Demo_User_1\AppData\Roaming\npm; %JAVA_HOME%</code></p>
<p>where the JAVA_HOME variable is defined as such:</p>
<p><code>C:\Program Files\Java\jdk1.7.0_25</code></p>
<p>I test the value of the variable through a command prompt by typing %JAVA_HOME%, and that's where I get the resulting error of "'C:\Program' is not recognized..."</p>
<p>The results of 'set' are as follows:</p>
<pre><code>C:\Users\Demo_User_1>set
ALLUSERSPROFILE=C:\ProgramData
ANDROID_HOME=C:\Users\Demo_User_1\Desktop\Android\adt-bundle-windows-x86_64-2013
0717\sdk
APPDATA=C:\Users\Demo_User_1\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=DEMO_USER_1-HP
ComSpec=C:\Windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\Demo_User_1
JAVA_HOME=C:\Program Files\Java\jdk1.7.0_25
LOCALAPPDATA=C:\Users\Demo_User_1\AppData\Local
LOGONSERVER=\\DEMO_USER_1-HP
NUMBER_OF_PROCESSORS=4
OnlineServices=Online Services
OS=Windows_NT
Path=C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Clien
t\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files
(x86)\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;
C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program
Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\
x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Intel\I
ntel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Managem
ent Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engin
e Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Compone
nts\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\Wir
elessCommon\;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files
(x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C:\Program Files (x86)\Windows
Kits\8.0\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\
Tools\Binn\;C:\Program Files\nodejs\; C:\Users\Demo_User_1\Desktop\Android\adt-b
undle-windows-x86_64-20130717\sdk/platform-tools; C:\Users\Demo_User_1\Desktop\A
ndroid\adt-bundle-windows-x86_64-20130717\sdk\tools; %JAVA_HOME%; %ANT_HOME%/bin
; C:\Program Files\Java\jdk1.7.0_25\bin; C:\Users\Demo_User_1\AppData\Roaming\np
m; "%JAVA_HOME%"; ;C:\Users\Demo_User_1\Desktop\Android\adt-bundle-windows-x86_6
4-20130717\sdk/tools; C:\Users\Demo_User_1\Desktop\Android\adt-bundle-windows-x8
6_64-20130717\sdk/platform-tools
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PCBRAND=Pavilion
Platform=MCD
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=3a09
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\DEMO_U~1\AppData\Local\Temp
TMP=C:\Users\DEMO_U~1\AppData\Local\Temp
USERDOMAIN=Demo_User_1-HP
USERNAME=Demo_User_1
USERPROFILE=C:\Users\Demo_User_1
VS110COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools
\
windir=C:\Windows
windows_tracing_flags=3
windows_tracing_logfile=C:\BVTBin\Tests\installpackage\csilogfile.log
</code></pre> | 17,866,410 | 8 | 2 | null | 2013-07-24 22:20:32.753 UTC | 6 | 2021-05-26 16:58:06.57 UTC | 2016-02-19 11:30:55.75 UTC | null | 3,885,376 | null | 864,574 | null | 1 | 23 | windows|cmd|environment-variables | 97,607 | <p>Okay, that makes it clearer.</p>
<p>There are two main problems here.</p>
<p>First of all, the reason you're getting <code>'C:\Program' is not recognized...</code> is, of course, because it contains spaces. The fact that you have it quoted in the PATH environment variable has no relation to how <strong>%JAVA_HOME%</strong> is interpreted at the prompt. You have two options. </p>
<ol>
<li>Quote it when you define the variable, i.e. set <strong>JAVA_HOME</strong> to <code>"C:\Program Files\Java\jdk1.7.0_25"</code></li>
<li>Quote it when you invoke it. Type <code>"%JAVA_HOME%\bin"</code> at the prompt. Of course, you'll get the "not recognized as an internal or external command, operable program or batch file" error unless you end the path with an executable (e.g. <code>"%JAVA_HOME%\bin\javac.exe"</code>), but you'll see that this way it complains about <strong>'"C:\Program Files\Java\jdk1.7.0_25"'</strong> rather than <strong>'C:\Program'</strong>.</li>
</ol>
<p>Second, you can't use environment variables in the path. You <em>can</em> use environment variables when you set the path at the command prompt. For example,</p>
<pre><code>set PATH=%PATH%;%JAVA_HOME%
</code></pre>
<p>will work, but that's because <strong>%JAVA_HOME%</strong> is expanded at the command line and <strong>PATH</strong> is set to the result. If you check the value of <strong>PATH</strong>, you'll see that it ends with <strong>C:\Program Files\Java\jdk1.7.0_25</strong>, not <strong>%JAVA_HOME%</strong>.</p>
<p>Also, if <strong>javac.exe</strong> is in the <strong>bin</strong> subdirectory, you'll need to include that in the path, i.e. add <code>;C:\Program Files\Java\jdk1.7.0_25\bin</code> to the path.</p>
<p>(BTW, you have <strong>%JAVA_HOME%</strong> in the path twice, and there's an extra semicolon after the second one.)</p> |
18,044,073 | Iframe without src but still has content? | <p>While debugging jquery code on their site ( via chrome developer toolbar)</p>
<p>I noticed that their examples are given under <code>Iframe</code> : </p>
<p><a href="http://api.jquery.com/empty-selector/" rel="noreferrer">Here - for example</a> there is a sample which is under an Iframe but after investigating , I see that the Iframe doesn't have <code>SRC</code> </p>
<p>The picture shows it all</p>
<p><img src="https://i.stack.imgur.com/atMy8.png" alt="enter image description here"></p>
<p><strong>Question :</strong> </p>
<p>Is it possible to set content to an Iframe without setting its SRC ? </p>
<p>p.s. this menu also shows me an empty content </p>
<p><img src="https://i.stack.imgur.com/pj8ud.png" alt="enter image description here"></p> | 18,044,141 | 9 | 0 | null | 2013-08-04 14:35:32.927 UTC | 10 | 2021-11-01 14:37:44.523 UTC | 2013-08-04 14:52:22.907 UTC | null | 218,196 | null | 859,154 | null | 1 | 47 | javascript|jquery|html|dom|iframe | 73,391 | <p>Yes, it is possible to load an empty <code><iframe></code> (with no <code>src</code> specified) and later apply content to it using script.</p>
<p>See: <a href="http://api.jquery.com/jquery-wp-content/themes/jquery/js/main.js" rel="noreferrer">http://api.jquery.com/jquery-wp-content/themes/jquery/js/main.js</a> (line 54 and below).</p>
<p>Or simply try:</p>
<pre><code><iframe></iframe>
<script>
document.querySelector('iframe')
.contentDocument.write("<h1>Injected from parent frame</h1>")
</script>
</code></pre> |
6,938,291 | Dynamically inserting string into a string array in Android | <p>I receive some data as a JSON response from a server. I extract the data I need and I want to put this data into a string array. I do not know the size of the data, so I cannot declare the array as static. I declare a dynamic string array:</p>
<pre><code>String[] xCoords = {};
</code></pre>
<p>After this I insert the data in the array:</p>
<pre><code> for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
xCoords[i] = json_data.getString("xCoord");
}
</code></pre>
<p>But I receive the </p>
<pre><code>java.lang.ArrayIndexOutOfBoundsException
Caused by: java.lang.ArrayIndexOutOfBoundsException
</code></pre>
<p>What is the way to dynamically insert strings into a string array?</p> | 6,938,420 | 3 | 0 | null | 2011-08-04 08:25:39.277 UTC | 3 | 2020-02-21 04:51:14.01 UTC | 2011-08-04 08:43:09.233 UTC | null | 851,555 | null | 851,555 | null | 1 | 8 | android|dynamic|arrays | 63,372 | <p>Use ArrayList although it is not really needed but just <strong>learn it</strong>:</p>
<pre><code>ArrayList<String> stringArrayList = new ArrayList<String>();
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
stringArrayList.add(json_data.getString("xCoord")); //add to arraylist
}
//if you want your array
String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);
</code></pre> |
6,931,494 | The non-generic type 'System.Collections.IEnumerable' cannot be used with type arguments | <pre><code>using System.Collections.Generic;
public sealed class LoLQueue<T> where T: class
{
private SingleLinkNode<T> mHe;
private SingleLinkNode<T> mTa;
public LoLQueue()
{
this.mHe = new SingleLinkNode<T>();
this.mTa = this.mHe;
}
}
</code></pre>
<p>Error:</p>
<pre><code>The non-generic type 'LoLQueue<T>.SingleLinkNode' cannot be used with type arguments
</code></pre>
<p>Why do i get this?</p> | 6,931,548 | 3 | 1 | null | 2011-08-03 18:39:08.773 UTC | 1 | 2011-08-03 18:48:26.403 UTC | null | null | null | null | 717,559 | null | 1 | 12 | c#|.net|generics|queue|nodes | 42,643 | <p>I'm pretty sure you haven't defined your <code>SingleLinkNode</code> class as having a generic type parameter. As such, an attempt to declare it with one is failing.</p>
<p>The error message suggests that <code>SingleLinkNode</code> is a nested class, so I suspect what may be happening is that you are declaring members of <code>SingleLinkNode</code> of type <code>T</code>, without actually declaring <code>T</code> as a generic parameter for <code>SingleLinkNode</code>. You still need to do this if you want <code>SingleLinkNode</code> to be generic, but if not, then you can simply use the class as <code>SingleLinkNode</code> rather than <code>SingleLinkNode<T></code>.</p>
<p>Example of what I mean:</p>
<pre><code>public class Generic<T> where T : class
{
private class Node
{
public T data; // T will be of the type use to construct Generic<T>
}
private Node myNode; // No need for Node<T>
}
</code></pre>
<p>If you <em>do</em> want your nested class to be generic, then this will work:</p>
<pre><code>public class Generic<T> where T : class
{
private class Node<U>
{
public U data; // U can be anything
}
private Node<T> myNode; // U will be of type T
}
</code></pre> |
6,984,526 | Facebook Graph API - Get like count on page/group photos | <p>I've been testing graph API and ran into a problem. How can I get like count from photos of a page/group?</p>
<p>I'm administrator/creator of a group. When entering in <a href="https://developers.facebook.com/tools/explorer/" rel="noreferrer">https://developers.facebook.com/tools/explorer/</a> certain photo ID from that group it brings almost all data, even comments, but not the like count. For like part it needs (according to docs) access token despite the fact that anyone can access that info.</p>
<p>How to get access token of my page/group with required permissions and how to use it to get info I need? </p>
<p>If possible I would like to get JSON from a single address if it is possible.</p> | 7,029,900 | 4 | 2 | null | 2011-08-08 15:27:44.333 UTC | 12 | 2016-01-20 03:43:36.47 UTC | 2011-08-11 09:35:25.06 UTC | null | 558,194 | null | 558,194 | null | 1 | 13 | facebook|facebook-graph-api|count|facebook-like|photos | 47,524 | <p>This is possible with a page (even without an access token!) and here's how:</p>
<p><strong>Visit the page on the graph</strong></p>
<p>Get the page's id by going to the page's url:</p>
<p><a href="https://www.facebook.com/pages/platform/19292868552">https://www.facebook.com/pages/platform/19292868552</a></p>
<p>The number on the end of the URL is the page's id. Take that id and use it with the graph explorer (<a href="https://developers.facebook.com/tools/explorer/?method=GET&path=19292868552">here</a>) or just visit it <a href="https://graph.facebook.com/19292868552">directly</a>. </p>
<p><strong>Visit the page's albums</strong></p>
<p>Now appending albums to that url will give you all the albums the page has, including wall photos:</p>
<p><a href="https://graph.facebook.com/19292868552/albums">https://graph.facebook.com/19292868552/albums</a></p>
<p>The output looks like this:</p>
<pre><code>{
"data": [
{
"id": "10150160810478553",
"from": {
"name": "Facebook Platform",
"category": "Product/service",
"id": "19292868552"
},
"name": "Bringing Operation Developer Love to Europe",
"description": "Blog post: http://developers.facebook.com/blog/post/479\n\nVideos and presentations uploaded here: http://developers.facebook.com/videos/",
"location": "Berlin, Paris, London",
"link": "https://www.facebook.com/album.php?fbid=10150160810478553&id=19292868552&aid=285301",
"cover_photo": "10150160811078553",
"count": 32,
"type": "normal",
"created_time": "2011-04-06T23:05:44+0000",
"updated_time": "2011-04-06T23:33:20+0000",
"comments": {
..... etc ....
</code></pre>
<p><strong>Selecting an album</strong></p>
<p>For each object in the <strong>data</strong> array there is an <strong>id</strong> and a <strong>name</strong>. Using these two fields you can select the album that contains the photos you want. The first album in this result is "Bringing Operation Developer Love to Europe". Lets look at this albums photos.</p>
<p><strong>Seeing Photos</strong></p>
<p>If you've followed the answer up to this point the next step should be fairly obvious. Use the <strong>id</strong> for the album you want and append <strong>photos</strong> to the graph url:</p>
<p><a href="https://graph.facebook.com/10150160810478553/photos">https://graph.facebook.com/10150160810478553/photos</a></p>
<p><strong>Seeing a Photo's likes</strong></p>
<p>Much like selecting an album, simply use an id in the output of the above step and append <strong>likes</strong> to the url to see a photos likes:</p>
<p><a href="https://graph.facebook.com/10150160813853553/likes">https://graph.facebook.com/10150160813853553/likes</a></p>
<p>Output:</p>
<pre><code>{
"data": [
{
"id": "1163036945",
"name": "Aditya Pn"
},
{
"id": "1555885347",
"name": "Nadin M\u00f6ller"
},
{
"id": "100001643068103",
"name": "Umut Ayg\u00fcn"
},
{
"id": "100000165334510",
"name": "Alessandra Milfont"
},
{
"id": "100001472353494",
"name": "Sayer Mohammad Naz"
},
{
"id": "1051008973",
"name": "Jenson Daniel Chambi"
},
{
"id": "100000233515895",
"name": "Ruby Atiga"
},
</code></pre>
<p>Using this output you can simply count the number of entries in the data array to get the like count.</p>
<hr>
<p>Note that all of this is possible from using the <a href="https://developers.facebook.com/tools/explorer/">graph explorer</a> by clicking on ids in the output box and the connections sidebar (<strong>except</strong> for the last /likes connection, which will hopefully be added soon. I hope this helps. Also, you do not need an access token to do any of this because pages are public. Hope this helps!</p> |
19,017,401 | How to store and retrieve image to localStorage? | <p>Thought I had this, but no. The goal: snap a photo (insurance card), save it locally, and retrieve it later.</p>
<pre><code>// Get a reference to the image element
var elephant = document.getElementById("SnapIt_mobileimage_5");
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height );
console.log( 'Did that' );
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("data:image/jpg;base64,");
// Save image into localStorage
try {
localStorage.setItem("elephant", imgAsDataURL);
}
catch (e) {
console.log("Storage failed: " + e);
};
//Did it work?
var pic = localStorage.getItem("elephant");
console.log( elephant );
console.log( pic );
</code></pre>
<p>Each step succeeds, the final output is:</p>
<pre><code><img id="SnapIt_mobileimage_5" class=" SnapIt_mobileimage_5" name="mobileimage_5" dsid="mobileimage_5" src="files/views/assets/image/IMG_0590.JPG">
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA
</code></pre>
<p>On a new page, when I ask</p>
<pre><code>var policy_shot = localStorage.getItem( 'elephant' );
console.log( policy_shot );
$('#TestScreen_mobileimage_1').src = policy_shot ;
</code></pre>
<p>It logs the binary:</p>
<pre><code>data:image/png;base64,iVBORw0KGgoAAAANSUhEUg ....
</code></pre>
<p>But the image doesn't appear.</p>
<ol>
<li>Is there a simpler approach?</li>
<li>Why is the getItem (binary) preceded by data:image/png; instead of data:image/jpg ?</li>
<li>Is that why it doesn't display, or am I doing something else wrong?</li>
</ol> | 19,017,498 | 2 | 3 | null | 2013-09-26 00:31:31.49 UTC | 17 | 2016-04-18 20:20:26.48 UTC | 2016-04-18 20:20:26.48 UTC | user1693593 | null | null | 733,766 | null | 1 | 16 | javascript|cordova|jquery-mobile|canvas|html5-canvas | 27,051 | <p><strong>1)</strong> This is the only way you can convert an image into a string locally (with the excpetion of files loaded with <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader">FileReader</a>, see below). Optionally you need to use the server to do it.</p>
<p><strong>2)</strong> To get a JPEG image you need to use the argument like this:</p>
<pre><code>var datauri = imgCanvas.toDataURL("image/jpeg", 0.5); //0.5 = optional quality
</code></pre>
<p>don't use <code>data:...</code> in the argument as that will be invalid and it will produce the default PNG as you can see in your result. <code>toDataURL()</code> can only take a type, ie. <code>image/png</code>, <code>image/jpeg</code> etc.</p>
<p><strong>3)</strong></p>
<h2>External files</h2>
<p>If your image was loaded from a different origin (scheme, server ...) or by using local referenced files (<code>file://</code>, <code>/my/path/</code> etc.) CORS kicks in and will prevent you from creating a data-uri, that is: the image will be empty (and therefor invisible).</p>
<p>For external servers you can request permission to use the image from a cross-origin by supplying the <code>crossOrigin</code> property:</p>
<pre><code><img src="http://extrernalserver/...." crossOrigin="anonymous" />
</code></pre>
<p>or by code (<code>img.crossOrigin = 'anonymous';</code>) before setting the <code>src</code>.</p>
<p>It's however up to the server to allow or deny the request.</p>
<p>If it still doesn't work you will need to load your image through a proxy (f.ex. a page on your server that can load and the image externally and serve it from your own server).</p>
<p>Or if you have access to the server's configuration you can add special access allow headers (<code>Access-Control-Allow-Origin: *</code>, see link below for more details).</p>
<p>CORS (<a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing">Cross-Origin Resource Sharing</a>) is a security mechanism and can't be worked around other than these ways.</p>
<h2>Local files</h2>
<p>For local files you will need to use <code>FileReader</code> - this can turn out to be an advantage as <code>FileReader</code> comes with a handy method: <code>readAsDataURL()</code>. This allow you to "upload" the image file directly as a data-uri without going by canvas.</p>
<p>See examples here:<br>
<a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader">https://developer.mozilla.org/en-US/docs/Web/API/FileReader</a></p>
<p>Unfortunately you can't just pick the files from code - you will need to provide an input element or a drop zone so the user can pick the files (s)he want to store.</p>
<h2>Conclusion</h2>
<p>If all these steps are fulfilled to the degree that you actually do get an image the problem possibly is in the other end, the string being truncated being too long to store.</p>
<p>You can verify by checking the length before and after storing the string to see if it has been cut:</p>
<pre><code>console.log(imgAsDataURL.length);
... set / get ...
console.log(pic.length);
</code></pre>
<p>Other possibilities:</p>
<ul>
<li>The image element is not properly defined.</li>
<li>A bug in the browser</li>
<li>A bug in the framework</li>
</ul>
<p>(I think I covered most of the typical pitfalls?)</p>
<p><strong>Update</strong> (missed one, sort of.. ;-p)</p>
<p>OP found a specific in the framework which I'll include here for future reference:</p>
<blockquote>
<p>In the end, the issue was with <code>$('#TestScreen_mobileimage_1').src =
policy_shot ;</code> I'm using Appery.io and they don't support <code>.src</code>.</p>
<p>It's <code>$('#TestScreen_mobileimage_1').attr("src", policy_shot ) ;</code></p>
</blockquote>
<p>A final note: <code>localStorage</code> is very limited in regards to storing images. Typical storage space is 2.5 - 5 mb. Each char stored takes 2 bytes and storing a data-uri encoded as base-64 is 33% larger than the original - so space will be scarce. Look into Indexed DB, Web SQL or File API for good alternatives.</p> |
34,974,039 | How can I run Kotlin-Script (.kts) files from within Kotlin/Java? | <p>I noticed that IntelliJ can parse <code>.kts</code> files as Kotlin and the code editor picks them up as free-floating Kotlin files. You are also able to run the script in IntelliJ as you would a Kotlin file with a main method. The script executes from top to bottom.</p>
<p>This form is PERFECT for the project I'm working on, if only I knew an easy way to use them from within Java or Kotlin.</p>
<p>What's the idiomatic way to "run" these scripts from Java or Kotlin?</p> | 34,975,642 | 4 | 5 | null | 2016-01-24 09:18:57.417 UTC | 5 | 2022-03-06 10:31:47.483 UTC | 2016-01-24 09:48:20.993 UTC | null | 1,938,929 | null | 1,938,929 | null | 1 | 42 | java|kotlin | 28,155 | <p>Note that script files support in Kotlin is still pretty much experimental. This is an undocumented feature which we're still in the process of designing. What's working today may change, break or disappear tomorrow.</p>
<p>That said, currently there are two ways to invoke a script. You can use the command line compiler:</p>
<pre><code>kotlinc -script foo.kts <args>
</code></pre>
<p>Or you can invoke the script directly from IntelliJ IDEA, by right-clicking in the editor or in the project view on a .kts file and selecting "Run ...":</p>
<p><a href="https://i.stack.imgur.com/7NSgW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7NSgW.png" alt="Run .kts from IntelliJ IDEA"></a></p> |
51,451,819 | How to get Context in Android MVVM ViewModel | <p>I am trying to implement MVVM pattern in my android app. I have read that ViewModels should contain no android specific code (to make testing easier), however I need to use context for various things (getting resources from xml, initializing preferences, etc). What is the best way to do this? I saw that <code>AndroidViewModel</code> has a reference to the application context, however that contains android specific code so I'm not sure if that should be in the ViewModel. Also those tie into the Activity lifecycle events, but I am using dagger to manage the scope of components so I'm not sure how that would affect it. I am new to the MVVM pattern and Dagger so any help is appreciated!</p> | 51,869,474 | 18 | 4 | null | 2018-07-21 00:29:46.983 UTC | 28 | 2022-08-19 13:11:05.39 UTC | null | null | null | null | 4,061,751 | null | 1 | 159 | android|mvvm|dagger-2|android-context | 155,535 | <p>What I ended up doing instead of having a Context directly in the ViewModel, I made provider classes such as ResourceProvider that would give me the resources I need, and I had those provider classes injected into my ViewModel</p> |
51,443,557 | How to install PHP composer inside a docker container | <p>I try to work out a way to create a dev environment using docker and laravel.</p>
<p>I have the following dockerfile:</p>
<pre><code>FROM php:7.1.3-fpm
RUN apt-get update && apt-get install -y libmcrypt-dev \
mysql-client libmagickwand-dev --no-install-recommends \
&& pecl install imagick \
&& docker-php-ext-enable imagick \
&& docker-php-ext-install mcrypt pdo_mysql
&& chmod -R o+rw laravel-master/bootstrap laravel-master/storage
</code></pre>
<p>Laravel requires composer to call composer dump-autoload when working with database migration. Therefore, I need composer inside the docker container. </p>
<p>I tried:</p>
<pre><code>RUN curl -sS https://getcomposer.org/installer | php -- \
--install-dir=/usr/bin --filename=composer
</code></pre>
<p>But when I call </p>
<pre><code>docker-compose up
docker-compose exec app composer dump-autoload
</code></pre>
<p>It throws the following error:</p>
<pre><code>rpc error: code = 13 desc = invalid header field value "oci runtime error: exec failed: container_linux.go:247: starting container process caused \"exec: \\\"composer\\\": executable file not found in $PATH\"\n"
</code></pre>
<p>I would be more than happy for advice how I can add composer to the PATH within my dockerfile or what else I can do to surpass this error. </p>
<p>Thanks for your support.
Also: <a href="https://github.com/andrelandgraf/laravel-docker" rel="noreferrer">this</a> is the gitub repository if you need to see the docker-compose.yml file or anything else.</p> | 51,446,468 | 9 | 6 | null | 2018-07-20 13:24:35.93 UTC | 17 | 2022-04-17 14:25:55.09 UTC | null | null | null | null | 6,331,985 | null | 1 | 87 | php|laravel|docker|composer-php|docker-compose | 157,868 | <p><strong>I can install composer adding this line on my test dockerfile:</strong></p>
<pre><code># Install Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
</code></pre>
<p><strong>Here is the dockerfile:</strong></p>
<pre><code>FROM php:7.1.3-fpm
RUN apt-get update && apt-get install -y libmcrypt-dev \
mysql-client libmagickwand-dev --no-install-recommends \
&& pecl install imagick \
&& docker-php-ext-enable imagick \
&& docker-php-ext-install mcrypt pdo_mysql
# Install Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
</code></pre>
<p>It works for me, to test if the composer are installed i access to my container bash and execute:</p>
<pre><code>composer --version
Composer version 1.6.5 2018-05-04 11:44:59
</code></pre> |
16,491,008 | How to serialize Django models with nested objects (Django REST Framework) | <p>If I have two serializers, where one is nested, how do I setup the restore_object method? For example, if I have the following serializers defined, how do I define the restore object field for my nested serializer? It is not obvious from the documentation how to handle such a case.</p>
<pre><code>class UserSerializer(serializers.Serializer):
first_name = serializers.CharField(required=True, max_length=30)
last_name = serializers.CharField(required=True, max_length=30)
username = serializers.CharField(required=True, max_length=30)
email = serializers.EmailField(required=True)
password = serializers.CharField(required=True)
def restore_object(self, attrs, instance=None):
if instance:
instance.first_name = attrs.get('first_name', instance.first_name)
instance.last_name = attrs.get('last_name', instance.last_name)
instance.email = attrs.get('email', instance.email)
instance.password = attrs.get('password', instance.password)
class UserProfileSerializer(serializers.Serializer):
user = UserSerializer()
bio = serializers.CharField()
def restore_object(self, attrs, instance=None):
if instance:
instance.bio = attrs.get('bio', instance.bio)
instance.user = ?????
</code></pre> | 16,794,059 | 1 | 0 | null | 2013-05-10 21:22:02.767 UTC | 10 | 2013-12-11 21:09:47.307 UTC | 2013-12-11 21:09:47.307 UTC | null | 675,065 | null | 1,876,508 | null | 1 | 12 | django|serialization|django-rest-framework | 21,566 | <p><strong>Important sidenote:</strong> <em>It looks like you are using the old User/Profile methodology. Since Django 1.5 there is no seperation of the default User and your custom Profile models. You have to create your own user model and use that instead of the default one:</em> <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model">Custom User Profile @ Django Docs</a></p>
<h2>Serialization</h2>
<p>I want to present you a different approach to serialize and restore models. All <strong>model objects can be serialized</strong> by using the following snippet:</p>
<pre><code>from django.core import serializers
serialized_data = serializers.serialize("json", myInstance)
</code></pre>
<p>or to <strong>serialize more than one object</strong>:</p>
<pre><code>serialized_data = serializers.serialize("json", User.objects.all())
</code></pre>
<p>Foreign keys and m2m relations are then stored in an array of ids.</p>
<p>If you want only a <strong>subset of fields</strong> to be serialized:</p>
<pre><code>serialized_data = serializers.serialize("json", myUserInstance, fields=('first_name ','last_name ','email ','password '))
</code></pre>
<p>To save the user profile you would just write:</p>
<pre><code>serialized_data = serializers.serialize("json", myUserProfileInstance)
</code></pre>
<p>The user id is saved in the serialized data and looks like this:</p>
<pre><code>{
"pk": 1,
"model": "profile.UserProfile",
"fields": {
"bio": "self-taught couch potato",
"user": 1
}
}
</code></pre>
<p>If you want <strong>related user fields in the serialization</strong> too, you need to modify your User model:</p>
<pre><code>class UserManager(models.Manager):
def get_by_natural_key(self, first_name, last_name):
return self.get(first_name=first_name, last_name=last_name)
class User(models.Model):
objects = UserManager()
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
...
def natural_key(self):
return (self.first_name, self.last_name)
class Meta:
unique_together = (('first_name', 'last_name'),)
</code></pre>
<p>When serializing with natural keys you need to add the <code>use_natural_keys</code> argument:</p>
<pre><code>serialized_data = serializers.serialize("json", myUserProfileInstance, use_natural_keys=True)
</code></pre>
<p>Which leads to the following output:</p>
<pre><code>{
"pk": 2,
"model": "profile.UserProfile",
"fields": {
"bio": "time-traveling smartass",
"user": ["Dr.", "Who"]
}
}
</code></pre>
<h2>Deserialization</h2>
<p><strong>Deserializing and saving</strong> is just as easy as:</p>
<pre><code>for deserialized_object in serializers.deserialize("json", serialized_data):
deserialized_object.save()
</code></pre>
<p>More information can be found in the Django docs: <a href="https://docs.djangoproject.com/en/dev/topics/serialization/">Serializing Django objects</a></p> |
1,110,986 | Crash Reporter for Cocoa app | <p>I'm working on a Cocoa app targeting Leopard and above, and I'm thinking about adding a crash reporter to it (I'd like to think my app won't crash, but let's get real here). I have some mostly conceptual questions before I really get started.</p>
<p>1) How does this work conceptually, knowing when there's a crash and bringing up a reporter? Do I have a daemon running looking for a crash, or do I wait until my app is launched next time to report?</p>
<p>2) Can this be done in Cocoa? Or would I have to dip into Carbon or IOKit or somesuch?</p>
<p>3) Is this even a good idea? Mac OS X already has a built in crash reporter, but as a developer I don't get to see the crash logs. I don't think my app will be crashing often, frankly, but I just don't want to be naive but this sort of thing.</p>
<p>What are your thoughts and opinions regarding this?</p> | 1,111,203 | 7 | 1 | null | 2009-07-10 17:46:24.763 UTC | 10 | 2014-09-24 11:20:24.637 UTC | null | null | null | null | 106,658 | null | 1 | 9 | objective-c|cocoa|user-experience | 4,027 | <p>I've had a lot of success with <a href="http://zathras.de/angelweb/sourcecode.htm" rel="nofollow noreferrer">UKCrashReporter</a>. The code is straighforward and easy to modify to match the L&F of your app.</p>
<p><a href="http://code.google.com/p/plcrashreporter/" rel="nofollow noreferrer">PLCrashReporter</a> looks interesting, though.</p>
<p>I'd stay away from Smart Crash Reporter just because many users (rightfully) don't appreciate your app injecting code into unexpected places and it strikes me as a fragile (perhaps dangerous to use in a released app) approach.</p> |
1,015,340 | .class vs .java | <p>What's the difference between a .class file and a .java file? I am trying to get my applet to work but currently I can only run it in Eclipse, I can't yet embed in HTML.
Thanks</p>
<p>**Edit: How to compile with JVM then?</p> | 1,015,380 | 7 | 3 | null | 2009-06-18 21:38:19.48 UTC | 11 | 2021-04-05 07:57:33.857 UTC | null | null | null | null | 51,518 | null | 1 | 48 | java|class|applet | 73,626 | <p>A .class file is a compiled .java file. </p>
<p>.java is all text and is human readable.<br>
.class is binary (usually).</p>
<p>You compile a java file into a class file by going to the command line, navigating to the .java file, and running</p>
<pre><code>javac "c:\the\path\to\your\file\yourFileName.java"
</code></pre>
<p>You must have a java SDK installed on your computer (get it from <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" rel="noreferrer">Oracle</a>), and make sure the javac.exe file is locatable in your computer's PATH environment variable.</p>
<p>Also, check out Java's <strong><a href="http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/compile.html" rel="noreferrer">Lesson 1: Compiling & Running a Simple Program</a></strong></p>
<p>If any of this is unclear, please comment on this response and I can help out :)</p> |
1,110,523 | Slicing a vector | <p>I have a std::vector. I want to create iterators representing a slice of that vector. How do I do it? In pseudo C++:</p>
<pre><code>class InterestingType;
void doSomething(slice& s) {
for (slice::iterator i = s.begin(); i != s.end(); ++i) {
std::cout << *i << endl;
}
}
int main() {
std::vector v();
for (int i= 0; i < 10; ++i) { v.push_back(i); }
slice slice1 = slice(v, 1, 5);
slice slice2 = slice(v, 2, 4);
doSomething(slice1);
doSomething(slice2);
return 0;
}
</code></pre>
<p>I would prefer not to have to copy the elements to a new datastructure.</p> | 1,110,552 | 8 | 2 | 2009-07-10 16:16:49.423 UTC | 2009-07-10 16:16:36.35 UTC | 9 | 2020-04-14 09:53:03.097 UTC | 2017-01-20 11:09:01.32 UTC | null | 1,938,163 | No Name | null | null | 1 | 34 | c++|stl | 54,363 | <p>You'd just use a pair of iterators:</p>
<pre><code>typedef std::vector<int>::iterator vec_iter;
void doSomething(vec_iter first, vec_iter last) {
for (vec_iter cur = first; cur != last; ++cur) {
std::cout << *cur << endl;
}
}
int main() {
std::vector v();
for (int i= 0; i < 10; ++i) { v.push_back(i); }
doSomething(v.begin() + 1, v.begin() + 5);
doSomething(v.begin() + 2, v.begin() + 4);
return 0;
}
</code></pre>
<p>Alternatively, the Boost.Range library should allow you to represent iterator pairs as a single object, but the above is the canonical way to do it.</p> |
861,626 | How to resolve 'unrecognized selector sent to instance'? | <p>In the AppDelegate, I'm alloc'ing an instance defined in a static library. This instance has an NSString property set a "copy". When I access the string property on this instance, the app crashes with 'unrecognized selector sent to instance'. Xcode provides a code hint for the property, which means it is known in the calling app. The particular class is compiled into the static library target. What am I missing?</p>
<p>Adding some code.</p>
<pre><code>//static library
//ClassA.h
@interface ClassA : NSObject {
...
NSString *downloadUrl;
}
@property(nonatomic, copy) NSString *downloadUrl;
//ClassA.m
@synthesize downloadUrl;
</code></pre>
<p>In the calling app's appDelegate.</p>
<pre><code>//app delegate header file
@interface myApp : NSObject <UIApplicationDelegate> {
ClassA *classA;
}
@property (nonatomic, retain) ClassA *classA;
//app delegate .m file
@synthesize classA;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
classA = [[ClassA alloc] init];
//exception occurs here. downloadUrl is of type NSCFNumber
classA.downloadUrl = @"http://www.abc.com/";
...}
</code></pre>
<p>Other classes in the app will get a reference to the delegate and call classA.downloadUrl.</p> | 861,801 | 9 | 1 | null | 2009-05-14 04:54:47.693 UTC | 6 | 2014-03-22 08:31:28.85 UTC | 2009-06-08 02:03:01.617 UTC | null | 45,654 | null | 40,106 | null | 1 | 40 | objective-c|iphone|cocoa-touch|memory-management|static-libraries | 191,217 | <p>1) Is the synthesize within <code>@implementation</code> block?</p>
<p>2) Should you refer to <code>self.classA = [[ClassA alloc] init];</code> and <code>self.classA.downloadUrl = @"..."</code> instead of plain <code>classA</code>?</p>
<p>3) In your <code>myApp.m</code> file you need to import <code>ClassA.h</code>, when it's missing it will default to a number, or pointer? (in C variables default to int if not found by compiler):</p>
<p><code>#import "ClassA.h"</code>.</p> |
1,006,979 | Best ASP.NET reporting engine with custom reports creation ability | <p>We need to choose the reporting engine for our ASP.NET application. The main functional requirement is an ability for end users (not programmers, just normal users) to <strong>create custom reports</strong>. We will be using SQL Server as a database so I am aware of some options: SQL Server Reporting services, Crystal Reports, Active Reports, even WindwardReports.</p>
<p>But frankly speaking I've never used any of those except Reporting services and it's quite difficult to choose which one suits the best to customer needs of custom reports creation. Is it possible to get some pros and cons for these options or at least your advice on what would be better to use in this case. Thanks a lot.</p> | 1,007,147 | 9 | 2 | 2011-02-16 13:55:57.693 UTC | 2009-06-17 13:21:06.2 UTC | 15 | 2019-04-12 19:27:59.487 UTC | null | null | null | null | 121,862 | null | 1 | 40 | asp.net|reporting-services|crystal-reports|reporting | 63,943 | <p>If you have Microsoft SQL Server as Database, so you don't need to purchase License for support of SQL Reporting Services, but there is an issue with SQL Reporting Services, SQL Reporting services only Compatible with IE. check these links ... <br/>
<a href="http://msdn.microsoft.com/en-us/library/ms156511.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms156511.aspx</a></p>
<p><a href="https://stackoverflow.com/questions/951009/print-button-not-shown-in-mozilla-sql-reporting-services">SQL Reporting Services - Print Button not shown in Mozilla</a></p>
<p>On the other hand, If you use other than Reporting Services, You need to purchase License.</p> |
518,226 | How should I start learning about SAP? | <p>I'm working as a MS developer working to provide bridging products between MS technology and SAP.</p>
<p>I'm used to the MS space which seems to have an absolutely different philosophy than SAP. And this is starting to be an issue - I can't "get" SAP.</p>
<p>So, what are good materials to "grok" SAP? - understand why people buy it, how it is used from a business standpoint, how to look at the architecture from a technology standpoint, learn how it is structured, what are the important tools in SAPGUI, and <em>gasp</em> how do I learn how to read ABAP? <em>shudder</em></p>
<p>I know enough SAP to do my job - I know the runes to incant in SAP. But that isn't enough, and SAP SDN and Help is really not enough for the big picture view (it also isn't great for small picture view, but that is another discussion for somewhere else).</p>
<p>Thanks in advance.</p> | 527,770 | 9 | 1 | null | 2009-02-05 22:16:00.583 UTC | 31 | 2020-10-26 21:05:44.497 UTC | 2020-10-26 21:05:44.497 UTC | Eli | 5,846,045 | Eli | 9,169 | null | 1 | 53 | abap|hana|sap-fiori|sap-gui|sap-erp | 92,332 | <p>First, SAP is so vast you will never be able to know every part of it. There are so many functionnal subjects and technologies that this is mind-numbing.</p>
<p>Courses can be used either for a first introduction (but this is costly for such a use) or for extremely advanced subject (better).</p>
<p>SAP is a full environment. The code for most of the content is available. Thus, checking how SAP has done something can/may/will help you understand the technology or the subject.
(Btw, a lot of comments are in German...) in-system transaction se80 is particularly useful in this aspect, as it show all related data to a program.</p>
<p>Also, <a href="http://sdn.sap.com" rel="noreferrer">SDN</a> <strong>is</strong> your friend. forum, how-to, white papers are present... it will help you. A few in-system transactions (se83) are to be used as example for coding technics.</p> |
818,567 | MySQL pagination without double-querying? | <p>I was wondering if there was a way to get the number of results from a MySQL query, and at the same time limit the results.</p>
<p>The way pagination works <em>(as I understand it)</em> is to first do something like:</p>
<pre><code>query = SELECT COUNT(*) FROM `table` WHERE `some_condition`
</code></pre>
<p>After I get the <code>num_rows(query)</code>, I have the number of results. But then to actually limit my results, I have to do a second query:</p>
<pre><code>query2 = SELECT COUNT(*) FROM `table` WHERE `some_condition` LIMIT 0, 10
</code></pre>
<p>Is there any way to both retrieve the total number of results that would be given, AND limit the results returned in a single query? Or are there any other efficient ways of achieving this?</p> | 818,621 | 9 | 1 | null | 2009-05-04 02:05:14.59 UTC | 33 | 2022-08-04 15:36:56.607 UTC | 2022-08-04 15:27:02.147 UTC | null | 8,982,034 | null | 100,208 | null | 1 | 125 | mysql|pagination|double | 67,509 | <p>No, that's how many applications that want to paginate have to do it. It's reliable and bullet-proof, albeit it makes the query twice, but you can cache the count for a few seconds and that will help a lot.</p>
<p>The other way is to use <code>SQL_CALC_FOUND_ROWS</code> clause and then call <code>SELECT FOUND_ROWS()</code>. Apart from the fact you have to put the <code>FOUND_ROWS()</code> call afterwards, there is a problem with this: there is <a href="http://bugs.mysql.com/bug.php?id=18454" rel="nofollow noreferrer">a bug in MySQL</a> that this tickles which affects <code>ORDER BY</code> queries making it much slower on large tables than the naive approach of two queries.</p> |
508,269 | How do I break a string across more than one line of code in JavaScript? | <p>Is there a character in JavaScript to break up a line of code so that it is read as continuous despite being on a new line?</p>
<p>Something like....</p>
<pre>
1. alert ( "Please Select file
2. \ to delete" );
</pre> | 508,279 | 11 | 0 | null | 2009-02-03 18:16:19.32 UTC | 34 | 2020-10-05 10:08:18.593 UTC | 2010-11-11 00:13:59.66 UTC | null | 6,651 | Tommy | 52,256 | null | 1 | 244 | javascript|line-breaks | 337,395 | <p>In your example, you can break the string into two pieces:</p>
<pre><code>alert ( "Please Select file"
+ " to delete");
</code></pre>
<p>Or, when it's a string, as in your case, you can use a <a href="http://www.nczonline.net/blog/2006/12/26/interesting-javascript-string-capability/" rel="noreferrer">backslash</a> as @Gumbo suggested:</p>
<pre><code>alert ( "Please Select file\
to delete");
</code></pre>
<p>Note that this backslash approach is <a href="http://davidwalsh.name/multiline-javascript-strings#comments" rel="noreferrer">not necessarily preferred</a>, and possibly not universally supported (I had trouble finding hard data on this). It is <em>not</em> in the <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4" rel="noreferrer">ECMA 5.1 spec</a>.</p>
<p>When working with other code (not in quotes), line breaks are ignored, and perfectly acceptable. For example:</p>
<pre><code>if(SuperLongConditionWhyIsThisSoLong
&& SuperLongConditionOnAnotherLine
&& SuperLongConditionOnThirdLineSheesh)
{
// launch_missiles();
}
</code></pre> |
115,124 | What are your experiences with Windows Workflow Foundation? | <p>I am evaluating WF for use in line of business applications on the web, and I would love to hear some recent first-hand accounts of this technology.</p>
<p>My main interest here is in improving the maintainability of projects and maybe in increasing developer productivity when working on complex processes that change frequently.</p>
<p>I really like the idea of WF, however it seems to be relatively unknown and many older comments I've come across mention that it's overwhelmingly complex once you get into it. </p>
<p>If it's overdesigned to the point that it's unusable (or a bad tradeoff) for a small to medium-sized project, that's something that I need to know.</p>
<p>Of course, it has been out since late 2006, so perhaps it has matured. If that's the case, that's another piece of information that would be very helpful!</p>
<p>Thanks in advance!</p> | 115,739 | 12 | 0 | null | 2008-09-22 14:26:06.837 UTC | 14 | 2014-04-30 22:18:35.033 UTC | 2012-03-12 09:37:26.683 UTC | null | 8,049 | Brian MacKay | 16,082 | null | 1 | 34 | asp.net|.net|workflow|workflow-foundation | 5,645 | <p>Windows Workflow Foundation is a very capable product but still very much in its 1st version :-(</p>
<p>The main reasons for use include:</p>
<ol>
<li>Visually modeling business requirements.</li>
<li>Separating your business logic from the business rules and externalizing rules as XML files.</li>
<li>Seperating your business flow from you application by externalizing your workflows as XML files.</li>
<li>Creating long running processes with the automatic ability to react if nothing has happened for some extended period of time. For example an invoice not being paid.</li>
<li>Automatic persistence of long running workflows to keep resource usage down and allow a process and/or machine to restart.</li>
<li>Automatic tracking of workflows helping with business requirements.</li>
</ol>
<p>WF comes as a library/framework so most of the time you need to write the host that instantiates the WF runtime. That said, using WCF hosted in IIS is a viable solution and saves a lot of work. However the WCF/WF coupling is less than perfect and needs some serious work. See here <a href="http://msmvps.com/blogs/theproblemsolver/archive/2008/08/06/using-a-transactionscopeactivity-with-a-wcf-receiveactivity.aspx" rel="noreferrer">http://msmvps.com/blogs/theproblemsolver/archive/2008/08/06/using-a-transactionscopeactivity-with-a-wcf-receiveactivity.aspx</a> for more details. Expect quite a few changes/enhancements in the next version.</p>
<p>WF (and WCF) are pretty central to a lot of the new stuff coming out of Microsoft. You can expect some interesting announcements during the PDC.</p>
<p>BTW keeping multiple versions of a workflow running takes a bit of work but that is mostly standard .NET. I just did a series of blog posts on the subject starting here: <a href="http://msmvps.com/blogs/theproblemsolver/archive/2008/09/10/versioning-long-running-workfows.aspx" rel="noreferrer">http://msmvps.com/blogs/theproblemsolver/archive/2008/09/10/versioning-long-running-workfows.aspx</a></p>
<p>About visually modeling business requirements.
In theory this works quite well with a separation of intent and implementation. However in practice you will drop quite a few extra activities on a workflow purely for technical reasons and that sort of defeats the purpose as You have to tell a business analyst to ignore half the shapes and lines.</p> |
290,898 | Overriding functionality with modules in Linux kernel | <p>Without getting into the details of <em>why</em>, I'm looking for a clean (as possible) way to replace kernel functions and system calls from a loadable module. My initial idea was to write some code to override some functions, which would take the original function (perhaps, if possible, <em>call</em> the function), and then add some of my own code. The key is that the function that I write has to have the name of the original function, so other code, upon trying to access it, will access mine instead.</p>
<p>I can easily (comparatively) do this directly in the kernel by just throwing my code into the appropriate functions, but I was wondering if anyone knew a little C magic that isn't <em>necessarily</em> horrible kernel (or C) coding practice that could achieve the same result.</p>
<p>Thoughts of #defines and typedefs come to mind, but I can't quite hack it out in my head.</p>
<p>In short: does anyone know a way to effectively override functions in the Linux kernel (from a module)?</p>
<p>EDIT: Since it's been asked, I essentially want to log certain functions (creating/deleting directories, etc.) <em>from within the kernel</em>, but for sanity's sake, a loadable module seems to make sense, rather than having to write a big patch to the kernel code and recompile on every change. A minimal amount of added code to the kernel is okay, but I want to offload most of the work to a module.</p> | 8,083,496 | 13 | 6 | null | 2008-11-14 18:04:46.467 UTC | 9 | 2015-09-10 19:50:58.467 UTC | 2008-11-14 18:41:48.11 UTC | Dan Fego | 34,426 | Dan Fego | 34,426 | null | 1 | 21 | c|linux|module|kernel | 8,479 | <p>I realise that the question is three years old, but for the benefit of other people trying to do this sort of thing, the kernel has an interface called <a href="http://www.mjmwired.net/kernel/Documentation/kprobes.txt" rel="noreferrer" title="kprobes">kprobes</a> to do just what you needed.</p> |
482,729 | C# Iterating through an enum? (Indexing a System.Array) | <p>I have the following code:</p>
<pre><code>// Obtain the string names of all the elements within myEnum
String[] names = Enum.GetNames( typeof( myEnum ) );
// Obtain the values of all the elements within myEnum
Array values = Enum.GetValues( typeof( myEnum ) );
// Print the names and values to file
for ( int i = 0; i < names.Length; i++ )
{
print( names[i], values[i] );
}
</code></pre>
<p>However, I cannot index values. Is there an easier way to do this? </p>
<p>Or have I missed something entirely!</p> | 482,741 | 13 | 0 | null | 2009-01-27 09:11:44.687 UTC | 30 | 2018-08-01 00:06:10.843 UTC | 2009-01-27 09:13:24.87 UTC | buyutec | 31,505 | TK | 1,816 | null | 1 | 133 | c#|enums|iteration|system.array | 132,274 | <pre><code>Array values = Enum.GetValues(typeof(myEnum));
foreach( MyEnum val in values )
{
Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));
}
</code></pre>
<p>Or, you can cast the System.Array that is returned:</p>
<pre><code>string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));
for( int i = 0; i < names.Length; i++ )
{
print(names[i], values[i]);
}
</code></pre>
<p>But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?</p> |
1,132,422 | Open a folder using Process.Start | <p>I saw the <a href="//stackoverflow.com/q/334630">other topic</a> and I'm having another problem. The process is starting (saw at task manager) but the folder is not opening on my screen. What's wrong?</p>
<pre><code>System.Diagnostics.Process.Start("explorer.exe", @"c:\teste");
</code></pre> | 1,132,493 | 13 | 6 | null | 2009-07-15 16:19:36.733 UTC | 26 | 2019-07-24 22:49:46.843 UTC | 2016-12-06 19:31:01.677 UTC | null | 2,157,640 | null | 75,975 | null | 1 | 186 | c#|explorer | 274,731 | <p>Have you made sure that the folder "<code>c:\teste</code>" exists? If it doesn't, explorer will open showing some default folder (in my case "<code>C:\Users\[user name]\Documents</code>").</p>
<p><strong>Update</strong></p>
<p>I have tried the following variations:</p>
<pre><code>// opens the folder in explorer
Process.Start(@"c:\temp");
// opens the folder in explorer
Process.Start("explorer.exe", @"c:\temp");
// throws exception
Process.Start(@"c:\does_not_exist");
// opens explorer, showing some other folder)
Process.Start("explorer.exe", @"c:\does_not_exist");
</code></pre>
<p>If none of these (well, except the one that throws an exception) work on your computer, I don't think that the problem lies in the code, but in the environment. If that is the case, I would try one (or both) of the following:</p>
<ul>
<li>Open the Run dialog, enter "explorer.exe" and hit enter</li>
<li>Open a command prompt, type "explorer.exe" and hit enter</li>
</ul> |
77,826 | PHP: $_SESSION - What are the pros and cons of storing temporarily used data in the $_SESSION variable | <p>One thing I've started doing more often recently is <strong>retrieving some data</strong> at the beginning of a task <strong>and storing it in a $_SESSION['myDataForTheTask']</strong>. </p>
<p>Now it seems very convenient to do so but I don't know anything about performance, security risks or similar, using this approach. Is it something which is regularly done by programmers with more expertise or is it more of an amateur thing to do?</p>
<p><strong>For example:</strong></p>
<pre><code>if (!isset($_SESSION['dataentry']))
{
$query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=" . mysql_real_escape_string($_GET['wave_id']);
$result_taskinfo = $db->query($query_taskinfo);
$row_taskinfo = $result_taskinfo->fetch_row();
$dataentry = array("pcode" => $row_taskinfo[0], "modules" => $row_taskinfo[1], "data_id" => 0, "wavenum" => $row_taskinfo[2], "prequest" => FALSE, "highlight" => array());
$_SESSION['dataentry'] = $dataentry;
}
</code></pre> | 77,916 | 15 | 1 | 2014-11-24 13:34:56.753 UTC | 2008-09-16 22:13:48.037 UTC | 3 | 2016-01-28 13:40:06.86 UTC | 2014-11-24 09:41:20.9 UTC | Adam Wright | 11,995 | tharkun | 11,995 | null | 1 | 32 | php|session|scope | 13,024 | <p>Well Session variables are really one of the only ways (and probably the most efficient) of having these variables available for the entire time that visitor is on the website, there's no real way for a user to edit them (other than an exploit in your code, or in the PHP interpreter) so they are fairly secure.</p>
<p>It's a good way of storing settings that can be changed by the user, as you can read the settings from database once at the beginning of a session and it is available for that entire session, you only need to make further database calls if the settings are changed and of course, as you show in your code, it's trivial to find out whether the settings already exist or whether they need to be extracted from database.</p>
<p>I can't think of any other way of storing temporary variables securely (since cookies can easily be modified and this will be undesirable in most cases) so $_SESSION would be the way toΒ go</p> |
164,194 | Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"? | <p>The following code receives seg fault on line 2:</p>
<pre><code>char *str = "string";
str[0] = 'z'; // could be also written as *str = 'z'
printf("%s\n", str);
</code></pre>
<p>While this works perfectly well:</p>
<pre><code>char str[] = "string";
str[0] = 'z';
printf("%s\n", str);
</code></pre>
<p>Tested with MSVC and GCC.</p> | 164,258 | 19 | 1 | null | 2008-10-02 19:45:21.547 UTC | 156 | 2021-08-31 21:54:59.36 UTC | 2020-06-08 05:34:52.123 UTC | csl | 918,959 | Mark | 24,622 | null | 1 | 324 | c|segmentation-fault|c-strings | 93,350 | <p>See the C FAQ, <a href="http://c-faq.com/decl/strlitinit.html" rel="noreferrer">Question 1.32</a></p>
<blockquote>
<p><strong>Q</strong>: What is the difference between these initializations?<br>
<code>char a[] = "string literal";</code><br>
<code>char *p = "string literal";</code><br>
My program crashes if I try to assign a new value to <code>p[i]</code>.</p>
<p><strong>A</strong>: A string literal (the formal term
for a double-quoted string in C
source) can be used in two slightly
different ways:</p>
<ol>
<li>As the initializer for an array of char, as in the declaration of <code>char a[]</code> , it specifies the initial values
of the characters in that array (and,
if necessary, its size).</li>
<li>Anywhere else, it turns into an unnamed, static array of characters,
and this unnamed array may be stored
in read-only memory, and which
therefore cannot necessarily be
modified. In an expression context,
the array is converted at once to a
pointer, as usual (see section 6), so
the second declaration initializes p
to point to the unnamed array's first
element. </li>
</ol>
<p>Some compilers have a switch
controlling whether string literals
are writable or not (for compiling old
code), and some may have options to
cause string literals to be formally
treated as arrays of const char (for
better error catching).</p>
</blockquote> |
37,324 | What is the syntax for an inner join in LINQ to SQL? | <p>I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an <code>ON</code> clause in C#.</p>
<p>How do you represent the following in LINQ to SQL:</p>
<pre><code>select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
</code></pre> | 37,332 | 19 | 4 | null | 2008-09-01 01:00:24.467 UTC | 85 | 2019-08-09 05:45:53.72 UTC | 2017-08-21 10:31:09.05 UTC | Kevin Fairchild | 148,412 | Glenn Slaven | 2,975 | null | 1 | 475 | c#|.net|sql|linq-to-sql|join | 665,033 | <p>It goes something like:</p>
<pre><code>from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
</code></pre>
<p>It would be nice to have sensible names and fields for your tables for a better example. :)</p>
<p><strong>Update</strong></p>
<p>I think for your query this might be more appropriate:</p>
<pre><code>var dealercontacts = from contact in DealerContact
join dealer in Dealer on contact.DealerId equals dealer.ID
select contact;
</code></pre>
<p>Since you are looking for the contacts, not the dealers.</p> |
952,924 | How do I chop/slice/trim off last character in string using Javascript? | <p>I have a string, <code>12345.00</code>, and I would like it to return <code>12345.0</code>.</p>
<p>I have looked at <code>trim</code>, but it looks like it is only trimming whitespace and <code>slice</code> which I don't see how this would work. Any suggestions?</p> | 952,945 | 25 | 2 | null | 2009-06-04 20:31:53.54 UTC | 278 | 2022-01-30 01:34:37.927 UTC | 2021-10-13 15:32:33.77 UTC | null | 542,251 | null | 93,966 | null | 1 | 2,401 | javascript|slice|trim | 2,200,831 | <p>You can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring" rel="noreferrer">substring</a> function:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let str = "12345.00";
str = str.substring(0, str.length - 1);
console.log(str);</code></pre>
</div>
</div>
</p>
<p>This is the accepted answer, but as per the conversations below, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice" rel="noreferrer">slice</a> syntax is much clearer:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let str = "12345.00";
str = str.slice(0, -1);
console.log(str);</code></pre>
</div>
</div>
</p> |
6,649,327 | Regex to remove letters, symbols except numbers | <p>How can you remove letters, symbols such as <code>βΒ§ΒΆβ’ΒͺΒΊΒΊΒ«β₯β€Γ·</code> but leaving plain numbers 0-9, I want to be able to not allow letters or certain symbols in an input field but to leave numbers only.</p>
<p><a href="http://jsfiddle.net/4vuHN/">Demo</a>.</p>
<p>If you put any symbols like <code>Β‘ β¬ # Β’ β Β§ ΒΆ β’ Βͺ</code> or else, it still does not remove it from the input field. How do you remove symbols too? The <code>\w</code> modifier does not work either.</p> | 6,649,350 | 5 | 1 | null | 2011-07-11 11:20:31.277 UTC | 6 | 2015-04-08 00:54:44.473 UTC | null | null | null | null | 264,795 | null | 1 | 80 | javascript|regex|symbols | 138,862 | <p>You can use <code>\D</code> which means <em>non digits</em>.</p>
<pre><code>var removedText = self.val().replace(/\D+/g, '');
</code></pre>
<p><a href="http://jsfiddle.net/alexdickson/ZxtXb/">jsFiddle</a>.</p>
<p>You could also use the <a href="http://www.w3.org/TR/html-markup/input.number.html">HTML5 <em>number</em> input</a>.</p>
<pre><code><input type="number" name="digit" />
</code></pre>
<p><a href="http://jsfiddle.net/alexdickson/v9g5e/">jsFiddle</a>.</p> |
6,715,158 | How to set up MiniTest? | <p>I'm a fairly novice tester, but have been trying to get better at TDD in Rails.</p>
<p>RSpec works great, but my tests are pretty slow. I've heard that MiniTest is a lot faster, and the MiniTest/Spec DSL looks pretty similar to how I'm used to working with RSpec, so I thought I'd give it a try.</p>
<p>However, I have not been able to find anything on the web that provides a walkthrough of how to setup and run Minitest. I learned how to test from the RSpec book, and I have no idea how Test::Unit or MiniTest are supposed to work. I have the gem in my gemfile, I've written a few simple tests, but I have no idea where to put them or how to run them. I figure this is one of those things that's so obvious nobody has bothered to write it down...</p>
<p>Can anyone explain to me how to setup some some Minitest/spec files and get them running so I can compare the performance against Rspec?</p>
<p><strong>EDIT</strong></p>
<p>Specifically these are the basics I most need to know:</p>
<ol>
<li>Do you need a test_helper file (like spec_helper) and if so how do you create it?</li>
<li><strong>How do you run minitest?</strong> There doesn't seem to be an equivalent to <code>rspec spec</code> or <code>rspec path/to/file_spec.rb</code>, what am I missing?</li>
</ol>
<p>Thanks!</p> | 8,395,163 | 7 | 5 | null | 2011-07-16 03:40:28.317 UTC | 11 | 2018-07-09 16:17:13.243 UTC | 2013-02-02 17:50:36.133 UTC | null | 23,368 | null | 417,872 | null | 1 | 47 | ruby-on-rails|ruby-on-rails-3|rspec|installation|minitest | 12,930 | <p>This question is similar to <a href="https://stackoverflow.com/questions/4788288/how-to-run-all-the-tests-with-minitest">How to run all tests with minitest?</a></p>
<p>Using Ruby 1.9.3 and Rake 0.9.2.2, given a directory layout like this:</p>
<pre><code>Rakefile
lib/alpha.rb
spec/alpha_spec.rb
</code></pre>
<p>Here is what <code>alpha_spec.rb</code> might look like:</p>
<pre><code>require 'minitest/spec'
require 'minitest/autorun' # arranges for minitest to run (in an exit handler, so it runs last)
require 'alpha'
describe 'Alpha' do
it 'greets you by name' do
Alpha.new.greet('Alice').must_equal('hello, Alice')
end
end
</code></pre>
<p>And here's <code>Rakefile</code></p>
<pre><code>require 'rake'
require 'rake/testtask'
Rake::TestTask.new do |t|
t.pattern = 'spec/**/*_spec.rb'
end
</code></pre>
<p>You can run</p>
<ul>
<li><strong>all tests:</strong> <code>rake test</code></li>
<li><strong>one test:</strong> <code>ruby -Ilib spec/alpha_spec.rb</code></li>
</ul>
<hr>
<p>I don't know if using a <code>spec_helper.rb</code> with minitest is common or not. There does not appear to be a convenience method for loading one. Add this to the Rakefile:</p>
<pre><code>require 'rake'
require 'rake/testtask'
Rake::TestTask.new do |t|
t.pattern = 'spec/**/*_spec.rb'
t.libs.push 'spec'
end
</code></pre>
<p>Then <code>spec/spec_helper.rb</code> can contain various redundant things:</p>
<pre><code>require 'minitest/spec'
require 'minitest/autorun'
require 'alpha'
</code></pre>
<p>And <code>spec/alpha_spec.rb</code> replaces the redundant parts with:</p>
<pre><code>require 'spec_helper'
</code></pre>
<ul>
<li><strong>all tests:</strong> <code>rake test</code></li>
<li><strong>one test:</strong> <code>ruby -Ilib -Ispec spec/alpha_spec.rb</code></li>
</ul> |
6,555,455 | How to set editable true/false EditText in Android programmatically? | <p>We can set editable property of <code>EditText</code> in XML layout but not programatically, but there is no <code>setEditable()</code> method!</p>
<p>If <code>EditText</code> is not <strong>Enabled</strong> [ by <code>setEnabled(false)</code>] it still <strong>Editable</strong>!</p> | 6,555,493 | 13 | 5 | null | 2011-07-02 06:26:17.057 UTC | 6 | 2021-01-27 15:52:10.113 UTC | 2017-04-15 19:01:45.483 UTC | null | 1,033,581 | null | 703,851 | null | 1 | 37 | android|android-edittext | 116,608 | <p>I did it in a easier way , setEditable and setFocusable false. but you should check this.</p>
<p><a href="https://stackoverflow.com/questions/660151/how-to-replicate-androideditable-false-in-code">How to replicate android:editable="false" in code?</a></p> |
6,648,518 | Save images in NSUserDefaults? | <p>Is it possible to save images into <code>NSUserDefaults</code> as an object and then retrieve for further use?</p> | 21,810,380 | 13 | 0 | null | 2011-07-11 10:02:05.94 UTC | 33 | 2021-02-11 10:42:40.32 UTC | 2016-02-09 12:30:28.12 UTC | null | 3,908,884 | null | 822,758 | null | 1 | 83 | ios|objective-c|iphone|swift|ipad | 66,810 | <p><strong>ATTENTION! IF YOU'RE WORKING UNDER iOS8/XCODE6 SEE MY UPDATE BELOW</strong></p>
<p>For those who still looking for answer here is code of "advisable" way to save image in NSUserDefaults. You SHOULD NOT save image data directly into NSUserDefaults!</p>
<p><strong>Write data:</strong></p>
<pre><code>// Get image data. Here you can use UIImagePNGRepresentation if you need transparency
NSData *imageData = UIImageJPEGRepresentation(image, 1);
// Get image path in user's folder and store file with name image_CurrentTimestamp.jpg (see documentsPathForFileName below)
NSString *imagePath = [self documentsPathForFileName:[NSString stringWithFormat:@"image_%f.jpg", [NSDate timeIntervalSinceReferenceDate]]];
// Write image data to user's folder
[imageData writeToFile:imagePath atomically:YES];
// Store path in NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:imagePath forKey:kPLDefaultsAvatarUrl];
// Sync user defaults
[[NSUserDefaults standardUserDefaults] synchronize];
</code></pre>
<p><strong>Read data:</strong></p>
<pre><code>NSString *imagePath = [[NSUserDefaults standardUserDefaults] objectForKey:kPLDefaultsAvatarUrl];
if (imagePath) {
self.avatarImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]];
}
</code></pre>
<p><strong>documentsPathForFileName:</strong></p>
<pre><code>- (NSString *)documentsPathForFileName:(NSString *)name {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return [documentsPath stringByAppendingPathComponent:name];
}
</code></pre>
<p><strong>For iOS8/XCODE6</strong>
As tmr and DevC mentioned in comments below there is a problem with xcode6/ios8. The difference between xcode5 and xcode 6 installation process is that xcode6 <strong>changes apps UUID</strong> after each run in xcode (see hightlighted part in path: /var/mobile/Containers/Data/Application/<strong>B0D49CF5-8FBE-4F14-87AE-FA8C16A678B1</strong>/Documents/image.jpg).</p>
<p>So there are 2 workarounds:</p>
<ol>
<li>Skip that problem, as once app installed on real device it's never changes UUID (in fact it does, but it is new app)</li>
<li>Save relative path to required folder (in our case to app's root)</li>
</ol>
<p>Here is swift version of code as a bonus (with 2nd approach):</p>
<p><strong>Write data:</strong></p>
<pre><code>let imageData = UIImageJPEGRepresentation(image, 1)
let relativePath = "image_\(NSDate.timeIntervalSinceReferenceDate()).jpg"
let path = self.documentsPathForFileName(relativePath)
imageData.writeToFile(path, atomically: true)
NSUserDefaults.standardUserDefaults().setObject(relativePath, forKey: "path")
NSUserDefaults.standardUserDefaults().synchronize()
</code></pre>
<p><strong>Read data:</strong></p>
<pre><code>let possibleOldImagePath = NSUserDefaults.standardUserDefaults().objectForKey("path") as String?
if let oldImagePath = possibleOldImagePath {
let oldFullPath = self.documentsPathForFileName(oldImagePath)
let oldImageData = NSData(contentsOfFile: oldFullPath)
// here is your saved image:
let oldImage = UIImage(data: oldImageData)
}
</code></pre>
<p><strong>documentsPathForFileName:</strong></p>
<pre><code>func documentsPathForFileName(name: String) -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
let path = paths[0] as String;
let fullPath = path.stringByAppendingPathComponent(name)
return fullPath
}
</code></pre> |
45,661,010 | Dynamic nested reactive form: ExpressionChangedAfterItHasBeenCheckedError | <p>My reactive form is three component levels deep. The parent component creates a new form without any fields and passes it down to child components.</p>
<p>At first the outer form is valid. Later on a child component adds new form elements with validators (that fail) making the outer form invalid.</p>
<p>I am getting an <strong><em>ExpressionChangedAfterItHasBeenCheckedError</em></strong> error in the console. I want to fix that error.</p>
<p>Somehow this only happens when I add the third level of nesting. The same approach seemed to work for two levels of nesting.</p>
<p><strong>Plunker:</strong> <a href="https://plnkr.co/edit/GymI5CqSACFEvhhz55l1?p=preview" rel="noreferrer">https://plnkr.co/edit/GymI5CqSACFEvhhz55l1?p=preview</a></p>
<p><strong><em>Parent component</em></strong></p>
<pre><code>@Component({
selector: 'app-root',
template: `
myForm.valid: <b>{{myForm.valid}}</b>
<form>
<app-subform [myForm]="myForm"></app-subform>
</form>
`
})
export class AppComponent implements OnInit {
...
ngOnInit() {
this.myForm = this.formBuilder.group({});
}
}
</code></pre>
<p><strong><em>Sub component</em></strong></p>
<pre><code>@Component({
selector: 'app-subform',
template: `
<app-address-form *ngFor="let addressData of addressesData;"
[addressesForm]="addressesForm">
</app-address-form>
`
})
export class SubformComponent implements OnInit {
...
addressesData = [...];
constructor() { }
ngOnInit() {
this.addressesForm = new FormArray([]);
this.myForm.addControl('addresses', this.addressesForm);
}
</code></pre>
<p><strong><em>Child component</em></strong></p>
<pre><code>@Component({
selector: 'app-address-form',
template: `
<input [formControl]="addressForm.controls.addressLine1">
<input [formControl]="addressForm.controls.city">
`
})
export class AddressFormComponent implements OnInit {
...
ngOnInit() {
this.addressForm = this.formBuilder.group({
addressLine1: [
this.addressData.addressLine1,
[ Validators.required ]
],
city: [
this.addressData.city
]
});
this.addressesForm.push(this.addressForm);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/iHm3f.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iHm3f.png" alt="enter image description here"></a></p> | 45,661,311 | 4 | 4 | null | 2017-08-13 13:44:29.733 UTC | 11 | 2022-06-24 23:46:00.673 UTC | 2017-08-13 13:54:09.127 UTC | null | 2,257,851 | null | 2,257,851 | null | 1 | 27 | javascript|forms|angular | 11,648 | <p>To understand the problem you need to read <a href="https://indepth.dev/posts/1001/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error" rel="nofollow noreferrer">Everything you need to know about the <code>ExpressionChangedAfterItHasBeenCheckedError</code> error</a> article.</p>
<p>For your particular case the problem is that you're creating a form in the <code>AppComponent</code> and use a <code>{{myForm.valid}}</code> interpolation in the DOM. It means that Angular <a href="https://indepth.dev/posts/1129/the-mechanics-of-dom-updates-in-angular" rel="nofollow noreferrer">will run create and run updateRenderer function</a> for the <code>AppComponent</code> that updates DOM. Then you use the <code>ngOnInit</code> lifecycle hook of subcomponent to add subgroup with control to this form:</p>
<pre><code>export class AddressFormComponent implements OnInit {
@Input() addressesForm;
@Input() addressData;
ngOnInit() {
this.addressForm = this.formBuilder.group({
addressLine1: [
this.addressData.addressLine1,
[ Validators.required ] <-----------
]
this.addressesForm.push(this.addressForm); <--------
</code></pre>
<p>The control becomes invalid because you don't supply initial value and you specify a required validator. Hence the entire form becomes invalid and the expression <code>{{myForm.valid}}</code> evaluates to <code>false</code>. But when Angular ran change detection for the <code>AppComponent</code> it evaluated to <code>true</code>. And that's what the error says.</p>
<p>One possible fix could be to mark the form as invalid in the start since you're planning to add required validator, but it seems Angular doesn't provide such method. Your best choice is probably to add controls asynchronously. In fact, this is what Angular does itself in the sources:</p>
<pre><code>const resolvedPromise = Promise.resolve(null);
export class NgForm extends ControlContainer implements Form {
...
addControl(dir: NgModel): void {
// adds controls asynchronously using Promise
resolvedPromise.then(() => {
const container = this._findContainer(dir.path);
dir._control = <FormControl>container.registerControl(dir.name, dir.control);
setUpControl(dir.control, dir);
dir.control.updateValueAndValidity({emitEvent: false});
});
}
</code></pre>
<p>So for you case it will be:</p>
<pre><code>const resolvedPromise = Promise.resolve(null);
@Component({
...
export class AddressFormComponent implements OnInit {
@Input() addressesForm;
@Input() addressData;
addressForm;
ngOnInit() {
this.addressForm = this.formBuilder.group({
addressLine1: [
this.addressData.addressLine1,
[ Validators.required ]
],
city: [
this.addressData.city
]
});
resolvedPromise.then(() => {
this.addressesForm.push(this.addressForm); <-------
})
}
}
</code></pre>
<p>Or use some variable in the <code>AppComponent</code> to hold form state and use it in the template:</p>
<pre><code>{{formIsValid}}
export class AppComponent implements OnInit {
myForm: FormGroup;
formIsValid = false;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.myForm = this.formBuilder.group({});
this.myForm.statusChanges((status)=>{
formIsValid = status;
})
}
}
</code></pre> |
15,596,834 | Could not load file or assembly 'Oracle.DataAccess' or one of its dependencies. An attempt was made to load a program with an incorrect format | <p>I have installed a Web app on IIS 7.0 Windows Server 2008 R2 64bit.
I am referring an oracle.DataAccess.dll;
When I try to access the application I get the following message:
"Could not load file or assembly 'Oracle.DataAccess' or one of its dependencies. An attempt was made to load a program with an incorrect format."
Can anybody help me, please?</p> | 15,596,861 | 10 | 0 | null | 2013-03-24 09:20:44.967 UTC | 11 | 2020-11-19 17:27:53.593 UTC | 2015-07-22 10:41:40.99 UTC | null | 1,650,038 | null | 2,204,178 | null | 1 | 15 | asp.net|oracle|iis-7|windows-server-2008|gac | 84,475 | <p>It seems the Oracle Data Access Component installation process using the "11.2 Release 3 (11.2.0.2.1) with Xcopy Deployment" version is broken. To fix this you must register the missing assemblies in the GAC. To do this for this specific version run these commands from within an administrator console:</p>
<pre><code>md C:\Windows\assembly\GAC_32\Oracle.DataAccess\4.112.2.0__89b483f429c47342\
copy %ORACLE_HOME%\odp.net\bin\4\Oracle.DataAccess.dll C:\Windows\assembly\GAC_32\Oracle.DataAccess\4.112.2.0__89b483f429c47342\
md C:\Windows\assembly\GAC_32\Oracle.Web\4.112.2.0__89b483f429c47342\
copy %ORACLE_HOME%\asp.net\bin\4\oracle.web.dll C:\Windows\assembly\GAC_32\Oracle.Web\4.112.2.0__89b483f429c47342\
</code></pre>
<p>Note that this registers only the DLL's but not other languages resources. So, if you are using any another language than English (de, es, fr, it, ja, ko, pt-BR, zh-CHS, and zh-CHT), then you need to register these as well using the corresponding resource file.</p>
<p>If you have Visual Studio installed on the machine, you can issue the following commands instead:</p>
<pre><code>gacutil /i %ORACLE_HOME%\odp.net\bin\4\Oracle.DataAccess.dll
gacutil /i %ORACLE_HOME%\asp.net\bin\4\oracle.web.dll
</code></pre>
<p>Note: look for gacutil.exe under the Visual Studio installation folder for it.</p>
<p>Hope this helps.</p>
<p>P.S. Or you can try <a href="http://rambletech.wordpress.com/2011/09/26/could-not-load-file-or-assembly-oracle-dataaccess-error/">this</a>.</p> |
15,985,837 | Can I make Google Drive Spreadsheets act like a MySQL database? | <p>Can I use a Google Drive spreadsheet as if it were (similar to) a MySQL database? </p>
<p>I'm thinking of using it as a player database for an HTML/JavaScript web game. The player's username, password, and score among other things would be saved in the database. It would be really interesting if it could actually work, however it of course has to be secure and private so that no player (or anyone on the internet for that matter) can access it except the owner of the spreadsheet which would be me for example.</p>
<p>I know that Google Apps Script allows a user to access their own spreadsheet and read/write to it, but is there a way that I could allow other users to "save their score" to MY spreadsheet WITHOUT giving them permission to view/edit the spreadsheet directly?</p>
<p>Also, i'm assuming PHP/Python/some other server-side language would have to be used in order to hide my account info which I also assume would be needed to open and close the connection with my spreadsheet.</p>
<p>Anyways, I'm just wondering if this is feasible.. literally turning a Google Drive spreadsheet into a database that players can update their score to but not have direct access to it.</p>
<p>This may be a stupid idea, so your opinions are welcome!</p>
<p>Thanks in advance!</p> | 15,988,776 | 3 | 8 | null | 2013-04-13 08:29:01.97 UTC | 10 | 2016-05-19 17:02:40.887 UTC | null | null | null | null | 798,681 | null | 1 | 20 | javascript|mysql|database|google-apps-script|google-drive-api | 33,756 | <p>Answers saying you need an extra server or oauth are incorrect.
Just publish an appscript (anonymous public) service using your permissions. For all operations always pass the username and password thus you validate users on every call. Call the service from client js using ajax.
Store it in scriptdb [update: scriptDb is deprecated now]. If you use spreadsheet for storage it will get slow with many rows.</p>
<p>In any case it will be slow if you use appscript.</p> |
15,503,782 | Architecture for async/await | <p>
If you are using async/await at a lower level in your architecture, is it necessary to "bubble up" the async/await calls all the way up, is it inefficient since you are basically creating a new thread for each layer (asynchronously calling an asynchronous function for each layer, or does it not really matter and is just dependent on your preference?</p>
<p>I'm using EF 6.0-alpha3 so that I can have async methods in EF.</p>
<p>My repository is such:</p>
<pre class="lang-cs prettyprint-override"><code>public class EntityRepository<E> : IRepository<E> where E : class
{
public async virtual Task Save()
{
await context.SaveChangesAsync();
}
}
</code></pre>
<p>Now my business layer is as such:</p>
<pre class="lang-cs prettyprint-override"><code>public abstract class ApplicationBCBase<E> : IEntityBC<E>
{
public async virtual Task Save()
{
await repository.Save();
}
}
</code></pre>
<p>And then of course my method in my UI would have the follow the same pattern when calling.</p>
<p>Is this: </p>
<ol>
<li>necessary</li>
<li>negative on performance</li>
<li>just a matter of preference </li>
</ol>
<p>Even if this isn't used in separate layers/projects the same questions applies to if I am calling nested methods in the same class:</p>
<pre class="lang-cs prettyprint-override"><code> private async Task<string> Dosomething1()
{
//other stuff
...
return await Dosomething2();
}
private async Task<string> Dosomething2()
{
//other stuff
...
return await Dosomething3();
}
private async Task<string> Dosomething3()
{
//other stuff
...
return await Task.Run(() => "");
}
</code></pre> | 15,503,860 | 2 | 0 | null | 2013-03-19 15:33:53.6 UTC | 32 | 2013-03-19 16:02:04.627 UTC | null | null | null | null | 1,134,836 | null | 1 | 59 | c#|.net|asynchronous|async-await|c#-5.0 | 9,269 | <blockquote>
<p>If you are using async/await at a lower level in your architecture, is it necessary to "bubble up" the async/await calls all the way up, is it inefficient since you are basically creating a new thread for each layer (asynchronously calling an asynchronous function for each layer, or does it not really matter and is just dependent on your preference?</p>
</blockquote>
<p>This question suggests a couple of areas of misunderstanding.</p>
<p>Firstly, you <em>don't</em> create a new thread each time you call an asynchronous function.</p>
<p>Secondly, you don't need to declare an async method, just because you're calling an asynchronous function. If you're happy with the task that's already being returned, just return that from a method which <em>doesn't</em> have the async modifier:</p>
<pre><code>public class EntityRepository<E> : IRepository<E> where E : class
{
public virtual Task Save()
{
return context.SaveChangesAsync();
}
}
public abstract class ApplicationBCBase<E> : IEntityBC<E>
{
public virtual Task Save()
{
return repository.Save();
}
}
</code></pre>
<p>This <em>will</em> be slightly more efficient, as it doesn't involve a state machine being created for very little reason - but more importantly, it's simpler.</p>
<p>Any async method where you have a single <code>await</code> expression awaiting a <code>Task</code> or <code>Task<T></code>, right at the end of the method with no further processing, would be better off being written without using async/await. So this:</p>
<pre><code>public async Task<string> Foo()
{
var bar = new Bar();
bar.Baz();
return await bar.Quux();
}
</code></pre>
<p>is better written as:</p>
<pre><code>public Task<string> Foo()
{
var bar = new Bar();
bar.Baz();
return bar.Quux();
}
</code></pre>
<p>(In theory there's a very slight difference in the tasks being created and therefore what callers could add continuations to, but in the vast majority of cases, you won't notice any difference.)</p> |
15,640,596 | ASP WebAPI generic List optional parameter | <p>I'm really struggling with this one. I need a generic list parameter for my Get method, but it needs to be optional. I just did this:</p>
<pre><code>public dynamic Get(List <long> ManufacturerIDs = null)
</code></pre>
<p>Unfortunately on runtime i get the error:</p>
<blockquote>
<p>Optional parameter 'ManufacturerIDs' is not supported by
'FormatterParameterBinding'.</p>
</blockquote>
<p>How to get a generic list as an optional parameter here?</p> | 15,641,033 | 1 | 0 | null | 2013-03-26 15:12:17.33 UTC | 3 | 2022-06-24 03:20:14.753 UTC | 2013-07-01 23:17:40.26 UTC | null | 1,259,510 | null | 1,902,503 | null | 1 | 62 | asp.net-mvc|asp.net-web-api | 24,519 | <p>What's the point of using an optional parameter? <code>List<T></code> is a reference type and if the client doesn't supply a value it will simply be null:</p>
<pre><code>public HttpResponseMessage Get(List<long> manufacturerIDs)
{
...
}
</code></pre> |
16,011,245 | Source files in a bash script | <p>I am using two versions of ROS next to each other. To use one I have to source some environment variables for the specific version. I would like to create a script that does this.
But if I create a script like below the variables are not set, they are probably set in a subshell. How can I source the files to the main terminal shell?</p>
<p>source.sh:</p>
<pre><code>source /opt/ros/fuerte/setup.bash;
source ~/fuerte_workspace/setup.bash;
</code></pre>
<p>Here is how i am calling source.sh:</p>
<pre><code>./source.sh
# This does not echo anything, but I expect it should
echo $ros_config
</code></pre>
<hr>
<p>Update: By sourcing source.sh as suggested in the answer, I can now see the variables being set.</p>
<pre><code>source ./source.sh
# This works now
echo $ros_config
</code></pre> | 16,011,496 | 2 | 1 | null | 2013-04-15 08:57:42.543 UTC | 21 | 2017-03-14 01:53:27.31 UTC | 2016-09-30 02:58:02.917 UTC | null | 99,777 | null | 408,041 | null | 1 | 81 | bash|shell|ubuntu | 121,752 | <p><strong>Execute Shell Script Using . ./ (dot space dot slash)</strong></p>
<p>While executing the shell script using <code>βdot space dot slashβ</code>, as shown below, it will execute the script in the current shell without forking a sub shell.</p>
<pre><code>$ . ./setup.bash
</code></pre>
<p>In other words, this executes the commands specified in the <code>setup.bash</code> in the current shell, and prepares the environment for you.</p> |
10,787,342 | Why does JQuery have dollar signs everywhere? | <p>I am working on a project with quite a lot of JQuery in it. The JQuery has a lot of $ signs everywhere, for example</p>
<pre><code>$(document).ready(function () {
$('input[type=file]').wl_File({
url: '/Admin/PolicyInventory/UploadDocuments',
onFileError: function (error, fileobj) {
$.msg('file is not allowed: ' + fileobj.name, {
header: error.msg + ' Error ',
live: 10000
});
}
});
...
</code></pre>
<p>My question is, what does this dollar sign mean? Why is it used all over the place and how do I understand and interpret it? It reminds me of the scary days of when I was learning Scheme at University and had to put brackets everywhere without knowing why I was doing it.</p> | 10,787,372 | 7 | 5 | null | 2012-05-28 15:53:36.443 UTC | 31 | 2020-08-11 14:00:01.943 UTC | null | null | null | null | 991,788 | null | 1 | 125 | jquery | 90,680 | <p><code>$</code> is just a shortcut for <a href="http://api.jquery.com/jQuery/"><code>jQuery</code></a>. The idea is that <strong>everything</strong> is done with the one global symbol (since the global namespaces is ridiculously crowded), <code>jQuery</code>, but you can use <code>$</code> (because it's shorter) if you like:</p>
<pre><code>// These are the same barring your using noConflict (more below)
var divs = $("div"); // Find all divs
var divs = jQuery("div"); // Also find all divs, because
console.log($ === jQuery); // "true"
</code></pre>
<p>If you don't want to use the alias, you don't have to. And if you want <code>$</code> to not be an alias for <code>jQuery</code>, you can use <a href="http://api.jquery.com/jQuery.noConflict/"><code>noConflict</code></a> and the library will restore <code>$</code> to whatever it was before jQuery took it over. (Useful if you also use Prototype or MooTools.)</p> |
25,424,382 | Replace single backslash in R | <p>I have a string that looks like:</p>
<pre><code>str<-"a\f\r"
</code></pre>
<p>I'm trying to remove the backslashes but nothing works:</p>
<pre><code>gsub("\","",str, fixed=TRUE)
gsub("\\","",str)
gsub("(\)","",str)
gsub("([\])","",str)
</code></pre>
<p>...basically all the variations you can imagine. I have even tried the <code>string_replace_all</code> function. ANY HELP??</p>
<p>I'm using R version 3.1.1; Mac OSX 10.7; the <code>dput</code> for a single string in my vector of strings gives:</p>
<pre><code>dput(line)
"ud83d\ude21\ud83d\udd2b"
</code></pre>
<p>I imported the file using
<code>readLines</code> from a standard
<code>.txt</code> file. The content of the file looks something like:
<code>
got an engineer booked for this afternoon \ud83d\udc4d all now hopefully sorted\ud83d\ude0a I m going to go insane ud83d\ude21\ud83d\udd2b in utf8towcs β¦
</code></p>
<p>Thanks.</p> | 25,433,494 | 5 | 31 | null | 2014-08-21 10:47:34.617 UTC | 7 | 2022-01-25 20:35:30.6 UTC | 2019-04-18 08:33:26.537 UTC | user4417050 | 680,068 | null | 3,943,453 | null | 1 | 44 | regex|r|string|replace | 52,330 | <p>Since there isn't any direct ways to dealing with single backslashes, here's the closest solution to the problem as provided by David Arenburg in the comments section</p>
<pre><code>gsub("[^A-Za-z0-9]", "", str) #remove all besides the alphabets & numbers
</code></pre> |
13,262,287 | How does hibernate save one-to-many / many-to-one annotations? (Children not saving) | <p>I've inherited a hibernate application and I've run into issues. It seems that the code does not save the child in a One-To-Many relationship. It's bidirectional, but on save of parent object, it doesn't seem to save the child. </p>
<p>The Question class is the parent in this case.</p>
<pre><code>// Question.java
@Entity
@SequenceGenerator(name = "question_sequence", sequenceName = "seq_question", allocationSize = 1000)
@Table(name = "question")
public class Question {
protected Long questionId;
protected Set<AnswerValue> answerValues;
public TurkQuestion(){}
public TurkQuestion(Long questionId){
this.questionId = questionId;
}
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "question_sequence")
@Column(name = "question_id")
public Long getQuestionId(){
return questionId;
}
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "question_id",referencedColumnName="question_id")
public Set<AnswerValue> getAnswerValues(){
return answerValues;
}
public void setQuestionId(Long questionId){
this.questionId = questionId;
}
public void setAnswerValues(Set<AnswerValue> answerValues){
this.answerValues = answerValues;
}
}
</code></pre>
<p>AnswerValue is the child class.</p>
<pre><code>// AnswerValue.java
@Entity
@SequenceGenerator(name = "answer_value_sequence", sequenceName = "seq_answer_value", allocationSize = 1)
@Table(name = "answer_value")
public class AnswerValue {
protected Long answerValueId;
protected Question question;
protected String answerValue;
public AnswerValue(){}
public AnswerValue(Long answerValueId, Long questionId, String answerValue){
this.answerValueId = answerValueId;
this.question = new Question(questionId);
this.answerValue = answerValue;
}
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "answer_value_sequence")
@Column(name = "answer_value_id")
public Long getAnswerValueId(){
return answerValueId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "question_id", nullable = false )
public Question getQuestion(){
return question;
}
@Column(name = "answer_value")
public String getAnswerValue(){
return answerValue;
}
public void setAnswerValueId(Long answerValueId){
this.answerValueId = answerValueId;
}
public void setQuestion(Question question){
this.question = question;
}
public void setAnswerValue(){
this.answerValue = answerValue;
}
}
</code></pre>
<p>And the DAO:</p>
<pre><code>// QuestionDao.java
public class QuestionDao {
public void saveOrUpdateAll(List<Question> list){
getHibernateTemplate().saveOrUpdateAll(list);
}
}
</code></pre>
<p>It seems when I call saveOrUpdateAll, Question is saved, but the AnswerValue that are children of the Question object are not.</p>
<p>Any suggestions?</p> | 13,262,297 | 3 | 0 | null | 2012-11-07 02:11:09.597 UTC | 5 | 2017-03-03 08:21:50.64 UTC | 2016-04-01 21:15:22.66 UTC | null | 1,065,197 | user1732480 | null | null | 1 | 19 | java|hibernate|annotations|one-to-many|many-to-one | 56,017 | <p>you need to do it manually or add the cascade property to your annotation, i.e. <a href="https://stackoverflow.com/questions/10551485/hibernate-cascade-type">Hibernate: Cascade Type</a></p>
<p>or <a href="https://stackoverflow.com/questions/5157853/hibernate-how-use-cascade-in-annotation">Hibernate: How use cascade in annotation?</a></p> |
13,690,162 | Rails + Postgres fe_sendauth: no password supplied | <p>Hi I'm trying to hook up postgresql to my rails project. I'm learning testing but my tests aren't running because of a postgresql error about having an incorrect password:</p>
<pre><code>Edmunds-MacBook-Pro:langexchange edmundmai$ rake test:units
rake aborted!
fe_sendauth: no password supplied
</code></pre>
<p>I've already read around and my pg_hba.conf file was originally already like this:</p>
<pre><code># TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local replication edmundmai
</code></pre>
<p>here's my database.yml file in my rails project</p>
<pre><code>default: &default
adapter: postgresql
encoding: utf8
pool: 5
username: edmundmai
password:
development:
<<: *default
database: project_development
test:
<<: *default
database: project_test
production:
<<: *default
database: project_production
</code></pre>
<p>Does anyone know how I could fix this? We can chat if it's easier.</p> | 13,690,394 | 4 | 0 | null | 2012-12-03 19:21:12 UTC | 10 | 2014-11-29 23:42:23.957 UTC | null | null | null | null | 1,555,312 | null | 1 | 29 | ruby-on-rails|postgresql | 58,878 | <p>First you should change:</p>
<pre><code>local all all trust
</code></pre>
<p>to:</p>
<pre><code>local all all md5
</code></pre>
<p>Then, You should create a <strong>super_user</strong> in PostgreSQL with <code>username</code> and <code>password</code>,after that adding <code>username</code> and <code>password</code> of new user to your <code>database.yml</code> file.</p>
<p>To create new <code>super_user</code>, open <code>Pg Admin III</code> and right click at the bottom <code>Login Roles</code> to create new super user. </p> |
13,552,575 | GNU Make pattern to build output in different directory than src | <p>I'm trying to create a Makefile which places my <code>.o</code> files in a different directory than my source files. I'm trying to use a pattern rule so I don't have to create identical rules for each source & object file.</p>
<p>My project structure looks something like:</p>
<pre><code>project/
+ Makefile
+ src/
+ main.cpp
+ video.cpp
+ Debug/
+ src/ [contents built via Makefile:]
+ main.o
+ video.o
</code></pre>
<p>My Makefile looks something like:</p>
<pre><code>OBJDIR_DEBUG = Debug
OBJ_DEBUG = $(OBJDIR_DEBUG)/src/main.o $(OBJDIR_DEBUG)/src/video.o
all: $(OBJ_DEBUG)
$(OBJ_DEBUG): %.o: %.cpp
$(CXX) $(CFLAGS_DEBUG) $(INC_DEBUG) -c $< -o $@
</code></pre>
<p>This doesn't work, because it looks for my source files at <code>Debug/src/*.cpp</code>.</p>
<p>I've tried the following:</p>
<pre><code># Broken: make: *** No rule to make target `Debug/src/main.cpp', needed by `Debug/src/main.o'. Stop.
# As a test, works if I change "%.cpp" to "Debug/src/main.cpp", though it obv. builds the wrong thing
# Strip OBJDIR_DEBUG from the start of source files
$(OBJ_DEBUG): %.o: $(patsubst $(OBJDIR_DEBUG)/%,%,%.cpp)
$(CXX) $(CFLAGS_DEBUG) $(INC_DEBUG) -c $< -o $@
</code></pre>
<h1> </h1>
<pre><code># Broken:
# Makefile:70: target `src/main.o' doesn't match the target pattern
# Makefile:70: target `src/video.o' doesn't match the target pattern
# Add OBJDIR_DEBUG in target rule
OBJ = src/main.o src/video.o
$(OBJ): $(OBJDIR_DEBUG)/%.o: %.cpp
$(CXX) $(CFLAGS_DEBUG) $(INC_DEBUG) -c $< -o $@
</code></pre> | 13,552,576 | 3 | 0 | null | 2012-11-25 15:45:47.447 UTC | 7 | 2017-02-06 14:48:07.893 UTC | 2012-11-25 15:54:03.02 UTC | null | 339,378 | null | 339,378 | null | 1 | 30 | makefile|gnu-make | 26,933 | <p>After re-reading the <a href="http://www.gnu.org/software/make/manual/html_node/Static-Usage.html#Static-Usage">documentation on static pattern rules</a>, I derived the following pattern rule which seems to work.</p>
<pre><code>$(OBJ_DEBUG): $(OBJDIR_DEBUG)/%.o: %.cpp
$(CXX) $(CFLAGS_DEBUG) $(INC_DEBUG) -c $< -o $@
</code></pre>
<p>I'm not sure this is the best approach, and I'm open to suggestions.</p> |
13,354,531 | Maven project.build.directory | <p>In Maven, what does the <code>project.build.directory</code> refer to? I am a bit confused, does it reference the source code directory or the target directory in the Maven project?</p> | 13,356,378 | 4 | 1 | null | 2012-11-13 01:47:55.997 UTC | 61 | 2020-09-22 12:55:13.407 UTC | 2017-02-03 09:13:04.907 UTC | null | 452,775 | null | 1,304,016 | null | 1 | 209 | maven | 260,754 | <p>You can find those maven properties in the super pom.</p>
<p>You find the jar here:</p>
<pre><code>${M2_HOME}/lib/maven-model-builder-3.0.3.jar
</code></pre>
<p>Open the jar with 7-zip or some other archiver (or use the jar tool).</p>
<p>Navigate to</p>
<pre><code>org/apache/maven/model
</code></pre>
<p>There you'll find the <code>pom-4.0.0.xml</code>.</p>
<p>It contains all those "short cuts":</p>
<pre class="lang-xml prettyprint-override"><code><project>
...
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
</testResources>
...
</build>
...
</project>
</code></pre>
<hr>
<h2>Update</h2>
<p>After some lobbying I am adding a <a href="https://github.com/apache/maven/blob/trunk/maven-model-builder/src/main/resources/org/apache/maven/model/pom-4.0.0.xml#L53">link to the <code>pom-4.0.0.xml</code></a>. This allows you to see the properties without opening up the local jar file.</p> |
39,779,962 | Access AWS S3 from Lambda within VPC | <p>Overall, I'm pretty confused by using AWS Lambda within a VPC. The problem is Lambda is timing out while trying to access an S3 bucket. The solution seems to be a VPC Endpoint.</p>
<p>I've added the Lambda function to a VPC so it can access an RDS hosted database (not shown in the code below, but functional). However, now I can't access S3 and any attempt to do so times out.</p>
<p>I tried creating a VPC S3 Endpoint, but nothing has changed.</p>
<p><strong>VPC Configuration</strong></p>
<p>I'm using a simple VPC created by default whenever I first made an EC2 instance. It has four subnets, all created by default.</p>
<p><strong>VPC Route Table</strong></p>
<pre><code>_Destination - Target - Status - Propagated_
172.31.0.0/16 - local - Active - No
pl-63a5400a (com.amazonaws.us-east-1.s3) - vpce-b44c8bdd - Active - No
0.0.0.0/0 - igw-325e6a56 - Active - No
</code></pre>
<p><strong>Simple S3 Download Lambda:</strong></p>
<pre><code>import boto3
import pymysql
from StringIO import StringIO
def lambda_handler(event, context):
s3Obj = StringIO()
return boto3.resource('s3').Bucket('marineharvester').download_fileobj('Holding - Midsummer/sample', s3Obj)
</code></pre> | 44,478,894 | 7 | 3 | null | 2016-09-29 21:01:24.06 UTC | 13 | 2022-04-07 03:11:42.867 UTC | 2017-07-05 05:31:35.29 UTC | null | 6,382,901 | null | 2,182,234 | null | 1 | 78 | amazon-web-services|amazon-s3|aws-lambda|amazon-vpc | 37,338 | <p>With boto3, the S3 urls are <em>virtual</em> by default, which then require internet access to be resolved to region specific urls. This causes the hanging of the Lambda function until timeout.</p>
<p>To resolve this requires use of a <code>Config</code> object when creating the client, which tells boto3 to create <em>path</em> based S3 urls instead:</p>
<pre><code>import boto3
import botocore
client = boto3.client('s3', 'ap-southeast-2', config=botocore.config.Config(s3={'addressing_style':'path'}))
</code></pre>
<p>Note that the region in the call must be the region to which you are deploying the lambda and VPC Endpoint.</p>
<p>Then you will be able to use the <code>pl-xxxxxx</code> prefix list for the VPC Endpoint within the Lambda's security group, and still access S3.</p>
<p>Here is a working <a href="https://github.com/gford1000-aws/lambda_s3_access_using_vpc_endpoint" rel="noreferrer" title="CloudFormation script">CloudFormation script</a> that demonstrates this. It creates an S3 bucket, a lambda (that puts records into the bucket) associated to a VPC containing only private subnets and the VPC Endpoint, and necessary IAM roles.</p> |
3,287,545 | How do I make a stored procedure in MS Access? | <p>How do I make a stored procedure in MS Access?</p> | 3,296,393 | 2 | 0 | null | 2010-07-20 06:30:30.333 UTC | 4 | 2019-11-27 11:12:34.96 UTC | 2013-10-09 03:28:07.93 UTC | null | 729,907 | null | 396,335 | null | 1 | 22 | ms-access|stored-procedures | 117,705 | <p>Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode). </p>
<p>If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.</p>
<p>For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers. </p>
<p>For example:</p>
<p><img src="https://i.stack.imgur.com/mLguZ.png" alt="screenshot"></p>
<p>Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table
<img src="https://i.stack.imgur.com/BiAvm.png" alt="alt text"></p>
<p>Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.</p> |
3,536,463 | Android - Application (apk) Maximum size | <p>I am going to install first application in my android phone, but having some doubts
related to Android Memory (Maximum size of APK).</p>
<p>So please help me know and solve the problems:</p>
<ol>
<li>What is <strong>maximum size of the apk</strong> that can be supported by the android ?</li>
<li>When we install any apk file in real phone, <strong>where does application installed</strong> (in SD-card or other memory) ??</li>
</ol>
<p>I have referred this link: <a href="http://groups.google.com/group/android-developers/browse_thread/thread/7965885da4d1a03a" rel="noreferrer">http://groups.google.com/group/android-developers/browse_thread/thread/7965885da4d1a03a</a> and also searched lot.</p>
<p>I came Across the search on the web that <strong><code>many people are facing the same issue</code></strong> What is the maximum size of Application supported by Android. I think this question also help to the people who are connected with Android application programming and development.</p>
<p><strong><code>Update:</code></strong></p>
<p>This time i am having 58Mb application from that 52.5MB Images and it runs on the my HTC Hero mobile but On Emulator, it shows an error:</p>
<pre><code>Failed to upload my_application.apk on device 'emulator-5554'
java.io.IOException: Unable to upload file: No space left on device
Launch canceled!
</code></pre>
<p>Now please suggest me the way to store images inside the Drawable folder? is there any way to zip the images or such method?</p> | 3,536,527 | 2 | 4 | null | 2010-08-21 05:25:47.06 UTC | 16 | 2017-07-05 20:23:46.847 UTC | 2010-11-10 11:55:32.547 UTC | null | 213,269 | null | 379,693 | null | 1 | 31 | android|android-emulator|sd-card|apk|avd | 37,453 | <ol>
<li><p>Its probably device specific as devices has a different amount of memory available for application. ref <a href="http://groups.google.com/group/android-developers/browse_thread/thread/18cbb2404778618e?pli=1" rel="nofollow noreferrer">http://groups.google.com/group/android-developers/browse_thread/thread/18cbb2404778618e?pli=1</a></p></li>
<li><p>Its application dependant. The developer may state that the app should be preferrebly install on internal memory, the SD-card, or to let the user choose from SD-card and memory. This is only supported on Android 2.2. On older version of android, version <= 2.1, the app will be installed into the memory. Its defined inside the AndoridMainfest.xml via the <code>android:installLocation</code> element. It supports the values <code>internalOnly</code>, <code>preferExternal</code> or <code>auto</code>. But again, only supported on Android 2.2. ref <a href="https://developer.android.com/about/versions/android-2.2.html" rel="nofollow noreferrer">https://developer.android.com/about/versions/android-2.2.html</a></p></li>
</ol>
<p>I tested on my HTC Desire with more than 500 MB of memory. With almost none apps installed I can install an apk that is 43MB, but an apk that is 57MB is too large, even i got plenty of available memory... it fails with </p>
<p><code>Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]</code></p>
<p>The <a href="http://www.androidpit.com/en/android/market/apps/app/com.adao.android.afm/File-Manager" rel="nofollow noreferrer">"File Manager"</a> application tells me that im using 60/147MB (40%). The limit seems be 147 MB, but in practice, as i have tested, this is not true...</p>
<p><strong>Update:</strong></p>
<p>I did some testing, and published the results <a href="http://vidarvestnes.blogspot.com/2010/08/how-large-can-android-apk-file-be.html" rel="nofollow noreferrer">here</a>:</p>
<p><strong>::Edit::</strong>
<br>I never changes the any thing in this answer just update this.
<a href="http://android-developers.blogspot.in/2015/09/support-for-100mb-apks-on-google-play.html?linkId=17389452" rel="nofollow noreferrer">Update size by Developer blog</a> please refer this link about the updated answer.</p> |
9,355,690 | how to run compiled class file in Kotlin? | <p>Jetbrains provides <a href="http://confluence.jetbrains.com/display/Kotlin/Welcome">some documentation</a> but I can't find how to run compiled class file of Kotlin.</p>
<p>hello.kt:</p>
<pre><code>fun main(args : Array<String>) {
println("Hello, world!")
}
</code></pre>
<p>compile:</p>
<pre><code>$ kotlinc -out dist -src hello.kt
$ ls dist
namespace.class
$ java dist/namespace
Exception in thread "main" java.lang.NoClassDefFoundError: dist/namespace (wrong name: namespace)
$ java -jar /usr/local/kotlin/lib/kotlin-runtime.jar
Failed to load Main-Class manifest attribute from
/usr/local/kotlin/lib/kotlin-runtime.jar
</code></pre>
<p>How to run Kotlin program?</p> | 9,356,023 | 5 | 2 | null | 2012-02-20 03:01:17.823 UTC | 5 | 2022-03-12 05:40:00.647 UTC | 2014-01-05 07:39:19.703 UTC | null | 1,196,603 | null | 514,249 | null | 1 | 28 | kotlin | 14,432 | <p>We ran into the same program and blogged our solution here: <a href="http://blog.ocheyedan.net/blog/2012/02/19/running-kotlin-code/" rel="noreferrer">http://blog.ocheyedan.net/blog/2012/02/19/running-kotlin-code/</a></p>
<p>Basically you just need to invoke java with the -cp and the main class of 'namespace'. From your question, the java invocation would look something like this:</p>
<pre><code>java -cp /usr/local/kotlin/lib/kotlin-runtime.jar:dist/namespace.class namespace
</code></pre> |
9,255,633 | Front facing camera in UIImagePickerController | <p>I am developing the front facing camera app in iPad2 by using the <code>UIImagePickerController</code>.</p>
<p>When I capture the image it's shows as flipped from left to right.</p>
<p>How do I correct this?</p>
<pre><code>if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController *imgPkr = [[UIImagePickerController alloc] init];
imgPkr.delegate = self;
imgPkr.sourceType = UIImagePickerControllerSourceTypeCamera;
imgPkr.cameraDevice=UIImagePickerControllerCameraDeviceFront;
UIImageView *anImageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"select%d.png",val]]];
anImageView.frame = CGRectMake(0, 0, anImageView.image.size.width, anImageView.image.size.height);
imgPkr.cameraOverlayView = anImageView;
[theApp.TabViewControllerObject presentModalViewController:imgPkr animated:YES];
[imgPkr release];
}
</code></pre> | 9,255,673 | 9 | 2 | null | 2012-02-13 04:30:49.633 UTC | 26 | 2021-07-21 00:32:21.37 UTC | 2015-10-11 10:03:14.947 UTC | null | 1,190,861 | null | 778,609 | null | 1 | 67 | ios|objective-c|iphone|swift|uiimagepickercontroller | 33,941 | <p>You can flip the image from the source image use this</p>
<pre><code>UIImage *flippedImage = [UIImage imageWithCGImage:picture.CGImage scale:picture.scale orientation:UIImageOrientationLeftMirrored];
</code></pre>
<hr>
<p><strong>Edit:</strong> Added swift code</p>
<pre><code>let flippedImage = UIImage(CGImage: picture.CGImage, scale: picture.scale, orientation:.LeftMirrored)
</code></pre> |
16,056,666 | Expand select dropdown | <p>I am trying to expand a select dropdown upon clicking on a link. </p>
<pre><code><button type="button" id="btn">Click Me!</button>
<select id='sel' name='sel'>
<option>item 1</option>
<option>item 2</option>
<option>item 3</option>
<option>item 4</option>
</select>
</code></pre>
<p>And the Javescript is as follows.</p>
<pre><code>$(document).ready(function() {
$("#btn").click(function() {
$("#sel").trigger('click');
});
});
</code></pre>
<p>Any Ideas...??</p> | 16,056,763 | 4 | 4 | null | 2013-04-17 09:41:02.633 UTC | 6 | 2017-11-23 09:54:58.57 UTC | null | null | null | null | 2,289,967 | null | 1 | 22 | jquery | 52,419 | <p>You cannot mimic native browser event using <code>.trigger</code>. Looking at <a href="http://learn.jquery.com/events/triggering-event-handlers/" rel="noreferrer">this link</a> to the jQuery tutorial it seems you need <code>.simulate</code> method from <a href="https://github.com/eduardolundgren/jquery-simulate/blob/master/jquery.simulate.js" rel="noreferrer">jquery.simulate.js</a>. Moreover the open event of the dropdown box is given by <code>mousedown</code> not <code>click</code>.</p>
<p><strong>Update:</strong> So the code become:</p>
<pre><code>$(document).ready(function() {
$("#btn").click(function() {
$("#sel").simulate('mousedown');
});
});
</code></pre> |
29,220,897 | CREATE DATABASE or ALTER DATABASE failed because the resulting cumulative database size would exceed your licensed limit of 10240 MB per database | <p>I have SQL Server not Express and when db grows to 10240 I get error:</p>
<blockquote>
<p>Could not allocate space for object in database because the 'PRIMARY'
filegroup is full. Create disk space by deleting unneeded files,
dropping objects in the filegroup, adding additional files to the
filegroup, or setting autogrowth on for existing files in the
filegroup.</p>
</blockquote>
<p>I tried to change Initial size from 10240 to more but then got error: </p>
<blockquote>
<p>CREATE DATABASE or ALTER DATABASE failed because the resulting
cumulative database size would exceed your licensed limit of 10240 MB
per database. (Microsoft SQL Server, Error: 1827)</p>
</blockquote>
<p>But this is really not Express but full SQL Server, so how it is possible that it has this limitation? </p> | 29,226,046 | 7 | 9 | null | 2015-03-23 21:38:08.963 UTC | 2 | 2022-08-24 03:32:16.727 UTC | 2015-03-23 21:42:07.517 UTC | null | 13,302 | null | 428,547 | null | 1 | 16 | sql|sql-server|sql-server-2008 | 55,831 | <p>The instance name for SQL Server Express is by default <code>SQLEXPRESS</code> - but it can be anything you choose during installation. If you install SQL Server Express as the <strong>default</strong> (un-named) instance, then you get <code>MSSQLSERVER</code> as the pseudo instance name for SQL Server Express.</p>
<p>Hence, you really cannot rely on the <em>instance name</em> to judge whether your SQL Server is the Express edition or not. You need to use </p>
<pre><code>SELECT @@Version
</code></pre>
<p>to get that information.</p> |
17,209,643 | What does is.na() applied to non-(list or vector) of type 'NULL' mean? | <p>I want to select a Cox model with the forward procedure from a data.frame with no NA. Here is some sample data:</p>
<pre><code>test <- data.frame(
x_1 = runif(100,0,1),
x_2 = runif(100,0,5),
x_3 = runif(100,10,20),
time = runif(100,50,200),
event = c(rep(0,70),rep(1,30))
)
</code></pre>
<p>This table has no signification but if we try to build a model anyway :</p>
<pre><code>modeltest <- coxph(Surv(time, event) ~1, test)
modeltest.forward <- step(
modeltest,
data = test,
direction = "forward",
scope = list(lower = ~ 1, upper = ~ x_1 + x_2 + x_3)
)
</code></pre>
<p>The forward ends at the first step and says:</p>
<blockquote>
<p>In is.na(fit$coefficients) : is.na() applied to non-(list or vector) of type 'NULL'</p>
</blockquote>
<p>(three times)</p>
<p>I tried to change the upper model, I even tried <code>upper = ~ 1</code> but the warning stays. I don't understand: I have no NAs and my vectors are all numerics (I checked it).
I searched if people had the same issue but all I could find was problems due to the name or class of the vectors.</p>
<p>What's wrong with my code?</p> | 34,260,357 | 1 | 7 | null | 2013-06-20 09:09:02.393 UTC | 1 | 2015-12-14 05:41:21.29 UTC | 2015-12-14 05:35:43.9 UTC | null | 134,830 | null | 2,504,372 | null | 1 | 12 | r|na|cox-regression | 39,046 | <h2>The problem in this specific case</h2>
<p>The right hand side of your formula is <code>1</code>, which makes it a <em>null model</em>. <code>coxph</code> calls <code>coxph.fit</code>, which (perhaps lazily) doesn't bother to return coefficients for null models.</p>
<p>Later <code>coxph</code> calls <code>extractAIC</code>, which erroneously assumes that the model object contains an element named <code>coefficients</code>.</p>
<h2>The general case</h2>
<p><code>is.na</code> assumes that its input argument is an atomic vector or a matrix or a list or a data.frame. Other data types cause the warning. It happens with <code>NULL</code>, as you've seen:</p>
<pre><code>is.na(NULL)
## logical(0)
## Warning message:
## In is.na(NULL) : is.na() applied to non-(list or vector) of type 'NULL'
</code></pre>
<p>One common cause of this problem is trying to access elements of a list, or columns of a data frame that don't exist.</p>
<pre><code>d <- data.frame(x = c(1, NA, 3))
d$y # "y" doesn't exist is the data frame, but NULL is returned
## NULL
is.na(d$y)
## logical(0)
## Warning message:
## In is.na(d$y) : is.na() applied to non-(list or vector) of type 'NULL'
</code></pre>
<p>You can protect against this by checking that the column exists before you manipulate it.</p>
<pre><code>if("y" in colnames(d))
{
d2 <- d[is.na(d$y), ]
}
</code></pre>
<h2>The warning with other data types</h2>
<p>You get a simliar warning with formulae, functions, expressions, etc.:</p>
<pre><code>is.na(~ NA)
## [1] FALSE FALSE
## Warning message:
## In is.na(~NA) : is.na() applied to non-(list or vector) of type 'language'
is.na(mean)
## [1] FALSE
## Warning message:
## In is.na(mean) : is.na() applied to non-(list or vector) of type 'closure'
is.na(is.na)
## [1] FALSE
## Warning message:
## In is.na(is.na) : is.na() applied to non-(list or vector) of type 'builtin'
is.na(expression(NA))
## [1] FALSE
## Warning message:
## In is.na(expression(NA)) :
## is.na() applied to non-(list or vector) of type 'expression'
</code></pre> |
37,371,451 | ImportError: No module named 'pandas.indexes' | <p>Importing pandas didn't throw the error, but rather trying to read a picked pandas dataframe as such:</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib
import seaborn as sns
sns.set(style="white")
control_data = pd.read_pickle('null_report.pickle')
test_data = pd.read_pickle('test_report.pickle')
</code></pre>
<p>The traceback is 165 lines with three concurrent exceptions (whatever that means). Is <code>read_pickle</code> not compatible with pandas version 17.1 I'm running? How do I unpickle my dataframe for use?</p>
<p>Below is a copy of the traceback:</p>
<pre><code>ImportError Traceback (most recent call last)
C:\Users\test\Anaconda3\lib\site-packages\pandas\io\pickle.py in try_read(path, encoding)
45 with open(path, 'rb') as fh:
---> 46 return pkl.load(fh)
47 except (Exception) as e:
ImportError: No module named 'pandas.indexes'
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
C:\Users\test\Anaconda3\lib\site-packages\pandas\io\pickle.py in try_read(path, encoding)
51 with open(path, 'rb') as fh:
---> 52 return pc.load(fh, encoding=encoding, compat=False)
53
C:\Users\test\Anaconda3\lib\site-packages\pandas\compat\pickle_compat.py in load(fh, encoding, compat, is_verbose)
115
--> 116 return up.load()
117 except:
C:\Users\test\Anaconda3\lib\pickle.py in load(self)
1038 assert isinstance(key, bytes_types)
-> 1039 dispatch[key[0]](self)
1040 except _Stop as stopinst:
C:\Users\test\Anaconda3\lib\pickle.py in load_stack_global(self)
1342 raise UnpicklingError("STACK_GLOBAL requires str")
-> 1343 self.append(self.find_class(module, name))
1344 dispatch[STACK_GLOBAL[0]] = load_stack_global
C:\Users\test\Anaconda3\lib\pickle.py in find_class(self, module, name)
1383 module = _compat_pickle.IMPORT_MAPPING[module]
-> 1384 __import__(module, level=0)
1385 if self.proto >= 4:
ImportError: No module named 'pandas.indexes'
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
C:\Users\test\Anaconda3\lib\site-packages\pandas\io\pickle.py in read_pickle(path)
59 try:
---> 60 return try_read(path)
61 except:
C:\Users\test\Anaconda3\lib\site-packages\pandas\io\pickle.py in try_read(path, encoding)
56 with open(path, 'rb') as fh:
---> 57 return pc.load(fh, encoding=encoding, compat=True)
58
C:\Users\test\Anaconda3\lib\site-packages\pandas\compat\pickle_compat.py in load(fh, encoding, compat, is_verbose)
115
--> 116 return up.load()
117 except:
C:\Users\test\Anaconda3\lib\pickle.py in load(self)
1038 assert isinstance(key, bytes_types)
-> 1039 dispatch[key[0]](self)
1040 except _Stop as stopinst:
C:\Users\test\Anaconda3\lib\pickle.py in load_stack_global(self)
1342 raise UnpicklingError("STACK_GLOBAL requires str")
-> 1343 self.append(self.find_class(module, name))
1344 dispatch[STACK_GLOBAL[0]] = load_stack_global
C:\Users\test\Anaconda3\lib\pickle.py in find_class(self, module, name)
1383 module = _compat_pickle.IMPORT_MAPPING[module]
-> 1384 __import__(module, level=0)
1385 if self.proto >= 4:
ImportError: No module named 'pandas.indexes'
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
C:\Users\test\Anaconda3\lib\site-packages\pandas\io\pickle.py in try_read(path, encoding)
45 with open(path, 'rb') as fh:
---> 46 return pkl.load(fh)
47 except (Exception) as e:
ImportError: No module named 'pandas.indexes'
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
C:\Users\test\Anaconda3\lib\site-packages\pandas\io\pickle.py in try_read(path, encoding)
51 with open(path, 'rb') as fh:
---> 52 return pc.load(fh, encoding=encoding, compat=False)
53
C:\Users\test\Anaconda3\lib\site-packages\pandas\compat\pickle_compat.py in load(fh, encoding, compat, is_verbose)
115
--> 116 return up.load()
117 except:
C:\Users\test\Anaconda3\lib\pickle.py in load(self)
1038 assert isinstance(key, bytes_types)
-> 1039 dispatch[key[0]](self)
1040 except _Stop as stopinst:
C:\Users\test\Anaconda3\lib\pickle.py in load_stack_global(self)
1342 raise UnpicklingError("STACK_GLOBAL requires str")
-> 1343 self.append(self.find_class(module, name))
1344 dispatch[STACK_GLOBAL[0]] = load_stack_global
C:\Users\test\Anaconda3\lib\pickle.py in find_class(self, module, name)
1383 module = _compat_pickle.IMPORT_MAPPING[module]
-> 1384 __import__(module, level=0)
1385 if self.proto >= 4:
ImportError: No module named 'pandas.indexes'
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-17-3b05fe7d20a4> in <module>()
3 # test_data = np.genfromtxt(fh, usecols=2)
4
----> 5 control_data = pd.read_pickle('null_report.pickle')
6 test_data = pd.read_pickle('test_report.pickle')
7
C:\Users\test\Anaconda3\lib\site-packages\pandas\io\pickle.py in read_pickle(path)
61 except:
62 if PY3:
---> 63 return try_read(path, encoding='latin1')
64 raise
C:\Users\test\Anaconda3\lib\site-packages\pandas\io\pickle.py in try_read(path, encoding)
55 except:
56 with open(path, 'rb') as fh:
---> 57 return pc.load(fh, encoding=encoding, compat=True)
58
59 try:
C:\Users\test\Anaconda3\lib\site-packages\pandas\compat\pickle_compat.py in load(fh, encoding, compat, is_verbose)
114 up.is_verbose = is_verbose
115
--> 116 return up.load()
117 except:
118 raise
C:\Users\test\Anaconda3\lib\pickle.py in load(self)
1037 raise EOFError
1038 assert isinstance(key, bytes_types)
-> 1039 dispatch[key[0]](self)
1040 except _Stop as stopinst:
1041 return stopinst.value
C:\Users\test\Anaconda3\lib\pickle.py in load_stack_global(self)
1341 if type(name) is not str or type(module) is not str:
1342 raise UnpicklingError("STACK_GLOBAL requires str")
-> 1343 self.append(self.find_class(module, name))
1344 dispatch[STACK_GLOBAL[0]] = load_stack_global
1345
C:\Users\test\Anaconda3\lib\pickle.py in find_class(self, module, name)
1382 elif module in _compat_pickle.IMPORT_MAPPING:
1383 module = _compat_pickle.IMPORT_MAPPING[module]
-> 1384 __import__(module, level=0)
1385 if self.proto >= 4:
1386 return _getattribute(sys.modules[module], name)[0]
ImportError: No module named 'pandas.indexes'
</code></pre>
<p>I also tried loading the pickle file from pickle directly:</p>
<p><code>via_pickle = pickle.load( open( 'null_report.pickle', "rb" ) )</code></p>
<p>and got the same error:</p>
<pre><code>---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-23-ba2e3adae1c4> in <module>()
1
----> 2 via_pickle = pickle.load( open( 'null_report.pickle', "rb" ) )
3
4 # control_data = pd.read_pickle('null_report.pickle')
5 # test_data = pd.read_pickle('test_report.pickle')
ImportError: No module named 'pandas.indexes'
</code></pre> | 46,389,140 | 7 | 5 | null | 2016-05-22 06:56:16.75 UTC | 3 | 2020-04-27 17:51:04.657 UTC | 2016-05-22 07:18:03.077 UTC | null | 4,154,548 | null | 4,154,548 | null | 1 | 33 | python|numpy|pandas|pickle | 41,493 | <p>I had this error when I created a pkl file with python 2.7 and was trying to read it with python 3.6
I did:</p>
<pre><code>pd.read_pickle('foo.pkl')
</code></pre>
<p>and it worked</p> |
27,151,806 | Deeplinking mobile browsers to native app - Issues with Chrome when app isn't installed | <p>I have a webpage, lets call it <code>entry.html</code>.</p>
<p>When a user enters this page, a javascript code (see below) is attempting to deep-link the user to the native iOS / Android app.</p>
<p>If the deep-link fails (probably if the app isn't installed on device), user should "fall back" to another page- lets call it <code>fallback.html</code>.</p>
<p>here is the javascript code that is running on <code>entry.html</code>:</p>
<pre><code>$(function(){
window.location = 'myapp://';
setTimeout(function(){
window.location = 'fallback.html';
}, 500);
});
</code></pre>
<p>this is a standard deep-linking method that is recommended all over the network; try to deep-link, and if the timeout fires it means that deep-link didn't occur- so fallback.</p>
<p><strong>this works fine, as long app is installed on device.</strong></p>
<p>but if the app isn't installed, this is the behaviour when trying to deep-link:</p>
<p><strong>Mobile Safari</strong>: I see an alert message saying "Safari cannot open this page..." for a moment, and then it falls-back properly to <code>fallback.html</code>- which is the expected behaviour.</p>
<p><strong>Mobile Chrome</strong> is my problem.</p>
<p>when the app isn't installed, browser is actually redirected to the <code>myapp://</code> url, which is of course, invalid- so i get a "not found" page, and fall-back doesn't occur.</p>
<p><strong>Finally</strong>- my question is:</p>
<p>How can I fix my code so FALL-BACK WILL OCCUR on mobile Chrome as well? just like mobile Safari?</p>
<p><em>note: i see that LinkedIn mobile website does this properly, with Safari & Chrome, with or without the app installed, but i couldn't trace the code responsible for it :(</em></p>
<p><em>note2: i tried appending an <code>iframe</code> instead of <code>window.location = url</code>, this works only on Safari, mobile Chrome doesn't deep-link when appending an iFrame even if app is installed.</em></p>
<p>Thanks all!</p>
<hr>
<p><strong>UPDATE:</strong></p>
<p>i found a decent solution, and answered my own question. see accepted answer for my solution.</p> | 29,060,700 | 7 | 5 | null | 2014-11-26 14:36:59.347 UTC | 16 | 2020-01-24 10:52:17.35 UTC | 2015-04-13 12:17:07.237 UTC | null | 326,804 | null | 326,804 | null | 1 | 28 | javascript|mobile-website|deep-linking|mobile-chrome | 45,634 | <p>for whoever is interested, i managed to find a decent solution to solve these issues with deeplinking Chrome on Android.</p>
<p>i abandoned the <code>myapp://</code> approach, i left it functioning only in cases of an iOS device.</p>
<p>for Android devices, i'm now using <code>intents</code> which are <strong>conceptually different</strong> than the <code>myapp://</code> protocol.</p>
<p>I'm mainly a web developer, not an Android developer, so it took me some time to understand the concept, but it's quite simple. i'll try to explain and demonstrate MY solution here (note that there are other approaches that could be implemented with <code>intents</code>, but this one worked for me perfectly).</p>
<p>here is the relevant part in the Android app manifest, registering the intent rules (note the <code>android:scheme="http"</code> - we'll talk about it shortly):</p>
<pre><code><receiver android:name=".DeepLinkReceiver">
<intent-filter >
<data android:scheme="http" android:host="www.myapp.com" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
</code></pre>
<p>now, after this is declared in the app manifest, i'm sending myself an email with <strong>"<a href="http://www.myapp.com" rel="noreferrer">http://www.myapp.com</a>"</strong> in the message.</p>
<p>when link is tapped with the Android device, a "chooser" dialog comes up, asking with which application i want to open the following? [chrome, <strong>myapp</strong>]</p>
<p>the reason this dialog came up upon tapping on a "regular" url, is because we registered the intent with the <strong>http</strong> scheme.</p>
<p>with this approach, the deeplink isn't even handled in the webpage, it's handled by <strong>the device</strong> itself, when tapping a matching link to an existing intent rule defined in the Android app manifest.</p>
<p>and yes, as i said, this approach is different by concept than the iOS approach, which invokes the deeplink from within the webpage, but it solves the problem, and it does the magic.</p>
<p><strong>Note:</strong> when app isn't installed, no chooser dialog will come up, you'll just get navigated to the actual web page with the given address (unless you have more than 1 browser, so you'll need to choose one... but lets not be petty).</p>
<p>i really hope that this could help someone who's facing the same thing.. wish i had such an explanation ;-)</p>
<p>cheers.</p> |
27,117,952 | missing commits after git rebase | <pre><code>A-B-C Master
\D-E Feature
</code></pre>
<p>After executing a <code>rebase</code> command <code>git checkout feature</code> -> <code>git rebase master</code> all my commits from <code>feature</code> branch disappears so I have <code>A-B-C</code> commits. <code>feature</code> branch looks like <code>master</code> after rebasing. Also rebasing doesn't give any error but it doesn't show 'commits are replayed' message which I think usually it shows during rebasing. Do you know what could have caused this behaviour? </p>
<p>Once I've noticed my commits disappeared I ran the following command to find the missing code in git history: <code>git rev-list --all | xargs git grep expression</code> This command returned a commit hash but this hash was not present when I run git log (because of rebase). If I do <code>git reset --hard missing-hash</code> I can see the original (correct) <code>feature</code> code again. Running <code>rebase master</code> recreates same problem again.</p>
<p><strong>EDIT:</strong> I've just noticed I have some extra commits like <code>WIP on commit-message</code> and <code>index on commit-message</code> when I do <code>git reset --hard missing-hash</code> Can it be related with <code>git stash / git stash apply</code></p> | 27,788,040 | 1 | 5 | null | 2014-11-25 02:43:08.79 UTC | 8 | 2015-01-05 21:45:28.96 UTC | 2014-11-25 10:10:51.38 UTC | null | 1,289,775 | null | 1,289,775 | null | 1 | 18 | git|github|rebase | 19,692 | <p>Just so were on the same page about how rebases work. In your example, git is basically trying to add and D and E after C one by one. The rebase commits on D & E will not be the originals, instead they will be clones with new hashes. The original will still exist, but will simply be dangling with no branch referencing them (garbage collection will delete them eventually). After a rebase, you can see the "original" version of the rebased commits by looking at <code>git log ORIG_HEAD</code></p>
<p>However, exceptions can take place in this process. Git will intelligently skip any commits that are already in the "base" (master, in this case) - this can happen a branch gets merged, reverted, then remerged. </p>
<p>It will also skip any commits if it finds that the commits being added to the base identically match, in their content - commits that are already in the history - even if the hashes are different - this can happen if a branch is merged, rebase, then merged again.</p>
<p>I suspect one of a few situations. </p>
<ol>
<li>Your feature branch may have already been merged into master. </li>
<li>Your feature branch already matches master.</li>
</ol>
<p>1) git branch --contains feature</p>
<p>This will list all branches which contain your feature branch in their history. If master is in that list, then your branch is already merged. Nothing to do here.</p>
<p>Theres a few reasons this might not seem right though. </p>
<p>One reason is that you may not see your changes in the current master code. This could be for a few reasons. If the branch had been previously merged into master, and then reverted, then the commits are already there, but negated - even if remerged those reverted commits will not return - you would need to revert the actual revert commit.</p>
<p>2) git checkout feature; git rebase --keep-empty feature</p>
<p>The --keep-empty will force git to keep your commits even if they don't contain any "new" content or changes. This isn't a fix or workaround, but if you see these commits in your history after doing this - then it means your commits arent being lost. They are getting skipped intentionally. You can decide for yourself if you want to keep the empty ones.</p>
<p>If this is the case, then I would look to see if this branch has been merged in the past. It may have been merged as part of a different branch for example. Maybe Bob thought he needed your work from the <code>feature</code> branch in his <code>bobs_feature</code> branch - his branch made it to master before yours and now your branch is basically irrelevant. Another case might be that it was merged in the past into master, and then reverted. The answer here is to revert the revert commit itself - sort of like hitting redo after hitting an undo.</p> |
21,659,671 | TypeError: google.visualization is undefined | <p>I'm trying to work with Google charts API, but I get an error I can't understand:</p>
<p>Here is my code:</p>
<pre><code><script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="js/statistics/overview.js"></script>
</code></pre>
<p>And the code from overview.js is like this:</p>
<pre><code>var statisticsOverview = {
init: function() {
google.load("visualization", "1", {packages: ["corechart"]});
google.setOnLoadCallback(this.drawIncomeChart());
google.setOnLoadCallback(this.drawExpensesChart());
google.setOnLoadCallback(this.drawEconomiesChart());
},
drawIncomeChart: function() {
var data = [
['Year', 'Income'],
['October 2013', 1000],
['January 2014', 1170],
['March 2014', 660]
];
var options = {
title: 'Income Performance',
colors: ['green']
};
var id = 'chart_income';
this.drawLineChart(data, options, id);
},
drawExpensesChart: function() {
var data = [
['Year', 'Expense'],
['October 2013', 1000],
['January 2014', 1170],
['March 2014', 660]
];
var options = {
title: 'Expense Performance',
colors: ['red']
};
var id = 'chart_expenses';
this.drawLineChart(data, options, id);
},
drawEconomiesChart: function() {
var data = [
['Year', 'Savings'],
['2004', 1000],
['2005', 1170],
['2006', 660],
['2007', 1030]
];
var options = {
title: 'Savings Performance',
colors: ['orange']
};
var id = 'chart_economies';
this.drawLineChart(data, options, id);
},
drawLineChart: function(data, options, id) {
console.log(google.visualization);
var chartData = google.visualization.arrayToDataTable(data);
var chart = new google.visualization.LineChart(document.getElementById(id));
chart.draw(chartData, options);
}
};
statisticsOverview.init();
</code></pre>
<p>This is strange, because console.log() will give me the google object with the property visualization. What am I doing wrong?</p> | 21,660,114 | 3 | 4 | null | 2014-02-09 13:35:14.02 UTC | 2 | 2022-04-06 18:09:17.263 UTC | null | null | null | null | 759,856 | null | 1 | 20 | javascript|google-visualization | 38,001 | <p>Timing problem. Typically you call google chart like</p>
<pre><code> google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
...
}
</code></pre>
<p>So, when visualization package is loaded function to draw is called. </p>
<p>Now, in your case everything is done later, so you have to do:</p>
<pre><code>google.load("visualization", "1", {packages: ["corechart"]});
function doStats() {
var statisticsOverview = {
init: function() {
console.log('init');
this.drawIncomeChart();
this.drawExpensesChart();
this.drawEconomiesChart();
},
...
};
statisticsOverview.init()
}
google.setOnLoadCallback(doStats);
</code></pre>
<p>Similar result can be get using </p>
<pre><code>setTimeout(function() {
statisticsOverview.init();
}, 3000);
</code></pre>
<p>without wrapper function.</p> |
21,733,919 | Ruby `each_with_object` with index | <p>I would like to do <code>a.each_with_object</code> with <code>index</code>, in a better way than this:</p>
<pre><code>a = %w[a b c]
a.each.with_index.each_with_object({}) { |arr, hash|
v,i = arr
puts "i is: #{i}, v is #{v}"
}
i is: 0, v is a
i is: 1, v is b
i is: 2, v is c
=> {}
</code></pre>
<p>Is there a way to do this without <code>v,i = arr</code> ?</p> | 21,734,108 | 3 | 4 | null | 2014-02-12 16:36:40.007 UTC | 7 | 2015-01-25 20:25:22.623 UTC | null | null | null | null | 226,255 | null | 1 | 41 | ruby | 16,516 | <p>Instead of</p>
<pre><code>|arr, hash|
</code></pre>
<p>you can do</p>
<pre><code>|(v, i), hash|
</code></pre> |
21,606,739 | django - update model with FormView and ModelForm | <p>I can't figure out how to use a <code>ModelForm</code> in a <code>FormView</code> so that it updates an already existing instance??</p>
<p>The form POSTs on this URL: <code>r'/object/(?P<pk>)/'</code></p>
<p>I use a <code>ModelForm</code> (and not directly an <code>UpdateView</code>) because one of the fields is required and I perform a clean on it.</p>
<p>I'd basically like to provide the kwarg <code>instance=...</code> when initializing the form in the <code>FormView</code> (at POST) so that it's bound to the object whose pk is given in the url. But I can't figure out where to do that...</p>
<pre><code>class SaveForm(ModelForm):
somedata = forms.CharField(required=False)
class Meta:
model = SomeModel # with attr somedata
fields = ('somedata', 'someotherdata')
def clean_somedata(self):
return sometransformation(self.cleaned_data['somedata'])
class SaveView(FormView):
form_class = SaveForm
def form_valid(self, form):
# form.instance here would be == SomeModel.objects.get(pk=pk_from_kwargs)
form.instance.save()
return ...
</code></pre> | 21,703,844 | 3 | 7 | null | 2014-02-06 15:16:13.693 UTC | 25 | 2015-07-13 13:28:45.187 UTC | 2014-02-10 09:53:47.117 UTC | null | 931,156 | null | 931,156 | null | 1 | 33 | django|django-views|django-forms | 35,243 | <p>After some discussion with you, I still don't see why you can't use an <code>UpdateView</code>. It seems like a very simple use case if I understand correctly. You have a model that you want to update. And you have a custom form to do cleaning before saving it to that model. Seems like an <code>UpdateView</code> would work just fine. Like this:</p>
<pre><code>class SaveForm(ModelForm):
somedata = forms.CharField(required=False)
class Meta:
model = SomeModel # with attr somedata
fields = ('somedata', 'someotherdata')
def clean_somedata(self):
return sometransformation(self.cleaned_data['somedata'])
class SaveView(UpdateView):
template_name = 'sometemplate.html'
form_class = SaveForm
model = SomeModel
# That should be all you need. If you need to do any more custom stuff
# before saving the form, override the `form_valid` method, like this:
def form_valid(self, form):
self.object = form.save(commit=False)
# Do any custom stuff here
self.object.save()
return render_to_response(self.template_name, self.get_context_data())
</code></pre>
<p>Of course, if I am misunderstanding you, please let me know. You should be able to get this to work though.</p> |
26,493,434 | How to refresh controls after a model has changed? | <p>I build a web application using <a href="https://openui5.hana.ondemand.com/docs/api/symbols/sap.m.SplitApp.html" rel="nofollow noreferrer">SplitApp</a>, and I have a problem with my sap.m.Select controls. </p>
<p>On page1.view I have 2 select controls, as it is shown <a href="http://jsbin.com/coparevumuga/2/edit?html,output" rel="nofollow noreferrer">here</a> (my thanks to <a href="https://stackoverflow.com/users/327864/allen">Allen</a> for his help). These select controls are populated from a database using ajax call.</p>
<p>The problem is that when I add a new project to one of the firms on page2.view, I can't make project select control on page1.view to refresh. </p>
<p>For example, if I go to page1.view, select firm3 in the first select control, then go to page2.view and add project4 to firm3 and then navigate back to page1.view, I still see firm 3 is selected and there are only 3 projects available in the second select control.
But if I select any other firm and then select firm3 again, I will see the 4th project in selection menu.</p>
<p>So, the question is how do I refresh my project select control so I could see the newly added project without re-selecting a firm?</p> | 26,499,705 | 2 | 2 | null | 2014-10-21 18:13:59.087 UTC | 3 | 2016-03-30 18:13:44.213 UTC | 2017-05-23 10:29:21.527 UTC | null | -1 | null | 3,649,862 | null | 1 | 2 | sapui5 | 57,217 | <p>You need to call <code>refresh()</code> of JSONModel. Please run and check the code snippet.</p>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m,sap.ui.commons"></script>
<script id="view1" type="sapui5/xmlview">
<mvc:View xmlns:core="sap.ui.core" xmlns:layout="sap.ui.commons.layout" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.ui.commons" controllerName="my.own.controller" xmlns:html="http://www.w3.org/1999/xhtml">
<layout:VerticalLayout id="vl">
<Button press="handlePress" text="Add Dummy Project to Firm1"/>
<DropdownBox id="db1" items="{/firms}" change="onchange">
<items>
<core:ListItem key="{name}" text="{name}" />
</items>
</DropdownBox>
<DropdownBox id="db2" items="{namedmodel>/projects}">
<items>
<core:ListItem key="{namedmodel>name}" text="{namedmodel>name}" />
</items>
</DropdownBox>
</layout:VerticalLayout>
</mvc:View>
</script>
<script>
sap.ui.controller("my.own.controller", {
onInit: function() {
var data = {
"firms": [{
"name": "firm1",
"projects": [{
"name": "firm1project1"
}, {
"name": "firm1project2"
}, {
"name": "firm1project3"
}]
}, {
"name": "firm2",
"projects": [{
"name": "firm2project1"
}, {
"name": "firm2project2"
}, {
"name": "firm2project3"
}]
}, {
"name": "firm3",
"projects": [{
"name": "firm3project1"
}, {
"name": "firm3project2"
}, {
"name": "firm3project3"
}]
}, {
"name": "firm4",
"projects": [{
"name": "firm4project1"
}, {
"name": "firm4project2"
}, {
"name": "firm4project3"
}]
}]
};
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
sap.ui.getCore().setModel(oModel);
//set initial values for second dropdown box
var oModel2 = new sap.ui.model.json.JSONModel();
oModel2.setData(data.firms[0]);
//using named data model binding for second dropdown box
this.byId("db2").setModel(oModel2, "namedmodel");
},
//event handler for first dropdown box selection change
onchange: function(oEvent) {
var bindingContext = oEvent.mParameters.selectedItem.getBindingContext();
var oModel = oEvent.getSource().getModel();
var firmData = oModel.getProperty(bindingContext.sPath);
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(firmData);
this.byId("db2").setModel(oModel, "namedmodel");
},
handlePress:function(oEvent) {
//Add a dummy project to firm1
var projectDropDown = this.byId("db2");
var oModel = projectDropDown.getModel("namedmodel");
oModel.oData.projects.push({"name":"dummy project"});
oModel.refresh();
}
});
var myView = sap.ui.xmlview("myView", {
viewContent: jQuery('#view1').html()
}); //
myView.placeAt('content');
</script>
<body class='sapUiBody'>
<div id='content'></div>
</body></code></pre>
</div>
</div>
</p> |
19,499,500 | Canvas getImageData() For optimal performance. To pull out all data or one at a time? | <p>I need to scan through every pixel in a canvas image and do some fiddling with the colors etc. For optimal performance, should I grab all the data in one go and work on it through the array? Or should I call each pixel as I work on it. </p>
<p>So basically... </p>
<pre><code>data = context.getImageData(x, y, height, width);
</code></pre>
<p>VS </p>
<pre><code>data = context.getImageData(x, y, 1, 1); //in a loop height*width times.
</code></pre> | 19,502,117 | 3 | 4 | null | 2013-10-21 16:08:55.547 UTC | 11 | 2016-08-29 23:16:58.423 UTC | 2013-10-23 10:40:03.473 UTC | null | 130,652 | null | 1,550,534 | null | 1 | 8 | javascript|performance|canvas | 9,839 | <p>You'll get much higher performances by grabbing the image all at once since :
a) a (contiguous) acces to an array is way faster than a function call.
b) especially when this function isa method of a DOM object having some overhead.
c) and there might be buffer refresh issues that might delay response (if canvas is
on sight... or not depending on double buffering implementation). </p>
<p>So go for a one-time grab. </p>
<p>I'll suggest you look into Javascript Typed Arrays to get the most of the
imageData result.</p>
<p>If i may quote myself, look at how you can handle pixels fast in this old post of mine
(look after 2) ): </p>
<h2> <a href="https://stackoverflow.com/questions/14424648/nice-ellipse-on-a-canvas/14429346#14429346">Nice ellipse on a canvas?</a></h2>
<p>(i quoted the relevant part below : )</p>
<hr>
<p>You can get a UInt32Array view on your ImageData with :</p>
<pre><code>var myGetImageData = myTempCanvas.getImageData(0,0,sizeX, sizeY);
var sourceBuffer32 = new Uint32Array(myGetImageData.data.buffer);
</code></pre>
<p>then sourceBuffer32[i] contains Red, Green, Blue, and transparency packed into one unsigned 32 bit int. Compare it to 0 to know if pixel is non-black ( != (0,0,0,0) )</p>
<p>OR you can be more precise with a Uint8Array view : </p>
<pre><code>var myGetImageData = myTempCanvas.getImageData(0,0,sizeX, sizeY);
var sourceBuffer8 = new Uint8Array(myGetImageData.data.buffer);
</code></pre>
<p>If you deal only with shades of grey, then R=G=B, so watch for </p>
<pre><code>sourceBuffer8[4*i]>Threshold
</code></pre>
<p>and you can set the i-th pixel to black in one time using the UInt32Array view : </p>
<pre><code>sourceBuffer32[i]=0xff000000;
</code></pre>
<p>set to any color/alpha with : </p>
<pre><code>sourceBuffer32[i]= (A<<24) |Β (B<<16) | (G<<8) | R ;
</code></pre>
<p>or just to any color : </p>
<pre><code>sourceBuffer32[i]= 0xff000000 |Β (B<<16) | (G<<8) | R ;
</code></pre>
<p>(be sure R is rounded).</p>
<hr>
<p>Listening to @Ken's comment, yes endianness can be an issue when you start fighting with bits 32 at a time.
Most computer are using little-endian, so RGBA becomes ABGR when dealing with them 32bits a once.<br>
Since it is the vast majority of systems, if dealing with 32bit integer assume this is the case,
and you can -for compatibility- reverse your computation before writing the 32 bits results on Big endian systems.
Let me share those two functions :</p>
<pre><code>function isLittleEndian() {
// from TooTallNate / endianness.js. https://gist.github.com/TooTallNate/4750953
var b = new ArrayBuffer(4);
var a = new Uint32Array(b);
var c = new Uint8Array(b);
a[0] = 0xdeadbeef;
if (c[0] == 0xef) { isLittleEndian = function() {return true }; return true; }
if (c[0] == 0xde) { isLittleEndian = function() {return false }; return false; }
throw new Error('unknown endianness');
}
function reverseUint32 (uint32) {
var s32 = new Uint32Array(4);
var s8 = new Uint8Array(s32.buffer);
var t32 = new Uint32Array(4);
var t8 = new Uint8Array(t32.buffer);
reverseUint32 = function (x) {
s32[0] = x;
t8[0] = s8[3];
t8[1] = s8[2];
t8[2] = s8[1];
t8[3] = s8[0];
return t32[0];
}
return reverseUint32(uint32);
};
</code></pre> |
19,646,719 | Eclipse command line arguments | <p>I understand how to run my application with command line arguments using the run configuration menu.</p>
<p>The problem I have is that no matter what I update these command line arguments to, eclipse does not reflect these updates when I execute the code.</p>
<p>so far I have set the arguments to:</p>
<pre><code>test1.txt test2.txt dfs
</code></pre>
<p>and this will print:</p>
<pre><code>args[0] = test1.txt
args[1] = test2.txt
args[2] = dfs
</code></pre>
<p><strong>but if I update the arguments and re-run it, the arguments won't update</strong></p>
<p>How can I "reset" the arguments and re-run the application using the updated arguments.</p>
<p>The above and below both function correctly and it was in fact eclipse that was causing me issues. The problem was resolved with a simple restart of eclipse.</p>
<p>Thanks all.</p> | 19,648,592 | 4 | 4 | null | 2013-10-28 23:07:22.973 UTC | 8 | 2019-05-01 10:29:57.897 UTC | 2013-10-29 20:03:43.897 UTC | user2896743 | null | user2896743 | null | null | 1 | 25 | java|eclipse | 88,438 | <ol>
<li>Click on <strong>Run</strong> -> <strong>Run Configurations</strong> </li>
<li>Click on <strong>Arguments</strong> tab </li>
<li>In <strong>Program Arguments</strong> section , Enter your arguments. </li>
<li>Click <strong>Apply</strong> </li>
</ol>
<p><em>It is sure to work cause I tried it in mine right before I wrote this answer</em></p> |
17,525,957 | Assigning 'wrap_content' or '-2' to dimension | <p>I want to create a dimension that would be equal to 'wrap_content' constant.</p>
<p>So according to <a href="http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html" rel="noreferrer">developer.android.com Reference</a> I write:</p>
<pre><code><dimen name="horizontal_border_height">-2</dimen>
</code></pre>
<p>But ADT says:</p>
<blockquote>
<p>Error: Integer types not allowed (at 'horizontal_border_height' with value '-2')</p>
</blockquote>
<p>Asigning 'wrap_content' value generates error too.</p>
<p>What am I doing wrong? Any ideas how to make it work?</p> | 34,176,327 | 6 | 1 | null | 2013-07-08 11:54:13.133 UTC | 3 | 2016-12-30 08:12:27.203 UTC | 2014-02-24 13:46:01.73 UTC | null | 56,285 | null | 2,552,829 | null | 1 | 36 | android|android-layout|adt|dimensions | 9,910 | <p>To use wrap_content or match_parent you need to create following items in dimens.xml file:</p>
<pre><code><item name="match_parent" format="integer" type="dimen">-1</item>
<item name="wrap_content" format="integer" type="dimen">-2</item>
</code></pre>
<p>Then you can simply use it like this:</p>
<pre><code><dimen name="layout_height">@dimen/match_parent</dimen>
<dimen name="layout_width">@dimen/wrap_content</dimen>
</code></pre> |
17,596,186 | Interface with generic parameter vs Interface with generic methods | <p>Let's say I have such interface and concrete implementation</p>
<pre><code>public interface IMyInterface<T>
{
T My();
}
public class MyConcrete : IMyInterface<string>
{
public string My()
{
return string.Empty;
}
}
</code></pre>
<p>So I create MyConcrete implementation for <code>strings</code>, I can have one more concrete implementation for <code>int</code>. And that's ok. But let's say, that I want to do the same thing, but with generic methods, so I have</p>
<pre><code>public interface IMyInterface2
{
T My<T>();
}
public class MyConcrete2 : IMyInterface2
{
public string My<string>()
{
throw new NotImplementedException();
}
}
</code></pre>
<p>So I have the same <code>IMyInterface2</code>, but which defines generic behavior by means of <code>T My<T>()</code>. In my concrete class I want to implement <code>My</code> behavior, but for concrete data type - <code>string</code>. But C# doesn't allow me to do that. </p>
<p>My question is why I cannot do that?
In other words, if i can create concrete implementation of <code>MyInterface<T></code> as <code>MyClass : MyInterface<string></code> and stop genericness at this point, why I can't do that with generic method - <code>T My<T>()</code>?</p> | 17,596,233 | 4 | 1 | null | 2013-07-11 14:32:09.087 UTC | 13 | 2019-10-04 16:07:40.01 UTC | 2017-01-11 03:33:06.54 UTC | null | 1,258,525 | null | 374,320 | null | 1 | 46 | c#|.net|clr | 73,826 | <p>Your generic method implementation has to be generic as well, so it has to be:</p>
<pre><code>public class MyConcrete2 : IMyInterface2
{
public T My<T>()
{
throw new NotImplementedException();
}
}
</code></pre>
<p>Why you can't do <code>My<string>()</code> here? Because interface contract needs a method, that could be called with any type parameter <code>T</code> and you have to fulfill that contract.</p>
<p><strong>Why you can't <em>stop genericness in this point</em>?</strong> Because it would cause situations like following:</p>
<p><em>Class declarations:</em></p>
<pre><code>public interface IMyInterface2
{
T My<T>(T value);
}
public class MyClass21 : IMyInterface2
{
public string My<string>(string value) { return value; }
}
public class MyClass22 : IMyInterface2
{
public int My<int>(int value) { return value; }
}
</code></pre>
<p><em>Usage:</em></p>
<pre><code>var item1 = new MyClass21();
var item2 = new MyClass22();
// they both implement IMyInterface2, so we can put them into list
var list = new List<IMyInterface2>();
list.Add(item1);
list.Add(item2);
// iterate the list and call My method
foreach(IMyInterface2 item in list)
{
// item is IMyInterface2, so we have My<T>() method. Choose T to be int and call with value 2:
item.My<int>(2);
// how would it work with item1, which has My<string> implemented?
}
</code></pre> |
17,192,776 | Get value of day month from Date object in Android? | <p>By using this code :</p>
<pre><code>SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(dtStart);
return date;
</code></pre>
<p>I have converted the String Date by Date Object and get the value:</p>
<blockquote>
<p>Sun Feb 17 07:00:00 GMT 2013</p>
</blockquote>
<p>Now I want to extract day (Sunday/Monday) and month from here.</p> | 17,192,941 | 10 | 2 | null | 2013-06-19 13:39:50.03 UTC | 21 | 2021-10-10 05:46:00.623 UTC | 2019-05-27 11:59:25.33 UTC | null | 472,495 | null | 2,380,316 | null | 1 | 61 | java|android|date|simpledateformat | 102,497 | <pre class="lang-java prettyprint-override"><code>import android.text.format.DateFormat;
String dayOfTheWeek = (String) DateFormat.format("EEEE", date); // Thursday
String day = (String) DateFormat.format("dd", date); // 20
String monthString = (String) DateFormat.format("MMM", date); // Jun
String monthNumber = (String) DateFormat.format("MM", date); // 06
String year = (String) DateFormat.format("yyyy", date); // 2013
</code></pre> |
36,908,994 | Using sprintf with std::string in C++ | <p>I am using <code>sprintf</code> function in C++ 11, in the following way:</p>
<pre><code>std::string toString()
{
std::string output;
uint32_t strSize=512;
do
{
output.reserve(strSize);
int ret = sprintf(output.c_str(), "Type=%u Version=%u ContentType=%u contentFormatVersion=%u magic=%04x Seg=%u",
INDEX_RECORD_TYPE_SERIALIZATION_HEADER,
FORAMT_VERSION,
contentType,
contentFormatVersion,
magic,
segmentId);
strSize *= 2;
} while (ret < 0);
return output;
}
</code></pre>
<p>Is there a better way to do this, than to check every time if the reserved space was enough? For future possibility of adding more things.</p> | 36,909,057 | 7 | 3 | null | 2016-04-28 08:16:15.773 UTC | 2 | 2021-09-29 21:39:27.367 UTC | 2017-12-25 11:43:37.79 UTC | null | 63,550 | null | 2,979,856 | null | 1 | 16 | c++|string|c++11 | 39,551 | <p>Your construct -- <em>writing</em> into the buffer received from <code>c_str()</code> -- is <strong>undefined behaviour</strong>, even if you checked the string's capacity beforehand. (The return value is a pointer to <strong>const</strong> char, and the function itself marked <strong>const</strong>, for a reason.)</p>
<p>Don't mix C and C++, <em>especially</em> not for writing into internal object representation. (That is breaking very basic OOP.) Use C++, for type safety and not running into conversion specifier / parameter mismatches, if for nothing else.</p>
<pre><code>std::ostringstream s;
s << "Type=" << INDEX_RECORD_TYPE_SERIALIZATION_HEADER
<< " Version=" << FORMAT_VERSION
// ...and so on...
;
std::string output = s.str();
</code></pre>
<p>Alternative:</p>
<pre><code>std::string output = "Type=" + std::to_string( INDEX_RECORD_TYPE_SERIALIZATION_HEADER )
+ " Version=" + std::to_string( FORMAT_VERSION )
// ...and so on...
;
</code></pre> |
18,375,506 | How to use definitions in JSON schema (draft-04) | <p>The rest service response I am working with is similar to following example, I have only included 3 fields here but there are many more:</p>
<pre><code>{
"results": [
{
"type": "Person",
"name": "Mr Bean",
"dateOfBirth": "14 Dec 1981"
},
{
"type": "Company",
"name": "Pi",
"tradingName": "Pi Engineering Limited"
}
]
}
</code></pre>
<p>I want to write a JSON schema file for above (draft-04) which will explicitly specify that:</p>
<pre><code>if type == Person then list of required properties is ["type", "name", "dateOfBirth", etc]
OR
if type == "Company" then list of required properties is ["type", "name", "tradingName", etc]
</code></pre>
<p>However am unable to find any documentation or example of how to do it.</p>
<p>Currently my JSON schema looks like following:</p>
<pre><code>{
"$schema": "http://json-schema.org/draft-04/schema",
"type": "object",
"required": ["results" ],
"properties": {
"results": {
"type": "array",
"items": {
"type": "object",
"required": ["type", "name"],
"properties": {
"type": { "type": "string" },
"name": { "type": "string" },
"dateOfBirth": { "type": "string" },
"tradingName": { "type": "string" }
}
}
}
}
}
</code></pre>
<p>Any pointers/examples of how I should handle this.</p> | 18,384,131 | 2 | 4 | null | 2013-08-22 08:41:36.97 UTC | 13 | 2017-10-09 20:13:09.987 UTC | 2017-10-09 20:13:09.987 UTC | null | 1,300,562 | null | 2,279,187 | null | 1 | 21 | json|jsonschema | 20,984 | <p>I think the recommended approach is the one shown in <a href="http://json-schema.org/example2.html" rel="noreferrer">Json-Schema web, Example2</a>. You need to use an enum to select schemas "by value". In your case it would be something like:</p>
<pre><code>{
"type": "object",
"required": [ "results" ],
"properties": {
"results": {
"type": "array",
"items": {
"oneOf": [
{ "$ref": "#/definitions/person" },
{ "$ref": "#/definitions/company" }
]
}
}
},
"definitions": {
"person": {
"properties": {
"type": { "enum": [ "person" ] },
"name": {"type": "string" },
"dateOfBirth": {"type":"string"}
},
"required": [ "type", "name", "dateOfBirth" ],
"additionalProperties": false
},
"company": {
"properties": {
"type": { "enum": [ "company" ] },
. . .
}
}
}
}
</code></pre> |
18,645,759 | tail-like continuous ls (file list) | <p>I am monitoring the new files created in a folder in linux. Every now and then I issue an "ls -ltr" in it. But I wish there was a program/script that would automatically print it, and only the latest entries. I did a short while loop to list it, but it would repeat the entries that were not new and it would keep my screen rolling up when there were no new files. I've learned about "watch", which does show what I want and refreshes every N seconds, but I don't want a ncurses interface, I'm looking for something like tail:</p>
<ul>
<li>continuous</li>
<li>shows only the new stuff</li>
<li>prints in my terminal, so I can run it in the background and do other things and see the output every now and then getting mixed with whatever I'm doing :D</li>
</ul>
<p>Summarizing: get the input, compare to a previous input, output only what is new.
Something that do that doesn't sound like such an odd tool, I can see it being used for other situations also, so I would expect it to already exist, but I couldn't find anything. Suggestions?</p> | 18,645,921 | 3 | 4 | null | 2013-09-05 20:52:55.59 UTC | 8 | 2016-11-17 21:52:19.257 UTC | null | null | null | null | 2,193,235 | null | 1 | 21 | linux|shell|ls | 16,723 | <p>If you have access to <code>inotifywait</code> (available from the inotify-tools package if you are on Debian/Ubuntu) you could write a script like this:</p>
<pre><code>#!/bin/bash
WATCH=/tmp
inotifywait -q -m -e create --format %f $WATCH | while read event
do
ls -ltr $WATCH/$event
done
</code></pre>
<p>This is a one-liner that won't give you the same information that <code>ls</code> does, but it will print out the filename:</p>
<pre><code>inotifywait -q -m -e create --format %w%f /some/directory
</code></pre> |
25,951,968 | Open and close new tab with Selenium WebDriver in OS X | <p>I'm using the Firefox Webdriver in Python 2.7 on Windows to simulate opening (<kbd>Ctrl</kbd>+<kbd>t</kbd>) and closing (<kbd>Ctrl</kbd> + <kbd>w</kbd>) a new tab.</p>
<p>Here's my code:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
browser.get('https://www.google.com')
main_window = browser.current_window_handle
# open new tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
browser.get('https://www.yahoo.com')
# close tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
</code></pre>
<p>How to achieve the same on a Mac?
Based on <a href="https://stackoverflow.com/questions/17547473/how-to-open-a-new-tab-using-selenium-webdriver#comment32151880_17558909">this comment</a> one should use <code>browser.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')</code> to open a new tab but I don't have a Mac to test it and what about the equivalent of <code>Ctrl-w</code>?</p>
<p>Thanks!</p> | 27,975,093 | 5 | 2 | null | 2014-09-20 18:23:04.387 UTC | 4 | 2021-02-03 12:27:43.3 UTC | 2018-08-30 18:11:48 UTC | null | 7,901,720 | null | 2,314,737 | null | 1 | 16 | python|macos|selenium | 54,169 | <p>There's nothing easier and clearer than just running JavaScript.</p>
<p>Open new tab:
<code>driver.execute_script("window.open('');")</code></p> |
25,911,287 | Change colour of small triangle on spinner in android | <p><img src="https://i.stack.imgur.com/5nzdR.jpg" alt="enter image description here"></p>
<p>How can I change the colour of small triangle at the bottom right corner of spinner like shown in the image?
It is showing default grey colour right now. like this</p>
<p><img src="https://i.stack.imgur.com/ZJwWm.jpg" alt="enter image description here"></p> | 25,911,612 | 9 | 4 | null | 2014-09-18 11:19:01.633 UTC | 17 | 2022-08-15 20:32:08.967 UTC | null | null | null | null | 1,542,624 | null | 1 | 60 | android|colors|android-spinner | 53,286 | <p>To get the correct images, you can go to <a href="http://romannurik.github.io/AndroidAssetStudio/" rel="noreferrer">Android Asset Studio</a> site and choose the <a href="http://android-holo-colors.com/" rel="noreferrer">Android Holo Colors Generator</a>. This will create all the assets you might need, including the "triangle". It also generates the XML files that implement the changes.</p>
<hr>
<p>Here are the example XML files:</p>
<p>Custom Color:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="apptheme_color">#33b5e5</color>
</resources>
</code></pre>
<p>Custom Spinner Style:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!-- Generated with http://android-holo-colors.com -->
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="SpinnerAppTheme" parent="android:Widget.Spinner">
<item name="android:background">@drawable/apptheme_spinner_background_holo_light</item>
<item name="android:dropDownSelector">@drawable/apptheme_list_selector_holo_light</item>
</style>
<style name="SpinnerDropDownItemAppTheme" parent="android:Widget.DropDownItem.Spinner">
<item name="android:checkMark">@drawable/apptheme_btn_radio_holo_light</item>
</style>
</resources>
</code></pre>
<p>Custom Application Theme:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!-- Generated with http://android-holo-colors.com -->
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="AppTheme" parent="@style/_AppTheme"/>
<style name="_AppTheme" parent="Theme.AppCompat.Light">
<item name="android:spinnerStyle">@style/SpinnerAppTheme</item>
<item name="android:spinnerDropDownItemStyle">@style/SpinnerDropDownItemAppTheme</item>
</style>
</resources>
</code></pre>
<hr>
<p>As you can see, there are also many drawables that are referenced by these styles.</p>
<p>Here is the one specific to the "triangle" you want to change:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false"
android:drawable="@drawable/apptheme_spinner_disabled_holo_light" />
<item android:state_pressed="true"
android:drawable="@drawable/apptheme_spinner_pressed_holo_light" />
<item android:state_pressed="false" android:state_focused="true"
android:drawable="@drawable/apptheme_spinner_focused_holo_light" />
<item android:drawable="@drawable/apptheme_spinner_default_holo_light" />
</selector>
</code></pre>
<p>I don't think this is the right place to list every file completely, since you can get them all directly from the referenced tool.</p>
<hr>
<p><strong>Note:</strong> this is the way to theme your whole app so that all spinners are updated to the custom style. </p>
<p>If you are looking for a quick and dirty way to change just one spinner, then check out that article referenced by Ricky in his comment:</p>
<ul>
<li><a href="http://www.synchronoussoft.net/blog/tom-gersic" rel="noreferrer">Android: Custom Spinners by Tom Gersic</a></li>
</ul>
<p>I recommend reading it anyway, because it explains the process very well, and will help you to understand the rest of my answer.</p> |
9,292,954 | How to make a copy of a file in android? | <p>In my app I want to save a copy of a certain file with a different name (which I get from user)</p>
<p>Do I really need to open the contents of the file and write it to another file?</p>
<p>What is the best way to do so?</p> | 9,293,885 | 12 | 3 | null | 2012-02-15 11:59:45.797 UTC | 44 | 2022-07-19 16:06:10.063 UTC | 2014-12-31 15:29:27.553 UTC | null | 675,552 | null | 832,949 | null | 1 | 209 | java|android | 183,519 | <p>To copy a file and save it to your destination path you can use the method below.</p>
<pre><code>public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
</code></pre>
<p>On API 19+ you can use Java Automatic Resource Management:</p>
<pre><code>public static void copy(File src, File dst) throws IOException {
try (InputStream in = new FileInputStream(src)) {
try (OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}
</code></pre> |
9,201,128 | How to map a ResultSet with unknown amount of columns to a List and display it in a HTML table? | <p>I have created a Database Application using Netbeans, GlassFish and JavaDB. Now my controller Servlet code executes some dynamic SQL queries and get back a Result Set (or I can ahange toString). Now, how can I show the returned Result Set in a tabular format ( I have no idea about structure of result set). Can anybody help me about this ?</p> | 9,201,946 | 2 | 4 | null | 2012-02-08 20:46:15.523 UTC | 9 | 2012-02-08 21:44:22.287 UTC | 2012-02-08 21:44:22.287 UTC | null | 157,882 | null | 1,060,880 | null | 1 | 11 | java|jsp|servlets|jdbc | 24,564 | <p>You can use <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Map.html" rel="noreferrer"><code>Map<String, Object></code></a> to represent a "dynamic" row, which is <a href="https://stackoverflow.com/questions/2117557/how-to-iterate-an-arraylist-inside-a-hashmap-using-jstl">iterable</a> in <code><c:forEach></code>. You can use <a href="http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSetMetaData.html" rel="noreferrer"><code>ResultSetMetaData</code></a> to collect information about the columns such as the <a href="http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSetMetaData.html#getColumnCount%28%29" rel="noreferrer">column count</a> and the <a href="http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSetMetaData.html#getColumnLabel%28int%29" rel="noreferrer">column labels</a>.</p>
<p>So, this mapping should do:</p>
<pre><code>List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
Map<String, Object> columns = new LinkedHashMap<String, Object>();
for (int i = 1; i <= columnCount; i++) {
columns.put(metaData.getColumnLabel(i), resultSet.getObject(i));
}
rows.add(columns);
}
</code></pre>
<p>You can display it in JSP as follows:</p>
<pre class="lang-html prettyprint-override"><code><table>
<thead>
<tr>
<c:forEach items="${rows[0]}" var="column">
<td><c:out value="${column.key}" /></td>
</c:forEach>
</tr>
</thead>
<tbody>
<c:forEach items="${rows}" var="columns">
<tr>
<c:forEach items="${columns}" var="column">
<td><c:out value="${column.value}" /></td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
</code></pre> |
18,246,053 | How can I create a link to a local file on a locally-run web page? | <p>I'd like to have an html file that organizes certain files scattered throughout my hard drive. For example, I have two files that I would link to:</p>
<ul>
<li><code>C:\Programs\sort.mw</code></li>
<li><code>C:\Videos\lecture.mp4</code></li>
</ul>
<p>The problem is that I'd like the links to function as a shortcut to the file. I've tried the following:</p>
<pre><code><a href="C:\Programs\sort.mw">Link 1</a>
<a href="C:\Videos\lecture.mp4">Link 2</a>
</code></pre>
<p>... but the first link does nothing and the second link opens the file in Chrome, not VLC.</p>
<p>My questions are:</p>
<ol>
<li><p>Is there a way to adjust my HTML to treat the links as shortcuts to the files?</p></li>
<li><p>If there isn't a way to adjust the HTML, are there any other ways to neatly link to files scattered throughout the hard drive?</p></li>
</ol>
<p>My computer runs Windows 7 and my web browser is Chrome.</p> | 18,246,357 | 5 | 0 | null | 2013-08-15 03:51:52.287 UTC | 43 | 2020-11-30 15:36:54.45 UTC | 2013-08-15 04:42:51.987 UTC | null | 254,830 | null | 2,684,663 | null | 1 | 191 | html|anchor|local-files | 830,540 | <p>You need to use the <code>file:///</code> protocol (yes, that's three slashes) if you want to link to local files.</p>
<pre class="lang-html prettyprint-override"><code><a href="file:///C:\Programs\sort.mw">Link 1</a>
<a href="file:///C:\Videos\lecture.mp4">Link 2</a>
</code></pre>
<p><strong>These will never open the file in your local applications automatically.</strong> That's for security reasons which I'll cover in the last section. If it opens, it will only ever open in the browser. If your browser can display the file, it will, otherwise it will probably ask you if you want to download the file.</p>
<h2>You cannot cross from http(s) to the file protocol</h2>
<p>Modern versions of many browsers (e.g. Firefox and Chrome) will refuse to cross from the http(s) protocol to the file protocol to prevent malicious behaviour.</p>
<p>This means a webpage hosted on a website somewhere will never be able to link to files on your hard drive. You'll need to open your webpage locally using the file protocol if you want to do this stuff at all.</p>
<h2>Why does it get stuck without <code>file:///</code>?</h2>
<p><a href="http://en.wikipedia.org/wiki/Uniform_resource_locator#Syntax" rel="noreferrer">The first part of a URL</a> is the protocol. A protocol is a few letters, then a colon and two slashes. <code>HTTP://</code> and <code>FTP://</code> are valid protocols; <code>C:/</code> isn't and I'm pretty sure it doesn't even properly resemble one.</p>
<p><code>C:/</code> also isn't a valid web address. The browser could assume it's meant to be <code>http://c/</code> with a blank port specified, but that's going to fail.</p>
<p>Your browser may not assume it's referring to a local file. It has little reason to make that assumption because webpages generally don't try to link to peoples' local files.</p>
<p>So if you want to access local files: tell it to use the file protocol.</p>
<h2>Why three slashes?</h2>
<p>Because it's part of the <a href="http://en.wikipedia.org/wiki/File_URI_scheme" rel="noreferrer">File URI scheme</a>. You have the option of specifying a host after the first two slashes. If you skip specifying a host it will just assume you're referring to a file on your own PC. This means <code>file:///C:/etc</code> is a shortcut for <code>file://localhost/C:/etc</code>.</p>
<h2>These files will still open in your browser and that is good</h2>
<p>Your browser will respond to these files the same way they'd respond to the same file anywhere on the internet. These files <strong>will not</strong> open in your default file handler (e.g. MS Word or VLC Media Player), and you <strong>will not</strong> be able to do anything like ask File Explorer to open the file's location.</p>
<p><strong>This is an extremely good thing for your security.</strong></p>
<p>Sites in your browser cannot interact with your operating system very well. If a good site could tell your machine to open <em>lecture.mp4</em> in <em>VLC.exe</em>, a malicious site could tell it to open <em>virus.bat</em> in <em>CMD.exe</em>. Or it could just tell your machine to run a few <em>Uninstall.exe</em> files or open File Explorer a million times.</p>
<p>This may not be convenient for you, but HTML and browser security weren't really designed for what you're doing. If you want to be able to open <em>lecture.mp4</em> in <em>VLC.exe</em> consider writing a desktop application instead.</p> |
15,118,524 | Get audio from an html5 video | <p>Is it possible to get the audio from an mp4 or webm video element in HTML5?</p>
<p>I'm trying to use <a href="https://github.com/corbanbrook/dsp.js" rel="noreferrer">https://github.com/corbanbrook/dsp.js</a> to calculate FFTs for audio, however, I only have the mp4 and webm videos.</p> | 15,286,719 | 2 | 0 | null | 2013-02-27 17:34:18.307 UTC | 12 | 2017-03-21 17:38:15.707 UTC | 2013-02-27 17:39:21.97 UTC | null | 493,034 | null | 493,034 | null | 1 | 17 | javascript|html|html5-video|html5-audio | 12,734 | <p>Not sure if this answers your question but you can run the audio of the video through the Web Audio API node graph. The code below can be demonstrated by changing the gain and filter parameters. I only tested this on Chrome.</p>
<pre><code><!DOCTYPE html>
<meta charset="UTF-8">
<title></title>
<body>
</body>
<script>
var video = document.createElement("video");
video.setAttribute("src", "ourMovie.mov");
video.controls = true;
video.autoplay = true;
document.body.appendChild(video);
var context = new webkitAudioContext();
var gainNode = context.createGain();
gainNode.gain.value = 1; // Change Gain Value to test
filter = context.createBiquadFilter();
filter.type = 2; // Change Filter type to test
filter.frequency.value = 5040; // Change frequency to test
// Wait for window.onload to fire. See crbug.com/112368
window.addEventListener('load', function(e) {
// Our <video> element will be the audio source.
var source = context.createMediaElementSource(video);
source.connect(gainNode);
gainNode.connect(filter);
filter.connect(context.destination);
}, false);
</script>
</code></pre>
<p>The above code is a modified version of this :
<a href="http://updates.html5rocks.com/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs">http://updates.html5rocks.com/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs</a></p>
<p>I simply replaced the audio element with the video element.</p> |
15,020,428 | Are there any advantages of using Rank2Types in favor of RankNTypes? | <p>As far as I know, a decidable type checking algorithm exists (only) for rank-2 types. Does GHC use somehow this fact, and does it have any practical implications?</p>
<p>Is there also a notion of principal types for rank-2 types, and a type inference algorithm? If yes, does GHC use it?</p>
<p>Are there any other advantages of rank-2 types over rank-<em>n</em> types?</p> | 15,020,571 | 2 | 0 | null | 2013-02-22 09:07:35.227 UTC | 1 | 2013-02-22 09:28:25.243 UTC | null | null | null | null | 1,333,025 | null | 1 | 29 | haskell|ghc|type-inference|higher-rank-types | 973 | <p><code>Rank2Types</code> is a <a href="http://www.mail-archive.com/[email protected]/msg43050.html" rel="noreferrer">synonym</a> for <code>RankNTypes</code>. So <em>right now</em> there are no advantages of rank-2 over rank-n.</p> |
15,310,782 | how to select distinct value from multiple tables | <p>I need to get distinct values from 3 tables.</p>
<p>When I perform this code:</p>
<pre><code>select DISTINCT(city) from a,b,c
</code></pre>
<p>I get an error which says that my column 'city' is ambiguous.</p>
<p>Also I have tried this:</p>
<pre><code>select DISTINCT(city) from a NATURAL JOIN b NATURAL JOIN c
</code></pre>
<p>With this code I receive nothing from my tables.</p>
<p>Let me show you on the example of what I am trying to do:</p>
<pre><code>TABLE A TABLE B TABLE C
id | city id | city id | city
1 | Krakow 1 | Paris 1 | Paris
2 | Paris 2 | London 2 | Krakow
3 | Paris 3 | Oslo
4 | Rome
</code></pre>
<p>And I need to get result like this</p>
<pre><code>RESULTS
city
----
Krakow
Paris
Rome
London
Oslo
</code></pre>
<p>Order of the cities is not important to me I just need to have them all, and there should be only one representation of each city.</p>
<p>Any idea? I was thinking to use <code>id's</code> in the <code>JOIN</code> but there are not connected so I can't use that.</p> | 15,310,790 | 2 | 0 | null | 2013-03-09 12:41:00.72 UTC | 6 | 2018-05-01 19:31:56.51 UTC | 2018-01-16 05:02:48.827 UTC | null | 1,905,949 | null | 1,182,591 | null | 1 | 34 | mysql|sql|database | 71,415 | <p>The <a href="https://www.w3schools.com/sql/sql_union.asp" rel="noreferrer"><code>UNION</code></a> keyword will return <code>unique</code> records on the result list. When specifying <code>ALL</code> (<a href="https://www.w3schools.com/sql/sql_union.asp" rel="noreferrer"><em>UNION ALL</em></a>) will keep duplicates on the result set, which the OP don't want.</p>
<pre><code>SELECT city FROM tableA
UNION
SELECT city FROM tableB
UNION
SELECT city FROM tableC
</code></pre>
<ul>
<li><a href="http://www.sqlfiddle.com/#!2/442ef/1" rel="noreferrer">SQLFiddle Demo</a></li>
</ul>
<p>RESULT</p>
<pre><code>ββββββββββ
β CITY β
β βββββββββ£
β Krakow β
β Paris β
β Rome β
β London β
β Oslo β
ββββββββββ
</code></pre> |
15,357,923 | Intellij IDEA: view class methods in their real order | <p>I am switching to IntelliJ IDEA from Eclipse. Currently I am using IDEA v 12.0.4.</p>
<p>In Eclipse when you called Class Outline view (<kbd>Ctrl</kbd> + <kbd>O</kbd>) you saw methods in the order they are declared in the class. While the similar File Structure view in IDEA (<kbd>Ctrl</kbd> + <kbd>F12</kbd>) lists methods in the alphabetical order which I find less convenient for myself in some cases.</p>
<p>Is there a way in IDEA's File Structure popup to see class methods listed in the order they appear in the class? Ideally I would like to have a possibility to switch from alphabetical to natural ordering.</p> | 15,358,074 | 3 | 2 | null | 2013-03-12 09:50:38.133 UTC | 5 | 2018-10-08 08:25:50.317 UTC | 2015-01-25 17:11:33.747 UTC | null | 3,885,376 | null | 1,936,698 | null | 1 | 43 | intellij-idea | 16,392 | <p>Use the <strong>"Structure" tool window</strong> ( <kbd>Alt</kbd>+<kbd>7</kbd> on Windows, <kbd>β</kbd>+<kbd>7</kbd> on OS X) instead of the "File structure" popup.</p> |
15,035,861 | (Deprecated) Fragment onOptionsItemSelected not being called | <p><strong>EDIT:</strong>
This question was for the deprecated sherlock action bar. Android support library should be used instead now</p>
<p>I have added an action bar menu option called share for my <code>fragment</code> which appears but the selection event is not being caught </p>
<p>I am adding it like this</p>
<pre><code>@Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
MenuItem item = menu.add(0, 7,0, R.string.share);
item.setIcon(R.drawable.social_share).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
</code></pre>
<p>Trying to capture it in both the <code>fragment</code> and the <code>fragment activity</code> like</p>
<pre><code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 7:
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, "I'm being sent!!");
startActivity(Intent.createChooser(share, "Share Text"));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>and I have <code>setHasOptionsMenu(true);</code> in the <code>onCreate()</code>.</p> | 15,073,577 | 10 | 0 | null | 2013-02-23 01:13:24.863 UTC | 27 | 2022-07-20 00:10:14.593 UTC | 2016-08-05 16:26:41.91 UTC | null | 2,065,587 | null | 1,634,451 | null | 1 | 82 | android|android-fragments|android-actionbar | 66,048 | <p>Edit for actionbar sherlock use</p>
<p>I had to use </p>
<pre><code>public boolean onMenuItemSelected(int featureId, MenuItem item) {
</code></pre>
<p>in the main activity to capture the menu item </p> |
48,369,599 | JSX Element type 'void' is not a constructor function for JSX elements | <p>What am I doing wrong here?</p>
<p>It doesn't like the way I am calling <code>Items</code></p>
<pre><code>import React, { Component } from 'react';
import { Link } from "react-router-dom";
interface LinkedItemProps {
icon: string;
title: string;
}
export const Items = ({icon, title}: LinkedItemProps) => {
<div>
<div className="nav-menu-link-icon">
{icon}
</div>
<div className="nav-menu-link-label">
{title}
</div>
</div>
}
export default class LinkedItems extends React.Component<any, any> {
render() {
return (
<Link
to={this.props.link}
title={this.props.title}
onClick={this.props.afterClick}
>
<Items icon={this.props.icon} title={this.props.title} /> //error
</Link>
)}
}
</code></pre>
<p>P.S. Thank you <a href="https://stackoverflow.com/users/5928186/shubham-khatri">Shubham Khatri</a> for marking this as a duplicate of a question that does not remotely resemble what I asked.</p> | 48,369,626 | 1 | 6 | null | 2018-01-21 17:23:47.257 UTC | 6 | 2020-02-04 15:58:29.573 UTC | 2020-02-04 15:58:29.573 UTC | null | 3,241,128 | null | 4,054,527 | null | 1 | 34 | javascript|reactjs | 24,879 | <p><code>Items</code> is an arrow function with <code>{}</code> which means you have to explicitly give it a <code>return</code> statement:</p>
<pre><code>export const Items = ({icon, title}: LinkedItemProps) => {
return ( // <------ must return here
<div>
<div className="nav-menu-link-icon">
{icon}
</div>
<div className="nav-menu-link-label">
{title}
</div>
</div>
)
}
</code></pre>
<p>If you do not, then the <code>Items</code> just returns <code>undefined</code> which is an empty value and thus </p>
<pre><code>JSX Element type 'void' is not a constructor function for JSX elements"
</code></pre>
<p>For a bit cleaner code, you can replace the <code>{}</code> with <code>()</code> completely:</p>
<pre><code>export const Items = ({icon, title}: LinkedItemProps) => (
<div>
<div className="nav-menu-link-icon">
{icon}
</div>
<div className="nav-menu-link-label">
{title}
</div>
</div>
)
</code></pre> |
9,439,256 | How can I handle R CMD check "no visible binding for global variable" notes when my ggplot2 syntax is sensible? | <p><em>EDIT: Hadley Wickham points out that I misspoke. R CMD check is throwing NOTES, not Warnings. I'm terribly sorry for the confusion. It was my oversight.</em></p>
<h2>The short version</h2>
<p><code>R CMD check</code> throws this note every time I use <a href="https://github.com/briandk/granovaGG/blob/dev/R/granovagg.contr.R#L254-265" rel="noreferrer">sensible plot-creation syntax</a> in ggplot2:</p>
<pre><code>no visible binding for global variable [variable name]
</code></pre>
<p>I understand why R CMD check does that, but it seems to be criminalizing an entire vein of otherwise sensible syntax. I'm not sure what steps to take to get my package to pass <code>R CMD check</code> and get admitted to CRAN.</p>
<h2>The background</h2>
<p>Sascha Epskamp previously posted on <a href="https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check">essentially the same issue</a>. The difference, I think, is that <code>subset()</code>'s manpage <a href="https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check/8096456#8096456">says it's designed for interactive use</a>.</p>
<p>In my case, the issue is not over <code>subset()</code> but over a core feature of <code>ggplot2</code>: the <code>data =</code> argument.</p>
<h2>An example of code I write that generates these notes</h2>
<p>Here's <a href="https://github.com/briandk/granovaGG/blob/dev/R/granovagg.contr.R#L254-265" rel="noreferrer">a sub-function</a> in <a href="https://github.com/briandk/granovaGG" rel="noreferrer">my package</a> that adds points to a plot:</p>
<pre><code>JitteredResponsesByContrast <- function (data) {
return(
geom_point(
aes(
x = x.values,
y = y.values
),
data = data,
position = position_jitter(height = 0, width = GetDegreeOfJitter(jj))
)
)
}
</code></pre>
<p><code>R CMD check</code>, on parsing this code, will say</p>
<pre><code>granovagg.contr : JitteredResponsesByContrast: no visible binding for
global variable 'x.values'
granovagg.contr : JitteredResponsesByContrast: no visible binding for
global variable 'y.values'
</code></pre>
<h2>Why R CMD check is right</h2>
<p>The check is technically correct. <code>x.values</code> and <code>y.values</code></p>
<ul>
<li>Aren't defined locally in the function <code>JitteredResponsesByContrast()</code></li>
<li>Aren't pre-defined in the form <code>x.values <- [something]</code> either globally or in the caller.</li>
</ul>
<p>Instead, they're variables within a dataframe that gets defined earlier and passed into the function <code>JitteredResponsesByContrast()</code>.</p>
<h2>Why ggplot2 makes it difficult to appease R CMD check</h2>
<p>ggplot2 seems to encourage the use of a <code>data</code> argument. The data argument, presumably, is why this code will execute</p>
<pre><code>library(ggplot2)
p <- ggplot(aes(x = hwy, y = cty), data = mpg)
p + geom_point()
</code></pre>
<p>but <strong>this</strong> code will produce an object-not-found error:</p>
<pre><code>library(ggplot2)
hwy # a variable in the mpg dataset
</code></pre>
<h2>Two work-arounds, and why I'm happy with neither</h2>
<h3>The NULLing out strategy</h3>
<p><a href="https://stackoverflow.com/a/8096882/180626">Matthew Dowle recommends</a> setting the problematic variables to NULL first, which in my case would look like this:</p>
<pre><code>JitteredResponsesByContrast <- function (data) {
x.values <- y.values <- NULL # Setting the variables to NULL first
return(
geom_point(
aes(
x = x.values,
y = y.values
),
data = data,
position = position_jitter(height = 0, width = GetDegreeOfJitter(jj))
)
)
}
</code></pre>
<p>I appreciate this solution, but I dislike it for three reasons.</p>
<ol>
<li>it serves no additional purpose beyond appeasing <code>R CMD check</code>.</li>
<li>it doesn't reflect intent. It raises the expectation that the <code>aes()</code> call will see our now-NULL variables (it won't), while obscuring the real purpose (making R CMD check aware of variables it apparently wouldn't otherwise know were bound)</li>
<li>The problems of 1 and 2 multiply because every time you write a function that returns a plot element, you have to add a confusing NULLing statement</li>
</ol>
<h3>The with() strategy</h3>
<p>You can use <code>with()</code> to explicitly signal that the variables in question can be found inside some larger environment. In my case, using <code>with()</code> looks like this:</p>
<pre><code>JitteredResponsesByContrast <- function (data) {
with(data, {
geom_point(
aes(
x = x.values,
y = y.values
),
data = data,
position = position_jitter(height = 0, width = GetDegreeOfJitter(jj))
)
}
)
}
</code></pre>
<p>This solution works. But, I don't like this solution because it doesn't even work the way I would expect it to. If <code>with()</code> were really solving the problem of pointing the interpreter to where the variables are, then I shouldn't even <em>need</em> the <code>data =</code> argument. But, <code>with()</code> doesn't work that way:</p>
<pre><code>library(ggplot2)
p <- ggplot()
p <- p + with(mpg, geom_point(aes(x = hwy, y = cty)))
p # will generate an error saying `hwy` is not found
</code></pre>
<p>So, again, I think this solution has similar flaws to the NULLing strategy:</p>
<ol>
<li>I still have to go through every plot element function and wrap the logic in a <code>with()</code> call</li>
<li>The <code>with()</code> call is misleading. I still need to supply a <code>data =</code> argument; all <code>with()</code> is doing is appeasing <code>R CMD check</code>.</li>
</ol>
<h2>Conclusion</h2>
<p>The way I see it, there are three options I could take:</p>
<ol>
<li>Lobby CRAN to ignore the notes by arguing that they're "spurious" (pursuant to <a href="http://cran.r-project.org/web/packages/policies.html#Submission" rel="noreferrer">CRAN policy</a>), and do that every time I submit a package</li>
<li>Fix my code with one of two undesirable strategies (NULLing or <code>with()</code> blocks)</li>
<li>Hum really loudly and hope the problem goes away</li>
</ol>
<p>None of the three make me happy, and I'm wondering what people suggest I (and other package developers wanting to tap into ggplot2) should do.</p> | 9,439,360 | 8 | 8 | null | 2012-02-24 23:00:56.057 UTC | 69 | 2022-04-05 13:14:56.91 UTC | 2022-02-21 22:46:29.61 UTC | null | 2,671,470 | null | 180,626 | null | 1 | 208 | r|ggplot2 | 28,179 | <p>Have you tried with <code>aes_string</code> instead of <code>aes</code>? This should work, although I haven't tried it:</p>
<pre><code>aes_string(x = 'x.values', y = 'y.values')
</code></pre> |
8,699,949 | What does the ~> symbol mean in a bundler Gemfile? | <p>What does the <code>-></code> mean next to a version number in a Gemfile?</p>
<p>For example:</p>
<pre><code>gem 'sass-rails', '~> 3.1.5'
</code></pre> | 8,699,973 | 2 | 3 | null | 2012-01-02 10:50:46.987 UTC | 6 | 2020-05-20 19:40:45.627 UTC | 2020-05-20 19:39:38.163 UTC | null | 229,044 | null | 215,895 | null | 1 | 68 | ruby-on-rails|bundler|gemfile | 27,776 | <p>From the bundler website:</p>
<blockquote>
<p>The specifier ~> has a special meaning, best shown by example:<br>
<code>'~> 2.0.3'</code> is identical to <code>'>= 2.0.3</code>' and <code>'< 2.1.'</code> <br>
<code>'~> 2.1'</code> is identical to <code>'>= 2.1'</code> and <code>'< 3.0'</code>. <br>
<code>'~> 2.2.beta'</code> will match prerelease versions like <code>'2.2.beta.12'</code>. <br></p>
</blockquote>
<p>See <a href="https://bundler.io/gemfile.html" rel="noreferrer">https://bundler.io/gemfile.html</a> and <a href="http://guides.rubygems.org/patterns/#pessimistic-version-constraint" rel="noreferrer">http://guides.rubygems.org/patterns/#pessimistic-version-constraint</a></p> |
8,708,814 | dump jquery object in an alert box | <p>I am not quite adept in maneuvering jQuery, and it came to a point that I need to debug a program that was passed down from me without a documentation.</p>
<p>I have this var <strong>a</strong>, an object, that I really want to know the content of its collection. In my mind I need a function like <code>foreach()</code> in PHP to iterate over this object variable. Upon researching I end up in using <a href="http://api.jquery.com/jQuery.each/" rel="noreferrer">jQuery.each()</a>. Now I can clearly iterate and see what was inside var <strong>a</strong>.</p>
<p>However, it was kind of annoying to alert once every value on the var <strong>a</strong>. What I wanna know if it's possible to display all the contents in just one pop of alert box?</p>
<p>Here is my code:</p>
<pre><code>$.each(a, function(index, value) {
alert(index + ': ' + value);
});
</code></pre>
<p>The var <strong>a</strong> contains infos such as:</p>
<pre><code>creationdate: date_here
id: SWFUpload
modificationdate: date_here
type: .jpg
index: 0
name: uploaded_filename.jpg
size: size_in_bytes
</code></pre>
<p>BTW: The var <strong>a</strong> is called via file upload script.</p> | 8,708,866 | 2 | 4 | null | 2012-01-03 06:42:25.43 UTC | 9 | 2015-03-26 01:55:32.763 UTC | 2012-01-03 06:51:22.717 UTC | null | 941,959 | null | 941,959 | null | 1 | 36 | javascript|jquery|object|alert|dump | 86,480 | <p>Why don't you just accumulate the values in an array, then display the whole array (for instance, using JSON)? Example:</p>
<pre><code>var acc = []
$.each(a, function(index, value) {
acc.push(index + ': ' + value);
});
alert(JSON.stringify(acc));
</code></pre>
<p>In any case, I'd suggest using a debug tool like <a href="http://getfirebug.com/" rel="noreferrer">Firebug</a>. So you could just use <strong>console.log(a)</strong> and be able to navigate freely through the objects's fields.</p> |
5,060,307 | ByteBuffer not releasing memory | <p>On Android, a direct ByteBuffer does not ever seem to release its memory, not even when calling System.gc(). </p>
<p>Example: doing</p>
<pre><code>Log.v("?", Long.toString(Debug.getNativeHeapAllocatedSize()));
ByteBuffer buffer = allocateDirect(LARGE_NUMBER);
buffer=null;
System.gc();
Log.v("?", Long.toString(Debug.getNativeHeapAllocatedSize()));
</code></pre>
<p>gives two numbers in the log, the second one being at least LARGE_NUMBER larger than the first.</p>
<p>How do I get rid of this leak?</p>
<hr>
<p><strong>Added:</strong></p>
<p>Following the suggestion by Gregory to handle alloc/free on the C++ side, I then defined</p>
<pre><code>JNIEXPORT jobject JNICALL Java_com_foo_bar_allocNative(JNIEnv* env, jlong size)
{
void* buffer = malloc(size);
jobject directBuffer = env->NewDirectByteBuffer(buffer, size);
jobject globalRef = env->NewGlobalRef(directBuffer);
return globalRef;
}
JNIEXPORT void JNICALL Java_com_foo_bar_freeNative(JNIEnv* env, jobject globalRef)
{
void *buffer = env->GetDirectBufferAddress(globalRef);
free(buffer);
env->DeleteGlobalRef(globalRef);
}
</code></pre>
<p>I then get my ByteBuffer on the JAVA side with</p>
<pre><code>ByteBuffer myBuf = allocNative(LARGE_NUMBER);
</code></pre>
<p>and free it with</p>
<pre><code>freeNative(myBuf);
</code></pre>
<p>Unfortunately, while it does allocate fine, it a) still keeps the memory allocated according to <code>Debug.getNativeHeapAllocatedSize()</code> and b) leads to an error </p>
<pre><code>W/dalvikvm(26733): JNI: DeleteGlobalRef(0x462b05a0) failed to find entry (valid=1)
</code></pre>
<p>I am now thoroughly confused, I thought I at least understood the C++ side of things... Why is free() not returning the memory? And what am I doing wrong with the <code>DeleteGlobalRef()</code>?</p> | 5,060,718 | 4 | 5 | null | 2011-02-20 21:49:19.35 UTC | 11 | 2015-09-15 13:15:05.2 UTC | 2011-02-21 20:12:50.3 UTC | null | 120,751 | null | 120,751 | null | 1 | 11 | android|memory-leaks|java-native-interface|bytebuffer | 28,200 | <p>There is no leak.</p>
<p><code>ByteBuffer.allocateDirect()</code> allocates memory from the native heap / free store (think <code>malloc()</code>) which is in turn wrapped in to a <code>ByteBuffer</code> instance.</p>
<p>When the <code>ByteBuffer</code> instance gets garbage collected, the native memory is reclaimed (<em>otherwise you would leak native memory</em>).</p>
<p>You're calling <code>System.gc()</code> in hope the native memory is reclaimed <em>immediately</em>. However, <strong>calling <code>System.gc()</code> is only a request</strong> which explains why your second log statement doesn't tell you memory has been released: it's because it hasn't yet!</p>
<p>In your situation, there is apparently enough free memory in the Java heap and the garbage collector decides to do nothing: as a consequence, unreachable <code>ByteBuffer</code> instances are not collected yet, their finalizer is not run and native memory is not released.</p>
<p>Also, keep in mind this <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4857305">bug</a> in the JVM (not sure how it applies to Dalvik though) where heavy allocation of direct buffers leads to unrecoverable <code>OutOfMemoryError</code>.</p>
<hr>
<p>You commented about doing controlling things from JNI. This is actually possible, you could implement the following:</p>
<ol>
<li><p>publish a <code>native ByteBuffer allocateNative(long size)</code> entry point that:</p>
<ul>
<li>calls <code>void* buffer = malloc(size)</code> to allocate native memory</li>
<li>wraps the newly allocated array into a <code>ByteBuffer</code> instance with a call to <code>(*env)->NewDirectByteBuffer(env, buffer, size);</code></li>
<li><strike>converts the <code>ByteBuffer</code> local reference to a global one with <code>(*env)->NewGlobalRef(env, directBuffer);</code></strike></li>
</ul></li>
<li><p>publish a <code>native void disposeNative(ByteBuffer buffer)</code> entry point that:</p>
<ul>
<li>calls <code>free()</code> on the direct buffer address returned by <code>*(env)->GetDirectBufferAddress(env, directBuffer);</code></li>
<li><strike>deletes the global ref with <code>(*env)->DeleteGlobalRef(env, directBuffer);</code></strike></li>
</ul></li>
</ol>
<p>Once you call <code>disposeNative</code> on the buffer, you're not supposed to use the reference anymore, so it could be very error prone. Reconsider whether you really need such explicit control over the allocation pattern.</p>
<hr>
<p><strong>Forget what I said about global references. Actually global references are a way to store a reference in native code (like in a global variable) so that a further call to JNI methods can use that reference. So you would have for instance:</strong></p>
<ul>
<li><strong>from Java, call native method <code>foo()</code> which creates a global reference out of a local reference (obtained by creating an object from native side) and stores it in a native global variable (as a <code>jobject</code>)</strong></li>
<li><strong>once back, from Java again, call native method <code>bar()</code> which gets the <code>jobject</code> stored by <code>foo()</code> and further processes it</strong></li>
<li><strong>finally, still from Java, a last call to native <code>baz()</code> deletes the global reference</strong></li>
</ul>
<p>Sorry for the confusion.</p> |
5,454,593 | how to clear all css styles | <p>I'm creating a snippet of HTML to allow others to add functionality to their web sites (it is a voting widget). I've created a snippet of HTML like this:</p>
<pre><code><div>
[implementation of my voting widget]
</div>
</code></pre>
<p>I spent a lot of time to get the formatting of this widget just right. It works great in a sample web page that does not import a style sheet.</p>
<p>When I add the widget to a page on a Drupal site, however, the imported CSS wreaks havoc with my careful formatting. I'd like my HTML snippet to ignore all CSS style sheets. Is this possible?</p>
<p>Regardless of whether it is possible, is there a better solution?</p> | 5,454,637 | 4 | 2 | null | 2011-03-28 04:11:34.987 UTC | 3 | 2011-03-28 04:26:15.427 UTC | null | null | null | null | 136,598 | null | 1 | 12 | html|css|widget | 44,393 | <p>Instead of relying on your CSS styles not being overridden by any imported stylesheets, you should give your widget a unique id and make sure all of your styles are a derivative of that id making sure to implement any styles you don't want to be overriden (<code>margin</code>, <code>padding</code>, etc):</p>
<pre><code><div id="votify">
[implementation of my voting widget]
</div>
#votify {}
#votify ul {}
#votify div span {}
/* etc */
</code></pre> |
4,923,380 | Difference between regex [A-z] and [a-zA-Z] | <p>I am using a regex to program an input validator for a text box where I only want alphabetical characters. I was wondering if <code>[A-z]</code> and <code>[a-zA-Z]</code> were equivalent or if there were differences performance wise.</p>
<p>I keep reading <code>[a-zA-Z]</code> on my searches and no mention of <code>[A-z]</code>.</p>
<p>I am using java's <code>String.matches(regex)</code>.</p> | 4,923,397 | 6 | 0 | null | 2011-02-07 15:56:52.777 UTC | 10 | 2019-09-10 20:31:36.25 UTC | 2015-05-30 20:54:38.397 UTC | null | 1,518,921 | null | 606,721 | null | 1 | 83 | java|regex | 108,476 | <p><code>[A-z]</code> will match ASCII characters in the range from <code>A</code> to <code>z</code>, while <code>[a-zA-Z]</code> will match ASCII characters in the range from <code>A</code> to <code>Z</code> <strong>and</strong> in the range from <code>a</code> to <code>z</code>. At first glance, this might seem equivalent -- however, if you look at <a href="http://www.asciitable.com/" rel="noreferrer">this table</a> of ASCII characters, you'll see that <code>A-z</code> includes several other characters. Specifically, they are <code>[</code>, <code>\</code>, <code>]</code>, <code>^</code>, <code>_</code>, and <code>`</code> (which you clearly don't want).</p> |
16,907,580 | TinyMCE is not defined Jquery | <p>Have been working on this error for 2 days and cannot get TinyMCE to work. I am using the jquery version of TinyMCE. Below is my HTML code with a form that contains a textarea. I use Google Inspect Element and under the console tab i get the following error: "Uncaught ReferenceError: tinymce is not defined". Any help would be appreciated.</p>
<pre><code><form id="add_update_form" action="" method="POST" title="Add Blog">
<p class="feedback"></p>
<!-- <label>Created:</label>
<input type="text" name="created"> -->
<label>Title:</label>
<input type="text" name="title" class="input-block-level">
<label>Content:</label>
<textarea width="100%" rows="10" cols="10" name="content" class="input-block-level"></textarea>
<div class="clear"></div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script src="<?php echo base_url();?>js/portal/tinymce/jquery.tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: "textarea",
plugins: [
"advlist autolink lists link image charmap print preview anchor",
"searchreplace visualblocks code fullscreen",
"insertdatetime media table contextmenu paste moxiemanager"
],
toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
});
</script>
</code></pre> | 16,907,889 | 3 | 3 | null | 2013-06-03 23:43:17.583 UTC | null | 2014-10-14 09:59:17.86 UTC | null | null | null | null | 2,149,025 | null | 1 | 9 | jquery|tinymce | 43,626 | <p>As you are using the jquery version you'll need to set it up like a jquery plugin</p>
<pre><code>$(function() {
$('textarea.tinymce').tinymce({
...
});
});
</code></pre>
<p><a href="http://www.tinymce.com/tryit/3_x/jquery_plugin.php" rel="noreferrer">http://www.tinymce.com/tryit/3_x/jquery_plugin.php</a></p> |
12,102,777 | Prevent Android activity dialog from closing on outside touch | <p>I have an activity that is using the Theme.Dialog style such that it is a floating window over another activity. However, when I click outside the dialog window (on the background activity), the dialog closes. How can I stop this behaviour?</p> | 12,102,791 | 20 | 3 | null | 2012-08-24 03:29:39.803 UTC | 41 | 2022-04-23 16:08:14.427 UTC | null | null | null | null | 966,538 | null | 1 | 265 | java|android|android-activity|dialog|touch | 205,746 | <p>This could help you. It is a way to handle the touch outside event:</p>
<p><a href="https://stackoverflow.com/questions/4650246/how-to-cancel-an-dialog-themed-like-activity-when-touched-outside-the-window/5831214#5831214">How to cancel an Dialog themed like Activity when touched outside the window?</a></p>
<p>By catching the event and doing nothing, I think you can prevent the closing. But what is strange though, is that the default behavior of your activity dialog should be <strong>not</strong> to close itself when you touch outside.</p>
<p>(PS: the code uses WindowManager.LayoutParams)</p> |
12,594,343 | How do I select multiple values in the same column? | <p>I am trying to select multiple values in a single column. Basically I want the query to select all those under column <code>family</code> with values <code>Software_1Y</code>,<code>XI_1Y</code> and <code>P1_1Y</code></p>
<p>I am running this query :</p>
<pre><code>SELECT `salesorder`
,`masterproduct`
,`family`
,`birthstamp`
,`duedate`
,COUNT(*) AS `total`
FROM `report`
WHERE `birthstamp` BETWEEN '$startDT'
AND '$endDT'
AND `family` = 'Software_1Y'
AND `family = 'XI_1Y'
AND `family` = 'PI_1Y'
GROUP BY `salesorder`
,`masterproduct`
,`family`
,`duedate`;
</code></pre>
<p>My query returns no rows but is I search each family one by one, I have values.</p>
<p>What is wrong with my query?</p>
<p>Also, my purpose is to get all the rows whose <code>family</code> values are <code>Software_1Y</code>, <code>XI_1Y</code> and <code>PI_1Y</code>. </p> | 12,594,357 | 2 | 2 | null | 2012-09-26 03:58:51.5 UTC | 1 | 2013-10-24 01:20:02.427 UTC | 2012-09-26 04:23:21.547 UTC | null | 1,699,078 | null | 1,699,078 | null | 1 | 14 | mysql | 74,736 | <p>How about using IN instead</p>
<pre><code>SELECT `salesorder`,
`masterproduct`,
`family`,
`birthstamp`,
`duedate`,
COUNT( * ) AS `total`
FROM `report`
WHERE `birthstamp` BETWEEN '$startDT' AND '$endDT'
AND `family` IN ('Software_1Y','XI_1Y','PI_1Y')
GROUP BY `salesorder`,
`masterproduct`,
`family`,
`duedate`;
</code></pre>
<p>The reason why no values are returned, is because of this section</p>
<pre><code>AND `family` = 'Software_1Y'
AND `family = 'XI_1Y'
AND `family` = 'PI_1Y'
</code></pre>
<p><code>family</code> cannot be all 3 values at once, but it might be 1 of the 3 values.</p>
<p>That is why you would use IN.</p>
<p>Another way to look at it would be to use OR, but that gets really long winded.</p> |
12,452,003 | iOS Accessibility: Custom voice over text for bundle display name | <p>iOS voice over does not correctly read out my companies name. For example it reads out "dog" instead of "D.O.G." (not my real company name but you get the idea)</p>
<p>We get around this by telling the app to read out "D O G" in all places where the company name is read out. </p>
<p>However, voice over reads the bundle display name out incorrectly both on the app icon, and after the app has finished launching.</p>
<p>Is there a way to make my app read out "D O G" instead of "dog" after app launch?
I would settle for forcing the app not to read out the bundle display name after app launch and then manually reading out "D O G".</p>
<p>(I'm assuming you can't set a custom voice over for the app icon, but bonus points for anyone that knows if I can or can't)</p> | 32,193,950 | 2 | 3 | null | 2012-09-17 00:52:38.877 UTC | 2 | 2015-08-25 00:55:28.573 UTC | 2013-04-08 15:22:43.303 UTC | null | 28,768 | null | 1,455,770 | null | 1 | 28 | ios|accessibility|voiceover | 3,114 | <p>As of iOS 8, you can achieve this by adding the CFBundleSpokenName key to your Info.plist.</p>
<p><a href="https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/plist/info/CFBundleSpokenName">https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/plist/info/CFBundleSpokenName</a></p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.