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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
14,992,521 | Python Weighted Random | <p>I need to return different values based on a weighted round-robin such that 1 in 20 gets A, 1 in 20 gets B, and the rest go to C.</p>
<p>So:</p>
<pre><code>A => 5%
B => 5%
C => 90%
</code></pre>
<p>Here's a basic version that appears to work:</p>
<pre><code>import random
x = random.randint(1, 100)
if x <= 5:
return 'A'
elif x > 5 and x <= 10:
return 'B'
else:
return 'C'
</code></pre>
<p>Is this algorithm correct? If so, can it be improved?</p> | 14,992,686 | 4 | 7 | null | 2013-02-21 00:26:34.983 UTC | 10 | 2013-02-21 03:43:29.923 UTC | null | null | null | null | 361,833 | null | 1 | 31 | python|algorithm|round-robin | 62,240 | <p>Your algorithm is correct, how about something more elegant:</p>
<pre><code>import random
my_list = ['A'] * 5 + ['B'] * 5 + ['C'] * 90
random.choice(my_list)
</code></pre> |
15,249,678 | Close Bootstrap modal from inside iframe | <p>Page which opens Twitter Bootstrap Modal with iframe inside:</p>
<pre><code><div id="iframeModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="btn btn-danger pull-right" data-dismiss="modal" aria-hidden="true">Close</button>
<div class="clearfix"></div>
</div>
<div class="modal-body">
<iframe src="iframe-modal.html"></iframe>
</div>
<div class="modal-footer">
</div>
</div>
</code></pre>
<p>And I am looking for a way to close this modal from inside the iframe.
Ex. clicking a link inside the <code>iframe-modal.html</code> to close the modal.
What I have tried, but non successful:</p>
<pre><code>$('#iframeModal', window.parent.document).modal('hide');
$('#iframeModal', top.document).modal('hide');
$('#iframeModal').modal('hide');
</code></pre> | 15,251,235 | 4 | 0 | null | 2013-03-06 14:17:18.35 UTC | 8 | 2019-03-08 10:20:21.183 UTC | 2019-03-08 10:20:21.183 UTC | null | 3,917,754 | null | 1,192,836 | null | 1 | 35 | javascript|jquery|twitter-bootstrap|parent-child | 41,572 | <p>You can always create a globally accessible function which closes the Bootstrap modal window.</p>
<p>eg.</p>
<pre><code>window.closeModal = function(){
$('#iframeModal').modal('hide');
};
</code></pre>
<p>Then from the iframe, call it using:</p>
<pre><code>window.parent.closeModal();
</code></pre> |
14,951,356 | Django : Testing if the page has redirected to the desired url | <p>In my django app, I have an authentication system. So, If I do not log in and try to access some profile's personal info, I get redirected to a login page. </p>
<p>Now, I need to write a test case for this. The responses from the browsers I get is : </p>
<pre><code>GET /myprofile/data/some_id/ HTTP/1.1 302 0
GET /account/login?next=/myprofile/data/some_id/ HTTP/1.1 301 0
GET /account/login?next=/myprofile/data/some_id/ HTTP/1.1 200 6533
</code></pre>
<p>How do I write my test ? This what I have so far:</p>
<pre><code>self.client.login(user="user", password="passwd")
response = self.client.get('/myprofile/data/some_id/')
self.assertEqual(response.status,200)
self.client.logout()
response = self.client.get('/myprofile/data/some_id/')
</code></pre>
<p>What could possibly come next ?</p> | 14,954,000 | 5 | 0 | null | 2013-02-19 06:41:54.737 UTC | 3 | 2021-01-11 07:24:34.22 UTC | 2020-05-22 08:31:48.46 UTC | null | 3,848,833 | null | 1,222,542 | null | 1 | 77 | python|django|django-testing | 52,613 | <p>Django 1.4:</p>
<p><a href="https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.TestCase.assertRedirects" rel="noreferrer">https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.TestCase.assertRedirects</a></p>
<p>Django 2.0:</p>
<p><a href="https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.SimpleTestCase.assertRedirects" rel="noreferrer">https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.SimpleTestCase.assertRedirects</a></p>
<blockquote>
<p><code>SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True)</code></p>
<p>Asserts that the response returned a <strong>status_code</strong> redirect status, redirected to <strong>expected_url</strong> (including any <strong>GET</strong> data), and that the final page was received with <strong>target_status_code</strong>.</p>
<p>If your request used the <strong>follow</strong> argument, the <strong>expected_url</strong> and <strong>target_status_code</strong> will be the url and status code for the final point of the redirect chain.</p>
<p>If <strong>fetch_redirect_response</strong> is <strong>False</strong>, the final page won’t be loaded. Since the test client can’t fetch external URLs, this is particularly useful if <strong>expected_url</strong> isn’t part of your Django app.</p>
<p>Scheme is handled correctly when making comparisons between two URLs. If there isn’t any scheme specified in the location where we are redirected to, the original request’s scheme is used. If present, the scheme in <strong>expected_url</strong> is the one used to make the comparisons to.</p>
</blockquote> |
38,209,656 | Get Angular2 routing working on IIS 7.5 | <p>I have been learning Angular2. The routing works just fine when running on the nodejs lite-server. I can go to the main (localhost:3000) page and move through the application. I can also type localhost:3000/employee and it will go to the requested page. </p>
<p>The app will eventually live on an Windows IIS 7.5 server. The routing works fine if I start at the main page (localhost:2500), I am able to move through application with out any problems. Where I run into a problem is when trying to go directly to an page other then the main landing page (localhost:2500/employee). I get a HTTP Error 404.0.</p>
<p>Here is my app.component file that handles the routing.</p>
<pre class="lang-js prettyprint-override"><code>import { Component } from '@angular/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { HTTP_PROVIDERS } from '@angular/http';
import { UserService } from './services/users/user.service';
import { LogonComponent } from './components/logon/logon.component';
import { EmployeeComponent } from './components/employee/employee.component';
@Component({
selector : 'opi-app',
templateUrl : 'app/app.component.html',
directives: [ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS, UserService, HTTP_PROVIDERS]
})
@RouteConfig([
{
path: '/',
name: 'Logon',
component: LogonComponent,
useAsDefault: true
},
{
path: '/employee',
name: 'Employee',
component: EmployeeComponent
}
])
export class AppComponent { }
</code></pre>
<p>I would like to say I understand the issue. IIS is looking for a direcotry of /employee but it does not exist. I just do not know how to make IIS aware of the routing. </p> | 44,600,609 | 6 | 4 | null | 2016-07-05 17:51:31.683 UTC | 8 | 2019-10-18 04:14:32.55 UTC | null | null | null | null | 1,108,913 | null | 1 | 32 | html|angular|iis-7.5 | 29,471 | <p>(For angular 2, angular 4)</p>
<p>Create a web.config file as in mentioned article.</p>
<pre><code><configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
</code></pre>
<p>Place it in the root directory (same as index.html) of your site. Mine is in the dist folder (angular-cli project).</p>
<p>After deploying, go to IIS if you have the access and you can click on the rewrite-rules icon and see that it read this config. If you do not see and icon for rewrite rules, you will need to enable the module under "modules" icon. This code snippet was not written by be but I wanted to share better implementation details.</p> |
38,081,150 | Failed to load resource 404 (Not Found) - file location error? | <p>I'm building an Angular 2 app which I just upgraded to Net Core RC2. Prior to the upgrade, my webpage would display just fine, but now I am getting errors in my Chrome Dev Tools console:</p>
<pre><code> Failed to load resource: the server responded with a status of 404 (Not Found):
http://localhost:5000/lib/bootstrap/dist/js/bootstrap.min.js
Failed to load resource: the server responded with a status of 404 (Not Found):
http://localhost:5000/lib/bootstrap/dist/css/bootstrap/bootstrap.min.css
</code></pre>
<p>I have bootstrap in my package.json file with version 3.3.6. I installed it with an <strong>npm install</strong> command. It installed properly in my Visual Studio project. The files are located at: </p>
<p><strong>project -> node_modules -> bootstrap -> dist -> js -> boostrap.min.js</strong> </p>
<p>and</p>
<p><strong>project -> node_modules -> bootstrap -> dist -> css -> boostrap.min.css</strong></p>
<p>My gulpfile has this section:</p>
<pre><code>var config = {
libBase: 'node_modules',
lib: [
require.resolve('bootstrap/dist/css/bootstrap.min.css'),
require.resolve('bootstrap/dist/js/bootstrap.min.js'),
path.dirname(require.resolve('bootstrap/dist/fonts/glyphicons-halflings-regular.woff')) + '/**',
require.resolve('jquery/dist/jquery.min.js'),
require.resolve('chart.js/dist/Chart.bundle.min.js')
]
</code></pre>
<p>};</p>
<p>I'm also seeing a reference to bootstrap.min.js in a _Layout.cshtml file:</p>
<pre><code><!doctype html>
<html lang="">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Homepage WebDev</title>
<base href="/" />
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</head>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="~/lib/chart.js/dist/Chart.bundle.min.js"></script>
</body>
</html>
</code></pre>
<p>I'm new to web development so I'm not completely sure what's happening. Could someone point me in the right direction? </p> | 38,081,452 | 1 | 6 | null | 2016-06-28 16:05:15.867 UTC | 3 | 2017-10-21 08:57:17.07 UTC | null | null | null | null | 5,874,702 | null | 1 | 2 | javascript|angularjs|node.js|twitter-bootstrap|angular | 127,271 | <p>Looks like the path you gave doesn't have any bootstrap files in them. </p>
<pre><code>href="~/lib/bootstrap/dist/css/bootstrap.min.css"
</code></pre>
<p>Make sure the files exist over there , else point the files to the correct path, which should be in your case </p>
<pre><code>href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
</code></pre> |
28,213,693 | Enum with localized string in swift | <p>I want to use enumeration with localized string, so I do like this, it works, but
the problem of this solution is : I can't get easily enum value from localized string, I must have the key to do it : </p>
<pre><code>let option = DietWithoutResidueOption(rawValue: "NoDiet")
</code></pre>
<p>If not I must to call dietWithoutResidueOptionWith method to get enum value... :/</p>
<p>There are a better solution to store directly localizedString and not keys in enum ?</p>
<p>Thanks </p>
<p><strong>Enumeration</strong> </p>
<pre><code> enum DietWithoutResidueOption: String {
case NoDiet = "NoDiet"
case ThreeDays = "ThreeDays"
case FiveDays = "FiveDays"
private func localizedString() -> String {
return NSLocalizedString(self.rawValue, comment: "")
}
static func dietWithoutResidueOptionWith(#localizedString: String) -> DietWithoutResidueOption {
switch localizedString {
case DietWithoutResidueOption.ThreeDays.localizedString():
return DietWithoutResidueOption.ThreeDays
case DietWithoutResidueOption.FiveDays.localizedString():
return DietWithoutResidueOption.FiveDays
default:
return DietWithoutResidueOption.NoDiet
}
}
}
</code></pre>
<p><strong>Localizable.strings</strong></p>
<pre><code>"NoDiet" = "NON, JE N'AI PAS DE RÉGIME";
"ThreeDays" = "OUI, SUR 3 JOURS";
"FiveDays" = "OUI, SUR 5 JOURS";
</code></pre>
<p><strong>call</strong></p>
<pre><code>println(DietWithoutResidueOption.FiveDays.localizedString())
</code></pre> | 28,213,905 | 7 | 2 | null | 2015-01-29 11:32:18.013 UTC | 9 | 2020-06-10 08:52:33.063 UTC | null | null | null | null | 2,477,632 | null | 1 | 22 | ios|swift|enums|localization | 16,013 | <p>You can use any <code>StringLiteralConvertible, Equatable</code> type for <code>RawValue</code> type of <code>enum</code>.</p>
<p>So, how about:</p>
<pre><code>import Foundation
struct LocalizedString: StringLiteralConvertible, Equatable {
let v: String
init(key: String) {
self.v = NSLocalizedString(key, comment: "")
}
init(localized: String) {
self.v = localized
}
init(stringLiteral value:String) {
self.init(key: value)
}
init(extendedGraphemeClusterLiteral value: String) {
self.init(key: value)
}
init(unicodeScalarLiteral value: String) {
self.init(key: value)
}
}
func ==(lhs:LocalizedString, rhs:LocalizedString) -> Bool {
return lhs.v == rhs.v
}
enum DietWithoutResidueOption: LocalizedString {
case NoDiet = "NoDiet"
case ThreeDays = "ThreeDays"
case FiveDays = "FiveDays"
var localizedString: String {
return self.rawValue.v
}
init?(localizedString: String) {
self.init(rawValue: LocalizedString(localized: localizedString))
}
}
</code></pre>
<p>Using this, you can construct <code>DietWithoutResidueOption</code> by 3 ways:</p>
<pre><code>let option1 = DietWithoutResidueOption.ThreeDays
let option2 = DietWithoutResidueOption(rawValue: "ThreeDays") // as Optional
let option3 = DietWithoutResidueOption(localizedString: "OUI, SUR 3 JOURS") // as Optional
</code></pre>
<p>and extract the localized string with:</p>
<pre><code>let localized = option1.localizedString
</code></pre> |
8,281,098 | Suggest # tags while typing (like Twitter) for iPhone UITextView | <p>I'd building an app that uses hashtags, like Twitter or Tweetbot. When you're typing a message, if you type the hashtag symbol, I'd like to suggest tags that match the current one you're typing.</p>
<p>I've already figured out how to get the UITableView to appear and show a list of hashtags, but what I can't figure out is how to do the following:</p>
<ol>
<li>Get the <code>NSRange</code> of the current word being typed,</li>
<li>See if that range is formatted like a hashtag (<code>NSRegularExpression @"#\\w\\w*"</code>)</li>
<li>(From here on out, I've got the code figured out to search for matching hashtags and show them in the UITableView)</li>
</ol>
<p>Can anyone help me with steps 1 and 2? I've been thinking about using <code>textViewDidChange:</code>, but I'm concerned that the app's performance might suffer if I'm constantly running methods every time the characters change.</p>
<p>Thanks!</p> | 8,371,325 | 2 | 0 | null | 2011-11-26 19:46:13.66 UTC | 9 | 2018-11-19 12:38:10.35 UTC | 2013-06-29 16:51:24 UTC | null | 20,938 | null | 686,902 | null | 1 | 6 | iphone|ios|regex|uitextview|nsregularexpression | 3,918 | <p>I figured it out! I wound up using the <code>textViewDidChange:</code> and <code>textViewDidChangeSelection:</code> methods.</p>
<p>To get the <code>NSRange</code> of the current hashtag being typed, I ran a <code>for</code> loop over the <code>NSRegularExpression</code> matches in the text string. From there, I used <code>NSLocationInRange</code> to find out if the current cursor position intersected any of the hashtags.</p>
<p>Here's the code:</p>
<pre><code>//Get the ranges of current hashtags
NSArray *hashtagRanges = [StringChecker rangesOfHashtagsInString:textView.text];
NSTextCheckingResult *currentHashtag;
if ([hashtagRanges count] >0)
{
//List the ranges of all the hashtags
for (int i = 0; i<[hashtagRanges count]; i++)
{
NSTextCheckingResult *hashtag = [hashtagRanges objectAtIndex:i];
//Check if the currentRange intersects the hashtag
//Have to add an extra space to the range for if you're at the end of a hashtag. (since NSLocationInRange uses a < instead of <=)
NSRange currentlyTypingHashtagRange = NSMakeRange(hashtag.range.location, hashtag.range.length + 1);
if (NSLocationInRange(currentRange.location, currentlyTypingHashtagRange))
{
//If the cursor is over the hashtag, then snag that hashtag for matching purposes.
currentHashtag = hashtag;
}
}
if (currentHashtag){
//If we found one hashtag that we're currently editing
//Display the hashtag suggester, feed it the current hashtag for matching.
[self showTagTable];
//Get the current list of hashtags into an array
NSFetchRequest *hashtagRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *tagEntityDescription = [NSEntityDescription entityForName:@"Tags"
inManagedObjectContext:self.note.managedObjectContext];
[hashtagRequest setEntity:tagEntityDescription];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"dateLastUsed"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[hashtagRequest setSortDescriptors:sortDescriptors];
NSPredicate *tagPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", [noteTextView.text substringWithRange:currentHashtag.range]];
[hashtagRequest setPredicate:tagPredicate];
tagsToDisplay = (NSMutableArray *)[self.note.managedObjectContext executeFetchRequest:hashtagRequest error:nil];
[tagListTable reloadData];
//If there are no matching hashtags, then let's hide the tag table.
if ([tagsToDisplay count] == 0)
{
[self hideTagTable];
return;
}
}
</code></pre>
<p>The <code>StringChecker</code> class is a custom one that I wrote, it just has class methods that parse the strings. I made <code>StringChecker</code> a class because the methods are used in several places in the app. Here's the method:</p>
<pre><code> #pragma mark - Hashtag Methods
+(NSArray *)rangesOfHashtagsInString:(NSString *)string {
NSRegularExpression *hashtagDetector = [[NSRegularExpression alloc] initWithPattern:@"#\\w\\w*"
options:NSRegularExpressionCaseInsensitive
error:nil];
NSArray *hashtagRanges = [hashtagDetector matchesInString:string
options:NSMatchingWithoutAnchoringBounds
range:NSMakeRange(0, string.length)];
return hashtagRanges;
}
+(NSUInteger)numberOfHashtagsInString:(NSString *)string {
NSRegularExpression *hashtagDetector = [[NSRegularExpression alloc] initWithPattern:@"#\\w\\w*"
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger numberOfHashtags = [hashtagDetector numberOfMatchesInString:string
options:NSRegularExpressionCaseInsensitive
range:NSMakeRange(0, string.length)];
return numberOfHashtags;
}
</code></pre> |
8,016,233 | In C#, How do I call a function that is returning a list? | <p>In C#, How do I call a function that is returning a list? </p>
<pre><code> static void Main(string[] args)
{
List<string> range = new List<string>();
range.ForEach(item => item.WildcardFiles()); //this is not working
}
List<string> WildcardFiles(string first)
{
List<string> listRange = new List<string>();
listRange.Add("q");
listRange.Add("s");
return listRange;
}
</code></pre> | 8,016,258 | 2 | 1 | null | 2011-11-04 22:04:04.54 UTC | 3 | 2014-05-21 14:19:49.75 UTC | null | null | null | null | 953,053 | null | 1 | 11 | c#|list|function|methods | 112,802 | <p>There are various things wrong with your code:</p>
<ul>
<li>You're creating an empty list, and then calling <code>ForEach</code> on it. That's not going to do anything.</li>
<li>You're trying to call <code>WildcardFiles</code> on a string, when it's not a method of string.</li>
<li>You're trying to call <code>WildcardFiles</code> which is an instance method in whatever your declaring type is, but without any instances of that type.</li>
<li>You're trying to call <code>WildcardFiles</code> without passing in an argument for the <code>first</code> parameter</li>
<li>You're ignoring the return value of the call to <code>WildcardFiles</code></li>
<li><code>WildcardFiles</code> ignores its parameter</li>
</ul>
<p>Now I <em>suspect</em> you really wanted something like:</p>
<pre><code>static void Main(string[] args)
{
List<string> range = WildcardFiles();
foreach (string item in range)
{
// Do something with item
}
}
static List<string> WildcardFiles()
{
List<string> listRange = new List<string>();
listRange.Add("q");
listRange.Add("s");
return listRange;
}
</code></pre> |
7,735,267 | Can I target a :before or :after pseudo-element with a sibling combinator? | <p>Is there a reason why this CSS doesn't work?</p>
<p><a href="http://jsfiddle.net/6v5BZ/" rel="noreferrer">http://jsfiddle.net/6v5BZ/</a></p>
<pre class="lang-css prettyprint-override"><code>a[href^="http"]:after {
content:"";
width:10px;
height:10px;
display:inline-block;
background-color:red;
}
a[href^="http"] img ~ :after {
display:none;
}
</code></pre>
<p>.. on this HTML?</p>
<pre class="lang-html prettyprint-override"><code><a href="http://google.com">Test</a>
<a href="http://google.com">
<img src="https://www.google.com/logos/classicplus.png">
</a>
</code></pre>
<p>The idea is to have a pseudo-element on matching anchor tags. But I do not want it to apply to anchor tags that wrap an image. And since I can't target anchors using something like <code>a < img</code>, I figured the maybe I could target the :after pseudo-element by finding an image that it's a sibling of.</p>
<p>Any insight would be greatly appreciated.</p> | 7,737,374 | 2 | 4 | null | 2011-10-12 04:28:48.467 UTC | 5 | 2016-02-21 16:15:37.167 UTC | 2016-02-21 16:12:06.93 UTC | null | 106,224 | null | 556,079 | null | 1 | 39 | css|css-selectors|pseudo-element | 14,352 | <p>You can't target :after since it's content is not rendered in the DOM and it does not manipulate it - for this to work the DOM would have to be re-rendered and CSS can't manipulate it like this. </p>
<p>Check the specification for detailed understanding: <a href="http://www.w3.org/TR/CSS2/generate.html#propdef-content" rel="noreferrer">http://www.w3.org/TR/CSS2/generate.html#propdef-content</a></p>
<blockquote>
<p>Generated content does not alter the document tree. In particular, it
is not fed back to the document language processor (e.g., for
reparsing).</p>
</blockquote>
<p>I suggest you use JavaScript to do the job for you.</p> |
65,477,613 | RVM, where is Ruby 3.0.0? | <p>I want to download the latest Ruby release(version 3.0.0), using RVM but I am faced with the following error when running <code>rvm install 3.0.0</code>:</p>
<pre><code>Unknown ruby interpreter version (do not know how to handle): 3.0.0
</code></pre>
<p>I have also tried <code>3</code> & <code>3.0</code>, but gives the same error.</p>
<p>According to <a href="https://www.ruby-lang.org/en/downloads/" rel="noreferrer">this page</a>, it should be available through RVM. I'm already using RVM to manage my ruby versions, so I don't want to use <code>rbenv</code> ... nor do I want to install from source.</p>
<p>How can I get Ruby version <code>3.0.0</code> installed using RVM?</p> | 65,478,767 | 5 | 3 | null | 2020-12-28 12:27:44.223 UTC | 3 | 2021-07-20 11:39:03.537 UTC | null | null | null | null | 7,128,479 | null | 1 | 36 | ruby|rvm|ruby-3 | 16,070 | <p>If you have not updated rvm do that first <a href="https://rvm.io/rvm/upgrading" rel="noreferrer">RVM Upgrading</a></p>
<pre><code>rvm get stable
# or
rvm get master # for even newer versions not in stable 3.0.0 in this case
</code></pre>
<p>To see all available rubies run</p>
<pre><code>rvm list remote all
# or
rvm list known # as pointed out in the comments
</code></pre>
<p>you should see <code>ruby-3.0.0</code> in the list of available rubies</p>
<p>Then run</p>
<pre><code>rvm install ruby-3.0.0
</code></pre> |
8,800,515 | jQuery hide dropdown when clicked anywhere but menu | <p>I'm trying to make it so that my dropdown menu shows when you click a button, and hides when you click anywhere except the dropdown menu. </p>
<p>I have some code working, as far as not closing when you click the menu, however when you click the document when the menu is closed, it shows the menu, so it continuously toggles no matter where you click.</p>
<pre><code>$(document).click(function(event) {
if ($(event.target).parents().index($('.notification-container')) == -1) {
if ($('.notification-container').is(":visible")) {
$('.notification-container').animate({
"margin-top": "-15px"
}, 75, function() {
$(this).fadeOut(75)
});
} else {
//This should only show when you click: ".notification-button" not document
$('.notification-container').show().animate({
"margin-top": "0px"
}, 75);
}
}
});
</code></pre> | 8,810,243 | 8 | 3 | null | 2012-01-10 08:42:47.877 UTC | 15 | 2021-09-09 07:42:58.677 UTC | 2021-09-09 07:42:58.677 UTC | null | 4,370,109 | null | 1,095,363 | null | 1 | 25 | javascript|jquery|jquery-events | 42,755 | <p>This is what I've decided to use, it's a nice little jQuery plugin that works with little code.</p>
<p>Here's the plugin:
<a href="http://benalman.com/projects/jquery-outside-events-plugin/" rel="nofollow">http://benalman.com/projects/jquery-outside-events-plugin/</a></p>
<p>This is the code that makes my above code in my question work.</p>
<pre><code>$(document).ready(function(){
$(".notification-button").click(function(){
$('.notification-container').toggle().animate({"margin-top":"0px"}, 75);
});
$('.notification-wrapper').bind('clickoutside', function (event) {
$('.notification-container').animate({"margin-top":"-15px"}, 75, function(){$(this).fadeOut(75)});
});
});
</code></pre> |
8,992,964 | Android load from URL to Bitmap | <p>I have a question about loading an image from a website. The code I use is:</p>
<pre><code>Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Bitmap bit=null;
try {
bit = BitmapFactory.decodeStream((InputStream)new URL("http://www.mac-wallpapers.com/bulkupload/wallpapers/Apple%20Wallpapers/apple-black-logo-wallpaper.jpg").getContent());
} catch (Exception e) {}
Bitmap sc = Bitmap.createScaledBitmap(bit,width,height,true);
canvas.drawBitmap(sc,0,0,null);
</code></pre>
<p>But it always returns a null pointer exception and the program crashes out.
The URL is valid, and it seems to work for everyone else.
I'm using 2.3.1.</p> | 8,993,175 | 20 | 3 | null | 2012-01-24 19:37:28.827 UTC | 29 | 2021-11-07 12:43:08.033 UTC | 2015-07-02 09:59:56.09 UTC | null | 243,164 | null | 1,078,093 | null | 1 | 84 | java|android|bitmap | 187,407 | <pre><code>public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
</code></pre> |
5,529,137 | Java Non-Blocking and Asynchronous IO with NIO & NIO.2 (JSR203) - Reactor/Proactor Implementations | <p>So here I am reading one of my favorite software pattern books (Pattern-Oriented Software Architecture - Patterns for Concurrent and Networked Objects), specifically the sections on Proactor/Reactor asynchronous IO patterns. I can see how by using selectable channels I can implement a Reactor style asynchronous IO mechanism quite easy (and have done so). But, I cannot see how I would implement a proper Proactor mechanism with non-blocking writes. That is taking advantage of OS managed non-blocking write functions. </p>
<p>Functionality supported by OS specific calls like <a href="http://msdn.microsoft.com/en-us/library/aa364986%28v=vs.85%29.aspx" rel="noreferrer">GetQueuedCompletionStatus</a> under win32. </p>
<p>I did see that Java 7 brings some updates to NIO with asynchronous completion handlers (which seems to be in the right direction). That being said... Given the lack of unified cross-platform support for OS managed async operations (specifically async write) I am assuming that this is a quassy-implementation that is not utilizing native OS support.</p>
<p>So my questions are, is proactor based IO handling possible in Java in such a way that it is advantageous to use for specific scenarios; and, if Java NIO does support proactor based IO handling (either in Java 6 or Java 7) is OS managed asynchronous IO support (i.e. completion callbacks from the OS) being utilized? Furthermore, if the implementation is purely in-VM are the performance benefits so little that using proactive event handling offers nothing more than a different (possibly simpler) way of constructing concurrent network handling software.</p>
<p>For anyone interested in proactive event handling <a href="http://www.cse.wustl.edu/~schmidt/PDF/proactor.pdf" rel="noreferrer">here is a good article</a> that outlines pros / cons and a comparison to both traditional thread-per-connection and reactive IO models.</p> | 5,551,856 | 4 | 2 | null | 2011-04-03 10:52:04.7 UTC | 31 | 2015-05-27 02:18:44.43 UTC | 2011-08-02 11:08:38.953 UTC | null | 213,269 | null | 104,302 | null | 1 | 27 | java|design-patterns|asynchronous|nio|asyncsocket | 14,215 | <p>There are lots of factors involved in this one. I will try to summarize my findings as best as possible (aware of the fact that there is contention regarding the usefulness of reactor and proactor IO handling implementations).</p>
<blockquote>
<p>Is proactor based IO handling possible
in Java in such a way that it is
advantageous to use for specific
scenarios.</p>
</blockquote>
<p>Java 1.4 introduced non-blocking IO which is NOT the same as asynchronous IO. Java SE 7 introduces asynchronous IO with JSR203 making "true" proactor style IO handling implementations possible.</p>
<p>See <a href="http://openjdk.java.net/projects/nio/javadoc/java/nio/channels/AsynchronousSocketChannel.html">AsyncrhonousSocketChannel</a>, <a href="http://openjdk.java.net/projects/nio/javadoc/java/nio/channels/AsynchronousServerSocketChannel.html">AsynchronousServerSocketChannel</a></p>
<blockquote>
<p>and, if Java NIO does support proactor
based IO handling (either in Java 6 or
Java 7) is OS managed asynchronous IO
support (i.e. completion callbacks
from the OS) being utilized?</p>
</blockquote>
<p>Reading through the JSR 203 specs, completion handlers using new asynchronous channels are definitely supported and it is reported that native OS features are being utilized but I have not ascertained to what extent yet. I may follow up on this after an analysis of the Java 7 source (unless someone beats me to it).</p>
<blockquote>
<p>Furthermore, if the implementation is
purely in-VM are the performance
benefits so little that using
proactive event handling offers
nothing more than a different
(possibly simpler) way of constructing
concurrent network handling software.</p>
</blockquote>
<p>I have not been able to find any performance comparisons regarding new Asynchronous IO features in Java 7. I'm sure they will become available in the near future.</p>
<p>As always, when presented with more than one way to tackle a problem the questions of which approach is better is almost always answered with "depends". Proactive event handling (using asynchronous completion handlers) is included with Java 7 and cannot simply exist without purpose. For certain applications, it will make sense to use such IO handling. Historically a common example given where proactor has good applicability is in a HTTP server where many short requests are issued frequently. For a deeper explanation <a href="http://www.cse.wustl.edu/~schmidt/PDF/proactor.pdf">give this a read</a> (provided only to highlight the advantages of proactor so try to overlook the fact that example code is C++).</p>
<p>IMO it seems obvious that in many circumstances reactor/proactor complicate what would otherwise be a very simple design using a more traditional approach and in other more complex systems they offer a high degree of simplification and flexibility.</p>
<p>.
.
.</p>
<p>On a side note I highly recommend reading through <a href="http://www.mailinator.com/tymaPaulMultithreaded.pdf">the following presentation about NIO</a> which offers performance comparison between NIO and the "traditional" approach. Though I would also advise caution regarding the results presented as the NIO implementation in the benchmark was based on the pre Java 1.4 NBIO NIO library and not the NIO implementation shipped in 1.4. </p> |
5,460,562 | Why it is impossible to create an array of references in c++? | <p>C++ Standard 8.3.2/4 says:</p>
<blockquote>
<p>There shall be no references to
references, no arrays of references,
and no pointers to references.</p>
</blockquote>
<p>But I can't understand why this restriction is added to c++. In my opinion the code bellow can easily be compiled and work? What is the real cause of this restriction?</p>
<pre><code>int a = 10, b = 20;
int &c[] = {a, b};
</code></pre> | 5,460,857 | 4 | 1 | null | 2011-03-28 14:36:52.84 UTC | 8 | 2017-02-15 11:13:57.41 UTC | 2014-11-07 17:01:46.077 UTC | null | 509,233 | null | 509,233 | null | 1 | 29 | c++|arrays|reference | 16,773 | <p>Because indexation into an array is actually defined in terms of an implicit conversion to a pointer, then pointer arithmetic. So to support this, you'd have to also support pointers to references, and define what pointer arithmetic means on them.</p> |
5,044,596 | Making Entity framework implement an interface | <p>I want to use IoC with Entity framework and Ninject. I figure I need the Generated Entity classes to implement an interface, ICRUD. There's a <a href="http://blogs.msdn.com/b/efdesign/archive/2009/01/22/customizing-entity-classes-with-t4.aspx" rel="noreferrer">walkthrough</a> that shows how to force Entity framework to implement an interface. I followed the directions and my EntityObjectCodeGenerator.cs file indeed shows "ICrud", but doesn't implement the interface. I don't see any subclasses under EntityObjectCodeGenerator.tt as the article says I'm supposed to. I get error </p>
<blockquote>
<p>'BugnetMvc.Models.BugNetEntities' does
not implement interface member
'BugnetMvc.Services.ICrud.Update()'</p>
</blockquote>
<p><strong>UPDATE</strong><br />
The goal is to create a testable, extensible MVC-3 intranet utilizing entity framework that also supports strongly typed Views and partial views. From my small level of experience with Ninject thus far, I believe I need to overload my Controller's constructor with a service for the View itself (Assume CRUD methods available for each interface) and one for each partial view:</p>
<p>E.G.</p>
<pre><code>public HomeController(HomeService homeCrudService, PartialViewService1 partialviewService)
</code></pre>
<p><strong>Update2</strong><br />
To be clear and hopefully help others, the code can be implemented as follows:</p>
<p>This is how one can extend Entity</p>
<pre><code>namespace BugnetMvc.Models//ensure namespace matches entity
{
public partial class Milestone : ICrud<Milestone>//Entity, note the CRUD generic. This gives us a lot of flexibility working with Ninject
{
public bool Create()
{
throw new System.NotImplementedException();
}
public List<Milestone> Read()
{
var milestones = new List<Milestone>();
var result = from a in new BugNetEntities1().Milestones
where a.MilestoneID >= 0
select new { a.Milestone1 };
milestones = result.AsEnumerable()
.Select(o => new Models.Milestone
{
Milestone1 = o.Milestone1
}).ToList();
return milestones;
}
public bool Update()
{
throw new System.NotImplementedException();
}
public bool Delete()
{
throw new System.NotImplementedException();
}
}
</code></pre>
<p>A sample Mock entity:</p>
<pre><code>namespace BugnetMvc.Services
{
public class MilestoneServiceMock : ICrud<MilestoneMock>
{
public MilestoneServiceMock()
{
}
public bool Create()
{
throw new System.NotImplementedException();
}
public bool Update()
{
throw new System.NotImplementedException();
}
public bool Delete()
{
throw new System.NotImplementedException();
}
List<MilestoneMock> ICrud<MilestoneMock>.Read()
{
//string[] mileStones = new string[14];
List<MilestoneMock> milestoneMocks = new List<MilestoneMock>();
milestoneMocks.Add(new MilestoneMock("New"));
milestoneMocks.Add(new MilestoneMock("Assessment"));
milestoneMocks.Add(new MilestoneMock("Pending Approval"));
milestoneMocks.Add(new MilestoneMock("Pending Start"));
milestoneMocks.Add(new MilestoneMock("Planning"));
milestoneMocks.Add(new MilestoneMock("Dev-In Process"));
milestoneMocks.Add(new MilestoneMock("Dev-Pending Approval to QA"));
milestoneMocks.Add(new MilestoneMock("Dev-Pending Move to QA"));
milestoneMocks.Add(new MilestoneMock("QA-In Process"));
milestoneMocks.Add(new MilestoneMock("QA-UAT"));
milestoneMocks.Add(new MilestoneMock("QA-Pending Approval to Prod"));
milestoneMocks.Add(new MilestoneMock("QA-Pending Move to Prod"));
milestoneMocks.Add(new MilestoneMock("On-Going"));
return milestoneMocks;
}
}
}
//Global.asax
internal class SiteModule : NinjectModule
{
public override void Load()
{
bool MOCKDB = true;
MOCKDB = false;
if (MOCKDB)
{
//Set up ninject bindings here.
Bind<ICrud<MilestoneMock>>().To<MilestoneServiceMock>();
Bind<ICrud<Application>>().To<ApplicationService>();
}
else
{
//Set up ninject bindings here.
Bind<ICrud<Milestone>>().To<Milestone>();
Bind<ICrud<Application>>().To<ApplicationService>();
}
}
}
</code></pre>
<p>The need for Read(int Id), may arise, in which case a new interface using the same basic ideas above should do the trick. One could even update ICrud to pass the model type into the methods as well. There's plenty of options. This worked for me, thanks to Jon Skeet for his expert guidance.</p> | 5,044,650 | 4 | 0 | null | 2011-02-18 17:35:02.117 UTC | 4 | 2014-05-12 04:32:09.14 UTC | 2011-02-19 05:53:07.04 UTC | null | 87,796 | null | 87,796 | null | 1 | 31 | c#|entity-framework|asp.net-mvc-3|ninject | 22,908 | <p>Presumably the generated entity classes are partial classes, correct?</p>
<p>If so, you can just add your own partial class files to specify the interfaces to be implemented - and to provide any actual implementation methods you need. I suspect that will be a lot simpler than changing what gets generated.</p> |
5,317,190 | How do browsers execute javascript | <p>I'm trying to figure out if web browsers use an interpreter to execute javascript, or some sort of compiler. It is well known that scripting languages are interpreted not compiled; however there is the <em>JScriptCompiler</em> that can compile javascript into MSIL. This leaves me to wonder if IE, FF, Chrome etc are using some sort of compiler or if it's an interpreter.</p>
<p>Can anyone cite the specific method in which browsers run javascript?</p> | 5,317,250 | 4 | 1 | null | 2011-03-15 19:51:24.94 UTC | 20 | 2013-08-27 09:07:27.7 UTC | 2013-08-27 09:07:27.7 UTC | null | 649,687 | user220583 | null | null | 1 | 37 | javascript | 31,095 | <p>In the past, Javascript was interpreted -- and nothing more.</p>
<p>In the past two years or so, browsers have been implementing new Javascript engines, trying to compile some portions of code, to speed Javascript up.</p>
<p><br>
For more informations on what has been done for Mozilla Firefox, you should take a look at :</p>
<ul>
<li><a href="https://wiki.mozilla.org/JavaScript:TraceMonkey" rel="noreferrer">JavaScript:TraceMonkey</a></li>
<li><a href="https://hacks.mozilla.org/2009/07/tracemonkey-overview/" rel="noreferrer">an overview of TraceMonkey</a></li>
</ul>
<p>For more informations about Chrome's engine, you'll want to read :</p>
<ul>
<li><a href="https://code.google.com/apis/v8/design.html#mach_code" rel="noreferrer">Dynamic Machine Code Generation</a></li>
</ul>
<p>And for webkit <em>(safari)</em> :</p>
<ul>
<li><a href="http://www.webkit.org/blog/189/announcing-squirrelfish/" rel="noreferrer">Announcing SquirrelFish</a></li>
</ul>
<p>Not sure what has been <em>(or is being)</em> done on other browsers -- but I suppose the same kind of thing exists, or will exist.</p>
<p><br>
And, of course, for more informations : <a href="https://secure.wikimedia.org/wikipedia/en/wiki/JavaScript_engine" rel="noreferrer"><strong>JavaScript engine</strong></a>, on wikipedia.</p> |
5,193,173 | getting cout output to a std::string | <p>I have the following <code>cout</code> statement. I use char arrays because I have to pass to <code>vsnprintf</code> to convert variable argument list and store in <code>Msg</code>.</p>
<p>Is there any way we can get <code>cout</code> output to C++ <code>std::string</code>?</p>
<pre><code>char Msg[100];
char appname1[100];
char appname2[100];
char appname3[100];
// I have some logic in function which some string is assigned to Msg.
std::cout << Msg << " "<< appname1 <<":"<< appname2 << ":" << appname3 << " " << "!" << getpid() <<" " << "~" << pthread_self() << endl;
</code></pre> | 5,193,203 | 4 | 0 | null | 2011-03-04 11:34:41.553 UTC | 5 | 2019-10-07 11:56:44.467 UTC | 2016-10-14 09:54:58.1 UTC | null | 572,834 | null | 519,882 | null | 1 | 44 | c++|cout|stdstring | 68,091 | <p>You can replace <code>cout</code> by a <a href="http://en.cppreference.com/w/cpp/io/basic_stringstream" rel="noreferrer"><code>stringstream</code></a>.</p>
<pre><code>std::stringstream buffer;
buffer << "Text" << std::endl;
</code></pre>
<p>You can access the string using <code>buffer.str()</code>.</p>
<p>To use <code>stringstream</code> you need to use the following libraries:</p>
<pre><code>#include <string>
#include <iostream>
#include <sstream>
</code></pre> |
5,453,026 | String to list in Python | <p>I'm trying to split a string:</p>
<pre><code>'QH QD JC KD JS'
</code></pre>
<p>into a list like:</p>
<pre><code>['QH', 'QD', 'JC', 'KD', 'JS']
</code></pre>
<p>How would I go about doing this? </p> | 5,453,032 | 5 | 3 | null | 2011-03-27 22:50:57.457 UTC | 5 | 2021-01-24 19:00:25.193 UTC | 2019-07-30 21:30:23.747 UTC | null | 6,862,601 | null | 679,421 | null | 1 | 39 | python|string|list | 145,982 | <pre><code>>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']
</code></pre>
<p><a href="http://docs.python.org/library/stdtypes.html#str.split"><code>split</code></a>:</p>
<blockquote>
<p>Return a list of the words in the
string, using <code>sep</code> as the delimiter
string. If <code>maxsplit</code> is given, at most
<code>maxsplit</code> splits are done (thus, the
list will have at most <code>maxsplit+1</code>
elements). If <code>maxsplit</code> is not
specified, then there is no limit on
the number of splits (all possible
splits are made).</p>
<p>If <code>sep</code> is given, consecutive
delimiters are not grouped together
and are deemed to delimit empty
strings (for example,
<code>'1,,2'.split(',')</code> returns <code>['1', '', '2']</code>). The <code>sep</code> argument may consist of
multiple characters (for example,
<code>'1<>2<>3'.split('<>')</code> returns <code>['1', '2', '3']</code>). Splitting an empty string
with a specified separator returns
<code>['']</code>.</p>
<p>If <code>sep</code> is not specified or is <code>None</code>, a
different splitting algorithm is
applied: runs of consecutive
whitespace are regarded as a single
separator, and the result will contain
no empty strings at the start or end
if the string has leading or trailing
whitespace. Consequently, splitting an
empty string or a string consisting of
just whitespace with a <code>None</code> separator
returns <code>[]</code>.</p>
<p>For example, <code>' 1 2 3 '.split()</code>
returns <code>['1', '2', '3']</code>, and <code>' 1 2 3 '.split(None, 1)</code> returns <code>['1', '2 3 ']</code>.</p>
</blockquote> |
5,029,593 | Getting Varnish To Work on Magento | <p>First please forgive me for total lack of understanding of Varnish. This is my first go at doing anything with Varnish.</p>
<p>I am following the example at: <a href="http://www.kalenyuk.com.ua/magento-performance-optimization-with-varnish-cache-47.html" rel="noreferrer">http://www.kalenyuk.com.ua/magento-performance-optimization-with-varnish-cache-47.html</a></p>
<p>However when I install and run this, Varnish does not seem to cache. I do get the X-Varnish header with a single number and a Via header that has a value of 1.1 varnish</p>
<p>I have been told (by my ISP) it is because of the following cookie that Magento sets:</p>
<p><code>Set-Cookie: frontend=6t2d2q73rv9s1kddu8ehh8hvl6; expires=Thu, 17-Feb-2011 14:29:19 GMT; path=/; domain=XX.X.XX.XX; httponly</code></p>
<p>They said that I either have to change Magento to handle this or configure Varnish to handle this. Since changing Magento is out of the question, I was wondering if someone can give me a clue as to how I would configure Varnish to handle this cookie?</p> | 6,121,292 | 7 | 4 | null | 2011-02-17 13:32:35.373 UTC | 17 | 2015-08-07 08:25:20.327 UTC | 2012-07-05 22:01:10.707 UTC | user212218 | null | null | 365,709 | null | 1 | 17 | php|caching|cookies|magento|varnish | 31,948 | <p><a href="http://moprea.ro/2011/may/6/magento-performance-optimization-varnish-cache-3/">http://moprea.ro/2011/may/6/magento-performance-optimization-varnish-cache-3/</a> describes the Magento extension that enables full page cache with varnish. This extension relies on Varnish config published on github.</p>
<p>These are the features already implemented:</p>
<ol>
<li>Workable varnish config</li>
<li>Enable full page caching using Varnish, a super fast caching HTTP reverse proxy.</li>
<li>Varnish servers are configurable in Admin, under System / Configuration / General - Varnish Options</li>
<li>Automatically clears (only) cached pages when products, categories and CMS pages are saved.</li>
<li>Adds a new cache type in Magento Admin, under System / Cache Management and offers the possibility to deactivate the cache and refresh the cache.</li>
<li>Notifies Admin users when a category navigation is saved and Varnish cache needs to be refreshed so that the menu will be updated for all pages.</li>
<li>Turns off varnish cache automatically for users that have products in the cart or are logged in, etc.)</li>
<li>Default varnish configuration offered so that the module is workable.
Screen shots: <a href="https://github.com/madalinoprea/magneto-varnish/wiki">https://github.com/madalinoprea/magneto-varnish/wiki</a></li>
</ol> |
5,493,281 | C sizeof a passed array | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/492384/how-to-find-the-sizeof-a-pointer-pointing-to-an-array">How to find the sizeof( a pointer pointing to an array )</a> </p>
</blockquote>
<p>I understand that the sizeof operator is evaluated and replaced with a constant at compile time. Given that, how can a function, being passed different arrays at different points in a program, have it's size computed? I can pass it as a parameter to the function, but I'd rather not have to add another parameter if I don't absolutely have to.</p>
<p>Here's an example to illustrate what I'm asking:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define SIZEOF(a) ( sizeof a / sizeof a[0] )
void printarray( double x[], int );
int main()
{
double array1[ 100 ];
printf( "The size of array1 = %ld.\n", SIZEOF( array1 ));
printf( "The size of array1 = %ld.\n", sizeof array1 );
printf( "The size of array1[0] = %ld.\n\n", sizeof array1[0] );
printarray( array1, SIZEOF( array1 ) );
return EXIT_SUCCESS;
}
void printarray( double p[], int s )
{
int i;
// THIS IS WHAT DOESN"T WORK, SO AS A CONSEQUENCE, I PASS THE
// SIZE IN AS A SECOND PARAMETER, WHICH I'D RATHER NOT DO.
printf( "The size of p calculated = %ld.\n", SIZEOF( p ));
printf( "The size of p = %ld.\n", sizeof p );
printf( "The size of p[0] = %ld.\n", sizeof p[0] );
for( i = 0; i < s; i++ )
printf( "Eelement %d = %lf.\n", i, p[i] );
return;
}
</code></pre> | 5,493,310 | 7 | 2 | null | 2011-03-30 22:33:04.137 UTC | 10 | 2016-07-25 20:49:31.117 UTC | 2017-05-23 12:18:07.123 UTC | null | -1 | null | 684,826 | null | 1 | 37 | c|arrays|function|sizeof | 50,654 | <p>There is no magic solution. C is not a reflective language. Objects don't automatically know what they are.</p>
<p>But you have many choices:</p>
<ol>
<li>Obviously, add a parameter</li>
<li>Wrap the call in a macro and automatically add a parameter</li>
<li>Use a more complex object. Define a structure which contains the dynamic array and also the size of the array. Then, pass the address of the structure.</li>
</ol> |
16,994,226 | How to get DataSource or Connection from JPA2 EntityManager in Java EE 6 | <p>I have a working application where I use Java EE 6 with EclipseLink for persistence and a PostgreSQL database.</p>
<p>For the User-Registration I want to set the password in PostgreSQL to:</p>
<pre><code>... password = crypt('inputPassword',gen_salt('bf')) ...
</code></pre>
<p>As I cant use DigestUtils for this, I have to insert the user manually into the DB.
To keep my application configurable I do not want to query the DataSource with an
<code>InitialContextInstance.lookup(dataSource)</code> but to extract it (or the Connection) somehow from the EntityManager
like:</p>
<pre><code>DataSource ds = entityManagerInstance.someFunctionThatReturnsADataSourceOrConnection();
</code></pre>
<p>Or would it be possible to use createNativeQuery or something similar in conjuntion
with a prepared statement to protect against injections?</p> | 16,994,321 | 3 | 2 | null | 2013-06-07 23:10:55.33 UTC | 2 | 2016-01-27 19:33:32.653 UTC | null | null | null | null | 830,197 | null | 1 | 12 | java|jpa|jdbc|java-ee-6 | 38,811 | <p>sometimes it just takes another run in google:</p>
<pre><code>entityManager.getTransaction().begin();
java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
entityManager.getTransaction().commit();
</code></pre>
<p>as described in the <a href="http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager">Eclipse Link Documentation</a></p> |
41,594,683 | Encrypt / Decrypt in C# using Certificate | <p>I'm having trouble finding a good example in encrypting / decrypting strings in C# <em>using a certificate</em>. I was able to find and implement an example of <strong>signing</strong> and validating a signature, as shown below. Could someone point me to an easy, similar example for encryption?</p>
<pre><code>private static string Sign(RSACryptoServiceProvider privateKey, string content)
{
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding ();
byte[] data = encoding.GetBytes(content);
byte[] hash = sha1.ComputeHash(data);
// Sign the hash
var signature = privateKey.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
return Convert.ToBase64String(signature);
}
public static bool Verify(RSACryptoServiceProvider publicKey, string content, string hashString)
{
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding ();
byte[] data = encoding.GetBytes(content);
byte[] hash = sha1.ComputeHash(data);
return publicKey.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String(hashString));
}
</code></pre> | 41,595,289 | 1 | 5 | null | 2017-01-11 15:26:17.077 UTC | 3 | 2017-01-11 17:09:39.163 UTC | null | null | null | null | 163,176 | null | 1 | 23 | c#|encryption|certificate|x509certificate|x509 | 43,088 | <p>Per the <a href="https://blogs.msdn.microsoft.com/dotnet/2015/07/20/announcing-net-framework-4-6/" rel="noreferrer">.NET Framework team's guidance</a> (have to search for "Cryptography Updates", there doesn't seem to be an anchor nearby -- or, just look at <a href="https://gist.github.com/richlander/52423b87b60d39d8b464#file-dotnet-crypto-46-cs" rel="noreferrer">the code samples</a>).</p>
<pre><code>public static byte[] EncryptDataOaepSha1(X509Certificate2 cert, byte[] data)
{
// GetRSAPublicKey returns an object with an independent lifetime, so it should be
// handled via a using statement.
using (RSA rsa = cert.GetRSAPublicKey())
{
// OAEP allows for multiple hashing algorithms, what was formermly just "OAEP" is
// now OAEP-SHA1.
return rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA1);
}
}
</code></pre>
<p>Decrypt would thus be</p>
<pre><code>public static byte[] DecryptDataOaepSha1(X509Certificate2 cert, byte[] data)
{
// GetRSAPrivateKey returns an object with an independent lifetime, so it should be
// handled via a using statement.
using (RSA rsa = cert.GetRSAPrivateKey())
{
return rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA1);
}
}
</code></pre>
<p>Caveats:</p>
<ul>
<li>RSA.Encrypt(byte[], RSAEncryptionPadding) was added in .NET Framework 4.6 (and .NET Core 1.0 / .NET Standard 1.3), so make sure you are building a project with a high enough target version.</li>
<li>RSA encryption is mainly used to encrypt symmetric keys, not actual data payloads, because it is expensive and has a size limit (always lower than the keysize (in bytes), the different padding modes consume different amounts of available space).</li>
<li>While the RSA base class talks about OaepSHA256 (etc) only Pkcs1 and OaepSHA1 are supported by all providers in .NET Core. (OaepSHA256+ is limited to RSACng)</li>
</ul> |
12,601,180 | How to download file via jQuery ajax and C# | <p>I want to download a file using jQuery Ajax web method, but it's not working. </p>
<p>Here is my jQuery ajax call to web method:</p>
<pre><code>function GenerateExcel() {
var ResultTable = jQuery('<div/>').append(jQuery('<table/>').append($('.hDivBox').find('thead').clone()).append($('.bDiv').find('tbody').clone()));
var list = [$(ResultTable).html()];
var jsonText = JSON.stringify({ list: list });
$.ajax({
type: "POST",
url: "GenerateMatrix.aspx/GenerateExcel",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
alert(response.d);
}
});
}
</code></pre>
<p>and this is the web method definition:</p>
<pre><code>[System.Web.Services.WebMethod()]
public static string GenerateExcel(List<string> list)
{
HttpContext.Current.Response.AppendHeader("content-disposition", "attachment;filename=FileEName.xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Write(list[0]);
HttpContext.Current.Response.End();
return "";
}
</code></pre>
<p>How to get it done?</p>
<p>One more thing: I want to download it on client PC, not to save it on server.</p> | 12,618,869 | 3 | 4 | null | 2012-09-26 11:54:45.59 UTC | 3 | 2020-02-29 11:22:42.543 UTC | 2020-02-29 11:22:42.543 UTC | null | 472,495 | null | 1,578,500 | null | 1 | 10 | c#|jquery|webmethod | 40,022 | <p>well i have done it using iframe</p>
<p>this is the modified ajax function call</p>
<pre><code> function GenerateExcel() {
var ResultTable = jQuery('<div/>').append(jQuery('<table/>').append($('.hDivBox').find('thead').clone()).append($('.bDiv').find('tbody').clone()));
var list = [$(ResultTable).html()];
var jsonText = JSON.stringify({ list: list });
$.ajax({
type: "POST",
url: "GenerateMatrix.aspx/GenerateExcel",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (isNaN(response.d) == false) {
$('#iframe').attr('src', 'GenerateMatrix.aspx?ExcelReportId=' + response.d);
$('#iframe').load();
}
else {
alert(response.d);
}
},
failure: function (response) {
alert(response.d);
}
});
}
</code></pre>
<p>and this is the design part</p>
<pre><code> <iframe id="iframe" style="display:none;"></iframe>
</code></pre>
<p>on Page load my code looks like this</p>
<pre><code> Response.AppendHeader("content-disposition", "attachment;filename=FileEName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.Write(tableHtml);
Response.End();
</code></pre> |
12,488,720 | NoSQL Database for ECommerce | <p>I will be constructing an ecommerce site, and would like to use a no-sql database, which will fit well with the plans for the app. But when it comes to which database would fit the job, im not sure. After comparing various DB's, the ones that seem best might be either mongo, couch, or even orientdb. I have seen arguments for all of them to be used or not used compared to something like MySQL. But between themselves (nosql databases), which one would fit well with an ecommerce solution?</p>
<p>Note, for the use case, i wont be having thousands of transactions a second. Or similarly high write rates. they will be moderate sure, but at a level that any established database could handle. </p>
<p>CouchDB: Has master to master replication, which I could really use. If not, I will still have to implement the same functionality in code anyways. I need to be able to have a users database, sync with the mothership. (users will have their own, potentially localhost database, that could sync with the main domains server). Couch is also fast, once your queries have been stored in the db.As i will probably have a higher need for read performance. Though not by a lot.</p>
<p>MongoDB: queries are very easy and user friendly. Also, with the fact that end users may need to query for certain things at a given time that I may not be able to account for ahead of time, this seems like it may be a better fit. I dont have to pre-store my queries in the db. Does support atomic transactions, though only when writing to a single document at a time.</p>
<p>OrientDB: A graph database. much different that most people are used to, but with the needs, it could fit very well too. Orient has the benefits of being schemaless, as well as having support for ACID transactions. There is a lot of customer, and product relationships that a graph database could be great with. Orient also support master to master replication, similar to couchdb.</p>
<p>Dont get me wrong, I can see how to build this traditionally with something like MySQL, but the ease and simplicity of a nosql solution, is very attractive. Although, in my case, needing a schemaless solution, would be much easier in nosql rather than mysql. a given product may have more or less items, than another. and avoiding recreating a table whenever a new field is added, is preferrable.</p>
<p>So between these 3 (or even others you think may be better), what features in each could potentially work for, or against me in regards to an ecommerce based site, when dealing with customer transactions?</p>
<p>Edit: The reason I am not using an existing solution, is because with the integrated features I need, there are no solutions available out there. We are also aiming to use this as a full product for our company. There will be a handful of other integrations than just sales. It is also going to be working with a store's POS system.</p> | 12,493,996 | 3 | 5 | null | 2012-09-19 04:44:22.573 UTC | 16 | 2021-11-20 03:19:40.067 UTC | 2017-09-22 18:01:22.247 UTC | null | -1 | null | 519,990 | null | 1 | 14 | mongodb|couchdb|e-commerce|orientdb|nosql | 14,779 | <p>Since <em>e-commerce</em> can encompass everything from shopping carts through to membership and recurring subscriptions, it is hard to guess exactly what requirements and complexity you are envisioning.</p>
<p>When constructing an e-commerce site, one of the early considerations should be investigating whether there is already an established e-commerce product or toolkit that could meet your requirements. There are many subtleties to processes like ordering, invoicing, payments, products, and customer relationships even when your use case appears to be straightforward. It may also be possible to separate your application into the catalog management aspects (possibly more custom) versus the billing (potentially third party, perhaps even via a hosted billing/payment API).</p>
<p>Another consideration should be who you are developing the e-commerce site for: is this to scratch your own itch, or for a client? Time, budget, and features for a custom build can be difficult to estimate and schedule .. and a niche choice of technology may make it difficult to find/hire additional development expertise.</p>
<p>A third consideration is what your language(s) of choice are for developing your application. Some languages will have more complete/mature/documented drivers and/or framework abstractions for the different databases.</p>
<p>That said, writing an e-commerce system appears to be a rite of passage for many developers ;-).</p>
<p>Edit: a lot has changed since this answer was originally posted in 2012 and you should definitely refer to current product information. For example, MongoDB has had support for <a href="https://www.mongodb.com/developer/quickstart/bson-data-types-decimal128/" rel="nofollow noreferrer">Decimal128 values</a> since MongoDB 3.4 (2016) and <a href="https://www.mongodb.com/transactions" rel="nofollow noreferrer">multi-document transactions</a> since MongoDB 3.6 (2017).</p> |
12,598,818 | Finding a picture in a picture with java? | <p>what i want to to is analyse input from screen in form of pictures. I want to be able to identify a part of an image in a bigger image and get its coordinates within the bigger picture. Example:</p>
<p><img src="https://i.stack.imgur.com/bCkh8.jpg" alt="box"></p>
<p>would have to be located in </p>
<p><img src="https://i.stack.imgur.com/IK3oa.jpg" alt="big picture"></p>
<p>And the result would be the upper right corner of the picture in the big picture and the lower left of the part in the big picture. As you can see, the white part of the picture is irrelevant, what i basically need is just the green frame. Is there a library that can do something like this for me? Runtime is not really an issue. </p>
<p>What i want to do with this is just generating a few random pixel coordinates and recognize the color in the big picture at that position, to recognize the green box fast later. And how would it decrease performance, if the white box in the middle is transparent?</p>
<p>The question has been asked several times on SO as it seems without a single answer. I found i found a solution at <a href="http://werner.yellowcouch.org/Papers/subimg/index.html" rel="noreferrer">http://werner.yellowcouch.org/Papers/subimg/index.html</a> . Unfortunately its in C++ and i do not understand a thing. Would be nice to have a Java implementation on SO. </p> | 12,662,066 | 2 | 1 | null | 2012-09-26 09:39:45.927 UTC | 12 | 2013-09-06 20:05:35.6 UTC | 2013-09-06 20:05:35.6 UTC | null | 881,229 | null | 419,497 | null | 1 | 22 | java|image-recognition | 34,570 | <p>The problem is hard to answer in general because people often have different requirements for what counts as an image match. Some people might want to search for an image that might have a different size or orientation than the template image they provide, in which case a scale- or rotation-invariant approach is needed. There are various option such as looking for similar textures, features or shapes, but I will focus on approaches that only looks for pixels of a similar colour that are in the exact same positions as the template image. This seems most suited to your example which seems to fall in the category of <a href="http://en.wikipedia.org/wiki/Template_matching" rel="noreferrer">template matching</a>.</p>
<h3>Possible approaches</h3>
<p>In this case the problem is closely related to the signal processing concepts of <a href="http://en.wikipedia.org/wiki/Cross-correlation" rel="noreferrer">cross-correlation</a> and <a href="http://en.wikipedia.org/wiki/Convolution" rel="noreferrer">convolution</a>, which is often implemented using an <a href="http://en.wikipedia.org/wiki/Fast_Fourier_transform" rel="noreferrer">FFT</a> as it is very fast (its in the name!). This is what was used in the approach you <a href="http://werner.yellowcouch.org/Papers/subimg/index.html" rel="noreferrer">linked</a> to, and the <a href="http://www.fftw.org/download.html" rel="noreferrer">FFTW</a> library could be of use when attempting such an implementation as it has wrappers for Java. Using cross-correlation works quite well, as seen in <a href="https://stackoverflow.com/questions/8591515/how-do-i-detect-an-instance-of-an-object-in-an-image/8594330#8594330">this</a> question, as well as the famous <a href="https://stackoverflow.com/questions/8479058/how-do-i-find-waldo-with-mathematica">waldo</a> question.</p>
<p>Another option is not to use all the pixels for comparison, but rather only the features that are easier to find and more likely to be unique. This would require a feature descriptor like <a href="http://en.wikipedia.org/wiki/Scale-invariant_feature_transform" rel="noreferrer">SIFT</a>, <a href="http://en.wikipedia.org/wiki/SURF" rel="noreferrer">SURF</a> or one of many <a href="http://docs.opencv.org/modules/features2d/doc/feature_detection_and_description.html" rel="noreferrer">others</a>. You would need to find all the features in both images and then look for features that have similar positions to those in the template image. With this approach I suggest you use <a href="http://code.google.com/p/javacv/" rel="noreferrer">JavaCV</a>.</p>
<p>The random guessing approach you mentioned should work fast when it is possible, but unfortunately it isn't generally applicable as it will only be useful with certain image combinations that produce a close match near the correct location. </p>
<p>Unless you use an external library, the simplest method in Java would be what I would call a brute-force approach, although it is a bit slow. The brute-force approach simply involves searching the whole image for the sub-region that best matches the image you are looking for. I'll explain this approach further. First you need to define how to determine the similarity between two equally sized images. This can be done by summing the differences between the pixel's colours which requires a definition for the difference between RGB values. </p>
<h3>Colour similarity</h3>
<p>One way of determining the difference between two RGB values is to use the euclidean distance: </p>
<blockquote>
<p><code>sqrt( (r1-r2)^2 + (g1-g2)^2 + (b1-b2)^2 )</code></p>
</blockquote>
<p>There are different colour spaces than RGB that can be used, but since your sub-image is most likely near identical (instead of just visually similar), this should work fine. If you have an ARGB colour space and you don't want semi-transparent pixels to influence your results as much, you can use:</p>
<blockquote>
<p><code>a1 * a2 * sqrt( (r1-r2)^2 + (g1-g2)^2 + (b1-b2)^2 )</code></p>
</blockquote>
<p>which will give a smaller value if the colours have transparency (assuming <code>a1</code> and <code>a2</code> are between 0 and 1). I would suggest that you use transparency instead of white areas and to use the PNG file format since it doesn't use lossy compression that subtly distorts the colours in the image.</p>
<h3>Comparing images</h3>
<p>To compare equally-sized images you can sum the difference between their individual pixels. This sum is then a measure of the difference and you can search for the region in the image with the lowest difference measure. It becomes harder if you don't even know whether the image contains the sub-image, but this would be indicated by the best match having a high difference measure. If you want, you could also normalize the difference measure to lie between 0 and 1 by dividing it by the size of the sub-image and the maximum possible RGB difference (sqrt(3) with the euclidean distance and RGB values from 0 to 1). Zero would then be an identical match and anything close to one would be as different as possible.</p>
<h3>Brute-force implementation</h3>
<p>Here's a simple implementation that uses the brute-force approach to search the image. With your example images it found the location at (139,55) to be the top-left location of the region with the best match (which looks correct). It took about 10 to 15 seconds to run on my PC and the normalized difference measure of the location was around 0.57.
</p>
<pre><code> /**
* Finds the a region in one image that best matches another, smaller, image.
*/
public static int[] findSubimage(BufferedImage im1, BufferedImage im2){
int w1 = im1.getWidth(); int h1 = im1.getHeight();
int w2 = im2.getWidth(); int h2 = im2.getHeight();
assert(w2 <= w1 && h2 <= h1);
// will keep track of best position found
int bestX = 0; int bestY = 0; double lowestDiff = Double.POSITIVE_INFINITY;
// brute-force search through whole image (slow...)
for(int x = 0;x < w1-w2;x++){
for(int y = 0;y < h1-h2;y++){
double comp = compareImages(im1.getSubimage(x,y,w2,h2),im2);
if(comp < lowestDiff){
bestX = x; bestY = y; lowestDiff = comp;
}
}
}
// output similarity measure from 0 to 1, with 0 being identical
System.out.println(lowestDiff);
// return best location
return new int[]{bestX,bestY};
}
/**
* Determines how different two identically sized regions are.
*/
public static double compareImages(BufferedImage im1, BufferedImage im2){
assert(im1.getHeight() == im2.getHeight() && im1.getWidth() == im2.getWidth());
double variation = 0.0;
for(int x = 0;x < im1.getWidth();x++){
for(int y = 0;y < im1.getHeight();y++){
variation += compareARGB(im1.getRGB(x,y),im2.getRGB(x,y))/Math.sqrt(3);
}
}
return variation/(im1.getWidth()*im1.getHeight());
}
/**
* Calculates the difference between two ARGB colours (BufferedImage.TYPE_INT_ARGB).
*/
public static double compareARGB(int rgb1, int rgb2){
double r1 = ((rgb1 >> 16) & 0xFF)/255.0; double r2 = ((rgb2 >> 16) & 0xFF)/255.0;
double g1 = ((rgb1 >> 8) & 0xFF)/255.0; double g2 = ((rgb2 >> 8) & 0xFF)/255.0;
double b1 = (rgb1 & 0xFF)/255.0; double b2 = (rgb2 & 0xFF)/255.0;
double a1 = ((rgb1 >> 24) & 0xFF)/255.0; double a2 = ((rgb2 >> 24) & 0xFF)/255.0;
// if there is transparency, the alpha values will make difference smaller
return a1*a2*Math.sqrt((r1-r2)*(r1-r2) + (g1-g2)*(g1-g2) + (b1-b2)*(b1-b2));
}
</code></pre>
<p>I haven't looked, but maybe one of these Java image processing libraries could also be of some use:</p>
<ul>
<li><a href="http://marvinproject.sourceforge.net/en/index.html" rel="noreferrer">Marvin project</a></li>
<li><a href="http://rsbweb.nih.gov/ij/docs/concepts.html" rel="noreferrer">ImageJ</a></li>
</ul>
<p>If speed is really important I think the best approach would be an implementation using cross-correlation or feature descriptors that uses an external library.</p> |
12,399,281 | Select from union tsql | <p>Is it possible to select from the result of a union? For example I'm trying to do something like:</p>
<pre><code>SELECT A
FROM
(
SELECT A, B FROM TableA
UNION
SELECT A, B FROM TableB
)
WHERE B > 'some value'
</code></pre>
<p>Am I missing anything or making an assumption about how this works? I'm using MSSQL 2005 so any solution will need to conform to what I can do there.</p> | 12,399,320 | 2 | 5 | null | 2012-09-13 04:09:17.5 UTC | 7 | 2012-09-13 04:26:04.723 UTC | null | null | null | null | 1,461,350 | null | 1 | 34 | sql|sql-server-2005|union | 65,529 | <p>You should give <em>alias</em> to your table. So try this:</p>
<pre><code>SELECT A
FROM
(
SELECT A, B FROM TableA
UNION
SELECT A, B FROM TableB
) AS tbl
WHERE B > 'some value'
</code></pre> |
19,151,247 | Ignoring folder meta files on version control | <p>Unity creates and deletes meta files for <em>folders</em> inside the Asset folder.</p>
<p>That can create an annoying situation when using version control (that you can skip and go to the questions): someone creates a folder of files that will be ignored but forget to ignore the folder's meta file. Unity creates the meta file and this person adds the meta to version control. Another person gets the changesets and, since they don't have the folder, <em>their</em> Unity deletes the meta file and they remove the meta file from version control. Not everyone in the team understand this, so the process is perpetuated in a loop from hell.</p>
<p>Surprisingly this happens all the time. So, two questions:</p>
<ol>
<li>Is it important to version folder meta files? </li>
<li>Is there a way to automatically ignore folder meta files - particularly on git or mercurial?</li>
</ol> | 19,157,675 | 4 | 5 | null | 2013-10-03 05:12:39.233 UTC | 19 | 2022-02-15 23:02:12.95 UTC | 2019-09-10 03:03:16.823 UTC | null | 534,006 | null | 534,006 | null | 1 | 75 | git|version-control|mercurial|unity3d | 55,471 | <p>The <a href="http://docs.unity3d.com/Documentation/Manual/ExternalVersionControlSystemSupport.html" rel="noreferrer">Unity docs</a> say:</p>
<blockquote>
<p>When creating new assets, make sure both the asset itself and the associated .meta file is added to version control. </p>
</blockquote>
<p>For me this is reason enough to put them under version control. I see two approaches to solve the problem:</p>
<ul>
<li>Organisational: Set up a naming convention for local folders like starting with "_". But we all know that this won't work ;-)</li>
<li>Install a client side <a href="http://git-scm.com/book/en/Customizing-Git-Git-Hooks" rel="noreferrer">pre-commit hook</a> on all machines. I haven't done this yet but it seems promising. </li>
</ul>
<p>I just played around with the different git commands, the following could be useful:
The git hook script shoud first check if .gitignore has changed by:</p>
<pre><code>git diff-index --cached --name-only HEAD | grep ".gitignore"
</code></pre>
<p>Print out directory names of all newly added lines in .gitignore if they are located under the Assets folder:</p>
<pre><code>git diff --cached --word-diff=plain .gitignore | grep -o -e "{+\/.*\/Assets\/.*+}" | cut -d + -f 2
</code></pre>
<hr>
<p><strong>Update</strong></p>
<p>I just wrote such a pre-commit hook :-) See the GitHub repository <a href="https://github.com/kayy/git-pre-commit-hook-unity-assets/tree/master" rel="noreferrer">git-pre-commit-hook-unity-assets</a> for code and my <a href="http://www.scio.de/en/blog-a-news/scio-development-blog-en/entry/git-pre-commit-hook-for-ignored-unity-asset-folders" rel="noreferrer">blog posting</a> about it for more details.</p> |
3,326,665 | Example of using Audio Queue Services | <p>I am seeking an example of using Audio Queue Services.</p>
<p>I would like to create a sound using a mathematical equation and then hear it.</p> | 3,350,353 | 3 | 0 | null | 2010-07-24 20:01:30.887 UTC | 20 | 2016-11-20 01:36:38.337 UTC | 2012-07-30 15:04:55.797 UTC | null | 322,283 | null | 318,205 | null | 1 | 18 | objective-c|audio|core-audio|audioqueueservices | 30,116 | <p>Here's my code for generating sound from a function. I'm assuming you know how to use AudioQueue services, set up an AudioSession, and properly start and stop an audio output queue. </p>
<p>Here's a snippet for setting up and starting an output AudioQueue:</p>
<pre><code>// Get the preferred sample rate (8,000 Hz on iPhone, 44,100 Hz on iPod touch)
size = sizeof(sampleRate);
err = AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
if (err != noErr) NSLog(@"AudioSessionGetProperty(kAudioSessionProperty_CurrentHardwareSampleRate) error: %d", err);
//NSLog (@"Current hardware sample rate: %1.0f", sampleRate);
BOOL isHighSampleRate = (sampleRate > 16000);
int bufferByteSize;
AudioQueueBufferRef buffer;
// Set up stream format fields
AudioStreamBasicDescription streamFormat;
streamFormat.mSampleRate = sampleRate;
streamFormat.mFormatID = kAudioFormatLinearPCM;
streamFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
streamFormat.mBitsPerChannel = 16;
streamFormat.mChannelsPerFrame = 1;
streamFormat.mBytesPerPacket = 2 * streamFormat.mChannelsPerFrame;
streamFormat.mBytesPerFrame = 2 * streamFormat.mChannelsPerFrame;
streamFormat.mFramesPerPacket = 1;
streamFormat.mReserved = 0;
// New output queue ---- PLAYBACK ----
if (isPlaying == NO) {
err = AudioQueueNewOutput (&streamFormat, AudioEngineOutputBufferCallback, self, nil, nil, 0, &outputQueue);
if (err != noErr) NSLog(@"AudioQueueNewOutput() error: %d", err);
// Enqueue buffers
//outputFrequency = 0.0;
outputBuffersToRewrite = 3;
bufferByteSize = (sampleRate > 16000)? 2176 : 512; // 40.5 Hz : 31.25 Hz
for (i=0; i<3; i++) {
err = AudioQueueAllocateBuffer (outputQueue, bufferByteSize, &buffer);
if (err == noErr) {
[self generateTone: buffer];
err = AudioQueueEnqueueBuffer (outputQueue, buffer, 0, nil);
if (err != noErr) NSLog(@"AudioQueueEnqueueBuffer() error: %d", err);
} else {
NSLog(@"AudioQueueAllocateBuffer() error: %d", err);
return;
}
}
// Start playback
isPlaying = YES;
err = AudioQueueStart(outputQueue, nil);
if (err != noErr) { NSLog(@"AudioQueueStart() error: %d", err); isPlaying= NO; return; }
} else {
NSLog (@"Error: audio is already playing back.");
}
</code></pre>
<p>Here's the part that generates the tone:</p>
<pre><code>// AudioQueue output queue callback.
void AudioEngineOutputBufferCallback (void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) {
AudioEngine *engine = (AudioEngine*) inUserData;
[engine processOutputBuffer:inBuffer queue:inAQ];
}
- (void) processOutputBuffer: (AudioQueueBufferRef) buffer queue:(AudioQueueRef) queue {
OSStatus err;
if (isPlaying == YES) {
[outputLock lock];
if (outputBuffersToRewrite > 0) {
outputBuffersToRewrite--;
[self generateTone:buffer];
}
err = AudioQueueEnqueueBuffer(queue, buffer, 0, NULL);
if (err == 560030580) { // Queue is not active due to Music being started or other reasons
isPlaying = NO;
} else if (err != noErr) {
NSLog(@"AudioQueueEnqueueBuffer() error %d", err);
}
[outputLock unlock];
} else {
err = AudioQueueStop (queue, NO);
if (err != noErr) NSLog(@"AudioQueueStop() error: %d", err);
}
}
-(void) generateTone: (AudioQueueBufferRef) buffer {
if (outputFrequency == 0.0) {
memset(buffer->mAudioData, 0, buffer->mAudioDataBytesCapacity);
buffer->mAudioDataByteSize = buffer->mAudioDataBytesCapacity;
} else {
// Make the buffer length a multiple of the wavelength for the output frequency.
int sampleCount = buffer->mAudioDataBytesCapacity / sizeof (SInt16);
double bufferLength = sampleCount;
double wavelength = sampleRate / outputFrequency;
double repetitions = floor (bufferLength / wavelength);
if (repetitions > 0.0) {
sampleCount = round (wavelength * repetitions);
}
double x, y;
double sd = 1.0 / sampleRate;
double amp = 0.9;
double max16bit = SHRT_MAX;
int i;
SInt16 *p = buffer->mAudioData;
for (i = 0; i < sampleCount; i++) {
x = i * sd * outputFrequency;
switch (outputWaveform) {
case kSine:
y = sin (x * 2.0 * M_PI);
break;
case kTriangle:
x = fmod (x, 1.0);
if (x < 0.25)
y = x * 4.0; // up 0.0 to 1.0
else if (x < 0.75)
y = (1.0 - x) * 4.0 - 2.0; // down 1.0 to -1.0
else
y = (x - 1.0) * 4.0; // up -1.0 to 0.0
break;
case kSawtooth:
y = 0.8 - fmod (x, 1.0) * 1.8;
break;
case kSquare:
y = (fmod(x, 1.0) < 0.5)? 0.7: -0.7;
break;
default: y = 0; break;
}
p[i] = y * max16bit * amp;
}
buffer->mAudioDataByteSize = sampleCount * sizeof (SInt16);
}
}
</code></pre>
<p>Something to watch out for is that your callback will be called on a non-main thread, so you have to practice thread safety with locks, mutexs, or other techniques.</p> |
3,776,204 | How to find out if "debug mode" is enabled | <p>How can a Java program find out if it is running in debug mode? </p>
<p>The application should behave a bit different in regular “full speed” mode than in “debug mode” (when a debugger is attached, when running in debug mode). The application communicates over TCP with either another computer, another process, or within itself. My co-worker wants us to use <code>Socket.setSoTimeout(1000)</code> by default, so that reads from the socket can block for at most 1 second. When debugging, this is not enough of course, and the application stops working as it should. So a solution would be to set the <code>SO_TIMEOUT</code> higher, but just in debug mode (for example: unlimited). Now, I don't always set breakpoints or don't want use a debug build where I could set the “debug” property myself. Sometimes I attach the debugger (remote debugging). I'm mainly using Eclipse so a solution that just works there is OK.</p>
<p>Possible answers include: </p>
<ol>
<li><p>To find out if run in debug mode, use the following method in <code>java.lang.management.*</code> or <code>javax.management.*</code> ...</p></li>
<li><p>Your co-worker is wrong for reason X, you shouldn't set <code>SO_TIMEOUT</code> to 1 second by default.</p></li>
</ol>
<h2>Update</h2>
<p>I know about the system property approach, but I leave the question open to solve my original question.</p> | 3,778,768 | 3 | 3 | null | 2010-09-23 07:30:20.21 UTC | 6 | 2017-01-20 17:53:18.327 UTC | 2015-05-25 10:51:15.847 UTC | null | 2,461,638 | null | 382,763 | null | 1 | 41 | java|eclipse|debugging | 24,217 | <p>I found it out myself now:</p>
<pre><code>boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().
getInputArguments().toString().indexOf("jdwp") >= 0;
</code></pre>
<p>This will check if the <a href="http://download.oracle.com/javase/1.5.0/docs/guide/jpda/jdwp-spec.html" rel="noreferrer">Java Debug Wire Protocol</a> agent is used.</p> |
38,440,631 | HttpClient: The uri string is too long | <p>Given the following attempt to post data to a web service that generates PDF files, <strong><a href="https://www.html2pdfrocket.com/" rel="noreferrer">PDF rocket</a></strong> (<em>which is awesome by the way</em>).</p>
<p>I get the error <strong>Invalid URI: The uri string is too long</strong><br>
<em>Why would anyone impose an arbitrary limit on <code>POST</code>ed data?</em></p>
<pre><code>using (var client = new HttpClient())
{
// Build the conversion options
var options = new Dictionary<string, string>
{
{ "value", html },
{ "apikey", ConfigurationManager.AppSettings["pdf:key"] },
{ "MarginLeft", "10" },
{ "MarginRight", "10" }
};
// THIS LINE RAISES THE EXCEPTION
var content = new FormUrlEncodedContent(options);
var response = await client.PostAsync("https://api.html2pdfrocket.com/pdf", content);
var result = await response.Content.ReadAsByteArrayAsync();
return result;
}
</code></pre>
<p>I receive this rediculous error.</p>
<pre><code> {System.UriFormatException: Invalid URI: The Uri string is too long.
at System.UriHelper.EscapeString
at System.Uri.EscapeDataString
at System.Net.Http.FormUrlEncodedContent.Encode
at System.Net.Http.FormUrlEncodedContent.GetContentByteArray
</code></pre>
<p>This reminds me of <code>640k</code> ought to be enough... I mean <em>really?</em></p> | 38,440,832 | 4 | 6 | null | 2016-07-18 15:29:07.987 UTC | 2 | 2018-10-13 14:46:26.67 UTC | 2016-07-19 07:51:33.053 UTC | null | 231,821 | null | 231,821 | null | 1 | 28 | c#|dotnet-httpclient | 43,228 | <p>With a post can include the content in the http message instead of the URI. A uri has a max length of 2083 characters. You could send it as JSON in the http message instead of the URI which is the recommended way to send larger chunks of data in an HttpPost/HttpPut. I altered your code to make use of it. This assumes that your service you are contacting can work with JSON (.net Web Api out of the box should have no problem with this).</p>
<pre><code>using (var client = new HttpClient())
{
// Build the conversion options
var options = new
{
value = html,
apikey = ConfigurationManager.AppSettings["pdf:key"],
MarginLeft = "10",
MarginRight = "10"
};
// Serialize our concrete class into a JSON String
var stringPayload = JsonConvert.SerializeObject(options);
var content = new StringContent(stringPayload, Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.html2pdfrocket.com/pdf", content);
var result = await response.Content.ReadAsByteArrayAsync();
return result;
}
</code></pre>
<hr>
<p>Make sure to install <a href="https://stackoverflow.com/a/18784702/4684797">newtonsoft json</a>.</p> |
8,730,451 | C# - Garbage Collection | <p>Ok so I understand about the stack and the heap (values live on the Stack, references on the Heap).</p>
<p>When I declare a new instance of a Class, this lives on the heap, with a reference to this point in memory on the stack. I also know that C# does it's own Garbage Collection (ie. It determines when an instanciated class is no longer in use and reclaims the memory).</p>
<p>I have 2 questions:</p>
<ol>
<li>Is my understanding of Garbage Collection correct?</li>
<li>Can I do my own? If so is there any real benefit to doing this myself or should I just leave it.</li>
</ol>
<p>I ask because I have a method in a For loop. Every time I go through a loop, I create a new instance of my Class. In my head I visualise all of these classes lying around in a heap, not doing anything but taking up memory and I want to get rid of them as quickly as I can to keep things neat and tidy!</p>
<p>Am I understanding this correctly or am I missing something?</p> | 8,731,828 | 9 | 8 | null | 2012-01-04 16:42:40.833 UTC | 11 | 2021-07-02 21:27:42.563 UTC | 2021-07-02 21:27:42.563 UTC | null | 5,459,839 | null | 969,613 | null | 1 | 16 | c#|heap-memory|stack-memory | 19,669 | <blockquote>
<p>Ok so I understand about the stack and the heap (values live on the Stack, references on the Heap</p>
</blockquote>
<p>I don't think you understand about the stack and the heap. If values live on the stack then where does an array of integers live? Integers are values. Are you telling me that an array of integers keeps its integers on the stack? When you return an array of integers from a method, say, with ten thousand integers in it, are you telling me that those ten thousand integers are copied onto the stack?</p>
<p>Values live on the stack when they live on the stack, and live on the heap when they live on the heap. The idea that the <em>type</em> of a thing has to do with <em>the lifetime of its storage</em> is nonsense. Storage locations that are <em>short lived</em> go on the stack; storage locations that are <em>long lived</em> go on the heap, and that is independent of their type. A long-lived int has to go on the heap, same as a long-lived instance of a class.</p>
<blockquote>
<p>When I declare a new instance of a Class, this lives on the heap, with a reference to this point in memory on the stack. </p>
</blockquote>
<p>Why does the reference have to go on the stack? Again, <em>the lifetime of the storage of the reference has nothing to do with its type</em>. If the storage of the reference is long-lived then the reference goes on the heap.</p>
<blockquote>
<p>I also know that C# does it's own Garbage Collection (ie. It determines when an instanciated class is no longer in use and reclaims the memory).</p>
</blockquote>
<p>The C# language does not do so; the CLR does so.</p>
<blockquote>
<p>Is my understanding of Garbage Collection correct? </p>
</blockquote>
<p>You seem to believe a lot of lies about the stack and the heap, so odds are good no, it's not.</p>
<blockquote>
<p>Can I do my own? </p>
</blockquote>
<p>Not in C#, no.</p>
<blockquote>
<p>I ask because I have a method in a For loop. Every time I go through a loop, I create a new instance of my Class. In my head I visualise all of these classes lying around in a heap, not doing anything but taking up memory and I want to get rid of them as quickly as I can to keep things neat and tidy!</p>
</blockquote>
<p>The whole point of garbage collection is to free you from worrying about tidying up. That's why its called "automatic garbage collection". It tidies for you.</p>
<p>If you are worried that your loops are creating <em>collection pressure</em>, and you wish to avoid collection pressure for performance reasons then I advise that you pursue a <em>pooling</em> strategy. It would be wise to start with an <em>explicit</em> pooling strategy; that is:</p>
<pre><code>while(whatever)
{
Frob f = FrobPool.FetchFromPool();
f.Blah();
FrobPool.ReturnToPool(f);
}
</code></pre>
<p>rather than attempting to do automatic pooling using a resurrecting finalizer. I advise against both finalizers and object resurrection in general unless you are an expert on finalization semantics.</p>
<p>The pool of course allocates a new Frob if there is not one in the pool. If there is one in the pool, then it hands it out and removes it from the pool until it is put back in. (If you forget to put a Frob back in the pool, the GC will get to it eventually.) By pursuing a pooling strategy you cause the GC to eventually move all the Frobs to the generation 2 heap, instead of creating lots of collection pressure in the generation 0 heap. The collection pressure then disappears because no new Frobs are allocated. If something else is producing collection pressure, the Frobs are all safely in the gen 2 heap where they are rarely visited.</p>
<p>This of course is the exact opposite of the strategy you described; the whole point of the pooling strategy is to <em>cause objects to hang around forever</em>. Objects hanging around forever is a <em>good</em> thing if you're going to use them. </p>
<p>Of course, do not make these sorts of changes before you know via profiling that you have a performance problem due to collection pressure! It is rare to have such a problem on the desktop CLR; it is rather more common on the compact CLR.</p>
<p>More generally, if you are the kind of person who feels uncomfortable having a memory manager clean up for you on its schedule, then C# is not the right language for you. Consider C instead.</p> |
11,007,024 | Cygwin SVN: E200030: SQLite disk I/O error | <p>When I use Subversion in Cygwin to update some repository, some directories update with success, while some other one gets a failure with the error message:</p>
<blockquote>
<p>svn: E200030: sqlite: disk I/O error</p>
</blockquote>
<p>When doing <code>svn update</code> again for the same repository, a different directory can get the same error. Sometimes, there is a SVN instruction after the above error message.</p> | 11,887,905 | 5 | 1 | null | 2012-06-13 01:19:23.763 UTC | 11 | 2020-02-11 19:05:49.117 UTC | 2012-08-19 11:34:05.073 UTC | null | 63,550 | null | 735,708 | null | 1 | 26 | sqlite|svn|cygwin | 23,566 | <p>This happened due to <a href="http://cygwin.com/ml/cygwin/2012-04/msg00079.html" rel="noreferrer">a change someone wanted</a> in Cygwin's <a href="http://sqlite.org/" rel="noreferrer">SQLite</a> package. I was the maintainer of that package when this question was asked, and I made the change that caused this symptom.</p>
<p>The change was released as Cygwin SQLite version <code>3.7.12.1-1</code>, and it fixed that one person's problem, but it had this bad side effect of preventing Cygwin's Subversion package from cooperating with native Windows Subversion implementations.</p>
<h2>What Happened?</h2>
<p>The core issue here is that <a href="http://subversion.apache.org/docs/release-notes/1.7.html#wc-ng" rel="noreferrer">Subversion 1.7 changed the working copy on-disk format</a>. Part of that change involves a new SQLite database file, <code>.svn/wc.db</code>. Now, in order to implement <a href="http://sqlite.org/faq.html#q5" rel="noreferrer">SQLite's concurrency guarantees</a>, SQLite locks the database file while it is accessing it.</p>
<p>That's all fine and sensible, but you run into a problem when you try to mix Windows native and POSIX <a href="http://en.wikipedia.org/wiki/File_locking" rel="noreferrer">file locking semantics</a>. On Windows, file locking almost always means <a href="http://en.wikipedia.org/wiki/File_locking#In_Microsoft_Windows" rel="noreferrer">mandatory locking</a>, but on Linux systems — which Cygwin is trying to emulate — locking usually means <a href="http://en.wikipedia.org/wiki/File_locking#In_Unix-like_systems" rel="noreferrer">advisory locking</a> instead.</p>
<p>That helps understand where the "disk I/O error" comes from.</p>
<p>The Cygwin SQLite <code>3.7.12.1-1</code> change was to build the library in "Unix mode" instead of "Cygwin mode." In Cygwin mode, the library uses Windows native file locking, which goes against the philosophy of Cygwin: where possible, Cygwin packages call POSIX functions instead of direct to the Windows API, so that <code>cygwin1.dll</code> can provide the proper POSIX semantics.</p>
<p>POSIX advisory file locking is exactly what you want with SQLite when all the programs accessing the SQLite DBs in question are built with Cygwin, which is the default assumption within Cygwin. But, when you run a Windows native Subversion program like TortoiseSVN alongside a pure POSIX Cygwin <code>svn</code>, you get a conflict. When the TortoiseSVN Windows Explorer shell extension has the <code>.svn/wc.db</code> file locked with a mandatory lock and Cygwin <code>svn</code> comes along and tries an advisory lock on it, it fails immediately. Cygwin <code>svn</code> assumes a lock attempt will either succeed immediately or block until it can succeed, so it incorrectly interprets the lock failure as a disk I/O error.</p>
<h2>How Did We Solve This Dilemma?</h2>
<p>Within Cygwin, we always try to play nice with Windows native programs where possible. The trick was to find a way to do that, while still playing nice with Cygwin programs, too.</p>
<p>Not everyone agreed that we should attempt this. "Cygwin SQLite is part of Cygwin, so it only needs to work well with other Cygwin programs," one group would say. The counterpartisans would reply, "Cygwin runs on Windows, so it has to perform well with other Windows programs."</p>
<p>Fortunately, we came up with a way to make both groups happy.</p>
<p>As part of the Cygwin SQLite <code>3.7.17-x</code> packaging effort, I tested <a href="http://cygwin.com/ml/cygwin-announce/2013-06/msg00006.html" rel="noreferrer">a new feature</a> that <a href="https://en.wikipedia.org/wiki/Cygwin#History" rel="noreferrer">Corinna Vinschen</a> added to <code>cygwin1.dll</code> version 1.7.19. It allowed a program to request mandatory file locking through the BSD file locking APIs. My part of the change was to make Cygwin SQLite turn this feature on and off at the user's direction, allowing the same package to meet the needs of both the Cygwin-centric and Windows-native camps.</p>
<p>This Cygwin DLL feature was further improved in 1.7.20, and I released Cygwin SQLite <code>3.7.13-3</code> using the finalized locking semantics. This version allowed a choice of three locking strategies: POSIX advisory locking, BSD advisory locking, and BSD/Cygwin mandatory locking. So far, the latter strategy has proven to be completely compatible with native Windows locking.</p>
<p>Later, when Jan Nijtmans took over maintenance of Cygwin SQLite, he further enhanced this mechanism by fully integrating it with the <a href="https://www.sqlite.org/vfs.html" rel="noreferrer">SQLite VFS layer</a>. This allowed a fourth option: the native Windows locking that Cygwin SQLite used to use before we started on this journey. This is mostly a hedge against the possibility that the BSD/Windows locking strategy doesn't cooperate cleanly with a native Windows SQLite program. So far as I know, no one has ever needed to use this option, but it's nice to know it's there.</p>
<h2>Alternate Remedy</h2>
<p>If the conflict you're having is between Cygwin's command line <code>svn</code> and the TortoiseSVN Windows Explorer shell extension, there's another option to fix it. TortoiseSVN ships with native Windows Subversion command-line programs as well. If you put these in your <code>PATH</code> ahead of Cygwin's <code>bin</code> directory, you shouldn't run into this problem at all.</p> |
10,899,725 | D3 force directed graph with drag and drop support to make selected node position fixed when dropped | <p>Example on a force direct graph can be found here: <a href="http://bl.ocks.org/950642">http://bl.ocks.org/950642</a></p>
<p>How can I easily add support for drag and drop?
It should set the node to fixed with current location of where it dropped it.
It is important that rest of the nodes still uses the 'force directed mode' to position rest of the nodes in the graph automatically</p>
<p><a href="https://github.com/mbostock/d3/wiki/Force-Layout">https://github.com/mbostock/d3/wiki/Force-Layout</a></p>
<p>I've played around a bit without success, and wondering if anyone is able to give me a quick example on how to add such support as explained above.</p> | 10,919,260 | 1 | 3 | null | 2012-06-05 14:59:38.653 UTC | 11 | 2014-02-02 01:26:01.837 UTC | 2014-02-02 01:26:01.837 UTC | null | 3,052,751 | null | 653,233 | null | 1 | 26 | d3.js|drag-and-drop|force-layout | 18,795 | <p>Finally got it working after figuring out it is not ideal to fight with two "drag" listeners (your own, and force.drag) attached to the nodes!</p>
<p>Much better to only have your own "drag"-listener and call tick() manually which is the key feature of getting the force graph to position the nodes for you on every new node position on the node your dragging. </p>
<p>Working example: <a href="http://bl.ocks.org/2883411" rel="noreferrer">http://bl.ocks.org/2883411</a></p> |
11,183,805 | Run bash script from another script without waiting for script to finish executing? | <p>Is there any way to execute two bash scripts without the first one blocking? The following does not work:</p>
<pre><code>exec ./script1.sh #this blocks!
exec ./script2.sh
</code></pre> | 11,183,822 | 2 | 0 | null | 2012-06-25 05:17:42.723 UTC | 7 | 2019-04-12 04:00:18.097 UTC | null | null | null | null | 963,396 | null | 1 | 26 | linux|bash|shell|process | 63,943 | <p>Put <code>&</code> at the end of the line.</p>
<pre><code>./script1.sh & #this doesn't blocks!
./script2.sh
</code></pre> |
11,129,401 | Debug Gradle plugins with IntelliJ | <h2>Problem</h2>
<p><strong>I want to use the interactive debugger with IntelliJ.</strong> <strike>Unfortunately, I can't convince IntelliJ to load and compile the plugin. However,</strike> I can do <code>gradle clean build</code> and the plugin builds and runs its tests as expected.</p>
<p>Specifically, I'm trying to debug local changes to <a href="https://github.com/eriwen/gradle-js-plugin.git" rel="noreferrer">gradle-js-plugin</a> <strike>and IntelliJ says it can't find <code>com.google.javascript.jscomp.CompilerOptions</code> as well as <code>spock.lang.Specification</code>. (I'm thinking maybe it's something about the way they are loaded, but that's a guess.)</strike> </p>
<p><br></p>
<h2>Things I've tried</h2>
<p><em>NOTE:</em> I didn't revert any processes between steps.</p>
<h3>0. My First Guess</h3>
<p>I noticed <a href="http://docs.codehaus.org/display/GRADLE/How+to+run+the+Gradle+project+in+IntelliJ+against+any+Gradle+build" rel="noreferrer">a howto</a> on <a href="http://docs.codehaus.org/" rel="noreferrer">docs.codehaus.org</a>. IntelliJ couldn't find <code>org.gradle.launcher.GradleMain</code>, so I've adapted it to use <code>GradleLauncher</code> with the following:</p>
<pre><code>import org.gradle.GradleLauncher
class GradleScriptRunner {
public static void main(String[] args) {
GradleLauncher.newInstance(
"-p",
"/path/to/gradle-js-plugin/src/test/resources/build.gradle",
"clean assemble"
)
}
}
</code></pre>
<p>Per <a href="http://gradle.org/docs/current/javadoc/org/gradle/GradleLauncher.html" rel="noreferrer">GradleLauncher's documentation</a>.</p>
<p><strong>Outcome:</strong> IntelliJ won't compile the project.</p>
<p><hr></p>
<h3>1. Per <a href="https://stackoverflow.com/a/11129708/455581">Peter Niederwieser's answer</a> Fix idea project & debug via plugin</h3>
<h3>Steps</h3>
<ol>
<li><code>~# cd /path/to/gradle-js-plugin && gradle cleanIdea idea</code></li>
<li>Opened the newly created project and attempted to debug using the ScriptRunner from step 0.</li>
</ol>
<p><strong>Outcome:</strong> Project compiles (<em>yay!</em>), but I can only hit breakpoints in <code>GradleScriptRunner.groovy</code>.</p>
<p><hr></p>
<h3>2. Per <a href="https://stackoverflow.com/a/11129708/455581">Peter Niederwieser's answer</a> run gradle CLI w/ special options</h3>
<p>1 & 2. Merged for clarity:</p>
<pre><code>~# export GRADLE_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
~# gradle clean assemble
Listening for transport dt_socket at address: 5005
</code></pre>
<ol start="3">
<li>Configure IntelliJ to connect to this port and start debugging (see image):
<img src="https://i.stack.imgur.com/aDwVA.png" alt="How I configured the debugger"></li>
</ol>
<p><strong>For this step I tried the following .gradle file configurations:</strong></p>
<p><em>1. Use only build.gradle</em></p>
<p>--build.gradle--</p>
<pre><code>apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'maven'
apply plugin: 'js'
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile findProject "/path/to/gradle-js-plugin"
}
}
repositories {
mavenLocal()
mavenCentral()
}
</code></pre>
<p><strong>Outcome:</strong> </p>
<pre><code>FAILURE: Build failed with an exception.
* Where:
Build file '/path/to/gradle-js-plugin/src/test/resources/build.gradle' line: 13
* What went wrong:
A problem occurred evaluating root project 'resources'.
> No such property: findProject for class: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 8 mins 50.498 secs
</code></pre>
<p><em>2. Use both build.gradle and settings.gradle</em></p>
<p>--settings.gradle--</p>
<pre><code>include "/path/to/gradle-js-plugin"
</code></pre>
<p>--build.gradle--</p>
<pre><code>apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'maven'
apply plugin: 'js'
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
}
repositories {
mavenLocal()
mavenCentral()
}
</code></pre>
<p><strong>Outcome:</strong></p>
<pre><code>FAILURE: Build failed with an exception.
* Where:
Build file '/path/to/gradle-js-plugin/src/test/resources/build.gradle' line: 5
* What went wrong:
A problem occurred evaluating root project 'resources'.
> Plugin with id 'js' not found.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 13.553 secs
</code></pre>
<p><hr></p>
<h2>My Setup</h2>
<h3>Gradle</h3>
<pre><code>~# gradle -v
------------------------------------------------------------
Gradle 1.0
------------------------------------------------------------
Gradle build time: Tuesday, June 12, 2012 12:56:21 AM UTC
Groovy: 1.8.6
Ant: Apache Ant(TM) version 1.8.2 compiled on December 20 2010
Ivy: 2.2.0
JVM: 1.7.0_04 (Oracle Corporation 23.0-b21)
OS: Linux 3.2.0-2-amd64 amd64
</code></pre>
<h3>Java</h3>
<pre><code>~# java -version
java version "1.7.0_04"
Java(TM) SE Runtime Environment (build 1.7.0_04-b20)
Java HotSpot(TM) 64-Bit Server VM (build 23.0-b21, mixed mode)
</code></pre>
<h3>IntelliJ</h3>
<pre><code>IntelliJ IDEA Ultimate 117.499 w/ Bundled Gradle plugin
</code></pre>
<p></p>
<h1>Hoping for</h1>
<p>Any tips that'll get me into debug mode within the plugin.</p> | 11,129,708 | 3 | 1 | null | 2012-06-20 23:01:34.99 UTC | 24 | 2015-03-25 10:34:28.53 UTC | 2017-05-23 10:31:30.497 UTC | null | -1 | null | 455,581 | null | 1 | 43 | debugging|intellij-idea|gradle | 36,086 | <p>First, it sounds like there is a problem with your IDEA Gradle project. If you run <code>gradlew cleanIdea idea</code> and then open the generated project from IDEA (rather than using the JetGradle plugin), all should be fine.</p>
<p>Second, if you still can't get the GradleMain/GradleLauncher (the former class <em>does</em> exist) approach to work, another approach is to debug the Gradle build as an external application. For that you need to add <code>-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005</code> to the <code>GRADLE_OPTS</code> environment variable, run the build from the command line, wait until it suspends, and then start a "Remote" run configuration (with corresponding settings) from IDEA. At that point the debugger should connect to the Gradle process and you should be up and running.</p> |
11,074,141 | Using function call in foreach loop | <p>Are there any issues, with regards to efficiency, for using a function call in a foreach loop. For example:</p>
<pre><code>foreach ($this->getValues() as $value) {
//Do something with $value
}
</code></pre>
<p>versus</p>
<pre><code>$values = $this->getValues();
foreach ($values as $value) {
//Do something with $value
}
</code></pre>
<p>Essentially, is php clever enough to call $this->getValues() only once in the first example, or does it call it on each iteration. If it calls it on each iteration, then how does it keep track of which element its currently at,</p> | 11,074,162 | 2 | 4 | null | 2012-06-17 19:24:28.463 UTC | 6 | 2014-11-27 13:51:27.54 UTC | null | null | null | user1462195 | null | null | 1 | 46 | php | 21,003 | <p>These are both essentially the same:</p>
<pre><code>foreach ($this->getValues() as $value) {
//
}
$values = $this->getValues();
foreach ($values as $value) {
//
}
</code></pre>
<p><code>$this->getValues()</code> will only run once, as it is not inside the loop itself. If you need to use the return value of <code>getValues</code> again later, go ahead and assign it to a variable so you don't have to call the function again. If not, you don't really need a variable.</p> |
13,211,137 | Get logarithm without math log python | <p>I'm learning Python and I must do a script that generate the result of the log.</p>
<p>I know that log base x = result</p>
<p>Then I made my code.</p>
<pre><code>def log(x, base):
log_b = 2
while x != int(round(base ** log_b)):
log_b += 0.01
print log_b
return int(round(log_b))
</code></pre>
<p>But it's works very slowly. I can use other method? thanks!</p> | 13,211,215 | 6 | 6 | null | 2012-11-03 16:33:52.94 UTC | 9 | 2019-04-09 19:10:10.387 UTC | 2012-11-07 01:15:53.37 UTC | null | 322,020 | null | 1,609,625 | null | 1 | 6 | math | 27,484 | <p>One other thing you might want to consider is using the <em>Taylor series</em> of the natural logarithm:</p>
<p><img src="https://i.stack.imgur.com/2jjLR.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/xVoxm.png" alt="enter image description here"></p>
<p>Once you've approximated the natural log using a number of terms from this series, it is easy to change base:</p>
<p><img src="https://i.stack.imgur.com/CkP8Z.png" alt="enter image description here"></p>
<hr>
<p><strong><em>EDIT</em></strong>: Here's another useful identity:</p>
<p><img src="https://i.stack.imgur.com/k6FzU.png" alt="enter image description here"></p>
<p>Using this, we could write something along the lines of</p>
<pre><code>def ln(x):
n = 1000.0
return n * ((x ** (1/n)) - 1)
</code></pre>
<p>Testing it out, we have:</p>
<pre><code>print ln(math.e), math.log(math.e)
print ln(0.5), math.log(0.5)
print ln(100.0), math.log(100.0)
</code></pre>
<p>Output:</p>
<pre><code>1.00050016671 1.0
-0.692907009547 -0.69314718056
4.6157902784 4.60517018599
</code></pre>
<p>This shows our value compared to the <code>math.log</code> value (separated by a space) and, as you can see, we're pretty accurate. You'll probably start to lose some accuracy as you get very large (e.g. <code>ln(10000)</code> will be about <code>0.4</code> greater than it should), but you can always increase <code>n</code> if you need to.</p> |
13,218,019 | Generating permutations of an int array using java -- error | <p>I am writing a JAVA code to generate all permutations of a integer array.
Though I am getting the number of permutations right, the permutations themselves are not correct.</p>
<p>On running I obtain:</p>
<pre><code>Input array Length
3
1
2
3
0Permutation is
1, 2, 3,
##########################
1Permutation is
1, 3, 2,
##########################
2Permutation is
3, 1, 2,
##########################
3Permutation is
3, 2, 1,
##########################
4Permutation is
1, 2, 3,
##########################
5Permutation is
1, 3, 2,
##########################
6 number of permutations obtained
BUILD SUCCESSFUL (total time: 3 seconds)
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
</code></pre> | 13,218,111 | 9 | 6 | null | 2012-11-04 11:11:40.527 UTC | 2 | 2021-04-29 09:40:19.81 UTC | 2017-04-30 09:05:35.923 UTC | null | 1,033,581 | null | 1,683,651 | null | 1 | 8 | java | 39,515 | <pre><code>int temp=input[i];
input[i]=input[startindex];
input[startindex]=temp;
Permute(input, startindex+1);
</code></pre>
<p>You've swapped an element before calling Permute but you need to swap it back again afterwards to keep consistent positions of elements across iterations of the for-loop.</p> |
13,114,881 | Set array of object to null in C++ | <p>Suppose I have an array of objects of type Foo in C++:</p>
<pre><code>Foo array[10];
</code></pre>
<p>In Java, I can set an object in this array to null simply by:</p>
<pre><code>array[0] = null //the first one
</code></pre>
<p>How can I do this in C++?</p> | 13,114,890 | 4 | 1 | null | 2012-10-29 01:29:15.117 UTC | 5 | 2018-10-13 20:45:35.553 UTC | 2012-10-29 01:33:36.053 UTC | null | 522,444 | null | 1,748,450 | null | 1 | 11 | c++|arrays|object|null | 60,889 | <p>Use pointers instead:</p>
<pre><code>Foo *array[10];
// Dynamically allocate the memory for the element in `array[0]`
array[0] = new Foo();
array[1] = new Foo();
...
// Make sure you free the memory before setting
// the array element to point to null
delete array[1];
delete array[0];
// Set the pointer in `array[0]` to point to nullptr
array[1] = nullptr;
array[0] = nullptr;
// Note the above frees the memory allocated for the first element then
// sets its pointer to nullptr. You'll have to do this for the rest of the array
// if you want to set the entire array to nullptr.
</code></pre>
<p>Note that you need to consider memory management in C++ because unlike Java, it does not have a Garbage Collector that will automatically clean up memory for you when you set a reference to nullptr. Also, nullptr is the modern and proper C++ way to do it, as rather than always is a pointer type rather than just zero.</p> |
12,946,150 | How to bring my application to the front? | <p>I know all the reasons why it is a bad idea. I dislike it if an application steals input focus, but this is for purely personal use and I want it to happen; it will not disturb anything. </p>
<p>(for the curious: I am running unit tests in NetBeans, which generate a log file. When my background application sees the log file's timestamp change I want it to parse the log file and come to the front to show the results).</p>
<p><a href="https://stackoverflow.com/questions/5282588/how-can-i-bring-my-application-window-to-the-front">This question</a> did not help, nor did googling. It seems that <code>BringToFront()</code> hasn't worked for a long time and I can't find any alternative that does.</p>
<p>Any ideas?</p> | 12,946,301 | 8 | 8 | null | 2012-10-18 02:19:12.72 UTC | 9 | 2022-04-04 13:42:45.617 UTC | 2017-09-01 10:25:25.667 UTC | null | 192,910 | null | 192,910 | null | 1 | 24 | delphi|delphi-xe2 | 40,500 | <p>You can't do this reliably. Windows XP had a workaround that would allow it, but versions since then prohibit it for the most part (see note below). This is expressly stated in the remarks section of the MSDN documentation on <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms633539%28v=vs.85%29.aspx"><code>SetForegroundWindow</code></a>:</p>
<blockquote>
<p>The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:</p>
<ul>
<li>The process is the foreground process.</li>
<li>The process was started by the foreground process.</li>
<li>The process received the last input event.</li>
<li>There is no foreground process.</li>
<li>The foreground process is being debugged.</li>
<li>The foreground is not locked (see LockSetForegroundWindow).</li>
<li>The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).</li>
<li>No menus are active.</li>
</ul>
<p>An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user.</p>
</blockquote>
<p>Note the final paragraph of the quoted documentation, especially the first sentence.</p>
<p>The problem with </p>
<blockquote>
<p>this is for purely personal use and I want it to happen; it will not disturb anything. </p>
</blockquote>
<p>is that any application could try to do the same thing. How does "purely personal use" tell it's you personally and not just any application? :-) </p>
<p>Note: I've tried everything I can think of to get the IDE's documentation to show in the foreground when I click the help toolbutton, but all I can get is the flashing taskbar button (and I as the user want it to do so).</p> |
12,836,043 | Inserting a record into a table with a column declared with the SERIAL function | <p>My database is using PostgreSQL. One table is using the <code>serial</code> auto-increment macro. If I want to insert a record into the table, do I still need to specify that value, or it is be automatically assigned for me? </p>
<pre><code>CREATE TABLE dataset
(
id serial NOT NULL,
age integer NOT NULL,
name character varying(32) NOT NULL,
description text NOT NULL DEFAULT ''::text
CONSTRAINT dataset_pkey PRIMARY KEY (id)
);
</code></pre> | 12,836,448 | 4 | 0 | null | 2012-10-11 09:08:19.583 UTC | 6 | 2020-05-13 16:51:36.17 UTC | 2015-12-26 10:16:56.84 UTC | null | 4,694,621 | null | 1,374,478 | null | 1 | 59 | database|postgresql | 63,199 | <p>Using the <code>DEFAULT</code> keyword or by omitting the column from the <code>INSERT</code> list:</p>
<pre><code>INSERT INTO dataset (id, age, name, description)
VALUES (DEFAULT, 42, 'fred', 'desc');
INSERT INTO dataset (age, name, description)
VALUES (42, 'fred', 'desc');
</code></pre> |
12,784,766 | Check substring exists in a string in C | <p>I'm trying to check whether a string contains a substring in C like:</p>
<pre><code>char *sent = "this is my sample example";
char *word = "sample";
if (/* sentence contains word */) {
/* .. */
}
</code></pre>
<p>What is something to use instead of <code>string::find</code> in C++?</p> | 12,784,812 | 12 | 4 | null | 2012-10-08 15:28:00.25 UTC | 53 | 2022-03-15 11:02:35.8 UTC | 2017-06-02 17:46:06.59 UTC | null | 63,550 | null | 1,385,119 | null | 1 | 220 | c|string | 593,337 | <pre><code>if (strstr(sent, word) != NULL) {
/* ... */
}
</code></pre>
<p>Note that <code>strstr</code> returns a pointer to the start of the word in <code>sent</code> if the word <code>word</code> is found.</p> |
16,930,563 | Regex - match anything except specific string | <p>I need a regex (will be used in ZF2 routing, I believe it uses the preg_match of php) that matches anything except a specific string.</p>
<p>For example: I need to match anything except "red", "green" or "blue".</p>
<p>I currently have the regex: </p>
<pre><code>^(?!red|green|blue).*$
test -> match (correct)
testred -> match (correct)
red -> doesn't match (correct)
redtest -> doesn't match (incorrect)
</code></pre>
<p>In the last case, the regex is not behaving like I want. It should match "redtest" because "redtest" is not ("red", "green" or "blue").</p>
<p>Any ideas of how to fix the regex?</p> | 16,930,660 | 3 | 0 | null | 2013-06-05 02:23:03.167 UTC | 4 | 2015-09-11 12:36:58.933 UTC | 2015-06-09 11:13:23.657 UTC | null | 3,885,376 | null | 789,542 | null | 1 | 15 | regex|preg-match|regex-negation | 43,011 | <p>You can include the end of string anchor in the lookahead</p>
<pre><code> ^(?!(red|blue|green)$)
</code></pre> |
16,899,503 | Check if my IOS application is updated | <p>I need to check when my app launches if it was being updated, because i need
to make a view that only appears when the app is firstly installed to appear again after being
updated.</p> | 16,899,672 | 8 | 2 | null | 2013-06-03 14:46:31.26 UTC | 5 | 2020-11-30 08:06:23.68 UTC | 2015-10-01 14:21:51.863 UTC | null | 184,245 | null | 2,412,870 | null | 1 | 28 | ios|objective-c|swift|uiapplication | 21,791 | <p>You could save a value (e.g. the current app version number) to <code>NSUserDefaults</code> and check it every time the user starts the app.</p>
<pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *currentAppVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
NSString *previousVersion = [defaults objectForKey:@"appVersion"];
if (!previousVersion) {
// first launch
// ...
[defaults setObject:currentAppVersion forKey:@"appVersion"];
[defaults synchronize];
} else if ([previousVersion isEqualToString:currentAppVersion]) {
// same version
} else {
// other version
// ...
[defaults setObject:currentAppVersion forKey:@"appVersion"];
[defaults synchronize];
}
return YES;
}
</code></pre>
<p>The <a href="/questions/tagged/swift-2" class="post-tag" title="show questions tagged 'swift-2'" rel="tag">swift-2</a> version looks like this:</p>
<pre><code>let defaults = NSUserDefaults.standardUserDefaults()
let currentAppVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let previousVersion = defaults.stringForKey("appVersion")
if previousVersion == nil {
// first launch
defaults.setObject(currentAppVersion, forKey: "appVersion")
defaults.synchronize()
} else if previousVersion == currentAppVersion {
// same version
} else {
// other version
defaults.setObject(currentAppVersion, forKey: "appVersion")
defaults.synchronize()
}
</code></pre>
<p>The <a href="/questions/tagged/swift-3" class="post-tag" title="show questions tagged 'swift-3'" rel="tag">swift-3</a> version looks like this:</p>
<pre><code>let defaults = UserDefaults.standard
let currentAppVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let previousVersion = defaults.string(forKey: "appVersion")
if previousVersion == nil {
// first launch
defaults.set(currentAppVersion, forKey: "appVersion")
defaults.synchronize()
} else if previousVersion == currentAppVersion {
// same version
} else {
// other version
defaults.set(currentAppVersion, forKey: "appVersion")
defaults.synchronize()
}
</code></pre> |
16,868,821 | Unit testing Javascript that involves the DOM | <p>How do you go about unit testing javascript that uses and modifies the DOM?</p>
<p>I'll give an easy example. A form validator that checks for blank text fields, written in javascript and that uses JQuery. </p>
<pre><code> function Validator() {
this.isBlank = function(id) {
if ($(id).val() == '') {
return true;
} else {
return false;
}
};
this.validate = function(inputs) {
var errors = false;
for (var field in inputs) {
if (this.isBlank(inputs[field])) {
errors = true;
break;
}
}
return errors;
};
}
</code></pre>
<p>Usage:</p>
<pre><code>var validator = new Validator();
var fields = { field_1 : '#username', field_2 : '#email' };
if (!validator.validate(fields)) {
console.log('validation failed');
} else {
console.log('validation passed');
}
</code></pre>
<p>What is the best practice for attempting to unit test something like this?</p> | 16,869,139 | 3 | 4 | null | 2013-06-01 03:39:56.54 UTC | 8 | 2017-02-14 17:28:20.23 UTC | 2016-01-31 17:47:44.393 UTC | null | 1,312,635 | null | 1,312,635 | null | 1 | 33 | javascript|unit-testing | 15,600 | <p>Ideally you should split the code. The validation logic does not really require DOM access, so you would put that into its own function, and put the logic that processes the ID into a value that is then validated into another.</p>
<p>By doing this, you can more easily unit test the validation logic, and if necessary do a functional test on the whole thing using some of the tools suggested by Joseph the Dreamer.</p> |
17,129,795 | Storing TimeSpan with Entity Framework Codefirst - SqlDbType.Time overflow | <p>I'm trying to seed some constants into my DB: </p>
<pre><code>context.Stages.AddOrUpdate(s => s.Name,
new Stage()
{
Name = "Seven",
Span = new TimeSpan(2, 0, 0),
StageId = 7
});
context.Stages.AddOrUpdate(s => s.Name,
new Stage()
{
Name = "Eight",
Span = new TimeSpan(1, 0, 0, 0),
StageId = 8
});
</code></pre>
<p>This is within my Seed() function for EF Codefirst Migrations. It fails at Stage Eight with the following: </p>
<blockquote>
<p>System.Data.UpdateException: An error occurred while updating the
entries. See the inner exception for details. --->
System.OverflowException: SqlDbType.Time overflow. Value '1.00:00:00'
is out of range. Must be between 00:00:00.0000000 and
23:59:59.9999999.</p>
</blockquote>
<p>Why would I not be able to store a timespan using EF? I really hope I don't need to do some silly time-to-ticks conversion on both ends here... </p> | 17,131,237 | 5 | 0 | null | 2013-06-16 03:03:24.243 UTC | 5 | 2022-08-17 15:11:42.067 UTC | 2020-11-14 17:28:01.73 UTC | null | 297,823 | null | 899,530 | null | 1 | 34 | c#|.net|entity-framework|ef-code-first|timespan | 31,999 | <p>In this line:</p>
<pre><code>Span = new TimeSpan(1, 0, 0, 0)
</code></pre>
<p>You're using this constructor:</p>
<pre><code>public TimeSpan(int days, int hours, int minutes, int seconds);
</code></pre>
<p>So you're actually creating a <code>TimeSpan</code> greater than 24 hours since you're passing <code>1</code> to the <code>days</code> parameter, while your underlying Database type is <code>Time</code> which only accepts values between 00:00-23:59.</p>
<p>Hard to tell whether you actually meant to have a <code>TimeSpan</code> with 1 day, or it's just a typo.</p>
<p>If you really want a <code>TimeSpan</code> greater than 24 hours, i guess you'll have to map your field to another Database type (like <code>SmallDateTime</code>).</p>
<p>If it's just a typo error, just change your line to:</p>
<pre><code>Span = new TimeSpan(1, 0, 0),
</code></pre> |
16,626,326 | Can one host an angular.js based static blog on Github? | <p>I know one can host a Jekyl based static site/blog via Github pages. <strong>Can one do the same with a static site/blog based on AngularJS?</strong> </p> | 16,626,724 | 4 | 0 | null | 2013-05-18 16:08:28.593 UTC | 18 | 2018-05-01 15:50:02.073 UTC | null | null | null | user883807 | null | null | 1 | 50 | angularjs|github-pages | 19,154 | <p>I would say yes considering all the angular UI github pages are in fact angular apps with demos:</p>
<p><a href="http://angular-ui.github.io/">http://angular-ui.github.io/</a></p>
<p><a href="http://angular-ui.github.io/bootstrap/">http://angular-ui.github.io/bootstrap/</a></p>
<p>etc</p> |
16,650,223 | What does "this[0]" mean in C#? | <p>I was going through some library code and saw a method like:</p>
<pre><code>public CollapsingRecordNodeItemList List
{
get { return this[0] as CollapsingRecordNodeItemList; }
}
</code></pre>
<p>The class that contains this method is not a list or something iterable, so what exactly does <code>this[0]</code> mean?</p> | 16,650,262 | 4 | 9 | null | 2013-05-20 13:05:54.073 UTC | 2 | 2013-05-20 14:06:10.07 UTC | 2013-05-20 14:06:10.07 UTC | null | 1,128,737 | null | 586,986 | null | 1 | 59 | c# | 4,361 | <p>Look for an <a href="http://msdn.microsoft.com/en-us/library/vstudio/6x16t2tx.aspx" rel="noreferrer">indexer</a> in the class.</p>
<p>C# lets you define indexers to allow this sort of access.</p>
<p>Here is an example from the official guide for "SampleCollection".</p>
<pre><code>public T this[int i]
{
get
{
// This indexer is very simple, and just returns or sets
// the corresponding element from the internal array.
return arr[i];
}
set
{
arr[i] = value;
}
}
</code></pre>
<p>Here is the definition from <a href="http://www.microsoft.com/en-us/download/details.aspx?id=7029" rel="noreferrer">the official language specification</a>:</p>
<blockquote>
<p>An <strong>indexer</strong> is a member that enables objects to be indexed in the same way as an array. An indexer is declared like a property except that the name of the member is this followed by a parameter list written between the delimiters [ and ]. The parameters are available in the accessor(s) of the indexer. Similar to properties, indexers can be read-write, read-only, and write-only, and the accessor(s) of an indexer can be virtual.</p>
</blockquote>
<p>One can find the full and complete definition in section <strong>10.9 Indexers</strong> of the specification.</p> |
25,847,349 | For { A=a; B=b; }, will "A=a" be strictly executed before "B=b"? | <p>Suppose <code>A</code>, <code>B</code>, <code>a</code>, and <code>b</code> are all variables, and the addresses of <code>A</code>, <code>B</code>, <code>a</code>, and <code>b</code> are all different. Then, for the following code:</p>
<pre><code>A = a;
B = b;
</code></pre>
<p>Do the C and C++ standard explicitly require <code>A=a</code> be strictly executed before <code>B=b</code>? Given that the addresses of <code>A</code>, <code>B</code>, <code>a</code>, and <code>b</code> are all different, are compilers allowed to swap the execution sequence of two statements for some purpose such as optimization?</p>
<p>If the answer to my question is different in C and C++, I would like to know both.</p>
<p>Edit: The background of the question is the following. In board game AI design, for optimization people use <a href="https://chessprogramming.wikispaces.com/Shared+Hash+Table">lock-less shared-hash table</a>, whose correctness strongly depends on the execution order if we do not add <code>volatile</code> restriction.</p> | 25,847,384 | 6 | 12 | null | 2014-09-15 11:46:06.037 UTC | 13 | 2014-12-02 14:32:50.567 UTC | 2014-09-15 13:05:00.38 UTC | null | 3,881,143 | null | 3,881,143 | null | 1 | 50 | c++|c|optimization|compiler-construction|standards | 3,758 | <p>Both standards allow for these instructions to be performed out of order, so long as that does not change observable behaviour. This is known as the as-if rule:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule">What exactly is the "as-if" rule?</a></li>
<li><a href="http://en.cppreference.com/w/cpp/language/as_if" rel="nofollow noreferrer">http://en.cppreference.com/w/cpp/language/as_if</a></li>
</ul>
<p>Note that as is pointed out in the comments, what is meant by "observable behaviour" is the observable behaviour of a program with defined behaviour. If your program has undefined behaviour, then the compiler is excused from reasoning about that.</p> |
4,664,517 | How do you convert a parent-child (adjacency) table to a nested set using PHP and MySQL? | <p>I've spent the last few hours trying to find the solution to this question online. I've found plenty of examples on how to convert from nested set to adjacency... but few that go the other way around. The examples I have found either don't work or use MySQL procedures. Unfortunately, I can't use procedures for this project. I need a pure PHP solution.</p>
<p>I have a table that uses the adjacency model below:</p>
<pre><code>id parent_id category
1 0 Books
2 0 CD's
3 0 Magazines
4 1 Books/Hardcover
5 1 Books/Large Format
6 3 Magazines/Vintage
</code></pre>
<p>And I would like to convert it to a Nested Set table below:</p>
<pre><code>id left right category
0 1 14 Root Node
1 2 7 Books
4 3 4 Books/Hardcover
5 5 6 Books/Large Format
2 8 9 CD's
3 10 13 Magazines
6 11 12 Magazines/Vintage
</code></pre>
<p>Here is an image of what I need:</p>
<p><img src="https://i.stack.imgur.com/3EFqO.png" alt="Nested Tree Chart"></p>
<p>I have a function, based on the pseudo code from this forum post (<a href="http://www.sitepoint.com/forums/showthread.php?t=320444" rel="nofollow noreferrer">http://www.sitepoint.com/forums/showthread.php?t=320444</a>) but it doesn't work. I get multiple rows that have the same value for left. This should not happen.</p>
<pre><code><?php
/**
--
-- Table structure for table `adjacent_table`
--
CREATE TABLE IF NOT EXISTS `adjacent_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`father_id` int(11) DEFAULT NULL,
`category` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
--
-- Dumping data for table `adjacent_table`
--
INSERT INTO `adjacent_table` (`id`, `father_id`, `category`) VALUES
(1, 0, 'ROOT'),
(2, 1, 'Books'),
(3, 1, 'CD''s'),
(4, 1, 'Magazines'),
(5, 2, 'Hard Cover'),
(6, 2, 'Large Format'),
(7, 4, 'Vintage');
--
-- Table structure for table `nested_table`
--
CREATE TABLE IF NOT EXISTS `nested_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lft` int(11) DEFAULT NULL,
`rgt` int(11) DEFAULT NULL,
`category` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
*/
mysql_connect('localhost','USER','PASSWORD') or die(mysql_error());
mysql_select_db('DATABASE') or die(mysql_error());
adjacent_to_nested(0);
/**
* adjacent_to_nested
*
* Reads a "adjacent model" table and converts it to a "Nested Set" table.
* @param integer $i_id Should be the id of the "root node" in the adjacent table;
* @param integer $i_left Should only be used on recursive calls. Holds the current value for lft
*/
function adjacent_to_nested($i_id, $i_left = 0)
{
// the right value of this node is the left value + 1
$i_right = $i_left + 1;
// get all children of this node
$a_children = get_source_children($i_id);
foreach ($a_children as $a)
{
// recursive execution of this function for each child of this node
// $i_right is the current right value, which is incremented by the
// import_from_dc_link_category method
$i_right = adjacent_to_nested($a['id'], $i_right);
// insert stuff into the our new "Nested Sets" table
$s_query = "
INSERT INTO `nested_table` (`id`, `lft`, `rgt`, `category`)
VALUES(
NULL,
'".$i_left."',
'".$i_right."',
'".mysql_real_escape_string($a['category'])."'
)
";
if (!mysql_query($s_query))
{
echo "<pre>$s_query</pre>\n";
throw new Exception(mysql_error());
}
echo "<p>$s_query</p>\n";
// get the newly created row id
$i_new_nested_id = mysql_insert_id();
}
return $i_right + 1;
}
/**
* get_source_children
*
* Examines the "adjacent" table and finds all the immediate children of a node
* @param integer $i_id The unique id for a node in the adjacent_table table
* @return array Returns an array of results or an empty array if no results.
*/
function get_source_children($i_id)
{
$a_return = array();
$s_query = "SELECT * FROM `adjacent_table` WHERE `father_id` = '".$i_id."'";
if (!$i_result = mysql_query($s_query))
{
echo "<pre>$s_query</pre>\n";
throw new Exception(mysql_error());
}
if (mysql_num_rows($i_result) > 0)
{
while($a = mysql_fetch_assoc($i_result))
{
$a_return[] = $a;
}
}
return $a_return;
}
?>
</code></pre>
<p>This is the output of the above script.</p>
<blockquote>
<p>INSERT INTO <code>nested_table</code> (<code>id</code>,
<code>lft</code>, <code>rgt</code>, <code>category</code>) VALUES(
NULL, '2', '5', 'Hard Cover' )</p>
<p>INSERT INTO <code>nested_table</code> (<code>id</code>,
<code>lft</code>, <code>rgt</code>, <code>category</code>) VALUES(
NULL, '2', '7', 'Large Format' )</p>
<p>INSERT INTO <code>nested_table</code> (<code>id</code>,
<code>lft</code>, <code>rgt</code>, <code>category</code>) VALUES(
NULL, '1', '8', 'Books' )</p>
<p>INSERT INTO <code>nested_table</code> (<code>id</code>,
<code>lft</code>, <code>rgt</code>, <code>category</code>) VALUES(
NULL, '1', '10', 'CD\'s' )</p>
<p>INSERT INTO <code>nested_table</code> (<code>id</code>,
<code>lft</code>, <code>rgt</code>, <code>category</code>) VALUES(
NULL, '10', '13', 'Vintage' )</p>
<p>INSERT INTO <code>nested_table</code> (<code>id</code>,
<code>lft</code>, <code>rgt</code>, <code>category</code>) VALUES(
NULL, '1', '14', 'Magazines' )</p>
<p>INSERT INTO <code>nested_table</code> (<code>id</code>,
<code>lft</code>, <code>rgt</code>, <code>category</code>) VALUES(
NULL, '0', '15', 'ROOT' )</p>
</blockquote>
<p>As you can see, there are multiple rows sharing the lft value of "1" same goes for "2" In a nested-set, the values for left and right must be unique. Here is an example of how to manually number the left and right ID's in a nested set:</p>
<p><img src="https://i.stack.imgur.com/rljwW.gif" alt="How to number nested sets"></p>
<p>Image Credit: Gijs Van Tulder, <a href="https://www.sitepoint.com/hierarchical-data-database-2/" rel="nofollow noreferrer">ref article</a></p> | 4,671,500 | 2 | 5 | 2011-01-12 17:00:02.237 UTC | 2011-01-12 01:18:34.497 UTC | 16 | 2016-07-01 03:30:57.263 UTC | 2016-07-01 03:30:57.263 UTC | null | 1,816,093 | null | 331,503 | null | 1 | 21 | php|mysql|nested-sets|adjacency-list | 11,704 | <p>I found an answer online and updated the question on this page to show others how it is done.</p>
<h2>UPDATE - PROBLEM SOLVED</h2>
<p>First off, I had mistakenly believed that the source table (the one in adjacent-lists format) needed to be altered to include a source node. This is not the case. Secondly, I <a href="http://gen5.info/q/2008/11/04/nested-sets-php-verb-objects-and-noun-objects/" rel="nofollow">found a class</a> via BING that does the trick. I've altered it for PHP5 and converted the original author's mysql related bits to basic PHP. He was using some DB class. You can convert them to your own database abstraction class later if you want.</p>
<p>Obviously, if your "source table" has other columns that you want to move to the nested set table, you will have to adjust the write method in the class below.</p>
<p>Hopefully this will save someone else from the same problems in the future.</p>
<pre><code><?php
/**
--
-- Table structure for table `adjacent_table`
--
DROP TABLE IF EXISTS `adjacent_table`;
CREATE TABLE IF NOT EXISTS `adjacent_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`father_id` int(11) DEFAULT NULL,
`category` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
--
-- Dumping data for table `adjacent_table`
--
INSERT INTO `adjacent_table` (`id`, `father_id`, `category`) VALUES
(1, 0, 'Books'),
(2, 0, 'CD''s'),
(3, 0, 'Magazines'),
(4, 1, 'Hard Cover'),
(5, 1, 'Large Format'),
(6, 3, 'Vintage');
--
-- Table structure for table `nested_table`
--
DROP TABLE IF EXISTS `nested_table`;
CREATE TABLE IF NOT EXISTS `nested_table` (
`lft` int(11) NOT NULL DEFAULT '0',
`rgt` int(11) DEFAULT NULL,
`id` int(11) DEFAULT NULL,
`category` varchar(128) DEFAULT NULL,
PRIMARY KEY (`lft`),
UNIQUE KEY `id` (`id`),
UNIQUE KEY `rgt` (`rgt`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
*/
/**
* @class tree_transformer
* @author Paul Houle, Matthew Toledo
* @created 2008-11-04
* @url http://gen5.info/q/2008/11/04/nested-sets-php-verb-objects-and-noun-objects/
*/
class tree_transformer
{
private $i_count;
private $a_link;
public function __construct($a_link)
{
if(!is_array($a_link)) throw new Exception("First parameter should be an array. Instead, it was type '".gettype($a_link)."'");
$this->i_count = 1;
$this->a_link= $a_link;
}
public function traverse($i_id)
{
$i_lft = $this->i_count;
$this->i_count++;
$a_kid = $this->get_children($i_id);
if ($a_kid)
{
foreach($a_kid as $a_child)
{
$this->traverse($a_child);
}
}
$i_rgt=$this->i_count;
$this->i_count++;
$this->write($i_lft,$i_rgt,$i_id);
}
private function get_children($i_id)
{
return $this->a_link[$i_id];
}
private function write($i_lft,$i_rgt,$i_id)
{
// fetch the source column
$s_query = "SELECT * FROM `adjacent_table` WHERE `id` = '".$i_id."'";
if (!$i_result = mysql_query($s_query))
{
echo "<pre>$s_query</pre>\n";
throw new Exception(mysql_error());
}
$a_source = array();
if (mysql_num_rows($i_result))
{
$a_source = mysql_fetch_assoc($i_result);
}
// root node? label it unless already labeled in source table
if (1 == $i_lft && empty($a_source['category']))
{
$a_source['category'] = 'ROOT';
}
// insert into the new nested tree table
// use mysql_real_escape_string because one value "CD's" has a single '
$s_query = "
INSERT INTO `nested_table`
(`id`,`lft`,`rgt`,`category`)
VALUES (
'".$i_id."',
'".$i_lft."',
'".$i_rgt."',
'".mysql_real_escape_string($a_source['category'])."'
)
";
if (!$i_result = mysql_query($s_query))
{
echo "<pre>$s_query</pre>\n";
throw new Exception(mysql_error());
}
else
{
// success: provide feedback
echo "<p>$s_query</p>\n";
}
}
}
mysql_connect('localhost','USER','PASSWORD') or die(mysql_error());
mysql_select_db('DATABASE') or die(mysql_error());
// build a complete copy of the adjacency table in ram
$s_query = "SELECT `id`,`father_id` FROM `adjacent_table`";
$i_result = mysql_query($s_query);
$a_rows = array();
while ($a_rows[] = mysql_fetch_assoc($i_result));
$a_link = array();
foreach($a_rows as $a_row)
{
$i_father_id = $a_row['father_id'];
$i_child_id = $a_row['id'];
if (!array_key_exists($i_father_id,$a_link))
{
$a_link[$i_father_id]=array();
}
$a_link[$i_father_id][]=$i_child_id;
}
$o_tree_transformer = new tree_transformer($a_link);
$o_tree_transformer->traverse(0);
?>
</code></pre>
<p>Here is the output:</p>
<blockquote>
<p>INSERT INTO <code>nested_table</code>
(<code>id</code>,<code>lft</code>,<code>rgt</code>,<code>category</code>) VALUES (
'4', '3', '4', 'Hard Cover' )</p>
<p>INSERT INTO <code>nested_table</code>
(<code>id</code>,<code>lft</code>,<code>rgt</code>,<code>category</code>) VALUES (
'5', '5', '6', 'Large Format' )</p>
<p>INSERT INTO <code>nested_table</code>
(<code>id</code>,<code>lft</code>,<code>rgt</code>,<code>category</code>) VALUES (
'1', '2', '7', 'Books' )</p>
<p>INSERT INTO <code>nested_table</code>
(<code>id</code>,<code>lft</code>,<code>rgt</code>,<code>category</code>) VALUES (
'2', '8', '9', 'CD\'s' )</p>
<p>INSERT INTO <code>nested_table</code>
(<code>id</code>,<code>lft</code>,<code>rgt</code>,<code>category</code>) VALUES (
'6', '11', '12', 'Vintage' )</p>
<p>INSERT INTO <code>nested_table</code>
(<code>id</code>,<code>lft</code>,<code>rgt</code>,<code>category</code>) VALUES (
'3', '10', '13', 'Magazines' )</p>
<p>INSERT INTO <code>nested_table</code>
(<code>id</code>,<code>lft</code>,<code>rgt</code>,<code>category</code>) VALUES (
'0', '1', '14', 'ROOT' )</p>
</blockquote> |
9,777,282 | The best way to calculate the best threshold with P. Viola, M. Jones Framework | <p>I'm trying to implement P. Viola and M. Jones detection framework in C++ (at the beginning, simply sequence classifier - not cascaded version). I think I have designed all required class and modules (e.g Integral images, Haar features), despite one - the most important: the AdaBoost core algorithm.</p>
<p>I have read the P. Viola and M. Jones original paper and many other publications. Unfortunately I still don't understand how I should find the best threshold for the one weak classifier? I have found only small references to "weighted median" and "gaussian distribution" algorithms and many pieces of mathematics formulas...</p>
<p>I have tried to use OpenCV Train Cascade module sources as a template, but it is so comprehensive that doing a reverse engineering of code is very time-consuming. I also coded my own simple code to understand the idea of Adaptive Boosting.</p>
<p>The question is: could you explain me the best way to calculate the best threshold for the one weak classifier?</p>
<p>Below I'm presenting the AdaBoost pseudo code, rewritten from sample found in Google, but I'm not convinced if it's correctly approach. Calculating of one weak classifier is very slow (few hours) and I have doubts about method of calculating the best threshold especially.</p>
<pre><code>(1) AdaBoost::FindNewWeakClassifier
(2) AdaBoost::CalculateFeatures
(3) AdaBoost::FindBestThreshold
(4) AdaBoost::FindFeatureError
(5) AdaBoost::NormalizeWeights
(6) AdaBoost::FindLowestError
(7) AdaBoost::ClassifyExamples
(8) AdaBoost::UpdateWeights
DESCRIPTION (1)
-Generates all possible arrangement of features in detection window and put to the vector
DO IN LOOP
-Runs main calculating function (2)
END
DESCRIPTION(2)
-Normalizes weights (5)
DO FOR EACH HAAR FEATURE
-Puts sequentially next feature from list on all integral images
-Finds the best threshold for each feature (3)
-Finds the error for each the best feature in current iteration (4)
-Saves errors for each the best feature in current iteration in array
-Saves threshold for each the best feature in current iteration in array
-Saves the threshold sign for each the best feature in current iteration in array
END LOOP
-Finds for classifier index with the lowest error selected by above loop (6)
-Gets the value of error from the best feature
-Calculates the value of the best feature in the all integral images (7)
-Updates weights (8)
-Adds new, weak classifier to vector
DESCRIPTION (3)
-Calculates an error for each feature threshold on positives integral images - seperate for "+" and "-" sign (4)
-Returns threshold and sign of the feature with the lowest error
DESCRIPTION(4)
- Returns feature error for all samples, by calculating inequality f(x) * sign < sign * threshold
DESCRIPTION (5)
-Ensures that samples weights are probability distribution
DESCRIPTION (6)
-Finds the classifier with the lowest error
DESCRIPTION (7)
-Calculates a value of the best features at all integral images
-Counts false positives number and false negatives number
DESCRIPTION (8)
-Corrects weights, depending on classification results
</code></pre>
<p>Thank you for any help</p> | 9,800,372 | 1 | 0 | null | 2012-03-19 20:18:00.53 UTC | 13 | 2013-10-21 09:33:34.727 UTC | 2013-06-12 09:09:33.477 UTC | null | 451,518 | null | 1,269,940 | null | 1 | 10 | machine-learning|artificial-intelligence|computer-vision|pattern-recognition|viola-jones | 7,410 | <p>In the original viola-Jones paper <a href="http://www.vision.caltech.edu/html-files/EE148-2005-Spring/pprs/viola04ijcv.pdf" rel="noreferrer">here</a>, section 3.1 Learning Discussion (para 4, to be precise) you will find out the procedure to find optimal threshold. </p>
<p>I'll sum up the method quickly below. </p>
<hr>
<p>Optimal threshold for each feature is sample-weight dependent and therefore calculated in very iteration of adaboost. The best weak classifier's threshold is saved as mentioned in the pseudo code. </p>
<p>In every round, for each weak classifier, you have to arrange the N training samples according to the feature value. Putting a threshold will separate this sequence in 2 parts. Both parts will have either positive or negative samples in majority along with a few samples of other type. </p>
<ul>
<li><code>T+</code> : total sum of positive sample weights </li>
<li><code>T-</code> : total sum of negative sample weights </li>
<li><code>S+</code> : sum of positive sample weights below the threshold </li>
<li><code>S-</code> : sum of negative sample weights below the threshold </li>
</ul>
<p>Error for this particular threshold is - </p>
<pre><code>e = MIN((S+) + (T-) - (S-), (S-) + (T+) - (S+))
</code></pre>
<p>Why the minimum? here's an example:<br>
If the samples and threshold is like this - </p>
<pre><code>+ + + + + - - | + + - - - - -
</code></pre>
<p>In the first round, if all weights are equal(=w), taking the minimum will give you the error of <code>4*w</code>, instead of <code>10*w</code>. </p>
<p>You calculate this error for all N possible ways of separating the samples.<br>
The minimum error will give you the range of threshold values. The actual threshold is probably the average of the adjacent feature values (I'm not sure though, do some research on this).<br>
This was the second step in your <code>DO FOR EACH HAAR FEATURE</code> loop.<br>
The cascades given along with OpenCV were created by Rainer Lienhart and I don't know what method he used.
You could closely follow the OpenCV source codes to get any further improvements on this procedure.</p> |
9,703,068 | Most efficient way of exporting large (3.9 mill obs) data.frames to text file? | <p>I have a fairly large dataframe in R that I would like to export to SPSS.
This file has caused me hours of headaches trying to import it to R in the first place, however I got successful using <code>read.fwf()</code> using the options <code>comment.char="%"</code> (a character not appearing in the file) and <code>fill= TRUE</code>(it was a fixed-width ASCII file with some rows lacking all variables, causing error messages).</p>
<p>Anyway, my data frame currently consists of 3,9 mill observations and 48 variables (all character). I can write it to file fairly quickly by splitting it into 4 x 1 mill obs sets with <code>df2 <- df[1:1000000,]</code> followed by <code>write.table(df2)</code> etc., but can't write the entire file in one sweep without the computer locking up and needing a hard reset to come back up. </p>
<p>After hearing anecdotal stories about how R is unsuited for large datasets for years, this is the first time I have actually encountered a problem of this kind. I wonder whether there are other approaches(low-level "dumping" the file directly to disk?) or whether there is some package unknown to me that can handle export of large files of this type efficiently?</p> | 9,704,400 | 5 | 0 | null | 2012-03-14 13:36:23.747 UTC | 17 | 2017-08-23 17:31:55.447 UTC | null | null | null | null | 1,269,026 | null | 1 | 24 | r|export|export-to-csv | 21,203 | <p>At a guess, your machine is short on RAM, and so R is having to use the swap file, which slows things down. If you are being paid to code, then buying more RAM will probably be cheaper than you writing new code.</p>
<p>That said, there are some possibilities. You can export the file to a database and then use that database's facility for writing to a text file. JD Long's answer to <a href="https://stackoverflow.com/questions/1727772/quickly-reading-very-large-tables-as-dataframes-in-r">this question</a> tells you how to read in files in this way; it shouldn't be too difficult to reverse the process. Alternatively the <code>bigmemory</code> and <code>ff</code> packages (as mentioned by Davy) could be used for writing such files.</p> |
9,855,445 | How to change text/font color in reportlab.pdfgen | <p>I want to use a different color of text in my auto-generated PDF.</p>
<p>According to <a href="http://www.reportlab.com/software/opensource/rl-toolkit/faq/#2.1.4" rel="noreferrer">the reportlab docs</a> all I need to do is:</p>
<pre><code>self.canvas.setFillColorRGB(255,0,0)
self.canvas.drawCentredString(...)
</code></pre>
<p>But that doesn't do anything. The text is black no matter what.</p> | 10,247,952 | 3 | 0 | null | 2012-03-24 20:43:40.53 UTC | 8 | 2017-06-07 09:05:09.203 UTC | 2013-07-18 07:15:58.233 UTC | null | 2,683 | null | 84,398 | null | 1 | 29 | python|reportlab | 38,999 | <p>If you copy and paste the code in User Guide Section 2. You'll get a fancy coloured rectangle with a coloured Text within it. Probably the approach is not that clear in the user guide, I'd spent some time playing with it and I finally know how it works.</p>
<p>You need to imagine yourself drawing a canvas. You need to do all the setup before you draw. Below is an example I prepared to show better how to style a text, draw a line, and draw a rectangle, all with the ability to put colour on them.</p>
<pre><code>from reportlab.pdfgen import canvas
def hello(c):
from reportlab.lib.units import inch
#First Example
c.setFillColorRGB(1,0,0) #choose your font colour
c.setFont("Helvetica", 30) #choose your font type and font size
c.drawString(100,100,"Hello World") # write your text
#Second Example
c.setStrokeColorRGB(0,1,0.3) #choose your line color
c.line(2,2,2*inch,2*inch)
#Third Example
c.setFillColorRGB(1,1,0) #choose fill colour
c.rect(4*inch,4*inch,2*inch,3*inch, fill=1) #draw rectangle
c = canvas.Canvas("hello.pdf")
hello(c)
c.showPage()
c.save()
</code></pre> |
10,013,493 | Failed to CoCreate Profiler error - but not using a profiler | <p>We're getting a:</p>
<blockquote>
<p>.NET Runtime version 2.0.50727.5448 - Failed to CoCreate profiler</p>
</blockquote>
<p>message in the Event Viewer on our webserver, along with an accompanying:</p>
<blockquote>
<p>.NET Runtime version 4.0.30319.239 - Loading profiler failed during CoCreateInstance. Profiler CLSID: '{d37a1b78-6dc5-46fc-bc31-f7c4d5a11c9c}'. HRESULT: 0x8007007e. Process ID (decimal): 224. Message ID: [0x2504].</p>
</blockquote>
<p>The thing is, we're not trying to use a profiler, there are no profiler's running or installed on the server and the code makes no reference to profilers anywhere...</p>
<p>We've tried removing the registry keys that other's have pointed out are related to these messages but to no avail; it would seem that two of our websites/webapps are firing off the error, one using .Net2 and the other using 4, but I'm not sure where to look.</p> | 10,024,946 | 9 | 1 | null | 2012-04-04 14:43:03.047 UTC | 6 | 2019-07-31 08:24:28.18 UTC | 2017-08-17 16:08:31.447 UTC | null | 7,256,341 | null | 95,027 | null | 1 | 37 | asp.net|.net|iis|profiler | 57,964 | <p>After much searching I found that someone had previously installed dotTrace, then uninstalled it, however the uninstall wasn't very clean and had left the registry littered with entries, though we'd removed some entries we thought could stop the problem there were more specific to that profiler.</p>
<p>After removing all registry entries related to dottrace and the CSID it presented we no longer have the error appearing in the event viewer.</p>
<p>See this answer for a script to aid in hunting down such entries: <a href="https://stackoverflow.com/a/36129656/361842">https://stackoverflow.com/a/36129656/361842</a></p> |
10,227,410 | Interface extends another interface but implements its methods | <p>In java when an interface extends another interface:</p>
<ol>
<li>Why does it implement its methods?</li>
<li>How can it implement its methods when an interface can't contain a
method body</li>
<li>How can it implement the methods when it extends the other interface
and not implement it?</li>
<li>What is the purpose of an interface implementing another interface?</li>
</ol>
<p>This has major concepts in Java!</p>
<p><strong>EDIT:</strong> </p>
<pre><code>public interface FiresDragEvents {
void addDragHandler(DragHandler handler);
void removeDragHandler(DragHandler handler);
}
public interface DragController extends FiresDragEvents {
void addDragHandler(DragHandler handler);
void removeDragHandler(DragHandler handler);
void dragEnd();
void dragMove();
}
</code></pre>
<p><strong>In eclipse there is the implement sign besides the implemented methods in <code>DragController</code>.</strong></p>
<p><strong>And when I mouse-hover it, it says that it implements the method!!!</strong></p> | 10,227,665 | 3 | 1 | null | 2012-04-19 11:50:21.547 UTC | 16 | 2017-05-29 08:57:14.23 UTC | 2017-05-29 08:57:14.23 UTC | null | 4,806,357 | null | 1,358,722 | null | 1 | 52 | java|interface|extends|implements | 131,799 | <blockquote>
<p>Why does it implement its methods? How can it implement its methods
when an interface can't contain method body? How can it implement the
methods when it extends the other interface and not implement it? What
is the purpose of an interface implementing another interface?</p>
</blockquote>
<p>Interface does not implement the methods of another interface but just extends them.
One example where the interface extension is needed is: consider that you have a vehicle interface with two methods <code>moveForward</code> and <code>moveBack</code> but also you need to incorporate the Aircraft which is a vehicle but with some addition methods like <code>moveUp</code>, <code>moveDown</code> so
in the end you have:</p>
<pre><code>public interface IVehicle {
bool moveForward(int x);
bool moveBack(int x);
};
</code></pre>
<p>and airplane:</p>
<pre><code>public interface IAirplane extends IVehicle {
bool moveDown(int x);
bool moveUp(int x);
};
</code></pre> |
10,111,441 | Is there a way to automatically update nuget.exe in the .nuget folder when using package restore? | <p>My team has been using the Enable Package Restore option since Nuget 1.5 to keep packages out of our source control. When Nuget 1.6 was released we noticed an issue where it wasn't pulling the packages down, and tracked it down to the Nuget.exe in the .nuget folder needed to updated to 1.6 to match the Package Manager.</p>
<p>What's the best way to update a solution once Nuget has been udpated? I don't see an easy way from studio to tell which version of nuget is in the solution folder. So far we blow away the .nuget folder and re-run the Enable Package Restore command.</p> | 10,111,854 | 3 | 0 | null | 2012-04-11 18:02:38.36 UTC | 20 | 2014-11-04 17:31:19.123 UTC | null | null | null | null | 139,705 | null | 1 | 93 | nuget | 30,409 | <p>I would suggest updating .nuget\nuget.exe with this command from the command line:</p>
<pre><code>nuget.exe update -self
</code></pre>
<p>[EDIT] : Close VS Solution first. If there's an update and the solution is opened, nuget.exe will be removed from the solution.</p>
<p>You <em>could</em> automatically update nuget.exe on restore by modifying the .nuget\nuget.targets to add the above command. I'd look at the restore command in there as an example. But I'm not sure if it's worth it, nuget.exe updates aren't that common, and backward compatibility should break very rarely.</p> |
10,132,883 | Getting the path of %AppData% in PowerShell | <p>How can I get the path for the application data directory (e.g. <code>C:\Users\User\AppData\Roaming</code>) in PowerShell?</p> | 10,132,925 | 3 | 0 | null | 2012-04-12 22:38:56.027 UTC | 19 | 2017-05-03 12:11:01.29 UTC | null | null | null | null | 135,441 | null | 1 | 126 | powershell|scripting | 133,383 | <p>This is the shortest way:</p>
<pre><code>$env:APPDATA
</code></pre>
<p>or for local app data:</p>
<pre><code>$env:LOCALAPPDATA
</code></pre> |
8,330,370 | Generic OR instead of AND <T extends Number | CharSequence> | <p>Is it possible to generically parameterize a method accepting EITHER ClassA OR InterfaceB ?</p>
<p><strong>Does Not Compile Due to | Pseudocode</strong></p>
<pre><code>public <T extends Number | CharSequence> void orDoer(T someData){ // ... }
</code></pre>
<p>i.e. instead of writing multiple method signatures, I would like this one method to accept either a Number or CharSequence as an argument</p>
<p><strong>Should Pass with a Number OR CharSequence argument</strong></p>
<pre><code>orDoer(new Integer(6));
int somePrimitive = 4;
orDoer(somePrimitive);
orDoer("a string of chars");
</code></pre> | 8,330,519 | 3 | 3 | null | 2011-11-30 17:36:27.277 UTC | 2 | 2018-08-09 07:09:56.08 UTC | 2011-11-30 17:39:25.783 UTC | null | 129,570 | null | 742,084 | null | 1 | 31 | java|android|generics|types|charsequence | 14,743 | <p>If you <strong>really</strong> want to do that, you'll need to wrap youur accepted classes inside a custom class of your own. In your example case, probably something like:</p>
<pre><code>public class OrDoerElement {
private final Number numberValue;
private final CharSequence charSequenceValue;
private OrDoerElement(Number number, CharSequence charSequence) {
this.numberValue = number;
this.charSequenceValue = charSequence;
}
public static OrDoerElement fromCharSequence(CharSequence value) {
return new OrDoerElement(null, value);
}
public static OrDoerElement fromNumber(Number value) {
return new OrDoerElement(value, null);
}
}
</code></pre>
<p>And your <code>orDoer</code> method becomes:</p>
<pre><code>public void orDoer(OrDoerElement someData) { .... }
</code></pre>
<p>Then you can build one of those and use in your method using either:</p>
<pre><code>orDoer(OrDoerElement.fromCharSequence("a string of chars"));
orDoer(OrDoerElement.fromNumber(new Integer(6)));
</code></pre>
<p>But honestly, that sounds a bit too complex and too much work just to be able to call a method with different parameter types. Are you sure you can't achieve the same using two methods, and a third method for the common logic?</p> |
12,044,674 | Android: rotate image without loading it to memory | <p>I am wondering is it possible to rotate an image stored on sdcard without loading it's to memory.</p>
<p>The reason is why I am looking for that is famous OutOfMemoryError. I know I can avoid it by downsampling large image but in fact I don't want to reduce size of that image, I want to have original image but rotated on 90 degrees.</p>
<p>Any suggestions about that are warmly appreciated :)</p> | 12,044,717 | 6 | 1 | null | 2012-08-20 20:30:32.303 UTC | 12 | 2019-02-26 21:27:11.72 UTC | null | null | null | null | 390,323 | null | 1 | 24 | android | 15,123 | <p>you should decode decode the images using <code>Bitmap</code>. you should follow <a href="http://developer.android.com/training/displaying-bitmaps/load-bitmap.html" rel="nofollow noreferrer">Loading Large Image</a> presented by google on how to do it.. it helped me alot, you'll notice the large difference in the RAM usage..</p>
<p><strong>UPDATE</strong> if all you want is just rotate the image you can use this code</p>
<pre><code>Matrix matrix = new Matrix();
matrix.setRotate(90);
result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), matrix, false);
</code></pre>
<p>if you just need to set the image orientation (for example the photo orientation when it's was taken) you can use</p>
<pre><code>ExifInterface exif = new ExifInterface(filePath);
</code></pre>
<p>with the attribute <code>ExifInterface.TAG_ORIENTATION</code>
I hope this helps you</p> |
11,531,353 | Viewing NSData contents in Xcode | <p>I am running Xcode and I would like to dump out a NSData*. The variable in question is buffer. Is there a way to do this through the UI or the GDB debugger?</p>
<p><img src="https://i.stack.imgur.com/koVDS.png" alt="This is what I see at runtime"></p>
<p><strong>Edit</strong></p>
<p>I've moved my notes into an answer.</p> | 11,936,672 | 12 | 5 | null | 2012-07-17 21:47:50.113 UTC | 12 | 2020-05-17 20:17:51.833 UTC | 2018-03-21 21:33:25.91 UTC | null | 1,265,393 | null | 516,126 | null | 1 | 27 | objective-c|xcode | 21,700 | <p>Unfortunately, none of the suggestions so far solved the problem of actually being able to quickly display <em>the data</em> inside NSData.</p>
<p>I wrote a simple method that works the way I need it to. From the GDB window, I can type in <code>print [Util dumpData:theData]</code> and I will get nice, formatted output.</p>
<pre><code>+(void) dumpData:(NSData *)data
{
unsigned char* bytes = (unsigned char*) [data bytes];
for(int i=0;i< [data length];i++)
{
NSString* op = [NSString stringWithFormat:@"%d:%X",i,bytes[i],nil];
NSLog(@"%@", op);
}
}
</code></pre>
<p><em>NsLog Output</em></p>
<p>0:24<br>
1:0<br>
2:4<br>
3:0<br>
4:0<br>
5:0<br></p> |
11,488,035 | Get the ID of a new record inserted into a database from the returned Uri | <p>When you insert a new item into a database like this </p>
<pre><code>Uri uri = getContentResolver().insert(Tournaments.CONTENT_URI, values);
</code></pre>
<p>is there any way to get the id from the uri that is returned so I don't have to run a query to get the id since its already in the returned uri?</p> | 11,488,103 | 4 | 0 | null | 2012-07-14 23:01:04.59 UTC | 9 | 2018-01-09 10:13:45.983 UTC | null | null | null | null | 599,346 | null | 1 | 35 | android|android-sqlite | 15,595 | <p><a href="http://developer.android.com/reference/android/content/ContentUris.html#parseId%28android.net.Uri%29" rel="noreferrer">ContentUris.parseId()</a> converts the last path segment to a long.</p> |
11,943,212 | What's the purpose of gruntjs server task? | <p>I'm learning how to propel use gruntjs. I found the <a href="https://github.com/cowboy/grunt/blob/master/docs/task_server.md" rel="nofollow noreferrer">server task</a> but I can't get the point.</p>
<p>Can i use the server task mapping concatenated/minified files to test my application (uses backbone.js) without moving or placing source files in web server root? Without apache for example.</p>
<p>If no, what's the supposed use of server task?</p> | 11,943,814 | 3 | 0 | null | 2012-08-13 22:28:41.653 UTC | 28 | 2017-02-03 08:59:39.34 UTC | 2016-08-15 14:41:45.457 UTC | null | 1,783,163 | null | 220,180 | null | 1 | 62 | node.js|gruntjs | 53,482 | <p>The <code>server</code> task is used to start a static server with the <code>base</code> path set as the web root.</p>
<p>Example: Serve <code>./web-root</code> as <code>http://localhost:8080/</code>:</p>
<pre><code>grunt.initConfig({
server: {
port: 8080,
base: './web-root'
}
});
</code></pre>
<p>It will function similar to an Apache server, serving up static files based on their path, but uses the <a href="http://nodejs.org/api/http.html" rel="nofollow noreferrer">http module</a> via <a href="http://www.senchalabs.org/connect/" rel="nofollow noreferrer">connect</a> to set it up (<a href="https://github.com/gruntjs/grunt" rel="nofollow noreferrer">source</a>).</p>
<p>If you need it to serve more than just static files, then you'll want to consider <a href="https://github.com/cowboy/grunt/blob/master/docs/task_server.md#roll-your-own-%E2%9A%91" rel="nofollow noreferrer">defining a custom <code>server</code> task</a>:</p>
<pre><code>grunt.registerTask('server', 'Start a custom web server.', function() {
grunt.log.writeln('Starting web server on port 1234.');
require('./server.js').listen(1234);
});
</code></pre>
<p>And custom server instance:</p>
<pre><code>// server.js
var http = require('http');
module.exports = http.createServer(function (req, res) {
// ...
});
</code></pre>
<hr>
<blockquote>
<p>Can I use the server task mapping concatenated/minified files to test my application [...]</p>
</blockquote>
<p>Concatenation and minification have their own dedicated tasks -- <a href="https://github.com/cowboy/grunt/blob/master/docs/task_concat.md" rel="nofollow noreferrer"><code>concat</code></a> and <a href="https://github.com/cowboy/grunt/blob/master/docs/task_min.md" rel="nofollow noreferrer"><code>min</code></a> -- but could be used along with a <code>server</code> task to accomplish all 3.</p>
<hr>
<h3>Edit</h3>
<p>If you want it to persist the server for a while (as well as grunt), you could <a href="https://github.com/cowboy/grunt/blob/master/docs/types_of_tasks.md#custom-tasks-%E2%9A%91" rel="nofollow noreferrer">define the task as asynchronous</a> (with the server's <a href="http://nodejs.org/api/http.html#http_event_close" rel="nofollow noreferrer"><code>'close'</code> event</a>):</p>
<pre><code>grunt.registerTask('server', 'Start a custom web server.', function() {
var done = this.async();
grunt.log.writeln('Starting web server on port 1234.');
require('./server.js').listen(1234).on('close', done);
});
</code></pre> |
11,634,809 | Twitter bootstrap - Focus on textarea inside a modal on click | <p>Just starting to play around with bootstrap and it's amazing. </p>
<p>I'm trying to figure this out. I have a textarea for feedback inside a modal window. It works great. But I want the focus to go on the textarea when you click on the button to activate the modal. And I can't seem to get it working. </p>
<p>Here is a fiddle: <a href="http://jsfiddle.net/denislexic/5JN9A/4/" rel="noreferrer">http://jsfiddle.net/denislexic/5JN9A/4/</a></p>
<p>Here is the code:</p>
<pre><code><a class="btn testBtn" data-toggle="modal" href="#myModal" >Launch Modal</a>
<div class="modal hide" id="myModal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<textarea id="textareaID"></textarea>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
</code></pre>
<p>Here is the JS</p>
<pre><code>$('.testBtn').on('click',function(){
$('#textareaID').focus();
});
</code></pre>
<p><strong>To resume</strong>
When I click on "Launch modal" I want the modal to show up and the focus to go on the textarea.</p>
<p>Thanks for any help.</p> | 11,634,933 | 13 | 1 | null | 2012-07-24 16:01:10.277 UTC | 21 | 2016-12-16 11:57:39.437 UTC | 2015-10-21 08:35:00.627 UTC | null | 2,771,704 | null | 517,477 | null | 1 | 70 | javascript|jquery|twitter-bootstrap|focus|textarea | 87,019 | <p>It doesn't work because when you click the button the modal is not loaded yet. You need to hook the focus to an event, and going to the <a href="http://getbootstrap.com/2.3.2/javascript.html#modals" rel="noreferrer">bootstrap's modals page</a> we see the event <code>shown</code>, that <code>is fired when the modal has been made visible to the user (will wait for css transitions to complete)</code>. And that's exactly what we want.</p>
<p>Try this:</p>
<pre><code>$('#myModal').on('shown', function () {
$('#textareaID').focus();
})
</code></pre>
<p>Here's your fiddle updated: <a href="http://jsfiddle.net/5JN9A/5/" rel="noreferrer">http://jsfiddle.net/5JN9A/5/</a></p>
<hr>
<p><strong>Update:</strong></p>
<p>As <a href="https://stackoverflow.com/users/488293/mrdba">@MrDBA</a> notes, in Bootstrap 3 the event name is <a href="http://getbootstrap.com/javascript/#modals-usage" rel="noreferrer">changed</a> to <code>shown.bs.modal</code>. So, for Bootstrap 3 use:</p>
<pre><code>$('#myModal').on('shown.bs.modal', function () {
$('#textareaID').focus();
})
</code></pre>
<p>New fiddle for Bootstrap 3: <a href="http://jsfiddle.net/WV5e7/" rel="noreferrer">http://jsfiddle.net/WV5e7/</a></p> |
11,918,977 | Right mime type for SVG images with fonts embedded | <p>This is the usual SVG mime type:</p>
<pre><code>image/svg+xml
</code></pre>
<p>And it works great. However, when embedding an SVG font, chrome tells you the mime type is incorrect, obviously because you return a font instead of an image.</p>
<p>Is there any universal mime type? is chrome wrong? is <code>application/svg+xml</code> accepted somehow?</p>
<p>I guess this is still a gray area in HTML5 but someone here might know.</p> | 11,930,514 | 1 | 0 | null | 2012-08-12 01:15:31.91 UTC | 18 | 2016-05-05 16:09:11.82 UTC | 2016-05-05 16:09:11.82 UTC | null | 444,991 | null | 665,363 | null | 1 | 219 | html|svg|font-face|mime-types | 176,969 | <p>There's only <a href="http://www.w3.org/TR/SVG11/mimereg.html" rel="noreferrer">one registered mediatype</a> for SVG, and that's the one you listed, <code>image/svg+xml</code>. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the <code>image/svg+xml</code> mediatype.</p> |
19,937,880 | mysqli::query(): Couldn't fetch mysqli | <blockquote>
<p>Warning: mysqli::query(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php on line 43</p>
</blockquote>
<p>The following is my connection file:</p>
<pre><code><?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = @new mysqli("localhost","root@localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
</code></pre>
<p>This is my class:</p>
<pre><code> <?php
class EventCalendar {
private $DBConnect = NULL;
function __construct() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
function __destruct() {
if (!$this->DBConnect->connect_error) {
$this->DBConnect->close();
}
}
function __wakeup() {
// Include the database connection data
include("inc_LadleDB.php");
$this->DBConnect = $DBConnect;
}
// Function to add events to Zodiac calendar
public function addEvent($Date, $Title, $Description) {
// Check to see if the required fields of Date and Title have been entered
if ((!empty($Date)) && (!empty($Title))) {
/* if all fields are complete then they are
inserted into the Zodiac event_calendar table */
$SQLString = "INSERT INTO tblSignUps".
" (EventDate, Title, Description) ".
" VALUES('$Date', '$Title', '".
$Description."')";
// Store query results in a variable
$QueryResult = $this->DBConnect->query($SQLString);
</code></pre>
<p>I'm not great with OOP PHP and I'm not sure why this error is being raised. I pulled this code from elsewhere and the only thing I changed was the <code>@new mysqli</code> parameters. Can anyone help me to understand what is going wrong?</p> | 26,147,425 | 4 | 6 | null | 2013-11-12 19:12:59.66 UTC | 2 | 2021-10-06 14:15:28.347 UTC | 2018-03-08 16:37:54.137 UTC | null | 2,844,319 | null | 2,524,121 | null | 1 | 45 | php|mysql|mysqli | 159,751 | <p>Probably somewhere you have <strong><code>DBconnection->close();</code></strong> and then some queries try to execute .</p>
<hr>
<p><em>Hint</em>: It's sometimes mistake to insert <strong><code>...->close();</code></strong> in <strong><code>__destruct()</code></strong> (because <code>__destruct</code> is event, after which there will be a need for execution of queries) </p> |
3,643,235 | How to add a margin to a tkinter window | <p>So I have so far a simple python tkinter window and i'm adding text, buttons, etc.</p>
<p>snippet:</p>
<pre><code>class Cfrm(Frame):
def createWidgets(self):
self.text = Text(self, width=50, height=10)
self.text.insert('1.0', 'some text will be here')
self.text.tag_configure('big', font=('Verdana', 24, 'bold'))
self.text["state"] = "disabled"
self.text.grid(row=0, column=1)
self.quitw = Button(self)
self.quitw["text"] = "exit",
self.quitw["command"] = self.quit
self.quitw.grid(row=1, column=1)
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
</code></pre>
<p>the problem is, I want to have about a 15-20 px margin around the window, I looked everywhere, and I couldn't find a solution. Also </p>
<pre><code>self.text.tag_configure('big', font=('Verdana', 24, 'bold'))
</code></pre>
<p>doesn't work. Any possible solutions?</p> | 3,643,820 | 4 | 0 | null | 2010-09-04 17:09:52.43 UTC | 2 | 2021-09-19 17:32:12.237 UTC | 2021-09-19 17:32:12.237 UTC | null | 7,758,804 | null | 433,493 | null | 1 | 16 | python|tkinter | 70,510 | <p>Ok, here is the solution I found for question 1:</p>
<pre><code>self.grid(padx=20, pady=20)
</code></pre>
<p>Removing <code>.text</code> seems to change the whole frame. I still haven't solved problem 2.</p> |
3,293,652 | Throw an exception in try catch block | <pre><code>try {
if (isFileDownloaded)
// do stuff
else
throw new CustomException()
}
catch (Exception e)
{
// something went wrong to save the error to log
}
finally
{
//release resources
}
</code></pre>
<p>My question is would the <code>catch</code> catches the <code>ApplicationException</code> thrown in the try block? is it in poor coding style?</p>
<p>Should it be written in another way?</p> | 3,293,682 | 4 | 1 | null | 2010-07-20 19:34:00.327 UTC | 3 | 2021-05-01 05:00:13.453 UTC | 2021-05-01 05:00:13.453 UTC | null | 2,125,010 | null | 103,369 | null | 1 | 27 | c#|exception|try-catch-finally | 74,447 | <p>The <code>catch</code> will catch your exception (and any other that occurs). That being said, I try to avoid writing code like this when possible.</p>
<p>Personally, I see little reason to ever have exception handling (catch) for an exception thrown in the same scope. If you can handle your error in your method - put the exception handling (ie: logging) directly in the try block as well.</p>
<p>Using a <code>catch</code> is more useful, IMO, for catching exceptions thrown by methods within your <code>try</code> block. This would be more useful, for example, if your <code>// do stuff</code> section happened to call a method that raised an exception.</p>
<p>Also, I recommend not catching every exception (<code>Exception e</code>), but rather the specific types of exceptions you can handle correctly. The one exception to this would be if you're rethrowing the exception within your catch - ie: using it for logging purposes but still letting it bubble up the call stack.</p> |
3,601,672 | How does Git deal with binary files? | <ul>
<li>Do I have to do something to tell Git whether some files are binary (like in Subversion)? Or, can Git handle binary data automatically?</li>
<li>If I change the binary file, so that I have 100 binary revisions, will git just store all 100 versions individually in the repository?</li>
<li>What are submodules for with git? </li>
</ul> | 3,601,728 | 4 | 0 | null | 2010-08-30 15:10:12.68 UTC | 9 | 2020-05-09 01:39:54.927 UTC | 2020-05-09 01:39:54.927 UTC | null | 6,900,127 | null | 260,127 | null | 1 | 72 | git|binaryfiles | 61,602 | <ol>
<li>Git can usually detect binary files automatically.</li>
<li>No, Git will attempt to store delta-based changesets <a href="https://web.archive.org/web/20180811051721/https://osdir.com/ml/git/2009-04/msg01221.html" rel="noreferrer">if it's less expensive to</a> (not always the case).</li>
<li>Submodules are used if you want to reference other Git repositories within your project.</li>
</ol> |
3,467,982 | Indexing Null Values in PostgreSQL | <p>I have a query of the form:</p>
<pre><code>select m.id from mytable m
left outer join othertable o on o.m_id = m.id
and o.col1 is not null and o.col2 is not null and o.col3 is not null
where o.id is null
</code></pre>
<p>The query returns a few hundred records, although the tables have millions of rows, and it takes forever to run (around an hour).</p>
<p>When I check my index statistics using:</p>
<pre><code>select * from pg_stat_all_indexes
where schemaname <> 'pg_catalog' and (indexrelname like 'othertable_%' or indexrelname like 'mytable_%')
</code></pre>
<p>I see that only the index for othertable.m_id is being used, and that the indexes for col1..3 are not being used at all. Why is this?</p>
<p>I've read in a <a href="http://archives.postgresql.org/pgsql-performance/2005-05/msg00455.php" rel="noreferrer">few</a> <a href="http://postgresql.1045698.n5.nabble.com/Using-index-for-IS-NULL-query-td2070691.html" rel="noreferrer">places</a> that PG has traditionally not been able to index NULL values. However, I've read this has supposedly changed since PG 8.3? I'm currently using PostgreSQL 8.4 on Ubuntu 10.04. Do I need to make a "partial" or "functional" index specifically to speed up IS NOT NULL queries, or is it already indexing NULLs and I'm just misunderstanding the problem?</p> | 3,468,204 | 5 | 0 | null | 2010-08-12 13:12:16.883 UTC | 3 | 2015-03-23 20:42:22.287 UTC | null | null | null | null | 247,542 | null | 1 | 33 | sql|database|postgresql|indexing | 30,944 | <p>You could try a partial index:</p>
<pre><code>CREATE INDEX idx_partial ON othertable (m_id)
WHERE (col1 is not null and col2 is not null and col3 is not null);
</code></pre>
<p>From the docs: <a href="http://www.postgresql.org/docs/current/interactive/indexes-partial.html" rel="noreferrer">http://www.postgresql.org/docs/current/interactive/indexes-partial.html</a></p> |
3,531,438 | jQuery DataTables server-side processing using ASP.NET WebForms | <p><strong>Problem:</strong></p>
<ul><li>jQuery DataTables server-side processing using ASP.NET WebForms.</li></ul>
<p><strong>Solution:</strong></p>
<ul><li>Darin Dimitrov answered the question using an example which pages and sorts, but doesn't do any searching. Here's my **basic** modification of his work to make searching work on his example:</li></ul>
<pre><code>public class Data : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Paging parameters:
var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);
// Sorting parameters
var iSortCol = int.Parse(context.Request["iSortCol_0"]);
var iSortDir = context.Request["sSortDir_0"];
// Search parameters
var sSearch = context.Request["sSearch"];
// Fetch the data from a repository (in my case in-memory)
var persons = Person.GetPersons();
// Define an order function based on the iSortCol parameter
Func<Person, object> order = person => iSortCol == 0 ? (object) person.Id : person.Name;
// Define the order direction based on the iSortDir parameter
persons = "desc" == iSortDir ? persons.OrderByDescending(order) : persons.OrderBy(order);
// prepare an anonymous object for JSON serialization
var result = new
{
iTotalRecords = persons.Count(),
iTotalDisplayRecords = persons.Count(),
aaData = persons
.Where(p => p.Name.Contains(sSearch)) // Search: Avoid Contains() in production
.Where(p => p.Id.ToString().Contains(sSearch))
.Select(p => new[] {p.Id.ToString(), p.Name})
.Skip(iDisplayStart) // Paging
.Take(iDisplayLength)
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(result);
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
public bool IsReusable { get { return false; } }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public static IEnumerable<Person> GetPersons()
{
for (int i = 0; i < 57; i++)
{
yield return new Person { Id = i, Name = "name " + i };
}
}
}
</code></pre> | 3,601,829 | 5 | 2 | null | 2010-08-20 13:48:30.557 UTC | 25 | 2010-08-31 02:13:51.567 UTC | 2010-08-31 02:13:51.567 UTC | null | 236,169 | null | 236,169 | null | 1 | 34 | javascript|asp.net|jquery|ajax|datatables | 37,808 | <p>I wrote a simple example that should illustrate the idea.</p>
<p>Start by writing a generic handler for handling data on the server side (<code>Data.ashx</code> but this could be a web page, web service, anything server side script capable of returning JSON formated data):</p>
<pre><code>public class Data : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Those parameters are sent by the plugin
var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);
var iSortCol = int.Parse(context.Request["iSortCol_0"]);
var iSortDir = context.Request["sSortDir_0"];
// Fetch the data from a repository (in my case in-memory)
var persons = Person.GetPersons();
// Define an order function based on the iSortCol parameter
Func<Person, object> order = p =>
{
if (iSortCol == 0)
{
return p.Id;
}
return p.Name;
};
// Define the order direction based on the iSortDir parameter
if ("desc" == iSortDir)
{
persons = persons.OrderByDescending(order);
}
else
{
persons = persons.OrderBy(order);
}
// prepare an anonymous object for JSON serialization
var result = new
{
iTotalRecords = persons.Count(),
iTotalDisplayRecords = persons.Count(),
aaData = persons
.Select(p => new[] { p.Id.ToString(), p.Name })
.Skip(iDisplayStart)
.Take(iDisplayLength)
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(result);
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public static IEnumerable<Person> GetPersons()
{
for (int i = 0; i < 57; i++)
{
yield return new Person
{
Id = i,
Name = "name " + i
};
}
}
}
</code></pre>
<p>And then a WebForm:</p>
<pre><code><%@ Page Title="Home Page" Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
<title></title>
<link rel="stylesheet" type="text/css" href="/styles/demo_table.css" />
<script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" src="/scripts/jquery.dataTables.js"></script>
<script type="text/javascript">
$(function () {
$('#example').dataTable({
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': '/data.ashx'
});
});
</script>
</head>
<body>
<form id="Form1" runat="server">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
</code></pre>
<p>The example is oversimplified but I hope it will illustrate the basics on how to get stared.</p> |
3,907,354 | SELECT with multiple subqueries to same table | <p>I'm using the same SQL pattern over and over, and I know there has to be a better way, but I'm having trouble piecing it together. Here's a simple version of the pattern, where I'm pulling back the student's information and the last book they checked out, if one exists:</p>
<pre><code>SELECT TStudents.*,
BookName = (SELECT TOP 1 BookName
FROM TBookCheckouts
WHERE StudentID = TStudents.ID
ORDER BY DateCheckedOut DESC),
BookAuthor = (SELECT TOP 1 BookAuthor
FROM TBookCheckouts
WHERE StudentID = TStudents.ID
ORDER BY DateCheckedOut DESC),
BookCheckout = (SELECT TOP 1 DateCheckedOut
FROM TBookCheckouts
WHERE StudentID = TStudents.ID
ORDER BY DateCheckedOut DESC)
FROM TStudents
</code></pre>
<p>(For the sake of this example, please ignore the fact that TBookCheckouts should probably be split into TCheckouts and TBooks)</p>
<p>What I'm trying to illustrate: I tend to have a lot of subqueries for columns from the same table. I also tend to need to sort those subqueried tables by a date to get the most recent record, so it's not quite as simple (at least to me) as doing a LEFT JOIN. Notice, though, that except for which field is being returned, I'm essentially doing the same subquery 3 times. SQL Server may be smart enough to optimize that, but I'm thinking not (I definitely need to get better at reading execution plans...).</p>
<p>While there might be advantages to structuring it this way (sometimes this ends up being more readable, if I have tons of subqueries and sub-tables), it doesn't seem like this is particularly efficient.</p>
<p>I've looked into doing a LEFT JOIN from a derived table, possibly incorporating a ROW_NUMBER() and PARTITION BY, but I just can't seem to piece it all together.</p> | 3,907,793 | 8 | 2 | null | 2010-10-11 14:55:04.47 UTC | 3 | 2018-08-23 06:35:02.077 UTC | 2010-10-11 15:59:23.44 UTC | null | 135,152 | null | 25,538 | null | 1 | 16 | sql|sql-server|tsql|subquery | 76,200 | <p>If you are using SQL Server 2005 and later, you can use a ranking function like so:</p>
<pre><code>With LastCheckout As
(
Select StudentId, BookName, BookAuthor, DateCheckedOut
, Row_Number() Over ( Partition By StudentId Order By DateCheckedOut Desc) As CheckoutRank
From TBookCheckouts
)
Select ..., LastCheckout.BookName, LastCheckout.BookAuthor, LastCheckout.DateCheckedOut
From TStudents
Left Join LastCheckout
On LastCheckout.StudentId = TStudents.StudentId
And LastCheckout.CheckoutRank = 1
</code></pre> |
3,759,440 | The Guava library: What are its most useful and/or hidden features? | <p>I have had a quick scan of the <a href="https://google.github.io/guava/releases/snapshot/api/docs/" rel="noreferrer">Guava API</a> and the new collection types it provides(<code>Multimap</code> and <code>BiMap</code> for example appear useful) and I am thinking of including the library in the project(s) I work on.</p>
<p>However, I also have a reticence to include libraries willy-nilly if they are of no great benefit and learning the features wastes valuable time.</p>
<p>Have you included the Guava library in your project and has it proved useful in any unexpected way? Would you always use it in the future? What has been its main benefit/time saver? What are its hidden features?</p> | 3,761,140 | 8 | 3 | null | 2010-09-21 10:35:03.523 UTC | 130 | 2018-10-20 16:04:51.923 UTC | 2018-10-20 16:04:51.923 UTC | null | 452,775 | null | 106,261 | null | 1 | 131 | java|guava | 43,826 | <p>Seriously, everything in Guava is useful. I've been using it for quite a while, and am still always discovering something new I can do with it that takes less code than doing it by hand.</p>
<p>Some things others have not really mentioned that I love:</p>
<ul>
<li><code>Multimap</code>s are just great. Any time you would use something like <code>Map<Foo, Collection<Bar>></code>, use a multimap instead and save yourself a ton of tedious checking for an existing collection mapped to a key and creating and adding it if it isn't there.</li>
<li><code>Ordering</code> is great for building <code>Comparator</code>s that behave just how you want.</li>
<li><code>Maps.uniqueIndex</code> and <code>Multimaps.index</code>: these methods take an <code>Iterable</code> and a <code>Function</code> and build an <code>ImmutableMap</code> or <code>ImmutableListMultimap</code> that indexes the values in the <code>Iterable</code> by the result of applying the function to each. So with a function that retrieves the ID of an item, you can index a list of items by their ID in one line.</li>
<li>The functional stuff it provides... <code>filter</code>, <code>transform</code>, etc. Despite the verbosity of using classes for <code>Function</code>s and <code>Predicate</code>s, I've found this useful. I give an example of one way to make this read nicely <a href="http://blog.cgdecker.com/2010/06/property-interfaces-and-guava.html" rel="noreferrer">here</a>.</li>
<li><code>ComparisonChain</code> is a small, easily overlooked class that's useful when you want to write a comparison method that compares multiple values in succession and should return when the first difference is found. It removes all the tedium of that, making it just a few lines of chained method calls.</li>
<li><code>Objects.equal(Object,Object)</code> - null safe equals.</li>
<li><code>Objects.hashCode(Object...)</code> - easy way to get a hash code based on multiple fields of your class.</li>
<li><code>Objects.firstNonNull(Object,Object)</code> - reduces the code for getting a default value if the first value is null, especially if the first value is the result of a method call (you'd have to assign it to a variable before doing this the normal way).</li>
<li><code>CharMatcher</code>s were already mentioned, but they're very powerful.</li>
<li><code>Throwables</code> lets you do some nice things with throwables, such as <code>Throwables.propagate</code> which rethrows a throwable if it's a <code>RuntimeException</code> or an <code>Error</code> and wraps it in a <code>RuntimeException</code> and throws that otherwise.</li>
</ul>
<p>I could certainly go on, but I have to get to work. =) Anyway, despite my having listed some things I like here, the fact is that everything in Guava is useful in some situation or another. Much of it is useful very often. As you use it, you'll discover more uses. Not using it will feel a bit like having one hand tied behind your back.</p> |
3,753,634 | Check if an element is a child of a parent | <p>I have the following code.</p>
<pre><code><html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<div id="hello">Hello <div>Child-Of-Hello</div></div>
<br />
<div id="goodbye">Goodbye <div>Child-Of-Goodbye</div></div>
<script type="text/javascript">
<!--
function fun(evt) {
var target = $(evt.target);
if ($('div#hello').parents(target).length) {
alert('Your clicked element is having div#hello as parent');
}
}
$(document).bind('click', fun);
-->
</script>
</html>
</code></pre>
<p>I expect only when <code>Child-Of-Hello</code> being clicked, <code>$('div#hello').parents(target).length</code> will return >0.</p>
<p>However, it just happen whenever I click on anywhere.</p>
<p>Is there something wrong with my code?</p> | 3,753,701 | 9 | 0 | null | 2010-09-20 16:54:15.03 UTC | 18 | 2022-05-15 22:46:52.443 UTC | 2022-05-15 22:46:52.443 UTC | null | 2,444,959 | null | 72,437 | null | 1 | 130 | javascript|jquery|css-selectors | 167,139 | <p>If you are only interested in the direct parent, and not other ancestors, you can just use <code>parent()</code>, and give it the selector, as in <code>target.parent('div#hello')</code>.</p>
<p><strong>Example:</strong> <a href="http://jsfiddle.net/6BX9n/" rel="noreferrer">http://jsfiddle.net/6BX9n/</a></p>
<pre><code>function fun(evt) {
var target = $(evt.target);
if (target.parent('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}
</code></pre>
<p>Or if you want to check to see if there are any ancestors that match, then use <code>.parents()</code>.</p>
<p><strong>Example:</strong> <a href="http://jsfiddle.net/6BX9n/1/" rel="noreferrer">http://jsfiddle.net/6BX9n/1/</a></p>
<pre><code>function fun(evt) {
var target = $(evt.target);
if (target.parents('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}
</code></pre> |
3,610,604 | how to take a screenshot of the iPhone programmatically? | <p>Is it possible in objective C that we can take the screen shot of screen and stored this image in UIImage.</p> | 3,611,033 | 11 | 2 | null | 2010-08-31 15:32:54.7 UTC | 13 | 2018-11-21 19:59:21.003 UTC | 2012-04-04 15:08:37.23 UTC | null | 579,628 | null | 423,912 | null | 1 | 14 | iphone|objective-c|cocoa-touch | 30,663 | <p>You need to create a bitmap context of the size of your screen and use</p>
<pre><code>[self.view.layer renderInContext:c]
</code></pre>
<p>to copy your view in it. Once this is done, you can use </p>
<pre><code>CGBitmapContextCreateImage(c)
</code></pre>
<p>to create a CGImage from your context.</p>
<p>Elaboration :</p>
<pre><code>CGSize screenSize = [[UIScreen mainScreen] applicationFrame].size;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(nil, screenSize.width, screenSize.height, 8, 4*(int)screenSize.width, colorSpaceRef, kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(ctx, 0.0, screenSize.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
[(CALayer*)self.view.layer renderInContext:ctx];
CGImageRef cgImage = CGBitmapContextCreateImage(ctx);
UIImage *image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
CGContextRelease(ctx);
[UIImageJPEGRepresentation(image, 1.0) writeToFile:@"screen.jpg" atomically:NO];
</code></pre>
<p>Note that if you run your code in response to a click on a UIButton, your image will shows that button pressed.</p> |
3,253,676 | How to fix "process is bad" error for an Android Widget? | <p>I have developed an Android Widget, and it was working fine. I added some extra functionality and pushed an update through the Android Market. Now people are complaining that it doesn't work anymore.</p>
<p>The error I see in the logs is:</p>
<pre><code>07-14 10:33:44.016: WARN/ActivityManager(78): Unable to launch app ...
for broadcast Intent { act=android.appwidget.action.APPWIDGET_ENABLED
cmp=... }: process is bad
07-14 10:33:44.026: WARN/ActivityManager(78): finishReceiver called
but none active
07-14 10:33:44.026: WARN/ActivityManager(78): Unable to launch app ...
for broadcast Intent { act=android.appwidget.action.APPWIDGET_UPDATE
cmp=... (has extras) }: process is bad
07-14 10:33:44.036: WARN/ActivityManager(78): finishReceiver called
but none active
</code></pre>
<p>I have searched, but I cannot find anywhere what the process is bad error means, so I have no clue on how to fix it.
Restarting the phone (or emulator) makes the error go away, however, that is not what I want my users to do.
Could someone please help me to explain what the cause of the error is and how to fix it?</p> | 3,895,595 | 14 | 2 | null | 2010-07-15 08:15:11.317 UTC | 23 | 2019-09-09 21:03:01.967 UTC | 2011-06-15 02:12:36.08 UTC | null | 2,598 | null | 392,445 | null | 1 | 50 | android|android-widget | 25,462 | <p>I am having the same problem and my current theory is that the appWidget crashed and when it was restarted it had the same bad persistent data that made it crash each time it was restarted. When this happens too often, the appWidget is "force stopped" by the OS. My band aid is to have a touch event that is "setOnClickPending" that the user will touch (out of frustration if necessary) and that will be processed internal to the appWidget and reset the appWidget.</p> |
7,888,568 | What are the advantages and disadvantages of using ARC? | <p>What are the advantages and disadvantages of using the new automatic reference counting (ARC) memory management style in an iOS project?</p>
<p>Can you choose not to use ARC when developing with the iOS 5.0 SDK?</p>
<p>Do you recommend ARC or manual reference counting (MRC) for a new project?</p>
<p>Will an application using ARC be able to run on older OS versions than iOS 5.0?</p> | 7,888,848 | 4 | 1 | null | 2011-10-25 11:29:14.477 UTC | 17 | 2012-03-31 14:25:46.88 UTC | 2011-11-04 19:46:57.437 UTC | null | 191,596 | null | 141,302 | null | 1 | 42 | iphone|ios|ios5|automatic-ref-counting|reference-counting | 11,905 | <blockquote>
<p>What are the advantages and disadvantages of using the new automatic reference counting (ARC) memory management style in an iOS project?</p>
</blockquote>
<p>An ARC program's execution is nearly identical to well written MRC. That is, the behavioral differences are often undetectable because both the order of operations and performance are very close.</p>
<p>If you already know how to implement OS X or iOS apps with manual reference counting (MRC), ARC doesn't really add functionality -- it just allows you to remove reference counting operations from your sources.</p>
<p>If you don't want to learn MRC, then you may want to first try ARC. A lot of people struggle with, or try to ignore common practices of MRC (example: I've introduced a number of objc devs to the static analyzer). If you want to avoid those issues, ARC will allow you to postpone your understanding; you cannot write nontrivial objc programs without understanding reference counting and object lifetimes and relationships, whether MRC, ARC, or GC. ARC and GC simply remove the implementation from your sources and do the right thing <em>in most cases</em>. With ARC and GC, you will still need to give some guidance.</p>
<p>I've not measured this, but it may be worth mentioning that <em>compiling</em> ARC sources would take more time and resources.</p>
<p>If the program you're developing has rather loose usage of reference counting (e.g. a typical amount of autoreleases), switching to ARC <em>could</em> really improve your program's execution times and peak memory usage.</p>
<blockquote>
<p>Can you choose not to use ARC when developing with the iOS 5.0 SDK?</p>
</blockquote>
<p>Yes, using CLANG_ENABLE_OBJC_ARC. ARC is binary compatible, and all that really happens is that the compiler does its best to introduce the appropriate reference counting operations automatically for you, based on the declarations visible to the current translation (<a href="https://stackoverflow.com/questions/7770872/deep-copy-of-dictionaries-gives-analyze-error-in-xcode-4-2/7770914#7770914">see my answer here as to why translation visibility is important</a>). Therefore, you can also enable and disable it for some sources in a project and enable it for others.</p>
<p>Mixed mode (some MRC and some ARC sources) is however quite complicated, and subtly, notably wrt implementations which may be duplicated by the compiler (e.g. an inline function's body may be incorrect). Such mixed mode issues will be very difficult to isolate. ObjC++ programs and sources will be <em>particularly</em> difficult in this regard. Furthermore, the behavior may differ based on your optimizations settings (as one example); a program which works perfectly in a debug build may introduce a leak or zombie in release.</p>
<blockquote>
<p>Do you recommend ARC or manual reference counting (MRC) for a new project?</p>
</blockquote>
<p>Personally, I'll be sticking with MRC for some time. Even if ARC has been tested in real world usage, it's likely that there are a number issues remaining which show up in complex scenarios, which you will want to avoid being the first to know and debug. OS X's Garbage Collection is an example of why you may want to wait. As one example, the switch could alter when objects are destroyed -- your objects may be destroyed sooner and never be placed in autorelease pools. It could also change the order in which ivars are released, which could have some side effects.</p>
<p>I also have a large codebase that I don't want to lose a week testing this feature for at this time. Finally, backwards compatibility is still important for me.</p>
<blockquote>
<p>Will an application using ARC be able to run on older OS versions than iOS 5.0?</p>
</blockquote>
<p>If you develop with MRC, it will be backwards compatible. If you develop with ARC, it will not necessarily be compatible. In fact, it may not even compile without a little extra work. The requirements for the runtime are available in some earlier versions. <a href="https://stackoverflow.com/questions/7768861/xcode-4-2-with-arc-will-my-code-run-even-on-ios-devices-with-firmware-older-tha">See also this question</a>. If you need backwards compatibility, ARC will not be an option for some OS versions.</p>
<p>Lastly, if you were to limit the choice to GC or ARC, I'd recommend ARC.</p> |
8,265,583 | Dividing Python module into multiple regions | <p>In C# we can create regions by using </p>
<pre><code>#region
// some methods
#endregion
</code></pre>
<p>Is there any way to format python code in similar fashion so that I can keep all my relevant methods in one block?</p> | 8,265,687 | 11 | 0 | null | 2011-11-25 06:42:57.093 UTC | 15 | 2022-09-06 02:48:21.493 UTC | 2017-05-30 12:26:58.963 UTC | null | 447,490 | null | 971,673 | null | 1 | 80 | python|formatting | 64,060 | <p>I recommend you have a look at <a href="http://pydev.org/" rel="noreferrer">PyDev</a>. If you structure your Python code well it will be very useful to have a document outline and code folding. Unfortunately I don't think you can do arbitrary structures like #region C# (VS) or #pragma mark in C/C++/ObjC (Xcode/CDT).</p> |
7,913,086 | How to set default value for form field in Symfony2? | <p>Is there an easy way to set a default value for text form field?</p> | 7,914,429 | 22 | 7 | null | 2011-10-27 07:56:54.173 UTC | 21 | 2019-08-27 06:22:48.863 UTC | null | null | null | null | 206,720 | null | 1 | 145 | php|symfony | 225,012 | <p>Can be use during the creation easily with :</p>
<pre><code>->add('myfield', 'text', array(
'label' => 'Field',
'empty_data' => 'Default value'
))
</code></pre> |
4,542,438 | Adding summary information to a density plot created with ggplot | <p>I have a density plot and I would like to add some summary information such as placing a line at the median and shading the 90% credible intervals (5th and 95th quantiles). Is there a way to do this in ggplot? </p>
<p>This is the type of plot that I would like to summarize:</p>
<p>I can figure out how to draw a line from the y=0 to y= density(median(x)), but it is not clear to me if I can shade the plot with a 90% CI. Alternatively, I could add a horizontal boxplot above the density plot, but it is not clear how to rotate the boxplot by itself, without rotating the density plot along with it. </p>
<pre><code>x <- as.vector(rnorm(10000))
d <- as.data.frame(x=x)
library(ggplot2)
ggplot(data = d) + theme_bw() +
geom_density(aes(x=x, y = ..density..), color = 'black')
</code></pre>
<p><img src="https://i.stack.imgur.com/NOGdN.png" alt="alt text"></p> | 4,542,637 | 3 | 0 | null | 2010-12-27 22:55:57.767 UTC | 11 | 2017-04-09 03:17:32.937 UTC | 2010-12-27 23:05:56.643 UTC | null | 199,217 | null | 199,217 | null | 1 | 8 | r|statistics|visualization|ggplot2 | 12,670 | <p>You can use the geom_area() function. First make the density explicit using the density() function.</p>
<pre><code>x <- as.vector(rnorm(10000))
d <- as.data.frame(x=x)
library(ggplot2)
p <- ggplot(data = d) + theme_bw() +
geom_density(aes(x=x, y = ..density..), color = 'black')
# new code is below
q5 <- quantile(x,.05)
q95 <- quantile(x,.95)
medx <- median(x)
x.dens <- density(x)
df.dens <- data.frame(x = x.dens$x, y = x.dens$y)
p + geom_area(data = subset(df.dens, x >= q5 & x <= q95),
aes(x=x,y=y), fill = 'blue') +
geom_vline(xintercept = medx)
</code></pre>
<p><img src="https://i.stack.imgur.com/p7RJo.png" alt="alt text"></p> |
4,806,033 | Converting empty String to null Date object with Spring | <p>I have a form field that should be converted to a Date object, as follows:</p>
<pre><code><form:input path="date" />
</code></pre>
<p>But I want to get a null value when this field is empty, instead of that I receive:</p>
<pre><code>Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date';
org.springframework.core.convert.ConversionFailedException: Unable to convert value "" from type 'java.lang.String' to type 'java.util.Date';
</code></pre>
<p>Is there an easy way to indicate that empty Strings should be converted to null? Or should I write my own <strong>PropertyEditor</strong>?</p>
<p>Thanks!</p> | 4,806,886 | 3 | 3 | null | 2011-01-26 15:03:09.35 UTC | 12 | 2020-10-03 14:23:38.357 UTC | 2011-01-26 15:12:41.143 UTC | null | 264,028 | null | 264,028 | null | 1 | 31 | java|spring|spring-mvc | 26,691 | <p>Spring provides a PropertyEditor named <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/propertyeditors/CustomDateEditor.html" rel="noreferrer">CustomDateEditor</a> which you can configure to convert an empty String to a null value. You typically have to register it in a <code>@InitBinder</code> method of your controller:</p>
<pre><code>@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
// true passed to CustomDateEditor constructor means convert empty String to null
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
</code></pre> |
14,752,012 | Invalid Operands to binary Expression, C | <p>Im working on a function that takes some values and finds the min, max, and average of the values. I'm passing everything to the function by reference and am getting some errors when I try and do basic operations like <code>+</code> and <code>/</code> Namely the error is</p>
<blockquote>
<p>Invalid operands to binary expression ('double *' and 'double *')</p>
</blockquote>
<pre><code>void MinMaxAvg(double *pA, double *min, double *max, double *avg, int lines, double *total )
{
for (int i=0; i<lines; i++)
{
if ( i==0)
{
min = &pA[0];
max = &pA[0];
}
else
{
if (&pA[i] < min)
{
min = &pA[i];
}
if (&pA[i] > max)
{
max = &pA[i];
}
}
total += &pA[i]; //<-- Errors on this line
}
avg = (total / lines); // <-- Errors on this line.
}
</code></pre> | 14,752,129 | 3 | 0 | null | 2013-02-07 13:14:16.85 UTC | 1 | 2016-03-18 21:38:06.097 UTC | 2016-03-18 21:38:06.097 UTC | null | 4,561,047 | null | 2,009,298 | null | 1 | 3 | c | 46,856 | <p>It seems like you're getting some of the types confused there. In your example you're setting the <em>pointers</em> to a new value, not the value of said pointers.</p>
<p>The first would have to be:</p>
<pre><code>*total += pA[i];
</code></pre>
<p>While the second should be:</p>
<pre><code>*avg = (*total / lines);
</code></pre>
<p>In fact, you probably want to use floating point division on the second error there (some compilers are notorious for using integer divison in unexpected places):</p>
<pre><code>*avg = (*total / (double)lines);
</code></pre>
<p>You'll still be getting errors if you do it like that, however. For example <code>&pA[i] > ...</code> will result in a pointer comparison, i.e. the <em>address</em> of the pointers will be compared. Most likely not what you want.</p> |
14,870,551 | C# Get substring with specific pattern from string | <p>I have a list of strings like this:</p>
<pre><code>List<string> list = new List<string>();
list.Add("Item 1: #item1#");
list.Add("Item 2: #item2#");
list.Add("Item 3: #item3#");
</code></pre>
<p>How can I get and add the substrings #item1#, #item2# etc into a new list?</p>
<p>I am only able to get the complete string if it contains a "#" by doing this:</p>
<pre><code>foreach (var item in list)
{
if(item.Contains("#"))
{
//Add item to new list
}
}
</code></pre> | 14,870,621 | 7 | 2 | null | 2013-02-14 08:24:07.737 UTC | null | 2013-02-14 09:36:38.59 UTC | null | null | null | null | 958,787 | null | 1 | 7 | c#|.net|string|list|substring | 43,282 | <p>You could have a look at <a href="http://msdn.microsoft.com/en-us/library/0z2heewz.aspx"><code>Regex.Match</code></a>. If you know a little bit about regular expressions (in your case it would be a quite simple pattern: <code>"#[^#]+#"</code>), you can use it to extract all items starting and ending with <code>'#'</code> with any number of other characters other than <code>'#'</code> in between.</p>
<p>Example: </p>
<pre><code>Match match = Regex.Match("Item 3: #item3#", "#[^#]+#");
if (match.Success) {
Console.WriteLine(match.Captures[0].Value); // Will output "#item3#"
}
</code></pre> |
4,358,771 | Updating a Haystack search index with Django + Celery | <p>In my Django project I am using Celery. I switched over a command from crontab to be a periodic task and it works well but it is just calling a method on a model. Is it possible to update my Haystack index from a periodic task as well? Has anyone done this?</p>
<pre><code>/manage.py update_index
</code></pre>
<p>That's the command to update the index from the Haystack documentation but I'm not sure how to call that from a task.</p> | 4,372,357 | 4 | 4 | null | 2010-12-05 12:28:28.49 UTC | 13 | 2017-08-16 16:00:11.207 UTC | 2017-08-16 16:00:11.207 UTC | null | 3,885,376 | null | 226,208 | null | 1 | 31 | python|django|indexing|celery|django-haystack | 8,584 | <p>the easiest way to do this would probably be to run the management command directly from python and run it in your task</p>
<pre><code>from haystack.management.commands import update_index
update_index.Command().handle()
</code></pre> |
4,641,346 | CSS to align label and input | <p>HTML Code Snippet:</p>
<pre><code><fieldset id="o-bs-sum-buginfo">
<label for="o-bs-sum-bug-ErrorPrefix">Error Prefix</label>
<input type="text" id="o-bs-sum-bug-ErrorPrefix" name="ErrorPrefix" value="" />
<label for="o-bs-sum-bug-ErrorNumber">Error Number</label>
<input type="text" id="o-bs-sum-bug-ErrorNumber" name="ErrorNumber" value="" />
....
</fieldset>
</code></pre>
<p>Using only CSS (or jquery), irrespective of the browser size, I want to pair label and input elements next to each other. I also do have freedom to change tweak the HTML. if required.</p> | 4,641,390 | 6 | 0 | null | 2011-01-09 19:46:50.21 UTC | 20 | 2016-01-07 21:14:29.56 UTC | null | null | null | null | 1,104,241 | null | 1 | 41 | jquery|html|css|input|label | 71,194 | <p>This is one of those things which can be surprisingly tricky to get right.</p>
<p>Many people will suggest using <code>float:left;</code> for this. Personally, I really dislike floats; they seem to cause more problems than they solve.</p>
<p>My preference is to use inline-block. This is a display method that combines inline properties (so you can easily align elements next to each other, etc) with block properties (such as being able to specify dimensions).</p>
<p>So the answer is simply to make them both <code>display:inline-block;</code> and give the prompts a fixed width, which will make the input fields next to them line up.</p>
<p>You'll also need some sort of line feed or break after the input field, otherwise the next prompt will appear on the same line, which isn't the desired effect. The best way to achieve this is to put each prompt and its field into a container <code><div></code>.</p>
<p>So your HTML will look like this:</p>
<pre><code><fieldset id="o-bs-sum-buginfo" class="myfields">
<div>
<label for="o-bs-sum-bug-ErrorPrefix">Error Prefix</label>
<input type="text" id="o-bs-sum-bug-ErrorPrefix" name="ErrorPrefix" value="" />
</div>
<div>
<label for="o-bs-sum-bug-ErrorNumber">Error Number</label>
<input type="text" id="o-bs-sum-bug-ErrorNumber" name="ErrorNumber" value="" />
</div>
....
</fieldset>
</code></pre>
<p>and your CSS will look like this:</p>
<pre><code>.myfields label, .myfields input {
display:inline-block;
}
.myfields label {
width:200px; /* or whatever size you want them */
}
</code></pre>
<p>Hope that helps.</p>
<p><strong>Edit</strong>:
you can use this plugin for setting the width of each label:</p>
<pre><code>jQuery.fn.autoWidth = function(options)
{
var settings = {
limitWidth : false
}
if(options) {
jQuery.extend(settings, options);
};
var maxWidth = 0;
this.each(function(){
if ($(this).width() > maxWidth){
if(settings.limitWidth && maxWidth >= settings.limitWidth) {
maxWidth = settings.limitWidth;
} else {
maxWidth = $(this).width();
}
}
});
this.width(maxWidth);
}
</code></pre>
<p><a href="http://www.jankoatwarpspeed.com/post/2008/07/09/Justify-elements-using-jQuery-and-CSS.aspx" rel="noreferrer">from this page in a comment</a></p>
<p>and you use it this way:</p>
<pre><code>$("div.myfields div label").autoWidth();
</code></pre>
<p>and thats all... all your labels are going to take the width of the longest label</p> |
4,748,655 | How do I make $.serialize() take into account those disabled :input elements? | <p>It seems by default disabled input elements are ignored by <code>$.serialize()</code>. Is there a workaround?</p> | 4,748,748 | 9 | 1 | null | 2011-01-20 15:01:21.857 UTC | 22 | 2021-11-23 10:31:12.833 UTC | 2018-08-03 03:43:52.527 UTC | null | 63,550 | null | 522,431 | null | 1 | 147 | jquery|serialization | 67,289 | <p>Temporarily enable them.</p>
<pre><code>var myform = $('#myform');
// Find disabled inputs, and remove the "disabled" attribute
var disabled = myform.find(':input:disabled').removeAttr('disabled');
// serialize the form
var serialized = myform.serialize();
// re-disabled the set of inputs that you previously enabled
disabled.attr('disabled','disabled');
</code></pre> |
4,480,652 | Android animation does not repeat | <p>I'm trying to make simple animation that would repeat several times (or infinitely).<br/>
It seems that <code>android:repeatCount</code> does not work!<br/>
Here is my animation resource from <code>/res/anim/first_animation.xml</code> :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false"
android:repeatCount="infinite"
>
<scale
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:toXScale="1.2"
android:toYScale="1.2"
android:pivotX="50%"
android:pivotY="50%"
android:fillAfter="false" />
<scale
android:interpolator="@android:anim/accelerate_interpolator"
android:startOffset="500"
android:duration="500"
android:fromXScale="1.2"
android:fromYScale="1.2"
android:toXScale="1.0"
android:toYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:fillAfter="false" />
</set>
</code></pre>
<p>First it should scale image from 1.0 to 1.2 size in 500 ms.<br/>
And then scale it back to 1.0 in 500 ms.<br/>
Here is how I'm using it:<br/></p>
<pre><code>Animation firstAnimation = AnimationUtils.loadAnimation(this, R.anim.first_animation);
imgView.startAnimation(firstAnimation);
</code></pre>
<p>It makes one cycle and then finishes. <br/>
It scales up, then scales down ans then stops.<br/>
<br/>
<strong>How can I make this work as intended?</strong></p> | 6,351,812 | 23 | 1 | null | 2010-12-18 23:04:34.387 UTC | 19 | 2020-06-04 16:51:57.14 UTC | 2015-02-21 05:47:47.17 UTC | null | 203,673 | null | 420,951 | null | 1 | 87 | android|animation | 99,951 | <p><strong>Update:</strong> Back in Sep, 2011 an Android engineer fixed this issue for the most part. The attributes that were ignored in XML now work, with the exception of <code>repeatCount</code> and <code>fillEnabled</code> which are still ignored (on purpose for some reason). This means it still isn't easy to repeat an <code>AnimationSet</code> unfortunately.</p>
<p>For details please see the overview in the <a href="http://developer.android.com/reference/android/view/animation/AnimationSet.html" rel="noreferrer">updated docs</a> (explains which attributes are ignored, which work, and which are passed onto children). And for a deeper understanding of what <code>fillAfter</code>, <code>fillBefore</code>, and <code>fillEnabled</code> actually do, see the engineer's (Chet Haase) blog post about it <a href="http://graphics-geek.blogspot.com/2011/08/mysterious-behavior-of-fillbefore.html" rel="noreferrer">here</a>.</p>
<hr>
<h2>Original Answer</h2>
<p>To expand upon answers by Pavel and others: it is true that the <code><set></code> tag is ridiculously buggy. It can't deal correctly with <code>repeatCount</code> and a number of other attributes.</p>
<p>I spent a few hours figuring out what it can and can't deal with and have submitted a bug report/issue here: <a href="https://code.google.com/p/android/issues/detail?id=17662" rel="noreferrer">Issue 17662</a></p>
<p>In summary (this concerns <code>AnimationSet</code>s):</p>
<blockquote>
<p>setRepeatCount() / android:repeatCount</p>
<blockquote>
<p>This attribute (as well as repeatMode) does not work in code or XML. This makes repeating an entire set of animations difficult.</p>
</blockquote>
<p>setDuration() / android:duration </p>
<blockquote>
<p>Setting this on an AnimationSet in code WORKS (overrides all durations of children animations), but not when included in the tag in XML</p>
</blockquote>
<p>setFillAfter() / android:fillAfter </p>
<blockquote>
<p>This works in both code and XML for the tag. Strangely I have gotten it to also work without the need to set fillEnabled to true.</p>
</blockquote>
<p>setFillBefore() / android:fillBefore </p>
<blockquote>
<p>Seems to have no effect/ignored in both code and XML</p>
</blockquote>
<p>setFillEnabled() / android:fillEnabled</p>
<blockquote>
<p>Seems to have no effect/ignored in both code and XML. I can still get fillAfter to work even without including fillEnabled or setting fillEnabled to false.</p>
</blockquote>
<p>setStartOffset() / android:startOffset</p>
<blockquote>
<p>This works only in code and not XML.</p>
</blockquote>
</blockquote> |
14,630,335 | How to select R data.table rows based on substring match (a la SQL like) | <p>I have a data.table with a character column, and want to select only those rows that contain a substring in it. Equivalent to SQL <code>WHERE x LIKE '%substring%'</code></p>
<p>E.g.</p>
<pre><code>> Months = data.table(Name = month.name, Number = 1:12)
> Months["mb" %in% Name]
Empty data.table (0 rows) of 2 cols: Name,Number
</code></pre>
<p>How would I select only the rows where Name contains "mb"?</p> | 14,630,872 | 2 | 0 | null | 2013-01-31 16:20:05.273 UTC | 31 | 2013-01-31 16:56:07.023 UTC | null | null | null | null | 1,900,520 | null | 1 | 60 | r|data.table|string-matching | 78,829 | <p><code>data.table</code> has a <code>like</code> function.</p>
<pre><code>Months[like(Name,"mb")]
Name Number
1: September 9
2: November 11
3: December 12
</code></pre>
<p>Or, <code>%like%</code> looks nicer :</p>
<pre><code>> Months[Name %like% "mb"]
Name Number
1: September 9
2: November 11
3: December 12
</code></pre>
<p>Note that <code>%like%</code> and <code>like()</code> use <code>grepl</code> (returns logical vector) rather than <code>grep</code> (returns integer locations). That's so it can be combined with other logical conditions :</p>
<pre><code>> Months[Number<12 & Name %like% "mb"]
Name Number
1: September 9
2: November 11
</code></pre>
<p>and you get the power of regular expression search (not just % or * wildcard), too.</p> |
26,953,591 | How to convert a double into a byte array in swift? | <p>I know how to do it in java (see <a href="https://stackoverflow.com/questions/2905556/how-can-i-convert-a-byte-array-into-a-double-and-back">here</a>), but I couldn't find a swift equivalent for java's ByteBuffer, and consequently its .putDouble(double value) method.
</p>Basically, I'm looking for a function like this:</p>
<pre><code>func doubleToByteArray(value: Double) -> [UInt8]? {
. . .
}
doubleToByteArray(1729.1729) // should return [64, 155, 4, 177, 12, 178, 149, 234]
</code></pre> | 26,954,091 | 7 | 0 | null | 2014-11-16 03:58:29.467 UTC | 12 | 2018-11-29 08:25:58.723 UTC | 2017-05-23 12:17:50.79 UTC | null | -1 | null | 1,388,497 | null | 1 | 20 | ios|swift|byte|bytearray|bytebuffer | 23,274 | <pre><code>typealias Byte = UInt8
func toByteArray<T>(var value: T) -> [Byte] {
return withUnsafePointer(&value) {
Array(UnsafeBufferPointer(start: UnsafePointer<Byte>($0), count: sizeof(T)))
}
}
toByteArray(1729.1729)
toByteArray(1729.1729 as Float)
toByteArray(1729)
toByteArray(-1729)
</code></pre>
<p>But the results are reversed from your expectations (because of endianness):</p>
<pre><code>[234, 149, 178, 12, 177, 4, 155, 64]
[136, 37, 216, 68]
[193, 6, 0, 0, 0, 0, 0, 0]
[63, 249, 255, 255, 255, 255, 255, 255]
</code></pre>
<hr>
<p>Added:</p>
<pre><code>func fromByteArray<T>(value: [Byte], _: T.Type) -> T {
return value.withUnsafeBufferPointer {
return UnsafePointer<T>($0.baseAddress).memory
}
}
let a: Double = 1729.1729
let b = toByteArray(a) // -> [234, 149, 178, 12, 177, 4, 155, 64]
let c = fromByteArray(b, Double.self) // -> 1729.1729
</code></pre>
<hr>
<p>For Xcode8/Swift3.0:</p>
<pre><code>func toByteArray<T>(_ value: T) -> [UInt8] {
var value = value
return withUnsafePointer(to: &value) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<T>.size) {
Array(UnsafeBufferPointer(start: $0, count: MemoryLayout<T>.size))
}
}
}
func fromByteArray<T>(_ value: [UInt8], _: T.Type) -> T {
return value.withUnsafeBufferPointer {
$0.baseAddress!.withMemoryRebound(to: T.self, capacity: 1) {
$0.pointee
}
}
}
</code></pre>
<hr>
<p>For Xcode8.1/Swift3.0.1</p>
<pre><code>func toByteArray<T>(_ value: T) -> [UInt8] {
var value = value
return withUnsafeBytes(of: &value) { Array($0) }
}
func fromByteArray<T>(_ value: [UInt8], _: T.Type) -> T {
return value.withUnsafeBytes {
$0.baseAddress!.load(as: T.self)
}
}
</code></pre> |
27,666,517 | certutil: function failed: SEC_ERROR_LEGACY_DATABASE: The certificate/key database is in an old, unsupported format | <p>I had downloaded a verified (not self-signed) S/MIME certificate with iceweasel (firefox) which was stored in cert8.db</p>
<p>Then I used:</p>
<pre><code>certutil -L -d <path_to_folder_that_cert8.db_resides>
</code></pre>
<p>in order to list the certificates, and then I extracted the .p12 file using the name of my certificate that certutil gave me:</p>
<pre><code>pk12util -o mycertfile.p12 -n "<name_found_from_certutil>" -d <path_to_folder_that_cert8.db_resides>
</code></pre>
<p>The problem is that <strong>I lost the access</strong> to the PC that the p12 was stored and now I have only <strong>a cert8.db copy</strong> to another PC. Thus I repeated the <code>certutil && pk12util</code> commands, but certutil fails with:</p>
<pre><code>certutil: function failed: SEC_ERROR_LEGACY_DATABASE: The certificate/key database is in an old, unsupported format.
</code></pre>
<p>I have desperately tried at 3 different computers, including one with identical kernel and <code>libnss3-tools</code> version, (like the initial desktop where I extracted the p12 successfully) which is:</p>
<pre><code>$ uname -a
Linux commander 3.16.0-4-amd64 #1 SMP Debian 3.16.7-2 (2014-11-06) x86_64 GNU/Linux
</code></pre>
<p><code>libnss3-tools</code> version: 2:3.17.2-1</p>
<p>Any thoughts?</p>
<p>Thanks</p> | 32,197,081 | 4 | 1 | null | 2014-12-27 10:49:31.09 UTC | 2 | 2018-07-09 10:16:00.887 UTC | 2018-07-09 10:16:00.887 UTC | null | 2,363,252 | null | 2,363,252 | null | 1 | 11 | certificate|smime|nss|certificate-store|certutil | 53,770 | <p>The error message is quite cryptic. I got similar error while using <code>certutil -L</code> to get the list of certificate in a <code>cert8.db</code> file. </p>
<p>Now I find why the command did not work.</p>
<p>The <code>–L</code> cannot work only with a <code>cert8.db</code> in a folder. It is also dependent on two other files, <code>key3.db and secmod.db</code>.
So in a folder where all the above 3 files are present, <code>-L</code> works only there.
And that’s why <code>–d</code> parameter takes a folder path. Not the <code>cert8.db</code> file. </p>
<p>I tried certutil by copying <code>cert8.db</code> from the Firefox profile folder to a temp directory. </p>
<p>I noticed it when certuitl -A succeeded but -L failed and the successful -A command created two other files in that temp folder. </p>
<p>Check also if the directory path have any space or not. With space, it gives the same error or 'bad file format error - old database format' etc. Specially in the Mac OS, the folder is in <code>"Application Support"</code> folder which contains space in the name. So it needs the path fully quoted:</p>
<pre><code>"/Users/myuser/Library/Application Support/Firefox/Profiles/jii912uh.default"
</code></pre>
<p>or add the \ escape character. </p>
<pre><code> /Users/myuser/Library/Application\ Support/Firefox/Profiles/jii912uh.default
</code></pre> |
3,056,410 | PLS-00103: Encountered the symbol "end-of-file" in simple update block | <p>The following Oracle statement:</p>
<pre><code> DECLARE ID NUMBER;
BEGIN
UPDATE myusername.terrainMap
SET playerID = :playerID,tileLayout = :tileLayout
WHERE ID = :ID
END;
</code></pre>
<p>Gives me the following error:</p>
<pre><code>ORA-06550: line 6, column 15:
PL/SQL: ORA-00933: SQL command not properly ended
ORA-06550: line 3, column 19:
PL/SQL: SQL Statement ignored
ORA-06550: line 6, column 18:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
( begin case declare end exception exit for goto if loop mod
null pragma raise return select update while with
<an identifier> <a double-quoted>
</code></pre>
<p>I am pretty much at a loss. This appears to be a rather simple statement. If it helps any, I had a similar statement that performed an INSERT which used to work, but today has been giving me the same message. </p> | 3,056,439 | 3 | 1 | null | 2010-06-16 19:12:01.933 UTC | 4 | 2017-04-10 21:03:45.16 UTC | 2011-05-19 05:43:32.207 UTC | null | 135,152 | null | 368,587 | null | 1 | 6 | sql|oracle|plsql|ora-00933|ora-06550 | 65,514 | <p>Add a semi-colon after <code>where id=:id</code></p> |
44,105,691 | ROW_NUMBER Without ORDER BY | <p>I've to add row number in my existing query so that I can track how much data has been added into Redis. If my query failed so I can start from that row no which is updated in other table. </p>
<p>Query to get data start after 1000 row from table </p>
<pre><code>SELECT * FROM (SELECT *, ROW_NUMBER() OVER (Order by (select 1)) as rn ) as X where rn > 1000
</code></pre>
<p>Query is working fine. If any way that I can get the row no without using order by.</p>
<p>What is <code>select 1</code> here?</p>
<p>Is the query optimized or I can do it by other ways. Please provide the better solution.</p> | 44,106,422 | 4 | 0 | null | 2017-05-22 06:07:01.897 UTC | 13 | 2020-11-22 11:51:10.45 UTC | 2017-11-05 07:44:41.657 UTC | null | 1,080,354 | null | 7,337,831 | null | 1 | 79 | sql|sql-server|tsql|window-functions | 105,325 | <p>There is no need to worry about specifying constant in the <code>ORDER BY</code> expression. The following is quoted from the <a href="https://rads.stackoverflow.com/amzn/click/com/0735658366" rel="noreferrer" rel="nofollow noreferrer">Microsoft SQL Server 2012 High-Performance T-SQL Using Window Functions</a> written by <code>Itzik Ben-Gan</code> (it was available for free download from Microsoft free e-books site):</p>
<blockquote>
<p>As mentioned, a window order clause is mandatory, and SQL Server
doesn’t allow the ordering to be based on a constant—for example,
ORDER BY NULL. But surprisingly, when passing an expression based on a
subquery that returns a constant—for example, ORDER BY (SELECT
NULL)—SQL Server will accept it. At the same time, the optimizer
un-nests, or expands, the expression and realizes that the ordering is
the same for all rows. Therefore, it removes the ordering requirement
from the input data. Here’s a complete query demonstrating this
technique:</p>
</blockquote>
<pre><code>SELECT actid, tranid, val,
ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum
FROM dbo.Transactions;
</code></pre>
<p><a href="https://i.stack.imgur.com/9RTM5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9RTM5.png" alt="enter image description here"></a></p>
<blockquote>
<p>Observe in the properties of the Index Scan iterator that the Ordered
property is False, meaning that the iterator is not required to return
the data in index key order</p>
</blockquote>
<hr>
<p>The above means that when you are using constant ordering is not performed. I will strongly recommend to read the book as <code>Itzik Ben-Gan</code> describes in depth how the window functions are working and how to optimize various of cases when they are used.</p> |
26,300,925 | Cannot upload video to iTunesConnect: The frame rate of your app video preview is too high | <p>I made an App Store preview video using QuickTime player on OS X Yosemite.<br>
When I try to upload the video to iTunesConnect, I get an error message:</p>
<blockquote>
<p>The frame rate of your app video preview is too high.</p>
</blockquote>
<p>I can't see any options in the QuickTime Player to change frame rate.</p>
<p><img src="https://i.stack.imgur.com/ZCFgZ.png" alt="Error message that I am getting"></p>
<p>Does anybody knows what to do with it?</p> | 26,730,600 | 11 | 0 | null | 2014-10-10 13:43:30.357 UTC | 9 | 2019-12-11 02:30:34.583 UTC | 2014-10-10 13:51:17.907 UTC | null | 3,991,344 | null | 1,121,716 | null | 1 | 30 | ios|app-store|app-store-connect|appstore-approval | 9,445 | <p>Videos can be easily converted using ffmpeg, a handy tool that can be installed using <a href="http://brew.sh" rel="noreferrer">homebrew</a>.</p>
<pre><code>ffmpeg -r 30 -i 60fpsvideo.m4v -vcodec copy -acodec copy 30fpsvideo.avi
</code></pre> |
2,335,920 | How do I output compressed CSS from Compass? | <p>How do I configure compass to output smaller or compressed CSS files? I tried <code>compass -s compressed</code> but that didn't work.</p> | 2,337,008 | 3 | 0 | null | 2010-02-25 17:01:41.31 UTC | 12 | 2015-01-29 16:38:50.98 UTC | 2011-07-25 22:24:55.013 UTC | null | 93,848 | null | 203,915 | null | 1 | 32 | css|compression|sass|compass-sass | 28,713 | <p>In your <code>config.rb</code> file:</p>
<pre><code>output_style = :compressed
</code></pre>
<p>More at <a href="http://compass-style.org/help/documentation/configuration-reference/" rel="noreferrer">http://compass-style.org/help/documentation/configuration-reference/</a>.</p> |
2,934,568 | Why does Scala apply thunks automatically, sometimes? | <p>At just after 2:40 in <a href="http://www.youtube.com/user/ShadowofCatron" rel="nofollow noreferrer">ShadowofCatron</a>'s <a href="http://www.youtube.com/watch?v=R3gh9jIIbME" rel="nofollow noreferrer">Scala Tutorial 3 video</a>, it's pointed out that the <strong>parentheses following the name of a <a href="http://en.wikipedia.org/wiki/Thunk#Functional_programming" rel="nofollow noreferrer">thunk</a> are <em>optional</em></strong>. "Buh?" said my functional programming brain, since the value of a function and the value it evaluates to when applied are completely different things.</p>
<p>So I wrote the following to try this out. My thought process is described in the comments.</p>
<pre><code>object Main {
var counter: Int = 10
def f(): Int = { counter = counter + 1; counter }
def runThunk(t: () => Int): Int = { t() }
def main(args: Array[String]): Unit = {
val a = f() // I expect this to mean "apply f to no args"
println(a) // and apparently it does
val b = f // I expect this to mean "the value f", a function value
println(b) // but it's the value it evaluates to when applied to no args
println(b) // and the application happens immediately, not in the call
runThunk(b) // This is an error: it's not println doing something funny
runThunk(f) // Not an error: seems to be val doing something funny
}
}
</code></pre>
<p> </p>
<p>To be clear about the problem, this Scheme program (and the console dump which follows) shows what I expected the Scala program to do.</p>
<pre><code>(define counter (list 10))
(define f (lambda ()
(set-car! counter (+ (car counter) 1))
(car counter)))
(define runThunk (lambda (t) (t)))
(define main (lambda args
(let ((a (f))
(b f))
(display a) (newline)
(display b) (newline)
(display b) (newline)
(runThunk b)
(runThunk f))))
> (main)
11
#<procedure:f>
#<procedure:f>
13
</code></pre>
<p> </p>
<p>After coming to this site to ask about this, I came across <a href="https://stackoverflow.com/questions/1450456/get-function-value-of-a-instance-method-in-scala/1450486#1450486">this answer</a> which told me how to fix the above Scala program:</p>
<pre><code> val b = f _ // Hey Scala, I mean f, not f()
</code></pre>
<p>But the underscore 'hint' is only needed <em>sometimes</em>. When I call <code>runThunk(f)</code>, no hint is required. But when I 'alias' f to b with a <code>val</code> then apply it, it doesn't work: the application happens in the <code>val</code>; and even <code>lazy val</code> works this way, so it's not the point of evaluation causing this behaviour.</p>
<p> </p>
<p>That all leaves me with the question:</p>
<p><strong>Why does Scala <em>sometimes</em> automatically apply thunks when evaluating them?</strong></p>
<p>Is it, as I suspect, type inference? And if so, shouldn't a type system stay out of the language's semantics?</p>
<p>Is this a good idea? Do Scala programmers apply thunks rather than refer to their values <em>so much more often</em> that making the parens optional is better overall?</p>
<hr>
<p>Examples written using Scala 2.8.0RC3, DrScheme 4.0.1 in R5RS.</p> | 3,030,768 | 4 | 1 | null | 2010-05-29 09:56:54.673 UTC | 6 | 2010-06-13 01:45:21.423 UTC | 2017-05-23 12:25:34.68 UTC | null | -1 | null | 2,391 | null | 1 | 28 | syntax|scala|functional-programming | 3,051 | <p>The problem is here:</p>
<blockquote>
<p>Buh?" said my functional programming
brain, since the value of a function
and the value it evaluates to when
applied are completely different
things.</p>
</blockquote>
<p>Yes, but you did not declare any function.</p>
<pre><code>def f(): Int = { counter = counter + 1; counter }
</code></pre>
<p>You declared a <em>method</em> called <code>f</code> which has one empty parameter list, and returns <code>Int</code>. A method is not a function -- it does not have a value. Never, ever. The best you can do is get a <code>Method</code> instance through reflection, which is not really the same thing at all.</p>
<pre><code>val b = f _ // Hey Scala, I mean f, not f()
</code></pre>
<p>So, what does <code>f _</code> means? If <code>f</code> was a function, it would mean the function itself, granted, but this is not the case here. What it really means is this:</p>
<pre><code>val b = () => f()
</code></pre>
<p>In other words, <code>f _</code> is a <em>closure</em> over a method call. And closures are implemented through functions.</p>
<p>Finally, why are empty parameter lists optional in Scala? Because while Scala allows declarations such as <code>def f = 5</code>, Java does not. All methods in Java require at least an empty parameter list. And there are many such methods which, in Scala style, would not have any parameters (for example, <code>length</code> and <code>size</code>). So, to make the code look more uniform with regards to empty parameter list, Scala makes them optional.</p> |
53,636,350 | Re-enable title bar in Visual Studio 2019 | <p>I've downloaded the preview version of Visual Studio 2019 and the title bar is disabled by default.</p>
<p>This doesn't work for me as I currently develop C# applications using multiple instances of visual studio at a time, and I like knowing what window relates to which solution, and whether I am running with elevated privileges. </p>
<p>I've found that I can re-enable the title bar by going to the 'Preview Features' section in options, but this will obviously not be in the real release of Visual Studio 2019. </p>
<p>I've searched online, but have only found feature requests to <a href="https://developercommunity.visualstudio.com/idea/381901/do-not-remove-title-bar-from-visual-studio-2019.html" rel="noreferrer">not remove the title bar</a>.</p>
<p>Is there currently any way to re-enable the title bar in VS 2019 (that is not related to the preview features option)? </p> | 54,600,661 | 3 | 0 | null | 2018-12-05 16:09:47.343 UTC | 5 | 2021-12-17 09:30:33.363 UTC | 2019-04-03 11:04:00.073 UTC | null | 397,817 | null | 685,341 | null | 1 | 40 | c#|.net|visual-studio|visual-studio-2019 | 10,617 | <p>It appears that <a href="https://developercommunity.visualstudio.com/content/idea/381901/do-not-remove-title-bar-from-visual-studio-2019.html" rel="noreferrer">some time around March 2019</a> the option to restore the title bar through a setting in the IDE was restored. I can confirm that the option remains in the latest release and preview versions of Visual Studio as of June 2019.</p>
<p>Go to:</p>
<blockquote>
<p>Tools > Options > Environment > Preview Features</p>
</blockquote>
<p>and untick</p>
<blockquote>
<p>"Use compact menu and search bar (requires restart)"</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/9cKaH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9cKaH.png" alt="enter image description here"></a></p>
<p>Then click "OK" and restart Visual Studio.</p>
<hr>
<p>If the setting gets removed again, it <em>may</em> still be possible to fall back to editing the file <code>CurrentSettings.vssettings</code>. Change:</p>
<pre><code><PropertyValue name="IsMinimalVsEnabled">True</PropertyValue>
</code></pre>
<p>to</p>
<pre><code><PropertyValue name="IsMinimalVsEnabled">False</PropertyValue>
</code></pre>
<p>Look for the file in <code>%LOCALAPPDATA%\Microsoft\VisualStudio\16.0_xxxxxxxx\Settings\CurrentSettings.vssettings</code> (where <code>16.0_xxxxxxxx</code> will be the version you have installed).</p> |
49,932,759 | pip 10 and apt: how to avoid "Cannot uninstall X" errors for distutils packages | <p>I am dealing with a legacy Dockerfile. Here is a <em>very simplified</em> version of what I am dealing with:</p>
<pre><code>FROM ubuntu:14.04
RUN apt-get -y update && apt-get -y install \
python-pip \
python-numpy # ...and many other packages
RUN pip install -U pip
RUN pip install -r /tmp/requirements1.txt # includes e.g., numpy==1.13.0
RUN pip install -r /tmp/requirements2.txt
RUN pip install -r /tmp/requirements3.txt
</code></pre>
<p>First, several packages are installed using <code>apt</code>, and then several packages are installed using <code>pip</code>. <code>pip</code> version 10 has been released, and <a href="https://pip.pypa.io/en/stable/news/#deprecations-and-removals" rel="noreferrer">part of the release</a> is this new restriction:</p>
<blockquote>
<p>Removed support for uninstalling projects which have been installed using distutils. distutils installed projects do not include metadata indicating what files belong to that install and thus it is impossible to actually uninstall them rather than just remove the metadata saying they've been installed while leaving all of the actual files behind.</p>
</blockquote>
<p>This leads to the following problem in my setup. For example, first <code>apt</code> installs <code>python-numpy</code>. Later <code>pip</code> tries to install a newer version of <code>numpy</code> from e.g., <code>/tmp/requirements1.txt</code>, and tries to uninstall the older version, but because of the new restriction, it cannot remove this version:</p>
<pre><code>Installing collected packages: numpy
Found existing installation: numpy 1.8.2
Cannot uninstall 'numpy'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
</code></pre>
<p>Now I know at this point there are several solutions.</p>
<p>I could not install <code>python-numpy</code> through <code>apt</code>. However, this causes issues because <code>python-numpy</code> installs a few different packages as requirements, and I do not know if another part of the system relies on these packages. And in reality, there are several <code>apt</code> packages installed through the Dockerfile, and each one I remove seems to reveal another <code>Cannot uninstall X</code> error, and removes a number of other packages along with it, that our app may or may not rely on.</p>
<p>I could also use the <code>--ignore-installed</code> option when I try to <code>pip</code> install things that have already been installed through <code>apt</code>, but then again I have the same problem of every <code>--ignore-installed</code> argument revealing yet another thing that needs to be ignored.</p>
<p>I could pin <code>pip</code> at an older version that does not have this restriction, but I don't want to be stuck using an outdated version of <code>pip</code> forever.</p>
<p>I have been going around in circles trying to come up with a good solution that involves minimal changes to this legacy Dockerfile, and allows the app we deploy with that file to continue to function as it has been. Any suggestions as to how I can safely get around this problem of <code>pip</code> 10 not being able to install newer versions of <code>distutils</code> packages? Thank you!</p>
<h1>UPDATE:</h1>
<p>I did not realize that <code>--ignore-installed</code> could be used without a package as an argument to ignore all installed packages. I am considering whether or not this might be a good option for me, and have asked about it <a href="https://stackoverflow.com/q/49932926/3642398">here</a>.</p> | 50,396,798 | 4 | 0 | null | 2018-04-20 01:58:13.01 UTC | 15 | 2019-11-21 21:01:11.3 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 3,642,398 | null | 1 | 62 | python|docker|pip|distutils|apt | 68,338 | <p>This is the solution I ended up going with, and our apps have been running in production without any issues for close to a month with this fix in place:</p>
<p>All I had to do was to add</p>
<p><code>--ignore-installed</code></p>
<p>to the <code>pip install</code> lines in my dockerfile that were raising errors. Using the same dockerfile example from my original question, the fixed dockerfile would look something like:</p>
<pre><code>FROM ubuntu:14.04
RUN apt-get -y update && apt-get -y install \
python-pip \
python-numpy # ...and many other packages
RUN pip install -U pip
RUN pip install -r /tmp/requirements1.txt --ignore-installed # don't try to uninstall existing packages, e.g., numpy
RUN pip install -r /tmp/requirements2.txt
RUN pip install -r /tmp/requirements3.txt
</code></pre>
<p>The documentation I could find for <code>--ignore-installed</code> was unclear in my opinion (<code>pip install --help</code> simply says "Ignore the installed packages (reinstalling instead)."), and I asked about the potential dangers of this flag <a href="https://stackoverflow.com/q/49932926/3642398">here</a>, but have yet to get satisfying answer. However, if there are any negative side effects, our production environment has yet to see the effects of them, and I think the risk is low/none (at least that has been our experience). I was able to confirm that in our case, when this flag was used, the existing installation was not uninstalled, but that the newer installation was always used. </p>
<h1>Update:</h1>
<p>I wanted to highlight <a href="https://stackoverflow.com/questions/53807511/pip-cannot-uninstall-package-it-is-a-distutils-installed-project/53807588#53807588">this</a> answer by @ivan_pozdeev. He provides some information that this answer does not include, and he also outlines some potential side-effects of my solution. </p> |
36,589,908 | Incompatible Bitbucket plugin 1.2.1 for Android Studio 2.0/2.1/3.0+ | <p>I have updated version of my Android Studio to 2.0 and is facing incompatibility issue of bitbucket plugin 1.2.1 when loading Android Studio.</p>
<p>Android Studio's Event log is saying:<br/>
<em>"Plugin Error<br/>
Problems found loading plugins:<br/>
Following plugins are incompatible with current IDE build: Bitbucket"</em></p>
<p>Can anyone help me regarding?</p>
<p>Thanks in advance.</p> | 36,607,806 | 1 | 0 | null | 2016-04-13 06:05:54.81 UTC | 10 | 2019-03-08 06:49:39.247 UTC | 2019-03-08 06:49:39.247 UTC | null | 3,459,944 | null | 3,459,944 | null | 1 | 15 | bitbucket|android-studio-3.0|android-studio-2.0|android-studio-2.1|android-studio-3.3 | 3,931 | <p>Try use jetbrains bitbucket connector, open this link and download the package:
<a href="https://drive.google.com/open?id=1L0bEhoCIrV9Jced1fqdYscI34wwuKyvQ" rel="nofollow noreferrer">https://drive.google.com/open?id=1L0bEhoCIrV9Jced1fqdYscI34wwuKyvQ</a></p>
<p>After dowloading you need install this plugin (Don't extract the package). </p>
<p>In Android Studio, follow the menu items path:</p>
<p>File => Settings => Plugins => Install plugin from disk => {choose downloaded package} => Restart Android Studio</p> |
22,584,427 | What is "compiler compliance level" in Eclipse? | <p>For some time I tried to understand, but I still don't get exactly what "compiler compliance level" for a project in Eclipse means. I looked all over this site and Google and couldn't find an answer I could understand.</p>
<p>Let's say I want my program to be able to run on JRE 6.</p>
<p>I can do: Project > Preferences > Java Build Path > Libraries, and set the JRE library I use to JRE 6.</p>
<p>Why isn't this enough?</p>
<p>I never understood why I also need to set the compiler compliance setting to JRE 6.</p>
<p>I'd like to understand the difference between using JRE 6 in a project, and setting the project's compiler compliance setting to JRE 6.</p>
<p><strong>What exactly does compiler compliance level mean?</strong></p> | 22,584,460 | 4 | 0 | null | 2014-03-22 22:23:11.68 UTC | 15 | 2015-04-27 06:00:05.003 UTC | 2015-04-27 06:00:05.003 UTC | null | 3,614,835 | null | 3,284,878 | null | 1 | 53 | java|eclipse | 52,300 | <p>The compiler compliance setting tells the compiler to pretend it's a different version of Java.</p>
<p>The Java 8 compiler will produce class files in the Java 8 version of the class file format, and accept Java 8 source files. JRE 6 can't load this version, because it was created after JRE 6 was.</p>
<p>If you set the compliance level to "JRE 6", it will instead compile Java 6 source files into Java 6 class files.</p>
<p>It's like saving a Word document as "Word 97-2003 format" - so that Word 97-2003 can read your document. You're saving the class files in Java 6 format so that Java 6 can read them.</p> |
2,599,879 | Rowcolor on a multirow tabular in LaTeX | <p>So I tried learning LaTeX last night, and I trying to get this template for school assignments done ASAP. Part of that requires building a table. I want to use multirow, but need the multirows, that are acting like headings, to be colored gray. This is what I created so far from the almighty Google.</p>
<pre><code>\documentclass{article}
\usepackage{xcolor,colortbl}
\begin{document}
\begin{tabular}{|l|l|p{5cm}|p{2.5cm}|l|l|}
\hline
\rowcolor{lightgray}
Stage & Aim & Procedure & Materials & Focus & Time \\
\hline
\rowcolor{lightgray}
\multicolumn{6}{|l|}{Engage} \\
\hline
Row 0 & Row 1 & Row 2 & Row 3 & Row 4 & Row 5 \\
%\hline
\rowcolor{lightgray} \multicolumn{6}{|l|}{Study} \\
\hline
Row 0 & Row 1 & Row 2 & Row 3 & Row 4 & Row 5 \\
\hline
\rowcolor{lightgray}
\multicolumn{6}{|l|}{Activate} \\
\hline
Row 0 & Row 1 & Row 2 & Row 3 & Row 4 & Row 5 \\
\hline
\rowcolor{lightgray}
\multicolumn{6}{|l|}{Conclusion} \\
\hline
Row 0 & Row 1 & Row 2 & Row 3 & Row 4 & Row 5 \\
\hline
\end{tabular}
\end{document}
</code></pre>
<p>Unfortunately, this does not work with pdflatex version 1.4.0 on Debian GNU/Linux 5.0.4 (lenny) I have in a VM. Instead of doing it correctly, it ends up looking like <a href="http://drop.io/ojyo1f6/asset/pdflatex-capture-png" rel="noreferrer">this</a>, where the first cell of the row after the multirow is blacked-out garbage.</p> | 2,599,983 | 1 | 2 | null | 2010-04-08 12:44:08.803 UTC | 2 | 2019-07-22 04:28:36.837 UTC | 2012-01-12 14:06:08.153 UTC | null | 110,204 | null | 311,888 | null | 1 | 10 | latex|colors|pdflatex|multirow | 46,920 | <p>Try this:</p>
<pre><code>\documentclass{article}
\usepackage{xcolor,colortbl}
\begin{document}
\begin{tabular}{|l|l|p{5cm}|p{2.5cm}|l|l|}
\hline
Stage & Aim & Procedure & Materials & Focus & Time \\
\hline
\multicolumn{6}{|>{\columncolor[gray]{.8}}l|}{Engage} \\
\hline
Row 0 & Row 1 & Row 2 & Row 3 & Row 4 & Row 5 \\
\hline
\multicolumn{6}{|>{\columncolor[gray]{.8}}l|}{Study} \\
\hline
Row 0 & Row 1 & Row 2 & Row 3 & Row 4 & Row 5 \\
\hline
\multicolumn{6}{|>{\columncolor[gray]{.8}}l|}{Activate} \\
\hline
Row 0 & Row 1 & Row 2 & Row 3 & Row 4 & Row 5 \\
\hline
\multicolumn{6}{|>{\columncolor[gray]{.8}}l|}{Conclusion} \\
\hline
Row 0 & Row 1 & Row 2 & Row 3 & Row 4 & Row 5 \\
\hline
\end{tabular}
\end{document}
</code></pre>
<p>Which produces:</p>
<p><a href="https://i.stack.imgur.com/9XCCn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9XCCn.png" alt="alt text"></a>
</p>
<p><strong>EDIT:</strong></p>
<p>Yes, <code>>{...}</code> is the command to place your <code>\columncolor</code> in (must be in it!). Also see 4.1 from <a href="https://web.archive.org/web/20100214195828/http://www.vision.ime.usp.br/~jmena/misc/latex/tables_with_latex.pdf" rel="nofollow noreferrer">this PDF</a>.</p> |
2,581,137 | Injecting generics with Guice | <p>I am trying to migrate a small project, replacing some factories with Guice (it is my first Guice trial). However, I am stuck when trying to inject generics. I managed to extract a small toy example with two classes and a module:</p>
<pre><code>import com.google.inject.Inject;
public class Console<T> {
private final StringOutput<T> out;
@Inject
public Console(StringOutput<T> out) {
this.out = out;
}
public void print(T t) {
System.out.println(out.converter(t));
}
}
public class StringOutput<T> {
public String converter(T t) {
return t.toString();
}
}
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.TypeLiteral;
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(StringOutput.class);
bind(Console.class);
}
public static void main(String[] args) {
Injector injector = Guice.createInjector( new MyModule() );
StringOutput<Integer> out = injector.getInstance(StringOutput.class);
System.out.println( out.converter(12) );
Console<Double> cons = injector.getInstance(Console.class);
cons.print(123.0);
}
}
</code></pre>
<p>When I run this example, all I got is:</p>
<p>Exception in thread "main" com.google.inject.CreationException: Guice creation errors:</p>
<pre><code>1) playground.StringOutput<T> cannot be used as a key; It is not fully specified.
at playground.MyModule.configure(MyModule.java:15)
1 error
at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:354)
at com.google.inject.InjectorBuilder.initializeStatically(InjectorBuilder.java:152)
at com.google.inject.InjectorBuilder.build(InjectorBuilder.java:105)
at com.google.inject.Guice.createInjector(Guice.java:92)
</code></pre>
<p>I tried looking for the error message, but without finding any useful hints. Further on the Guice FAQ I stumble upon a question about how to inject generics. I tried to add the following binding in the <code>configure</code> method:</p>
<pre><code>bind(new TypeLiteral<StringOutput<Double>>() {}).toInstance(new StringOutput<Double>());
</code></pre>
<p>But without success (same error message).</p>
<p>Can someone explain me the error message and provide me some tips ? Thanks.</p> | 2,581,256 | 1 | 1 | null | 2010-04-05 20:57:55.073 UTC | 7 | 2016-09-03 21:44:07.777 UTC | null | null | null | null | 220,447 | null | 1 | 29 | java|dependency-injection|guice | 24,270 | <p>I think the specific issue you're seeing is probably because of the <code>bind(Console.class)</code> statement. It should use a <code>TypeLiteral</code> as well. Or, you could just bind neither of those and JIT bindings will take care of it for you since both of the types involved here are concrete classes.</p>
<p>Additionally, you should retrieve the <code>Console</code> with:</p>
<pre><code>Console<Double> cons =
injector.getInstance(Key.get(new TypeLiteral<Console<Double>>(){}));
</code></pre>
<p><strong>Edit:</strong> You don't need to bind to an instance just because you're using a <code>TypeLiteral</code>. You can just do:</p>
<pre><code>bind(new TypeLiteral<Console<Double>>(){});
</code></pre>
<p>Of course, like I said above you could just skip that in this case and retrieve the <code>Console</code> from the injector using a <code>Key</code> based on the <code>TypeLiteral</code> and the binding would be implicit.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.