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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
58,649 | How to get the EXIF data from a file using C# | <p>I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...). </p>
<p>Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically?
Thanks!</p> | 156,640 | 8 | 2 | null | 2008-09-12 10:43:49.07 UTC | 33 | 2020-08-11 05:32:29.243 UTC | null | null | null | Joel in Gö | 6,091 | null | 1 | 79 | c#|exif|photography | 135,811 | <p>Check out this <a href="https://www.drewnoakes.com/code/exif/" rel="noreferrer">metadata extractor</a>. <strike>It is written in Java but has also been ported to C#.</strike> I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use.</p>
<hr>
<p><strong>EDIT</strong> <em>metadata-extractor</em> supports .NET too. It's a very fast and simple library for accessing metadata from images and videos.</p>
<p>It fully supports Exif, as well as IPTC, XMP and many other types of metadata from file types including JPEG, PNG, GIF, PNG, ICO, WebP, PSD, ...</p>
<pre><code>var directories = ImageMetadataReader.ReadMetadata(imagePath);
// print out all metadata
foreach (var directory in directories)
foreach (var tag in directory.Tags)
Console.WriteLine($"{directory.Name} - {tag.Name} = {tag.Description}");
// access the date time
var subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
var dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTime);
</code></pre>
<p>It's available via <a href="https://www.nuget.org/packages/MetadataExtractor/" rel="noreferrer">NuGet</a> and the <a href="https://github.com/drewnoakes/metadata-extractor-dotnet" rel="noreferrer">code's on GitHub</a>.</p> |
775,170 | When should you NOT use a Rules Engine? | <p>I have a pretty decent list of the advantages of using a Rules Engine, as well as some reasons to use them, what I need is a list of the reasons why you should NOT use a Rules Engine</p>
<p>The best I have so far is this:</p>
<blockquote>
<p>Rules engines are not really intended to handle workflow or process
executions nor are workflow engines or process management tools
designed to do rules.</p>
</blockquote>
<p>Any other big reasons why you should not use them?</p> | 775,224 | 9 | 1 | 2009-04-21 23:51:32.45 UTC | 2009-04-21 23:51:32.467 UTC | 62 | 2016-08-22 14:48:50.963 UTC | 2011-11-04 20:30:20.593 UTC | null | 815,724 | null | 8,411 | null | 1 | 112 | rule-engine | 124,680 | <p>I get very nervous when I see people using very large rule sets (e.g., on the order of thousands of rules in a single rule set). This often happens when the rules engine is a singleton sitting in the center of the enterprise in the hope that keeping rules <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="noreferrer">DRY</a> will make them accessible to many apps that require them. I would defy anyone to tell me that a Rete rules engine with that many rules is well-understood. I'm not aware of any tools that can check to ensure that conflicts don't exist.</p>
<p>I think partitioning rules sets to keep them small is a better option. Aspects can be a way to share a common rule set among many objects.</p>
<p>I prefer a simpler, more data driven approach wherever possible.</p> |
638,845 | WPF - Image 'is not part of the project or its Build Action is not set to Resource' | <p>I have a project which requires an image in the window. This is a static image and i added through 'Add>Existing Item'. It exists in the root of the project.</p>
<p>I reference the image in a test page like so - </p>
<pre><code><Page x:Class="Critter.Pages.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test">
<Image Source="bug.png"/>
</Page>
</code></pre>
<p>Problem is I get a message saying it can't be found or it's build action isn't resource but it DOES exist and it's build action IS resource. If i create a new application and just throw it on a window then it works fine.</p>
<p>Any help would be great.</p> | 639,309 | 10 | 3 | null | 2009-03-12 14:26:31.197 UTC | 5 | 2020-05-17 07:36:10.407 UTC | 2012-06-12 08:29:14.43 UTC | null | 45,382 | Stimul8d | 5,559 | null | 1 | 31 | wpf|image|resources|imagesource|buildaction | 50,500 | <p>Try doing a full rebuild, or delete the build files and then build the file.</p>
<p>Visual Studio doesn't always pick up changes to resources, and it can be a pain to get it recompile.</p>
<p>Also try using a full URI as that helped me when I had the same problem. Something like</p>
<pre><code>pack://application:,,,/MyAssembly;component/bug.png
</code></pre> |
729,489 | Duplicate / Copy records in the same MySQL table | <p>I have been looking for a while now but I can not find an easy solution for my problem. I would like to duplicate a record in a table, but of course, the unique primary key needs to be updated.</p>
<p>I have this query:</p>
<pre><code>INSERT INTO invoices
SELECT * FROM invoices AS iv WHERE iv.ID=XXXXX
ON DUPLICATE KEY UPDATE ID = (SELECT MAX(ID)+1 FROM invoices)
</code></pre>
<p>the problem is that this just changes the <code>ID</code> of the row instead of copying the row. Does anybody know how to fix this ?</p>
<p>//edit: I would like to do this without typing all the field names because the field names can change over time.</p> | 2,936,128 | 10 | 0 | null | 2009-04-08 11:01:58.18 UTC | 40 | 2021-02-17 09:43:06.857 UTC | 2015-02-05 20:53:50.05 UTC | null | 3,885,376 | null | 76,793 | null | 1 | 91 | mysql | 136,377 | <p>The way that I usually go about it is using a temporary table. It's probably not computationally efficient but it seems to work ok! Here i am duplicating record 99 in its entirety, creating record 100.</p>
<pre><code>CREATE TEMPORARY TABLE tmp SELECT * FROM invoices WHERE id = 99;
UPDATE tmp SET id=100 WHERE id = 99;
INSERT INTO invoices SELECT * FROM tmp WHERE id = 100;
</code></pre>
<p>Hope that works ok for you!</p> |
982,354 | Where are the Properties.Settings.Default stored? | <p>I thought I knew this, but today I'm being proven wrong - again.</p>
<p>Running VS2008, .NET 3.5 and C#. I added the User settings to the Properties Settings tab with default values, then read them in using this code:</p>
<pre><code>myTextBox.Text = Properties.Settings.Default.MyStringProperty;
</code></pre>
<p>Then, after the user edits the value in the options dialog I save it like this:</p>
<pre><code>Properties.Settings.Default.MyStringProperty = myTextBox.Text;
Properties.Settings.Default.Save();
</code></pre>
<p>My question is, where is this new value saved? the MyApp.exe.config file in the executable directory is not updated, it still contains the default values. Plus, as far as I can tell, none of the other files in that directory are updated either! However, when the program reads the value back in, it gets the changed value, so I know it's saved somewhere...</p>
<p>This isn't just academic, I needed to be able to manually edit the value this morning and got myself stumped when I couldn't find anything that was changing.</p> | 982,397 | 10 | 4 | null | 2009-06-11 17:05:27.487 UTC | 42 | 2020-11-17 12:42:18.007 UTC | 2016-12-21 02:00:40.647 UTC | null | 2,557,128 | null | 83,678 | null | 1 | 165 | c#|.net|settings | 176,701 | <p>In order to work with newer versions of Windows' policy of only allowing read access by default to the Program Files folder (unless you prompt for elevation with UAC, but that's another topic...), your application will have a settings folder under <code>%userprofile%\appdata\local</code> or <code>%userprofile%\Local Settings\Application Data</code> depending on which version of Windows you're running, for settings that are user specific. If you store settings for all users, then they'll be in the corresponding folder under <code>C:\users</code> or <code>C:\Documents and Settings</code> for all user profiles (ex: <code>C:\users\public\appdata\local</code>).</p> |
405,288 | SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row | <p>Consider this trigger:</p>
<pre><code>ALTER TRIGGER myTrigger
ON someTable
AFTER INSERT
AS BEGIN
DELETE FROM someTable
WHERE ISNUMERIC(someField) = 1
END
</code></pre>
<p>I've got a table, someTable, and I'm trying to prevent people from inserting bad records. For the purpose of this question, a bad record has a field "someField" that is all numeric.</p>
<p>Of course, the right way to do this is NOT with a trigger, but I don't control the source code... just the SQL database. So I can't really prevent the insertion of the bad row, but I can delete it right away, which is good enough for my needs.</p>
<p>The trigger works, with one problem... when it fires, it never seems to delete the just-inserted bad record... it deletes any OLD bad records, but it doesn't delete the just-inserted bad record. So there's often one bad record floating around that isn't deleted until somebody else comes along and does another INSERT.</p>
<p>Is this a problem in my understanding of triggers? Are newly-inserted rows not yet committed while the trigger is running?</p> | 405,295 | 12 | 1 | null | 2009-01-01 18:50:01.39 UTC | 14 | 2020-02-06 20:39:52.567 UTC | null | null | null | Joel Spolsky | 4 | null | 1 | 45 | sql-server|sql-server-2005|triggers | 195,223 | <p>Triggers cannot modify the changed data (<code>Inserted</code> or <code>Deleted</code>) otherwise you could get infinite recursion as the changes invoked the trigger again. One option would be for the trigger to roll back the transaction.</p>
<p><strong>Edit:</strong> The reason for this is that the standard for SQL is that inserted and deleted rows cannot be modified by the trigger. The underlying reason for is that the modifications could cause infinite recursion. In the general case, this evaluation could involve multiple triggers in a mutually recursive cascade. Having a system intelligently decide whether to allow such updates is computationally intractable, essentially a variation on the <a href="http://en.wikipedia.org/wiki/Halting_problem" rel="noreferrer">halting problem.</a> </p>
<p>The accepted solution to this is not to permit the trigger to alter the changing data, although it can roll back the transaction. </p>
<pre><code>create table Foo (
FooID int
,SomeField varchar (10)
)
go
create trigger FooInsert
on Foo after insert as
begin
delete inserted
where isnumeric (SomeField) = 1
end
go
Msg 286, Level 16, State 1, Procedure FooInsert, Line 5
The logical tables INSERTED and DELETED cannot be updated.
</code></pre>
<p>Something like this will roll back the transaction.</p>
<pre><code>create table Foo (
FooID int
,SomeField varchar (10)
)
go
create trigger FooInsert
on Foo for insert as
if exists (
select 1
from inserted
where isnumeric (SomeField) = 1) begin
rollback transaction
end
go
insert Foo values (1, '1')
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
</code></pre> |
1,211,608 | Possible to iterate backwards through a foreach? | <p>I know I could use a <code>for</code> statement and achieve the same effect, but can I loop backwards through a <code>foreach</code> loop in C#?</p> | 1,211,611 | 12 | 3 | null | 2009-07-31 09:39:35.367 UTC | 18 | 2021-11-10 21:21:12.513 UTC | 2015-04-14 13:02:54.473 UTC | null | 63,550 | null | 41,543 | null | 1 | 169 | c#|foreach | 220,690 | <p>When working with a list (direct indexing), you cannot do it as efficiently as using a <code>for</code> loop.</p>
<p>Edit: Which generally means, when you are <em>able</em> to use a <code>for</code> loop, it's likely the correct method for this task. Plus, for as much as <code>foreach</code> is implemented in-order, the construct itself is built for expressing loops that are independent of element indexes and iteration order, which is particularly important in <a href="http://msdn.microsoft.com/en-us/library/dd321840.aspx" rel="noreferrer">parallel programming</a>. It is <em>my opinion</em> that iteration relying on order should not use <code>foreach</code> for looping.</p> |
979,662 | How can I detect pressing Enter on the keyboard using jQuery? | <p>I would like to detect whether the user has pressed <kbd>Enter</kbd> using jQuery.</p>
<p>How is this possible? Does it require a plugin?</p>
<p>It looks like I need to use the <a href="http://docs.jquery.com/Events/keypress" rel="noreferrer"><code>keypress()</code></a> method.</p>
<p>Are there browser issues with that command - like are there any browser compatibility issues I should know about?</p> | 979,686 | 19 | 4 | null | 2009-06-11 06:39:43.17 UTC | 119 | 2022-05-04 22:24:44.67 UTC | 2022-04-28 20:49:08.07 UTC | null | 63,550 | null | 111,691 | null | 1 | 807 | javascript|jquery|keyboard-events|enter|jquery-events | 963,157 | <p>The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with <kbd>enter</kbd> being 13 in all browsers. So with that in mind, you can do this:</p>
<pre><code>$(document).on('keypress',function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
</code></pre> |
94,361 | When do you use Java's @Override annotation and why? | <p>What are the best practices for using Java's <code>@Override</code> annotation and why? </p>
<p>It seems like it would be overkill to mark every single overridden method with the <code>@Override</code> annotation. Are there certain programming situations that call for using the <code>@Override</code> and others that should never use the <code>@Override</code>? </p> | 94,411 | 27 | 0 | null | 2008-09-18 16:48:26.74 UTC | 663 | 2012-08-16 22:57:00.897 UTC | 2011-11-09 00:12:28.693 UTC | Alex B | 13,940 | Alex B | 6,180 | null | 1 | 498 | java|annotations | 938,326 | <p>Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.</p>
<p>Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like <code>@Implements</code>), but it's better than nothing.</p> |
6,987,479 | How to use strpos to determine if a string exists in input string? | <pre><code>$filename = 'my_upgrade(1).zip';
$match = 'my_upgrade';
if(!strpos($filename, $match))
{
die();
}
else
{
//proceed
}
</code></pre>
<p>In the code above, I'm trying to die out of the script when the filename does not contain the text string "my_upgrade". However, in the example given, it should not die since "<strong>my_upgrade(1).zip</strong>" contains the string "<strong>my_upgrade</strong>". </p>
<p>What am I missing?</p> | 6,987,496 | 8 | 1 | null | 2011-08-08 19:28:12.37 UTC | 2 | 2021-03-05 07:02:31.007 UTC | null | null | null | null | 209,102 | null | 1 | 27 | php|strpos | 71,222 | <p><code>strpos</code> returns <code>false</code> if the string is not found, and <code>0</code> if it is found at the beginning. Use the <a href="http://php.net/manual/en/language.operators.comparison.php" rel="noreferrer">identity operator</a> to distinguish the two:</p>
<pre><code>if (strpos($filename, $match) === false) {
</code></pre>
<p>By the way, this fact is documented with a red background and an exclamation mark in the <a href="http://php.net/strpos#refsect1-function.strpos-returnvalues" rel="noreferrer">official documentation</a>.</p> |
6,578,178 | Node.js Mongoose.js string to ObjectId function | <p>Is there a function to turn a string into an objectId in node using mongoose? The schema specifies that something is an ObjectId, but when it is saved from a string, mongo tells me it is still just a string. The _id of the object, for instance, is displayed as <code>objectId("blah")</code>.</p> | 8,393,613 | 8 | 0 | null | 2011-07-05 05:15:19.623 UTC | 57 | 2021-08-31 14:31:45.697 UTC | null | null | null | null | 741,072 | null | 1 | 230 | mongodb|node.js|mongoose | 287,080 | <p>You can do it like so:</p>
<pre><code>var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
</code></pre> |
6,819,813 | Solution for: Store update, insert, or delete statement affected an unexpected number of rows (0) | <p>I found a solution for people who get an exception:</p>
<p><em>Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.</em></p>
<p>But, anyway I have question. </p>
<p>I read topic:
<a href="https://stackoverflow.com/questions/1836173/entity-framework-store-update-insert-or-delete-statement-affected-an-unexpect">Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."</a>
<em>To <strong>VMAtm, Robert Harvey</em></strong></p>
<p>In my case I had for example table articles:</p>
<pre><code>Articles
------------
article_id
title
date_cr
date_mod
deleted
</code></pre>
<p>And I had trigger:</p>
<pre><code>create trigger articles_instead_of_insert
on articles instead of insert
as
SET NOCOUNT ON;
insert into articles(
article_id,
title,
date_cr,
date_mod,
deleted
)
select
user_id,
title,
isnull(date_cr, {fn NOW()}),
isnull(date_mod, {fn NOW()}),
isnull(deleted, 0)
from inserted;
go
</code></pre>
<p>When I delete this trigger then I dont get this exception. So this trigger is problem. And now I have a question - Why? Should I do something?</p> | 6,848,729 | 11 | 7 | null | 2011-07-25 17:09:01.447 UTC | 17 | 2020-06-20 14:49:25.473 UTC | 2017-05-23 12:34:42.623 UTC | null | -1 | null | 677,202 | null | 1 | 30 | sql|sql-server|entity-framework|entity-framework-4|triggers | 103,516 | <p>Solution:</p>
<pre><code>try {
context.SaveChanges();
} catch (OptimisticConcurrencyException) {
context.Refresh(RefreshMode.ClientWins, db.Articles);
context.SaveChanges();
}
</code></pre> |
6,892,754 | Creating a simple configuration file and parser in C++ | <p>I am trying to create a simple configuration file that looks like this</p>
<pre><code>url = http://mysite.com
file = main.exe
true = 0
</code></pre>
<p>when the program runs, I would like it to load the configuration settings into the programs variables listed below.</p>
<pre><code>string url, file;
bool true_false;
</code></pre>
<p>I have done some research and <a href="http://www.daniweb.com/software-development/cpp/threads/185995" rel="noreferrer">this</a> link seemed to help (nucleon's post) but I can't seem to get it to work and it is too complicated to understand on my part. Is there a simple way of doing this? I can load the file using <code>ifstream</code> but that is as far as I can get on my own. Thanks!</p> | 6,892,829 | 15 | 7 | null | 2011-07-31 22:28:27.583 UTC | 38 | 2022-03-13 00:50:09.517 UTC | null | null | null | null | 684,838 | null | 1 | 79 | c++|file|parsing|configuration|settings | 193,033 | <p>In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.<br>
In C++, lines can be read from a stream using <code>std::getline()</code>. While by default it will read up to the next <code>'\n'</code> (which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like <code>=</code> in your example. </p>
<p>For simplicity, the following presumes that the <code>=</code> are <em>not</em> surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically place <code>is >> std::ws</code> before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader. </p>
<pre><code>const char config[] = "url=http://example.com\n"
"file=main.exe\n"
"true=0";
std::istringstream is_file(config);
std::string line;
while( std::getline(is_file, line) )
{
std::istringstream is_line(line);
std::string key;
if( std::getline(is_line, key, '=') )
{
std::string value;
if( std::getline(is_line, value) )
store_line(key, value);
}
}
</code></pre>
<p><em>(Adding error handling is left as an exercise to the reader.)</em></p> |
45,608,362 | Android Studio 3.0 Beta 1: Failed to resolve: com.android.support:multidex:1.0.2 | <p>After migrating from Android Studio 3.0 (Canary 5) to Android Studio 3.0 (Beta 1), and moving to latest gradle , i.e. <code>'com.android.tools.build:gradle:3.0.0-beta1'</code></p>
<p>When I try to gradle sync, it error stating below.</p>
<pre><code>Failed to resolve: com.android.support:multidex:1.0.2
Failed to resolve: com.android.support:multidex-instrumentation:1.0.2
</code></pre>
<p>I check on <a href="https://stackoverflow.com/questions/45486553/android-studio-3-0-canary-9-failed-to-resolve-packages">Android Studio 3.0 Canary 9 - Failed to resolve packages</a>, it doesn't solve my problem, as I already have this</p>
<pre><code> maven {
url 'https://maven.google.com'
}
</code></pre>
<p>I'm surprise it is even asking for multidex 1.0.2, as I only have in my build.gradle</p>
<pre><code>compile 'com.android.support:multidex:1.0.1'
</code></pre>
<p>I check using <code>./gradlew app:dependencies | grep multidex</code>, it shows the failures as below (across various flavors etc)</p>
<pre><code>+--- com.android.support:multidex-instrumentation:1.0.2 FAILED
+--- com.android.support:multidex:1.0.1
+--- com.android.support:multidex:1.0.2 FAILED
+--- com.android.support:multidex:1.0.1 -> 1.0.2 FAILED
</code></pre>
<p>Where did the dependencies of <code>multidex:1.0.2</code> and <code>multidex-instrumentation:1.0.2</code> comes from? How could I solve this problem?</p> | 45,609,732 | 12 | 4 | null | 2017-08-10 08:30:16.09 UTC | 11 | 2022-06-14 13:36:17.563 UTC | null | null | null | null | 3,286,489 | null | 1 | 38 | android|gradle|android-gradle-plugin|build.gradle|android-multidex | 45,185 | <p>Apparently my issue is I should post this:</p>
<pre><code>maven {
url 'https://maven.google.com'
}
</code></pre>
<p>in <code>allprojects</code> and not in <code>buildscript</code> (the subtle different has blinded me where the issue is), which then looks like this:</p>
<pre><code>allprojects {
repositories {
maven {
url 'https://maven.google.com'
}
}
}
</code></pre>
<p>Thanks to M D for the pointers!</p> |
15,938,466 | Plugin execution not covered by lifecycle configuration error in Eclipse Juno | <p>Why does my Maven build work perfectly fine on the command line but when I run in Eclipse, it requires I add this section to my pom.xml, otherwise I get this error:</p>
<pre><code>Plugin execution not covered by lifecycle configuration
: org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile
(execution: default-testCompile, phase: test-compile)
</code></pre>
<p>Isn't it strange that this occurs around the 'maven-compiler-plugin' plugin?? I cannot find another question like this anywhere on google, although I find many fix suggestions around 3rd party plugins. I've done a great deal of researching and searching and found no explanation of this, not even <a href="http://wiki.eclipse.org/M2E_plugin_execution_not_covered" rel="noreferrer">from here</a>.</p>
<p>And the pom.xml required to fix this:</p>
<pre><code><!--This plugin's configuration is used to store Eclipse m2e
settings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<versionRange>[3.1,)</versionRange>
<goals>
<goal>testCompile</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</code></pre>
<p>And , <a href="https://github.com/djangofan/maven-groovy" rel="noreferrer">here is my simple project on GitHub</a> if you want to see my source.</p> | 15,974,923 | 3 | 2 | null | 2013-04-10 23:45:26.027 UTC | 4 | 2018-10-01 11:55:50.01 UTC | 2013-04-11 02:31:27.907 UTC | null | 118,228 | null | 118,228 | null | 1 | 15 | maven|maven-3 | 39,029 | <p>I finally solved it. It appears that the "pluginManagement" section I posted above is required by an Eclipse Maven project in general, even though I resisted it, and even though no documentation that I can find on the internet ever mentions this explicitly.</p>
<p>ALso, the "versionRange" in the lifecycle exclusion section seems to also require the version number of the "gmaven-plugin" rather than the "version of Maven" which I was trying to give it above.</p>
<pre><code><pluginExecutionFilter>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<versionRange>[1.5,)</versionRange>
<goals>
<goal>testCompile</goal>
<goal>compile</goal>
</goals>
</pluginExecutionFilter>
</code></pre> |
15,617,207 | Line colour of 3D parametric curve in python's matplotlib.pyplot | <p>I've been googling quite some time with no success ... maybe my keywords are just lousy. Anyway, suppose I have three 1D <code>numpy.ndarray</code>s of the same length I'd like to plot them in 3D as a trajectory. Moreover, I'd like to be able to do either of the following things:</p>
<ol>
<li>Change the colour of the line as a function of <code>z</code></li>
<li>Change the colour of the line as a function of time (i.e. the index in the arrays)</li>
</ol>
<p><a href="http://matplotlib.org/examples/mplot3d/lines3d_demo.html" rel="noreferrer">This demo</a> has an example of making such a curve:</p>
<pre><code>import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/gH7ly.png" alt="enter image description here"></p>
<p>But how do I achieve <code>1</code> or <code>2</code>? Solutions to only one or the other are welcome!
Thanks in advance.</p> | 15,617,576 | 2 | 0 | null | 2013-03-25 14:18:14.493 UTC | 8 | 2013-03-25 15:09:38.367 UTC | null | null | null | null | 1,082,565 | null | 1 | 22 | python|matplotlib | 11,695 | <p>As with normal 2d plots, you cannot have a gradient of color along an ordinary line. However, you can do it with <code>scatter</code>:</p>
<pre><code>import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
#1 colored by value of `z`
ax.scatter(x, y, z, c = plt.cm.jet(z/max(z)))
#2 colored by index (same in this example since z is a linspace too)
N = len(z)
ax.scatter(x, y, z, c = plt.cm.jet(np.linspace(0,1,N)))
plt.show()
</code></pre>
<hr>
<p>I liked <a href="https://stackoverflow.com/users/1404505/junuxx">@Junuxx's</a> <a href="https://stackoverflow.com/a/15617860/1730674">hack</a> so I applied it here:</p>
<pre><code>for i in xrange(N-1):
ax.plot(x[i:i+2], y[i:i+2], z[i:i+2], color=plt.cm.jet(255*i/N))
</code></pre>
<p><img src="https://i.stack.imgur.com/loWUe.png" alt="2-Color by index">
<img src="https://i.stack.imgur.com/tLj3p.png" alt="2-Color lines by index"></p> |
32,840,399 | Printing Exception vs Exception.getMessage | <p>Is there a best practice on using the followng two pieces of code regarding exceptions.</p>
<pre><code>//code1
} catch (SomeException e) {
logger.error("Noinstance available!", e.getMessage());
}
//code2
} catch (SomeException e) {
logger.error("Noinstance available!", e);
}
</code></pre>
<p>When should I use the getMessage method of an exception?</p> | 32,840,469 | 6 | 7 | null | 2015-09-29 09:25:05.147 UTC | 10 | 2016-06-04 06:29:17.48 UTC | 2015-09-29 09:27:37.27 UTC | null | 4,014,108 | null | 2,285,855 | null | 1 | 47 | java|exception | 66,824 | <p>The first doesn't compile because the method <code>error</code> accept a <code>String</code> as first parameter and a <code>Throwable</code> as second parameter.</p>
<p><code>e.getMessage()</code> is not a <code>Throwable</code>.</p>
<p>The code should be </p>
<pre><code>} catch (SomeException e) {
// No stack trace
logger.error("Noinstance available! " + e.getMessage());
}
</code></pre>
<p>Compared with </p>
<pre><code>} catch (SomeException e) {
// Prints message and stack trace
logger.error("Noinstance available!", e);
}
</code></pre>
<p>The first prints only a message. The second prints also the whole stack trace.</p>
<p>It depends from the context if it is necessary to print the stack trace or not. </p>
<p>If you already know why an exception can be thrown it is not a good idea to print the whole stack trace. </p>
<p>If you don't know, it is better to print the whole strack trace to find easily the error.</p> |
10,502,241 | java.lang.ClassNotFoundException: javax.servlet.ServletContainerInitializer | <p>I was working on writing some servlets and they all worked fine Tomcat had no issue running what so ever. Then I wrote a class file that used JERSEY and when I tried to run it Tomcat wouldn't start. I have the Web development tools plug in installed in Eclipse, everytime I hit compile I get </p>
<blockquote>
<p>java.lang.ClassNotFoundException: javax.servlet.ServletContainerInitializer</p>
</blockquote>
<p>Here is the output from the console </p>
<pre><code>May 08, 2012 4:51:36 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files (x86)\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files (x86)/Java/jre7/bin/client;C:/Program Files (x86)/Java/jre7/bin;C:/Program Files (x86)/Java/jre7/lib/i386;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\TortoiseSVN\bin;c:\Program Files (x86)\Microsoft SQL Server\90\Tools\bin\;C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE;C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN;C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools;C:\Windows\Microsoft.NET\Framework\v3.5;C:\Windows\Microsoft.NET\Framework\v2.0.50727;C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\VCPackages;C:\Python27\Scripts;C:\Program Files (x86)\SSH Communications Security\SSH Tectia\SSH Tectia AUX;C:\Program Files (x86)\SSH Communications Security\SSH Tectia\SSH Tectia AUX\Support binaries;C:\Program Files (x86)\SSH Communications Security\SSH Tectia\SSH Tectia Broker;C:\Program Files (x86)\SSH Communications Security\SSH Tectia\SSH Tectia Client;C:\Program Files\CREDANT\Shield v7.1\;C:\Development Tools\java\eclipse;;.
May 08, 2012 4:51:36 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Test_Server' did not find a matching property.
May 08, 2012 4:51:37 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-80"]
May 08, 2012 4:51:37 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
May 08, 2012 4:51:37 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 546 ms
May 08, 2012 4:51:37 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
May 08, 2012 4:51:37 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.27
May 08, 2012 4:51:37 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Test_Server]]
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1128)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Test_Server]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 7 more
Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletContainerInitializer
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1626)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.apache.catalina.startup.ContextConfig.getServletContainerInitializer(ContextConfig.java:1601)
at org.apache.catalina.startup.ContextConfig.processServletContainerInitializers(ContextConfig.java:1519)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1222)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:855)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:345)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletContainerInitializer
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 33 more
May 08, 2012 4:51:37 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1128)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Catalina.start(Catalina.java:675)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:450)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1136)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
May 08, 2012 4:51:37 PM org.apache.catalina.startup.Catalina start
SEVERE: Catalina.start:
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.startup.Catalina.start(Catalina.java:675)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:450)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1136)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more
May 08, 2012 4:51:37 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 416 ms
</code></pre>
<p>How is this caused and how can I solve it?</p> | 10,509,599 | 5 | 5 | null | 2012-05-08 16:05:40.74 UTC | 1 | 2016-09-02 12:48:43.113 UTC | 2015-06-28 08:25:54.993 UTC | null | 157,882 | null | 858,356 | null | 1 | 11 | java|eclipse|tomcat|servlets | 61,718 | <p><code>javax/servlet/ServletContainerInitializer</code> is a class in <code>Servlet 3.0</code> which is not support in Tomcat 6.</p>
<p>You probably have <code>servlet.jar</code> floating around somewhere in your CLASSPATH, it shouldn't be. This really messes up the classloaders since Tomcat's classloaders don't act quite as normal as one expects (see links above). <code>servlet.jar</code> should only be found only once in <code>$CATALINA_HOME/lib</code>. </p> |
10,536,136 | Why does session object throw a null reference exception? | <p>on some of my aspx page I am checking session like this</p>
<pre><code>if (bool.Parse(Session["YourAssessment"].ToString()) == false
&& bool.Parse(Session["MyAssessment"].ToString()) == true)
{
Response.Redirect("~/myAssessment.aspx");
}
</code></pre>
<p>It works fine if I keep playing with the pages frequently, but if I don't do anything with the page at least even for 5 min, running the page throws the error </p>
<pre><code>Object reference not set to an instance of an object.
</code></pre>
<p>Following is the stack for this</p>
<pre><code>[NullReferenceException: Object reference not set to an instance of an object.]
yourAssessment.Page_Load(Object sender, EventArgs e) in d:\Projects\NexLev\yourAssessment.aspx.cs:27
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
</code></pre>
<p>Could some body explain me this weird behaviour?</p>
<p>And as we know by default the session last for is 20 min.</p>
<p>EDITED</p>
<p>See I have a page default aspx, it has got a button which fixes on the some basis where to redirect
On default page it check like this</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (!HttpContext.Current.Request.IsAuthenticated)
{
Response.Redirect("~/login.aspx");
}
else
{
Session["YourAssessment"] = false;
Session["MyAssessment"] = false;
}
}
</code></pre>
<p>on button click it has</p>
<pre><code>protected void imgClientFreeEval_Click(object sender,
System.Web.UI.ImageClickEventArgs e)
{
if (HttpContext.Current.Request.IsAuthenticated)
{
string sqlQuery = "SELECT count(*) FROM SurveyClient WHERE UserID='"
+ cWebUtil.GetCurrentUserID().ToString() + "'";
SqlParameter[] arrParams = new SqlParameter[0];
int countSurvey = int.Parse(
Data.GetSQLScalerVarQueryResults(sqlQuery).ToString());
if (countSurvey > 0)
{
Session["YourAssessment"] = true;
Session["MyAssessment"] = false;
}
Response.Redirect((countSurvey > 0)
? "~/yourAssessment.aspx"
: "~/myAssessment.aspx");
}
else
{
Response.Redirect("~/login.aspx");
}
</code></pre>
<p>and on myAssessment page it check like this</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (!HttpContext.Current.Request.IsAuthenticated)
{
Response.Redirect("~/login.aspx");
}
else
{
if (Session["YourAssessment"] != null
&& Session["MyAssessment"] != null
&& bool.Parse(Session["YourAssessment"].ToString())
&& !bool.Parse(Session["myAssessment"].ToString()))
{
Response.Redirect("~/yourAssessment.aspx");
}
}
}
</code></pre>
<p>and on yourAssessmtn it check like this</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (!HttpContext.Current.Request.IsAuthenticated)
{
Response.Redirect("~/login.aspx");
}
else
{
if (Session["YourAssessment"] != null
&& Session["MyAssessment"] != null
&& !bool.Parse(Session["YourAssessment"].ToString())
&& bool.Parse(Session["MyAssessment"].ToString()))
{
Response.Redirect("~/myAssessment.aspx");
}
PopulateAllSurveyByUser();
if (ViewState["surveyClientID"] != null)
{
grdSurveyDetail.Visible = true;
PopulateSurveyDetails(
int.Parse(ViewState["surveyClientID"].ToString()));
}
else
{
grdSurveyDetail.Visible = false;
}
}
}
</code></pre>
<p>what's wrong please explain?</p> | 10,536,191 | 7 | 7 | null | 2012-05-10 14:25:49.127 UTC | 2 | 2018-04-23 08:56:50.793 UTC | 2018-04-23 08:56:50.793 UTC | null | 107,625 | null | 357,261 | null | 1 | 6 | c#|asp.net|session | 41,392 | <p>You first need to check whether that session variable exists</p>
<pre><code>if(Session["YourAssessment"] != null)
// Do something with it
else
// trying to call Session["YourAssessment"].ToString() here will FAIL.
</code></pre>
<p>That happens since your session has a lifecycle, which means - it expires (the cookie that defines it expires) - thus your objects vanish. you could increase <code>sessionState timeout</code> in web.config for your sessions to last longer.</p>
<p>For example, in web.config</p>
<pre><code> <system.web>
<sessionState timeout="40" />
</system.web>
</code></pre>
<p>Will make your sessions last for 40 minutes, as long as the client doesn't clear it, and the web server is up&running.</p> |
10,348,196 | make a temporary table and select from it | <p>I'm getting an error 'undeclared variable: temp' when I run this...</p>
<pre><code><?php
$maketemp = "CREATE TEMPORARY TABLE temp(`itineraryId` int NOT NULL, `live` varchar(1), `shipCode` varchar(10), `description` text, `duration` varchar(10), PRIMARY KEY(itineraryId))";
mysql_query( $maketemp, $connection ) or die ( "Sql error : " . mysql_error ( ) );
$inserttemp = "SELECT live, id AS itineraryId, ship AS shipCode, description AS description, duration AS length FROM cruises WHERE live ='Y' INTO temp";
mysql_query( $inserttemp, $connection ) or die ( "Sql error : " . mysql_error ( ) );
$select = "SELECT intineraryId, shipCode, description, duration FROM temp";
$export = mysql_query ( $select, $connection ) or die ( "Sql error : " . mysql_error( ) );
</code></pre>
<p>Any ideas ?</p> | 10,348,532 | 3 | 12 | null | 2012-04-27 09:30:40.343 UTC | 2 | 2019-05-25 11:58:31.74 UTC | 2012-04-27 13:00:39.667 UTC | user1280616 | null | null | 835,092 | null | 1 | 9 | php|mysql | 53,815 | <p><a href="https://stackoverflow.com/q/12859942/"><strong>Please, don't use <code>mysql_*</code> functions in new code</strong></a>. They are no longer maintained <a href="https://wiki.php.net/rfc/mysql_deprecation" rel="nofollow noreferrer">and are officially deprecated</a>. See the <a href="https://www.php.net/manual/en/function.mysql-connect.php" rel="nofollow noreferrer"><strong>red box</strong></a>? Learn about <a href="https://en.wikipedia.org/wiki/Prepared_statement" rel="nofollow noreferrer"><em>prepared statements</em></a> instead, and use <a href="http://php.net/pdo" rel="nofollow noreferrer">PDO</a> or <a href="http://php.net/mysqli" rel="nofollow noreferrer">MySQLi</a> - <a href="https://php.net/manual/en/mysqlinfo.api.choosing.php" rel="nofollow noreferrer">this article</a> will help you decide which. If you choose PDO, <a href="http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers" rel="nofollow noreferrer">here is a good tutorial</a>.</p>
<hr>
<p>This code should work:</p>
<pre><code><?php
$maketemp = "
CREATE TEMPORARY TABLE temp_table_1 (
`itineraryId` int NOT NULL,
`live` varchar(1),
`shipCode` varchar(10),
`description` text,
`duration` varchar(10),
PRIMARY KEY(itineraryId)
)
";
mysql_query($maketemp, $connection) or die ("Sql error : ".mysql_error());
$inserttemp = "
INSERT INTO temp_table_1
(`itineraryId`, `live`, `shipCode`, `description`, `duration`)
SELECT `id`, `live`, `ship`, `description`, `duration`
FROM `cruises`
WHERE `live` = 'Y'
";
mysql_query($inserttemp, $connection) or die ("Sql error : ".mysql_error());
$select = "
SELECT `itineraryId`, `shipCode`, `description`, `duration`
FROM temp_table_1
";
$export = mysql_query($select, $connection) or die ("Sql error : ".mysql_error());
</code></pre>
<p>I guess you are going to do more stuff with the temporary table, or are just playing with it, but if not be aware that the whole code could be summed up with:</p>
<pre><code><?php
$query = "
SELECT `id` AS 'itineraryId', `ship`, `description`, `duration`
FROM `cruises`
WHERE `live` = 'Y'
";
$export = mysql_query($query, $connection) or die ("Sql error : ".mysql_error());
</code></pre> |
41,140,187 | can not find module "@angular/material" | <p>I'm using Angular 2. When I'm trying to import "@angular/material" i'm getting error for this. I'm importing packages like:</p>
<pre><code>import {MdDialog} from "@angular/material";
import {MdDialogRef} from "@angular/material";
</code></pre>
<p>My tsconfig.json file like:</p>
<pre><code>{
"compilerOptions": {
"baseUrl": "",
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es6", "dom"],
"mapRoot": "./",
"module": "es6",
"moduleResolution": "node",
"outDir": "../dist/out-tsc",
"sourceMap": true,
"target": "es5",
"typeRoots": [
"../node_modules/@types"
]
}
}
</code></pre>
<p>My package.json code:</p>
<pre><code>{
"name": "rmc-temporary",
"version": "0.0.0",
"license": "MIT",
"angular-cli": {},
"scripts": {
"start": "ng serve",
"lint": "tslint \"src/**/*.ts\"",
"test": "ng test",
"pree2e": "webdriver-manager update",
"e2e": "protractor"
},
"private": true,
"dependencies": {
"@angular/common": "2.2.1",
"@angular/compiler": "2.2.1",
"@angular/core": "2.2.1",
"@angular/forms": "2.2.1",
"@angular/http": "2.2.1",
"@angular/platform-browser": "2.2.1",
"@angular/platform-browser-dynamic": "2.2.1",
"@angular/router": "3.2.1",
"core-js": "^2.4.1",
"rxjs": "5.0.0-beta.12",
"ts-helpers": "^1.1.1",
"zone.js": "^0.6.23"
},
"devDependencies": {
"@angular/compiler-cli": "2.2.1",
"@types/jasmine": "2.5.38",
"@types/node": "^6.0.42",
"angular-cli": "1.0.0-beta.21",
"codelyzer": "~1.0.0-beta.3",
"jasmine-core": "2.5.2",
"jasmine-spec-reporter": "2.5.0",
"karma": "1.2.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-remap-istanbul": "^0.2.1",
"protractor": "4.0.9",
"ts-node": "1.2.1",
"tslint": "3.13.0",
"typescript": "~2.0.3",
"webdriver-manager": "10.2.5"
}
}
</code></pre> | 44,156,815 | 10 | 7 | null | 2016-12-14 10:25:11.853 UTC | 14 | 2021-08-09 07:42:31.113 UTC | 2016-12-14 10:31:50.897 UTC | null | 4,927,984 | null | 6,624,422 | null | 1 | 61 | angular|typescript | 177,544 | <p>Follow these steps to begin using Angular Material.</p>
<p><strong>Step 1: Install Angular Material</strong></p>
<pre><code>npm install --save @angular/material
</code></pre>
<p><strong>Step 2: Animations</strong></p>
<p>Some Material components depend on the Angular animations module in order to be able to do more advanced transitions. If you want these animations to work in your app, you have to install the <code>@angular/animations</code> module and include the BrowserAnimationsModule in your app.</p>
<pre><code>npm install --save @angular/animations
</code></pre>
<p>Then</p>
<pre><code>import {BrowserAnimationsModule} from '@angular/platform browser/animations';
@NgModule({
...
imports: [BrowserAnimationsModule],
...
})
export class PizzaPartyAppModule { }
</code></pre>
<p><strong>Step 3: Import the component modules</strong></p>
<p>Import the NgModule for each component you want to use:</p>
<pre><code>import {MdButtonModule, MdCheckboxModule} from '@angular/material';
@NgModule({
...
imports: [MdButtonModule, MdCheckboxModule],
...
})
export class PizzaPartyAppModule { }
</code></pre>
<p>be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules</p>
<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdCardModule} from '@angular/material';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
HomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MdCardModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p><strong>Step 4: Include a theme</strong> </p>
<p>Including a theme is required to apply all of the core and theme styles to your application.</p>
<p>To get started with a prebuilt theme, include the following in your app's index.html:</p>
<pre><code><link href="../node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
</code></pre> |
13,507,721 | how to delete a file from folder in php | <p>I have a folder <code>'items'</code> in which there are 3 files <code>item1.txt, item2.txt and item3.txt.</code>
I want to <code>delete item2.txt</code> file from folder. I am using the below code but it not deleting a file from folder. Can any body help me in that.</p>
<pre><code><?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($file);
}
}
closedir($dirHandle);
?>
</code></pre> | 13,507,775 | 6 | 3 | null | 2012-11-22 07:29:17.12 UTC | 5 | 2020-10-26 10:42:37.877 UTC | 2017-03-13 08:31:23.447 UTC | null | 6,887,672 | null | 983,887 | null | 1 | 9 | php|file|delete-file | 71,604 | <p>Initially the folder should have 777 permissions</p>
<pre class="lang-php prettyprint-override"><code>$data = "item2.txt";
$dir = "items";
while ($file = readdir($dirHandle)) {
if ($file==$data) {
unlink($dir.'/'.$file);
}
}
</code></pre>
<p>or try</p>
<pre class="lang-php prettyprint-override"><code>$path = $_SERVER['DOCUMENT_ROOT'].'items/item2.txt';
unlink($path);
</code></pre> |
13,423,593 | Eclipse 4.2 (Juno) 'Cannot create a server using the selected type' in Tomcat 7 | <p>I have installed:</p>
<ul>
<li>eclipse juno</li>
<li>java-6-openjdk-i386 (selected as default JRE in Eclipse)</li>
<li>java-7-openjdk-i386</li>
</ul>
<p>When I try to add a new server Tomcat7, in Eclipse, I get this message </p>
<p><strong>'Cannot create a server using the selected type'</strong></p>
<p>and I can not continue. No problem adding Tomcat6 server.</p>
<p>I read this <a href="https://stackoverflow.com/questions/8025841/eclipse-3-7-indigo-tomcat7-cannot-create-a-server-using-the-selected-typ">question</a> but it didn't solve it for me </p> | 13,426,349 | 8 | 1 | null | 2012-11-16 20:01:46.117 UTC | 39 | 2020-02-07 16:04:28.807 UTC | 2020-02-07 16:04:28.807 UTC | null | 12,409,240 | null | 953,263 | null | 1 | 54 | eclipse|tomcat|tomcat7|ubuntu-12.04|eclipse-juno | 47,748 | <p>1 . To fix the error <strong>'Cannot create a server using the selected type'</strong> run the following:</p>
<pre><code>cd ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/
rm org.eclipse.jst.server.tomcat.core.prefs
rm org.eclipse.wst.server.core.prefs
</code></pre>
<p>2 . Once you do this, another error </p>
<p><strong>'Could not load the Tomcat server configuration at /usr/share/tomcat7/conf. The configuration may be corrupt or incomplete /usr/share/tomcat7/conf/catalina.policy (No such file or directory)'</strong> </p>
<p>So to fix this run the following commands:</p>
<pre><code>cd /usr/share/tomcat7
sudo ln -s /var/lib/tomcat7/conf conf
sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy
sudo ln -s /var/log/tomcat7 log
sudo chmod -R 777 /usr/share/tomcat7/conf
</code></pre>
<p>3 . Restart server and Eclipse</p>
<p>4 . Add new server</p>
<ul>
<li>Choose the Servers under the Server category;</li>
<li>Create <strong>new server wizard</strong>;</li>
<li>Choose <strong>Apache / Tomcat v7.0 Server</strong> and press Next;</li>
<li>Enter <strong>/usr/share/tomcat7</strong> into the <strong>Tomcat installation directory</strong> and press Next;</li>
<li>Select your project on the left pane under “Available” and press Add> to move it to the right pane under <strong>Configured</strong>; press <strong>Finish</strong>;</li>
</ul>
<p>Eclipse need to start the server, and to do that, first, it has to stop the one running in background.</p>
<blockquote>
<p>sudo service tomcat7 stop</p>
</blockquote>
<p>If you don't have to automatically start at boot, we can use the following command</p>
<blockquote>
<p>sudo update-rc.d tomcat7 disable</p>
</blockquote>
<p>If, during server start, you receive warnings like:</p>
<pre><code>WARNING: Problem with directory [/usr/share/tomcat7/common/classes], exists: [false], isDirectory: [false], canRead: [false]
WARNING: Problem with directory [/usr/share/tomcat7/common], exists: [false], isDirectory: [false], canRead: [false]
WARNING: Problem with directory [/usr/share/tomcat7/server/classes], exists: [false], isDirectory: [false], canRead: [false]
WARNING: Problem with directory [/usr/share/tomcat7/server], exists: [false], isDirectory: [false], canRead: [false]
WARNING: Problem with directory [/usr/share/tomcat7/shared/classes], exists: [false], isDirectory: [false], canRead: [false]
WARNING: Problem with directory [/usr/share/tomcat7/shared], exists: [false], isDirectory: [false], canRead: [false]
</code></pre>
<p>You may also need to run the following:</p>
<pre><code>cd /usr/share/tomcat7
sudo ln -s /var/lib/tomcat7/common common
sudo ln -s /var/lib/tomcat7/server server
sudo ln -s /var/lib/tomcat7/shared shared
</code></pre> |
13,336,576 | Extracting an information from web page by machine learning | <p>I would like to <strong>extract a specific type of information from web pages</strong> in Python. Let's say postal address. It has thousands of forms, but still, it is somehow recognizable. As there is a large number of forms, it would be probably very difficult to write <strong>regular expression</strong> or even something like a <strong>grammar</strong> and to use a <strong>parser generator</strong> for parsing it out.</p>
<p>So I think the way I should go is <strong>machine learning</strong>. If I understand it well, I should be able to make a sample of data where I will point out what should be the result and then I have something which can learn from this how to recognize the result by itself. This is all I know about machine learning. Maybe I could use some <strong>natural language</strong> processing, but probably not much as all the libraries work with English mostly and I need this for Czech.</p>
<p>Questions:</p>
<ol>
<li>Can I solve this problem easily by machine learning? Is it a good way to go?</li>
<li>Are there any <strong>simple</strong> examples which would allow me to start? I am machine learning noob and I need something practical for start; closer to my problem is better; simpler is better.</li>
<li>There are plenty of Python libraries for machine learning. Which one would suit my problem best?</li>
<li>Lots of such libs have not very easy-to-use docs as they come from scientific environment. Are there any good sources (books, articles, quickstarts) bridging the gap, i.e. focused on newbies who know totally nothing about machine learning? Every docs I open start with terms I don't understand such as <em>network</em>, <em>classification</em>, <em>datasets</em>, etc.</li>
</ol>
<p>Update:</p>
<p>As you all mentioned I should show a piece of data I am trying to get out of the web, here is an example. I am interested in cinema <em>showtimes</em>. They look like this (three of them):</p>
<pre><code><div class="Datum" rel="d_0">27. června – středa, 20.00
</div><input class="Datum_cas" id="2012-06-27" readonly=""><a href="index.php?den=0" rel="0" class="Nazev">Zahájení letního kina
</a><div style="display: block;" class="ajax_box d-0">
<span class="ajax_box Orig_nazev">zábava • hudba • film • letní bar
</span>
<span class="Tech_info">Svět podle Fagi
</span>
<span class="Popis">Facebooková komiksová Fagi v podání divadla DNO. Divoké písně, co nezařadíte, ale slušně si na ně zařádíte. Slovní smyčky, co se na nich jde oběsit. Kabaret, improvizace, písně, humor, zběsilost i v srdci.<br>Koncert Tres Quatros Kvintet. Instrumentální muzika s pevným funkovým groovem, jazzovými standardy a neodmyslitelnými improvizacemi.
</span>
<input class="Datum_cas" id="ajax_0" type="text">
</div>
<div class="Datum" rel="d_1">27. června – středa, 21.30
</div><input class="Datum_cas" id="2012-06-27" readonly=""><a href="index.php?den=1" rel="1" class="Nazev">Soul Kitchen
</a><div style="display: block;" class="ajax_box d-1">
<span class="ajax_box Orig_nazev">Soul Kitchen
</span>
<span class="Tech_info">Komedie, Německo, 2009, 99 min., čes. a angl. tit.
</span>
<span class="Rezie">REŽIE: Fatih Akin
</span>
<span class="Hraji">HRAJÍ: Adam Bousdoukos, Moritz Bleibtreu, Birol Ünel, Wotan Wilke Möhring
</span>
<span class="Popis">Poslední film miláčka publika Fatiho Akina, je turbulentním vyznáním lásky multikulturnímu Hamburku. S humorem zde Akin vykresluje příběh Řeka žijícího v Německu, který z malého bufetu vytvoří originální restauraci, jež se brzy stane oblíbenou hudební scénou. "Soul Kitchen" je skvělá komedie o přátelství, lásce, rozchodu a boji o domov, který je třeba v dnešním nevypočitatelném světě chránit víc než kdykoliv předtím. Zvláštní cena poroty na festivalu v Benátkách
</span>
<input class="Datum_cas" id="ajax_1" type="text">
</div>
<div class="Datum" rel="d_2">28. června – čtvrtek, 21:30
</div><input class="Datum_cas" id="2012-06-28" readonly=""><a href="index.php?den=2" rel="2" class="Nazev">Rodina je základ státu
</a><div style="display: block;" class="ajax_box d-2">
<span class="Tech_info">Drama, Česko, 2011, 103 min.
</span>
<span class="Rezie">REŽIE: Robert Sedláček
</span>
<span class="Hraji">HRAJÍ: Igor Chmela, Eva Vrbková, Martin Finger, Monika A. Fingerová, Simona Babčáková, Jiří Vyorálek, Jan Fišar, Jan Budař, Marek Taclík, Marek Daniel
</span>
<span class="Popis">Když vám hoří půda pod nohama, není nad rodinný výlet. Bývalý učitel dějepisu, který dosáhl vysokého manažerského postu ve významném finančním ústavu, si řadu let spokojeně žije společně se svou rodinou v luxusní vile na okraji Prahy. Bezstarostný život ale netrvá věčně a na povrch začnou vyplouvat machinace s penězi klientů týkající se celého vedení banky. Libor se následně ocitá pod dohledem policejních vyšetřovatelů, kteří mu začnou tvrdě šlapat na paty. Snaží se uniknout před hrozícím vězením a oddálit osvětlení celé situace své nic netušící manželce. Rozhodne se tak pro netradiční útěk, kdy pod záminkou společné dovolené odveze celou rodinu na jižní Moravu… Rodinný výlet nebo zoufalý úprk před spravedlností? Igor Chmela, Eva Vrbková a Simona Babčáková v rodinném dramatu a neobyčejné road-movie inspirované skutečností.
</span>
</code></pre>
<p>Or like this:</p>
<pre><code><strong>POSEL&nbsp;&nbsp; 18.10.-22.10 v 18:30 </strong><br>Drama. ČR/90´. Režie: Vladimír Michálek Hrají: Matěj Hádek, Eva Leinbergerová, Jiří Vyorávek<br>Třicátník Petr miluje kolo a své vášni podřizuje celý svůj život. Neplánuje, neplatí účty, neřeší nic, co může<br>počkat do zítra. Budování společného života s přételkyní je mu proti srsti stejně jako dělat kariéru. Aby mohl jezdit na kole, raději pracuje jako poslíček. Jeho život je neřízená střela, ve které neplatí žádná pravidla. Ale problémy se na sebe na kupí a je stále těžší před nimi ujet …<br> <br>
<strong>VE STÍNU&nbsp; 18.10.-24.10. ve 20:30 a 20.10.-22.10. též v 16:15</strong><br>Krimi. ČR/98´. Režie: D.Vondříček Hrají: I.Trojan, S.Koch, S.Norisová, J.Štěpnička, M.Taclík<br>Kapitán Hakl (Ivan Trojan) vyšetřuje krádež v klenotnictví. Z běžné vloupačky se ale vlivem zákulisních intrik tajné policie začíná stávat politická kauza. Z nařízení Státní bezpečnosti přebírá Haklovo vyšetřování major Zenke (Sebastian Koch), policejní specialista z NDR, pod jehož vedením se vyšetřování ubírá jiným směrem, než Haklovi napovídá instinkt zkušeného kriminalisty. Na vlastní pěst pokračuje ve vyšetřování. Může jediný spravedlivý obstát v boji s dobře propojenou sítí komunistické policie?&nbsp; Protivník je silný a Hakl se brzy přesvědčuje, že věřit nelze nikomu a ničemu. Každý má svůj stín minulosti, své slabé místo, které dokáže z obětí udělat viníky a z viníků hrdiny. <br><br>
<strong>ASTERIX A OBELIX VE SLUŽBÁCH JEJÍHO VELIČENSTVA&nbsp; ve 3D&nbsp;&nbsp;&nbsp; 20.10.-21.10. ve 13:45 </strong><br>Dobrodružná fantazy. Fr./124´. ČESKÝ DABING. Režie: Laurent Tirard<br>Hrají: Gérard Depardieu, Edouard Baer, Fabrice Luchini<br>Pod vedením Julia Caesara napadly proslulé římské legie Británii. Jedné malé vesničce se však daří statečně odolávat, ale každým dnem je slabší a slabší. Britská královna proto vyslala svého věrného důstojníka Anticlimaxe, aby vyhledal pomoc u Galů v druhé malinké vesničce ve Francii vyhlášené svým důmyslným bojem proti Římanům… Když Anticlimax popsal zoufalou situaci svých lidí, Galové mu darovali barel svého kouzelného lektvaru a Astérix a Obélix jsou pověřeni doprovodit ho domů. Jakmile dorazí do Británie, Anticlimax jim představí místní zvyky ve vší parádě a všichni to pořádně roztočí! Vytočený Caesar se však rozhodne naverbovat Normanďany, hrůzu nahánějící bojovníky Severu, aby jednou provždy skoncovali s Brity. <br><br>
</code></pre>
<p>Or it can look like anything similar to this. No special rules in HTML markup, no special rules in order, etc.</p> | 13,444,345 | 7 | 4 | null | 2012-11-11 23:27:23.267 UTC | 54 | 2021-07-23 07:24:37.753 UTC | 2012-11-12 09:03:25.007 UTC | null | 325,365 | null | 325,365 | null | 1 | 82 | python|machine-learning|html-parsing|web-scraping|extract | 44,878 | <p>First, your task fits into the <strong>information extraction</strong> area of research. There are mainly 2 levels of complexity for this task:</p>
<ul>
<li>extract from a given html page or a website with the fixed template
(like Amazon). In this case the best way is to look at the HTML code
of the pages and craft the corresponding XPath or DOM selectors to
get to the right info. The disadvantage with this approach is that it
is not generalizable to new websites, since you have to do it for
each website one by one.</li>
<li>create a model that extracts same
information from many websites within one domain (having an
assumption that there is some inherent regularity in the way web
designers present the corresponding attribute, like zip or phone or whatever else). In this case you should create some features (to use ML approach and let IE algorithm to "understand the content of pages"). The most common features are: DOM path, the format of the value (attribute) to be extracted, layout (like bold, italic and etc.), and surrounding context words. You label some values (you need at least 100-300 pages depending on domain to do it with some sort of reasonable quality). Then you train a model on the labelled pages. There is also an alternative to it - to do IE in unsupervised manner (leveraging the idea of information regularity across pages). In this case you/your algorith tries to find repetitive patterns across pages (without labelling) and consider as valid those, that are the most frequent. </li>
</ul>
<p>The most challenging part overall will be to work with DOM tree and generate the right features. Also data labelling in the right way is a tedious task. For ML models - have a look at <strong>CRF, 2DCRF, semi-markov CRF</strong>. </p>
<p>And finally, this is in the general case a cutting edge in IE research and not a hack that you can do it a few evenings. </p>
<p>p.s. also I think NLTK will not be very helpful - it is an NLP, not Web-IE library.</p> |
51,946,571 | How can I get Python 3.7 new dataclass field types? | <p>Python 3.7 introduces new feature called data classes.</p>
<pre><code>from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
</code></pre>
<p>When using type hints (annotation) in function parameters, you can easily get annotated types using inspect module. How can I get dataclass field types?</p> | 51,946,806 | 3 | 3 | null | 2018-08-21 10:22:45.42 UTC | 3 | 2022-08-14 23:55:26.937 UTC | 2022-08-14 23:55:26.937 UTC | null | 523,612 | null | 3,105,524 | null | 1 | 59 | python|python-3.7|python-dataclasses | 58,702 | <pre><code>from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
myclass = MyClass()
myclass.__annotations__
>> {'id': int, 'name': str}
myclass.__dataclass_fields__
>> {'id': Field(name='id',type=<class 'int'>,default=0,default_factory=<dataclasses._MISSING_TYPE object at 0x0000000004EED668>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD),
'name': Field(name='name',type=<class 'str'>,default='',default_factory=<dataclasses._MISSING_TYPE object at 0x0000000004EED668>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)}
</code></pre>
<p>on a side note there is also:</p>
<pre><code>myclass.__dataclass_params__
>>_DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)
</code></pre> |
39,853,646 | How to import a CSS file in a React Component | <p>I want to import a CSS file into a react component.</p>
<p>I've tried <code>import disabledLink from "../../../public/styles/disabledLink";</code> but I get the error below;</p>
<blockquote>
<p>Module not found: Error: Cannot resolve 'file' or 'directory' ../../../public/styles/disabledLink in c:\Users\User\Documents\pizza-app\client\src\components @ ./client/src/components/ShoppingCartLink.js 19:20-66 Hash: 2d281bb98fe0a961f7c4 Version: webpack 1.13.2</p>
</blockquote>
<p><code>C:\Users\User\Documents\pizza-app\client\public\styles\disabledLink.css</code> is the location of the CSS file I'm trying to load.</p>
<p>To me it seems like import is not looking up the correct path.</p>
<p>I thought with <code>../../../</code> it would start to look up the path three folder layers above.</p>
<p><code>C:\Users\User\Documents\pizza-app\client\src\components\ShoppingCartLink.js</code> is the location of the file that should import the CSS file.</p>
<p>What am I doing wrong and how can I fix it?</p> | 46,386,097 | 12 | 4 | null | 2016-10-04 13:28:18.66 UTC | 33 | 2022-01-15 04:57:52.307 UTC | 2020-01-26 16:55:29.127 UTC | null | 6,381,711 | null | 6,858,589 | null | 1 | 153 | javascript|reactjs|relative-path | 470,033 | <p>You don't even have to name it if you don't need to: </p>
<p>e.g.</p>
<pre><code>import React from 'react';
import './App.css';
</code></pre>
<p>see a complete example here (<a href="https://egghead.io/lessons/build-a-jsx-live-compiler" rel="noreferrer">Build a JSX Live Compiler as a React Component</a>).</p> |
3,814,804 | Initializing a static const char* array | <p>here is my question I have this in my .h file</p>
<pre><code>static const char *Title[];
</code></pre>
<p>How do I initialize the array in my .C file the array to lets say "first", "second", "third"</p> | 3,814,821 | 2 | 2 | null | 2010-09-28 16:12:14.45 UTC | 3 | 2012-08-03 08:15:32.68 UTC | null | null | null | null | 261,842 | null | 1 | 8 | static|char|constants | 44,349 | <p><code>static const char* Title[] = { "first", "second", "third" };</code></p>
<p>Check out this little blurb on <a href="http://publications.gbdirect.co.uk/c_book/chapter6/initialization.html" rel="noreferrer">initialization</a>. Why do you want to do it in separate files? You'll have to do externs.</p>
<pre><code>// in .h
extern const char* Title[];
// in .c
const char* Title[] = { "first", "second" };
</code></pre> |
9,418,554 | Starting a new thread in a foreach loop | <p>I have a List of objects and I'd like to loop over that list and start a new thread, passing in the current object.</p>
<p>I've written an example of what I thought should do this, but it's not working. Specifically, it seems like the threads are getting overwritten on each iteration. This doesn't really make sense to me though because I'm making a new Thread object each time.</p>
<p>This is the test code I wrote</p>
<pre><code>class Program
{
static void Main(string[] args)
{
TestClass t = new TestClass();
t.ThreadingMethod();
}
}
class TestClass
{
public void ThreadingMethod()
{
var myList = new List<MyClass> { new MyClass("test1"), new MyClass("test2") };
foreach(MyClass myObj in myList)
{
Thread myThread = new Thread(() => this.MyMethod(myObj));
myThread.Start();
}
}
public void MyMethod(MyClass myObj) { Console.WriteLine(myObj.prop1); }
}
class MyClass
{
public string prop1 { get; set; }
public MyClass(string input) { this.prop1 = input; }
}
</code></pre>
<p>The output on my machine is</p>
<pre><code>test2
test2
</code></pre>
<p>but I expected it to be</p>
<pre><code>test1
test2
</code></pre>
<p>I tried changing the thread lines to</p>
<pre><code>ThreadPool.QueueUserWorkItem(x => this.MyMethod(myObj));
</code></pre>
<p>but none of the threads started.</p>
<p>I think I just have a misunderstanding about how threads are supposed to work. Can someone point me in the right direction and tell me what I'm doing wrong?</p> | 9,418,565 | 5 | 2 | null | 2012-02-23 18:00:15.557 UTC | 7 | 2013-04-17 12:15:18.573 UTC | null | null | null | null | 817,630 | null | 1 | 25 | c#|.net|multithreading|foreach | 41,270 | <p>This is because you're closing over a variable in the wrong scope. The solution here is to use a temporary in your foreach loop:</p>
<pre><code> foreach(MyClass myObj in myList)
{
MyClass tmp = myObj; // Make temporary
Thread myThread = new Thread(() => this.MyMethod(tmp));
myThread.Start();
}
</code></pre>
<p>For details, I recommend reading Eric Lippert's post on this exact subject: <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx">Closing over the loop variable considered harmful</a></p> |
16,040,567 | Use Awk to extract substring | <p>Given a hostname in format of <code>aaa0.bbb.ccc</code>, I want to extract the first substring before <code>.</code>, that is, <code>aaa0</code> in this case. I use following awk script to do so,</p>
<pre><code>echo aaa0.bbb.ccc | awk '{if (match($0, /\./)) {print substr($0, 0, RSTART - 1)}}'
</code></pre>
<p>While the script running on one machine <code>A</code> produces <code>aaa0</code>, running on machine <code>B</code> produces only <code>aaa</code>, without <code>0</code> in the end. Both machine runs <code>Ubuntu/Linaro</code>, but <code>A</code> runs newer version of awk(gawk with version 3.1.8 while <code>B</code> with older awk (mawk with version 1.2)</p>
<p>I am asking in general, how to write a compatible awk script that performs the same functionality ...</p> | 16,040,609 | 7 | 0 | null | 2013-04-16 15:07:20.773 UTC | 12 | 2022-07-08 04:28:41.833 UTC | null | null | null | null | 486,720 | null | 1 | 38 | bash|awk | 152,666 | <p>You just want to set the field separator as <code>.</code> using the <code>-F</code> option and print the first field:</p>
<pre><code>$ echo aaa0.bbb.ccc | awk -F'.' '{print $1}'
aaa0
</code></pre>
<p>Same thing but using cut:</p>
<pre><code>$ echo aaa0.bbb.ccc | cut -d'.' -f1
aaa0
</code></pre>
<p>Or with <code>sed</code>:</p>
<pre><code>$ echo aaa0.bbb.ccc | sed 's/[.].*//'
aaa0
</code></pre>
<p>Even <code>grep</code>:</p>
<pre><code>$ echo aaa0.bbb.ccc | grep -o '^[^.]*'
aaa0
</code></pre> |
16,103,810 | Force my local master to be origin/master | <p>I've let master and origin/master get stuck in the sidelines, and am no longer interested in the changes on that branch.</p>
<p>I followed these instructions to get my local master pointing to the right place
<a href="https://stackoverflow.com/questions/2763006/change-the-current-branch-to-master-in-git">Make the current git branch a master branch</a></p>
<pre><code> git checkout better_branch
git merge --strategy=ours master # keep the content of this branch, but record a merge
git checkout master
git merge better_branch # fast-forward master up to the merge
</code></pre>
<p>which worked fine except git status gives</p>
<pre><code>C:\data\localprojects\Beko2011Azure [master]> git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 395 and 2 different commits each, respectively.
#
nothing to commit, working directory clean
</code></pre>
<p>so how do I now persuade origin/master (github) to reflect my master. Anything orphaned on origin/master can be safely abandoned.</p> | 16,103,915 | 2 | 0 | null | 2013-04-19 11:42:04.197 UTC | 17 | 2020-09-09 04:42:30.083 UTC | 2017-05-23 11:47:13.56 UTC | null | -1 | null | 107,565 | null | 1 | 44 | git|github|branch | 51,285 | <p>To have <code>origin/master</code> the same as <code>master</code>:</p>
<pre><code>git push -f origin master:master
</code></pre>
<p>Discussion on the parameters: </p>
<ul>
<li><p><code>-f</code> is the <strong>force</strong> flag. Normally, some checks are being applied before it's allowed to push to a branch. The <code>-f</code> flag turns off all checks.</p></li>
<li><p><code>origin</code> is the name of the remote where to push (you could have several remotes in one repo)</p></li>
<li><p><code>master:master</code> means: push my local branch <code>master</code> to the remote branch <code>master</code>. The general form is <code>localbranch:remotebranch</code>. Knowing this is especially handy when you want to delete a branch on the remote: in that case, you push an empty local branch to the remote, thus deleting it: <code>git push origin :remote_branch_to_be_deleted</code></p></li>
</ul>
<p>A more elaborate description of the parameters could be found with <a href="https://www.kernel.org/pub/software/scm/git/docs/git-push.html" rel="noreferrer"><code>man git-push</code></a></p>
<hr>
<p><strong>Opposite direction:</strong> If you want to throw away all your changes on <code>master</code> and want to have it exactly the same as <code>origin/master</code>:</p>
<pre><code>git checkout master
git reset --hard origin/master
</code></pre> |
16,538,372 | Git proxy bypass | <p>Git works in a proxied environment by setting the http.proxy configuration parameter. </p>
<p>For certain addresses I need to bypass the proxy. Is there a no-proxy/bypass-proxy configuration parameter?</p> | 16,612,442 | 10 | 1 | null | 2013-05-14 08:28:21.82 UTC | 23 | 2022-08-25 09:40:46.62 UTC | null | null | null | null | 281,121 | null | 1 | 71 | git|http|proxy | 116,460 | <p>The proxy can be overridden on a per-remote basis - see <a href="http://git-scm.com/docs/git-config">http://git-scm.com/docs/git-config</a>
(look for the "http.proxy" and "remote.<name>.proxy" settings). Assuming you have the remote called "origin" then the command you could use to bypass proxy for this remote is:</p>
<pre><code>git config --add remote.origin.proxy ""
</code></pre> |
13,150,452 | Two's complement in verilog | <p>I've been trying to build a module which returns the two's complement representation of the (3-bit) input (first bit being the sign). I think that the following code is correct conceptually, but I am probably missing something about it's structure: when I try to compile, I get the following errors:</p>
<pre><code>(vlog-2110) Illegal reference to net "f_o".
(vlog-2110) Illegal reference to net "f_o".
(vlog-2110) Illegal reference to net "f_o".
</code></pre>
<p>Searching for that error showed it is usually seen when using a variable as input and output at the same time, but that's not my case. Could you point where the error is?</p>
<pre><code>module ca2 (a_i,f_o);
input [2:0] a_i;
output [2:0] f_o;
always @(a_i[2:0] or f_o[2:0])
begin
if (a_i[2] == 1)
begin
f_o[2] = a_i[2];
f_o[1:0] = (~a_i[1:0] + 'b1);
end
else
begin
f_o = a_i;
end
end
endmodule
</code></pre> | 13,150,960 | 3 | 0 | null | 2012-10-31 02:32:31.85 UTC | null | 2021-07-27 11:20:35.043 UTC | 2012-10-31 08:43:51.42 UTC | null | 97,073 | null | 1,431,591 | null | 1 | 5 | verilog | 46,637 | <p>In Verilog, undeclared identifiers are considered implicit wire declarations in most circumstances. Since f_o has not been declared the compiler considers it a wire, not a variable. This causes the compiler to complain about all the assignments.</p>
<pre><code>// What was typed
module ca2 (a_i,f_o);
input [2:0] a_i;
output [2:0] f_o;
// What the compiler implicitly declares
wire [2:0] a_i;
wire [2:0] f_o;
</code></pre>
<p>To fix it you can declare the variable or declare both the port and the variable.</p>
<pre><code>module ca2 (a_i,f_o);
input [2:0] a_i;
output [2:0] f_o;
reg [2:0] f_o;
module ca2 (a_i,f_o);
input [2:0] a_i;
output reg [2:0] f_o;
</code></pre> |
17,485,548 | Search particular word in PDF using iTextSharp | <p>I have a PDF file in my System drive. I want to write a program in C# using iTextSharp to search for a particular word in that PDF.</p>
<p>Say I want to search "StackOverFlow": If the PDF contains the Word "StackOverFlow", it should return true, else it should return false.</p>
<p>What I have tried till now is:</p>
<pre><code>public string ReadPdfFile(string fileName)
{
StringBuilder text = new StringBuilder();
if (File.Exists(fileName))
{
PdfReader pdfReader = new PdfReader(fileName);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = "2154/MUM/2012 A";// PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
}
pdfReader.Close();
}
return text.ToString();
}
</code></pre> | 17,486,097 | 1 | 1 | null | 2013-07-05 09:29:27.753 UTC | 9 | 2022-06-01 22:12:13.63 UTC | 2022-06-01 22:12:13.63 UTC | null | 8,528,014 | null | 2,553,159 | null | 1 | 13 | c#|pdf|itext | 26,531 | <p>The following method works fine. It gives the list of pages in which the text is found.</p>
<pre class="lang-cs prettyprint-override"><code>public List<int> ReadPdfFile(string fileName, String searthText)
{
List<int> pages = new List<int>();
if (File.Exists(fileName))
{
PdfReader pdfReader = new PdfReader(fileName);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentPageText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
if (currentPageText.Contains(searthText))
{
pages.Add(page);
}
}
pdfReader.Close();
}
return pages;
}
</code></pre> |
37,349,314 | Is it possible to add border to image in GitHub markdown? | <p>I need to add border to the image in GitHub README.md file. This is how image should be embeded:</p>
<pre><code>
</code></pre>
<p>I have tried to wrap image with the table:</p>
<pre><code>|--------------------------------|
||
</code></pre>
<p>but it is not possible to create table without header.</p>
<p>I have also tried to include image as html tag:</p>
<pre><code><img src="/images/logo.png" style="border: 1px solid black" />
</code></pre>
<p>but without success. Is there any way how to do this?</p> | 38,923,123 | 8 | 2 | null | 2016-05-20 14:26:15.17 UTC | 13 | 2022-08-20 04:56:20.83 UTC | null | null | null | null | 741,871 | null | 1 | 86 | html|github|markdown | 39,899 | <p>It's hacky and not always pretty, but surround the image with a <code><kbd></code> tag.</p>
<h1>Before</h1>
<pre><code><img src="https://i.stack.imgur.com/CtiyS.png">
</code></pre>
<h1>After</h1>
<pre><code><kbd>
<img src="https://i.stack.imgur.com/CtiyS.png">
</kbd>
</code></pre>
<p>And it renders like this:</p>
<kbd>
<img src="https://i.stack.imgur.com/CtiyS.png">
</kbd>
<hr />
<p><strong>Surrounding the <em>markdown</em> image syntax might not work for some markdown implementations.</strong> If the following does not work</p>
<pre><code><kbd></kbd>
</code></pre>
<p>Try embedding the image as an HTML <code><img></code> tag instead</p>
<pre><code><kbd><img src="https://example.com/image.png" /></kbd>
</code></pre> |
19,351,151 | Remove position:absolute attribute by adding css | <p>I have a html element with id="#item" I have a UI event that programaticaly alters the css for "#item" by adding the class ".new" to "#item". Initially I want "#item" to have "position:absolute". However once the class ".new" is added to "#item" the only way I can get the formatting I want in Chrome inspector is to removed position:absolute from the css for "#item". I'd like to accomplish this instead via the css in ".new", however in Chrome inspector my options for changing the position attribute are</p>
<pre><code>static
absolute
relative
initial
inherit
fixed
</code></pre>
<p>As far as I can tell none of these do the same thing as removing "position:absolute" in Chrome inspector. Can anyone suggest what to put in the css for ".new" to revert to the css default positioning.</p> | 19,351,233 | 3 | 3 | null | 2013-10-13 22:41:37.907 UTC | 1 | 2020-06-30 19:49:48.313 UTC | null | null | null | null | 996,035 | null | 1 | 25 | html|css|dynamic|position|css-position | 96,763 | <p><a href="http://jsbin.com/ICeweli/1/" rel="noreferrer">http://jsbin.com/ICeweli/1/</a></p>
<pre><code>#test {
position: absolute;
}
#test {
position: static;
}
</code></pre>
<p>Remove one or the other to see the difference.</p> |
17,226,779 | Django humanize outside of template? | <p>I know I can use the humanize module to convert date/time to a friendlier format in the django templates. I was wondering if I can convert those things outside the templates. For example in a <code>views.py</code> function or a <code>models.py</code> class(meaning outside of a django template). Is there any other library that can do that?</p> | 17,226,840 | 1 | 0 | null | 2013-06-21 02:22:00.077 UTC | 3 | 2020-03-05 20:00:37.297 UTC | 2020-03-05 20:00:37.297 UTC | null | 9,789,097 | null | 926,011 | null | 1 | 33 | python|django|django-templates|humanize | 8,391 | <p>Yes you can</p>
<p>Lets say you want to call <code>naturalday</code> in <code>views.py</code> you would do</p>
<pre><code>from django.contrib.humanize.templatetags.humanize import naturalday
natural_day = naturalday(value)
</code></pre>
<p>You can refer to the <a href="https://github.com/django/django/blob/master/django/contrib/humanize/templatetags/humanize.py">source code here</a> for the signature, and options</p> |
17,519,090 | Gemfile.lock write error, permissions? | <p>I created a Rails model "model" a while ago and now I'm trying to run the server. After a <code>bundle install</code> I get: </p>
<blockquote>
<p>There was an error while trying to write to Gemfile.lock. It is likely that you need to allow write permissions for the file at path: <code>/home/thiago/model/Gemfile.lock</code></p>
</blockquote>
<p>Tried <code>rails s</code> to see what happens and:</p>
<pre>
/home/thiago/.rvm/gems/ruby-1.9.3-p429/gems/bundler-1.3.5/lib/bundler/definition.rb:235:in `rescue in lock': There was an error while trying to write to Gemfile.lock. It is likely that (Bundler::InstallError)
you need to allow write permissions for the file at path:
/home/thiago/model/Gemfile.lock
from /home/thiago/.rvm/gems/ruby-1.9.3-p429/gems/bundler-1.3.5/lib/bundler/definition.rb:220:in `lock'
from /home/thiago/.rvm/gems/ruby-1.9.3-p429/gems/bundler-1.3.5/lib/bundler/environment.rb:34:in `lock'
from /home/thiago/.rvm/gems/ruby-1.9.3-p429/gems/bundler-1.3.5/lib/bundler/runtime.rb:43:in `setup'
from /home/thiago/.rvm/gems/ruby-1.9.3-p429/gems/bundler-1.3.5/lib/bundler.rb:120:in `setup'
from /home/thiago/.rvm/gems/ruby-1.9.3-p429@global/gems/rubygems-bundler-1.1.1/lib/rubygems-bundler/noexec.rb:79:in `setup'
from /home/thiago/.rvm/gems/ruby-1.9.3-p429@global/gems/rubygems-bundler-1.1.1/lib/rubygems-bundler/noexec.rb:91:in `'
from /home/thiago/.rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:110:in `require'
from /home/thiago/.rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:110:in `rescue in require'
from /home/thiago/.rvm/rubies/ruby-1.9.3-p429/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:35:in `require'
from /home/thiago/.rvm/gems/ruby-1.9.3-p429/bin/ruby_noexec_wrapper:9:in `'
</pre>
<p>Can I set the permissions for the Gemfile.lock so I can bundle and run server?</p>
<pre>
$ ls -a -l
total 80
drwxr-xr-x. 13 root root 4096 May 19 14:08 .
drwx------. 41 thiago thiago 4096 Jul 7 23:51 ..
drwxr-xr-x. 8 root root 4096 May 19 14:08 app
drwxr-xr-x. 5 root root 4096 May 19 14:08 config
-rw-r--r--. 1 root root 155 May 19 14:08 config.ru
drwxr-xr-x. 2 root root 4096 May 19 14:08 db
drwxr-xr-x. 2 root root 4096 May 19 14:08 doc
-rw-r--r--. 1 root root 765 May 19 14:08 Gemfile
-rw-r--r--. 1 root root 430 May 19 14:08 .gitignore
drwxr-xr-x. 4 root root 4096 May 19 14:08 lib
drwxr-xr-x. 2 root root 4096 May 19 14:08 log
drwxr-xr-x. 2 root root 4096 May 19 14:08 public
-rw-r--r--. 1 root root 270 May 19 14:08 Rakefile
-rw-r--r--. 1 root root 9208 May 19 14:08 README.rdoc
drwxr-xr-x. 2 root root 4096 May 19 14:08 script
drwxr-xr-x. 7 root root 4096 May 19 14:08 test
drwxr-xr-x. 3 root root 4096 May 19 14:08 tmp
drwxr-xr-x. 4 root root 4096 May 19 14:08 vendor
</pre>
<p>Model files created incorrectly?</p> | 17,526,037 | 3 | 2 | null | 2013-07-08 04:11:13.02 UTC | 8 | 2018-06-30 08:11:03.12 UTC | 2013-07-08 11:54:54.557 UTC | null | 211,563 | null | 2,373,003 | null | 1 | 34 | ruby|linux|bundler | 42,965 | <p>Your app root directory (whose permissions govern file creation) and files are all owned by root instead of your user (possibly because you did <code>sudo rails new</code>—don’t use <code>sudo</code> for that). You can change the permissions by doing:</p>
<pre><code>sudo chown -R $(whoami):$(whoami) myappfolder
</code></pre>
<p>Where “myappfolder” is your Rails app’s root directory.</p>
<p>By the way, a good tip with regard to <code>sudo</code> is to always try the command without it first, then, if there’s a permissions error when it runs, you may need <code>sudo</code>. Don’t default to using <code>sudo</code>.</p> |
18,474,690 | Is there a way to follow redirects with command line cURL? | <p>I know that in a php script:</p>
<pre><code>curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
</code></pre>
<p>will follow redirects. Is there a way to follow redirects with command line cURL?</p> | 18,474,746 | 3 | 1 | null | 2013-08-27 20:21:22.517 UTC | 66 | 2022-08-31 20:37:04.683 UTC | 2022-08-31 20:37:04.683 UTC | null | 1,255,289 | null | 1,592,380 | null | 1 | 572 | curl|http-redirect | 321,356 | <p>Use the location header flag:</p>
<p><code>curl -L <URL></code></p> |
51,652,897 | How to hide soft input keyboard on flutter after clicking outside TextField/anywhere on screen? | <p>Currently, I know the method of hiding the soft keyboard using this code, by <code>onTap</code> methods of any widget.</p>
<pre><code>FocusScope.of(context).requestFocus(new FocusNode());
</code></pre>
<p>But I want to hide the soft keyboard by clicking outside of TextField or anywhere on the screen. Is there any method in <code>flutter</code> to do this?</p> | 54,977,554 | 22 | 10 | null | 2018-08-02 11:49:12.237 UTC | 33 | 2022-09-07 09:38:15.09 UTC | 2021-05-07 10:16:38.277 UTC | user10563627 | null | null | 7,334,184 | null | 1 | 163 | flutter|dart|keyboard|hide | 129,913 | <p>You are doing it in the wrong way, just try this simple method to hide the soft keyboard. you just need to wrap your whole screen in the <code>GestureDetector</code> method and <code>onTap</code> method write this code.</p>
<pre><code> FocusScope.of(context).requestFocus(new FocusNode());
</code></pre>
<p>Here is the complete example:</p>
<pre><code>new Scaffold(
body: new GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: new Container(
//rest of your code write here
)
)
</code></pre>
<p><strong>Updated (May 2021)</strong></p>
<pre><code>return GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Body(),
),
);
</code></pre>
<p>This will work even when you touch the AppBar, <code>new</code> is <a href="https://medium.com/dartlang/announcing-dart-2-80ba01f43b6#da82" rel="noreferrer">optional in Dart 2</a>. <code>FocusManager.instance.primaryFocus</code> will return the node that currently has the primary focus in the widget tree.</p>
<p><a href="https://dart.dev/guides/language/cheatsheet#ab" rel="noreferrer">Conditional access in Dart with null-safety</a></p> |
5,102,758 | How to rename an SVN branch and update references in an existing sandbox? | <p>I needed to rename a SVN branch, so I did:</p>
<pre>$ svn move https://server/repos/myrepo/branches/oldbranch \
https://server/repos/myrepo/branches/newbranch</pre>
<p>So far, so good -- the branch has been renamed.</p>
<p>The trouble is, we have existing sandboxes checked out from this branch and when I try to update I get this error:</p>
<pre>$ svn update
svn: Target path '/branches/oldbranch' does not exist</pre>
<p>A fairly self-explanatory error. After a quick search I thought I had found the solution: <a href="https://stackoverflow.com/q/4411003/341459">Relocating SVN working copy following branch rename</a></p>
<p>The trouble is, that when I try to issue that command I get another error:</p>
<pre>$ svn switch --relocate https://server/repos/myrepo/branches/oldbranch \
https://server/repos/myrepo/branches/newbranch
svn: Relocate can only change the repository part of an URL</pre>
<p>As far as I can see, I am using the <code>--relocate</code> command the same way as Sander Rijken. Any ideas why I get this error? </p> | 5,102,999 | 3 | 1 | null | 2011-02-24 09:34:12.783 UTC | 9 | 2014-07-07 09:46:25.04 UTC | 2017-05-23 11:45:31.16 UTC | null | -1 | null | 341,459 | null | 1 | 51 | svn|branch|rename | 55,113 | <p>Just do</p>
<pre><code>svn switch https://server/repos/myrepo/branches/newbranch
</code></pre>
<p>from within your working copy.</p> |
43,062,870 | Add custom controls to AVPlayer in swift | <p>I am trying to create a table view such that I am able to play videos . I am able to do this using AVPlayer and layer.</p>
<p>I want to add a custom play and pause button with a slider to the bottom of a video view.</p>
<p>AVPlayerController comes built in with these controls.</p>
<p>How can I implement these in AVPlayer. I have been looking for examples. But I haven't found any.</p>
<p>Are there any GitHub examples or code samples that I can follow? Any help will be really appreciated. </p> | 43,070,099 | 2 | 3 | null | 2017-03-28 07:11:40.507 UTC | 13 | 2020-12-06 00:27:00.32 UTC | 2017-07-05 05:10:18.42 UTC | null | 2,783,370 | null | 5,443,885 | null | 1 | 17 | ios|swift|swift3|avplayer|avplayeritem | 20,409 | <p>here I add the points , you need to customize based on your need.</p>
<p><strong>Step-1</strong></p>
<p>initially hide your <code>AVPlayer</code> controls, </p>
<pre><code> YourAVPlayerViewController.showsPlaybackControls = false
</code></pre>
<p><strong>Step-2</strong></p>
<p>create the structure like</p>
<p><a href="https://i.stack.imgur.com/kRtWF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kRtWF.png" alt="enter image description here"></a></p>
<blockquote>
<p>one label for current Duration, One label for overall Duration, one UIbutton for pause and play your current player and one UISlider for seek The video.</p>
</blockquote>
<p><strong>step-3</strong></p>
<p>initially close the simple steps.</p>
<blockquote>
<p>first stop and play the player using button action , currentPlayer is your AVPlayer name.</p>
</blockquote>
<pre><code>@IBAction func handlePlayPauseButtonPressed(_ sender: UIButton) {
// sender.isSelected ? currentPlayer.pause() : currentPlayer.play()
if sender.isSelected {
currentPlayer.pause()
}
else {
currentPlayer.play()
}
}
</code></pre>
<blockquote>
<p>second set the video duration, as like</p>
</blockquote>
<pre><code> let duration : CMTime = currentPlayer.currentItem!.asset.duration
let seconds : Float64 = CMTimeGetSeconds(duration)
lblOverallDuration.text = self.stringFromTimeInterval(interval: seconds)
</code></pre>
<blockquote>
<p>third set the player current time to current duration label</p>
</blockquote>
<pre><code> let duration : CMTime = currentPlayer.currentTime()
let seconds : Float64 = CMTimeGetSeconds(duration)
lblcurrentText.text = self.stringFromTimeInterval(interval: seconds)
</code></pre>
<blockquote>
<p>the following method is convert from NSTimeinterval to HH:MM:SS</p>
</blockquote>
<pre><code>func stringFromTimeInterval(interval: TimeInterval) -> String {
let interval = Int(interval)
let seconds = interval % 60
let minutes = (interval / 60) % 60
let hours = (interval / 3600)
return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}
</code></pre>
<blockquote>
<p>finally we go for slider control for calulate the seek time</p>
</blockquote>
<pre><code>_playheadSlider.addTarget(self, action: #selector(self.handlePlayheadSliderTouchBegin), for: .touchDown)
_playheadSlider.addTarget(self, action: #selector(self.handlePlayheadSliderTouchEnd), for: .touchUpInside)
_playheadSlider.addTarget(self, action: #selector(self.handlePlayheadSliderTouchEnd), for: .touchUpOutside)
_playheadSlider.addTarget(self, action: #selector(self.handlePlayheadSliderValueChanged), for: .valueChanged)
</code></pre>
<blockquote>
<p>lets we go for action, initially when touchbegin is start then stop the player</p>
<p>handlePlayheadSliderTouchBegin</p>
</blockquote>
<pre><code>@IBAction func handlePlayheadSliderTouchBegin(_ sender: UISlider) {
currentPlayer.pause()
}
</code></pre>
<blockquote>
<p>set the current item label for calculate the <code>sender.value * CMTimeGetSeconds(currentPlayer.currentItem.duration)</code></p>
</blockquote>
<pre><code>@IBAction func handlePlayheadSliderValueChanged(_ sender: UISlider) {
let duration : CMTime = currentPlayer.currentItem!.asset.duration
let seconds : Float64 = CMTimeGetSeconds(duration) * sender.value
// var newCurrentTime: TimeInterval = sender.value * CMTimeGetSeconds(currentPlayer.currentItem.duration)
lblcurrentText.text = self.stringFromTimeInterval(interval: seconds)
}
</code></pre>
<blockquote>
<p>finally move the player based on seek</p>
</blockquote>
<pre><code> @IBAction func handlePlayheadSliderTouchEnd(_ sender: UISlider) {
let duration : CMTime = currentPlayer.currentItem!.asset.duration
var newCurrentTime: TimeInterval = sender.value * CMTimeGetSeconds(duration)
var seekToTime: CMTime = CMTimeMakeWithSeconds(newCurrentTime, 600)
currentPlayer.seek(toTime: seekToTime)
}
</code></pre> |
9,439,401 | Set ListView item height | <p>this should be a very easy thing to do, but it looks like it's very tricky.
In my code I have this ListView:</p>
<pre><code><ListView android:id="@+id/sums_list" android:layout_width="fill_parent"
android:layout_height="0dp" android:layout_weight="1" android:dividerHeight="0dp"></ListView>
</code></pre>
<p>That is populated with an ArrayAdapter that uses this view:</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cdpb="http://schemas.android.com/apk/res/ale.android.brainfitness"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="55dp">
...
</LinearLayout>
</code></pre>
<p>Why isn't the item 55dp high?</p>
<p>Thanks everybody</p> | 9,446,006 | 4 | 3 | null | 2012-02-24 23:14:36.83 UTC | 10 | 2019-04-29 16:30:49.637 UTC | null | null | null | null | 449,689 | null | 1 | 19 | android|listview | 41,927 | <p>How are you inflating the view? </p>
<p>If you are setting 'parent' parameter to null like below, then layout parameters are ignored.</p>
<pre><code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
...
View v = inflater.inflate(R.layout.filtered_trip_row, null);
…
return v;
}
</code></pre>
<p>Passing 'parent' to inflate should work as you expect.</p>
<pre><code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
...
View v = inflater.inflate(R.layout.filtered_trip_row, parent);
…
return v;
}
</code></pre>
<p>This explains it in detail: <a href="https://stackoverflow.com/questions/5026926/making-sense-of-layoutinflater">Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?</a></p>
<p>To avoid getting <code>UnsupportedOperationException</code>, you can add <code>false</code> as an input parameter to the <code>inflator</code>. Example:</p>
<pre><code>inflater.inflate(R.layout.filtered_trip_row, parent, false)
</code></pre> |
18,572,365 | Get Local IP of a device in chrome extension | <p>I am working on a chrome extension which is supposed to discover and then communicate with other devices in a local network. To discover them it needs to find out its own IP-address to find out the IP-range of the network to check for other devices. I am stuck on how to find the IP-address of the local machine (I am not talking about the localhost nor am I talking about the address that is exposed to the internet but the address on the local network). <strong>Basically, what I would love is to get what would be the <a href="http://de.wikipedia.org/wiki/Ifconfig" rel="noreferrer">ifconfig</a> output in the terminal inside my <a href="http://developer.chrome.com/extensions/background_pages.html" rel="noreferrer">background.js</a>.</strong></p>
<p>The Chrome Apps API offers <a href="http://developer.chrome.com/apps/app_network.html" rel="noreferrer">chrome.socket</a> which seems to be able to do this, <a href="https://stackoverflow.com/questions/12161964/socket-is-not-allowed-for-specified-package-type-theme-app-etc">however, it is not available for extensions</a>. Reading through <a href="http://developer.chrome.com/extensions/api_index.html" rel="noreferrer">the API for extensions</a> I have not found anything that seems to enable me to find the local ip. </p>
<p>Am I missing something or is this impossible for some reason? Is there any other way to discover other devices on the network, that would also do just fine (as they would be on the same IP-range) but while there are some rumors from December of 2012 that there could be a discovery API for extensions nothing seems to exist yet.</p>
<p>Does anybody have any ideas?</p> | 29,514,292 | 4 | 4 | null | 2013-09-02 11:37:36.997 UTC | 12 | 2017-09-29 07:16:05.893 UTC | 2017-05-23 11:54:25.417 UTC | null | -1 | null | 806,920 | null | 1 | 22 | google-chrome|networking|google-chrome-extension | 22,660 | <p>
You can get a list of your local IP addresses (more precisely: The IP addresses of your local network interfaces) via the WebRTC API. This API can be used by any web application (not just Chrome extensions).</p>
<p>Example:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Example (using the function below).
getLocalIPs(function(ips) { // <!-- ips is an array of local IP addresses.
document.body.textContent = 'Local IP addresses:\n ' + ips.join('\n ');
});
function getLocalIPs(callback) {
var ips = [];
var RTCPeerConnection = window.RTCPeerConnection ||
window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
var pc = new RTCPeerConnection({
// Don't specify any stun/turn servers, otherwise you will
// also find your public IP addresses.
iceServers: []
});
// Add a media line, this is needed to activate candidate gathering.
pc.createDataChannel('');
// onicecandidate is triggered whenever a candidate has been found.
pc.onicecandidate = function(e) {
if (!e.candidate) { // Candidate gathering completed.
pc.close();
callback(ips);
return;
}
var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];
if (ips.indexOf(ip) == -1) // avoid duplicate entries (tcp/udp)
ips.push(ip);
};
pc.createOffer(function(sdp) {
pc.setLocalDescription(sdp);
}, function onerror() {});
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body style="white-space:pre"> IP addresses will be printed here... </body></code></pre>
</div>
</div>
</p> |
18,662,261 | Fastest implementation of sine, cosine and square root in C++ (doesn't need to be much accurate) | <p>I am googling the question for past hour, but there are only points to Taylor Series or some sample code that is either too slow or does not compile at all. Well, most answer I've found over Google is "Google it, it's already asked", but sadly <em>it's not</em>...</p>
<p>I am profiling my game on low-end Pentium 4 and found out that ~85% of execution time is wasted on calculating sinus, cosinus and square root (from standard C++ library in Visual Studio), and this seems to be heavily CPU dependent (on my I7 the same functions got only 5% of execution time, and the game is <em>waaaaaaaaaay</em> faster). I cannot optimize this three functions out, nor calculate both sine and cosine in one pass (there interdependent), but I don't need too accurate results for my simulation, so I can live with faster approximation.</p>
<p>So, the question: What are the fastest way to calculate sine, cosine and square root for float in C++?</p>
<p><strong>EDIT</strong>
Lookup table are more painful as resulting Cache Miss is way more costly on modern CPU than Taylor Series. The CPUs are just so fast these days, and cache is not.</p>
<p>I made a mistake, I though that I need to calculate several factorials for Taylor Series, and I see now they can be implemented as constants.</p>
<p>So the updated question: is there any speedy optimization for square root as well?</p>
<p><strong>EDIT2</strong></p>
<p>I am using square root to calculate distance, not normalization - can't use fast inverse square root algorithm (as pointed in comment: <a href="http://en.wikipedia.org/wiki/Fast_inverse_square_root" rel="noreferrer">http://en.wikipedia.org/wiki/Fast_inverse_square_root</a></p>
<p><strong>EDIT3</strong></p>
<p>I also cannot operate on squared distances, I need exact distance for calculations</p> | 18,662,397 | 19 | 19 | null | 2013-09-06 16:20:50.157 UTC | 35 | 2022-05-08 17:50:59.19 UTC | 2016-04-16 02:47:23.537 UTC | null | 1,658,810 | null | 151,150 | null | 1 | 67 | c++|math|optimization|trigonometry | 109,189 | <p>The fastest way is to pre-compute values an use a table like in this example:</p>
<p><a href="https://stackoverflow.com/questions/3688649/create-sine-lookup-table-in-c">Create sine lookup table in C++</a></p>
<p>BUT if you insist upon computing at runtime you can use the Taylor series expansion of sine or cosine...</p>
<p><a href="https://i.stack.imgur.com/eF4rm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eF4rm.png" alt="Taylor Series of sine" /></a></p>
<p>For more on the Taylor series... <a href="http://en.wikipedia.org/wiki/Taylor_series" rel="noreferrer">http://en.wikipedia.org/wiki/Taylor_series</a></p>
<p>One of the keys to getting this to work well is pre-computing the factorials and truncating at a sensible number of terms. The factorials grow in the denominator very quickly, so you don't need to carry more than a few terms.</p>
<p>Also...Don't multiply your x^n from the start each time...e.g. multiply x^3 by x another two times, then that by another two to compute the exponents.</p> |
19,883,736 | how to discard initial data in a Firebase DB | <p>I'm making a simple app that informs a client that other clients clicked a button. I'm storing the clicks in a Firebase (<code>db</code>) using: </p>
<pre><code>db.push({msg:data});
</code></pre>
<p>All clients get notified of other user's clicks with an <code>on</code>, such as </p>
<pre><code>db.on('child_added',function(snapshot) {
var msg = snapshot.val().msg;
});
</code></pre>
<p>However, when the page first loads I want to discard any existing data on the stack. My strategy is to call <code>db.once()</code> before I define the <code>db.on('child_added',...)</code> in order to get the initial number of children, and then use that to discard that number of calls to <code>db.on('child_added',...)</code>.</p>
<p>Unfortunately, though, all of the calls to db.on('child_added',...) are happening <em>before</em> I'm able to get the initial count, so it fails. </p>
<p>How can I effectively and simply discard the initial data?</p> | 19,884,322 | 2 | 2 | null | 2013-11-09 22:14:07.843 UTC | 9 | 2014-12-29 17:26:21.743 UTC | null | null | null | null | 348,496 | null | 1 | 15 | firebase | 6,575 | <p>If I understand your question correctly, it sounds like you <em>only</em> want data that has been added since the user visited the page. In Firebase, the behavior you describe is by design, as the data is always changing and there isn't a notion of "old" data vs "new" data.</p>
<p>However, if you only want to display data added after the page has loaded, try ignoring all events prior until the complete set of children has loaded at least once. For example:</p>
<pre><code>var ignoreItems = true;
var ref = new Firebase('https://<your-Firebase>.firebaseio.com');
ref.on('child_added', function(snapshot) {
if (!ignoreItems) {
var msg = snapshot.val().msg;
// do something here
}
});
ref.once('value', function(snapshot) {
ignoreItems = false;
});
</code></pre>
<p>The alternative to this approach would be to write your new items with a priority as well, where the priority is <code>Firebase.ServerValue.TIMESTAMP</code> (the current server time), and then use a <code>.startAt(...)</code> query using the current timestamp. However, this is more complex than the approach described above.</p> |
27,677,399 | Julia: How to copy data to another processor in Julia | <p>How do you move data from one processor to another in julia? </p>
<p>Say I have an array</p>
<pre><code>a = [1:10]
</code></pre>
<p>Or some other data structure. What is the proper way to put it on all other available processors so that it will be available on those processors as the same variable name?</p> | 27,724,240 | 4 | 5 | null | 2014-12-28 14:39:58.753 UTC | 12 | 2016-10-02 16:29:04.32 UTC | 2014-12-29 03:40:39.447 UTC | null | 803,954 | null | 803,954 | null | 1 | 36 | parallel-processing|julia | 4,630 | <p>I didn't know how to do this at first, so I spent some time figuring it out.</p>
<p>Here are some functions I wrote to pass objects:</p>
<h2><code>sendto</code></h2>
<p>Send an arbitrary number of variables to specified processes.</p>
<p>New variables are created in the Main module on specified processes. The
name will be the key of the keyword argument and the value will be the
associated value.</p>
<pre><code>function sendto(p::Int; args...)
for (nm, val) in args
@spawnat(p, eval(Main, Expr(:(=), nm, val)))
end
end
function sendto(ps::Vector{Int}; args...)
for p in ps
sendto(p; args...)
end
end
</code></pre>
<h3>Examples</h3>
<pre><code># creates an integer x and Matrix y on processes 1 and 2
sendto([1, 2], x=100, y=rand(2, 3))
# create a variable here, then send it everywhere else
z = randn(10, 10); sendto(workers(), z=z)
</code></pre>
<h2><code>getfrom</code></h2>
<p>Retrieve an object defined in an arbitrary module on an arbitrary
process. Defaults to the Main module.</p>
<p>The name of the object to be retrieved should be a symbol.</p>
<pre><code>getfrom(p::Int, nm::Symbol; mod=Main) = fetch(@spawnat(p, getfield(mod, nm)))
</code></pre>
<h3>Examples</h3>
<pre><code># get an object from named x from Main module on process 2. Name it x
x = getfrom(2, :x)
</code></pre>
<h2><code>passobj</code></h2>
<p>Pass an arbitrary number of objects from one process to arbitrary
processes. The variable must be defined in the <code>from_mod</code> module of the
src process and will be copied under the same name to the <code>to_mod</code>
module on each target process.</p>
<pre><code>function passobj(src::Int, target::Vector{Int}, nm::Symbol;
from_mod=Main, to_mod=Main)
r = RemoteRef(src)
@spawnat(src, put!(r, getfield(from_mod, nm)))
for to in target
@spawnat(to, eval(to_mod, Expr(:(=), nm, fetch(r))))
end
nothing
end
function passobj(src::Int, target::Int, nm::Symbol; from_mod=Main, to_mod=Main)
passobj(src, [target], nm; from_mod=from_mod, to_mod=to_mod)
end
function passobj(src::Int, target, nms::Vector{Symbol};
from_mod=Main, to_mod=Main)
for nm in nms
passobj(src, target, nm; from_mod=from_mod, to_mod=to_mod)
end
end
</code></pre>
<h3>Examples</h3>
<pre><code># pass variable named x from process 2 to all other processes
passobj(2, filter(x->x!=2, procs()), :x)
# pass variables t, u, v from process 3 to process 1
passobj(3, 1, [:t, :u, :v])
# Pass a variable from the `Foo` module on process 1 to Main on workers
passobj(1, workers(), [:foo]; from_mod=Foo)
</code></pre> |
27,647,407 | Why do we use autoboxing and unboxing in Java? | <blockquote>
<p>Autoboxing is the automatic conversion that the Java compiler makes
between the primitive types and their corresponding object wrapper
classes. For example, converting an int to an Integer, a double to a
Double, and so on. If the conversion goes the other way, this is
called unboxing.</p>
</blockquote>
<p>So why do we need it and why do we use autoboxing and unboxing in Java?</p> | 27,647,772 | 10 | 5 | null | 2014-12-25 12:59:00.133 UTC | 81 | 2021-10-04 20:13:53.14 UTC | 2016-01-24 12:12:38.36 UTC | null | 1,892,179 | user1968030 | null | null | 1 | 95 | java|autoboxing | 74,466 | <p>Some context is required to fully understand the main reason behind this.</p>
<h2>Primitives versus classes</h2>
<p><strong>Primitive variables in Java contain values</strong> (an integer, a double-precision floating point binary number, etc). Because <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="noreferrer">these values may have different lengths</a>, the variables containing them may also have different lengths (consider <code>float</code> versus <code>double</code>).</p>
<p>On the other hand, <strong>class variables contain references</strong> to instances. References are typically implemented as pointers (or something very similar to pointers) in many languages. These things typically have the same size, regardless of the sizes of the instances they refer to (<code>Object</code>, <code>String</code>, <code>Integer</code>, etc).</p>
<p>This property of class variables <strong>makes the references they contain interchangeable</strong> (to an extent). This allows us to do what we call <em>substitution</em>: broadly speaking, <strong><a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="noreferrer">to use an instance of a particular type as an instance of another, related type</a></strong> (use a <code>String</code> as an <code>Object</code>, for example).</p>
<p><strong>Primitive variables aren't interchangeable</strong> in the same way, neither with each other, nor with <code>Object</code>. The most obvious reason for this (but not the only reason) is their size difference. This makes primitive types inconvenient in this respect, but we still need them in the language (for reasons that mainly boil down to performance).</p>
<h2>Generics and type erasure</h2>
<p>Generic types are types with one or more <em>type parameters</em> (the exact number is called <em>generic arity</em>). For example, the <em>generic type definition</em> <code>List<T></code> has a type parameter <code>T</code>, which can be <code>Object</code> (producing a <em>concrete type</em> <code>List<Object></code>), <code>String</code> (<code>List<String></code>), <code>Integer</code> (<code>List<Integer></code>) and so on.</p>
<p>Generic types are a lot more complicated than non-generic ones. When they were introduced to Java (after its initial release), in order to avoid making radical changes to the JVM and possibly breaking compatibility with older binaries, <strong>the creators of Java decided to implement generic types in the least invasive way:</strong> all concrete types of <code>List<T></code> are, in fact, compiled to (the binary equivalent of) <code>List<Object></code> (for other types, the bound may be something other than <code>Object</code>, but you get the point). <strong>Generic arity and type parameter information are lost in this process</strong>, which is why we call it <a href="http://docs.oracle.com/javase/tutorial/java/generics/erasure.html" rel="noreferrer"><em>type erasure</em></a>.</p>
<h2>Putting the two together</h2>
<p>Now the problem is the combination of the above realities: if <code>List<T></code> becomes <code>List<Object></code> in all cases, then <strong><code>T</code> must always be a type that can be directly assigned to <code>Object</code></strong>. Anything else can't be allowed. Since, as we said before, <code>int</code>, <code>float</code> and <code>double</code> aren't interchangeable with <code>Object</code>, there can't be a <code>List<int></code>, <code>List<float></code> or <code>List<double></code> (unless a significantly more complicated implementation of generics existed in the JVM).</p>
<p>But Java offers types like <code>Integer</code>, <code>Float</code> and <code>Double</code> which wrap these primitives in class instances, making them effectively substitutable as <code>Object</code>, thus <strong>allowing generic types to indirectly work with the primitives</strong> as well (because you <em>can</em> have <code>List<Integer></code>, <code>List<Float></code>, <code>List<Double></code> and so on).</p>
<p>The process of creating an <code>Integer</code> from an <code>int</code>, a <code>Float</code> from a <code>float</code> and so on, is called <em><a href="http://coderevisited.com/boxing-and-unboxing-in-java/" rel="noreferrer">boxing</a></em>. The reverse is called <em>unboxing</em>. Because having to box primitives every time you want to use them as <code>Object</code> is inconvenient, <strong>there are cases where the language does this automatically - <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/autoboxing.html" rel="noreferrer">that's called <em>autoboxing</em></a>.</strong></p> |
15,340,582 | Python extract pattern matches | <p>I am trying to use a regular expression to extract words inside of a pattern.</p>
<p>I have some string that looks like this</p>
<pre class="lang-none prettyprint-override"><code>someline abc
someother line
name my_user_name is valid
some more lines
</code></pre>
<p>I want to extract the word <code>my_user_name</code>. I do something like</p>
<pre><code>import re
s = #that big string
p = re.compile("name .* is valid", re.flags)
p.match(s) # this gives me <_sre.SRE_Match object at 0x026B6838>
</code></pre>
<p>How do I extract <code>my_user_name</code> now?</p> | 15,340,694 | 10 | 0 | null | 2013-03-11 14:04:05.137 UTC | 41 | 2022-03-24 23:03:34.05 UTC | 2022-03-24 23:03:34.05 UTC | null | 4,621,513 | null | 44,124 | null | 1 | 210 | python|regex | 365,378 | <p>You need to capture from regex. <code>search</code> for the pattern, if found, retrieve the string using <code>group(index)</code>. Assuming valid checks are performed:</p>
<pre><code>>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1) # group(1) will return the 1st capture (stuff within the brackets).
# group(0) will returned the entire matched text.
'my_user_name'
</code></pre> |
8,015,542 | Azure/web-farm ready SecurityTokenCache | <p>Our site uses ADFS for auth. To reduce the cookie payload on every request we're turning IsSessionMode on (see <a href="http://blogs.msdn.com/b/vbertocci/archive/2010/05/26/your-fedauth-cookies-on-a-diet-issessionmode-true.aspx">Your fedauth cookies on a diet</a>).</p>
<p>The last thing we need to do to get this working in our load balanced environment is to implement a farm ready SecurityTokenCache. The implementation seems pretty straightforward, I'm mainly interested in finding out if there are any gotchas we should consider when dealing with SecurityTokenCacheKey and the TryGetAllEntries and TryRemoveAllEntries methods (SecurityTokenCacheKey has a custom implementation of the Equals and GetHashCode methods).</p>
<p>Does anyone have an example of this? We're planning on using AppFabric as the backing store but an example using any persistent store would be helpful- database table, Azure table-storage, etc.</p>
<p>Here are some places I've searched:</p>
<ul>
<li>In <a href="http://www.microsoftpdc.com/2009/SVC17">Hervey Wilson's PDC09
session</a> he uses a
DatabaseSecurityTokenCache. I haven't been able to find the sample
code for his session. </li>
<li>On page 192 of Vittorio Bertocci's excellent
book, "Programming Windows Identity Foundation" he mentions uploading
a sample implementation of an Azure ready SecurityTokenCache to the
book's website. I haven't been able to find this sample either.</li>
</ul>
<p>Thanks!</p>
<p>jd</p>
<p><strong>3/16/2012 UPDATE</strong>
<a href="http://blogs.msdn.com/b/vbertocci/archive/2012/03/15/windows-identity-foundation-in-the-net-framework-4-5-beta-tools-samples-claims-everywhere.aspx">Vittorio's blog</a> links to a sample using the new .net 4.5 stuff:</p>
<p><a href="http://code.msdn.microsoft.com/vstudio/Claims-Aware-Web-Farm-088a7a4f">ClaimsAwareWebFarm</a>
This sample is an answer to the feedback we got from many of you guys: you wanted a sample showing a farm ready session cache (as opposed to a tokenreplycache) so that you can use sessions by reference instead of exchanging big cookies; and you asked for an easier way of securing cookies in a farm. </p> | 8,087,383 | 2 | 2 | null | 2011-11-04 20:48:13.9 UTC | 9 | 2012-03-16 12:35:27.333 UTC | 2012-03-16 12:35:27.333 UTC | null | 725,866 | null | 725,866 | null | 1 | 19 | azure|wif|web-farm|adfs|geneva-framework | 4,503 | <p>To come up with a working implementation we ultimately had to use reflector to analyze the different SessionSecurityToken related classes in Microsoft.IdentityModel. Below is what we came up with. This implementation is deployed on our dev and qa environments, seems to be working fine, it's resiliant to app pool recycles etc.</p>
<p>In global.asax:</p>
<pre><code>protected void Application_Start(object sender, EventArgs e)
{
FederatedAuthentication.ServiceConfigurationCreated += this.OnServiceConfigurationCreated;
}
private void OnServiceConfigurationCreated(object sender, ServiceConfigurationCreatedEventArgs e)
{
var sessionTransforms = new List<CookieTransform>(new CookieTransform[]
{
new DeflateCookieTransform(),
new RsaEncryptionCookieTransform(
e.ServiceConfiguration.ServiceCertificate),
new RsaSignatureCookieTransform(
e.ServiceConfiguration.ServiceCertificate)
});
// following line is pseudo code. use your own durable cache implementation.
var durableCache = new AppFabricCacheWrapper();
var tokenCache = new DurableSecurityTokenCache(durableCache, 5000);
var sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly(),
tokenCache,
TimeSpan.FromDays(1));
e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler);
}
private void WSFederationAuthenticationModule_SecurityTokenValidated(object sender, SecurityTokenValidatedEventArgs e)
{
FederatedAuthentication.SessionAuthenticationModule.IsSessionMode = true;
}
</code></pre>
<p>DurableSecurityTokenCache.cs:</p>
<pre><code>/// <summary>
/// Two level durable security token cache (level 1: in memory MRU, level 2: out of process cache).
/// </summary>
public class DurableSecurityTokenCache : SecurityTokenCache
{
private ICache<string, byte[]> durableCache;
private readonly MruCache<SecurityTokenCacheKey, SecurityToken> mruCache;
/// <summary>
/// The constructor.
/// </summary>
/// <param name="durableCache">The durable second level cache (should be out of process ie sql server, azure table, app fabric, etc).</param>
/// <param name="mruCapacity">Capacity of the internal first level cache (in-memory MRU cache).</param>
public DurableSecurityTokenCache(ICache<string, byte[]> durableCache, int mruCapacity)
{
this.durableCache = durableCache;
this.mruCache = new MruCache<SecurityTokenCacheKey, SecurityToken>(mruCapacity, mruCapacity / 4);
}
public override bool TryAddEntry(object key, SecurityToken value)
{
var cacheKey = (SecurityTokenCacheKey)key;
// add the entry to the mru cache.
this.mruCache.Add(cacheKey, value);
// add the entry to the durable cache.
var keyString = GetKeyString(cacheKey);
var buffer = this.GetSerializer().Serialize((SessionSecurityToken)value);
this.durableCache.Add(keyString, buffer);
return true;
}
public override bool TryGetEntry(object key, out SecurityToken value)
{
var cacheKey = (SecurityTokenCacheKey)key;
// attempt to retrieve the entry from the mru cache.
value = this.mruCache.Get(cacheKey);
if (value != null)
return true;
// entry wasn't in the mru cache, retrieve it from the app fabric cache.
var keyString = GetKeyString(cacheKey);
var buffer = this.durableCache.Get(keyString);
var result = buffer != null;
if (result)
{
// we had a cache miss in the mru cache but found the item in the durable cache...
// deserialize the value retrieved from the durable cache.
value = this.GetSerializer().Deserialize(buffer);
// push this item into the mru cache.
this.mruCache.Add(cacheKey, value);
}
return result;
}
public override bool TryRemoveEntry(object key)
{
var cacheKey = (SecurityTokenCacheKey)key;
// remove the entry from the mru cache.
this.mruCache.Remove(cacheKey);
// remove the entry from the durable cache.
var keyString = GetKeyString(cacheKey);
this.durableCache.Remove(keyString);
return true;
}
public override bool TryReplaceEntry(object key, SecurityToken newValue)
{
var cacheKey = (SecurityTokenCacheKey)key;
// remove the entry in the mru cache.
this.mruCache.Remove(cacheKey);
// remove the entry in the durable cache.
var keyString = GetKeyString(cacheKey);
// add the new value.
return this.TryAddEntry(key, newValue);
}
public override bool TryGetAllEntries(object key, out IList<SecurityToken> tokens)
{
// not implemented... haven't been able to find how/when this method is used.
tokens = new List<SecurityToken>();
return true;
//throw new NotImplementedException();
}
public override bool TryRemoveAllEntries(object key)
{
// not implemented... haven't been able to find how/when this method is used.
return true;
//throw new NotImplementedException();
}
public override void ClearEntries()
{
// not implemented... haven't been able to find how/when this method is used.
//throw new NotImplementedException();
}
/// <summary>
/// Gets the string representation of the specified SecurityTokenCacheKey.
/// </summary>
private string GetKeyString(SecurityTokenCacheKey key)
{
return string.Format("{0}; {1}; {2}", key.ContextId, key.KeyGeneration, key.EndpointId);
}
/// <summary>
/// Gets a new instance of the token serializer.
/// </summary>
private SessionSecurityTokenCookieSerializer GetSerializer()
{
return new SessionSecurityTokenCookieSerializer(); // may need to do something about handling bootstrap tokens.
}
}
</code></pre>
<p>MruCache.cs:</p>
<pre><code>/// <summary>
/// Most recently used (MRU) cache.
/// </summary>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
public class MruCache<TKey, TValue> : ICache<TKey, TValue>
{
private Dictionary<TKey, TValue> mruCache;
private LinkedList<TKey> mruList;
private object syncRoot;
private int capacity;
private int sizeAfterPurge;
/// <summary>
/// The constructor.
/// </summary>
/// <param name="capacity">The capacity.</param>
/// <param name="sizeAfterPurge">Size to make the cache after purging because it's reached capacity.</param>
public MruCache(int capacity, int sizeAfterPurge)
{
this.mruList = new LinkedList<TKey>();
this.mruCache = new Dictionary<TKey, TValue>(capacity);
this.capacity = capacity;
this.sizeAfterPurge = sizeAfterPurge;
this.syncRoot = new object();
}
/// <summary>
/// Adds an item if it doesn't already exist.
/// </summary>
public void Add(TKey key, TValue value)
{
lock (this.syncRoot)
{
if (mruCache.ContainsKey(key))
return;
if (mruCache.Count + 1 >= this.capacity)
{
while (mruCache.Count > this.sizeAfterPurge)
{
var lru = mruList.Last.Value;
mruCache.Remove(lru);
mruList.RemoveLast();
}
}
mruCache.Add(key, value);
mruList.AddFirst(key);
}
}
/// <summary>
/// Removes an item if it exists.
/// </summary>
public void Remove(TKey key)
{
lock (this.syncRoot)
{
if (!mruCache.ContainsKey(key))
return;
mruCache.Remove(key);
mruList.Remove(key);
}
}
/// <summary>
/// Gets an item. If a matching item doesn't exist null is returned.
/// </summary>
public TValue Get(TKey key)
{
lock (this.syncRoot)
{
if (!mruCache.ContainsKey(key))
return default(TValue);
mruList.Remove(key);
mruList.AddFirst(key);
return mruCache[key];
}
}
/// <summary>
/// Gets whether a key is contained in the cache.
/// </summary>
public bool ContainsKey(TKey key)
{
lock (this.syncRoot)
return mruCache.ContainsKey(key);
}
}
</code></pre>
<p>ICache.cs:</p>
<pre><code>/// <summary>
/// A cache.
/// </summary>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
public interface ICache<TKey, TValue>
{
void Add(TKey key, TValue value);
void Remove(TKey key);
TValue Get(TKey key);
}
</code></pre> |
8,214,368 | Visual Studio 2010: Projectitem unavailable | <p>When trying to design a form in Visual Studio 2010:</p>
<p><img src="https://i.stack.imgur.com/cLhPV.png" alt="enter image description here" /></p>
<p>How do i tell Visual Studio to ignore whatever's causing the problem and continue?</p>
<hr />
<p>Research the problem showed two possible solutions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/5090435/image-button-on-visual-studio-2010-c">Merideth was able to click "Ignore and Continue"</a>. (i have no such option)</li>
<li>[Dan simply restarted Visual Studio (Visual Studio 2005)</li>
</ul>
<p>In my case restarting Visual Studio causes it to get its head out of it's own assembler.</p>
<p>Someone phrase those in the form of an answer, and get free rep. (<a href="https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/">SO prevents me from posting my own answer</a>).</p> | 8,217,181 | 2 | 4 | null | 2011-11-21 15:43:27.593 UTC | null | 2022-01-03 01:27:40.387 UTC | 2021-01-18 12:38:11.483 UTC | null | -1 | null | 12,597 | null | 1 | 32 | visual-studio-2010|windows-forms-designer | 11,450 | <p>Simply restart Visual Studio, and it will get unstuck.</p>
<ul>
<li>It's a bug in Visual Studio.</li>
<li>Microsoft isn't going to fix it.</li>
<li>Microsoft isn't going to release the source code so anyone else fix it.</li>
<li>Microsoft isn't going to even investigate the issue.</li>
</ul>
<p>So we are where we are: you have to workaround their bugs.</p> |
23,931,546 | Java: Getter and setter faster than direct access? | <p>I tested the performance of a Java ray tracer I'm writing on with <a href="http://visualvm.java.net">VisualVM</a> 1.3.7 on my Linux Netbook. I measured with the profiler.<br>
For fun I tested if there's a difference between using getters and setters and accessing the fields directly. The getters and setters are standard code with no addition.</p>
<p>I didn't expected any differences. But the directly accessing code was slower.</p>
<p>Here's the sample I tested in Vector3D:</p>
<pre><code>public float dot(Vector3D other) {
return x * other.x + y * other.y + z * other.z;
}
</code></pre>
<p>Time: 1542 ms / 1,000,000 invocations</p>
<pre><code>public float dot(Vector3D other) {
return getX() * other.getX() + getY() * other.getY() + getZ() * other.getZ();
}
</code></pre>
<p>Time: 1453 ms / 1,000,000 invocations</p>
<p>I didn't test it in a micro-benchmark, but in the ray tracer. The way I tested the code:</p>
<ul>
<li>I started the program with the first code and set it up. The ray tracer isn't running yet.</li>
<li>I started the profiler and waited a while after initialization was done.</li>
<li>I started a ray tracer.</li>
<li>When VisualVM showed enough invocations, I stopped the profiler and waited a bit.</li>
<li>I closed the ray tracer program.</li>
<li>I replaced the first code with the second and repeated the steps above after compiling.</li>
</ul>
<p>I did at least run 20,000,000 invocations for both codes. I closed any program I didn't need.
I set my CPU on performance, so my CPU clock was on max. all the time.<br>
How is it possible that the second code is 6% faster?</p> | 24,117,737 | 3 | 7 | null | 2014-05-29 10:46:40.26 UTC | 10 | 2014-06-09 09:54:31.42 UTC | 2014-05-29 11:32:56.547 UTC | null | 3,557,679 | null | 3,557,679 | null | 1 | 31 | java|performance|getter-setter | 11,456 | <p>Thank you all for helping me answering this question. In the end, I found the answer.</p>
<p>First, <a href="/questions/23931546/java-getter-and-setter-faster-than-direct-access#24051675">Bohemian is right</a>: With <a href="https://wikis.oracle.com/display/HotSpotInternals/PrintAssembly" rel="noreferrer">PrintAssembly</a> I checked the assumption that the generated assembly codes are identical. And yes, although the bytecodes are different, the generated codes are identical.<br>
So <a href="/questions/23931546/java-getter-and-setter-faster-than-direct-access#comment36968649_23931546">masterxilo is right</a>: The profiler have to be the culprit. But masterxilo's guess about timing fences and more instrumentation code can't be true; both codes are identical in the end.</p>
<p>So there's still the question: How is it possible that the second code seems to be 6% faster in the profiler?</p>
<p>The answer lies in the way how VisualVM measures: <a href="http://visualvm.java.net/troubleshooting.html#calibration" rel="noreferrer">Before you start profiling, you need calibration data.</a> This is used for removing the overhead time caused by the profiler.<br>
Although the calibration data is correct, the final calculation of the measurement is not. VisualVM sees the method invocations in the bytecode. But it doesn't see that the JIT compiler removes these invocations while optimizing.<br>
So it removes non-existing overhead time. And that's how the difference appears.</p> |
19,325,319 | Jumping input fields in Safari | <p>I'm trying to recreate <a href="http://dribbble.com/shots/1254439--GIF-Mobile-Form-Interaction?list=users" rel="noreferrer">a pretty cool placeholder UI</a> using only HTML and CSS, and I've almost got it (<a href="http://jsbin.com/aCUvOnI/18" rel="noreferrer">demo</a>). However, if you type something in an input field and tab to focus on the next, the one you just entered a value into will be offset a little bit in Safari (6.0.5) and MobileSafari (iOS 6.1). It works fine in Chrome (30).</p>
<p>To reproduce:</p>
<ol>
<li>Focus on the 'price' input field</li>
<li>Enter a value</li>
<li>Tab to focus the next input field</li>
<li>Watch and amaze while the form eats itself</li>
</ol>
<p><strong>So the question is: what's causing this and how can I fix it?</strong></p>
<p><em>Note: I only really care about getting this to work in MobileSafari, anything beyond that is a bonus.</em></p>
<h2>HTML</h2>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input name="title" type="text" placeholder="Title">
<input name="price" type="text" placeholder="Price">
<input name="location" type="text" placeholder="Specific location (optional)">
<textarea name="desc" rows='4' placeholder="Description"></textarea>
</body>
</html>
</code></pre>
<h2>CSS</h2>
<pre><code>* {
box-sizing: border-box;
}
body {
padding: 0;
margin: 0;
font-size: 0;
}
input, textarea {
position: relative;
display: inline-block;
margin: 0;
outline: none;
border: 0;
border-radius: 0;
padding: 2pt 4pt;
padding-top: 8pt;
font-family: "Helvetica Neue";
font-size: 14pt;
font-weight: lighter;
}
::-webkit-input-placeholder {
color: lightgrey;
position: relative;
top: 0;
left: 0;
-webkit-transition-property: top, color;
-webkit-transition-duration: .1s;
transition-property: top, color;
transition-duration: .1s;
}
::-webkit-input-placeholder[style*=hidden] {
color: rgb(16,124,246);
font-size: 8pt;
font-weight: normal;
top: -8pt;
opacity: 1;
visibility: visible !important;
}
[name=title] {
width: 100%;
border-bottom: 1px solid lightgrey;
margin-bottom: 1px;
}
[name=price] {
width: 30%;
margin-bottom: 1px;
border-bottom: 1px solid lightgrey;
border-right: 1px solid lightgrey;
}
[name=location] {
width: 70%;
border-bottom: 1px solid lightgrey;
}
[name=desc] {
width: 100%;
}
</code></pre> | 19,326,771 | 3 | 10 | null | 2013-10-11 18:57:19.497 UTC | 10 | 2013-10-12 13:54:53.82 UTC | 2013-10-12 01:25:01.32 UTC | null | 68,909 | null | 68,909 | null | 1 | 13 | html|css|mobile-safari | 6,697 | <p>Adding this to your input and textarea element solves the problem:</p>
<pre class="lang-css prettyprint-override"><code>float: left;
</code></pre>
<p>Tested on Safari Version 6.0.5 (8536.30.1) and Mobile Safari</p> |
8,597,081 | How to stretch images with no antialiasing | <p>So I ran across this recently: <a href="http://www.nicalis.com/" rel="nofollow noreferrer">http://www.nicalis.com/</a></p>
<p>And I was curious: Is there a way to do this sort of thing with smaller images? I mean, it's pixel art, and rather than using an image with each pixel quadrupled in size couldn't we stretch them with the code? So I started trying to make it happen.</p>
<p>I tried CSS, Javascript, and even HTML, none of which worked. They all blur up really badly (like this: <a href="http://jsfiddle.net/nUVJt/2/" rel="nofollow noreferrer">http://jsfiddle.net/nUVJt/2/</a>), which brings me to my question: Can you stretch an image in-browser without any antialiasing?</p>
<p>I'm open to any suggestions, whether it's using a canvas, jQuery, CSS3, or whatever.</p>
<p>Thanks for the help!</p>
<p><strong>EDIT:</strong> There's a better way to do this now! A slightly less hackish way! Here's the magic:</p>
<pre><code>.pixelated {
image-rendering: -moz-crisp-edges;
image-rendering: -o-crisp-edges;
image-rendering: -webkit-optimize-contrast;
-ms-interpolation-mode: nearest-neighbor;
image-rendering: pixelated;
}
</code></pre>
<p>And that'll stop the anti-aliasing in all the modern browsers. It'll even work in IE7-8, but not in 9, and I don't know of any way of doing it in 9, unfortunately (aside from the canvas hack outlined below).
It's not even funny how much faster it is doing it this way than with JS. Here's more info on those: <a href="https://developer.mozilla.org/en-US/docs/CSS/Image-rendering" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/CSS/Image-rendering</a></p>
<p><strong>EDIT2:</strong> Because this isn't an official spec yet, it's not very reliable. Chrome and FF both seem to have stopped supporting it since I wrote the above (according to <a href="http://vaughnroyko.com/state-of-nearest-neighbor-interpolation-in-canvas/" rel="nofollow noreferrer">this article</a> which was mentioned below), which is really annoying. We're probably going to have to wait a few more years before we really can start using this in CSS, which is really unfortunate.</p>
<p><strong>FINAL EDIT:</strong> There is an official way to do this now! There's a new property called <code>image-rendering</code>. It's in the <a href="http://dev.w3.org/csswg/css-images-3/#the-image-rendering" rel="nofollow noreferrer">CSS3 spec</a>. Support is <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering#Browser_compatibility" rel="nofollow noreferrer">super spotty</a> right now, but <a href="https://www.chromestatus.com/feature/5118058116939776" rel="nofollow noreferrer">Chrome just added support</a> so before too long we’ll be able to just say <code>image-rendering: pixelated;</code> and it’ll work all the places (yaayy evergreen browsers!)</p> | 8,597,422 | 5 | 3 | null | 2011-12-21 22:11:42.163 UTC | 11 | 2019-12-03 01:42:20.73 UTC | 2019-12-03 01:42:20.73 UTC | null | 934,019 | null | 934,019 | null | 1 | 40 | javascript|css|image|image-manipulation | 18,418 | <p>The Canvas documentation explicitly does not specify a scaling method - in my own tests it did indeed anti-alias the image quite badly in Firefox.</p>
<p>The code below copies pixel by pixel from a source image (which must be from the same Origin or from a Data URI) and scales it by the specified factor.</p>
<p>An extra off-screen canvas (<code>src_canvas</code>) is required to receive the original source image, and its image data is then copied pixel by pixel into an on-screen canvas.</p>
<pre><code>var img = new Image();
img.src = ...;
img.onload = function() {
var scale = 8;
var src_canvas = document.createElement('canvas');
src_canvas.width = this.width;
src_canvas.height = this.height;
var src_ctx = src_canvas.getContext('2d');
src_ctx.drawImage(this, 0, 0);
var src_data = src_ctx.getImageData(0, 0, this.width, this.height).data;
var dst_canvas = document.getElementById('canvas');
dst_canvas.width = this.width * scale;
dst_canvas.height = this.height * scale;
var dst_ctx = dst_canvas.getContext('2d');
var offset = 0;
for (var y = 0; y < this.height; ++y) {
for (var x = 0; x < this.width; ++x) {
var r = src_data[offset++];
var g = src_data[offset++];
var b = src_data[offset++];
var a = src_data[offset++] / 100.0;
dst_ctx.fillStyle = 'rgba(' + [r, g, b, a].join(',') + ')';
dst_ctx.fillRect(x * scale, y * scale, scale, scale);
}
}
};
</code></pre>
<p>Working demo at <a href="http://jsfiddle.net/alnitak/LwJJR/" rel="noreferrer">http://jsfiddle.net/alnitak/LwJJR/</a></p>
<p><strong>EDIT</strong> a more optimal demo is available at <a href="http://jsfiddle.net/alnitak/j8YTe/" rel="noreferrer">http://jsfiddle.net/alnitak/j8YTe/</a> that also uses a raw image data array for the destination canvas.</p> |
8,379,596 | How do I convert a Ruby hash so that all of its keys are symbols? | <p>I have a Ruby hash which looks like:</p>
<pre><code>{ "id" => "123", "name" => "test" }
</code></pre>
<p>I would like to convert it to:</p>
<pre><code>{ :id => "123", :name => "test" }
</code></pre> | 8,380,073 | 15 | 3 | null | 2011-12-04 23:56:13.963 UTC | 13 | 2020-04-13 06:05:51.177 UTC | 2015-12-29 16:28:39.73 UTC | null | 4,370,109 | null | 92,621 | null | 1 | 60 | ruby|hash | 57,499 | <pre><code>hash = {"apple" => "banana", "coconut" => "domino"}
Hash[hash.map{ |k, v| [k.to_sym, v] }]
#=> {:apple=>"banana", :coconut=>"domino"}
</code></pre>
<p>@mu is too short: Didn't see word "recursive", but if you insist (along with protection against non-existent <code>to_sym</code>, just want to remind that in Ruby 1.8 <code>1.to_sym == nil</code>, so playing with some key types can be misleading):</p>
<pre><code>hash = {"a" => {"b" => "c"}, "d" => "e", Object.new => "g"}
s2s =
lambda do |h|
Hash === h ?
Hash[
h.map do |k, v|
[k.respond_to?(:to_sym) ? k.to_sym : k, s2s[v]]
end
] : h
end
s2s[hash] #=> {:d=>"e", #<Object:0x100396ee8>=>"g", :a=>{:b=>"c"}}
</code></pre> |
5,255,147 | Dual SIM card Android | <p>Has anyone had experience with programming the selection of the SIM card, when the phone uses a dual SIM adapter?</p>
<p>Thanks,
STeN</p>
<hr>
<p><strong>Added later:</strong>
I have found the <a href="https://market.android.com/details?id=de.qianqin.multisim&hl=en">MultiSim</a> application on the Android Market, which has in its description written that "<em>...Analog dual-sim-adapter users can switch their sim cards...</em>", so is there some API in the Android SDK, which allows the SIM card switch/selection?</p> | 5,255,993 | 4 | 2 | null | 2011-03-10 03:32:45.69 UTC | 12 | 2017-01-09 09:13:24.26 UTC | 2011-03-10 04:53:28.227 UTC | null | 384,115 | null | 384,115 | null | 1 | 24 | android | 26,941 | <p>The current Android platform does not have support for multiple SIMs. A device with such support has been customized for this, so you will need to get information from that device's manufacturer for any facilities they have to interact with it.</p> |
5,310,609 | Dropdownlist validation in Asp.net Using Required field validator | <p>I have Dropdownlist whose value field and text field are bind at runtime.
it has <code>--select--</code> as first item with a value of <code>0</code>
and the rest of the values are bind at runtime.</p>
<p>I have given validaton group for both the control and the validator as <code>"g1"</code>
and <code>Intialvalue=0</code></p>
<p>But still the page is posting back even if I select <code>--select--</code> option.</p>
<pre><code><asp:DropDownList AutoPostBack="true" CssClass="dropdown" ValidationGroup="g1"
ID="ddlReportType" runat="server"
OnSelectedIndexChanged="ddlReportType_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="ddlReportType" ID="RequiredFieldValidator1"
ValidationGroup="g1" CssClass="errormesg" ErrorMessage="Please select a type"
InitialValue="0" runat="server" Display="Dynamic">
</asp:RequiredFieldValidator>
</code></pre>
<p>And code Behind to Bind the Dropdown </p>
<pre><code>ddlReportType.Items.Clear();
ddlReportType.DataSource = dt.Tables[0];
ddlReportType.DataTextField = "ReportType";
ddlReportType.DataValueField = "ReportTypeID";
ddlReportType.DataBind();
ddlReportType.Items.Insert(0, new ListItem("--Select--", "0"));
//ddlReportType.Items[0].Value = "0";
ddlReportType.SelectedIndex = 0;
</code></pre> | 5,310,704 | 4 | 0 | null | 2011-03-15 10:50:17.843 UTC | 6 | 2018-05-22 20:41:30.037 UTC | 2016-10-18 20:08:03.4 UTC | null | 5,910,368 | null | 654,843 | null | 1 | 36 | asp.net|requiredfieldvalidator | 166,699 | <pre><code><asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic"
ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>
</code></pre> |
5,224,697 | Deserializing JSON when sometimes array and sometimes object | <p>I'm having a bit of trouble deserializing data returned from Facebook using the JSON.NET libraries.</p>
<p>The JSON returned from just a simple wall post looks like:</p>
<pre><code>{
"attachment":{"description":""},
"permalink":"http://www.facebook.com/permalink.php?story_fbid=123456789"
}
</code></pre>
<p>The JSON returned for a photo looks like:</p>
<pre><code>"attachment":{
"media":[
{
"href":"http://www.facebook.com/photo.php?fbid=12345",
"alt":"",
"type":"photo",
"src":"http://photos-b.ak.fbcdn.net/hphotos-ak-ash1/12345_s.jpg",
"photo":{"aid":"1234","pid":"1234","fbid":"1234","owner":"1234","index":"12","width":"720","height":"482"}}
],
</code></pre>
<p>Everything works great and I have no problems. I've now come across a simple wall post from a mobile client with the following JSON, and deserialization now fails with this one single post:</p>
<pre><code>"attachment":
{
"media":{},
"name":"",
"caption":"",
"description":"",
"properties":{},
"icon":"http://www.facebook.com/images/icons/mobile_app.gif",
"fb_object_type":""
},
"permalink":"http://www.facebook.com/1234"
</code></pre>
<p>Here is the class I am deserializing as:</p>
<pre><code>public class FacebookAttachment
{
public string Name { get; set; }
public string Description { get; set; }
public string Href { get; set; }
public FacebookPostType Fb_Object_Type { get; set; }
public string Fb_Object_Id { get; set; }
[JsonConverter(typeof(FacebookMediaJsonConverter))]
public List<FacebookMedia> { get; set; }
public string Permalink { get; set; }
}
</code></pre>
<p>Without using the FacebookMediaJsonConverter, I get an error: Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[FacebookMedia]'.
which makes sense, since in the JSON, Media is not a collection. </p>
<p>I found this post which describes a similar problem, so I've attempted to go down this route: <a href="https://stackoverflow.com/questions/4572732/deserialize-json-sometimes-value-is-an-array-sometimes-blank-string">Deserialize JSON, sometimes value is an array, sometimes "" (blank string)</a></p>
<p>My converter looks like:</p>
<pre><code>public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartArray)
return serializer.Deserialize<List<FacebookMedia>>(reader);
else
return null;
}
</code></pre>
<p>Which works fine, except I now get a new exception:</p>
<p>Inside JsonSerializerInternalReader.cs, CreateValueInternal(): Unexpected token while deserializing object: PropertyName</p>
<p>The value of reader.Value is "permalink". I can clearly see in the switch that there's no case for JsonToken.PropertyName. </p>
<p>Is there something I need to do differently in my converter? Thanks for any help. </p> | 5,226,924 | 7 | 1 | null | 2011-03-07 20:09:33.387 UTC | 23 | 2021-07-23 02:48:06.943 UTC | 2017-05-23 10:31:23.467 UTC | null | -1 | null | 108,602 | null | 1 | 54 | c#|json|json.net|facebook-c#-sdk|json-deserialization | 33,861 | <p>The developer of JSON.NET ended up helping on the projects codeplex site. Here is the solution:</p>
<p>The problem was, when it was a JSON object, I wasn't reading past the attribute. Here is the correct code: </p>
<pre><code>public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartArray)
{
return serializer.Deserialize<List<FacebookMedia>>(reader);
}
else
{
FacebookMedia media = serializer.Deserialize<FacebookMedia>(reader);
return new List<FacebookMedia>(new[] {media});
}
}
</code></pre>
<p>James was also kind enough to provide unit tests for the above method. </p> |
5,291,726 | What is the main purpose of setTag() getTag() methods of View? | <p>What is the main purpose of such methods as <code>setTag()</code> and <code>getTag()</code> of <code>View</code> type objects? </p>
<p>Am I right in thinking that I can associate any number of objects with a single View?</p> | 5,291,891 | 7 | 0 | null | 2011-03-13 19:18:08.893 UTC | 164 | 2020-05-23 09:43:56.283 UTC | 2018-10-14 17:30:21.447 UTC | null | 3,623,128 | null | 397,991 | null | 1 | 452 | android|view|android-view|android-viewholder | 275,680 | <p>Let's say you generate a bunch of views that are similar. You could set an <code>OnClickListener</code> for each view individually:</p>
<pre><code>button1.setOnClickListener(new OnClickListener ... );
button2.setOnClickListener(new OnClickListener ... );
...
</code></pre>
<p>Then you have to create a unique <code>onClick</code> method for each view even if they do the similar things, like:</p>
<pre><code>public void onClick(View v) {
doAction(1); // 1 for button1, 2 for button2, etc.
}
</code></pre>
<p>This is because <code>onClick</code> has only one parameter, a <code>View</code>, and it has to get other information from instance variables or final local variables in enclosing scopes. What we really want is to get information <em>from the views themselves</em>.</p>
<p>Enter <code>getTag</code>/<code>setTag</code>:</p>
<pre><code>button1.setTag(1);
button2.setTag(2);
</code></pre>
<p>Now we can use the same OnClickListener for every button:</p>
<pre><code>listener = new OnClickListener() {
@Override
public void onClick(View v) {
doAction(v.getTag());
}
};
</code></pre>
<p>It's basically a way for views to have <em>memories</em>.</p> |
5,271,598 | Java Generate Random Number Between Two Given Values | <p>I would like to know how to generate a random number between two given values.</p>
<p>I am able to generate a random number with the following:</p>
<pre><code>Random r = new Random();
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
a[i][j] = r.nextInt();
}
}
</code></pre>
<p>However, how can I generate a random number between 0 and 100 (inclusive)?</p> | 5,271,613 | 7 | 0 | null | 2011-03-11 10:15:31.973 UTC | 46 | 2018-10-30 10:30:32.09 UTC | 2018-09-25 13:19:24.387 UTC | null | 636,987 | null | 636,987 | null | 1 | 205 | java|random|numbers | 875,656 | <p>You could use e.g. <code>r.nextInt(101)</code></p>
<p>For a more generic "in between two numbers" use:</p>
<pre><code>Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;
</code></pre>
<p>This gives you a random number in between 10 (inclusive) and 100 (exclusive)</p> |
5,171,901 | Find and replace in file and overwrite file doesn't work, it empties the file | <p>I would like to run a find and replace on an HTML file through the command line.</p>
<p>My command looks something like this:</p>
<pre><code>sed -e s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html > index.html
</code></pre>
<p>When I run this and look at the file afterward, it is empty. It deleted the contents of my file.</p>
<p>When I run this after restoring the file again:</p>
<pre><code>sed -e s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html
</code></pre>
<p>The <code>stdout</code> is the contents of the file, and the find and replace has been executed.</p>
<p>Why is this happening?</p> | 5,171,935 | 12 | 3 | null | 2011-03-02 18:44:28.38 UTC | 145 | 2019-04-04 19:18:53.013 UTC | 2019-04-04 19:18:53.013 UTC | null | 6,862,601 | null | 540,738 | null | 1 | 631 | shell|unix|sed|io-redirection | 741,763 | <p>When the <strong>shell</strong> sees <code>> index.html</code> in the command line it opens the file <code>index.html</code> for <strong>writing</strong>, wiping off all its previous contents.</p>
<p>To fix this you need to pass the <code>-i</code> option to <code>sed</code> to make the changes inline and create a backup of the original file before it does the changes in-place:</p>
<pre><code>sed -i.bak s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html
</code></pre>
<p>Without the .bak the command will fail on some platforms, such as Mac OSX.</p> |
5,229,081 | position:relative leaves an empty space | <p>Code is here: <a href="http://lasers.org.ru/vs/example.html" rel="noreferrer">http://lasers.org.ru/vs/example.html</a></p>
<p>How to remove an empty space under main block (#page)?</p> | 5,229,122 | 13 | 6 | null | 2011-03-08 06:21:45.187 UTC | 10 | 2022-08-10 16:51:04.373 UTC | null | null | null | null | 531,272 | null | 1 | 107 | css | 106,359 | <p>Well, don't use relative positioning then. The element still takes up space where it originally was when using relative positioning, and you can't get rid of that. You can for example use absolute positioning instead, or make the elements float beside each other.</p>
<p>I played around with the layout a bit, and I suggest that you change these three rules to:</p>
<pre><code>#layout { width: 636px; margin: 0 auto; }
#menu { position: absolute; width: 160px; margin-left: 160px; }
#page { width: 600px; padding: 8px 16px; border: 2px solid #404241; }
</code></pre> |
12,116,511 | How to delete cookie from .Net | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/7079565/delete-cookie-on-clicking-sign-out">Delete cookie on clicking sign out</a> </p>
</blockquote>
<p>I want to delete cookies when the user logout. </p>
<p>Here is my code:</p>
<pre><code> if (HttpContext.Current.Request.Cookies["currentUser"] != null)
{
DeleteCookie(HttpContext.Current.Request.Cookies["currentUser"]);
}
public void DeleteCookie(HttpCookie httpCookie)
{
try
{
httpCookie.Value = null;
httpCookie.Expires = DateTime.Now.AddMinutes(-20);
HttpContext.Current.Request.Cookies.Add(httpCookie);
}
catch (Exception ex)
{
throw (ex);
}
}
</code></pre>
<p>But it doesn't work. Do you have any suggestion? </p> | 12,116,807 | 4 | 2 | null | 2012-08-24 20:54:30.087 UTC | 3 | 2018-10-03 15:57:59.03 UTC | 2017-05-23 12:34:39.837 UTC | null | -1 | null | 117,899 | null | 1 | 40 | c#|.net|cookies | 88,828 | <pre><code> HttpCookie currentUserCookie = HttpContext.Current.Request.Cookies["currentUser"];
HttpContext.Current.Response.Cookies.Remove("currentUser");
currentUserCookie.Expires = DateTime.Now.AddDays(-10);
currentUserCookie.Value = null;
HttpContext.Current.Response.SetCookie(currentUserCookie);
</code></pre>
<p>It works.</p> |
12,181,760 | Twitter Bootstrap: Print content of modal window | <p>I'm developing a site using Bootstrap which has 28 modal windows with information on different products. I want to be able to print the information in an open modal window. Each window has an <code>id</code>. </p>
<pre><code><!-- firecell panel & radio hub -->
<div class="modal hide fade" id="fcpanelhub">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">X</button>
<h3>5000 Control Panel & Radio Hub</h3>
</div>
<div class="modal-body">
<img src="../site/img/firecell/firecell-panel-info-1.png" alt=""/><hr/>
<img src="../site/img/firecell/firecell-panel-info-2.png" alt=""/><hr/>
<img src="../site/img/firecell/firecell-radio-hub-info-1.png" alt=""/><hr/>
<img src="../site/img/firecell/firecell-radio-hub-info-2.png" alt=""/>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal">Close</a>
</div>
</div>
</code></pre>
<p>So if I add in a new button in <code>modal-footer</code> - 'print', and it's clicked I want that modal to print. Would I be right in saying javascript would be used? If so, how do I tell javascript to print only the open modal, and not the others?</p>
<p>All help appreciated.</p> | 12,181,825 | 11 | 1 | null | 2012-08-29 15:47:35.543 UTC | 38 | 2021-06-24 15:34:14.863 UTC | null | null | null | null | 1,260,835 | null | 1 | 59 | javascript|printing|twitter-bootstrap|modal-dialog | 138,341 | <h2>Another solution</h2>
<p>Here is a new solution based on <a href="https://stackoverflow.com/a/2618980/603003">Bennett McElwee answer</a> in the <a href="https://stackoverflow.com/users/24181/greg">same question</a> as mentioned below.</p>
<p>Tested with IE 9 & 10, Opera 12.01, Google Chrome 22 and Firefox 15.0. <br />
<a href="http://jsfiddle.net/95ezN/3/" rel="noreferrer">jsFiddle example</a></p>
<h3>1.) Add this CSS to your site:</h3>
<pre class="lang-css prettyprint-override"><code>@media screen {
#printSection {
display: none;
}
}
@media print {
body * {
visibility:hidden;
}
#printSection, #printSection * {
visibility:visible;
}
#printSection {
position:absolute;
left:0;
top:0;
}
}
</code></pre>
<h3>2.) Add my JavaScript function</h3>
<pre class="lang-js prettyprint-override"><code>function printElement(elem, append, delimiter) {
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
$printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
if (append !== true) {
$printSection.innerHTML = "";
}
else if (append === true) {
if (typeof (delimiter) === "string") {
$printSection.innerHTML += delimiter;
}
else if (typeof (delimiter) === "object") {
$printSection.appendChild(delimiter);
}
}
$printSection.appendChild(domClone);
}
</code></pre>
<p>You're ready to print any element on your site!
<br />
Just call <code>printElement()</code> with your element(s) and execute <code>window.print()</code> when you're finished.</p>
<p><strong>Note:</strong>
If you want to modify the content before it is printed (and only in the print version), checkout this example (provided by waspina in the comments): <a href="http://jsfiddle.net/95ezN/121/" rel="noreferrer">http://jsfiddle.net/95ezN/121/</a></p>
<p>One could also use CSS in order to show the additional content in the print version (and only there).</p>
<hr />
<h2>Former solution</h2>
<p>I think, you have to hide all other parts of the site via CSS.</p>
<p>It would be the best, to move all non-printable content into a separate <code>DIV</code>:</p>
<pre class="lang-html prettyprint-override"><code><body>
<div class="non-printable">
<!-- ... -->
</div>
<div class="printable">
<!-- Modal dialog comes here -->
</div>
</body>
</code></pre>
<p>And then in your CSS:</p>
<pre class="lang-css prettyprint-override"><code>.printable { display: none; }
@media print
{
.non-printable { display: none; }
.printable { display: block; }
}
</code></pre>
<p>Credits go to <a href="https://stackoverflow.com/users/24181/greg">Greg</a> who has already answered a similar question: <a href="https://stackoverflow.com/questions/468881/print-div-id-printarea-div-only">Print <div id="printarea"></div> only?</a></p>
<p>There is <strong>one problem in using JavaScript</strong>: the user cannot see a preview - at least in Internet Explorer!</p> |
12,570,834 | Get file size, image width and height before upload | <p>How can I get the file size, image height and width before upload to my website, with jQuery or JavaScript?</p> | 12,570,870 | 7 | 2 | null | 2012-09-24 18:36:08.567 UTC | 77 | 2019-07-28 18:47:56.733 UTC | 2019-07-28 14:49:37.1 UTC | null | 383,904 | null | 1,682,339 | null | 1 | 105 | javascript|jquery|html|dimensions|image-size | 205,365 | <h1>Multiple images upload with info data preview</h1>
<p>Using <strong>HTML5 and the <a href="http://www.w3.org/TR/FileAPI/" rel="noreferrer">File API</a></strong></p>
<h3>Example using <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL#Static_methods" rel="noreferrer">URL API</a></h3>
<p>The images sources will be a <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL" rel="noreferrer">URL representing the Blob object</a><br>
<code><img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d"></code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const EL_browse = document.getElementById('browse');
const EL_preview = document.getElementById('preview');
const readImage = file => {
if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )
return EL_preview.insertAdjacentHTML('beforeend', `Unsupported format ${file.type}: ${file.name}<br>`);
const img = new Image();
img.addEventListener('load', () => {
EL_preview.appendChild(img);
EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB<div>`);
window.URL.revokeObjectURL(img.src); // Free some memory
});
img.src = window.URL.createObjectURL(file);
}
EL_browse.addEventListener('change', ev => {
EL_preview.innerHTML = ''; // Remove old images and data
const files = ev.target.files;
if (!files || !files[0]) return alert('File upload not supported');
[...files].forEach( readImage );
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#preview img { max-height: 100px; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="browse" type="file" multiple>
<div id="preview"></div></code></pre>
</div>
</div>
</p>
<h3>Example using <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader" rel="noreferrer">FileReader API</a></h3>
<p>In case you need images sources as long Base64 encoded data strings<br>
<code><img src="data:image/png;base64,iVBORw0KGg... ...lF/++TkSuQmCC="></code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const EL_browse = document.getElementById('browse');
const EL_preview = document.getElementById('preview');
const readImage = file => {
if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )
return EL_preview.insertAdjacentHTML('beforeend', `<div>Unsupported format ${file.type}: ${file.name}</div>`);
const reader = new FileReader();
reader.addEventListener('load', () => {
const img = new Image();
img.addEventListener('load', () => {
EL_preview.appendChild(img);
EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB</div>`);
});
img.src = reader.result;
});
reader.readAsDataURL(file);
};
EL_browse.addEventListener('change', ev => {
EL_preview.innerHTML = ''; // Clear Preview
const files = ev.target.files;
if (!files || !files[0]) return alert('File upload not supported');
[...files].forEach( readImage );
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#preview img { max-height: 100px; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="browse" type="file" multiple>
<div id="preview"></div>
</code></pre>
</div>
</div>
</p> |
43,964,539 | Google API: Not a valid origin for the client: url has not been whitelisted for client ID "ID" | <p>I need help. I don't found an answer to my question. I tried googling and I tried asking on other sides but I never found an answer.</p>
<p>I'm working with the google API (Youtube data API) and I use the example code from the google side the code it works I'm pretty sure about that. I got an error when i try to start the Script:</p>
<blockquote>
<p>details: "Not a valid origin for the client: "MyURL" has not been whitelisted for client ID "MyID". Please go to <a href="https://console.developers.google.com/" rel="noreferrer">https://console.developers.google.com/</a> and whitelist this origin for your project's client ID."</p>
<p>error: "idpiframe_initialization_failed"</p>
</blockquote>
<p>The problem i whitelisted my Website and it's accepted. i don't know what is wrong. What should i do to "whitelist" my Domain (It's whitelisted)</p>
<p>And another question. I did not search for an answer on this question before.</p>
<p>I think it's possible that I can use the code on Localhost, I think I must whitelist my localhost address or something like this. But whitelisting does not work.</p>
<ul>
<li>DreamGamer</li>
</ul> | 44,370,212 | 21 | 3 | null | 2017-05-14 13:39:46.16 UTC | 20 | 2022-04-25 19:23:58.527 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 8,010,227 | null | 1 | 127 | google-api|youtube-data-api|whitelist | 135,214 | <p>Had the same problem and here's how I solved it:</p>
<ol>
<li>Activate both Analytics and Google Plus APIs on your project</li>
<li>Create new OAUTH 2.0 client credentials
<ul>
<li>Add the <strong>Authorized Javascript Origins</strong> under <strong>Restrictions</strong> section</li>
</ul></li>
<li>Use the new client id.</li>
</ol>
<p>Enjoy.</p> |
24,259,508 | java.lang.ClassNotFoundException: org.springframework.core.io.Resource | <p>I'm using spring 4.0.5, Hibernate 4.3.5 and JSF for web developpement in eclipse, and this is the content of my <code>lib</code> folder :</p>
<p><img src="https://i.stack.imgur.com/7jiC6.png" alt="enter image description here"></p>
<p>When I run my project I get this error : </p>
<pre><code>java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/EMaEval]]
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:799)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/EMaEval]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 6 more
Caused by: java.lang.NoClassDefFoundError: org/springframework/core/io/Resource
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Unknown Source)
at java.lang.Class.getDeclaredFields(Unknown Source)
at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:261)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationListenerAnnotations(WebAnnotationSet.java:90)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:63)
at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:403)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:879)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:374)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5355)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more
Caused by: java.lang.ClassNotFoundException: org.springframework.core.io.Resource
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
... 20 more
</code></pre>
<p>these are the configuration files :</p>
<p><code>web.xml</code></p>
<pre class="lang-xml prettyprint-override"><code> <?xml version="1.0" encoding="ASCII"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name></display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsf</welcome-file>
</welcome-file-list>
</web-app>
</code></pre>
<p><code>application-context.xml</code></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/ schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value ="org.postgresql.Driver" />
<property name="user" value="postgres" />
<property name="password" value="toor"/>
<property name="jdbcUrl" value="jdbc:postgresql://172.16.83.128:5432/emaeval" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.models" />
<property name="hibernateProperties">
<props>
<prop key="hiberante.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
</props>
</property>
</bean>
<bean id="tansactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config/>
<context:component-scan base-package="com"></context:component-scan>
</beans>
</code></pre>
<p>How can I solve this probelm ?</p> | 24,259,842 | 6 | 4 | null | 2014-06-17 08:52:55.613 UTC | 4 | 2020-07-13 10:00:33.03 UTC | 2014-06-17 09:03:02.683 UTC | null | 865,448 | null | 1,754,790 | null | 1 | 15 | java|spring | 136,406 | <p>Make sure, following jar file included in your class path and lib folder.</p>
<p><strong><em>spring-core-3.0.5.RELEASE.jar</em></strong></p>
<p><img src="https://i.stack.imgur.com/BIy6t.png" alt="enter image description here"></p>
<p>if you are using maven, make sure you have included dependency for spring-core-3xxxxx.jar file</p>
<pre><code><dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
</code></pre>
<p>Note : Replace ${org.springframework.version} with version number. </p> |
3,867,164 | SQL update query syntax with inner join | <p>Can anyone find my error in this query? I'm using SQL Server 2000 and I want to update all entries in the CostEntry table to the corresponding value in the ActiveCostDetails table. The where clause DOES work with a select statement.</p>
<pre><code> UPDATE CostEntry CE
INNER JOIN ActiveCostDetails As AD ON CostEntry.lUniqueID = ActiveCostDetails.UniqueID
SET CostEntry.sJobNumber = ActiveCostDetails.JobNumber
WHERE CostEntry.SEmployeeCode = '002'
AND SubString(CostCentre, 1, 1) = sDepartmentCode
AND substring(CostCentre, 3, 1) = sCategoryCode
AND substring(CostCentre, 5, 2) = sOperationCode
</code></pre> | 3,867,188 | 3 | 3 | null | 2010-10-05 19:49:34.507 UTC | 4 | 2020-07-20 12:56:27.137 UTC | 2012-05-03 15:46:38.887 UTC | null | 1,209,430 | null | 456,532 | null | 1 | 32 | sql|sql-server|tsql|sql-server-2000|sql-update | 102,132 | <p>The <code>SET</code> needs to come before the <code>FROM\JOIN\WHERE</code> portion of the query.</p>
<pre><code>UPDATE CE
SET sJobNumber = AD.JobNumber
FROM CostEntry CE
INNER JOIN ActiveCostDetails As AD
ON CE.lUniqueID = AD.UniqueID
WHERE CE.SEmployeeCode = '002'
AND SubString(CostCentre, 1, 1) = sDepartmentCode
AND substring(CostCentre, 3, 1) = sCategoryCode
AND substring(CostCentre, 5, 2) = sOperationCode
</code></pre> |
22,609,217 | Rounding Bigdecimal values with 2 Decimal Places | <p>I want a function to convert <em>Bigdecimal</em> <code>10.12 for 10.12345</code> and <code>10.13 for 10.12556</code>.
But no function is satisfying both conversion in same time.Please help to achieve this.</p>
<p>Below is what I tried.<br>
With value 10.12345:</p>
<pre><code>BigDecimal a = new BigDecimal("10.12345");
a.setScale(2, BigDecimal.ROUND_UP)
a.setScale(2, BigDecimal.ROUND_CEILING)
a.setScale(2, BigDecimal.ROUND_DOWN)
a.setScale(2, BigDecimal.ROUND_FLOOR)
a.setScale(2, BigDecimal.ROUND_HALF_DOWN)
a.setScale(2, BigDecimal.ROUND_HALF_EVEN)
a.setScale(2, BigDecimal.ROUND_HALF_UP)
</code></pre>
<p>Output :</p>
<pre><code>10.12345::10.13
10.12345::10.13
10.12345::10.12
10.12345::10.12
10.12345::10.12
10.12345::10.12
10.12345::10.12
</code></pre>
<p>With value 10.12556:</p>
<pre><code>BigDecimal b = new BigDecimal("10.12556");
b.setScale(2, BigDecimal.ROUND_UP)
b.setScale(2, BigDecimal.ROUND_CEILING)
b.setScale(2, BigDecimal.ROUND_DOWN)
b.setScale(2, BigDecimal.ROUND_FLOOR)
b.setScale(2, BigDecimal.ROUND_HALF_DOWN)
b.setScale(2, BigDecimal.ROUND_HALF_EVEN)
b.setScale(2, BigDecimal.ROUND_HALF_UP)
</code></pre>
<p>Output :</p>
<pre><code>10.12556::10.13
10.12556::10.13
10.12556::10.12
10.12556::10.12
10.12556::10.12
10.12556::10.12
10.12556::10.12
</code></pre> | 22,610,642 | 4 | 12 | null | 2014-03-24 12:19:45.587 UTC | 4 | 2021-08-25 10:36:21.563 UTC | 2019-03-01 14:40:23.84 UTC | null | 3,681,565 | null | 1,755,242 | null | 1 | 69 | java|bigdecimal | 179,723 | <p>I think that the <code>RoundingMode</code> you are looking for is <code>ROUND_HALF_EVEN</code>. From <a href="http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#ROUND_HALF_EVEN" rel="noreferrer">the javadoc</a>:</p>
<blockquote>
<p>Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.</p>
</blockquote>
<p>Here is a quick test case:</p>
<pre><code>BigDecimal a = new BigDecimal("10.12345");
BigDecimal b = new BigDecimal("10.12556");
a = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
b = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(a);
System.out.println(b);
</code></pre>
<p>Correctly prints:</p>
<pre><code>10.12
10.13
</code></pre>
<p>UPDATE:</p>
<p><code>setScale(int, int)</code> has not been recommended since Java 1.5, when enums were first introduced, and was finally deprecated in Java 9. You should now use <code>setScale(int, RoundingMode)</code> e.g: </p>
<p><code>setScale(2, RoundingMode.HALF_EVEN)</code></p> |
26,070,410 | Robust atan(y,x) on GLSL for converting XY coordinate to angle | <p>In GLSL (specifically 3.00 that I'm using), there are two versions of
<code>atan()</code>: <code>atan(y_over_x)</code> can only return angles between -PI/2, PI/2, while <code>atan(y/x)</code> can take all 4 quadrants into account so the angle range covers everything from -PI, PI, much like <code>atan2()</code> in C++. </p>
<p>I would like to use the second <code>atan</code> to convert XY coordinates to angle.
However, <code>atan()</code> in GLSL, besides not able to handle when <code>x = 0</code>, is not very stable. Especially where <code>x</code> is close to zero, the division can overflow resulting in an opposite resulting angle (you get something close to -PI/2 where you suppose to get approximately PI/2).</p>
<p>What is a good, simple implementation that we can build on top of GLSL <code>atan(y,x)</code> to make it more robust?</p> | 26,070,411 | 5 | 5 | null | 2014-09-27 01:27:09.607 UTC | 8 | 2019-01-17 12:38:11.23 UTC | null | null | null | null | 1,452,174 | null | 1 | 16 | c++|glsl|coordinates|atan2|numerical-stability | 16,033 | <p>I'm going to answer my own question to share my knowledge. We first notice that the instability happens when <code>x</code> is near zero. However, we can also translate that as <code>abs(x) << abs(y)</code>. So first we divide the plane (assuming we are on a unit circle) into two regions: one where <code>|x| <= |y|</code> and another where <code>|x| > |y|</code>, as shown below:</p>
<p><img src="https://i.imgur.com/85MbHs4.png" alt="two regions"></p>
<p>We know that <code>atan(x,y)</code> is much more stable in the green region -- when x is close to zero we simply have something close to atan(0.0) which is very stable numerically, while the usual <code>atan(y,x)</code> is more stable in the orange region. You can also convince yourself that this relationship:</p>
<pre><code>atan(x,y) = PI/2 - atan(y,x)
</code></pre>
<p>holds for all non-origin (x,y), where it is undefined, and we are talking about <code>atan(y,x)</code> that is able to return angle value in the entire range of -PI,PI, not <code>atan(y_over_x)</code> which only returns angle between -PI/2, PI/2. Therefore, our robust <code>atan2()</code> routine for GLSL is quite simple:</p>
<pre><code>float atan2(in float y, in float x)
{
bool s = (abs(x) > abs(y));
return mix(PI/2.0 - atan(x,y), atan(y,x), s);
}
</code></pre>
<p>As a side note, the identity for mathematical function <code>atan(x)</code> is actually:</p>
<pre><code>atan(x) + atan(1/x) = sgn(x) * PI/2
</code></pre>
<p>which is true because its range is (-PI/2, PI/2).</p>
<p><img src="https://i.stack.imgur.com/lvnfy.png" alt="graph"></p> |
21,989,860 | Get total size of a list of files in UNIX | <p>I want to run a <code>find</code> command that will find a certain list of files and then iterate through that list of files to run some operations. I also want to find the total size of all the files in that list.</p>
<p>I'd like to make the list of files FIRST, then do the other operations. Is there an easy way I can report just the total size of all the files in the list?</p>
<p>In essence I am trying to find a one-liner for the 'total_size' variable in the code snippet below:</p>
<pre><code>#!/bin/bash
loc_to_look='/foo/bar/location'
file_list=$(find $loc_to_look -type f -name "*.dat" -size +100M)
total_size=???
echo 'total size of all files is: '$total_size
for file in $file_list; do
# do a bunch of operations
done
</code></pre> | 21,990,076 | 6 | 4 | null | 2014-02-24 13:56:32.483 UTC | 14 | 2020-04-19 20:03:05.077 UTC | null | null | null | null | 2,378,266 | null | 1 | 50 | bash|shell|unix | 59,825 | <p>You should simply be able to pass <code>$file_list</code> to <code>du</code>:</p>
<pre><code>du -ch $file_list | tail -1 | cut -f 1
</code></pre>
<p><code>du</code> options:</p>
<ul>
<li><code>-c</code> display a total</li>
<li><code>-h</code> human readable (i.e. 17M)</li>
</ul>
<p><code>du</code> will print an entry for each file, followed by the total (with <code>-c</code>), so we use <code>tail -1</code> to trim to only the last line and <code>cut -f 1</code> to trim that line to only the first column.</p> |
11,352,056 | PostgreSQL composite primary key | <p>In MySQL, when I create a composite primary key, say with columns <code>X, Y, Z</code>, then all three columns become indexes automatically. Does the same happen for Postgres?</p> | 11,352,543 | 3 | 1 | null | 2012-07-05 20:25:17.037 UTC | 14 | 2020-10-07 11:23:50.877 UTC | 2012-07-05 21:05:06.73 UTC | null | 939,860 | null | 1,467,855 | null | 1 | 50 | postgresql|indexing|composite-primary-key | 31,056 | <p>If you create a composite primary key, on <code>(x, y, z)</code>, PostgreSQL implements this with the help of one <code>UNIQUE</code> multi-column btree index on <code>(x, y, z)</code>. In addition, all three columns are <code>NOT NULL</code> (implicitly), which is the main difference between a <code>PRIMARY KEY</code> and a <code>UNIQUE INDEX</code>.</p>
<p>Besides obvious restrictions on your data, the <a href="https://www.postgresql.org/docs/current/indexes-bitmap-scans.html" rel="noreferrer">multi-column index</a> also has a somewhat different effect on the performance of queries than three individual indexes on <code>x</code>, <code>y</code> and <code>z</code>.</p>
<p>Related discussion on dba.SE:</p>
<ul>
<li><a href="https://dba.stackexchange.com/q/6115/3684">Working of indexes in PostgreSQL</a></li>
</ul>
<p>With examples, benchmarks, discussion and outlook on the new feature of <a href="https://wiki.postgresql.org/wiki/What%27s_new_in_PostgreSQL_9.2#Index-only_scans" rel="noreferrer"><em>index-only scans</em> in Postgres 9.2</a>.</p>
<p>In particular, a primary key on <code>(x, y, z)</code> will speed up queries with conditions on <code>x</code>, <code>(x,y)</code> or <code>(x,y,z)</code> optimally. It will also help with queries on <code>y</code>, <code>z</code>, <code>(y,z)</code> or <code>(x,z)</code> but to a far lesser extent.</p>
<p>If you need to speed up queries on the latter combinations, you may want to change the order of column in your PK constraint and/or create one or more additional indexes. See:</p>
<ul>
<li><a href="https://dba.stackexchange.com/a/27493/3684">Is a composite index also good for queries on the first field?</a></li>
</ul> |
10,921,451 | Start Activity Using Custom Action | <p>I am looking to start an activity in my app using a custom action. I have found a few answers but everything I try it throws <code>java.lang.RuntimeException</code> saying No Activity found to handle Intent { act=com.example.foo.bar.YOUR_ACTION }.</p>
<p>This is the activity in my manifest file:</p>
<pre><code><activity
android:name=".FeedbackActivity" >
<intent-filter>
<action android:name="com.example.foo.bar.YOUR_ACTION" />
</intent-filter>
</activity>
</code></pre>
<p>And this is how I'm starting the activity:</p>
<pre><code>Intent intent = new Intent("com.example.foo.bar.YOUR_ACTION");
startActivity(intent);
</code></pre>
<p>Any help would be greatly appreciated.</p> | 10,922,326 | 4 | 2 | null | 2012-06-06 20:09:57.147 UTC | 19 | 2021-04-27 19:01:41.857 UTC | 2012-06-06 20:11:52.507 UTC | null | 927,034 | null | 1,215,222 | null | 1 | 51 | android|android-intent|android-activity | 62,959 | <p>I think you are creating your intent wrong. Try like this:</p>
<pre><code>String CUSTOM_ACTION = "com.example.foo.bar.YOUR_ACTION";
//Intent i = new Intent(this, FeedBackActivity.class); // <--- You might need to do it this way.
Intent i = new Intent();
i.setAction(CUSTOM_ACTION);
startActivity(i);
</code></pre> |
10,972,555 | iOS: load an image from url | <p>I need to load an image from a url and set it inside an UIImageView; the problem is that I don't know the exact size of the image, then how can I show the image correctly?</p> | 10,972,566 | 9 | 1 | null | 2012-06-10 21:38:03.503 UTC | 14 | 2021-12-14 05:48:29.63 UTC | 2016-02-22 22:10:04.883 UTC | null | 1,265,393 | null | 630,412 | null | 1 | 55 | ios|uiimageview|uiimage|nsurl | 89,852 | <p>Just use the size property of UIImage, for example:</p>
<pre><code>NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
CGSize size = img.size;
</code></pre> |
12,825,669 | Remove cookie on log-out | <p>On pageload of Home page, I have set a cookie like this:-</p>
<pre><code>if (abc == true)
{
HttpCookie cookie = new HttpCookie("Administrator");
cookie.Value = "Admin";
cookie.Expires = DateTime.Now.AddDays(-1);
Response.SetCookie(cookie);
}
</code></pre>
<p>And use the cookie as:-</p>
<pre><code>if (Request.Cookies["Administrator"] != null)
{
if (Request.Cookies["Administrator"].Value == "Admin")
//some code
}
</code></pre>
<p>On log out I want this cookie should expire or gets deleted. So there I have written:- <code>Seesion.Abandon();</code></p>
<p>Now even after I log-out, when I log back in to Home page..
the line <code>Request.Cookies["Administrator"]</code> is stil not empty.</p>
<p>Strange...! Please let me know whats the reason and solution for this.</p> | 12,825,719 | 4 | 0 | null | 2012-10-10 18:11:02.707 UTC | 9 | 2019-12-29 10:32:23.947 UTC | 2012-10-10 18:16:47.423 UTC | null | 655,203 | null | 609,736 | null | 1 | 11 | asp.net|cookies | 50,795 | <p>You can try with</p>
<pre><code>Session.Abandon();
Response.Cookies.Clear();
</code></pre>
<p>Or also </p>
<pre><code>YourCookies.Expires = DateTime.Now.AddDays(-1d);
</code></pre>
<p>Link : <a href="http://msdn.microsoft.com/en-us/library/ms178195%28v=vs.100%29.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms178195%28v=vs.100%29.aspx</a></p> |
12,717,969 | JavaFX 2 custom popup pane | <p>The JavaFX 2 colour picker has a button that pops up a colour chooser pane like so:</p>
<p><img src="https://i.stack.imgur.com/fKAHT.png" alt="JavaFX 2 colour picker"></p>
<p>I'd like to do something similar, in that I'd like a custom pane to pop up when the button is clicked on and disappear when something else is clicked (in my case, a few image thumbnails). What would be the best way of achieving this? Should I use a ContextMenu and add a pane to a MenuItem somehow, or is there something else I should look at?</p> | 12,718,891 | 1 | 0 | null | 2012-10-03 22:47:51.97 UTC | 9 | 2016-10-25 20:00:53.237 UTC | null | null | null | null | 551,406 | null | 1 | 20 | popup|javafx-2|javafx | 22,350 | <p>It's kind of difficult to do well with the current JavaFX 2.2 API.</p>
<p>Here are some options.</p>
<hr>
<p><em>Use a MenuButton with a graphic set in it's MenuItem</em></p>
<p>This is the approach taken in <a href="https://stackoverflow.com/a/15560080/1155209">Button with popup showed below</a>'s executable <a href="https://gist.github.com/jewelsea/5217750" rel="noreferrer">sample code</a>.</p>
<p><img src="https://i.stack.imgur.com/mEBxb.png" alt="wizpopup"></p>
<hr>
<p><em>Use a PopupControl</em></p>
<p>Take a look at how the ColorPicker does this in it's <a href="http://hg.openjdk.java.net/openjfx/8/master/rt/file/7c436f8509c8/javafx-ui-controls/src/com/sun/javafx/scene/control/skin/ColorPickerSkin.java" rel="noreferrer">code</a>.</p>
<p>ColorPicker extends <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/PopupControl.html" rel="noreferrer">PopupControl</a>. You could do this, but not all of the API required to build your own PopupControl is currently public. So, for JavaFX 2.2, you would have to rely on internal com.sun classes which are deprecated and will be replaced by public javafx.scene.control classes in JDK8.</p>
<hr>
<p><em>Use a ContextMenu</em></p>
<p>So, I think your idea to "use a ContextMenu and add a pane to a MenuItem" is probably the best approach for now. You should be able to do this by using a <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/CustomMenuItem.html" rel="noreferrer">CustomMenuItem</a> or <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/MenuItem.html#setGraphic%28javafx.scene.Node%29" rel="noreferrer">setting a graphic</a> on a normal <code>MenuItem</code>. The <code>ContextMenu</code> has nice <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/ContextMenu.html#show%28javafx.scene.Node,%20javafx.geometry.Side,%20double,%20double%29" rel="noreferrer">relative positioning logic</a>. A <code>ContextMenu</code> can also be triggered by a <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/MenuButton.html" rel="noreferrer">MenuButton</a>.</p>
<hr>
<p><em>Use a Custom Dialog</em></p>
<p>To do this, display a transparent stage at a location relative to the node.</p>
<p>There is some sample code to get you started which I have temporarily linked <a href="https://s3.amazonaws.com/baanthaispa/ConfirmationDialog.zip" rel="noreferrer">here</a>.
The sample code does relative positioning to the sides of the main window, but you could update it to perform positioning relative to the sides of a given node (like the ContextMenu's show method).</p>
<hr>
<p><em>Use a Glass Pane</em></p>
<p>To do this, create a StackPane as your root of your main window. Place your main content pane as the first node in the StackPane and then create a Group as the second node in the stackpane, so that it will layer over the top of the main content. Normally, the top group contains nothing, but when you want to show your popup, place it in the top group and translate it to a location relative to the appropriate node in your main content.</p>
<p>You could look at how the anchor nodes in <a href="https://gist.github.com/1441960" rel="noreferrer">this demo</a> are used to see how this might be adaptable to your context.</p>
<hr>
<blockquote>
<p>Is there a relevant update for this for JavaFX8? </p>
</blockquote>
<p>There is not much difference of relevance for Java 8, in general the options are as outlined in this post based on Java 2.2 functionality. Java 8 does add <a href="https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Dialog.html" rel="noreferrer">Dialog</a> and <a href="https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.html" rel="noreferrer">Alert</a> functionality, but those are more targeted at use of dialogs with borders, titles and buttons rather than the kind of functionality desired in the question. Perhaps you might be able to start from the Dialog class and heavily customize it to get something close to what is needed, but you are probably better off starting from a blank stage or PopupControl instead.</p> |
13,081,653 | Difference between static and dynamic web project in eclipse | <p>Is there any difference between static and dynamic projects in eclipse 3.x.when it will be use static project?</p> | 13,081,698 | 3 | 0 | null | 2012-10-26 06:08:51.393 UTC | 7 | 2014-10-25 21:11:12.057 UTC | null | null | null | null | 1,357,722 | null | 1 | 30 | eclipse | 45,634 | <p>In static web project, you will not have Java, servlets and JSP etc. (server side scripts).
You can only have HTML, JavaScript etc.</p>
<p>Please check the link below, it will help you:</p>
<p><a href="http://www.velvetblues.com/web-development-blog/what-is-the-difference-between-static-and-dynamic-websites/">http://www.velvetblues.com/web-development-blog/what-is-the-difference-between-static-and-dynamic-websites/</a></p> |
12,872,446 | git with --git-dir= results in 'not a git repository' | <p>I have a script in one of my iOS apps that should get the git revision hash and put it in the version number. In this script I run git --git-dir="$PROJECT_DIR" show -s --pretty=format:%h for that. However, I get the message that the directory isn't a git repository. If I echo the PROJECT_DIR var and go to the terminal the following works:</p>
<pre><code>cd projectDirPath
git show -s --pretty=format:%h
</code></pre>
<p>What doesn't work is:</p>
<pre><code>git --git-dir=projectDirPath show -s --pretty=format:%h
</code></pre>
<p>Am I missing something? The documentation states, that I can specify the path to a git repository with --git-dir and the specified path obviously is a git repository as all the git commands work without any problem if I first cd into that path. However if I am not in this path, specifing --git-dir doesn't work.</p> | 12,881,460 | 3 | 3 | null | 2012-10-13 10:58:50.193 UTC | 4 | 2021-12-24 18:39:43.673 UTC | 2021-12-24 18:39:43.673 UTC | null | 1,839,439 | null | 653,133 | null | 1 | 34 | git|bash|terminal|sh | 5,823 | <p>When using <a href="https://git-scm.com/docs/git#Documentation/git.txt---git-dirltpathgt" rel="noreferrer"><code>--git-dir</code></a>, you need to point at the <code>.git</code> folder of your repository. Try:</p>
<pre><code>git --git-dir=projectDirPath/.git show -s --pretty=format:%h
</code></pre>
<p>The doc on <code>--git-dir</code> says that:</p>
<blockquote>
<p>--git-dir=</p>
<p>Set the path to the repository (".git" directory). This can also be controlled by setting the GIT_DIR environment variable. It can be an absolute path or relative path to current working directory.</p>
</blockquote>
<p>I use to have an issue remembering this myself. To help me remember what to do, I try to remember that the option is asking for exactly what it wants: the path to the <code>.git</code> directory (git-dir).</p> |
12,681,357 | TWTweetComposeViewController deprecated in IOS6 | <p>My code is working as expected just that I need to get rid of this warning message.
TWTeetComposeViewController deprecated in IOS6. Any replacement for this built-in view controller in ios6?</p>
<p>Here is my sample code.</p>
<pre><code>if ([TWTweetComposeViewController canSendTweet]) {
// Initialize Tweet Compose View Controller
TWTweetComposeViewController *vc = [[TWTweetComposeViewController alloc] init];
// Settin The Initial Text
[vc setInitialText:@"This tweet was sent using the new Twitter framework available in iOS 5."];
// Adding an Image
UIImage *image = [UIImage imageNamed:@"sample.jpg"];
[vc addImage:image];
// Adding a URL
NSURL *url = [NSURL URLWithString:@"http://mobile.tutsplus.com"];
[vc addURL:url];
// Setting a Completing Handler
[vc setCompletionHandler:^(TWTweetComposeViewControllerResult result) {
[self dismissModalViewControllerAnimated:YES];
}];
// Display Tweet Compose View Controller Modally
[self presentViewController:vc animated:YES completion:nil];
} else {
// Show Alert View When The Application Cannot Send Tweets
NSString *message = @"The application cannot send a tweet at the moment. This is because it cannot reach Twitter or you don't have a Twitter account associated with this device.";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Oops" message:message delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[alertView show];
}
</code></pre> | 16,494,448 | 2 | 1 | null | 2012-10-01 21:26:29.543 UTC | 2 | 2020-01-06 10:10:10.043 UTC | 2012-11-20 15:28:27.133 UTC | null | 631 | null | 1,688,346 | null | 1 | 39 | objective-c|ios|twitter|ios6 | 19,801 | <p>There're some change with using Social network between iOS 5 & iOS 6.
<br/>
1. About library: in iOS 6 we use Social framework instead of Twitter
Framework.
<br/>
2. We use SLComposeViewController instead of TWTweetComposeViewController.
<br/>
3.Please compare some api with the following code:</p>
<pre><code>if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"Cancelled");
} else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
//Adding the Text to the facebook post value from iOS
[controller setInitialText:@"Test Post from mobile.safilsunny.com"];
//Adding the URL to the facebook post value from iOS
[controller addURL:[NSURL URLWithString:@"http://www.mobile.safilsunny.com"]];
//Adding the Image to the facebook post value from iOS
[controller addImage:[UIImage imageNamed:@"fb.png"]];
[self presentViewController:controller animated:YES completion:Nil];
}
else{
NSLog(@"UnAvailable");
}
</code></pre>
<p>There's just a little differences, but they're more great.</p>
<p>PREFERENCES:
- safilsunny Tips: <a href="http://www.mobile.safilsunny.com/integrating-facebook-ios-6/" rel="noreferrer">http://www.mobile.safilsunny.com/integrating-facebook-ios-6/</a></p>
<p>Thanks,</p> |
12,843,099 | Python: Logging TypeError: not all arguments converted during string formatting | <p>Here is what I am doing</p>
<pre><code>>>> import logging
>>> logging.getLogger().setLevel(logging.INFO)
>>> from datetime import date
>>> date = date.today()
>>> logging.info('date={}', date)
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 846, in emit
msg = self.format(record)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 723, in format
return fmt.format(record)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 464, in format
record.message = record.getMessage()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 328, in getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file <stdin>, line 1
>>>
</code></pre>
<p>My python version is </p>
<pre><code>$ python --version
Python 2.7.3
</code></pre>
<p>How do I make it work?</p> | 12,843,568 | 4 | 1 | null | 2012-10-11 15:23:29.56 UTC | 9 | 2018-08-17 11:25:08.713 UTC | 2012-10-11 15:27:44.43 UTC | null | 100,297 | null | 379,235 | null | 1 | 57 | python|logging|string-formatting | 50,406 | <p>You could do the formatting yourself:</p>
<pre><code>logging.info('date={}'.format(date))
</code></pre>
<p>As was pointed out by Martijn Pieters, this will always run the string formatting, while using the logging module would cause the formatting to only be performed if the message is actually logged. </p> |
13,155,449 | How to do a verbatim string literal in VB.NET? | <p>How do you do a <em>verbatim</em> string literal in VB.NET?</p>
<p>This is achieved in C# as follows:</p>
<pre><code>String str = @"c:\folder1\file1.txt";
</code></pre>
<p>This means that the backslashes are treated literally and not as escape characters.</p>
<p>How is this achieved in VB.NET?</p> | 13,155,483 | 7 | 0 | null | 2012-10-31 10:04:46.1 UTC | 3 | 2018-02-08 06:46:16.77 UTC | null | null | null | null | 327,528 | null | 1 | 63 | c#|vb.net|string|escaping|verbatim-string | 49,095 | <p>All string literals in VB.NET are verbatim string literals. Simply write</p>
<pre><code>Dim str As String = "c:\folder1\file1.txt"
</code></pre>
<p>VB.NET doesn't support inline control characters. So backslashes are always interpreted literally. </p>
<p>The only character that needs to be escaped is the double quotation mark, which is escaped by doubling it, as you do in C#</p>
<pre><code>Dim s As String = """Ahoy!"" cried the captain." ' "Ahoy!" cried the captain.
</code></pre> |
12,711,202 | how to turn on minor ticks only on y axis matplotlib | <p>How can I turn the minor ticks only on y axis on a linear vs linear plot?</p>
<p>When I use the function <code>minor_ticks_on</code> to turn minor ticks on, they appear on both x and y axis.</p> | 12,711,768 | 6 | 1 | null | 2012-10-03 14:58:29.22 UTC | 20 | 2020-12-25 18:45:01.47 UTC | 2019-04-16 09:58:53.81 UTC | null | 1,714,692 | null | 1,269,526 | null | 1 | 96 | python|matplotlib | 137,235 | <p>Nevermind, I figured it out.</p>
<pre><code>ax.tick_params(axis='x', which='minor', bottom=False)
</code></pre> |
12,692,089 | Preventing "double" borders in CSS | <p>Say I have two divs next to each other (take <a href="https://chrome.google.com/webstore/category/home" rel="noreferrer">https://chrome.google.com/webstore/category/home</a> as reference) with a border.</p>
<p>Is there a way (preferably a CSS trick) to prevent my divs from appearing like having a double border? Have a look at this image to better understand what I mean: </p>
<p><img src="https://i.stack.imgur.com/tWNni.png" alt=""Double" border"></p>
<p>You can see that where the two divs meet, it appears like they have a double border.</p> | 12,692,124 | 19 | 3 | null | 2012-10-02 14:19:01.387 UTC | 25 | 2021-09-27 09:26:42.543 UTC | 2012-10-02 14:36:44.553 UTC | null | 58,792 | null | 1,687,353 | null | 1 | 121 | css | 91,313 | <p><code>#divNumberOne { border-right: 0; }</code></p> |
30,317,119 | classifiers in scikit-learn that handle nan/null | <p>I was wondering if there are classifiers that handle nan/null values in scikit-learn. I thought random forest regressor handles this but I got an error when I call <code>predict</code>.</p>
<pre><code>X_train = np.array([[1, np.nan, 3],[np.nan, 5, 6]])
y_train = np.array([1, 2])
clf = RandomForestRegressor(X_train, y_train)
X_test = np.array([7, 8, np.nan])
y_pred = clf.predict(X_test) # Fails!
</code></pre>
<p>Can I not call predict with any scikit-learn algorithm with missing values?</p>
<p><strong>Edit.</strong>
Now that I think about this, it makes sense. It's not an issue during training but when you predict how do you branch when the variable is null? maybe you could just split both ways and average the result? It seems like k-NN should work fine as long as the distance function ignores nulls though.</p>
<p><strong>Edit 2 (older and wiser me)</strong>
Some gbm libraries (such as xgboost) use a ternary tree instead of a binary tree precisely for this purpose: 2 children for the yes/no decision and 1 child for the missing decision. sklearn is <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_tree.pyx#L70-L74" rel="noreferrer">using a binary tree</a></p> | 30,319,249 | 4 | 5 | null | 2015-05-19 05:02:35.13 UTC | 15 | 2020-06-12 09:07:24.447 UTC | 2017-10-26 20:34:45.693 UTC | null | 1,536,499 | null | 1,536,499 | null | 1 | 72 | python|pandas|machine-learning|scikit-learn|nan | 71,365 | <p>I made an example that contains both missing values in training and the test sets</p>
<p>I just picked a strategy to replace missing data with the mean, using the <code>SimpleImputer</code> class. There are other strategies.</p>
<pre><code>from __future__ import print_function
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
X_train = [[0, 0, np.nan], [np.nan, 1, 1]]
Y_train = [0, 1]
X_test_1 = [0, 0, np.nan]
X_test_2 = [0, np.nan, np.nan]
X_test_3 = [np.nan, 1, 1]
# Create our imputer to replace missing values with the mean e.g.
imp = SimpleImputer(missing_values=np.nan, strategy='mean')
imp = imp.fit(X_train)
# Impute our data, then train
X_train_imp = imp.transform(X_train)
clf = RandomForestClassifier(n_estimators=10)
clf = clf.fit(X_train_imp, Y_train)
for X_test in [X_test_1, X_test_2, X_test_3]:
# Impute each test item, then predict
X_test_imp = imp.transform(X_test)
print(X_test, '->', clf.predict(X_test_imp))
# Results
[0, 0, nan] -> [0]
[0, nan, nan] -> [0]
[nan, 1, 1] -> [1]
</code></pre> |
22,290,501 | Can I download the Visual C++ Command Line Compiler without Visual Studio? | <p>As per the title. I don't want to download the entire Visual C++ installer, only "cl.exe" and the other programs required for compiling and linking C++ programs on Windows.</p> | 22,290,557 | 10 | 12 | null | 2014-03-10 01:10:32.007 UTC | 23 | 2022-03-21 22:34:20.23 UTC | null | null | null | null | 1,420,752 | null | 1 | 101 | c++|winapi|visual-c++ | 91,540 | <p>In 2014 you could not download the Visual C++ compiler alone from Microsoft.</p>
<p>It used to be that you could. Then it used to be that you could get it in the Platform SDK. Then you could only get it by installing Visual Studio.</p>
<p>Happily, at that time, the compiler that was bundled with Visual Studio Express for Desktop (the free version of Visual Studio at the time) was, and is, the very same that you get with Professional or Universal editions.</p>
<p>In November 2015 Microsoft again started providing the compiler tools in a free-standing package called the <strong><a href="https://blogs.msdn.microsoft.com/vcblog/2015/11/02/announcing-visual-c-build-tools-2015-standalone-c-tools-for-build-environments/" rel="nofollow">Visual C++ Build Tools</a></strong>.</p>
<p>Microsoft writes:</p>
<blockquote>
<p><strong>”</strong> the C++ Build Tools installer will not run on a machine with Visual Studio 2015 already installed on it. The reverse (i.e. upgrade to Visual Studio) is supported.</p>
</blockquote>
<p>The long term situation is, as always, unclear. And, disclaimer: I have not used the build tools myself – I would have to uninstall Visual Studio first.</p> |
11,120,392 | Android Center text on canvas | <p>I'm trying to display a text using the code below.
The problem is that the text is not centered horizontally.
When I set the coordinates for <code>drawText</code>, it sets the bottom of the text at this position. I would like the text to be drawn so that the text is centered also horizontally.</p>
<p>This is a picture to display my problem further:</p>
<p><a href="https://i.stack.imgur.com/vEJNb.png"><img src="https://i.stack.imgur.com/vEJNbm.png" alt="Screenshot"></a></p>
<pre><code>@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//canvas.drawRGB(2, 2, 200);
Paint textPaint = new Paint();
textPaint.setARGB(200, 254, 0, 0);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTypeface(font);
textPaint.setTextSize(300);
canvas.drawText("Hello", canvas.getWidth()/2, canvas.getHeight()/2 , textPaint);
}
</code></pre> | 11,121,873 | 12 | 4 | null | 2012-06-20 13:13:15.967 UTC | 81 | 2020-12-21 22:25:22.707 UTC | 2015-06-07 03:10:59.023 UTC | null | 1,402,846 | null | 1,469,324 | null | 1 | 224 | java|android|android-activity|android-canvas|drawtext | 131,958 | <p>Try the following:</p>
<pre><code> Paint textPaint = new Paint();
textPaint.setTextAlign(Paint.Align.CENTER);
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
//((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
canvas.drawText("Hello", xPos, yPos, textPaint);
</code></pre> |
25,522,309 | Converting JSON between string and byte[] with GSON | <p>I'm using hibernate to map objects to the database. A client (an iOS app) sends me particular objects in JSON format which I convert to their true representation using the following utility method:</p>
<pre><code>/**
* Convert any json string to a relevant object type
* @param jsonString the string to convert
* @param classType the class to convert it too
* @return the Object created
*/
public static <T> T getObjectFromJSONString(String jsonString, Class<T> classType) {
if(stringEmptyOrNull(jsonString) || classType == null){
throw new IllegalArgumentException("Cannot convert null or empty json to object");
}
try(Reader reader = new StringReader(jsonString)){
Gson gson = new GsonBuilder().create();
return gson.fromJson(reader, classType);
} catch (IOException e) {
Logger.error("Unable to close the reader when getting object as string", e);
}
return null;
}
</code></pre>
<p>The issue however is, that in my pogo I store the value as a byte[] as can be seen below (as this is what is stored in the database - a blob):</p>
<pre><code>@Entity
@Table(name = "PersonalCard")
public class PersonalCard implements Card{
@Id @GeneratedValue
@Column(name = "id")
private int id;
@OneToOne
@JoinColumn(name="userid")
private int userid;
@Column(name = "homephonenumber")
protected String homeContactNumber;
@Column(name = "mobilephonenumber")
protected String mobileContactNumber;
@Column(name = "photo")
private byte[] optionalImage;
@Column(name = "address")
private String address;
</code></pre>
<p>Now of course, the conversion fails because it can't convert between a byte[] and a String.</p>
<p>Is the best approach here to change the constructor to accept a String instead of a byte array and then do the conversion myself whilst setting the byte array value or is there a better approach to doing this.</p>
<p>The error thrown is as follows;</p>
<blockquote>
<p>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_ARRAY but was STRING at line 1 column 96 path
$.optionalImage</p>
</blockquote>
<p>Thanks.</p>
<p><strong>Edit</strong> In fact even the approach I suggested will not work due to the way in which GSON generates the object.</p> | 25,523,772 | 5 | 7 | null | 2014-08-27 08:25:21.963 UTC | 4 | 2021-10-14 11:13:52.31 UTC | 2020-12-24 21:02:16.32 UTC | null | 4,442,606 | null | 287,732 | null | 1 | 14 | java|arrays|json|hibernate|gson | 43,460 | <p>You can use this <a href="https://gist.github.com/orip/3635246">adapter</a> to serialize and deserialize byte arrays in base64.
Here's the content.</p>
<pre><code> public static final Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class,
new ByteArrayToBase64TypeAdapter()).create();
// Using Android's base64 libraries. This can be replaced with any base64 library.
private static class ByteArrayToBase64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return Base64.decode(json.getAsString(), Base64.NO_WRAP);
}
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(Base64.encodeToString(src, Base64.NO_WRAP));
}
}
</code></pre>
<p>Credit to the author <a href="https://gist.github.com/orip">Ori Peleg</a>. </p> |
50,738,198 | How to use graaljs ? Is there a place where to get a .jar file/files? | <p>I use Java 8 and I use the default JavaScript Engine (Nashorn).</p>
<p>I would like to see how it compares with the 'highly hyped' GRAAL JS.
See: </p>
<ul>
<li><a href="https://github.com/graalvm/graaljs" rel="noreferrer">https://github.com/graalvm/graaljs</a></li>
<li><a href="https://www.graalvm.org/" rel="noreferrer">https://www.graalvm.org/</a></li>
</ul>
<p>particularly because I hear they want to deprecate nashorn:</p>
<ul>
<li><a href="http://openjdk.java.net/jeps/335" rel="noreferrer">http://openjdk.java.net/jeps/335</a></li>
</ul>
<p>Does anybody know how to get access (easily) to graaljs ?
I was hoping to find a pom.xml or a place where to download a jar file
but not luck</p> | 50,742,571 | 2 | 3 | null | 2018-06-07 09:50:09.313 UTC | 9 | 2022-05-05 07:58:07.4 UTC | null | null | null | null | 246,394 | null | 1 | 11 | java|nashorn|graalvm | 4,020 | <p>At the moment there are no pre-built jars of Graal.js available outside of GraalVM. To run it on an other JDK, you can extract the jars from GraalVM or build it like this:</p>
<pre><code>$ git clone [email protected]:graalvm/graaljs.git
$ git clone [email protected]:graalvm/mx.git
$ export PATH=$PWD/mx:$PATH
$ export JAVA_HOME=/usr/java/jdk1.8.0_161
$ cd graaljs/graal-js
$ mx build
</code></pre>
<p>Note that it built fine with JDK 8. It also runs on JDK 8:</p>
<pre><code>$ mx js
> typeof([] + 1)
string
>
</code></pre>
<p>The shell works, <kbd>Ctrl</kbd>+<kbd>D</kbd> exits it. The <code>-v</code> option in the previous command line shows how it launches it:</p>
<pre><code>$ mx -v js
...
env JAVA_HOME=/usr/java/jdk1.8.0_161 ... \
/usr/java/jdk1.8.0_161/bin/java -d64 -cp /tmp/graal-js/graal/sdk/mxbuild/dists/graal-sdk.jar:/tmp/graal-js/graal/truffle/mxbuild/dists/truffle-api.jar:/tmp/graal-js/graal/tools/mxbuild/dists/truffle-profiler.jar:/tmp/graal-js/graal/tools/mxbuild/dists/chromeinspector.jar:/tmp/graal-js/graal/sdk/mxbuild/dists/launcher-common.jar:/tmp/graal-js/graaljs/graal-js/mxbuild/dists/graaljs-launcher.jar:/tmp/graal-js/graal/regex/mxbuild/dists/tregex.jar:/home/gmdubosc/.mx/cache/ASM_DEBUG_ALL_702b8525fcf81454235e5e2fa2a35f15ffc0ec7e.jar:/home/gmdubosc/.mx/cache/ICU4J_6f06e820cf4c8968bbbaae66ae0b33f6a256b57f.jar:/tmp/graal-js/graaljs/graal-js/mxbuild/dists/graaljs.jar -Dtruffle.js.BindProgramResult=false -Xms2g -Xmx2g -Xss16m com.oracle.truffle.js.shell.JSLauncher
</code></pre>
<p>So it puts those jars on the classpath:</p>
<ul>
<li><code>/tmp/graal-js/graal/sdk/mxbuild/dists/graal-sdk.jar</code></li>
<li><code>/tmp/graal-js/graal/truffle/mxbuild/dists/truffle-api.jar</code></li>
<li><code>/tmp/graal-js/graal/tools/mxbuild/dists/truffle-profiler.jar</code></li>
<li><code>/tmp/graal-js/graal/tools/mxbuild/dists/chromeinspector.jar</code></li>
<li><code>/tmp/graal-js/graal/sdk/mxbuild/dists/launcher-common.jar</code></li>
<li><code>/tmp/graal-js/graaljs/graal-js/mxbuild/dists/graaljs-launcher.jar</code></li>
<li><code>/tmp/graal-js/graal/regex/mxbuild/dists/tregex.jar</code></li>
<li><code>/home/gmdubosc/.mx/cache/ASM_DEBUG_ALL_702b8525fcf81454235e5e2fa2a35f15ffc0ec7e.jar</code></li>
<li><code>/home/gmdubosc/.mx/cache/ICU4J_6f06e820cf4c8968bbbaae66ae0b33f6a256b57f.jar</code></li>
<li><code>/tmp/graal-js/graaljs/graal-js/mxbuild/dists/graaljs.jar</code></li>
</ul>
<p>Looking into the build artifacts we can also see <code>mxbuild/dists/graaljs-scriptengine.jar</code> which is responsible for registering Graal.js with the script engine API.</p>
<p>Using a small test file:</p>
<pre><code>import javax.script.*;
import java.util.Arrays;
public class Test {
public static void main(String... args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
for (ScriptEngineFactory factory : manager.getEngineFactories()) {
System.out.printf("%s %s: %s %s%n", factory.getLanguageName(), factory.getLanguageVersion(), factory.getEngineName(), factory.getNames());
}
ScriptEngine engine = manager.getEngineByName("Graal.js");
if (engine != null) {
Object result = engine.eval("typeof([] + 1)");
System.out.println(result);
}
}
}
</code></pre>
<p>Compiling and running it on a stock JDK 8 gives:</p>
<pre><code>$ javac Test.java
$ java -cp . Test
ECMAScript ECMA - 262 Edition 5.1: Oracle Nashorn [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript]
</code></pre>
<p>Now with Graal.js on the classpath:</p>
<pre><code>$ java -cp /tmp/graal-js/graal/sdk/mxbuild/dists/graal-sdk.jar:/tmp/graal-js/graal/truffle/mxbuild/dists/truffle-api.jar:/tmp/graal-js/graal/regex/mxbuild/dists/tregex.jar:/home/gmdubosc/.mx/cache/ASM_DEBUG_ALL_702b8525fcf81454235e5e2fa2a35f15ffc0ec7e.jar:/home/gmdubosc/.mx/cache/ICU4J_6f06e820cf4c8968bbbaae66ae0b33f6a256b57f.jar:/tmp/graal-js/graaljs/graal-js/mxbuild/dists/graaljs.jar:/tmp/graal-js/graaljs/graal-js/mxbuild/dists/graaljs-scriptengine.jar:. Test
ECMAScript ECMA - 262 Edition 6: Graal.js [Graal.js, graal.js, Graal-js, graal-js, Graal.JS, Graal-JS, GraalJS, GraalJSPolyglot, js, JS, JavaScript, javascript, ECMAScript, ecmascript]
ECMAScript ECMA - 262 Edition 5.1: Oracle Nashorn [nashorn, Nashorn, null, null, null, null, null, null]
string
</code></pre>
<p>(note that this command line ignores <code>truffle-profiler</code>, <code>chromeinspector</code>, <code>launcher-common</code> and <code>graaljs-launcher</code> which are not necessary when using Graal.js through the script engine.)</p>
<p>Since the standard JDK 8 doesn't support JVMCI and/or the Graal compiler, there will be no JIT compilations for JS so don't expect much in terms of performance. To get performance you need a special JDK 8 or JDK 9+ as well as the Graal-Truffle bindings.</p> |
9,651,842 | will main thread exit before child threads complete execution? | <p>will main thread exit before child threads complete execution?</p>
<p>i read in 2 articles </p>
<p><a href="http://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-management.html" rel="noreferrer">http://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-management.html</a></p>
<p>in the above article, In "Thread Termination" para, it states in Red " if the parent thread terminates, all of its child threads terminate as well."</p>
<p><a href="http://www.roseindia.net/java/thread/overview-of-thread.shtml" rel="noreferrer">http://www.roseindia.net/java/thread/overview-of-thread.shtml</a></p>
<p>in the above article, the last line in that page states "The main() method execution can finish, but the program will keep running until the all threads have complete its execution.". </p>
<p>i fee they are contradictory. if i am wrong, Please experts correct me. </p>
<p>In my program, a program with Main method calls the constructor of 2 threads . in the constructor of the respective threads, i am having the start() method . </p>
<pre><code> TestA A = new TestA("TestA");
TestB B = new TestB("TestB");
public TestA(String name) {
System.out.println(name);
t = new Thread(this);
t.start();
}
</code></pre>
<p>i would like to know what happens, main thread terminates before child threads complete execution? if so, will the child threads anyway, continue their execution??</p>
<p>i tried running the program, some times all the child threads are getting executed complete even if the main thread exits.
In the 2 threads , i am processing some files. in testA thread A alone, 1 file alone is not getting processed some times. but many times, all the files are getting processed and i do not have any issues. </p> | 9,651,919 | 3 | 1 | null | 2012-03-11 02:15:26.353 UTC | 8 | 2021-03-03 21:48:32.843 UTC | null | null | null | null | 1,257,836 | null | 1 | 21 | java | 42,468 | <p>Java makes a distinction between a user thread and another type of thread known as a daemon thread. The difference between these two types of threads is that if the JVM determines that the only threads running in an application are daemon threads (i.e., there are no user threads), the Java runtime closes down the application. On the other hand, if at least one user thread is alive, the Java runtime won't terminate your application.</p>
<p>When your <code>main()</code> method initially receives control from the Java runtime, it executes in the context of a user thread. As long as the main-method thread or any other user thread remains alive, your application will continue to execute.</p>
<p>In your case, the threads are user threads and hence are allowed to complete before the main thread exits.</p>
<blockquote>
<p>i am processing some files. in <code>testA</code> thread A alone, 1 file alone is
not getting processed some times. but many times</p>
</blockquote>
<p>The reason for the above is could be something else than thread exits. It could be file locks, synchronization issue etc.</p>
<p><a href="https://docs.oracle.com/javase/10/docs/api/java/lang/Thread.html" rel="nofollow noreferrer">Thread (Java SE 10 & JDK 10)</a>:</p>
<blockquote>
<p>When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named <code>main</code> of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:</p>
<ul>
<li>The <code>exit</code> method of class <code>Runtime</code> has been called and the security manager has permitted the exit operation to take place.</li>
<li>All threads that are not daemon threads have died, either by returning from the call to the <code>run</code> method or by throwing an exception that propagates beyond the <code>run</code> method.</li>
</ul>
</blockquote> |
10,202,987 | In C# how to collect stack trace of program crash | <p>I am new to C#. I am writing a small desktop form based application and I need to have this feature in the app.</p>
<p>If the application crashes at any time, there should be a last opportunity for the app to collect stack trace and send it back to me...</p>
<p>Please give me directions on this.</p>
<p>Do I need a try catch covering the main the entry point of my app ?? or what is the best way to handle such things in a C# app.</p>
<p>thank you, </p> | 10,203,030 | 4 | 1 | null | 2012-04-18 04:52:56.19 UTC | 9 | 2012-04-18 05:49:41.087 UTC | 2012-04-18 05:32:16.977 UTC | null | 795,861 | null | 1,185,422 | null | 1 | 22 | c#|.net|winforms|error-handling | 15,287 | <p>To catch all unhandled exceptions, Add this to program.cs:</p>
<pre><code> [STAThread]
static void Main()
{
AppDomain currentDomain = default(AppDomain);
currentDomain = AppDomain.CurrentDomain;
// Handler for unhandled exceptions.
currentDomain.UnhandledException += GlobalUnhandledExceptionHandler;
// Handler for exceptions in threads behind forms.
System.Windows.Forms.Application.ThreadException += GlobalThreadExceptionHandler;
...
}
private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = default(Exception);
ex = (Exception)e.ExceptionObject;
ILog log = LogManager.GetLogger(typeof(Program));
log.Error(ex.Message + "\n" + ex.StackTrace);
}
private static void GlobalThreadExceptionHandler(object sender, System.Threading.ThreadExceptionEventArgs e)
{
Exception ex = default(Exception);
ex = e.Exception;
ILog log = LogManager.GetLogger(typeof(Program)); //Log4NET
log.Error(ex.Message + "\n" + ex.StackTrace);
}
</code></pre>
<p>Stack trace you can get by <strong>exception.StackTrace</strong></p> |
10,084,400 | How to count the number of columns in a table using SQL? | <p>How to count the number of columns in a table using SQL?</p>
<p>I am using Oracle 11g</p>
<p>Please help.
t.</p> | 10,084,424 | 3 | 1 | null | 2012-04-10 06:58:12.01 UTC | 9 | 2018-10-24 05:36:43.23 UTC | null | null | null | null | 612,925 | null | 1 | 24 | sql|oracle | 129,935 | <pre><code>select count(*)
from user_tab_columns
where table_name='MYTABLE' --use upper case
</code></pre>
<p>Instead of uppercase you can use lower function.
Ex:
select count(*) from user_tab_columns where lower(table_name)='table_name';</p> |
10,128,530 | Set Text property of asp:label in Javascript PROPER way | <p>I have a series of textboxes on a form. When the user inserts numbers into these textboxes, calculations are made and <code><asp:Label></code> controls are updated via JavaScript to reflect these calculations:</p>
<pre><code>document.getElementById('<%=TotalLoans.ClientID %>').innerHTML = TotalLoans;
</code></pre>
<p>This correctly updates the UI. However, when I try to access the value in the codebehind, the <code>Text</code> property is empty. This makes sense I guess, since I was updating the <code>innerHTML</code> property via the JavaScript.</p>
<pre><code>//TotalLoans.Text will always be equal to "" in this scenario
double bTotalLoans = string.IsNullOrEmpty(TotalLoans.Text)
? 0.00
: Convert.ToDouble(TotalLoans.Text);
</code></pre>
<p>How do I update the <code>Text</code> property of the <code><asp:Label></code> via JavaScript in such a way that I can read the property in the codebehind?</p>
<h3>Update</h3>
<p>This is a small problem on a large form that contains 41 labels, each of which displays the results of some calculation for the user. Taking the advice of FishBasketGordo I converted my <code><asp:Label></code> to a disabled <code><asp:TextBox></code>. I'm setting the value of the new textbox as such:</p>
<pre><code> document.getElementById('<%=TotalLoans.ClientID %>').value = TotalLoans;
</code></pre>
<p>Again, in the codebehind, the value of <code>TotalLoans.Text</code> is always equal to "".</p>
<p><br/>
I don't mind changing how I approach this, but here's the crux of the matter.</p>
<p>I am using JavaScript to manipulate the property values of some controls. I need to be able to access these manipulated values from the code behind when 'Submit' is clicked. </p>
<p>Any advice how I can go about this?</p>
<h3>Update 2</h3>
<p>Regarding the answer by @James Johnson, I am not able to retrieve the value using <code>.innerText</code> property as suggested. I have <code>EnableViewState</code> set to true on the <code><asp:Label></code>. Is there something else I am missing?</p>
<p>I don't understand why, when I type in a textbox and submit the form, I can access the value in the codebehind, but when I programmatically change the text of a textbox or label by way of JavaScript, I cannot access the new value.</p> | 10,129,027 | 7 | 5 | null | 2012-04-12 17:17:48.357 UTC | 2 | 2016-02-18 14:37:33.49 UTC | 2016-02-18 14:37:33.49 UTC | null | 4,642,212 | null | 81,235 | null | 1 | 24 | javascript|asp.net|label|code-behind | 127,644 | <h2>Place HiddenField Control in your Form.</h2>
<pre><code><asp:HiddenField ID="hidden" runat="server" />
</code></pre>
<h2>Create a Property in the Form</h2>
<pre><code>protected String LabelProperty
{
get
{
return hidden.Value;
}
set
{
hidden.Value = value;
}
}
</code></pre>
<h2>Update the Hidden Field value from JavaScript</h2>
<pre><code><script>
function UpdateControl() {
document.getElementById('<%=hidden.ClientID %>').value = '12';
}
</script>
</code></pre>
<p>Now you can access the Property directly across the <code>Postback</code>. The <code>Label</code> Control updated value will be Lost across <code>PostBack</code> in case it is being used directly in code behind .</p> |
9,988,211 | List<Object> and List<?> | <p>I have two questions, actaully...
First off, Why cant I do this:</p>
<pre><code>List<Object> object = new List<Object>();
</code></pre>
<p>And second, I have a method that returns a <code>List<?></code>, how would I turn that into a <code>List<Object></code>, would I be able to simply cast it? </p>
<p>Thank you!</p> | 9,988,236 | 5 | 2 | null | 2012-04-03 06:32:35.723 UTC | 8 | 2019-08-06 10:56:07.807 UTC | 2015-01-16 22:07:36.83 UTC | null | 945,456 | null | 822,606 | null | 1 | 28 | java|list|object|arraylist | 227,818 | <blockquote>
<p>Why cant I do this:</p>
<pre><code>List<Object> object = new List<Object>();
</code></pre>
</blockquote>
<p>You can't do this because <a href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html" rel="noreferrer"><code>List</code></a> is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing <code>List</code> include <a href="http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html" rel="noreferrer"><code>ArrayList</code></a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html" rel="noreferrer"><code>LinkedList</code></a> etc.</p>
<p>Here is how one would create an instance of <code>ArrayList</code>:</p>
<pre><code>List<Object> object = new ArrayList<Object>();
</code></pre>
<blockquote>
<p>I have a method that returns a <code>List<?></code>, how would I turn that into a <code>List<Object></code></p>
</blockquote>
<p>Show us the relevant code and I'll update the answer.</p> |
9,774,504 | Does C++11 offer a better way to concatenate strings on the fly? | <p>I've seen <a href="https://stackoverflow.com/a/900035/207655">this</a> answer, and I wonder (I hope) if C++11 has come up with a native better method to concatenate, and possibly format, strings.</p>
<p>With "better" I mean actually <em>really</em> one-line, like in pretty much all higher level languages (bonus points if it supports something like python's "formatted string"%(tuple) syntax but I guess that's really hoping for too much).</p>
<p>The ideal result should be something like:</p>
<pre><code>my_func("bla bla bla" << int(my_int) << "bla bla bla");
</code></pre>
<p>The only barely acceptable methods listed in that answer are the fastformat ones, but I wonder if C++11 managed to do better.</p> | 9,775,703 | 1 | 1 | null | 2012-03-19 17:03:34.837 UTC | 6 | 2012-03-19 19:26:30.5 UTC | 2017-05-23 12:32:14.49 UTC | null | -1 | null | 207,655 | null | 1 | 31 | c++|string|c++11|concatenation|string-formatting | 13,958 | <p>C++11 introduces <code>to_string()</code> functions:</p>
<pre><code>my_func("bla bla bla" + to_string(my_int) + "bla bla bla");
</code></pre> |
10,204,021 | How do I test 'normal' (non-Node specific) JavaScript functions with Mocha? | <p>This seems like it <em>should</em> be extremely simple; however, after two hours of reading and trial-and-error without success, I'm admitting defeat and asking you guys! </p>
<p>I'm trying to use <a href="http://visionmedia.github.com/mocha/" rel="noreferrer">Mocha</a> with <a href="https://github.com/visionmedia/should.js" rel="noreferrer">Should.js</a> to test some JavaScript functions, but I'm running into scoping issues. I've simplified it down to the most basic of test cases, but I cannot get it working. </p>
<p>I have a file named <code>functions.js</code>, which just contains the following:</p>
<pre><code>function testFunction() {
return 1;
}
</code></pre>
<p>And my <code>tests.js</code> (located in the same folder) contents:</p>
<pre><code>require('./functions.js')
describe('tests', function(){
describe('testFunction', function(){
it('should return 1', function(){
testFunction().should.equal(1);
})
})
})
</code></pre>
<p>This test fails with a <code>ReferenceError: testFunction is not defined</code>.</p>
<p>I can see why, because most of the examples I've found either attach objects and functions to the Node <code>global</code> object or export them using <code>module.exports</code>—but using either of these approaches means my function code would throw errors in a standard browser situation, where those objects don't exist.</p>
<p>So how can I access standalone functions which are declared in a separate script file from my tests, without using Node-specific syntax?</p> | 10,204,349 | 3 | 2 | null | 2012-04-18 06:30:58.317 UTC | 15 | 2016-05-15 05:54:26.597 UTC | 2016-05-15 05:54:26.597 UTC | null | 43,140 | null | 43,140 | null | 1 | 48 | javascript|unit-testing|node.js|mocha.js | 12,235 | <pre><code>require('./functions.js')
</code></pre>
<p>That doesn't do anything since you're not exporting anything. What you're expecting is that <code>testFunction</code> is globally available, essentially the same as </p>
<pre><code>global.testFunction = function() {
return 1;
}
</code></pre>
<p>You just <em>can't</em> bypass the export/globals mechanism. It's the way node has been designed. There is no implicit global shared context (like <code>window</code> on a browser). Every "global" variable in a module is trapped in it's context.</p>
<p>You should use <code>module.exports</code>. If you intend to share that file with a browser environments, there are ways to make it compatible. For a quick hack just do <code>window.module = {}; jQuery.extend(window, module.exports)</code> in the browser, or <code>if (typeof exports !== 'undefined'){ exports.testFunction = testFunction }</code> for node.</p> |
12,023,564 | Spring Security: Ignore login page by using a special URL parameter | <p>I currently have a setup that looks something like this:</p>
<p><b>spring-security.xml:</b></p>
<pre><code><http auto-config="true">
<intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login login-page="/login"
default-target-url="/main.html"
authentication-failure-url="/failedLogin"/>
<logout logout-url="/logout.html" logout-success-url="/login" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="foo" password="bar" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</code></pre>
<p><b>web.xml:</b></p>
<pre><code><filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</code></pre>
<p>This all seems to work as expected, however, in special situations I want the login page to be bypassed if the user passes in a special token. So currently, if the user goes to a url such as <code>/dog</code>, they will see the login page and if they pass in the credentials of <code>foo/bar</code> then they will be logged in and see the page corresponding to <code>/dog</code>. </p>
<p>I want the ability to use a URL such as <code>/dog?token=abcd</code> which will bypass the login screen and take them directly to the page corresponding to <code>/dog</code>. If they provide an invalid token then they would just see an access denied page.</p> | 12,026,557 | 1 | 2 | null | 2012-08-19 01:33:34.837 UTC | 9 | 2012-09-18 17:20:04.33 UTC | null | null | null | null | 30,563 | null | 1 | 6 | java|spring|spring-security | 10,876 | <p>In Spring Security the scenario you want to cover is described <a href="http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#preauth" rel="noreferrer">in reference manual, chapter <em>Pre-Authentication Scenarios</em></a>.</p>
<p>Basically you have to:</p>
<ul>
<li>create custom filter by extending <a href="http://static.springsource.org/spring-security/site/docs/3.1.x/apidocs/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilter.html" rel="noreferrer"><code>AbstractPreAuthenticatedProcessingFilter</code></a> or choosing one of its implementations,</li>
<li>register custom filter <code><custom-filter position="PRE_AUTH_FILTER" ref="yourPreAuthFilter" /></code>, </li>
<li>implement or choose one of implemented <a href="http://static.springsource.org/spring-security/site/docs/3.1.x/apidocs/org/springframework/security/core/userdetails/AuthenticationUserDetailsService.html" rel="noreferrer"><code>AuthenticationUserDetailsService</code></a>s,</li>
<li>register the service in <code>PreAuthenticatedAuthenticationProvider</code> (with <code><property name="yourPreAuthenticatedUserDetailsService"></code>).</li>
</ul>
<p><strong>EDIT</strong>: In <a href="https://stackoverflow.com/a/9919988/708434">this answer</a> OP shows his way of implementig custom <code>PRE_AUTH_FILTER</code>.</p> |
11,695,375 | Tornado: Identify / track connections of websockets? | <p>I have a basic Tornado websocket test:</p>
<pre><code>import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'new connection'
self.write_message("Hello World")
def on_message(self, message):
print 'message received %s' % message
def on_close(self):
print 'connection closed'
application = tornado.web.Application([
(r'/ws', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
</code></pre>
<p>I want to be able to handle multiple connections (which it seems to do already) but also to be able to reference other connections. I don't see a way to identify and keep track of individual connections, just to be able to handle events on connection open, receipt of messages, and connection close. </p>
<p>[Edit]<br>
Thought of creating a dict where the key is the Sec-websocket-key and and the value is the WSHandler object... thoughts? I'm not sure how dependable Sec-websocket-key is to be unique. </p> | 11,697,191 | 4 | 1 | null | 2012-07-27 20:41:55.82 UTC | 12 | 2015-10-28 19:20:42.807 UTC | 2012-07-27 21:10:26.017 UTC | null | 1,025,963 | null | 1,025,963 | null | 1 | 18 | python|websocket|tornado | 16,197 | <p>The simplest method is just to keep a list or dict of WSHandler instances:</p>
<pre><code>class WSHandler(tornado.websocket.WebSocketHandler):
clients = []
def open(self):
self.clients.append(self)
print 'new connection'
self.write_message("Hello World")
def on_message(self, message):
print 'message received %s' % message
def on_close(self):
self.clients.remove(self)
print 'closed connection'
</code></pre>
<p>If you want to identify connections, e.g. by user, you'll probably have to send that information over the socket.</p> |
11,853,551 | Python Multiple users append to the same file at the same time | <p>I'm working on a python script that will be accessed via the web, so there will be multiple users trying to append to the same file at the same time. My worry is that this might cause a race condition where if multiple users wrote to the same file at the same time and it just might corrupt the file.</p>
<p>For example:</p>
<pre><code>#!/usr/bin/env python
g = open("/somepath/somefile.txt", "a")
new_entry = "foobar"
g.write(new_entry)
g.close
</code></pre>
<p>Will I have to use a lockfile for this as this operation looks risky.</p> | 11,853,621 | 4 | 3 | null | 2012-08-07 20:23:47.123 UTC | 14 | 2022-03-19 11:31:52.92 UTC | 2018-04-28 20:49:08.43 UTC | null | 2,838,606 | null | 632,890 | null | 1 | 39 | python|concurrency|text-files|simultaneous|simultaneous-calls | 28,820 | <p>You can use <a href="http://docs.python.org/library/fcntl.html#fcntl.flock" rel="noreferrer">file locking</a>:</p>
<pre><code>import fcntl
new_entry = "foobar"
with open("/somepath/somefile.txt", "a") as g:
fcntl.flock(g, fcntl.LOCK_EX)
g.write(new_entry)
fcntl.flock(g, fcntl.LOCK_UN)
</code></pre>
<p>Note that on some systems, locking is <strong>not</strong> needed if you're only writing small buffers, because <a href="https://stackoverflow.com/questions/1154446/is-file-append-atomic-in-unix">appends on these systems are atomic</a>.</p> |
11,690,504 | How to use View.OnTouchListener instead of onClick | <p>I'm developing an Android 2.2.2 application for a client and he wants to do the following:</p>
<p>Now I have a button with an onClick event but he doesn't like, he wants to dectect when user release the button.</p>
<p>I've found <a href="http://developer.android.com/reference/android/view/View.OnTouchListener.html">View.OnTouchListener</a> which I think this is what I need to use but, is there any posibility to add this event to xml like I did with onClick?</p>
<pre><code><ImageButton
android:id="@+id/btnSaveNewGate"
android:layout_width="@dimen/btnSaveNewGate_width"
android:layout_height="@dimen/btnSaveNewGate_height"
android:layout_below="@+id/radioGrGateType"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/btnSaveNewGate_marginTop"
android:background="@null"
android:contentDescription="@string/layout_empty"
android:onClick="onSaveNewGateClick"
android:scaleType="fitXY"
android:src="@drawable/save_gate_selector" />
</code></pre>
<p>I have two questions more:</p>
<p>Which is the event associated when user releases his finger?</p>
<p>Is there any guidelines which prohibit using <code>View.OnTouchListener</code> instead of <code>onClick</code>?</p> | 11,690,679 | 4 | 0 | null | 2012-07-27 15:02:54.17 UTC | 21 | 2019-10-01 15:12:47.063 UTC | null | null | null | null | 68,571 | null | 1 | 51 | android|android-layout|user-input | 165,239 | <p>The event when user releases his finger is <code>MotionEvent.ACTION_UP</code>. I'm not aware if there are any guidelines which prohibit using View.OnTouchListener instead of onClick(), most probably it depends of situation.</p>
<p>Here's a sample code:</p>
<pre><code>imageButton.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
// Do what you want
return true;
}
return false;
}
});
</code></pre> |
3,776,117 | What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim? | <p>What is the difference between the <code>remap</code>, <code>noremap</code>, <code>nnoremap</code> and <code>vnoremap</code> mapping commands in Vim?</p> | 3,776,182 | 4 | 1 | null | 2010-09-23 07:13:30.917 UTC | 576 | 2022-02-20 17:55:58.503 UTC | 2020-04-16 08:04:32.067 UTC | null | 806,202 | null | 238,030 | null | 1 | 1,338 | vim|mapping|command | 279,358 | <p><code>remap</code> is an <strong>option</strong> that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are <strong>mapping commands</strong>, described below:</p>
<p><code>:map</code> and <code>:noremap</code> are <strong>recursive</strong> and <strong>non-recursive</strong> versions of the various mapping commands. For example, if we run:</p>
<pre><code>:map j gg (moves cursor to first line)
:map Q j (moves cursor to first line)
:noremap W j (moves cursor down one line)
</code></pre>
<p>Then:</p>
<ul>
<li><code>j</code> will be mapped to <code>gg</code>.</li>
<li><code>Q</code> will <em>also</em> be mapped to <code>gg</code>, because <code>j</code> will be expanded for the recursive mapping.</li>
<li><code>W</code> will be mapped to <code>j</code> (and not to <code>gg</code>) because <code>j</code> will not be expanded for the non-recursive mapping.</li>
</ul>
<p>Now remember that Vim is a <strong>modal editor</strong>. It has a <strong>normal</strong> mode, <strong>visual</strong> mode and other modes.</p>
<p>For each of these sets of mappings, there is a <a href="http://vim.wikia.com/wiki/Mapping_keys_in_Vim_-_Tutorial_%28Part_1%29#Creating_keymaps" rel="noreferrer">mapping</a> that works in normal, visual, select and operator modes (<code>:map</code> and <code>:noremap</code>), one that works in normal mode (<code>:nmap</code> and <code>:nnoremap</code>), one in visual mode (<code>:vmap</code> and <code>:vnoremap</code>) and so on.</p>
<p>For more guidance on this, see:</p>
<pre><code>:help :map
:help :noremap
:help recursive_mapping
:help :map-modes
</code></pre> |
3,815,411 | Stored Procedure and Permissions - Is EXECUTE enough? | <p>I have a SQL Server 2008 database where all access to the underlying tables is done through stored procedures. Some stored procedures simply SELECT records from the tables while others UPDATE, INSERT, and DELETE. </p>
<p>If a stored procedure UPDATES a table does the user executing the stored procedure also need UPDATE permissions to the affected tables or is the fact that they have EXECUTE permissions to the stored procedure enough? </p>
<p>Basically I am wondering if giving the user EXECUTE permissions to the stored procedures is enough or do I need to give them SELECT, UPDATE, DELETE, and INSERT permissions to the tables in order for the stored procedures to work. Thank you.</p>
<p><strong>[EDIT]</strong> In most of my stored procedures it does indeed appear that EXECUTE is enough. However, I did find that in stored procedures where "Execute sp_Executesql" was used that EXECUTE was not enough. The tables involved needed to have permissions for the actions being performed within "sp_Executesql".</p> | 3,815,444 | 5 | 3 | null | 2010-09-28 17:26:51.317 UTC | 4 | 2018-06-06 18:03:44.09 UTC | 2014-07-08 11:19:33.173 UTC | null | 3,302,887 | null | 287,793 | null | 1 | 43 | sql-server|stored-procedures|permissions | 83,562 | <p>Execute permissions on the stored procedure is sufficient.</p>
<pre><code>CREATE TABLE dbo.Temp(n int)
GO
DENY INSERT ON dbo.Temp TO <your role>
GO
CREATE PROCEDURE dbo.SPTemp(@Int int)
AS
INSERT dbo.Temp
SELECT @Int
GO
GRANT EXEC ON dbo.SPTemp TO <your role>
GO
</code></pre>
<p>Then the (non-db_owner) user will have the following rights:</p>
<pre><code>EXEC dbo.SPTemp 10
GO
INSERT dbo.Temp --INSERT permission was denied on the object 'Temp'
SELECT 10
</code></pre>
<p>However, if there is dynamic SQL inside dbo.SPTemp that attempts to insert into dbo.Temp then that will fail. In this case direct permission on the table will need to be granted.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.