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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8,483,002 | Image shows up in Visual Studio designer but not during run-time | <p>I'm currently working w/ VS studio 2010, .NET 4.0. Here is my scenario: </p>
<p>I currently have a class library project called "Images" that contains a sub folder called "Icons". All my icons currently live in this project and are accessed by multiple projects via siteoforigin. Everything shows up fine while in the designer, but during run time the images do not display. </p>
<p>Here is my folder structure:</p>
<ul>
<li>Root Folder
<ul>
<li>Images
<ul>
<li>Icons</li>
</ul></li>
<li>Project 1</li>
<li>Project 2</li>
<li>Project 3</li>
</ul></li>
</ul>
<p>All projects are referencing the Images class lib. proj, and all icons inside the "icons" sub-folder within the "Images" project is set to: "Build Action = Resource".</p>
<p>The xaml looks like this (which is perfectly visible during design time):</p>
<pre><code> <Button Name="Button1" Click="Button1_Click">
<Button.Content>
<Image Source="pack://siteoforigin:,,,/Data.Images;component/Icons/Button1.png" />
</Button.Content>
</Button>
</code></pre> | 28,901,136 | 26 | 1 | null | 2011-12-13 00:46:26.837 UTC | 3 | 2022-09-19 18:00:43.813 UTC | null | null | null | null | 701,560 | null | 1 | 45 | wpf|visual-studio-2010|image|xaml | 62,218 | <p>This was driving me crazy. I tried lots of different things based on various articles but nothing worked. My xaml window and image are in a separate DLL from the executable assembly. Not sure if that was part of my problem.</p>
<p>In the end I had success with:</p>
<ol>
<li>Make sure the image properties in the project has "Build Action" = "Resource", NOT "Embedded Resource"</li>
<li>In the xaml, with the image tag selected, use the properties windows to select the Source dropdown since NOW the image appears in the dropdown list! This let visual studio format the string for me.</li>
</ol>
<p>The string visual studio formatted for my image was:</p>
<pre><code><Image Source="/Paperless.Common;component/Resources/Checkbook.png" />
</code></pre>
<p>where "Paperless.Common" was the name of my assembly, and "Checkbook.png" was my image that resided in a "Resources" folder.</p>
<hr />
<p>For completeness, the above URI is a <a href="https://docs.microsoft.com/en-us/dotnet/desktop/wpf/app-development/pack-uris-in-wpf?view=netframeworkdesktop-4.8" rel="noreferrer">Resource File Pack URI</a>, where the URI prefix part is automatically added by the XAML Parser.</p>
<p>The full URI - which you would have to use in code behind - has a <code>pack://application:</code> prefix and would also work in XAML:</p>
<pre><code>Source="pack://application:,,,/Paperless.Common;component/Resources/Checkbook.png"
</code></pre> |
19,417,081 | Doing math on variable argument Sass mixins | <p>I like to use rem units with pixel fallbacks for my CSS sizing and am trying to make mixins to help with that. For font-size, this is easy:</p>
<pre><code>@mixin font-size($size) {
font-size: $size + px;
font-size: ($size / 10) + rem;
}
</code></pre>
<p>But for padding, margin, etc. the mixin needs to accept variable arguments, which is possible per the Sass documentation <a href="http://sass-lang.com/documentation/file.SASS_REFERENCE.html#variable_arguments" rel="noreferrer">http://sass-lang.com/documentation/file.SASS_REFERENCE.html#variable_arguments</a></p>
<p>However, with the following mixin, instead of dividing by 10, the mixin is just adding a slash between the numbers. That is, this:</p>
<pre><code>@mixin padding($padding...) {
padding: $padding + px;
padding: ($padding / 10) + rem;
}
.class {
@include padding(24);
}
</code></pre>
<p>Outputs this:</p>
<pre><code>.class {
padding: 24px;
padding: 24/10rem;
}
</code></pre>
<p>Instead of this, like I would expect:</p>
<pre><code>.class {
padding: 24px;
padding: 2.4rem;
}
</code></pre>
<p>Is there a way to make sure Sass recognizes the variables as numbers and thus uses the division operator on them correctly?</p>
<p>Also, after testing this more, I realized the concatenation only takes place on the last variable.</p> | 19,524,682 | 3 | 1 | null | 2013-10-17 02:04:58.16 UTC | 3 | 2021-03-15 18:40:13.043 UTC | 2013-10-18 17:59:04.257 UTC | null | 486,008 | null | 486,008 | null | 1 | 28 | css|sass|mixins | 42,598 | <p>It seems what I really needed to use here was a list rather than a variable argument in order to manipulate each value separately.</p>
<p>I first tried doing this with the @each directive, but couldn't figure out how to use it inside a declaration. This throws an error:</p>
<pre><code>@mixin padding($padding) {
padding: @each $value in $padding { $value + px };
padding: @each $value in $padding { ($value / 10) + rem };
}
</code></pre>
<p>So I ended up writing something much more verbose that handles each of the four possible cases separately (i.e. you pass 1, 2, 3 or 4 arguments). That looks like this and works as I wanted:</p>
<pre><code>@mixin padding($padding) {
@if length($padding) == 1 {
padding: $padding+px;
padding: $padding/10+rem;
}
@if length($padding) == 2 {
padding: nth($padding, 1)+px nth($padding, 2)+px;
padding: nth($padding, 1)*0.1+rem nth($padding, 2)*0.1+rem;
}
@if length($padding) == 3 {
padding: nth($padding, 1)+px nth($padding, 2)+px nth($padding, 3)+px;
padding: nth($padding, 1)*0.1+rem nth($padding, 2)*0.1+rem nth($padding, 3)*0.1+rem;
}
@if length($padding) == 4 {
padding: nth($padding, 1)+px nth($padding, 2)+px nth($padding, 3)+px nth($padding, 4)+px;
padding: nth($padding, 1)*0.1+rem nth($padding, 2)*0.1+rem nth($padding, 3)*0.1+rem nth($padding, 4)*0.1+rem;
}
}
</code></pre>
<p>I made collection of rem mixins including this one as a Gist here <a href="https://gist.github.com/doughamlin/7103259">https://gist.github.com/doughamlin/7103259</a></p> |
297,954 | Uploading Files with ASP.Net MVC - get name but no file stream, what am I doing wrong? | <p>I have this form in my view: </p>
<pre><code><!-- Bug (extra 'i') right here-----------v -->
<!-- was: <form method="post" enctype="mulitipart/form-data" action="/Task/SaveFile"> -->
<form method="post" enctype="multipart/form-data" action="/Task/SaveFile">
<input type="file" id="FileBlob" name="FileBlob"/>
<input type="submit" value="Save"/>
<input type="button" value="Cancel" onclick="window.location.href='/'" />
</form>
</code></pre>
<p>And this code in my controller: </p>
<pre><code>public ActionResult SaveFile( FormCollection forms )
{
bool errors = false;
//this field is never empty, it contains the selected filename
if ( string.IsNullOrEmpty( forms["FileBlob"] ) )
{
errors = true;
ModelState.AddModelError( "FileBlob", "Please upload a file" );
}
else
{
string sFileName = forms["FileBlob"];
var file = Request.Files["FileBlob"];
//'file' is always null, and Request.Files.Count is always 0 ???
if ( file != null )
{
byte[] buf = new byte[file.ContentLength];
file.InputStream.Read( buf, 0, file.ContentLength );
//do stuff with the bytes
}
else
{
errors = true;
ModelState.AddModelError( "FileBlob", "Please upload a file" );
}
}
if ( errors )
{
return ShowTheFormAgainResult();
}
else
{
return View();
}
}
</code></pre>
<p>Based on every code sample I've been able to find, this seems like the way to do it. I've tried with small and large files, with no difference in the result. The form field always contains the filename which matches what I've chosen, and the Request.Files collection is always empty. </p>
<p>I don't think it's relevant, but I'm using the VS Development Web Server. AFAIK it supports file uploads the same as IIS. </p>
<p>It's getting late and there's a chance I'm missing something obvious. I'd be grateful for any advice. </p> | 298,010 | 4 | 1 | null | 2008-11-18 05:53:43.103 UTC | 13 | 2013-11-09 12:35:03.867 UTC | 2011-02-08 22:24:38.263 UTC | Jason Diller | 58,391 | Jason Diller | 2,187 | null | 1 | 41 | asp.net-mvc|upload | 51,454 | <p>I don't know what the policy is on posting profanity, but here's the problem: </p>
<pre><code>enctype="mulitipart/form-data"
</code></pre>
<p>The extra <code>i</code> in there stopped the file from uploading. Had to run Fiddler to see that it was never sending the file in the first place. </p>
<p>It should read:</p>
<pre><code>enctype="multipart/form-data"
</code></pre> |
23,730,882 | What is the role of src and dist folders? | <p>I'm looking at a git repo for a jquery plugin. I want to make a few changes for use in my own project, but when I opened up the repo it had a structure I've never seen before. I'm not sure which files to use / copy into my own project.</p>
<p>There is a "dist" and a "src" folder. What purpose do these serve? Is this something specific for gruntjs or maybe jquery plugins?</p>
<p>The git repo I'm curious about: <a href="https://github.com/ducksboard/gridster.js">https://github.com/ducksboard/gridster.js</a></p> | 23,731,040 | 1 | 1 | null | 2014-05-19 06:20:49.753 UTC | 49 | 2022-03-31 07:40:05.563 UTC | 2014-05-19 06:48:31.003 UTC | null | 432,696 | null | 1,001,938 | null | 1 | 204 | javascript|jquery|jquery-plugins|gruntjs | 101,531 | <p><code>src/</code> stands for <em>source</em>, and is the <strong>raw code</strong> before minification or concatenation or some other compilation - used to read/edit the code.</p>
<p><code>dist/</code> stands for <em>distribution</em>, and is the <strong>minified/concatenated</strong> version - actually used on production sites.</p>
<p>This is a common task that is done for assets on the web to make them smaller.</p>
<p>You can see an example here: <a href="http://blog.kevinchisholm.com/javascript/node-js/javascript-concatenation-and-minification-with-the-grunt-js-task-runer/">http://blog.kevinchisholm.com/javascript/node-js/javascript-concatenation-and-minification-with-the-grunt-js-task-runer/</a></p> |
23,892,547 | What is the best way to trigger onchange event in react js | <p>We use Backbone + ReactJS bundle to build a client-side app.
Heavily relying on notorious <code>valueLink</code> we propagate values directly to the model via own wrapper that supports ReactJS interface for two way binding.</p>
<p>Now we faced the problem:</p>
<p>We have <code>jquery.mask.js</code> plugin which formats input value programmatically thus it doesn't fire React events. All this leads to situation when model receives <strong>unformatted</strong> values from user input and <strong>misses formatted ones</strong> from plugin.</p>
<p>It seems that React has plenty of event handling strategies depending on browser. Is there any common way to trigger change event for particular DOM element so that React will hear it?</p> | 46,012,210 | 13 | 1 | null | 2014-05-27 14:49:19.713 UTC | 70 | 2022-03-03 15:57:41.39 UTC | 2018-07-11 10:11:47.847 UTC | null | 1,143,634 | null | 1,215,802 | null | 1 | 162 | reactjs | 192,697 | <p><strong>For React 16 and React >=15.6</strong></p>
<p>Setter <code>.value=</code> is not working as we wanted because React library overrides input value setter but we can call the function directly on the <code>input</code> as context.</p>
<pre class="lang-js prettyprint-override"><code>var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
nativeInputValueSetter.call(input, 'react 16 value');
var ev2 = new Event('input', { bubbles: true});
input.dispatchEvent(ev2);
</code></pre>
<p>For textarea element you should use <code>prototype</code> of <code>HTMLTextAreaElement</code> class.</p>
<p>New <a href="https://codepen.io/catthr/pen/pddWzo" rel="noreferrer">codepen example</a>.</p>
<p>All credits to <a href="https://github.com/cypress-io/cypress/issues/647#issuecomment-335829482" rel="noreferrer">this contributor</a> and <a href="https://github.com/cypress-io/cypress/commit/4a56ca83b3b6e19ec57d10a8160f54f513e8f8ec" rel="noreferrer">his solution</a></p>
<p><strong>Outdated answer only for React <=15.5</strong></p>
<p>With <code>react-dom ^15.6.0</code> you can use <code>simulated</code> flag on the event object for the event to pass through</p>
<pre class="lang-js prettyprint-override"><code>var ev = new Event('input', { bubbles: true});
ev.simulated = true;
element.value = 'Something new';
element.dispatchEvent(ev);
</code></pre>
<p>I made a <a href="https://codepen.io/catthr/pen/PKXzLQ" rel="noreferrer">codepen with an example</a> </p>
<p>To understand why new flag is needed I found <a href="https://github.com/cypress-io/cypress/issues/536#issuecomment-308739206" rel="noreferrer">this comment</a> very helpful: </p>
<blockquote>
<p>The input logic in React now dedupe's change events so they don't fire
more than once per value. It listens for both browser onChange/onInput
events as well as sets on the DOM node value prop (when you update the
value via javascript). This has the side effect of meaning that if you
update the input's value manually input.value = 'foo' then dispatch a
ChangeEvent with { target: input } React will register both the set
and the event, see it's value is still `'foo', consider it a duplicate
event and swallow it.</p>
<p>This works fine in normal cases because a "real" browser initiated
event doesn't trigger sets on the element.value. You can bail out of
this logic secretly by tagging the event you trigger with a simulated
flag and react will always fire the event.
<a href="https://github.com/jquense/react/blob/9a93af4411a8e880bbc05392ccf2b195c97502d1/src/renderers/dom/client/eventPlugins/ChangeEventPlugin.js#L128" rel="noreferrer">https://github.com/jquense/react/blob/9a93af4411a8e880bbc05392ccf2b195c97502d1/src/renderers/dom/client/eventPlugins/ChangeEventPlugin.js#L128</a></p>
</blockquote> |
23,691,795 | Browserify and bower. Canonical approach | <p>The way I'm using packages that not available out of the box in npm, right now is like that:</p>
<p>package.json has:</p>
<pre><code> "napa": {
"angular": "angular/bower-angular",
"angular-animate": "angular/bower-angular-animate",
"d3": "mbostock/d3",
"ui-router":"angular-ui/ui-router",
"bootstrap":"twbs/bootstrap"
},
"scripts": {
"install": "node node_modules/napa/bin/napa"
</code></pre>
<p>and that installs files into node_modules directory, and I use them natively like this</p>
<pre><code>require('angular/angular')
require('ui-router')
... etc
</code></pre>
<p>That works, but I was thinking if it's possible to use packages installed with bower (into bower specific folder) and use them natively as node modules? Is it possible to tweak node's module resolution and force it to look for modules not just inside node_modules directory, but also in bower directory as well? Or maybe using <code>npm link</code> or whatever?</p>
<p>Is there some sort of convention to use browserify with bower?</p> | 23,692,863 | 2 | 1 | null | 2014-05-16 02:40:27.173 UTC | 17 | 2014-05-22 22:17:59.563 UTC | null | null | null | null | 116,395 | null | 1 | 29 | node.js|bower|browserify | 18,380 | <p>You can use <a href="https://www.npmjs.org/package/browserify-shim">browserify-shim</a> and configure the bower-installed modules in your <code>package.json</code> like this:</p>
<pre><code>"browser": {
"angular": "./bower_components/angular/angular.js",
"angular-resource": "./bower_components/angular-resource/angular-resource.js"
},
"browserify-shim": {
"angular": {
"exports": "angular"
},
"angular-resource": {
"depends": ["./bower_components/angular/angular.js:angular"]
}
},
</code></pre>
<p>Then your code can <code>require</code> them by their short name as if there were regular npm modules.</p>
<p><a href="https://gist.github.com/defunctzombie/4339901">Here is the spec for the "browser" package.json property</a>.</p> |
23,218,242 | Set cookies with NSURLSession | <p>Hi I am developing one Iphone application In which I want to set cookies after server response and use that for another request. My network request looks like.</p>
<pre><code>NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
NSLog(@"sttaus code %i", httpResp.statusCode);
if (error) {
[self.delegate signinWithError:error];
}
else {
[self.delegate signinWithJson:data];
}
}] resume];
</code></pre>
<p>But I don't know how to set cookies. I know I have to use <code>NSHTTPCookieStorage</code> but I don't know how to set. And I also want to use that cookies for another request. Is there any one who knows about this? Need help. Thank you.</p>
<p>See I tried in this way </p>
<pre><code>NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if(error) {
[self.delegate signinWithError:error];
}
else {
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
NSHTTPCookie *cookie;
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields];
for(NSString *key in [headers allKeys]) {
NSLog(@"%@ ..PPPP ... %@",key ,[headers objectForKey:key]);
[cookieProperties setObject:[headers objectForKey:key] forKey:key];
}
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];
cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
[self.delegate signinWithJson:data];
}
}] resume];
</code></pre>
<p>I am interested in only one header field <code>Set-Cookie SSID=kgu62c0fops35n6qbf12anqlo7; path=/</code></p> | 23,219,536 | 2 | 0 | null | 2014-04-22 11:31:49.927 UTC | 9 | 2016-11-19 23:03:42.31 UTC | 2016-11-19 23:03:42.31 UTC | null | 974,781 | null | 861,204 | null | 1 | 18 | ios|session-cookies|nsurlsession | 23,918 | <p>You can probably get away with just using the <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookieStorage_Class/Reference/Reference.html#//apple_ref/occ/clm/NSHTTPCookieStorage/sharedHTTPCookieStorage" rel="noreferrer"><code>sharedHTTPCookieStorage</code></a> for <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookieStorage_Class/Reference/Reference.html" rel="noreferrer"><code>NSHTTPCookieStorage</code></a>, and then use <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookieStorage_Class/Reference/Reference.html#//apple_ref/occ/instm/NSHTTPCookieStorage/setCookies:forURL:mainDocumentURL:" rel="noreferrer"><code>setCookies:forURL:mainDocumentURL:</code></a> or the single <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookieStorage_Class/Reference/Reference.html#//apple_ref/doc/uid/20001703-CJBDADAC" rel="noreferrer"><code>setCookie:</code></a> - the latter might be better for your needs.</p>
<p>If this doesn't work you might need to setup the <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/Reference/Reference.html#//apple_ref/doc/c_ref/NSURLSessionConfiguration" rel="noreferrer"><code>NSURLSessionConfiguration</code></a> and set the <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/Reference/Reference.html#//apple_ref/occ/instp/NSURLSessionConfiguration/HTTPCookieStorage" rel="noreferrer"><code>NSHTTPCookieStorage</code></a></p>
<p>The docs don't state it, but the <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/Reference/Reference.html#//apple_ref/occ/clm/NSURLSessionConfiguration/defaultSessionConfiguration" rel="noreferrer"><code>defaultSessionConfiguration</code></a> might use the shared store anyway.</p>
<pre><code>NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[response URL]];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:[response URL] mainDocumentURL:nil];
NSLog(@"sttaus code %i", httpResp.statusCode);
if (error) {
[self.delegate signinWithError:error];
}
else {
[self.delegate signinWithJson:data];
}
}] resume];
</code></pre> |
46,635,830 | Missing or insufficient permissions when writing to Firestore using field in access rules | <p>I am getting an error when attempting to write to Firestore.</p>
<p>I am attempting to use a field containing the user uid for my security rule.</p>
<pre><code>service cloud.firestore {
match /databases/{database}/documents {
match /messages/{document=**} {
allow read: if resource.data.user_uid == request.auth.uid;
allow write: if resource.data.user_uid == request.auth.uid;
}
}
}
</code></pre>
<p>If I have data in my Firestore database, the read rule works fine - but when I attempt to write I get: <code>Error: Missing or insufficient permissions.</code>
Is there something I'm doing wrong with this write rule?</p>
<p>P.S. If I change my rule to this, I'm able to write to my database - but this isn't secure enough for my purposes:</p>
<pre><code> match /messages/{document=**} {
allow read: if resource.data.user_uid == request.auth.uid;
allow write: if request.auth != null;
}
</code></pre> | 46,636,036 | 4 | 0 | null | 2017-10-08 20:39:47.103 UTC | 8 | 2021-05-24 11:18:28.547 UTC | 2017-10-11 18:35:32.553 UTC | null | 153,407 | null | 2,793,265 | null | 1 | 39 | firebase|firebase-security|google-cloud-firestore | 69,021 | <p><code>resource.data</code> refers to the data already stored, so your rule allowed users to only update data that already includes their user ID.</p>
<p>What you probably want to check is <code>request.resource.data</code> which is the new data coming in.</p>
<p>There's a rather extensive document about those fields and other security rules here: <a href="https://firebase.google.com/docs/firestore/security/rules-conditions" rel="noreferrer">https://firebase.google.com/docs/firestore/security/rules-conditions</a></p> |
43,052,290 | Representing a graph in JSON | <p>Inspired by <a href="https://stackoverflow.com/questions/9897956/how-do-you-store-a-directed-acyclic-graph-dag-as-json">this</a> question, I'm trying to represent a DAG in JSON. My case includes edges and nodes that contain some data (rather than just strings as in this example). I was thinking of a spec like this:</p>
<pre><code>{
"graph": {
"a": ["b", "c"],
"b": ["c"]
"c"
},
"nodes": {
"a": {
"name": "Adam"
},
"b": {
"name": "Bob"
},
"c": {
"name": "Caillou"
}
},
"edges": {
// how to do the same for edges?
// ie: how to query edges ?
}
}
</code></pre>
<p>One idea I had was to make the keys of the edges be the concatenation of the two vertex ids that it connects. For example, <code>ab</code>, <code>ac</code>, and <code>bc</code> are the three edges in this graph. I want to know if there's a more standard way of doing this.</p>
<p>EDIT: This is what I'm thinking of now</p>
<pre><code>{
"graph": {
"a": {
"data": {
// a's vertex data
},
"neighbors": {
"b": {
"data": {
// data in edge ab
}
},
"c": {
"data": {
// data in edge ac
}
}
}
},
"b": {
"data": {
// b's vertex data
},
"neighbors": {
"c": {
"data": {
// data in edge bc
}
}
}
},
"c": {
"data": {
// c's vertex data
}
}
}
}
</code></pre> | 43,055,168 | 3 | 0 | null | 2017-03-27 16:57:05.747 UTC | 13 | 2020-03-14 04:23:14.683 UTC | 2017-05-23 12:25:30.577 UTC | null | -1 | null | 896,112 | null | 1 | 17 | json|data-structures|graph|directed-acyclic-graphs | 27,315 | <p>Since the DAG's edges hold data, they better have their own identifiers, just like the nodes. That is, the json representation should be composed of three components:</p>
<ol>
<li><strong>Node records:</strong> mapping each node identifier to the node's data.</li>
<li><strong>Edge records:</strong> mapping each edge identifier to the edge's data.</li>
<li><p><strong>Adjacency lists:</strong> mapping each node identifier to an array of edge identifiers, each corresponds to an edge going out of the node.</p>
<pre><code>DAG = {
"adjacency": {
"a": ["1", "2"],
"b": ["3"]
},
"nodes": {
"a": {
// data
},
"b": {
// data
},
"c": {
// data
}
},
"edges": {
"1": {
"from": "a", "to": "b",
"data": {
// data
}
},
"2": {
"from": "a", "to": "b",
"data": {
// data
}
},
"3": {
"from": "b", "to": "c",
"data": {
// data
}
}
}
}
</code></pre></li>
</ol> |
25,636,779 | Google play error "Please check the languages marked above for errors" | <p>currently receiving the following error withiin google play under store listing:
Please check the languages marked above for errors.
no matter what language i select this error shows and i am unable to update the store.. How to fix this?</p> | 25,636,834 | 7 | 1 | null | 2014-09-03 05:22:42.033 UTC | 2 | 2021-02-17 20:53:04.65 UTC | null | null | null | null | 1,175,430 | null | 1 | 34 | google-play | 16,549 | <p>Problem is caused by a mandatory feature graphic, error code is misleading..</p> |
39,778,686 | pandas reset_index after groupby.value_counts() | <p>I am trying to groupby a column and compute value counts on another column.</p>
<pre><code>import pandas as pd
dftest = pd.DataFrame({'A':[1,1,1,1,1,1,1,1,1,2,2,2,2,2],
'Amt':[20,20,20,30,30,30,30,40, 40,10, 10, 40,40,40]})
print(dftest)
</code></pre>
<p>dftest looks like</p>
<pre><code> A Amt
0 1 20
1 1 20
2 1 20
3 1 30
4 1 30
5 1 30
6 1 30
7 1 40
8 1 40
9 2 10
10 2 10
11 2 40
12 2 40
13 2 40
</code></pre>
<p>perform grouping</p>
<pre><code>grouper = dftest.groupby('A')
df_grouped = grouper['Amt'].value_counts()
</code></pre>
<p>which gives</p>
<pre><code> A Amt
1 30 4
20 3
40 2
2 40 3
10 2
Name: Amt, dtype: int64
</code></pre>
<p>what I want is to keep top two rows of each group</p>
<p>Also, I was perplexed by an error when I tried to <code>reset_index</code></p>
<pre><code>df_grouped.reset_index()
</code></pre>
<p>which gives following error</p>
<blockquote>
<p>df_grouped.reset_index()
ValueError: cannot insert Amt, already exists</p>
</blockquote> | 39,778,707 | 1 | 1 | null | 2016-09-29 19:41:03.913 UTC | 10 | 2020-05-14 10:54:28.88 UTC | 2016-09-29 19:54:42.683 UTC | null | 2,901,002 | null | 3,130,926 | null | 1 | 34 | python|pandas|dataframe|data-manipulation|data-science | 65,146 | <p>You need parameter <code>name</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>reset_index</code></a>, because <code>Series</code> name is same as name of one of levels of <code>MultiIndex</code>:</p>
<pre><code>df_grouped.reset_index(name='count')
</code></pre>
<p>Another solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rename.html" rel="noreferrer"><code>rename</code></a> <code>Series</code> name:</p>
<pre><code>print (df_grouped.rename('count').reset_index())
A Amt count
0 1 30 4
1 1 20 3
2 1 40 2
3 2 40 3
4 2 10 2
</code></pre>
<hr>
<p>More common solution instead <code>value_counts</code> is aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="noreferrer"><code>size</code></a>:</p>
<pre><code>df_grouped1 = dftest.groupby(['A','Amt']).size().reset_index(name='count')
print (df_grouped1)
A Amt count
0 1 20 3
1 1 30 4
2 1 40 2
3 2 10 2
4 2 40 3
</code></pre> |
6,814,780 | Regex - Without Special Characters | <p>I'm using regex to validate username</p>
<pre><code>^[a-zA-Z]+\.[a-zA-Z]{4,10}^'
</code></pre>
<p>Unfortunately it doesn't affect if the the value contains special characters such as <code>!@#$%^&*)(':;</code></p>
<p>I would glad to get some help for Regex that contains:</p>
<ul>
<li>Alphanumeric only (<code>a-zA-Z0-9</code>)</li>
<li>Length between 4 - 10 characters.</li>
</ul> | 6,814,901 | 2 | 3 | null | 2011-07-25 10:33:32.047 UTC | 1 | 2021-04-16 15:43:35.083 UTC | 2021-04-16 15:43:35.083 UTC | null | 2,370,483 | user330885 | null | null | 1 | 19 | regex|special-characters|alphanumeric | 128,615 | <p>The conditions you specified do not conform to the regexp you posted.</p>
<p>the regexp you posted <code>^[a-zA-Z]+\.[a-zA-Z]{4,10}^</code> is erroneous I guess, because of the <code>^</code> in the end, <strong>it will never be matched to any expression</strong>, if you want to match with the <code>^</code> at the end of the expression, you need to escape it like this <code>\^</code>. but <code>^</code> alone means "here is the start of the expression", while <code>$</code> means "here is the end of the expression".</p>
<p>Even though, it denotes:</p>
<ul>
<li>It starts with alpha (at least 1).</li>
<li>there must be a '.' period character.</li>
<li>Now there must be at least 4 alphas.</li>
</ul>
<p>The regexp you need is really is:</p>
<pre><code>^[a-zA-Z0-9]{4,10}$
</code></pre>
<p>This says:</p>
<ul>
<li>It starts with alphanumeric.</li>
<li>There can be minimum of 4 and maximum of 10 of alphanumeric.</li>
<li>End of expression.</li>
</ul> |
6,453,842 | JSF 2 - How can I add an Ajax listener method to composite component interface? | <p>I have a JSF 2 composite component that employs some Ajax behavior. I want to add a <code>listener</code> method to the <code><f:ajax></code> tag inside my composite component, but the <code>listener</code> method should be provided as a <code><composite:attribute></code> in the <code><composite:interface></code>.</p>
<p>The <code><f:ajax></code> tag inside my composite component is currently hard-coded to a listener like this:</p>
<pre class="lang-html prettyprint-override"><code><f:ajax
event="valueChange"
execute="@this"
listener="#{controller.genericAjaxEventLogger}"
render="#{cc.attrs.ajaxRenderTargets}" />
</code></pre>
<p>The listener method on the bean has this signature:</p>
<pre><code>public void genericAjaxEventLogger(AjaxBehaviorEvent event)
throws AbortProcessingException {
// implementation code...
}
</code></pre>
<p>I want the composite component to be something like this so the page can supply its own event method, but I can't figure out the correct syntax for the interface.</p>
<pre class="lang-html prettyprint-override"><code><f:ajax
event="valueChange"
execute="@this"
listener="#{cc.attrs.ajaxEventListener}"
render="#{cc.attrs.ajaxRenderTargets}" />
</code></pre>
<p><strong>How can I do this?</strong></p>
<p><em><strong>UPDATED WITH SOLUTION:</em></strong></p>
<p>I took the approach suggested by BalusC and it works great. The relevant snippets are:</p>
<p>The interface declaration in the composite component</p>
<pre class="lang-html prettyprint-override"><code><composite:interface>
<composite:attribute
name="myattributeUpdatedEventListener"
method-signature="void listener()"
required="true" />
...
</composite:interface>
</code></pre>
<p>The Ajax tag used in my composite component</p>
<pre class="lang-html prettyprint-override"><code><f:ajax
event="valueChange"
execute="@this"
listener="#{cc.attrs.myattributeUpdatedEventListener}"
render="#{cc.attrs.ajaxRenderTargets}" />
</code></pre>
<p>The place in my page where I use the composite component</p>
<pre class="lang-html prettyprint-override"><code><h:form>
<compcomp:myCompositeComponent
myattributeUpdatedEventListener="#{myBackingBean.updatedEventListenerXYZ}" />
</h:form>
</code></pre>
<p>And the method on my backing bean</p>
<pre><code>public void updatedEventListenerXYZ() {
// do something here...
}
</code></pre> | 6,454,339 | 2 | 2 | null | 2011-06-23 12:17:25.51 UTC | 10 | 2011-10-26 14:37:35.827 UTC | 2011-10-26 14:37:35.827 UTC | null | 157,882 | null | 346,112 | null | 1 | 23 | java|ajax|jsf-2|listener|composite-component | 30,964 | <p>If you <em>can</em> get rid of the <code>AjaxBehaviorEvent</code> argument,</p>
<pre><code>public void genericAjaxEventLogger() {
// ...
}
</code></pre>
<p>then you can use</p>
<pre class="lang-xml prettyprint-override"><code><cc:attribute name="ajaxEventListener" method-signature="void listener()" />
</code></pre>
<p>If the argument is mandatory (for logging?), then you need to re-specify the attribute as follows</p>
<pre class="lang-xml prettyprint-override"><code><cc:attribute name="ajaxEventListener" method-signature="void listener(javax.faces.event.AjaxBehaviorEvent)" />
</code></pre>
<p>However, this does here not work as expected with</p>
<pre class="lang-xml prettyprint-override"><code><f:ajax listener="#{cc.attrs.ajaxEventListener}" />
</code></pre>
<p>on GF 3.1 + Mojarra 2.1.1:</p>
<pre><code>SEVERE: javax.faces.FacesException: wrong number of arguments
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:89)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:409)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at com.sun.faces.facelets.el.ContextualCompositeMethodExpression.invoke(ContextualCompositeMethodExpression.java:177)
at com.sun.faces.facelets.tag.TagAttributeImpl$AttributeLookupMethodExpression.invoke(TagAttributeImpl.java:450)
at com.sun.faces.facelets.tag.jsf.core.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxHandler.java:447)
at javax.faces.event.AjaxBehaviorEvent.processListener(AjaxBehaviorEvent.java:113)
at javax.faces.component.behavior.BehaviorBase.broadcast(BehaviorBase.java:102)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:760)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
... 28 more
</code></pre>
<p>I'm not sure if this is a bug or not. For that I'd need to invest some more time to naildown it. However, it was workaroundable by creating a backing component which gets the <code>MethodExpression</code> from the attributes and invokes with the right number of arguments. Here's a complete kickoff example:</p>
<pre class="lang-xml prettyprint-override"><code><ui:component
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:cc="http://java.sun.com/jsf/composite"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<cc:interface componentType="testCC">
<cc:attribute name="ajaxEventListener" method-signature="void listener(javax.faces.event.AjaxBehaviorEvent)" />
</cc:interface>
<cc:implementation>
<h:commandButton value="Submit">
<f:ajax listener="#{cc.ajaxEventListener}" />
</h:commandButton>
</cc:implementation>
</ui:component>
</code></pre>
<p>with</p>
<pre><code>package com.example;
import javax.el.MethodExpression;
import javax.faces.component.FacesComponent;
import javax.faces.component.UINamingContainer;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
@FacesComponent(value="testCC")
public class TestCC extends UINamingContainer {
public void ajaxEventListener(AjaxBehaviorEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
MethodExpression ajaxEventListener = (MethodExpression) getAttributes().get("ajaxEventListener");
ajaxEventListener.invoke(context.getELContext(), new Object[] { event });
}
}
</code></pre>
<p>Regardless, I believe that the backing component puts doors open for new ways to achieve the functional requirement you have had in mind anyway ;)</p> |
7,450,370 | Disable select options based on value *through the HTML only!* | <p>I need to disable a select option based on the value of a variable. The value is similar to one of the select option value and it needs to be disabled.</p>
<p>For ex,</p>
<pre><code><select>
<option>Value a</option>
<option>Value b</option>
</select>
$variable = <some select option value>;
</code></pre>
<p>So if variable is equal to Value a then it needs to be disabled in select option.</p>
<p>Thanks.</p> | 7,450,414 | 4 | 0 | null | 2011-09-16 21:01:59.703 UTC | 5 | 2018-12-20 14:50:34.587 UTC | 2014-07-09 12:27:22.05 UTC | null | 1,428,854 | null | 729,338 | null | 1 | 21 | jquery|html|select | 75,986 | <p>With your current markup this will work:</p>
<pre><code>$("select option:contains('Value b')").attr("disabled","disabled");
</code></pre>
<p><a href="http://jsfiddle.net/CtqC6/">http://jsfiddle.net/CtqC6/</a></p>
<p>EDIT</p>
<p><a href="http://jsfiddle.net/CtqC6/1/">http://jsfiddle.net/CtqC6/1/</a></p>
<pre><code>var variable = "b"
$("select option:contains('Value " + variable + "')").attr("disabled","disabled");
$("select").prop("selectedIndex",-1)
</code></pre> |
24,224,441 | How do I create a noop block for a switch case in Swift? | <p>How do I create a noop block for a switch case in Swift? Swift forces you to have at least one executable statement under your case, including default. I tried putting an empty { } but Swift won't take that. Which means that Swift's switch case is not totally translatable between if-else and vice versa because in if-else you are allowed to have empty code inside the condition.</p>
<p>e.g.</p>
<pre><code>switch meat {
case "pork":
print("pork is good")
case "poulet":
print("poulet is not bad")
default:
// I want to do nothing here
}
</code></pre> | 24,224,475 | 1 | 1 | null | 2014-06-14 21:26:06.27 UTC | 2 | 2015-03-24 21:44:11.513 UTC | null | null | null | null | 66,814 | null | 1 | 58 | swift | 12,817 | <pre><code>default:
break
</code></pre>
<p>Apple talks about this keyword in <a href="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Statements.html#//apple_ref/doc/uid/TP40014097-CH33-XID_976" rel="noreferrer"><strong>this article</strong></a>. See <a href="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_174" rel="noreferrer"><strong>here</strong></a>, too.</p>
<blockquote>
<p>Although break is not required in Swift, you can still use a break statement to match and ignore a particular case, or to break out of a matched case before that case has completed its execution.</p>
</blockquote> |
24,242,060 | How to change memory per node for apache spark worker | <p>I am configuring an Apache Spark cluster.</p>
<p>When I run the cluster with 1 master and 3 slaves, I see this on the master monitor page:</p>
<pre><code>Memory
2.0 GB (512.0 MB Used)
2.0 GB (512.0 MB Used)
6.0 GB (512.0 MB Used)
</code></pre>
<p>I want to increase the used memory for the workers but I could not find the right config for this. I have changed <strong>spark-env.sh</strong> as below:</p>
<pre><code>export SPARK_WORKER_MEMORY=6g
export SPARK_MEM=6g
export SPARK_DAEMON_MEMORY=6g
export SPARK_JAVA_OPTS="-Dspark.executor.memory=6g"
export JAVA_OPTS="-Xms6G -Xmx6G"
</code></pre>
<p>But the used memory is still the same. What should I do to change used memory?</p> | 24,243,287 | 5 | 1 | null | 2014-06-16 10:53:47.327 UTC | 11 | 2016-03-10 17:53:45.647 UTC | 2014-06-16 23:30:55.967 UTC | null | 877,069 | null | 2,981,694 | null | 1 | 34 | memory|cluster-computing|config|apache-spark | 34,044 | <p>When using 1.0.0+ and using spark-shell or spark-submit, use the <code>--executor-memory</code> option. E.g.</p>
<pre><code>spark-shell --executor-memory 8G ...
</code></pre>
<p><strong>0.9.0 and under:</strong></p>
<p>When you start a job or start the shell change the memory. We had to modify the spark-shell script so that it would carry command line arguments through as arguments for the underlying java application. In particular:</p>
<pre><code>OPTIONS="$@"
...
$FWDIR/bin/spark-class $OPTIONS org.apache.spark.repl.Main "$@"
</code></pre>
<p>Then we can run our spark shell as follows:</p>
<pre><code>spark-shell -Dspark.executor.memory=6g
</code></pre>
<p>When configuring it for a standalone jar, I set the system property programmatically before creating the spark context and pass the value in as a command line argument (I can make it shorter than the long winded system props then).</p>
<pre><code>System.setProperty("spark.executor.memory", valueFromCommandLine)
</code></pre>
<p>As for changing the default cluster wide, sorry, not entirely sure how to do it properly.</p>
<p>One final point - I'm a little worried by the fact you have 2 nodes with 2GB and one with 6GB. The memory you can use will be limited to the smallest node - so here 2GB.</p> |
7,730,562 | How to set up Beanstalkd with PHP | <p>Recently I've been researching the use of Beanstalkd with PHP. I've learned quite a bit but have a few questions about the setup on a server, etc.</p>
<p>Here is how I see it working:</p>
<ol>
<li>I install Beanstalkd and any dependencies (such as libevent) on my Ubuntu server. I then start the Beanstalkd daemon (which should basically run at all times).</li>
<li>Somewhere in my website (such as when a user performs some actions, etc) tasks get added to various tubes within the Beanstalkd queue.</li>
<li><p>I have a bash script (such as the following one) that is run as a deamon that basically executes a PHP script.</p>
<pre><code>#!/bin/sh
php worker.php
</code></pre></li>
</ol>
<p>4) The worker script would have something like this to execute the queued up tasks:</p>
<pre><code>while(1) {
$job = $this->pheanstalk->watch('test')->ignore('default')->reserve();
$job_encoded = json_decode($job->getData(), false);
$done_jobs[] = $job_encoded;
$this->log('job:'.print_r($job_encoded, 1));
$this->pheanstalk->delete($job);
}
</code></pre>
<p>Now here are my questions based on the above setup (which correct me if I'm wrong about that):</p>
<ol>
<li><p>Say I have the task of importing an RSS feed into a database or something. If 10 users do this at once, they'll all be queued up in the "test" tube. However, they'd then only be executed one at a time. Would it be better to have 10 different tubes all executing at the same time?</p></li>
<li><p>If I do need more tubes, does that then also mean that i'd need 10 worker scripts? One for each tube all running concurrently with basically the same code except for the string literal in the watch() function.</p></li>
<li><p>If I run that script as a daemon, how does that work? Will it constantly be executing the worker.php script? That script loops until the queue is empty theoretically, so shouldn't it only be kicked off once? How does the daemon decide how often to execute worker.php? Is that just a setting?</p></li>
</ol>
<p>Thanks!</p> | 7,732,659 | 1 | 0 | null | 2011-10-11 18:17:19.157 UTC | 9 | 2013-08-01 14:17:13.693 UTC | 2013-08-01 14:17:13.693 UTC | null | 42,522 | null | 115,629 | null | 1 | 12 | php|bash|message-queue|daemon|beanstalkd | 7,974 | <ol>
<li>If the worker isn't taking too long to fetch the feed, it will be fine. You can run multiple workers if required to process more than one at a time. I've got a system (currently using Amazon SQS, but I've done similar with BeanstalkD before), with up to 200 (or more) workers pulling from the queue.</li>
<li>A single worker script (the same script running multiple times) should be fine - the script can watch multiple tubes at the same time, and the first one available will be reserved. You can also use the <code>job-stat</code> command to see where a particular $job came from (which tube), or put some meta-information into the message if you need to tell each type from another.</li>
<li>A good example of running a worker is <a href="http://www.phpscaling.com/2009/06/23/doing-the-work-elsewhere-sidebar-running-the-worker/" rel="nofollow">described here</a>. I've also added <a href="http://supervisord.org/" rel="nofollow">supervisord</a> (also, a <a href="http://phpadvent.org/2009/daemonize-your-php-by-sean-coates" rel="nofollow">useful post</a> to get started) to easily start and keep running a number of workers per machine (I run shell scripts, as in the <a href="http://www.phpscaling.com/2009/06/23/doing-the-work-elsewhere-sidebar-running-the-worker/" rel="nofollow">first link</a>). I would limit the number of times it loops, and also put a number into the <code>reserve()</code> to have it wait for a few seconds, or more, for the next job the become available without spinning out of control in a tight loop that does not pause at all - even if there was nothing to do.</li>
</ol>
<p>Addendum:</p>
<ol>
<li>The shell script would be run as many times as you need. (the link show how to have it re-run as required with <code>exec $@</code>). Whenever the php script exits, it re-runs the PHP.</li>
<li>Apparently there's a Djanjo app to show some stats, but it's trivial enough to connect to the daemon, get a list of tubes, and then get the stats for each tube - or just counts.</li>
</ol> |
59,441,794 | ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly | <p>I get an error when pip builds wheels for the cryptography package.</p>
<p>Error:</p>
<p><a href="https://i.stack.imgur.com/2F20z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2F20z.png" alt="Error"></a></p>
<pre><code>LINK : fatal error LNK1181: cannot open input file 'libssl.lib'
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x86\\link.exe' failed with exit status 1181
----------------------------------------
ERROR: Failed building wheel for cryptography
Running setup.py clean for cryptography
Failed to build cryptography
ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
</code></pre>
<p>I have already installed OpenSSL and set the environment variables as suggested in <a href="https://stackoverflow.com/a/22210069/7199817">this post</a> yet the problem persists. My setup details: </p>
<ul>
<li>System - Windows 10 </li>
<li>Python - 3.8 </li>
<li>Pip - 19.3.1</li>
</ul> | 60,241,422 | 14 | 9 | null | 2019-12-22 05:19:39.62 UTC | 5 | 2022-09-22 22:26:09.507 UTC | 2019-12-24 11:58:08.77 UTC | null | 7,199,817 | null | 7,199,817 | null | 1 | 60 | python|pip|cryptography|python-cryptography | 124,772 | <p>Setting cryptography to version 2.8 in requirements.txt fixed the issue.</p> |
1,930,161 | Best practices to access schema-less data? | <p>I am toying with RDF, and in particular how to access information stored in a rdf storage. The huge difference from a traditional relational database is the lack of a predefined schema: in a relational database, you know that table has those columns, and you can technically map each row to an instance of a class. The class has well defined methods, and well defined attributes. </p>
<p>In a schema-less system, you don't know what data is associated to a given information. It's like having a database table with an arbitrary and not predefined number of columns, and every row can have data in any number of these columns.</p>
<p>Similar to ObjectRelational Mappers, there are Object RDF mappers. RDFAlchemy and SuRF are the two I am playing right now. Basically, they provide you a Resource object, whose methods and attributes are provided dynamically. It kind of make sense... however, it's not that easy. In many cases, you prefer to have a well defined interface, and to have more control of what's going on when you set and get data on your model object. Having such a generic access makes things difficult, in some sense.</p>
<p>Another thing (and most important) I noted is that, even if <em>in</em> <em>general</em>, schema-less data are expected to provide arbitrary information about a resource, in practice you more or less know "classes of information" that tend to be together. Of course, you cannot exclude the presence of additional info, but this, in some cases, is the exception, rather than the norm, although the exception is sensible enough to be too disruptive for a strict schema. In a rdf representation of an article (e.g. like in RSS/ATOM feeds) you know the terms of your described resources, and you can map them to a well defined object. If you provide additional information, you can define an extended object (inherited from the base one) to provide accessors to the enhanced information. So in a sense, you deal with schema-less data by means of "schema oriented objects" you can extend <em>when</em> you want to see specific additional information you are interested about.</p>
<p>My question is relative to your experience about real world usage practices of schema-less data storage. How do they map to the object-oriented world so that you can use it proficiently and without going too near to the "bare metal" of the schema-less storage ? (in RelDB terms, without using too much SQL and directly messing with the table structure)</p>
<p>Is the access doomed to be very generic (e.g. SuRF "plugged-in attributes" is the highest, most specialized level you can have to access your data), or having specialized classes for specific agreed convenient schemas is also a good approach, introducing however the risk of having a proliferation of classes to access new and unexpected associated data ?</p> | 1,987,087 | 4 | 1 | null | 2009-12-18 19:15:32.613 UTC | 11 | 2009-12-31 20:55:18.667 UTC | null | null | null | null | 78,374 | null | 1 | 9 | orm|schemaless | 2,241 | <p>I guess my short answer would be "don't". I'm a bit of a greybeard, and have done a lot of mapping XML data into relational databases. If you do decide to use such a database, you're going to have to validate your data constantly. You'll also need very strict discipline in order to avoid having databases with little commonality. Using a schema helps here, as most XML schemas are object-oriented and thus extensible, easing the need for analysis to keep from creating similar data with dissimilar names, which will cause anyone who has to access your database to think evil thoughts about you.</p>
<p>In my personal experience, if you're doing the sorts of things where a networked database makes sense, go for it. If not, you lose all the other things relational databases can do, like integrity checking, transactions and set selecting. However, since most people use a relational database as an object store anyway, I guess the point is moot.</p>
<p>As for how to access that data, just put it in a Hashtable. Seriously. If there is no schema anywhere, then you'll never know what is in there. If you have a schema, you can use that to generate accessor objects, but you gain little, as you lose all the flexibility of the underlying store while simultaneously gaining the inflexibility of a DAO (Data Access Object).</p>
<p>For instance, if you have a Hashtable, getting the values out of an XML parser is often fairly easy. You define the storage types you're going to use, then you walk the XML tree and put the values in the storage types, storing the types in either a Hashtable or List as appropriate. If, however, you use a DAO, you end up not being able to trivially extend the data object, one of the strengths of XML, and you have to create getters and setters for the object that do</p>
<pre><code>public void setter(Element e) throws NoSuchElementException {
try {
this.Name = e.getChild("Name").getValue();
} catch (Exception ex) {
throw new NoSuchElementException("Element not found for Name: "+ex.getMessage());
}
}
</code></pre>
<p>Except, of course, you have to do it for every single value in that schema layer, including loaders and definitions for sublayers. And, of course, you end up with a much bigger mess if you use the faster parsers that employ callbacks, as you now have to track which object your'e in as you produce the resultant tree.</p>
<p>I've done all this, although I normally construct a validator, then an adapter that provides the match between the XML and the data class, then a reconcile process to reconcile it to the database. Almost all the code ends up being generated, though. If you have the DTD, you can generate most of the Java code to access it, and do so with reasonable performance.</p>
<p>In the end, I'd simply keep freeform, networked or hierarchical data as freeform, networked or hierarchical data.</p> |
42,724,118 | Laravel 5.4^ - How to customize notification email layout? | <p>I am trying to customize the HTML email layout that is used when sending notifications via email.</p>
<p>I have published both the mail and notification views.</p>
<p><code>php artisan vendor:publish --tag=laravel-mail</code></p>
<p><code>php artisan vendor:publish --tag=laravel-notifications</code></p>
<p>If I modify the <code>/resources/views/vendor/notifications/email.blade.php</code> file, I can only change the BODY content of the emails that get sent. I am looking to modify the footer, header, and every other part of the email layout as well.</p>
<p>I tried also modifying the views inside <code>/resources/vendor/mail/html/</code>, but whenever the notification gets sent, it is not even using these views and instead uses the default laravel framework ones.</p>
<p>I am aware I can set a view on the <code>MailMessage</code> returned by my Notification class, but I want to keep the standard <code>line()</code>, <code>greeting()</code>, etc. functions.</p>
<p>Does anyone know how I can get my notifications to send email using the views in <code>/resources/vendor/mail/html</code> ?</p>
<p><a href="https://i.stack.imgur.com/S7EKi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/S7EKi.png" alt="enter image description here"></a></p>
<p>The following is my <code>/resources/views/vendor/notifications/email.blade.php</code> file, but it does not have anywhere to customize the header/footer/ overall layout.</p>
<pre><code>@component('mail::message')
{{-- Greeting --}}
@if (! empty($greeting))
# {{ $greeting }}
@else
@if ($level == 'error')
# Whoops!
@else
# Hello!
@endif
@endif
{{-- Intro Lines --}}
@foreach ($introLines as $line)
{{ $line }}
@endforeach
{{-- Action Button --}}
@if (isset($actionText))
<?php
switch ($level) {
case 'success':
$color = 'green';
break;
case 'error':
$color = 'red';
break;
default:
$color = 'blue';
}
?>
@component('mail::button', ['url' => $actionUrl, 'color' => $color])
{{ $actionText }}
@endcomponent
@endif
{{-- Outro Lines --}}
@foreach ($outroLines as $line)
{{ $line }}
@endforeach
<!-- Salutation -->
@if (! empty($salutation))
{{ $salutation }}
@else
Regards,<br>{{ config('app.name') }}
@endif
<!-- Subcopy -->
@if (isset($actionText))
@component('mail::subcopy')
If you’re having trouble clicking the "{{ $actionText }}" button, copy and paste the URL below
into your web browser: [{{ $actionUrl }}]({{ $actionUrl }})
@endcomponent
@endif
@endcomponent
</code></pre> | 42,725,231 | 8 | 9 | null | 2017-03-10 17:17:01.363 UTC | 10 | 2020-03-18 13:43:17.06 UTC | 2019-08-28 09:37:39.937 UTC | null | 2,502,731 | null | 830,247 | null | 1 | 27 | laravel|laravel-5|laravel-5.4 | 48,357 | <p>Run this command</p>
<pre><code>php artisan vendor:publish --tag=laravel-notifications
php artisan vendor:publish --tag=laravel-mail
</code></pre>
<blockquote>
<p>update for laravel 5.7+</p>
</blockquote>
<pre><code>php artisan vendor:publish
</code></pre>
<p>and then you will get:</p>
<pre><code> [<number>] Tag: laravel-mail
[<number>] Tag: laravel-notifications
</code></pre>
<p>and then just type in that number in front to publish the file for editing</p>
<hr>
<p>and then in </p>
<pre><code>/resources/views/vendor/mail/html/
</code></pre>
<p>you can edit all the components and customize anything you want.
For example i have edited the sentence "All rights reserved". to "All test reserved" at the bottom of that image inside this file:</p>
<pre><code>/resources/views/vendor/mail/html/message.blade.php
</code></pre>
<p>and this is what i got:</p>
<p><a href="https://i.stack.imgur.com/gaoxS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gaoxS.png" alt="enter image description here"></a></p> |
28,599,870 | Laravel: Controller does not exist | <p>I added new controller in /app/controllers/admin/ folder and added the route in /app/routes.php file as well. Then i run the following command to autoload them</p>
<pre><code>php artisan dump-autoload
</code></pre>
<p>I got the following error</p>
<pre><code>Mcrypt PHP extension required.
</code></pre>
<p>I followed instruction given at <a href="https://askubuntu.com/questions/460837/mcrypt-extension-is-missing-in-14-04-server-for-mysql">https://askubuntu.com/questions/460837/mcrypt-extension-is-missing-in-14-04-server-for-mysql</a> and able to resolve the mcrypt issue.</p>
<p>After that i run the <code>php artisan dump-autoload</code> command but still getting following error</p>
<pre><code>{"error":{"type":"ReflectionException","message":"Class CoursesController does not exist","file":"\/var\/www\/html\/vendor\/laravel\/framework\/src\/Illuminate\/Container\/Container.php","line":504}}
</code></pre>
<p>Here is code of my <strong>routes.php</strong> file</p>
<pre><code>Route::group(array('before' => 'adminauth', 'except' => array('/admin/login', '/admin/logout')), function() {
Route::resource('/admin/courses', 'CoursesController');
Route::resource('/admin/teachers', 'TeachersController');
Route::resource('/admin/subjects', 'SubjectsController');
});
</code></pre>
<p>Here is code of <strong>CoursesController.php</strong> file</p>
<pre><code><?php
class CoursesController extends BaseController
{
public function index()
{
$courses = Course::where('is_deleted', 0)->get();
return View::make('admin.courses.index', compact('courses'));
}
public function create()
{
return View::make('admin.courses.create');
}
public function store()
{
$validator = Validator::make($data = Input::all(), Course::$rules);
if ($validator->fails()) {
$messages = $validator->messages();
$response = '';
foreach ($messages->all(':message') as $message) {
$response = $message;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
Course::create($data);
return Response::json(array('message'=>'Course created successfully','status'=>'success'));
}
}
public function edit($id)
{
$course = Course::find($id);
return View::make('admin.courses.edit', compact('course'));
}
public function update($id)
{
$course = Course::findOrFail($id);
$validator = Validator::make($data = Input::all(), Course::editRules($id));
if ($validator->fails()) {
$messages = $validator->messages();
$response = '';
foreach ($messages->all(':message') as $message) {
$response = $message;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
$course->update($data);
return Response::json(array('message'=>'Course updated successfully','status'=>'success'));
}
}
public function destroy($id)
{
Course::findOrFail($id)->update(array('is_deleted' => '1'));
return Response::json(array('message'=>'Course deleted successfully','status'=>'success'));
}
}
</code></pre> | 28,600,419 | 13 | 3 | null | 2015-02-19 06:23:02.327 UTC | 7 | 2022-04-14 13:43:35.4 UTC | 2017-04-13 12:22:42.277 UTC | null | -1 | null | 592,298 | null | 1 | 21 | laravel-4|controller|autoload | 81,212 | <p>Did you add autoload classmap to composer.json file?
Open your composer.json file and add</p>
<pre><code>"autoload": {
"classmap": [
"app/controllers/admin",
]
}
</code></pre>
<p>if you add folders inside controllers, you need to add it to composer.json file. Then run</p>
<pre><code>composer dumpautoload
</code></pre>
<p><strong>OR ALTERNATIVE</strong></p>
<p>go to app/start/global.php and add</p>
<pre><code>ClassLoader::addDirectories(array(
app_path().'/controllers/admin',
));
</code></pre> |
28,763,389 | How does the removeSparseTerms in R work? | <p>I am using the removeSparseTerms method in R and it required a threshold value to be input. I also read that the higher the value, the more will be the number of terms retained in the returned matrix.</p>
<p>How does this method work and what is the logic behind it? I understand the concept of sparseness but does this threshold indicate how many documents should a term be present it, or some other ratio, etc?</p> | 33,830,637 | 3 | 3 | null | 2015-02-27 10:55:27.143 UTC | 16 | 2019-10-12 19:36:08.997 UTC | null | null | null | null | 492,372 | null | 1 | 20 | r|tm|lda | 34,024 | <p>In the sense of the <code>sparse</code> argument to <code>removeSparseTerms()</code>, sparsity refers to the threshold of <em>relative document frequency</em> for a term, <strong>above which</strong> the term will be removed. Relative document frequency here means a proportion. As the help page for the command states (although not very clearly), sparsity is <em>smaller</em> as it approaches 1.0. (Note that sparsity cannot take values of 0 or 1.0, only values in between.)</p>
<p>For example, if you set <code>sparse = 0.99</code> as the argument to <code>removeSparseTerms()</code>, then this will remove only terms that are <em>more</em> sparse than 0.99.
The exact interpretation for <code>sparse = 0.99</code> is that for term $j$, you will retain all terms for which
$df_j > N * (1 - 0.99)$, where $N$ is the number of documents -- in this case probably all terms will be retained (see example below).</p>
<p>Near the other extreme, if <code>sparse = .01</code>, then only terms that appear in (nearly) every document will be retained. (Of course this depends on the number of terms and the number of documents, and in natural language, common words like "the" are likely to occur in every document and hence never be "sparse".)</p>
<p>An example of the sparsity threshold of 0.99, where a term that occurs at most in (first example) less than 0.01 documents, and (second example) just over 0.01 documents:</p>
<pre><code>> # second term occurs in just 1 of 101 documents
> myTdm1 <- as.DocumentTermMatrix(slam::as.simple_triplet_matrix(matrix(c(rep(1, 101), rep(1,1), rep(0, 100)), ncol=2)),
+ weighting = weightTf)
> removeSparseTerms(myTdm1, .99)
<<DocumentTermMatrix (documents: 101, terms: 1)>>
Non-/sparse entries: 101/0
Sparsity : 0%
Maximal term length: 2
Weighting : term frequency (tf)
>
> # second term occurs in 2 of 101 documents
> myTdm2 <- as.DocumentTermMatrix(slam::as.simple_triplet_matrix(matrix(c(rep(1, 101), rep(1,2), rep(0, 99)), ncol=2)),
+ weighting = weightTf)
> removeSparseTerms(myTdm2, .99)
<<DocumentTermMatrix (documents: 101, terms: 2)>>
Non-/sparse entries: 103/99
Sparsity : 49%
Maximal term length: 2
Weighting : term frequency (tf)
</code></pre>
<p>Here are a few additional examples with actual text and terms: </p>
<pre><code>> myText <- c("the quick brown furry fox jumped over a second furry brown fox",
"the sparse brown furry matrix",
"the quick matrix")
> require(tm)
> myVCorpus <- VCorpus(VectorSource(myText))
> myTdm <- DocumentTermMatrix(myVCorpus)
> as.matrix(myTdm)
Terms
Docs brown fox furry jumped matrix over quick second sparse the
1 2 2 2 1 0 1 1 1 0 1
2 1 0 1 0 1 0 0 0 1 1
3 0 0 0 0 1 0 1 0 0 1
> as.matrix(removeSparseTerms(myTdm, .01))
Terms
Docs the
1 1
2 1
3 1
> as.matrix(removeSparseTerms(myTdm, .99))
Terms
Docs brown fox furry jumped matrix over quick second sparse the
1 2 2 2 1 0 1 1 1 0 1
2 1 0 1 0 1 0 0 0 1 1
3 0 0 0 0 1 0 1 0 0 1
> as.matrix(removeSparseTerms(myTdm, .5))
Terms
Docs brown furry matrix quick the
1 2 2 0 1 1
2 1 1 1 0 1
3 0 0 1 1 1
</code></pre>
<p>In the last example with <code>sparse = 0.34</code>, only terms occurring in two-thirds of the documents were retained.</p>
<p>An alternative approach for trimming terms from document-term matrixes based on a document frequency is the <strong>text analysis package <a href="http://github.com/kbenoit/quanteda" rel="nofollow noreferrer">quanteda</a></strong>. The same functionality here refers not to <em>sparsity</em> but rather directly to the <em>document frequency</em> of terms (as in <em>tf-idf</em>).</p>
<pre><code>> require(quanteda)
> myDfm <- dfm(myText, verbose = FALSE)
> docfreq(myDfm)
a brown fox furry jumped matrix over quick second sparse the
1 2 1 2 1 2 1 2 1 1 3
> dfm_trim(myDfm, minDoc = 2)
Features occurring in fewer than 2 documents: 6
Document-feature matrix of: 3 documents, 5 features.
3 x 5 sparse Matrix of class "dfmSparse"
features
docs brown furry the matrix quick
text1 2 2 1 0 1
text2 1 1 1 1 0
text3 0 0 1 1 1
</code></pre>
<p>This usage seems much more straightforward to me.</p> |
28,744,096 | Convert ByteBuffer to byte array java | <p>Does anyone know how to convert ByteBuffer to byte[] array? I need to get byte array from my <code>ByteBuffer</code>. When I run <code>bytebuffer.hasArray()</code> it returns no. Every question I looked so far is converting byte array to byteBuffer, but I need it other way around.
Thank you.</p> | 28,744,228 | 2 | 4 | null | 2015-02-26 13:44:11.237 UTC | 5 | 2022-08-24 12:31:27.753 UTC | 2021-02-10 10:52:54.367 UTC | null | 350,428 | null | 4,508,333 | null | 1 | 52 | java|arrays|bytebuffer | 93,018 | <p><code>ByteBuffer</code> exposes the bulk <code>get(byte[])</code> method which transfers bytes from the buffer into the array. You'll need to instantiate an array of length equal to the number of remaining bytes in the buffer. </p>
<pre><code>ByteBuffer buf = ...
byte[] arr = new byte[buf.remaining()];
buf.get(arr);
</code></pre> |
7,643,999 | How to remove white space characters in between the string? | <p>For example, I want to convert the string <code>test123 test124 test125</code> to </p>
<p><code>test123+""+test124+""+test125</code> or <code>test123test124test125</code>. </p>
<p>How to achieve this?</p>
<p>Thanks</p> | 7,644,041 | 5 | 2 | null | 2011-10-04 06:24:23.033 UTC | 3 | 2015-09-15 12:38:31.533 UTC | 2011-10-04 06:57:43.14 UTC | null | 251,173 | null | 726,964 | null | 1 | 16 | java | 54,747 | <pre><code>String output = inputText.replaceAll("\\s+","");
</code></pre> |
7,377,912 | OpenGL define vertex position in pixels | <p>I've been writing a 2D basic game engine in OpenGL/C++ and learning everything as I go along. I'm still rather confused about defining vertices and their "position". That is, I'm still trying to understand the vertex-to-pixels conversion mechanism of OpenGL. Can it be explained briefly or can someone point to an article or something that'll explain this. Thanks!</p> | 7,378,146 | 5 | 6 | null | 2011-09-11 11:29:30.823 UTC | 14 | 2011-10-04 20:54:01.56 UTC | 2011-09-11 11:48:03.947 UTC | null | 734,069 | user562566 | null | null | 1 | 25 | c++|opengl | 22,763 | <p>This is rather basic knowledge that your favourite OpenGL learning resource should teach you as one of the first things. But anyway the standard OpenGL pipeline is as follows:</p>
<ol>
<li><p>The vertex position is transformed from object-space (local to some object) into world-space (in respect to some global coordinate system). This transformation specifies where your object (to which the vertices belong) is located in the world</p></li>
<li><p>Now the world-space position is transformed into camera/view-space. This transformation is determined by the position and orientation of the virtual camera by which you see the scene. In OpenGL these two transformations are actually combined into one, the modelview matrix, which directly transforms your vertices from object-space to view-space.</p></li>
<li><p>Next the projection transformation is applied. Whereas the modelview transformation should consist only of affine transformations (rotation, translation, scaling), the projection transformation can be a perspective one, which basically distorts the objects to realize a real perspective view (with farther away objects being smaller). But in your case of a 2D view it will probably be an orthographic projection, that does nothing more than a translation and scaling. This transformation is represented in OpenGL by the projection matrix.</p></li>
<li><p>After these 3 (or 2) transformations (and then following perspective division by the w component, which actually realizes the perspective distortion, if any) what you have are normalized device coordinates. This means after these transformations the coordinates of the visible objects should be in the range <code>[-1,1]</code>. Everything outside this range is clipped away.</p></li>
<li><p>In a final step the viewport transformation is applied and the coordinates are transformed from the <code>[-1,1]</code> range into the <code>[0,w]x[0,h]x[0,1]</code> cube (assuming a <code>glViewport(0, w, 0, h)</code> call), which are the vertex' final positions in the framebuffer and therefore its pixel coordinates.</p></li>
</ol>
<p>When using a vertex shader, steps 1 to 3 are actually done in the shader and can therefore be done in any way you like, but usually one conforms to this standard modelview -> projection pipeline, too.</p>
<p>The main thing to keep in mind is, that after the modelview and projection transforms every vertex with coordinates outside the <code>[-1,1]</code> range will be clipped away. So the <code>[-1,1]</code>-box determines your visible scene after these two transformations.</p>
<p>So from your question I assume you want to use a 2D coordinate system with units of pixels for your vertex coordinates and transformations? In this case this is best done by using <code>glOrtho(0.0, w, 0.0, h, -1.0, 1.0)</code> with <code>w</code> and <code>h</code> being the dimensions of your viewport. This basically counters the viewport transformation and therefore transforms your vertices from the <code>[0,w]x[0,h]x[-1,1]</code>-box into the <code>[-1,1]</code>-box, which the viewport transformation then transforms back to the <code>[0,w]x[0,h]x[0,1]</code>-box.</p>
<p>These have been quite general explanations without mentioning that the actual transformations are done by matrix-vector-multiplications and without talking about homogenous coordinates, but they should have explained the essentials. This <a href="http://www.opengl.org/sdk/docs/man/xhtml/gluProject.xml" rel="noreferrer">documentation of gluProject</a> might also give you some insight, as it actually models the transformation pipeline for a single vertex. But in this documentation they actually forgot to mention the division by the w component (<code>v" = v' / v'(3)</code>) after the <code>v' = P x M x v</code> step.</p>
<p><strong>EDIT:</strong> Don't forget to look at the <a href="http://www.songho.ca/opengl/gl_transform.html" rel="noreferrer">first link</a> in epatel's answer, which explains the transformation pipeline a bit more practical and detailed.</p> |
14,252,465 | PHPExcel file cannot open file because the file format or file extension is not valid | <p>I'm stuck with this problem, it's not displaying the actual excel file. Please check my code below:</p>
<pre><code>/** Error reporting */
error_reporting(E_ALL);
/** PHPExcel */
require_once 'PHPExcel.php';
include 'PHPExcel/Writer/Excel2007.php';
// Create new PHPExcel object
#echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();
$excel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("Payroll");
if(!$result){
die("Error");
}
$col = 0;
$row = 2;
while($mrow = mysql_fetch_assoc($result)) {
$col = 0;
foreach($mrow as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Scholar Id')
->setCellValue('B1', 'Lastname')
->setCellValue('C1', 'Middlename')
->setCellValue('D1', 'Firstname')
->setCellValue('E1', 'Barangay')
->setCellValue('F1', 'Level')
->setCellValue('G1', 'Allowance')
->setCellValue('H1', 'Has claimed?');
$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(18);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(14);
$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getAlignment()- >setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->setShowGridlines(true);
$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->applyFromArray(
array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'FFFF00')
)
)
);
// Save Excel 2007 file
echo date('H:i:s') . " Write to Excel2007 format\n";
#$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="payroll.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
</code></pre> | 14,256,562 | 9 | 2 | null | 2013-01-10 07:03:42.923 UTC | 4 | 2020-08-04 03:48:44.14 UTC | 2018-12-15 06:52:58.123 UTC | null | 5,022,249 | user1410081 | null | null | 1 | 12 | php|phpexcel | 61,138 | <p>I got it working now! Thanks to this <a href="https://stackoverflow.com/questions/8566196/phpexcel-to-download">phpexcel to download</a></p>
<p>I changed the code to this:</p>
<pre><code>// Save Excel 2007 file
#echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="payroll.xlsx"');
$objWriter->save('php://output');
</code></pre>
<p>I think this line: </p>
<pre><code>ob_end_clean();
</code></pre>
<p>solved my problem.</p> |
14,251,220 | How to delete a specific file from folder using asp.net | <p>here's the deal I got a datagridviewer which is called gridview1 and a fileupload1 when i upload a file it updates the gridview1 and table in database with the file name and path and stores the said file in folder "Mag"... but now what i want to do is the reverse i got how to use the gridview to delete the table entry but deleting the file from folder "Mag" is not working have used the following code in C# or codebehind</p>
<pre><code>protected void GridView1_Del(object sender, EventArgs e)
{
string DeleteThis = GridView1.SelectedRow.Cells[0].Text;
string[] Files = Directory.GetFiles(@"i:/Website/WebSite3/Mag/");
foreach (string file in Files)
{
if (file.ToUpper().Contains(DeleteThis.ToUpper()))
{
File.Delete(file);
}
}
}
</code></pre>
<p>it gives me error </p>
<blockquote>
<p>"Object reference not set to an instance of an object." </p>
</blockquote>
<p>pls tell me what im doing wrong am new and don't have to in depth understanding of the platform so any and all help will be appreciated
thanks in advance
Mark </p>
<p>Here is the answer i found Thanks Tammy and everyone else for all the answers</p>
<p>Ok here the deal target function delete file details from gridview and database table and file from project folder where the file is stored </p>
<p>in script section of gridview you would want to include</p>
<pre><code>OnRowDeleting="FuntionName"
</code></pre>
<p>Not</p>
<pre><code>OnSelectedIndexChanged = "FuntionName"
</code></pre>
<p>or</p>
<pre><code>OnRowDeleted="FuntionName"
</code></pre>
<p>then in C# code(codebehind)</p>
<pre><code>protected void FuntionName(object sender, GridViewDeleteEventArgs e)
{
// storing value from cell
TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
// full path required
string fileName = ("i:/Website/WebSite3/Mag/" + cell.Text);
if(fileName != null || fileName != string.Empty)
{
if((System.IO.File.Exists(fileName)))
{
System.IO.File.Delete(fileName);
}
}
}
</code></pre>
<p>And just for added reference for those who want to learn</p>
<p>OnRowDeleting="FuntionName" is for just before deleting a row you can cancel deleting or run functions on the data like i did</p>
<p>OnRowDeleted="FuntionName" it directly deletes</p> | 14,251,470 | 5 | 6 | null | 2013-01-10 05:14:35.047 UTC | 8 | 2017-04-14 07:55:56.247 UTC | 2014-07-14 13:29:11.81 UTC | null | 759,866 | null | 1,922,335 | null | 1 | 18 | c#|asp.net | 122,336 | <p>This is how I delete files</p>
<pre><code>if ((System.IO.File.Exists(fileName)))
{
System.IO.File.Delete(fileName);
}
</code></pre>
<p>Also make sure that the file name you are passing in your delete, is the accurate path</p>
<p><strong>EDIT</strong></p>
<p>You could use the following event instead as well or just use the code in this snippet and use in your method</p>
<pre><code>void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = CustomersGridView.SelectedRow;
//Debug this line and see what value is returned if it contains the full path.
//If it does not contain the full path then add the path to the string.
string fileName = row.Cells[0].Text
if(fileName != null || fileName != string.empty)
{
if((System.IO.File.Exists(fileName))
System.IO.File.Delete(fileName);
}
}
</code></pre> |
14,247,373 | Python None comparison: should I use "is" or ==? | <p>My editor warns me when I compare <code>my_var == None</code>, but no warning when I use <code>my_var is None</code>. </p>
<p>I did a test in the Python shell and determined both are valid syntax, but my editor seems to be saying that <code>my_var is None</code> is preferred. </p>
<p>Is this the case, and if so, why?</p> | 14,247,383 | 7 | 3 | null | 2013-01-09 22:06:58.557 UTC | 47 | 2022-09-05 13:01:36.657 UTC | 2020-04-25 18:10:28.75 UTC | null | 2,988,730 | null | 943,184 | null | 1 | 275 | python|comparison|nonetype | 177,555 | <h3>Summary:</h3>
<p>Use <code>is</code> when you want to check against an object's <em>identity</em> (e.g. checking to see if <code>var</code> is <code>None</code>). Use <code>==</code> when you want to check <em>equality</em> (e.g. Is <code>var</code> equal to <code>3</code>?).</p>
<h3>Explanation:</h3>
<p>You can have custom classes where <code>my_var == None</code> will return <code>True</code></p>
<p>e.g:</p>
<pre><code>class Negator(object):
def __eq__(self,other):
return not other
thing = Negator()
print thing == None #True
print thing is None #False
</code></pre>
<p><code>is</code> checks for object <em>identity</em>. There is only 1 object <code>None</code>, so when you do <code>my_var is None</code>, you're checking whether they actually are the same object (not just <em>equivalent</em> objects) </p>
<p>In other words, <code>==</code> is a check for equivalence (which is defined from object to object) whereas <code>is</code> checks for object identity:</p>
<pre><code>lst = [1,2,3]
lst == lst[:] # This is True since the lists are "equivalent"
lst is lst[:] # This is False since they're actually different objects
</code></pre> |
29,245,411 | Android Studio threaded debugging | <p>I've been having trouble debugging a multithreaded app with Android Studio 1.1. It seems as if when a breakpoint is hit all other threads also stop, not just the one with the breakpoint. I created a simple test app with the following method in the Activity's onCreate. </p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread a = new Thread("thread-a") {
@Override
public void run() {
Log.v("thread", "thread-a");
}
};
Thread b = new Thread("thread-b") {
@Override
public void run() {
Log.v("thread", "thread-b");
}
};
a.start();
b.start();
}
</code></pre>
<p>I set breakpoints at the Log.v lines in thread-a and thread-b and then I run it in debug mode on my Lollipop Nexus 5.</p>
<p>When the app starts it hits the breakpoint in thread-a but the first problem I notice is that the app's UI is blank as if the main thread is paused. Next I went to see that the breakpoint in thread-b is also hit so I pull up the Threads view in Android Studio's debugger but when I go to expand the thread-b arrow there's nothing there. When I expand the main thread it shows it is paused somewhere in onStart().</p>
<p><img src="https://i.stack.imgur.com/79t8m.png" alt="Android Studio screenshot"></p>
<p>Am I doing something wrong or is this debugger incapable of debugging multiple threads at once?</p> | 29,389,601 | 2 | 2 | null | 2015-03-25 00:23:42.68 UTC | 10 | 2015-09-23 23:44:21.8 UTC | 2015-09-23 23:44:21.8 UTC | null | 3,063,884 | null | 11,015 | null | 1 | 53 | java|multithreading|debugging|android-studio|breakpoints | 42,671 | <p>In IntelliJ IDEA (and Android Studio is based on IntelliJ), when you place a breakpoint, if you do right click over it a dialog is displayed and you can select whether to pause all threads (the default) or only that thread.</p>
<p>You are pausing all the threads as it is the default setting.</p> |
29,196,447 | How do I compress HTML in laravel 5 | <p>In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5.</p>
<pre><code>App::after(function($request, $response)
{
if($response instanceof Illuminate\Http\Response)
{
$buffer = $response->getContent();
if(strpos($buffer,'<pre>') !== false)
{
$replace = array(
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\r/" => '',
"/>\n</" => '><',
"/>\s+\n</" => '><',
"/>\n\s+</" => '><',
);
}
else
{
$replace = array(
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\n([\S])/" => '$1',
"/\r/" => '',
"/\n/" => '',
"/\t/" => '',
"/ +/" => ' ',
);
}
$buffer = preg_replace(array_keys($replace), array_values($replace), $buffer);
$response->setContent($buffer);
}
});
</code></pre>
<p>Please how do i make this work in Laravel 5. </p>
<p>OR</p>
<p>Please provide a better way of compressing HTML in laravel 5 if any.
Thanks in advance. </p>
<p>NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.</p> | 29,203,480 | 10 | 3 | null | 2015-03-22 15:52:14.88 UTC | 16 | 2021-03-17 09:22:40.82 UTC | null | null | null | null | 2,772,319 | null | 1 | 27 | php|laravel|laravel-5|laravel-blade|html-compression | 28,489 | <p>The recommended way to do this in Larvel 5 is to rewrite your function as <a href="http://laravel.com/docs/5.0/middleware" rel="noreferrer">middleware</a>. As stated in the docs:</p>
<p>..this middleware would perform its task <strong>after</strong> the request is handled by the application:</p>
<pre><code><?php namespace App\Http\Middleware;
class AfterMiddleware implements Middleware {
public function handle($request, Closure $next)
{
$response = $next($request);
// Perform action
return $response;
}
}
</code></pre> |
43,368,604 | Constant struct in Go | <p>Why can't I create constant struct?</p>
<pre><code>const FEED_TO_INSERT = quzx.RssFeed{ 0,
"",
"desc",
"www.some-site.com",
"upd_url",
"img_title",
"img_url",
0,
0,
0,
0,
0,
100,
"alt_name",
1,
1,
1,
"test",
100,
100,
0 }
</code></pre>
<blockquote>
<p>.\rss_test.go:32: const initializer quzx.RssFeed literal is not a constant</p>
</blockquote> | 43,368,686 | 3 | 2 | null | 2017-04-12 11:44:22.527 UTC | 7 | 2019-07-24 03:32:48.453 UTC | 2017-04-12 11:47:37.79 UTC | null | 45,375 | null | 205,270 | null | 1 | 62 | go | 71,843 | <p>Because Go does not support struct constants (emphasis mine)</p>
<blockquote>
<p><strong>There are boolean constants, rune constants, integer constants,
floating-point constants, complex constants, and string constants.</strong>
Rune, integer, floating-point, and complex constants are collectively
called numeric constants.</p>
</blockquote>
<p>Read more here: <a href="https://golang.org/ref/spec#Constants" rel="noreferrer">https://golang.org/ref/spec#Constants</a></p> |
9,390,679 | LEFT JOIN after GROUP BY? | <p>I have a table of "Songs", "Songs_Tags" (relating songs with tags) and "Songs_Votes" (relating songs with boolean like/dislike).</p>
<p>I need to retrieve the songs with a GROUP_CONCAT() of its tags and also the number of likes (true) and dislikes (false).</p>
<p>My query is something like that:</p>
<pre><code>SELECT
s.*,
GROUP_CONCAT(st.id_tag) AS tags_ids,
COUNT(CASE WHEN v.vote=1 THEN 1 ELSE NULL END) as votesUp,
COUNT(CASE WHEN v.vote=0 THEN 1 ELSE NULL END) as votesDown,
FROM Songs s
LEFT JOIN Songs_Tags st ON (s.id = st.id_song)
LEFT JOIN Votes v ON (s.id=v.id_song)
GROUP BY s.id
ORDER BY id DESC
</code></pre>
<p>The problem is that when a Song has more than 1 tag, it gets returned more then once, so when I do the COUNT(), it returns more results.</p>
<p>The best solution I could think is if it would be possible to do the last LEFT JOIN after the GROUP BY (so now there would be only one entry for each song). Then I'd need another GROUP BY m.id.</p>
<p>Is there a way to accomplish that? Do I need to use a subquery?</p> | 9,392,472 | 3 | 1 | null | 2012-02-22 07:26:00.857 UTC | 4 | 2017-04-14 02:11:05.733 UTC | 2017-04-14 02:11:05.733 UTC | null | 1,905,949 | null | 834,604 | null | 1 | 15 | mysql|join|group-by|group-concat | 40,990 | <p>There've been some good answers so far, but I would adopt a slightly different method quite similar to what you described originally</p>
<pre><code>SELECT
songsWithTags.*,
COALESCE(SUM(v.vote),0) AS votesUp,
COALESCE(SUM(1-v.vote),0) AS votesDown
FROM (
SELECT
s.*,
COLLATE(GROUP_CONCAT(st.id_tag),'') AS tags_ids
FROM Songs s
LEFT JOIN Songs_Tags st
ON st.id_song = s.id
GROUP BY s.id
) AS songsWithTags
LEFT JOIN Votes v
ON songsWithTags.id = v.id_song
GROUP BY songsWithTags.id DESC
</code></pre>
<p>In this the subquery is responsible for collating songs with tags into a 1 row per song basis. This is then joined onto Votes afterwards. I also opted to simply sum up the v.votes column as you have indicated it is 1 or 0 and therefore a SUM(v.votes) will add up 1+1+1+0+0 = 3 out of 5 are upvotes, while SUM(1-v.vote) will sum 0+0+0+1+1 = 2 out of 5 are downvotes. </p>
<p>If you had an index on votes with the columns (id_song,vote) then that index would be used for this so it wouldn't even hit the table. Likewise if you had an index on Songs_Tags with (id_song,id_tag) then that table wouldn't be hit by the query. </p>
<p><strong>edit</strong> added solution using count </p>
<pre><code>SELECT
songsWithTags.*,
COUNT(CASE WHEN v.vote=1 THEN 1 END) as votesUp,
COUNT(CASE WHEN v.vote=0 THEN 1 END) as votesDown
FROM (
SELECT
s.*,
COLLATE(GROUP_CONCAT(st.id_tag),'') AS tags_ids
FROM Songs s
LEFT JOIN Songs_Tags st
ON st.id_song = s.id
GROUP BY s.id
) AS songsWithTags
LEFT JOIN Votes v
ON songsWithTags.id = v.id_song
GROUP BY songsWithTags.id DESC
</code></pre> |
9,227,268 | How can val() return Number? | <p>In the <code>val</code><a href="http://api.jquery.com/val/" rel="noreferrer">docs</a> written this description:</p>
<blockquote>
<p>.val() Returns: String, Number, Array</p>
</blockquote>
<p>I tried to get a <code>Number</code>, but it seems to return <code>string</code> only, Is there something that I'm doing wrong?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('#gdoron').val('1');
alert($('#gdoron').val() === '1'); // true
alert(typeof $('#gdoron').val()); // string.
$('#gdoron').val(1);
alert($('#gdoron').val() === 1); // false
alert(typeof $('#gdoron').val()); // string (not "number"!)</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="gdoron" /></code></pre>
</div>
</div>
</p>
<p>My question is: <strong>how can <code>val()</code> return number as the docs says?</strong> The question is not about how can I parse the string.</p>
<p></p> | 9,227,362 | 5 | 1 | null | 2012-02-10 11:45:04.41 UTC | 6 | 2019-12-16 11:56:41.443 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 601,179 | null | 1 | 64 | javascript|jquery|string|numbers | 84,422 | <p>Some HTML5 elements e.g. progress;</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(typeof $("#prog").val()); // number </code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<progress value="50" max="100" id="prog"></progress></code></pre>
</div>
</div>
</p> |
34,179,179 | What is use of android:supportsRtl="true" in AndroidManifest xml file | <p>Whenever I created new project in android studio, I got <code>android:supportsRtl="true"</code> in my app AndroidManifest File.</p>
<pre><code><application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
...
</application>
</code></pre>
<p>What is use in app, or what is advantages & disadvantage when I add or not add in my app AndroidManifest .</p> | 34,179,360 | 4 | 3 | null | 2015-12-09 12:45:36.77 UTC | 9 | 2021-05-31 15:07:54.773 UTC | null | null | null | null | 2,949,612 | null | 1 | 101 | android|android-studio|android-manifest|android-applicationinfo | 95,290 | <blockquote>
<p>Declares whether your application is willing to support right-to-left
(RTL) layouts. If set to true and targetSdkVersion is set to 17 or
higher, various RTL APIs will be activated and used by the system so
your app can display RTL layouts. If set to false or if
targetSdkVersion is set to 16 or lower, the RTL APIs will be ignored
or will have no effect and your app will behave the same regardless of
the layout direction associated to the user's Locale choice (your
layouts will always be left-to-right).</p>
<p>The default value of this attribute is false.</p>
<p>This attribute was added in API level 17.</p>
</blockquote>
<p>(Source: <a href="http://developer.android.com/guide/topics/manifest/application-element.html" rel="noreferrer">http://developer.android.com/guide/topics/manifest/application-element.html</a>)</p> |
24,714,665 | Why is rune in golang an alias for int32 and not uint32? | <p>The type <code>rune</code> in Go is <a href="http://golang.org/pkg/builtin/#rune" rel="noreferrer">defined</a> as </p>
<blockquote>
<p>an alias for <code>int32</code> and is equivalent to <code>int32</code> in all ways. It is
used, by convention, to distinguish character values from integer
values.</p>
</blockquote>
<p>If the intention is to use this type to represent character values, why did the authors of the Go language do not use <code>uint32</code> instead of <code>int32</code>? How do they expect a <code>rune</code> value to be handled in a program, when it is negative? The other similar type, <code>byte</code>, is an alias for <code>uint8</code> (and not <code>int8</code>), which seems reasonable.</p> | 24,714,789 | 5 | 2 | null | 2014-07-12 15:55:52.853 UTC | 13 | 2021-03-31 14:09:06.923 UTC | 2018-11-15 07:28:49.627 UTC | null | 9,818,506 | user1820956 | null | null | 1 | 47 | go | 9,367 | <p>I googled and found <a href="https://groups.google.com/forum/#!topic/golang-nuts/d3_GPK8bwBg" rel="noreferrer">this</a> </p>
<blockquote>
<p>This has been asked several times. rune occupies 4 bytes and not just one because it is supposed to store unicode codepoints and not just ASCII characters. Like array indices, the datatype is signed so that you can easily detect overflows or other errors while doing arithmetic with those types.</p>
</blockquote> |
283,128 | How do I send ctrl+c to a process in c#? | <p>I'm writing a wrapper class for a command line executable. This exe accepts input from <code>stdin</code> until I hit <code>Ctrl+C</code> in the command prompt shell, in which case it prints output to <code>stdout</code> based on the input. I want to simulate that <code>Ctrl+C</code> press in C# code, sending the kill command to a .NET <code>Process</code> object. I've tried calling <code>Process.Kill()</code>, but that doesn't seem to give me anything in the process's <code>StandardOutput</code> <code>StreamReader</code>. Might there be anything I'm not doing right? Here's the code I'm trying to use:</p>
<pre><code>ProcessStartInfo info = new ProcessStartInfo(exe, args);
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process p = Process.Start(info);
p.StandardInput.AutoFlush = true;
p.StandardInput.WriteLine(scriptcode);
p.Kill();
string error = p.StandardError.ReadToEnd();
if (!String.IsNullOrEmpty(error))
{
throw new Exception(error);
}
string output = p.StandardOutput.ReadToEnd();
</code></pre>
<p>The output is always empty, even though I get data back from <code>stdout</code> when I run the exe manually.</p>
<p><strong>Edit</strong>: This is C# 2.0 by the way.</p> | 285,041 | 6 | 1 | null | 2008-11-12 05:38:15.467 UTC | 13 | 2022-05-01 16:26:33.867 UTC | 2019-11-19 18:40:04.623 UTC | Kevlar | 4,404,544 | Kevlar | 19,252 | null | 1 | 48 | c#|command-line|.net-2.0|process | 77,425 | <p>I've actually just figured out the answer. Thank you both for your answers, but it turns out that all i had to do was this:</p>
<pre><code>p.StandardInput.Close()
</code></pre>
<p>which causes the program I've spawned to finish reading from stdin and output what i need.</p> |
795,160 | Java is NEVER pass-by-reference, right?...right? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/40480/is-java-pass-by-reference">Is Java “pass-by-reference”?</a> </p>
</blockquote>
<p>I found an unusual Java method today:</p>
<pre><code>private void addShortenedName(ArrayList<String> voiceSetList, String vsName)
{
if (null == vsName)
vsName = "";
else
vsName = vsName.trim();
String shortenedVoiceSetName = vsName.substring(0, Math.min(8, vsName.length()));
//SCR10638 - Prevent export of empty rows.
if (shortenedVoiceSetName.length() > 0)
{
if (!voiceSetList.contains("#" + shortenedVoiceSetName))
voiceSetList.add("#" + shortenedVoiceSetName);
}
}
</code></pre>
<p>According to everything I've read about Java's behavior for passing variables, complex objects or not, this code should do exactly nothing. So um...am I missing something here? Is there some subtlety that was lost on me, or does this code belong on thedailywtf?</p> | 795,186 | 6 | 10 | null | 2009-04-27 20:29:41.407 UTC | 12 | 2018-04-11 10:42:55.693 UTC | 2017-05-23 12:34:34.957 UTC | null | -1 | null | 88,218 | null | 1 | 54 | java|pass-by-reference|pass-by-value | 23,630 | <p>As Rytmis said, Java passes references by value. What this means is that you can legitimately call mutating methods on the parameters of a method, but you cannot reassign them and expect the value to propagate.</p>
<p>Example:</p>
<pre><code>private void goodChangeDog(Dog dog) {
dog.setColor(Color.BLACK); // works as expected!
}
private void badChangeDog(Dog dog) {
dog = new StBernard(); // compiles, but has no effect outside the method
}
</code></pre>
<p><strong>Edit:</strong> What this means in this case is that although <code>voiceSetList</code> <em>might</em> change as a result of this method (it could have a new element added to it), the changes to <code>vsName</code> will not be visible outside of the method. To prevent confusion, I often mark my method parameters <code>final</code>, which keeps them from being reassigned (accidentally or not) inside the method. This would keep the second example from compiling at all.</p> |
386,731 | Get Absolute Position of element within the window in wpf | <p>I would like to get the absolute position of an element in relation to the window/root element when it is double clicked. The element's relative position within it's parent is all I can seem to get to, and what I'm trying to get to is the point relative to the window. I've seen solutions of how to get a the point of an element on the screen, but not in the window.</p> | 387,681 | 6 | 0 | null | 2008-12-22 16:57:10.78 UTC | 13 | 2021-09-16 20:05:59.133 UTC | 2013-10-16 17:31:12 UTC | null | 246,246 | BrandonS | 42,858 | null | 1 | 98 | wpf|wpf-positioning | 132,905 | <p>I think what BrandonS wants is not the position of the <em>mouse</em> relative to the root element, but rather the position of some descendant element.</p>
<p>For that, there is the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.visual.transformtoancestor.aspx" rel="noreferrer">TransformToAncestor</a> method:</p>
<pre><code>Point relativePoint = myVisual.TransformToAncestor(rootVisual)
.Transform(new Point(0, 0));
</code></pre>
<p>Where <code>myVisual</code> is the element that was just double-clicked, and <code>rootVisual</code> is Application.Current.MainWindow or whatever you want the position relative to.</p> |
37,618,738 | How to check if a "lateinit" variable has been initialized? | <p>I wonder if there is a way to check if a <code>lateinit</code> variable has been initialized. For example:</p>
<pre><code>class Foo() {
private lateinit var myFile: File
fun bar(path: String?) {
path?.let { myFile = File(it) }
}
fun bar2() {
myFile.whateverMethod()
// May crash since I don't know whether myFile has been initialized
}
}
</code></pre> | 46,584,412 | 9 | 4 | null | 2016-06-03 15:53:56.913 UTC | 68 | 2021-11-16 08:05:16.69 UTC | 2019-11-27 12:03:33.77 UTC | null | 4,235,946 | null | 4,613,968 | null | 1 | 759 | kotlin | 283,038 | <p>There is a <code>lateinit</code> improvement in Kotlin 1.2 that allows to check the initialization state of <code>lateinit</code> variable directly:</p>
<pre><code>lateinit var file: File
if (this::file.isInitialized) { ... }
</code></pre>
<p>See the annoucement on <a href="https://blog.jetbrains.com/kotlin/2017/09/kotlin-1-2-beta-is-out/" rel="noreferrer">JetBrains blog</a> or the <a href="https://github.com/Kotlin/KEEP/pull/73" rel="noreferrer">KEEP proposal</a>.</p>
<p><strong>UPDATE:</strong> Kotlin 1.2 has been released. You can find <code>lateinit</code> enhancements here:</p>
<ul>
<li><a href="http://kotlinlang.org/docs/reference/whatsnew12.html#checking-whether-a-lateinit-var-is-initialized" rel="noreferrer">Checking whether a lateinit var is initialized</a></li>
<li><a href="http://kotlinlang.org/docs/reference/whatsnew12.html#lateinit-top-level-properties-and-local-variables" rel="noreferrer">Lateinit top-level properties and local variables</a></li>
</ul> |
35,738,346 | How do I fix the npm UNMET PEER DEPENDENCY warning? | <p>I'm on Windows 10, with Node 5.6.0 and npm 3.6.0. I'm trying to install angular-material and mdi into my working folder. <strong>npm install angular-material mdi</strong> errors with:</p>
<pre><code>+-- [email protected]
+-- UNMET PEER DEPENDENCY angular-animate@^1.5.0
+-- UNMET PEER DEPENDENCY angular-aria@^1.5.0
+-- [email protected]
+-- UNMET PEER DEPENDENCY angular-messages@^1.5.0 `-- [email protected]
npm WARN enoent ENOENT: no such file or directory, open
'C:\Users\xxxxx\Desktop\ngClassifieds\package.json'
npm WARN [email protected] requires a peer of
angular-animate@^1.5.0 but none was installed.
npm WARN [email protected] requires a peer of angular-aria@^1.5.0
but none was installed.
npm WARN [email protected] requires a peer of
angular-messages@^1.5.0 but none was installed.
</code></pre>
<p>How do I resolve this to get AngularJS Material and MDI installed?</p> | 35,738,361 | 14 | 4 | null | 2016-03-02 04:09:42.71 UTC | 52 | 2022-08-01 15:41:16.487 UTC | 2019-01-08 04:55:19.16 UTC | null | 1,038,379 | null | 4,686,716 | null | 1 | 291 | angularjs|node.js|npm|npm-install|angularjs-material | 372,757 | <p>npm no longer installs peer dependencies so you need to install them manually, just do an <code>npm install</code> on the needed deps, and then try to install the main one again.</p>
<hr>
<p>Reply to comment: </p>
<p>it's right in that message, it says which deps you're missing</p>
<pre><code>UNMET PEER DEPENDENCY angular-animate@^1.5.0 +--
UNMET PEER DEPENDENCY angular-aria@^1.5.0 +-- [email protected] +
UNMET PEER DEPENDENCY angular-messages@^1.5.0 `-- [email protected]`
</code></pre>
<p>So you need to <code>npm install angular angular-animate angular-aria angular-material angular-messages mdi</code></p> |
21,164,976 | CSS white-space nowrap not working | <p>I have a div with several child divs which are floating left. I don't want them to break, so I set them to <code>display:inline-block</code> and <code>white-space:nowrap</code>. Unfortunately nothing happens at all. They just keep breaking.</p>
<p>At the end I want to scroll in x-direction, but when I add <code>overflow-x:scroll; overflow-y:visible</code> it scrolls in y-direction.</p>
<pre><code>.a {
width: 400px;
height: 300px;
white-space: nowrap;
display: inline-block;
}
.b {
float: left;
width: 50px;
height: 200px;
display: inline-block;
}
<div class="a">
<div class="b"></div>
<div class="b"></div>
<div class="b"></div>
<div class="clearfix"></div>
</div>
</code></pre>
<p>You can see <a href="http://jsfiddle.net/julian_weinert/88yjz/">my complete implementation on JSFiddle</a></p> | 21,165,352 | 3 | 4 | null | 2014-01-16 14:46:48.27 UTC | 1 | 2021-04-14 18:14:05.517 UTC | null | null | null | null | 1,041,122 | null | 1 | 9 | html|css|overflow|whitespace | 41,870 | <p>I may not fully understand your question but it seems like the divs/scroll behave if you remove: <code>float: left;</code> from <code>.b</code> and add: <code>overflow:auto;</code> to <code>.a</code></p> |
21,052,753 | Error creating bean with name "datasource" defined in servlet context resource [WEB-INF/applicationContext.xml] | <p>I am doing an example how to integrate struts2 and spring. I used spring jdbc template.
I am getting an exception when creating the dataSource bean. Could someone help on this. </p>
<p>Eclipse console</p>
<pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not load JDBC driver class [com.mysql.jdbc.driver]; nested exception is java.lang.ClassNotFoundException: com.mysql.jdbc.driver
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1279)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not load JDBC driver class [com.mysql.jdbc.driver]; nested exception is java.lang.ClassNotFoundException: com.mysql.jdbc.driver
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:104)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:59)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1276)
... 31 more
Jan 10, 2014 11:47:15 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not load JDBC driver class [com.mysql.jdbc.driver]; nested exception is java.lang.ClassNotFoundException: com.mysql.jdbc.driver
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1279)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not load JDBC driver class [com.mysql.jdbc.driver]; nested exception is java.lang.ClassNotFoundException: com.mysql.jdbc.driver
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:104)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:59)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1276)
... 31 more
Jan 10, 2014 11:47:15 PM org.apache.catalina.core.StandardContext start
</code></pre>
<p>applicatinContext.xml</p>
<pre><code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="studentDAOImpl" class="com.tech.daoImpl.StudentDAOImpl" />
<bean id="studentAction" class="com.tech.action.StudentAction">
<property name="studentDAO" ref="studentDAOImpl" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.driver" />
<property name="url" value="jdbc:mysql://localhost:3306/CD-UKUMARA" />
<property name="username" value="root" />
<property name="password" value="root123" />
</bean>
<bean id="studentDAO" class="com.tech.dao.StudentDAO">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
</code></pre>
<p>web.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>TechCollection</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<!-- <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> -->
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<!-- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> -->
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
</code></pre>
<p>Thank you.</p> | 21,053,002 | 1 | 5 | null | 2014-01-10 19:25:39.41 UTC | null | 2014-01-10 19:39:55.29 UTC | null | null | null | null | 2,525,560 | null | 1 | 2 | java|xml|eclipse|spring | 38,767 | <p>It's <code>com.mysql.jdbc.Driver</code> - check the capitalization.</p> |
17,045,493 | Default int main arguments in C/C++ | <p>I was messing around with projects in C/C++ and I noticed this:</p>
<p><strong>C++</strong></p>
<pre><code>#include <iostream.h>
int main (int argc, const char * argv[]) {
// insert code here...
cout << "Hello, World!\n";
return 0;
}
</code></pre>
<p>and</p>
<p><strong>C</strong></p>
<pre><code>#include <stdio.h>
int main (int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
return 0;
}
</code></pre>
<p>So I've always sort of wondered about this, what exactly do those default arguments do in C/C++ under int main? I know that the application will still compile without them, but what purpose do they serve? </p> | 17,045,580 | 4 | 9 | null | 2013-06-11 13:35:33.973 UTC | 5 | 2018-05-17 12:59:30.967 UTC | null | null | null | null | 2,346,085 | null | 1 | 2 | c++|c | 41,769 | <p>They hold the arguments passed to the program on the command line. For example, if I have program <code>a.out</code> and I invoke it thusly:</p>
<pre><code>$ ./a.out arg1 arg2
</code></pre>
<p>The contents of <code>argv</code> will be an array of strings containing</p>
<ol>
<li>[0] <code>"a.out"</code> - The executable's file name is always the first element</li>
<li>[1] <code>"arg1"</code> - The other arguments</li>
<li>[2] <code>"arg2"</code> - that I passed</li>
</ol>
<p><code>argc</code> holds the number of elements in <code>argv</code> (as in C you need another variable to know how many elements there are in an array, when passed to a function).</p>
<p>You can try it yourself with this simple program:</p>
<hr>
<p><strong>C++</strong></p>
<pre><code>#include <iostream>
int main(int argc, char * argv[]){
int i;
for(i = 0; i < argc; i++){
std::cout << "Argument "<< i << " = " << argv[i] << std::endl;
}
return 0;
}
</code></pre>
<hr>
<p><strong>C</strong></p>
<pre><code>#include <stdio.h>
int main(int argc, char ** argv){
int i;
for(i = 0; i < argc; i++){
printf("Argument %i = %s\n", i, argv[i]);
}
return 0;
}
</code></pre> |
1,628,628 | Can you use REST in PHP? If so how? | <p>I am developing my own PHP Library and I would like to call RESTful web-services from my API. Can this be done in PHP and if so what are the basics in doing so?</p> | 1,628,680 | 5 | 3 | null | 2009-10-27 03:32:55.253 UTC | 11 | 2017-01-09 05:15:57.433 UTC | 2017-01-09 05:15:57.433 UTC | null | 3,299,397 | null | 152,308 | null | 1 | 45 | php|rest|restful-architecture | 48,002 | <p>Since REST is the application of the same methods of the HTTP protocol to the design of client-server architectures and PHP is already so good to handle HTTP protocol requests such as GET and POST. PHP is specially suited to make developing REST services easy.</p>
<p>Remember REST is the application of the same http patterns that already exists.</p>
<p>So if you currently have an application that does something like:</p>
<ol>
<li>HTML Form</li>
<li>PHP Process</li>
<li>HTML Output in a table</li>
</ol>
<p>So to make it REST you would need to:</p>
<ol>
<li><p>Accept parameters from the web. This is easy since you will receive the parameters either as get or post... so it is basically the same.</p>
</li>
<li><p>PHP process</p>
</li>
<li><p>Output in either <strong>JSON</strong> or <strong>XML</strong>. And that is it!</p>
<p>Is pretty easy.</p>
</li>
</ol>
<p>Now the difficult part is to make your API (the functions and URLs) that you will generate to be programmer friendly.</p>
<p>In that case I suggest you look at the <a href="http://www.flickr.com/services/api/" rel="noreferrer">flickr API</a> as an example is very developer friendly easy to guess and has good documentation.</p>
<p>For more info on APIs look at this presentation: <a href="http://www.infoq.com/presentations/effective-api-design" rel="noreferrer">How to Design a Good API & Why it Matters (Joshua Bloch)</a></p>
<p>Finally a RESTful API should implement also the PUT and DELETE methods of the http protocol <em>when it makes sense</em></p>
<p>For example if you had a delete action in your api, said service should receive the delete method from the http protocol. Instead of the more common thing of sending an action parameter as part of a post request.</p>
<p><strong>Edit:</strong> Replaced "Php is rest by default" with "Since REST is the application of the same methods of the HTTP protocol to the design of client-server architectures and PHP is already so good to handle HTTP protocol requests such as GET and POST. PHP is specially suited to make developing REST services easy."</p>
<p>And also added the final note that you should implement the appropiate PUT or DELETE methods when that action makes sense for your api.</p> |
1,946,296 | Use of extern in Objective C | <p>How good is it to use extern in Objective C?
It does make coding for some parts easy.. but doesn't it spoil the object orientation?</p> | 1,946,571 | 5 | 0 | null | 2009-12-22 13:10:30.78 UTC | 26 | 2019-05-13 09:35:03.54 UTC | 2009-12-22 13:15:32.36 UTC | anon | null | null | 229,667 | null | 1 | 52 | objective-c | 48,646 | <p>You'll find that <code>extern</code> is used extensively in the Cocoa frameworks, and one would be hard-pressed to find a convincing argument that their OO is "spoiled". On the contrary, Cocoa is well-encapsulated and only exposes what it must, often via extern. Globally-defined constants are certainly the most common usage, but not necessarily the only valid use.</p>
<p>IMO, using <code>extern</code> doesn't necessarily "spoil" object orientation. Even in OO, it is frequent to use variables that are accessible from anywhere. Using <code>extern</code> is the most frequent workaround for the lack of "class variables" (like those declared with <code>static</code> in Java) in Objective-C. It allows you to expand the scope in which you can reference a symbol beyond the compilation unit where it is declared, essentially by promising that it will be defined somewhere by someone.</p>
<p>You can also combine <code>extern</code> with <code>__attribute__((visibility("hidden")))</code> to create a symbol that can be used outside its compilation unit, but not outside its linkage unit, so to speak. I've used this for custom library and framework code to properly encapsulate higher-level internal details.</p> |
1,603,340 | Track the number of "page views" or "hits" of an object? | <p>I am sure that someone has a pluggable app (or tutorial) out there that approximates this, but I have having trouble finding it: I want to be able to track the number of "views" a particular object has (just like a question here on stackoverflow has a "view count").</p>
<p>If the user isn't logged in, I wouldn't mind attempting to place a cookie (or log an IP) so they can't inadvertently run up the view count by refreshing the page; and if a user is logged in, only allow them one "view" across sessions/browsers/IP addresses. I don't think I need it any fancier than that.</p>
<p>I figure the best way to do this is with Middleware that is decoupled from the various models I want to track and using an F expression (of sorts) -- other questions on StackOverflow have alluded to this (<a href="https://stackoverflow.com/questions/622652/incremement-page-hit-count-in-django">1</a>), (<a href="https://stackoverflow.com/questions/888905/django-counting-model-instance-views-for-a-top-entries-app/891100#891100">2</a>), (<a href="https://stackoverflow.com/questions/1212559/spam-proof-hit-counter-in-django">3</a>).</p>
<p>But I wonder if this code exists out in the wild already -- because I am not the savviest coder and I'm sure someone could do it better. Smile.</p>
<p>Have you seen it?</p> | 1,622,715 | 6 | 0 | null | 2009-10-21 20:18:05.263 UTC | 30 | 2020-08-21 19:13:35.29 UTC | 2020-08-21 19:13:35.29 UTC | null | 11,335,073 | null | 181,902 | null | 1 | 50 | django|view | 37,722 | <p>I am not sure if it's in the best taste to answer my own question but, after a bit of work, I put together an app that solves the problems in earnest: <a href="http://github.com/thornomad/django-hitcount" rel="noreferrer">django-hitcount</a>.</p>
<p>You can read about how to use it at <a href="http://django-hitcount.readthedocs.io/en/latest/" rel="noreferrer">the documentation page</a>.</p>
<p>The ideas for django-hitcount came came from both of my two original answers (<a href="https://stackoverflow.com/questions/1603340/track-the-number-of-page-views-or-hits-of-an-object/1603719#1603719">Teebes</a> -and- <a href="https://stackoverflow.com/questions/1603340/track-the-number-of-page-views-or-hits-of-an-object/1603632#1603632">vikingosegundo</a>), which really got me started thinking about the whole thing.</p>
<p>This is my first attempt at sharing a pluggable app with the community and hope someone else finds it useful. Thanks!</p> |
2,198,470 | Javascript: Uploading a file... without a file | <p>I am trying to fake a file upload without actually using a file input from the user. The file's content will be dynamically generated from a string.</p>
<p>Is this possible? Have anyone ever done this before? Are there examples/theory available?</p>
<p>To clarify, I know how to upload a file using AJAX techniques using a hidden iframe and friends - the problem is uploading a file that is not in the form.</p>
<p>I am using ExtJS, but jQuery is feasible as well since ExtJS can plug into it (ext-jquery-base).</p> | 2,198,524 | 7 | 2 | null | 2010-02-04 09:18:41.083 UTC | 19 | 2022-06-20 12:45:23.75 UTC | 2010-02-04 09:25:30.647 UTC | null | 41,983 | null | 41,983 | null | 1 | 60 | javascript|file-upload|extjs | 53,478 | <p>Why not just use <code>XMLHttpRequest()</code> with POST?</p>
<pre><code>function beginQuoteFileUnquoteUpload(data)
{
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.mysite.com/myuploadhandler.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200)
alert("File uploaded!");
}
xhr.send("filedata="+encodeURIComponent(data));
}
</code></pre>
<p>The handler script at the server just writes the file data to a file.</p>
<p><strong>EDIT</strong><br>
File upload is still a http post with a different content type. You can use this content type and separate your content with boundaries:</p>
<pre><code>function beginQuoteFileUnquoteUpload(data)
{
// Define a boundary, I stole this from IE but you can use any string AFAIK
var boundary = "---------------------------7da24f2e50046";
var xhr = new XMLHttpRequest();
var body = '--' + boundary + '\r\n'
// Parameter name is "file" and local filename is "temp.txt"
+ 'Content-Disposition: form-data; name="file";'
+ 'filename="temp.txt"\r\n'
// Add the file's mime-type
+ 'Content-type: plain/text\r\n\r\n'
+ data + '\r\n'
+ boundary + '--';
xhr.open("POST", "http://www.mysite.com/myuploadhandler.php", true);
xhr.setRequestHeader(
"Content-type", "multipart/form-data; boundary="+boundary
);
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200)
alert("File uploaded!");
}
xhr.send(body);
}
</code></pre>
<p>If you want to send additional data, you just separate each section with a boundary and describe the content-disposition and content-type headers for each section. Each header is separated by a newline and the body is separated from the headers by an additional newline. Naturally, uploading binary data in this fashion would be slightly more difficult :-)</p>
<p>Further edit: forgot to mention, make sure whatever boundary string isn't in the text "file" that you're sending, otherwise it will be treated as a boundary.</p> |
2,325,923 | How to fix "ImportError: No module named ..." error in Python? | <p>What is the correct way to fix this ImportError error?</p>
<p>I have the following directory structure:</p>
<pre><code>/home/bodacydo
/home/bodacydo/work
/home/bodacydo/work/project
/home/bodacydo/work/project/programs
/home/bodacydo/work/project/foo
</code></pre>
<p>And I am in the directory</p>
<pre><code>/home/bodacydo/work/project
</code></pre>
<p>Now if I type</p>
<pre><code>python ./programs/my_python_program.py
</code></pre>
<p>I instantly get</p>
<pre><code>ImportError: No module named foo.tasks
</code></pre>
<p>The <code>./programs/my_python_program.py</code> contains the following line:</p>
<pre><code>from foo.tasks import my_function
</code></pre>
<p>I can't understand why python won't find <code>./foo/tasks.py</code> - it's there.</p>
<p>If I do it from the Python shell, then it works:</p>
<pre><code>python
>>> from foo.tasks import my_function
</code></pre>
<p>It only doesn't work if I call it via <code>python ./programs/my_python_program.py</code> script.</p> | 2,326,045 | 7 | 0 | null | 2010-02-24 12:31:09.3 UTC | 27 | 2019-11-22 09:30:56.04 UTC | 2015-07-09 20:36:23.62 UTC | null | 1,886,357 | null | 257,942 | null | 1 | 136 | python | 572,490 | <p>Python does not add the current directory to <code>sys.path</code>, but rather the directory that the script is in. Add <code>/home/bodacydo/work/project</code> to either <code>sys.path</code> or <code>$PYTHONPATH</code>.</p> |
1,493,969 | Insert elements into a vector at given indexes | <p>I have a logical vector, for which I wish to insert new elements at particular indexes. I've come up with a clumsy solution below, but is there a neater way?</p>
<pre><code>probes <- rep(TRUE, 15)
ind <- c(5, 10)
probes.2 <- logical(length(probes)+length(ind))
probes.ind <- ind + 1:length(ind)
probes.original <- (1:length(probes.2))[-probes.ind]
probes.2[probes.ind] <- FALSE
probes.2[probes.original] <- probes
print(probes)
</code></pre>
<p>gives</p>
<pre><code>[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
</code></pre>
<p>and</p>
<pre><code>print(probes.2)
</code></pre>
<p>gives</p>
<pre><code>[1] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE
[13] TRUE TRUE TRUE TRUE TRUE
</code></pre>
<p>So it works but is ugly looking - any suggestions?</p> | 1,495,204 | 8 | 2 | null | 2009-09-29 17:35:31.17 UTC | 17 | 2022-09-08 17:17:40.787 UTC | 2022-09-08 17:17:40.787 UTC | null | 1,851,712 | null | 160,588 | null | 1 | 54 | r | 87,718 | <p>You can do some magic with indexes:</p>
<p>First create vector with output values:</p>
<pre><code>probs <- rep(TRUE, 15)
ind <- c(5, 10)
val <- c( probs, rep(FALSE,length(ind)) )
# > val
# [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
# [13] TRUE TRUE TRUE FALSE FALSE
</code></pre>
<p>Now trick. Each old element gets rank, each new element gets half-rank </p>
<pre><code>id <- c( seq_along(probs), ind+0.5 )
# > id
# [1] 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0
# [16] 5.5 10.5
</code></pre>
<p>Then use <code>order</code> to sort in proper order:</p>
<pre><code>val[order(id)]
# [1] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE
# [13] TRUE TRUE TRUE TRUE TRUE
</code></pre> |
1,398,919 | Make Git consume less disk space? | <p>What is the best way for git to consume less disk space?</p>
<p>I'm using <a href="https://git-scm.com/docs/git-gc" rel="noreferrer">git-gc</a> on my repositories (which does help, especially if there have been many commits since it was cloned) but I would like suggestions if there is any other command to shrink the disk space used by git.</p> | 1,398,968 | 11 | 6 | null | 2009-09-09 10:49:01.297 UTC | 10 | 2019-12-16 22:47:59.05 UTC | 2019-12-16 22:47:59.05 UTC | null | 1,430,996 | null | 74,650 | null | 1 | 48 | git | 34,604 | <p>git-gc calls lots of other commands that are used to clean up and compress the repository. All you could do is delete some old unused branches.</p>
<p>Short answer: No :-(</p> |
1,391,503 | Why did a network-related or instance-specific error occur while establishing a connection to SQL Server? | <p>I'm very frustrated. I have a website running on Visual Web Developer 2008 Express with my local database, everything works great. I also have the same web site running on a production server. Everything was working great but tonight I did a "reset" on production.</p>
<ol>
<li><p>I deleted a couple of table, re-created them and inserted data. Everything was ok at this time.</p>
</li>
<li><p>I deleted ALL the files via the FTP.</p>
</li>
<li><p>I used the module called "Copy website" in visual studio and copy the site to the website via FTP.</p>
</li>
</ol>
<p>When I log on my website, here is the error I got:</p>
<blockquote>
<p>Server Error in '/' Application.</p>
<p>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)</p>
<p>Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p>
<p>Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)</p>
</blockquote>
<hr />
<p>Nothing has changed related to SQL connection, this is OLD code that I always used.
My website is completely paralysed because of this and I feel sick inside because I feel there is nothing I can do.</p>
<p>Can anyone help me please?</p> | 1,393,125 | 15 | 6 | null | 2009-09-08 01:09:10.103 UTC | 21 | 2020-07-02 22:53:18.367 UTC | 2020-07-02 22:53:18.367 UTC | null | 3,082,718 | null | 130,993 | null | 1 | 67 | .net|sql-server|visual-studio | 487,090 | <p>Your connection string was probably overriden when you copied your new website version on the server. Please check the connection string in web.config and see if it is valid. </p> |
1,615,352 | Why doesn't Maven's mvn clean ever work the first time? | <p>Nine times out of ten when I run <strong>mvn clean</strong> on my projects I experience a build error. I have to execute <strong>mvn clean</strong> multiple times until the build error goes away. Does anyone else experience this? Is there any way to fix this within Maven? If not, how do you get around it? I wrote a bat file that deletes the target folders and that works well, but it's not practical when you are working on multiple projects. I am using Maven 2.2.1.</p>
<pre><code>[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Failed to delete directory: C:\Documents and Settings\user\My Documents\software-developm
ent\a\b\c\application-domain\target. Reason: Unable to delete directory C:\Documen
ts and Settings\user\My Documents\software-development\a\b\c\application-domai
n\target\classes\com\a\b
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6 seconds
[INFO] Finished at: Fri Oct 23 15:22:48 EDT 2009
[INFO] Final Memory: 11M/254M
[INFO] ------------------------------------------------------------------------
</code></pre> | 1,615,391 | 19 | 1 | null | 2009-10-23 19:09:05.59 UTC | 11 | 2019-04-26 19:43:38.17 UTC | 2009-10-23 19:24:55.153 UTC | null | 43,365 | null | 43,365 | null | 1 | 42 | maven-2 | 47,398 | <p>It may be that your IDE or some other process is holding on to the the "target" folder and preventing maven from deleting it.</p> |
2,286,648 | Named placeholders in string formatting | <p>In Python, when formatting string, I can fill placeholders by name rather than by position, like that:</p>
<pre><code>print "There's an incorrect value '%(value)s' in column # %(column)d" % \
{ 'value': x, 'column': y }
</code></pre>
<p>I wonder if that is possible in Java (hopefully, without external libraries)? </p> | 2,295,004 | 21 | 3 | null | 2010-02-18 06:06:09.517 UTC | 54 | 2022-01-14 10:29:23.937 UTC | 2017-11-27 22:33:40.973 UTC | null | 4,284,627 | null | 199,621 | null | 1 | 229 | java|string-formatting | 234,213 | <p>Thanks for all your help! Using all your clues, I've written routine to do exactly what I want -- python-like string formatting using dictionary. Since I'm Java newbie, any hints are appreciated.</p>
<pre><code>public static String dictFormat(String format, Hashtable<String, Object> values) {
StringBuilder convFormat = new StringBuilder(format);
Enumeration<String> keys = values.keys();
ArrayList valueList = new ArrayList();
int currentPos = 1;
while (keys.hasMoreElements()) {
String key = keys.nextElement(),
formatKey = "%(" + key + ")",
formatPos = "%" + Integer.toString(currentPos) + "$";
int index = -1;
while ((index = convFormat.indexOf(formatKey, index)) != -1) {
convFormat.replace(index, index + formatKey.length(), formatPos);
index += formatPos.length();
}
valueList.add(values.get(key));
++currentPos;
}
return String.format(convFormat.toString(), valueList.toArray());
}
</code></pre> |
18,069,716 | Why am I getting 'module' object is not callable in python 3? | <p>First, all relevant code</p>
<p><strong>main.py</strong> </p>
<pre><code>import string
import app
group1=[ "spc", "bspc",",","."]#letters, space, backspace(spans mult layers)
# add in letters one at a time
for s in string.ascii_lowercase:
group1.append(s)
group2=[0,1,2,3,4,5,6,7,8,9, "tab ","ent","lAR" ,"rAR" , "uAR", "dAR"]
group3= []
for s in string.punctuation:
group3.append(s)#punc(spans mult layers)
group4=["copy","cut","paste","save","print","cmdW","quit","alf","sWDW"] #kb shortcut
masterGroup=[group1,group2,group3,group4]
myApp =app({"testFKey":[3,2,2]})
</code></pre>
<p><strong>app.py</strong></p>
<pre><code>import tkinter as tk
import static_keys
import dynamic_keys
import key_labels
class app(tk.Frame):
def __init__(inputDict,self, master=None,):
tk.Frame.__init__(self, master)
self.grid(sticky=tk.N+tk.S+tk.E+tk.W)
self.createWidgets(self, inputDict)
def createWidgets(self,inDict):
top=self.winfo_toplevel()
top.rowconfigure(0, weight=1)
top.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
tempDict = {}
for k,v in inDict.items():
if 1<=v[0]<=3:
tempDict[k] = static_keys(*v[1:])
elif v[0] ==4:
tempDict[k] = dynamic_keys(k,*v[1:])
elif v[0]==5:
tempDict[k] = key_labels(*v[1:])
for o in tempDict:
tempDict[o].grid()
return tempDict
</code></pre>
<p><strong>static_keys.py</strong></p>
<pre><code>import tkinter
class static_keys(tkinter.Label):
"""class for all keys that just are initiated then do nothing
there are 3 options
1= modifier (shift etc)
2 = layer
3 = fkey, eject/esc"""
def __init__(t,selector,r,c,parent,self ):
if selector == 1:
tkinter.Label.__init__(master=parent, row=r, column=c, text= t, bg ='#676731')
if selector == 2:
tkinter.Label.__init__(master=parent, row=r, column=c, text= t, bg ='#1A6837')
if selector == 3:
tkinter.Label.__init__(master=parent, row=r, column=c, text= t, bg ='#6B6966')
</code></pre>
<p>Now for a description of the problem. When I run <code>main.py</code> in python3, I get the error</p>
<pre><code>File "Desktop/kblMaker/main.py", line 13, in <module>
myApp =app({"testFKey":[3,2,2]})
TypeError: 'module' object is not callable
</code></pre> | 18,069,772 | 4 | 3 | null | 2013-08-05 23:57:28.743 UTC | null | 2021-11-17 02:48:59.533 UTC | 2013-08-06 01:05:55.693 UTC | null | 2,102,455 | null | 2,102,455 | null | 1 | 12 | python|python-3.x|tkinter|runtime-error | 53,975 | <p>You have a module named <code>app</code> that contains a class named <code>app</code>. If you just do <code>import app</code> in main.py then <code>app</code> will refer to the module, and <code>app.app</code> will refer to the class. Here are a couple of options:</p>
<ul>
<li>Leave your import statement alone, and use <code>myApp = app.app({"testFKey":[3,2,2]})</code> inside of main.py</li>
<li>Replace <code>import app</code> with <code>from app import app</code>, now <code>app</code> will refer to the class and <code>myApp = app({"testFKey":[3,2,2]})</code> will work fine</li>
</ul> |
6,788,398 | How to save progressive jpeg using Python PIL 1.1.7? | <p>I'm trying to save with the following call and it raises error, but if i remove progressive and optimize options, it saves.</p>
<p>Here is my test.py that doesn't work:</p>
<pre><code>import Image
img = Image.open("in.jpg")
img.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True)
</code></pre>
<p>It raises this error:</p>
<pre><code>Suspension not allowed here
Traceback (most recent call last):
File "test.py", line 3, in <module>
img.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True)
File "/Library/Python/2.6/site-packages/PIL/Image.py", line 1439, in save
save_handler(self, fp, filename)
File "/Library/Python/2.6/site-packages/PIL/JpegImagePlugin.py", line 471, in _save
ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
File "/Library/Python/2.6/site-packages/PIL/ImageFile.py", line 501, in _save
raise IOError("encoder error %d when writing image file" % s)
IOError: encoder error -2 when writing image file
</code></pre>
<p>Link to image: <a href="http://static.cafe.nov.ru/in.jpg" rel="noreferrer">http://static.cafe.nov.ru/in.jpg</a> (4.3 mb)</p> | 6,789,301 | 3 | 3 | null | 2011-07-22 09:58:34.377 UTC | 13 | 2013-09-10 10:37:48.967 UTC | 2011-07-22 10:55:08.55 UTC | null | 329,226 | null | 329,226 | null | 1 | 25 | python|python-imaging-library | 39,732 | <p>Here's a hack that might work, but you may need to make the buffer even larger:</p>
<pre><code>from PIL import Image, ImageFile
ImageFile.MAXBLOCK = 2**20
img = Image.open("in.jpg")
img.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True)
</code></pre> |
6,432,605 | Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks? | <p>I'd like to be able to dump a dictionary containing long strings that I'd like to have in the block style for readability. For example:</p>
<pre><code>foo: |
this is a
block literal
bar: >
this is a
folded block
</code></pre>
<p>PyYAML supports the loading of documents with this style but I can't seem to find a way to dump documents this way. Am I missing something?</p> | 7,445,560 | 3 | 1 | null | 2011-06-21 22:07:27.923 UTC | 12 | 2018-08-23 07:35:07.17 UTC | null | null | null | null | 279,104 | null | 1 | 28 | python|yaml|pyyaml | 13,482 | <pre><code>import yaml
class folded_unicode(unicode): pass
class literal_unicode(unicode): pass
def folded_unicode_representer(dumper, data):
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='>')
def literal_unicode_representer(dumper, data):
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.add_representer(literal_unicode, literal_unicode_representer)
data = {
'literal':literal_unicode(
u'by hjw ___\n'
' __ /.-.\\\n'
' / )_____________\\\\ Y\n'
' /_ /=== == === === =\\ _\\_\n'
'( /)=== == === === == Y \\\n'
' `-------------------( o )\n'
' \\___/\n'),
'folded': folded_unicode(
u'It removes all ordinary curses from all equipped items. '
'Heavy or permanent curses are unaffected.\n')}
print yaml.dump(data)
</code></pre>
<p>The result:</p>
<pre><code>folded: >
It removes all ordinary curses from all equipped items. Heavy or permanent curses
are unaffected.
literal: |
by hjw ___
__ /.-.\
/ )_____________\\ Y
/_ /=== == === === =\ _\_
( /)=== == === === == Y \
`-------------------( o )
\___/
</code></pre>
<p>For completeness, one should also have str implementations, but I'm going to be lazy :-)</p> |
6,976,486 | Is there any way in JavaScript to focus the document (content area)? | <p>Is there any way to set focus to the document, i.e. the content area, in JavaScript? <code>document.focus()</code> doesn’t seem to do anything.</p> | 6,976,583 | 3 | 4 | null | 2011-08-07 23:23:11.89 UTC | 6 | 2022-01-06 19:17:30.04 UTC | null | null | null | null | 33,225 | null | 1 | 34 | javascript|focus | 41,570 | <p>In <a href="http://www.w3.org/TR/html401/interact/forms.html#focus" rel="noreferrer">HTML 4.01</a>, <em>focus</em> is only discussed in the context of elements such as form controls and links. In <a href="http://www.w3.org/TR/html5/editing.html#focus" rel="noreferrer">HTML 5</a>, it is discussed much more widely. However, how focus works for documents is mostly browser dependent.</p>
<p>You might try:</p>
<pre><code>// Give the document focus
window.focus();
// Remove focus from any focused element
if (document.activeElement) {
document.activeElement.blur();
}
</code></pre>
<p>It is very well <a href="http://caniuse.com/#search=activeElement" rel="noreferrer">supported</a> as well.</p> |
6,718,514 | Android check user logged in before, else start login activity | <p>I want the login activity to start when the user starts the app but has not logged in before. If a successful login has been completed before, the app will skip the login page and move to MainMenu.java.
What I have now is:</p>
<pre><code> public class Login extends Activity implements OnClickListener, TaskCompleteCallback{
first_time_check();
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.configure);
...}
private boolean first_time_check() {
String first = mPreferences.getString("first", null);
if((first == null)){
Intent i = new Intent(Login.this, MainMenu.class);
startActivity(i);
}
return false;
}
...
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString("first", value);
...
editor.commit();
// Close the activity
Intent i = new Intent(Login.this, MainMenu.class);
startActivity(i);
}
</code></pre>
<p>But I get FCs'. Is something wrong with how I implemented SharedPreferences?</p> | 6,718,590 | 4 | 7 | null | 2011-07-16 15:56:50.643 UTC | 15 | 2014-06-25 17:12:49.837 UTC | 2014-06-25 17:12:49.837 UTC | null | 2,246,344 | null | 837,627 | null | 1 | 33 | android|authentication | 40,622 | <p>Your code just never calls that <code>first_time_check()</code>, thus the automatic forward in case of a returning user does not work.</p>
<p>You could in <code>onCreate()</code> do</p>
<pre><code>protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
first_time_check();
setContentView(R.layout.configure);
...}
</code></pre>
<p>So for a new user, <code>first_time_check()</code> would forward him to the login page, otherwise
the current layout would be shown and he could continue on this page.</p> |
23,488,326 | std::vector of references | <p>I have such problem: I have class <code>Foo</code>, and if have some objects of this class,
</p>
<pre><code>Foo a();
</code></pre>
<p>I need to put this object to 2 different vectors:
</p>
<pre><code>std::vector<Foo> vA, vB;
</code></pre>
<p>and if <code>a</code> changes in <code>vA</code> it should be changed in <code>vB</code>, vectors <code>vA</code> and <code>vB</code> can be different, but they can have same objects. I know that it is possible to do with Boost, but I can't use Boost.</p> | 23,488,449 | 3 | 3 | null | 2014-05-06 07:19:48.237 UTC | 11 | 2017-07-27 15:38:17.847 UTC | 2017-07-27 15:38:17.847 UTC | null | 2,642,204 | null | 1,624,275 | null | 1 | 31 | c++|vector|stl | 33,109 | <p>There are some possibilities:</p>
<ol>
<li><p>Store a vector of pointers (use if your vectors <em>share ownership</em> of the pointers):
</p>
<pre><code>std::vector<std::shared_ptr<Foo>> vA, vB;
</code></pre></li>
<li><p>Store a vector of wrapped references (use if the vectors <em>do not share ownership</em> of the pointers, and you know the object referenced <em>are</em> valid past the lifetime of the vectors):
</p>
<pre><code>std::vector<std::reference_wrapper<Foo>> vA, vB;
</code></pre></li>
<li><p>Store a vector of raw pointers (use if your vectors <em>do not share ownership of the pointers</em>, and/or the pointers stored may change depending on other factors):</p>
<pre><code>std::vector<Foo*> vA, vB;
</code></pre>
<p>This is common for observation, keeping track of allocations, etc. The usual caveats for raw pointers apply: Do not use the pointers to access the objects after the end of their life time.</p></li>
<li><p>Store a vector of <code>std::unique_ptr</code> that wrap the objects (use if your vectors want to <em>handover the ownership of the pointers</em> in which case the lifetime of the referenced objects are governed by the rules of <code>std::unique_ptr</code> class):
</p>
<pre><code>std::vector<std::unique_ptr<Foo>> vA, vB;
</code></pre></li>
</ol> |
18,900,508 | Nginx: allow access only to referrer that match location name | <p>Is there a way, in nginx, to allow access to a "location" only to clients with a referrer that matches the current location name?</p>
<p>This is the scenario:</p>
<p><a href="http://foooooo.com/bar.org/" rel="noreferrer">http://foooooo.com/bar.org/</a></p>
<p><a href="http://foooooo.com/zeta.net/" rel="noreferrer">http://foooooo.com/zeta.net/</a></p>
<p>etc etc</p>
<p>I want the contents of the bar.org location available only if the referrer is bar.org. The same goes for zeta.net</p>
<p>I know I can do this "statically", but there are a lot of those locations and I need to find a way to do this defining only one "dynamic" location.</p>
<p>Sorry for my bad english.</p>
<p><strong>SOLUTION</strong></p>
<p>I've solved this way:</p>
<pre><code>location ~/([a-zA-Z0-9\.\-]*)/* {
set $match "$1::$http_referer";
if ($match !~* ^(.+)::http[s]*://[www]*[.]*\1.*$ ) {
return 403;
}
}
</code></pre> | 18,917,016 | 2 | 3 | null | 2013-09-19 16:44:22.57 UTC | 6 | 2020-05-30 19:08:59.833 UTC | 2013-09-20 15:59:18.85 UTC | null | 2,795,921 | null | 2,795,921 | null | 1 | 10 | nginx|http-referer | 38,420 | <pre><code>location ~ ^/([a-zA-Z0-9\.\-]*)/(.*) {
if ($http_referer !~ "^$1.*$"){
return 403;
}
}
</code></pre> |
51,125,266 | How do I split Tensorflow datasets? | <p>I have a tensorflow dataset based on one .tfrecord file. How do I split the dataset into test and train datasets? E.g. 70% Train and 30% test?</p>
<p>Edit:</p>
<p>My Tensorflow Version: 1.8
I've checked, there is no "split_v" function as mentioned in the possible duplicate. Also I am working with a tfrecord file.</p> | 51,126,863 | 2 | 4 | null | 2018-07-01 17:00:30.987 UTC | 20 | 2020-12-30 01:31:08.49 UTC | 2018-07-01 17:13:30.703 UTC | null | 5,240,684 | null | 5,240,684 | null | 1 | 41 | tensorflow|tensorflow-datasets | 40,701 | <p>You may use <code>Dataset.take()</code> and <code>Dataset.skip()</code>:</p>
<pre><code>train_size = int(0.7 * DATASET_SIZE)
val_size = int(0.15 * DATASET_SIZE)
test_size = int(0.15 * DATASET_SIZE)
full_dataset = tf.data.TFRecordDataset(FLAGS.input_file)
full_dataset = full_dataset.shuffle()
train_dataset = full_dataset.take(train_size)
test_dataset = full_dataset.skip(train_size)
val_dataset = test_dataset.skip(test_size)
test_dataset = test_dataset.take(test_size)
</code></pre>
<p>For more generality, I gave an example using a 70/15/15 train/val/test split but if you don't need a test or a val set, just ignore the last 2 lines.</p>
<p><a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#take" rel="noreferrer"><strong>Take</strong></a>:</p>
<blockquote>
<p>Creates a Dataset with at most count elements from this dataset.</p>
</blockquote>
<p><a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#skip" rel="noreferrer"><strong>Skip</strong></a>:</p>
<blockquote>
<p>Creates a Dataset that skips count elements from this dataset.</p>
</blockquote>
<p>You may also want to look into <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shard" rel="noreferrer"><code>Dataset.shard()</code></a>:</p>
<blockquote>
<p>Creates a Dataset that includes only 1/num_shards of this dataset.</p>
</blockquote> |
41,025,200 | android.view.InflateException Error inflating class android.webkit.WebView | <p>In Lollipop (API 22) every time in my application I show a webview the application crashes.
I have multiple crashes in my android developer console related to this event.</p>
<p>No need to say that it works on Android 4, 6 and 7.</p>
<p>Reading the stack trace (posted at the end of this post), something bugs me</p>
<pre><code>Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x2040003
</code></pre>
<p>I searched in the generated R.java without any luck, obviously because the ID does not exists, but it was worth a try.</p>
<p>Googling around the problem seems to be related to how lollipop handles the webview. I started a fresh AVD with lollipop based on a device I found on the crash reporter in GDC, and I can reproduce the problem.</p>
<hr>
<p>Full stack trace:</p>
<pre><code>android.view.InflateException: Binary XML file line #7: Error inflating class android.webkit.WebView
at android.view.LayoutInflater.createView(LayoutInflater.java:633)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:682)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at it.artecoop.ibreviary.WebViewFragment.onCreateView(WebViewFragment.java:67)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2087)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1113)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1295)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1682)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:541)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:607)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:682)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at it.artecoop.ibreviary.WebViewFragment.onCreateView(WebViewFragment.java:67)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2087)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1113)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1295)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1682)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:541)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x2040003
at android.content.res.Resources.getText(Resources.java:299)
at android.content.res.Resources.getString(Resources.java:385)
at com.android.org.chromium.content.browser.ContentViewCore.setContainerView(ContentViewCore.java:684)
at com.android.org.chromium.content.browser.ContentViewCore.initialize(ContentViewCore.java:608)
at com.android.org.chromium.android_webview.AwContents.createAndInitializeContentViewCore(AwContents.java:631)
at com.android.org.chromium.android_webview.AwContents.setNewAwContents(AwContents.java:780)
at com.android.org.chromium.android_webview.AwContents.<init>(AwContents.java:619)
at com.android.org.chromium.android_webview.AwContents.<init>(AwContents.java:556)
at com.android.webview.chromium.WebViewChromium.initForReal(WebViewChromium.java:311)
at com.android.webview.chromium.WebViewChromium.access$100(WebViewChromium.java:96)
at com.android.webview.chromium.WebViewChromium$1.run(WebViewChromium.java:263)
at com.android.webview.chromium.WebViewChromium$WebViewChromiumRunQueue.drainQueue(WebViewChromium.java:123)
at com.android.webview.chromium.WebViewChromium$WebViewChromiumRunQueue$1.run(WebViewChromium.java:110)
at com.android.org.chromium.base.ThreadUtils.runOnUiThread(ThreadUtils.java:144)
at com.android.webview.chromium.WebViewChromium$WebViewChromiumRunQueue.addTask(WebViewChromium.java:107)
at com.android.webview.chromium.WebViewChromium.init(WebViewChromium.java:260)
at android.webkit.WebView.<init>(WebView.java:554)
at android.webkit.WebView.<init>(WebView.java:489)
at android.webkit.WebView.<init>(WebView.java:472)
at android.webkit.WebView.<init>(WebView.java:459)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:607)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:682)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at it.artecoop.ibreviary.WebViewFragment.onCreateView(WebViewFragment.java:67)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2087)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1113)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1295)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1682)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:541)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code></pre> | 57,968,071 | 20 | 6 | null | 2016-12-07 18:55:29.847 UTC | 38 | 2021-01-23 20:06:30.623 UTC | 2019-11-16 14:22:35.373 UTC | null | 1,839,439 | null | 813,728 | null | 1 | 148 | java|android|webview | 47,955 | <p>If you use <code>androidx.appcompat:appcompat:1.1.0</code>, try <code>androidx.appcompat:appcompat:1.0.2</code> instead.
it seems that <code>1.1.0</code> doesn't fix the bug with <code>WebView</code> in Android <code>5.1.1</code>.</p>
<p>Feb-2020 update: Reverting to <code>1.0.2</code> stopped working for many people (including my app), but using the current version of <code>androidx.appcompat:appcompat:1.2.0-alpha02</code> did fix the crash. <em>(I was seeing it on a Huawei P8 Lite running Android 5.0 during Google's automated "Pre-launch report" testing).</em></p>
<p>Jun-2020 update: There are newer releases available than the one mentioned in the Feb-2020 update, you can see the currently available versions here:</p>
<ul>
<li><a href="https://developer.android.com/jetpack/androidx/releases/appcompat" rel="noreferrer">https://developer.android.com/jetpack/androidx/releases/appcompat</a></li>
</ul> |
5,097,191 | $.ajax context option | <p>Episode 11 of the <a href="http://yayquery.com/" rel="noreferrer">yayQuery</a> podcast mentions the <a href="https://api.jquery.com/jquery.ajax/" rel="noreferrer">$.ajax context option</a>.
How would I use this option in the success callback?
What I'm currently doing is passing my input parameters back to the success callback so that I can animate the id that was called after success/error.
If I use the context option, then perhaps I don't have to pass the parameters back from the called routine.</p>
<p>In this example, I pass STATEID back to the success field so that the state is removed from the DOM once it's been deleted from the database:</p>
<pre><code>$('td.delete').click(function() {
var confirm = window.confirm('Are you sure?');
if (confirm) {
var StateID = $(this).parents('tr').attr('id');
$.ajax({
url: 'Remote/State.cfc',
data: {
method: 'Delete',
'StateID': StateID
},
success: function(result) {
if (result.MSG == '') {
$('#' + result.STATEID).remove();
} else {
$('#msg').text(result.MSG).addClass('err');;
};
}
});
}
});
</code></pre> | 5,097,214 | 2 | 0 | null | 2011-02-23 21:13:08.12 UTC | 15 | 2018-03-20 13:04:48.28 UTC | 2018-03-20 13:04:48.28 UTC | null | 1,429,387 | null | 111,665 | null | 1 | 66 | jquery|coldfusion | 70,228 | <p>All the <code>context</code> does is it sets the value of <code>this</code> in the callbacks.</p>
<p>So if you're in an event handler, and you want <code>this</code> in the callbacks to be the element that received the event, you'd do:</p>
<pre><code>context:this,
success:function() {
// "this" is whatever the value was where this ajax call was made
}
</code></pre>
<p>If you wanted it to be some other type, just set that, and <code>this</code> will refer to that:</p>
<pre><code>context:{some:'value'},
success:function() {
// "this" the object you passed
alert( this.some ); // "value"
}
</code></pre>
<hr>
<p>In the code you added to the question, you could use <code>StateID</code>, but you wouldn't really need to since you already have access to that variable.</p>
<pre><code>var StateID = $(this).parents('tr').attr('id');
$.ajax({
url: 'Remote/State.cfc'
,data: {
method:'Delete'
,'StateID':StateID
}
,context: StateID
,success: function(result){
alert(this); // the value of StateID
alert(StateID); // same as above
if (result.MSG == '') {
$('#' + result.STATEID).remove();
} else {
$('#msg').text(result.MSG).addClass('err');;
};
}
});
</code></pre> |
16,055,391 | Writing data to a local text file with javascript | <p>I have created a procedure to write content to a text file in my local machine.</p>
<pre><code><form id="addnew">
<input type="text" class="id">
<input type="text" class="content">
<input type="submit" value="Add">
</form>
<script>
jQuery(function($) {
$('#form_addjts').submit(function(){
writeToFile({
id: $(this).find('.id').val(),
content: $(this).find('.content').val()
});
return false;
});
function writeToFile(data){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("D:\\data.txt", 8);
fh.WriteLine(data.id + ',' + data.content);
fh.Close();
}
});
</script>
</code></pre>
<p>This is working fine, and able to append my new data to the file.</p>
<p>But I want to update a particular row CONTENT based on the ID which I am passing.<br>
I searched a lot, but could not find any.</p>
<p>How can update a particular row in the file based on the ID? </p>
<p>Note:- I am not using any server as such. I have a a html file (contains all the functionality) which I will be running on my local machine itself.</p> | 22,290,200 | 1 | 3 | null | 2013-04-17 08:39:04.843 UTC | 10 | 2017-02-13 19:05:51.71 UTC | 2016-07-29 04:13:39.477 UTC | null | 2,202,732 | null | 1,841,369 | null | 1 | 9 | javascript|jquery|html|file-io|hta | 132,557 | <p>Our HTML:</p>
<pre><code><div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
</code></pre>
<p>JS (writing to the txt file):</p>
<pre><code>function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
</code></pre>
<p>checking a particular row:</p>
<pre><code>function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
</code></pre>
<p>Put these inside a <code>.hta</code> file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.</p> |
493,838 | Eclipse Keyboard shortcuts in Mac OSX | <p>I'm running Leopard and do all my Java development in eclipse. Some of the shortcuts work such as Command-1 which will do a quick suggest. However how do I get the Function Keys (F5 for refresh in the package explorer) to work? Right now it brings up spaces or whatever System Preferences maps to that.</p>
<p>What about Control-click into a breakpoint when I'm debugging and want to go directly to the chosen function? Is there a way for my eclipse keyboard shortcuts to take precedence over other programs?</p>
<p>i'm running eclipse 3.4 though I've had this problem since eclipse 3.2.</p> | 493,937 | 7 | 0 | null | 2009-01-29 22:50:23.577 UTC | 2 | 2021-05-14 23:53:34.97 UTC | null | null | null | Ish | 58,175 | null | 1 | 21 | eclipse|macos | 49,334 | <p>Its been a while since I used eclipse on the mac but I think you have to go to Preferences.app and check the "keyboard" pane. There should be an option that chooses if its <kbd>Fn</kbd>-function-key or just function-key for the key press. After that, it would be <kbd>Fn+F5</kbd> for expose and just <kbd>F5</kbd> for <kbd>F5</kbd>. You will lose the ability to dim the screen and adjust the sound from the keyboard.</p> |
656,703 | How does flex support bison-location exactly? | <p>I'm trying to use flex and bison to create a filter, because I want get certain grammar elements from a complex language. My plan is to use flex + bison to recognise the grammar, and dump out the location of elements of interest. (Then use a script to grab text according the locations dumped.) </p>
<p>I found flex can support a bison feature called bison-locations, but how it works in exactly. I tried the example in flex document, it seems the yylloc is not set automatically by flex, I always get <code>(1,0)-(1,0)</code>. Could flex calculate each token's location automatically? If not, what interface function is defined for me to implement? Is there any example?</p>
<p>Any better solution regarding to tools?</p>
<p>Best Regards,
Kevin</p>
<p><strong>Edit:</strong></p>
<p>Now the interface for yylex turn to:</p>
<pre><code>int yylex(YYSTYPE * yylval_param,YYLTYPE * yylloc_param );
</code></pre>
<p>bison manual does not specify how lexer should implement to correctly set yylloc_param. For me it is hard to manually trace column number of each token.</p> | 656,806 | 8 | 0 | null | 2009-03-18 01:49:15.433 UTC | 9 | 2016-12-06 14:43:54.473 UTC | 2014-03-02 09:59:56.973 UTC | Kevin Yu | 394,013 | Kevin Yu | 43,130 | null | 1 | 23 | bison|flex-lexer | 20,593 | <p>Take a look at section <a href="https://www.gnu.org/software/bison/manual/html_node/Tracking-Locations.html#Tracking-Locations" rel="nofollow noreferrer">3.6 of the Bison manual</a> - that seems to cover locations in some detail. Combined with what you found in the Flex manual, that may be sufficient.</p> |
456,884 | Extending python - to swig, not to swig or Cython | <p>I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.</p>
<p>With the help of swig you almost don't need to care about arguments etc. Everything works fine.</p>
<p>Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.</p>
<p>Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it. </p> | 456,995 | 10 | 0 | null | 2009-01-19 08:32:06.433 UTC | 36 | 2019-05-28 08:05:52.85 UTC | 2014-04-12 13:27:01.937 UTC | John Mulder | 1,227,469 | RSabet | 49,219 | null | 1 | 70 | python|c++|c|swig|cython | 32,399 | <p>For sure you will always have a performance gain doing this by hand, but the gain will be very small compared to the effort required to do this. I don't have any figure to give you but I don't recommend this, because you will need to maintain the interface by hand, and this is not an option if your module is large!</p>
<p>You did the right thing to chose to use a scripting language because you wanted rapid development. This way you've avoided the early optimization syndrome, and now you want to optimize bottleneck parts, great! But if you do the C/python interface by hand you will fall in the early optimization syndrome for sure.</p>
<p>If you want something with less interface code, you can think about creating a dll from your C code, and use that library directly from python with <a href="http://python.net/crew/theller/ctypes/" rel="noreferrer">cstruct</a>.</p>
<p>Consider also <a href="http://www.cython.org/" rel="noreferrer">Cython</a> if you want to use only python code in your program.</p> |
773,672 | Page-specific css rules - where to put them? | <p>Often when I'm designing a site, I have a need for a specific style to apply to a specific element on a page and I'm absolutely certain it will only ever apply to that element on that page (such as an absolutely positioned button or something). I don't want to resort to inline styles, as I tend to agree with the philosophy that styles be kept separate from markup, so I find myself debating internally where to put the style definition. </p>
<p>I hate to define a specific class or ID in my base css file for a one-time use scenario, and I dread the idea of making page-specific .css files. For the current site I'm working on, I'm considering just putting the style definition at the top of the page in the head element. What would you do?</p> | 773,697 | 11 | 0 | null | 2009-04-21 17:27:47.193 UTC | 5 | 2022-06-18 16:54:43.697 UTC | 2009-04-21 17:33:30.877 UTC | null | 34,942 | null | 34,942 | null | 1 | 23 | html|css | 47,792 | <p>Look to see if there's a combination of classes which would give you the result that you want. You might also want to consider breaking up the CSS for that one element into a few classes that could be re-used on other elements. This would help minimize the CSS required for your site as a whole.</p>
<p>I would try to avoid page-specific CSS at the top the HTML files since that leaves your CSS fragmented in the event that you want to change the appearance of the site.</p>
<p>For CSS which is really, truely, never to be used on anything else, I would still resort to putting a <code>#id</code> rule in the site-wide CSS.</p>
<p>Since the CSS is linked in from a different file it allows the browsers to cache that file, which reduces your server bandwidth (very) slightly for future loads.</p> |
190,543 | How can I change the width of a Windows console window? | <p>Is it possible to programmatically, or otherwise, increase the width of the Windows console window? Or do I need to create a wrapper program that looks and acts like the console somehow? Are there any programs around that do this already? I use Cygwin extensively in my development, and it seems a little ridiculous to me that all console windows in Windows are width limited.</p>
<p>If it matters at all, I'm running Windows XP.</p> | 190,554 | 11 | 0 | null | 2008-10-10 08:42:59.47 UTC | 8 | 2019-02-19 18:30:27.367 UTC | 2011-11-07 14:51:59.15 UTC | monoxide | 496,830 | monoxide | 15,537 | null | 1 | 28 | windows|windows-xp|console | 62,519 | <p>You can increase it manually by right-clicking the tray icon and entering the options dialog.</p>
<p>There are also third-party terminal emulators for Windows, such as <a href="http://sourceforge.net/projects/console/" rel="nofollow noreferrer">Console</a>:</p>
<p><a href="https://i.stack.imgur.com/qHaXc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qHaXc.jpg" alt="Screenshot of Console"></a>
</p> |
650,743 | In Perl, how to remove ^M from a file? | <p>I have a script that is appending new fields to an existing CSV, however <code>^M</code> characters are appearing at the end of the old lines so the new fields end up on a new row instead of the same one. How do I remove <code>^M</code> characters from a CSV file using Perl?</p> | 651,400 | 11 | 1 | null | 2009-03-16 14:48:16.647 UTC | 7 | 2021-12-17 21:12:02.86 UTC | 2017-12-07 00:22:30.813 UTC | brian d foy | 63,550 | Alex Wong | 55,119 | null | 1 | 39 | perl|carriage-return|hidden-characters | 115,195 | <p>You found out you can also do this:</p>
<pre><code>$line=~ tr/\015//d;
</code></pre> |
1,331,367 | Rake just one migration | <p>I'm trying to run just one migration out of a whole bunch in my rails app. How can I do this? I don't want to run any of the migrations before or after it. Thanks.</p> | 1,332,145 | 11 | 1 | null | 2009-08-25 22:25:01.293 UTC | 30 | 2017-05-11 00:27:15.13 UTC | null | null | null | null | 131,383 | null | 1 | 101 | ruby-on-rails|database|migration|rake | 75,375 | <p><code>rake db:migrate:redo VERSION=xxxxxxx</code>, but that will run the <code>down</code> and then the <code>up</code> step. You could do this in conjunction with commenting out the down step temporarily.</p> |
90,451 | Why would one use REST instead of SOAP based services? | <p>Attended an interesting demo on REST today, however, I couldn't think of a single reason (nor was one presented) why REST is in anyway better or simpler to use and implement than a SOAP based Services stack.</p>
<p>What are some of the reasons Why anyone in the "real world" use REST instead of the SOAP based Services?</p> | 90,473 | 11 | 1 | null | 2008-09-18 06:12:21.543 UTC | 80 | 2016-02-22 18:33:24.873 UTC | 2014-08-10 20:56:41.26 UTC | null | 463,785 | null | 9,382 | null | 1 | 153 | web-services|rest | 76,872 | <p>Less overhead (no SOAP envelope to wrap every call in)</p>
<p>Less duplication (HTTP already represents operations like DELETE, PUT, GET, etc. that have to otherwise be represented in a SOAP envelope).</p>
<p>More standardized - HTTP operations are well understood and operate consistently. Some SOAP implementations can get finicky.</p>
<p>More human readable and testable (harder to test SOAP with just a browser).</p>
<p>Don't need to use XML (well you kind of don't have to for SOAP either but it hardly makes sense since you're already doing parsing of the envelope).</p>
<p>Libraries have made SOAP (kind of) easy. But you are abstracting away a lot of redundancy underneath as I have noted. yes in theory SOAP can go over other transports so as to avoid riding atop a layer doing similar things, but in reality just about all SOAP work you'll ever do is over HTTP.</p> |
989,943 | Weird Objective-C Mod Behavior for Negative Numbers | <p>So I thought that negative numbers, when mod'ed should be put into positive space... I cant get this to happen in objective-c</p>
<p>I expect this:</p>
<pre><code>-1 % 3 = 2
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
</code></pre>
<p>But get this</p>
<pre><code>-1 % 3 = -1
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
</code></pre>
<p>Why is this and is there a workaround?</p> | 990,007 | 12 | 5 | null | 2009-06-13 04:05:36.783 UTC | 4 | 2016-09-05 22:28:36.26 UTC | 2012-12-29 18:27:13.913 UTC | null | 8,047 | null | 69,634 | null | 1 | 43 | objective-c|modulo | 33,005 | <pre><code>result = n % 3;
if( result < 0 ) result += 3;
</code></pre>
<p>Don't perform extra mod operations as suggested in the other answers. They are very expensive and unnecessary.</p> |
396,429 | How do you know what version number to use? | <p>Here's one I have always wondered about...</p>
<p>Please excuse my naivety, but - How do you decide what version number to name your software?</p>
<p>I assume, when somebody creates a "final" version of an application/program it is version 1.0? - Then, what happens when you update it, how do you decide to call it 1.1 or 1.03 etc etc. </p>
<p>Is this mostly for the developer?</p> | 396,433 | 12 | 2 | null | 2008-12-28 17:32:41.61 UTC | 34 | 2018-10-21 07:18:14.143 UTC | null | null | null | Keith Donegan | 37,418 | null | 1 | 47 | version | 11,781 | <p>I've recently heard a pithier versioning strategy, that I first encountered at <a href="https://medium.com/javascript-scene/software-versions-are-broken-3d2dc0da0783" rel="noreferrer">Eric Elliot's Medium account</a>. It's more weighted towards library versioning that customer facing version numbers, but it has the advantage of simplicity. Use a three part version number, where each number means:</p>
<p><strong>breaking.feature.fix</strong></p>
<ul>
<li><strong>breaking</strong>: Something has changed that means code/expectations must change</li>
<li><strong>feature</strong>: Something new is added, but old code/expectations will still work fine.</li>
<li><strong>fix</strong>: Nothing's new, but a bug has been fixed.</li>
</ul>
<p>I leave my old answer below, as it's still relevant to customer facing versions.</p>
<hr>
<p>I tend to weight the significant digits as follows....</p>
<p>w.x.y.z (or w.xyz)</p>
<ul>
<li>w - Major version, with many new
features. A paid upgrade. The first
public release of software is 1.X
(pre-release versions are 0.X)</li>
<li>x -
Significant release, but without
groundbreaking new features.</li>
<li>y -
Bugfix releases</li>
<li>z - Patchlevel
releases (fixing an emergency bug,
perhaps just for one client).</li>
</ul>
<p>If you choose to use the w.xyz format, you only get 9 digits before overflow. However, if you're releasing that often, you may have a bigger problem.</p>
<p>Let's illustrate with FooApp, my new product! </p>
<ul>
<li>0.9 - The first public beta</li>
<li>0.91 - The second public beta</li>
<li>0.911 - The emergency beta release to fix a crash on the Motorola 68010</li>
<li>1.0 - The first public release</li>
<li>1.1 - Added new BlahBaz feature</li>
<li>1.11 - Bugfixes</li>
<li>2.0 - Totally redeveloped interface.</li>
</ul> |
980,170 | How to create a lightweight C code sandbox? | <p>I'd like to build a C pre-processor / compiler that allows functions to be collected from local and online sources. ie:</p>
<pre><code>#fetch MP3FileBuilder http://scripts.com/MP3Builder.gz
#fetch IpodDeviceReader http://apple.com/modules/MP3Builder.gz
void mymodule_main() {
MP3FileBuilder(&some_data);
}
</code></pre>
<p>That's the easy part. </p>
<p>The hard part is <strong>I need a reliable way to "sandbox" the imported code from direct or unrestricted access to disk or system resources (including memory allocation and the stack)</strong>. I want a way to safely run <strong>small snippets of untrusted C code</strong> (modules) without the overhead of putting them in separate process, VM or interpreter (a separate thread would be acceptable though).</p>
<p><strong>REQUIREMENTS</strong></p>
<ul>
<li>I'd need to put quotas on its access to data and resources including CPU time. </li>
<li>I will block direct access to the standard libraries</li>
<li>I want to stop malicious code that creates endless recursion</li>
<li>I want to limit static and dynamic allocation to specific limits</li>
<li>I want to catch all exceptions the module may raise (like divide by 0).</li>
<li>Modules may only interact with other modules via core interfaces</li>
<li>Modules may only interact with the system (I/O etc..) via core interfaces</li>
<li>Modules must allow bit ops, maths, arrays, enums, loops and branching.</li>
<li>Modules cannot use ASM</li>
<li>I want to limit pointer and array access to memory reserved for the module (via a custom safe_malloc())</li>
<li>Must support ANSI C or a subset (see below)</li>
<li>The system must be lightweight and cross-platform (including embedded systems). </li>
<li>The system must be GPL or LGPL compatible.</li>
</ul>
<p>I'm happy to settle for a subset of C. I don't need things like templates or classes. I'm primarily interested in the things high-level languages don't do well like fast maths, bit operations, and the searching and processing of binary data.</p>
<p>It is <strong>not</strong> the intention that existing C code can be reused without modification to create a module. The intention is that modules would be required to conform to a set of rules and limitations designed to limit the module to basic logic and transformation operations (like a video transcode or compression operations for example).</p>
<p>The theoretical input to such a compiler/pre-processor would be a single ANSI C file (or safe subset) with a module_main function, NO includes or pre-processor directives, no ASM, It would allow loops, branching, function calls, pointer maths (restricted to a range allocated to the module), bit-shifting, bitfields, casts, enums, arrays, ints, floats, strings and maths. Anything else is optional.</p>
<p><strong>EXAMPLE IMPLEMENTATION</strong></p>
<p>Here's a pseudo-code snippet to explain this better. Here a module exceeds it's memory allocation quota and also creates infinite recursion.</p>
<pre><code>buffer* transcodeToAVI_main( &in_buffer ) {
int buffer[1000000000]; // allocation exceeding quota
while(true) {} // infinite loop
return buffer;
}
</code></pre>
<p>Here's a transformed version where our preprocessor has added watchpoints to check for memory usage and recursion and wrapped the whole thing in an exception handler.</p>
<pre><code>buffer* transcodeToAVI_main( &in_buffer ) {
try {
core_funcStart(__FILE__,__FUNC__); // tell core we're executing this function
buffer = core_newArray(1000000000, __FILE__, __FUNC__); // memory allocation from quota
while(true) {
core_checkLoop(__FILE__, __FUNC__, __LINE__) && break; // break loop on recursion limit
}
core_moduleEnd(__FILE__,__FUNC__);
} catch {
core_exceptionHandler(__FILE__, __FUNC__);
}
return buffer;
}
</code></pre>
<p>I realise performing these checks impact the module performance but I suspect it will still outperform high-level or VM languages for the tasks it is intended to solve. I'm not trying to stop modules doing dangerous things outright, I'm just trying to force those dangerous things to happen in a controlled way (like via user feedback). ie: "Module X has exceeded it's memory allocation, continue or abort?".</p>
<p><strong>UPDATE</strong></p>
<p>The best I've got so far is to use a custom compiler (Like a hacked TCC) with bounds checking and some custom function and looping code to catch recursions. I'd still like to hear thoughts on what else I need to check for or what solutions are out there. I imagine that removing ASM and checking pointers before use solves a lot of the concerns expressed in previous answers below. I added a bounty to pry some more feedback out of the SO community. </p>
<p><strong>For the bounty I'm looking for:</strong></p>
<ul>
<li>Details of potential exploits against the theoretical system defined above</li>
<li>Possible optimisations over checking pointers on each access</li>
<li>Experimental open-source implementations of the concepts (like Google Native Client)</li>
<li>Solutions that support a wide range of OS and devices (no OS/hardware based solutions)</li>
<li>Solutions that support the most C operations, or even C++ (if that's possible)</li>
</ul>
<p>Extra credit for a method that can work with GCC (ie, a pre-processor or <em>small</em> GCC patch).</p>
<p>I'll also give consideration to anyone who can conclusively prove what I'm attempting cannot be done at all. You will need to be pretty convincing though because none of the objections so far have really nailed the technical aspects of why they think it's impossible. In the defence of those who said no this question was originally posed as a way to safely run C++. I have now scaled back the requirement to a limited subset of C.</p>
<p>My understanding of C could be classed as "intermediate", my understanding of PC hardware is maybe a step below "advanced". Try to coach your answers for that level if you can. Since I'm no C expert I'll be going largely based on votes given to an answer as well as how closely the answer comes to my requirements. You can assist by providing sufficient evidence for your claims (respondents) and by voting (everyone else). I'll assign an answer once the bounty countdown reaches 6 hours.</p>
<p>Finally, I believe solving this problem would be a major step towards maintaining C's relevance in an increasingly networked and paranoid world. As other languages close the gap performance-wise and computing power grows it will be harder and harder to justify the added risk of C development (as it is now with ASM). I believe your answers will have a much greater relevance than scoring a few SO points so please contribute what you can, even if the bounty has expired.</p> | 993,420 | 13 | 14 | 2009-06-14 08:09:32.46 UTC | 2009-06-11 09:28:34.66 UTC | 24 | 2017-03-12 01:11:57.23 UTC | 2009-06-14 15:15:07.43 UTC | null | 108,741 | null | 108,741 | null | 1 | 39 | c|sandbox | 17,440 | <p>Since the C standard is much too broad to be allowed, you would need to go the other way around: specify the minimum subset of C which you need, and try to implement that. Even ANSI C is already too complicated and allows unwanted behaviour.</p>
<p>The aspect of C which is most problematic are the pointers: the C language requires pointer arithmitic, and those are not checked. For example:</p>
<pre><code>char a[100];
printf("%p %p\n", a[10], 10[a]);
</code></pre>
<p>will both print the same address. Since <code>a[10] == 10[a] == *(10 + a) == *(a + 10)</code>.</p>
<p>All these pointer accesses cannot be checked at compile time. That's the same complexity as asking the compiler for 'all bugs in a program' which would require solving the halting problem.</p>
<p>Since you want this function to be able to run in the same process (potentially in a different thread) you share memory between your application and the 'safe' module since that's the whole point of having a thread: share data for faster access. However, this also means that both threads can read and write the same memory.</p>
<p>And since you cannot prove compile time where pointers end up, you have to do that at runtime. Which means that code like 'a[10]' has to be translated to something like 'get_byte(a + 10)' at which point I wouldn't call it C anymore.</p>
<p><strong>Google Native Client</strong></p>
<p>So if that's true, how does google do it then? Well, in contrast to the requirements here (cross-platform (including embedded systems)), Google concentrates on x86, which has in additional to paging with page protections also segment registers. Which allows it to create a sandbox where another thread does not share the same memory in the same way: the sandbox is by segmentation limited to changing only its own memory range. Furthermore:</p>
<ul>
<li>a list of safe x86 assembly constructs is assembled</li>
<li>gcc is changed to emit those safe constructs</li>
<li>this list is constructed in a way that is verifiable.</li>
<li>after loading a module, this verification is done</li>
</ul>
<p>So this is platform specific and is not a 'simple' solution, although a working one. Read more at their <a href="http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en/us/pubs/archive/34913.pdf" rel="nofollow noreferrer">research paper</a>.</p>
<p><strong>Conclusion</strong></p>
<p>So whatever route you go, you need to start out with something new which is verifiable and
only then you can start by adapting an existing a compiler or generating a new one. However, trying to mimic ANSI C requires one to think about the pointer problem. Google modelled their sandbox not on ANSI C but on a subset of x86, which allowed them to use existing compilers to a great extend with the disadvantage of being tied to x86.</p> |
1,108,693 | Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps? | <p>I'd like to have iOS to open URLs from my domain (e.g. <a href="http://martijnthe.nl" rel="noreferrer">http://martijnthe.nl</a>) with my app whenever the app is installed on the phone, and with Mobile Safari in case it is not.</p>
<p>I read it is possible to create a unique protocol suffix for this and register it in the Info.plist, but Mobile Safari will give an error in case the app is not installed.</p>
<p>What would be a workaround?</p>
<p>One idea:</p>
<p>1) Use http:// URLs that open in any desktop browser and render the service through the browser</p>
<p>2) Check the User-Agent and in case it's Mobile Safari, open a myprotocol:// URL to (attempt) to open the iPhone app and have it open Mobile iTunes to the download of the app in case the attempt fails</p>
<p>Not sure if this will work... suggestions? Thanks!</p> | 1,109,200 | 13 | 2 | null | 2009-07-10 09:53:01.71 UTC | 306 | 2020-08-04 15:03:29 UTC | 2012-03-03 14:43:01.213 UTC | null | 299,797 | null | 136,168 | null | 1 | 230 | iphone|ios|url | 150,280 | <p>I think the least intrusive way of doing this is as follows:</p>
<ol>
<li>Check if the user-agent is that of an iPhone/iPod Touch</li>
<li>Check for an <code>appInstalled</code> cookie</li>
<li>If the cookie exists and is set to true, set <code>window.location</code> to <code>your-uri://</code> (or do the redirect server side)</li>
<li>If the cookie doesn't exist, open a "Did you know Your Site Name has an iPhone application?" modal with a "Yep, I've already got it", "Nope, but I'd love to try it", and "Leave me alone" button.
<ol>
<li>The "Yep" button sets the cookie to true and redirects to <code>your-uri://</code></li>
<li>The "Nope" button redirects to "<a href="http://itunes.com/apps/yourappname" rel="noreferrer">http://itunes.com/apps/yourappname</a>" which will open the App Store on the device</li>
<li>The "Leave me alone" button sets the cookie to false and closes the modal</li>
</ol></li>
</ol>
<p>The other option I've played with but found a little clunky was to do the following in Javascript:</p>
<pre><code>setTimeout(function() {
window.location = "http://itunes.com/apps/yourappname";
}, 25);
// If "custom-uri://" is registered the app will launch immediately and your
// timer won't fire. If it's not set, you'll get an ugly "Cannot Open Page"
// dialogue prior to the App Store application launching
window.location = "custom-uri://";
</code></pre> |
420,429 | Mirroring console output to a file | <p>In a C# console application, is there a smart way to have console output mirrored to a text file?</p>
<p>Currently I am just passing the same string to both <code>Console.WriteLine</code> and <code>InstanceOfStreamWriter.WriteLine</code> in a log method.</p> | 420,502 | 14 | 0 | null | 2009-01-07 14:13:30.73 UTC | 42 | 2020-03-26 07:39:49.3 UTC | null | null | null | frou | 82 | null | 1 | 93 | c#|.net|file|text|console | 70,792 | <p>This may be some kind of more work, but I would go the other way round.</p>
<p>Instantiate a <code>TraceListener</code> for the console and one for the log file; thereafter use <code>Trace.Write</code> statements in your code instead of <code>Console.Write</code>. It becomes easier afterwards to remove the log, or the console output, or to attach another logging mechanism.</p>
<pre><code>static void Main(string[] args)
{
Trace.Listeners.Clear();
TextWriterTraceListener twtl = new TextWriterTraceListener(Path.Combine(Path.GetTempPath(), AppDomain.CurrentDomain.FriendlyName));
twtl.Name = "TextLogger";
twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime;
ConsoleTraceListener ctl = new ConsoleTraceListener(false);
ctl.TraceOutputOptions = TraceOptions.DateTime;
Trace.Listeners.Add(twtl);
Trace.Listeners.Add(ctl);
Trace.AutoFlush = true;
Trace.WriteLine("The first line to be in the logfile and on the console.");
}
</code></pre>
<p>As far as I can recall, you can define the listeners in the application configuration making it possible to activate or deactivate the logging without touching the build.</p> |
307,352 | g++ undefined reference to typeinfo | <p>I just ran across the following error (and found the solution online, but it's not present in Stack Overflow):</p>
<blockquote>
<p>(.gnu.linkonce.[stuff]): undefined
reference to [method] [object
file]:(.gnu.linkonce.[stuff]):
undefined reference to `typeinfo for
[classname]'</p>
</blockquote>
<p>Why might one get one of these "undefined reference to typeinfo" linker errors?</p>
<p>(Bonus points if you can explain what's going on behind the scenes.)</p> | 307,427 | 18 | 6 | null | 2008-11-21 00:02:18.893 UTC | 48 | 2021-09-02 16:14:17.433 UTC | null | null | null | cdleary | 3,594 | null | 1 | 261 | c++|linker|g++ | 229,648 | <p>One possible reason is because you are declaring a virtual function without defining it.</p>
<p>When you declare it without defining it in the same compilation unit, you're indicating that it's defined somewhere else - this means the linker phase will try to find it in one of the other compilation units (or libraries).</p>
<p>An example of defining the virtual function is:</p>
<pre><code>virtual void fn() { /* insert code here */ }
</code></pre>
<p>In this case, you are attaching a definition to the declaration, which means the linker doesn't need to resolve it later.</p>
<p>The line</p>
<pre><code>virtual void fn();
</code></pre>
<p>declares <code>fn()</code> without defining it and will cause the error message you asked about.</p>
<p>It's very similar to the code:</p>
<pre><code>extern int i;
int *pi = &i;
</code></pre>
<p>which states that the integer <code>i</code> is declared in another compilation unit which must be resolved at link time (otherwise <code>pi</code> can't be set to it's address).</p> |
743,164 | How to emulate a do-while loop? | <p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p>
<pre><code>list_of_ints = [ 1, 2, 3 ]
iterator = list_of_ints.__iter__()
element = None
while True:
if element:
print element
try:
element = iterator.next()
except StopIteration:
break
print "done"
</code></pre>
<p>Instead of "1,2,3,done", it prints the following output:</p>
<pre><code>[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', ' File "test_python.py", line 8, in <module>
s = i.next()
', 'StopIteration
']
</code></pre>
<p>What can I do in order to catch the 'stop iteration' exception and break a while
loop properly?</p>
<p>An example of why such a thing may be needed is shown below as pseudocode.</p>
<p>State machine:</p>
<pre><code>s = ""
while True :
if state is STATE_CODE :
if "//" in s :
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT :
if "//" in s :
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
else
state = STATE_CODE
# Re-evaluate same line
continue
try :
s = i.next()
except StopIteration :
break
</code></pre> | 743,186 | 20 | 4 | null | 2009-04-13 06:18:42.693 UTC | 159 | 2022-06-29 01:32:35.74 UTC | 2021-03-13 18:11:33.687 UTC | null | 355,230 | null | 69,882 | null | 1 | 1,041 | python|while-loop|do-while | 1,675,382 | <p>I am not sure what you are trying to do. You can implement a do-while loop like this:</p>
<pre><code>while True:
stuff()
if fail_condition:
break
</code></pre>
<p>Or:</p>
<pre><code>stuff()
while not fail_condition:
stuff()
</code></pre>
<p>What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:</p>
<pre><code>for i in l:
print i
print "done"
</code></pre>
<p>Update:</p>
<p>So do you have a list of lines? And you want to keep iterating through it? How about: </p>
<pre><code>for s in l:
while True:
stuff()
# use a "break" instead of s = i.next()
</code></pre>
<p>Does that seem like something close to what you would want? With your code example, it would be:</p>
<pre><code>for s in some_list:
while True:
if state is STATE_CODE:
if "//" in s:
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT:
if "//" in s:
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
break # get next s
else:
state = STATE_CODE
# re-evaluate same line
# continues automatically
</code></pre> |
6,861,487 | Importing modules inside python class | <p>I'm currently writing a class that needs <code>os</code>, <code>stat</code> and some others.</p>
<p>What's the best way to import these modules in my class?</p>
<p>I'm thinking about when others will use it, I want the 'dependency' modules to be already
imported when the class is instantiated.</p>
<p>Now I'm importing them in my methods, but maybe there's a better solution.</p> | 6,861,854 | 4 | 0 | null | 2011-07-28 15:24:48.5 UTC | 19 | 2022-07-25 19:26:54.46 UTC | null | null | null | null | 770,023 | null | 1 | 74 | python|class|import|module | 98,440 | <p>If your module will always import another module, always put it at the top as <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP 8</a> and the other answers indicate. Also, as @delnan mentions in a comment, <code>sys</code>, <code>os</code>, etc. are being used anyway, so it doesn't hurt to import them globally.</p>
<p>However, there is nothing wrong with conditional imports, if you really only need a module under certain runtime conditions.</p>
<p>If you only want to import them if the class is <strong>defined</strong>, like if the class is in an conditional block or another class or method, you can do something like this:</p>
<pre><code>condition = True
if condition:
class C(object):
os = __import__('os')
def __init__(self):
print self.os.listdir
C.os
c = C()
</code></pre>
<p>If you only want it to be imported if the class is <strong>instantiated</strong>, do it in <code>__new__</code> or <code>__init__</code>.</p> |
6,343,630 | GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag | <pre><code><form runat="server" id="f1">
<div runat="server" id="d">
grid view:
<asp:GridView runat="server" ID="g">
</asp:GridView>
</div>
<asp:TextBox runat="server" ID="t" TextMode="MultiLine" Rows="20" Columns="50"></asp:TextBox>
</form>
</code></pre>
<p>Code behind:</p>
<pre><code>public partial class ScriptTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
g.DataSource = new string[] { "a", "b", "c" };
g.DataBind();
TextWriter tw = new StringWriter();
HtmlTextWriter h = new HtmlTextWriter(tw);
d.RenderControl(h);
t.Text = tw.ToString();
}
}
</code></pre>
<p>Even the GridView is within a from tag with runat="server", still I am getting this error.</p>
<p>Any clues please ?</p> | 6,343,859 | 5 | 4 | null | 2011-06-14 12:41:53.427 UTC | 23 | 2016-09-02 13:32:19.843 UTC | 2014-05-06 06:39:20.847 UTC | null | 1,537,726 | null | 353,512 | null | 1 | 90 | c#|.net|asp.net | 212,776 | <p>You are calling <code>GridView.RenderControl(htmlTextWriter)</code>, hence the page raises an exception that a Server-Control was rendered outside of a Form. </p>
<p>You could avoid this execption by overriding <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.verifyrenderinginserverform.aspx" rel="noreferrer">VerifyRenderingInServerForm</a></p>
<pre><code>public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
</code></pre>
<p>See <a href="http://forums.asp.net/t/1016960.aspx/1?Problem%20with%20GridView%20s%20RenderControl" rel="noreferrer">here</a> and <a href="http://aspalliance.com/771_CodeSnip_Exporting_GridView_to_Excel" rel="noreferrer">here</a>.</p> |
6,705,955 | Why switch is faster than if | <p>Lots of Java books describe the <code>switch</code> statement as being faster than the <code>if else</code> statement. But I did not find out anywhere <strong>why switch is faster than if</strong>.</p>
<h2>Example</h2>
<p>I have a situation I have to choose any one item out of two. I can use either use</p>
<pre><code>switch (item) {
case BREAD:
//eat Bread
break;
default:
//leave the restaurant
}
</code></pre>
<p>or</p>
<pre><code>if (item == BREAD) {
//eat Bread
} else {
//leave the restaurant
}
</code></pre>
<p>considering item and BREAD is a constant int value.</p>
<p>In the above example which <strong>is faster in action and why?</strong></p> | 6,705,977 | 5 | 15 | null | 2011-07-15 10:53:50.177 UTC | 23 | 2019-12-12 06:44:49.803 UTC | 2019-12-12 06:44:49.803 UTC | null | 2,049,986 | user831722 | null | null | 1 | 131 | java|switch-statement | 91,898 | <p>Because there are special bytecodes that allow efficient switch statement evaluation when there are a lot of cases.</p>
<p>If implemented with IF-statements you would have a check, a jump to the next clause, a check, a jump to the next clause and so on. With switch the JVM loads the value to compare and iterates through the value table to find a match, which is faster in most cases.</p> |
6,427,096 | Heroku: see params and sql activity in logs? | <p>When i view my heroku logs on the server (with <code>heroku logs --tail --app myapp</code>) i see something like this:</p>
<pre><code>2011-06-21T14:09:25+00:00 app[web.1]: Started PUT "/reports/19.xml" for 77.89.149.137 at 2011-06-21 07:09:25 -0700
2011-06-21T14:09:25+00:00 heroku[router]: PUT myapp.heroku.com/reports/19.xml dyno=web.1 queue=0 wait=0ms service=7ms status=401 bytes=28
2011-06-21T14:09:26+00:00 heroku[nginx]: PUT /reports/19.xml HTTP/1.1 | 77.89.149.137 | 656 | http | 401
</code></pre>
<p>While in my local log i'd see something like this:</p>
<pre><code>Started PUT "/reports/19" for 127.0.0.1 at 2011-06-21 15:27:01 +0100
Processing by ReportsController#update as XML
Parameters: {"report"=>{"workflow_status"=>"3"}, "id"=>"19"}
Person Load (0.9ms) SELECT "people".* FROM "people" WHERE "people"."email" = '[email protected]' LIMIT 1
Report Load (0.4ms) SELECT "reports".* FROM "reports" WHERE "reports"."id" = 19 LIMIT 1
DEPRECATION WARNING: Object#returning has been deprecated in favor of Object#tap. (called from update_report at /home/max/work/rails_apps/flamingo_container/flamingo/vendor/plugins/resource_this/lib/resource_this.rb:135)
Creating scope :open. Overwriting existing method Task.open.
Task Load (2.0ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = 14 LIMIT 1
Completed 200 OK in 1648ms (Views: 568.2ms | ActiveRecord: 3.2ms)
</code></pre>
<p>Ie with a lot more information, particularly the params, info from the router, generated sql, any templates rendered etc etc.</p>
<p>Does anyone know how i can get my heroku log to be as verbose as my development one? I've done the following already:</p>
<p>1) Set the log level in the relevant (rails 3) environment file:</p>
<pre><code>config.log_level = :debug
</code></pre>
<p>2) Told heroku to use a different logger level, as described on <a href="http://devcenter.heroku.com/articles/logging">http://devcenter.heroku.com/articles/logging</a></p>
<pre><code>heroku config:add LOG_LEVEL=DEBUG --app myapp #from CLI
</code></pre>
<p>Neither has made any difference...any ideas anyone?<br>
thanks, max</p> | 6,907,808 | 6 | 0 | null | 2011-06-21 14:37:54.577 UTC | 14 | 2016-09-18 22:39:15.717 UTC | null | null | null | null | 138,557 | null | 1 | 28 | ruby-on-rails|logging|heroku | 8,256 | <p>You're essentially wanting to show the SQL / params output in the Heroku logs. You can do this by adding the line shown below to the <code>config</code> block within your <code>production.rb</code> file:</p>
<pre><code>MyAppNameHere::Application.configure do
# add this line
config.logger = Logger.new(STDOUT)
end
</code></pre>
<p>By the way, setting the log level to debug just means that <code>Rails.logger.debug</code> will output to the logs when you're on Heroku</p> |
6,633,184 | How Can I Enable Root SSH Access in An Amazon EC2 Instance? | <p>This issue has been bugging me for the past several days.</p>
<p>I've been working on setting up a LAMP Server on Amazon EC2. The main issue is that I'm writing an application for a client that requires a lot of high-end processing, and Amazon EC2 seemed like a good choice.</p>
<p>Initially I started off with a basic AMI which really didn't have anything. I tried using root access to log into SSH (using WinSCP) and I was told to use ec2-user.</p>
<p>I tried using ec2-user, and I was able to log in. However, I still didn't have root access and couldn't install apache. I did some reason and I found out about the "sudo" command, and pretty much every article I read on this issue said to either use root access, or log into ec2-user and user sudo.</p>
<p>I have since tried again with a different AMI where LAMP was already installed. I was able to get it working, set up a database and start running a website off of it. However, I still needed to install some extensions. Namely, an API I'm trying to use for this application requires SOAP to be installed.</p>
<p>Here's my dilemma:</p>
<pre><code>/$ whereis soap
soap:
/$ whereis yum
yum: /usr/bin/yum /etc/yum /etc/yum.conf /usr/share/man/man8/yum.8.gz
/$ yum install php-soap
Loaded plugins: fastestmirror, priorities, security
You need to be root to perform this command.
/$ sudo yum install php-soap
sudo: sorry, you must have a tty to run sudo
Command 'sudo yum install php-soap' failed with return code 1 and error message sudo: sorry, you must have a tty to run sudo
</code></pre>
<p>I can't use yum because I don't have root access, and whenever I log into root it either tells me to use ec2-user or provide a password I don't have. The other alternative was to use sudo to make ec2-user act like root, but I always get the error 'sorry, you must have a tty to run sudo.' I've ran that error message online and that it seems I need to add a user to sudoers... which I can't do without root access.</p>
<p>This exact same issue plagued me on two separate AMI's. On the first I just received a message saying I had to log in as ec2-user (and I must have a tty to run sudo), while the second (with LAMP installed) required me to enter a password for root, and for user I got the same sudo error.</p>
<p>Here are the id's of the AMI's I used:</p>
<pre><code>ami-8c1fece5
ami-6ae81503
</code></pre>
<p>I also tried a third AMI later that also had LAMP installed... I couldn't even get into that one at all.</p>
<p>I did download my SSH key and used PuttyGen to convert it to a ppk file. I can log in successfully as ec2-user, but I cannot gain root access anywhere.</p>
<p>I have been looking around quite a bit for help on this, but every article I've read assumes that the user either has root access available or has sudo available on ec2-user. I don't have either. Is it just that I need a new image?</p>
<p>Any help would be greatly appreciated...</p> | 6,633,256 | 6 | 2 | null | 2011-07-09 06:33:22.173 UTC | 10 | 2018-07-09 20:13:32.113 UTC | null | null | null | null | 424,785 | null | 1 | 31 | ssh|amazon-ec2|lamp | 39,055 | <p>Use a real SSH client like <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html" rel="noreferrer">PuTTY</a>, not WinSCP, a file transfer client. All your problems will disappear.</p> |
6,743,849 | MongoDB: Unique index on array element's property | <p>I have a structure similar to this:</p>
<pre><code>class Cat {
int id;
List<Kitten> kittens;
}
class Kitten {
int id;
}
</code></pre>
<p>I'd like to prevent users from creating a cat with more than one kitten with the same id. I've tried creating an index as follows:</p>
<pre><code>db.Cats.ensureIndex({'id': 1, 'kittens.id': 1}, {unique:true})
</code></pre>
<p>But when I attempt to insert a badly-formatted cat, Mongo accepts it.</p>
<p>Am I missing something? can this even be done?</p> | 6,744,183 | 6 | 3 | null | 2011-07-19 07:48:34.153 UTC | 6 | 2020-07-02 12:16:55.567 UTC | null | null | null | null | 51,967 | null | 1 | 38 | mongodb | 26,208 | <p>As far as I know, unique indexes only enforce uniqueness across different documents, so this would throw a duplicate key error:</p>
<pre><code>db.cats.insert( { id: 123, kittens: [ { id: 456 } ] } )
db.cats.insert( { id: 123, kittens: [ { id: 456 } ] } )
</code></pre>
<p>But this is allowed:</p>
<pre><code>db.cats.insert( { id: 123, kittens: [ { id: 456 }, { id: 456 } ] } )
</code></pre>
<p>I'm not sure if there's any way enforce the constraint you need at the Mongo level, maybe it's something you could check in the application logic when you insert of update?</p> |
6,571,964 | Which tool to use to parse programming languages in Python? | <p>Which Python tool can you recommend to parse programming languages? It should allow for a readable representation of the language grammar inside the source, and it should be able to scale to complicated languages (something with a grammar as complex as e.g. Python itself).</p>
<p>When I search, I mostly find pyparsing, which I will be evaluating, but of course I'm interested in other alternatives.</p>
<p>Edit: Bonus points if it comes with good error reporting and source code locations attached to syntax tree elements.</p> | 6,612,248 | 9 | 2 | null | 2011-07-04 13:09:27.883 UTC | 18 | 2020-05-11 02:10:16.713 UTC | null | null | null | null | 334,761 | null | 1 | 38 | python|parsing | 21,268 | <p>I really like <a href="http://fdik.org/pyPEG/" rel="noreferrer" title="pyPEG: Parsing Expression Grammar for Python">pyPEG</a>. Its error reporting isn't very friendly, but it can add source code locations to the AST.</p>
<p>pyPEG doesn't have a separate lexer, which would make parsing Python itself hard (I think CPython recognises indent and dedent in the lexer), but I've used pyPEG to build a parser for subset of C# with surprisingly little work.</p>
<p>An example adapted from <a href="http://fdik.org/pyPEG/" rel="noreferrer" title="pyPEG: Parsing Expression Grammar for Python">fdik.org/pyPEG/</a>: A simple language like this:</p>
<pre><code>function fak(n) {
if (n==0) { // 0! is 1 by definition
return 1;
} else {
return n * fak(n - 1);
};
}
</code></pre>
<p>A pyPEG parser for that language:</p>
<pre><code>def comment(): return [re.compile(r"//.*"),
re.compile("/\*.*?\*/", re.S)]
def literal(): return re.compile(r'\d*\.\d*|\d+|".*?"')
def symbol(): return re.compile(r"\w+")
def operator(): return re.compile(r"\+|\-|\*|\/|\=\=")
def operation(): return symbol, operator, [literal, functioncall]
def expression(): return [literal, operation, functioncall]
def expressionlist(): return expression, -1, (",", expression)
def returnstatement(): return keyword("return"), expression
def ifstatement(): return (keyword("if"), "(", expression, ")", block,
keyword("else"), block)
def statement(): return [ifstatement, returnstatement], ";"
def block(): return "{", -2, statement, "}"
def parameterlist(): return "(", symbol, -1, (",", symbol), ")"
def functioncall(): return symbol, "(", expressionlist, ")"
def function(): return keyword("function"), symbol, parameterlist, block
def simpleLanguage(): return function
</code></pre> |
6,489,584 | Best way to turn a Lists of Eithers into an Either of Lists? | <p>I have some code like the below, where I have a list of Eithers, and I want to turn it into an Either of Lists ... in particular (in this case), if there are any Lefts in the list, then I return a Left of the list of them, otherwise I return a Right of the list of the rights.</p>
<pre><code>val maybe: List[Either[String, Int]] = getMaybe
val (strings, ints) = maybe.partition(_.isLeft)
strings.map(_.left.get) match {
case Nil => Right(ints.map(_.right.get))
case stringList => Left(stringList)
}
</code></pre>
<p>Calling <code>get</code> always makes me feel like I must be missing something.</p>
<p>Is there a more idiomatic way to do this?</p> | 6,490,882 | 9 | 2 | null | 2011-06-27 07:01:22.787 UTC | 9 | 2020-10-10 05:33:36.08 UTC | null | null | null | null | 436,820 | null | 1 | 41 | scala|either | 16,816 | <pre><code>data.partition(_.isLeft) match {
case (Nil, ints) => Right(for(Right(i) <- ints) yield i)
case (strings, _) => Left(for(Left(s) <- strings) yield s)
}
</code></pre>
<p>For one pass:</p>
<pre><code>data.partition(_.isLeft) match {
case (Nil, ints) => Right(for(Right(i) <- ints.view) yield i)
case (strings, _) => Left(for(Left(s) <- strings.view) yield s)
}
</code></pre> |
6,842,245 | converting date time to 24 hour format | <p>The time I get from the server is like <code>Jul 27, 2011 8:35:29 AM</code>. </p>
<p>I want to convert it to <code>yyyy-MM-dd HH:mm:ss</code>.</p>
<p>I also want the converted time to be in 24 hour format. Can any one give solution to this problem. The output I want to get is like <code>2011-07-27 08:35:29</code></p> | 6,842,384 | 12 | 0 | null | 2011-07-27 09:40:50.293 UTC | 20 | 2016-06-10 06:25:04.1 UTC | 2015-01-23 09:30:46.237 UTC | null | 1,245,337 | null | 790,928 | null | 1 | 90 | java|datetime | 279,321 | <p>Try this:</p>
<pre><code>String dateStr = "Jul 27, 2011 8:35:29 AM";
DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = readFormat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
String formattedDate = writeFormat.format(date);
}
</code></pre> |
42,553,039 | If (false == true) executes block when throwing exception is inside | <p>I have a rather strange problem that is occurring.</p>
<p>This is my code:</p>
<pre><code>private async Task BreakExpectedLogic()
{
bool test = false;
if (test == true)
{
Console.WriteLine("Hello!");
throw new Exception("BAD HASH!");
}
}
</code></pre>
<p>Seems really simple, it shouldn't hit the <code>Console.WriteLine</code> or the <code>throw</code>.
For some reason it's always hitting the <code>throw</code>.</p>
<p>If I move the <code>throw</code> into its own method then it works fine. My question is how is it ignoring the <code>if</code> block and hitting the <code>throw new Exception</code>:</p>
<p><a href="https://i.stack.imgur.com/XpP8d.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XpP8d.png" alt="Here is some evidence"></a></p>
<p><strong>EDIT 1:</strong> I've updated my code to include the signature, I've removed everything not related to this problem and ran it, it still happens.</p> | 42,553,184 | 2 | 22 | null | 2017-03-02 10:37:49.607 UTC | 15 | 2021-12-16 08:18:17.14 UTC | 2019-07-12 04:10:37.943 UTC | null | 4,217,744 | null | 2,315,360 | null | 1 | 156 | c#|.net|visual-studio|.net-core | 7,648 | <p>It seems to be the bug in <code>async</code> method, the code <strong>is not</strong> actually executed but debugger steps to the line with <code>throw</code> statement. If there are some lines of code before <code>throw</code> statement inside <code>if</code> these lines are ignored, debugger steps <strong>only</strong> to the line with <code>throw</code> statement.</p>
<p>Also, if you don't use variable - <code>if (false)</code> or <code>if (true == false)</code> then debugger steps to the correct line of code - to the closing curly brace.</p>
<p>This bug has been posted by <strong>@Matthew Watson</strong> to Visual Studio team (link is not available now).</p>
<p>Also, see similar question - <a href="https://stackoverflow.com/questions/42528458/condition-check-in-async-method">Condition check in async method</a></p>
<p><strong>EDIT (2017-10-06):</strong></p>
<p>Issue cannot be reproduced in VS 2017 15.3.5 using .Net Framework 4.7. Seems like VS team has fixed this issue.</p> |
45,333,177 | When to use forEach(_:) instead of for in? | <p>As documented in both <a href="https://developer.apple.com/documentation/swift/array/1689783-foreach" rel="noreferrer">Array</a> and <a href="https://developer.apple.com/documentation/swift/dictionary/1689593-foreach" rel="noreferrer">Dictionary</a> <code>forEach(_:)</code> Instance methods:</p>
<blockquote>
<p>Calls the given closure on each element in the <strong>sequence</strong> in the same
order as a for-in loop.</p>
</blockquote>
<p>Nevertheless, adapted from <a href="https://developer.apple.com/documentation/swift/sequence" rel="noreferrer">Sequence Overview</a>:</p>
<blockquote>
<p>A sequence is a list of values that you can step through one at a
time. <em>The most common way</em> to iterate over the elements of a sequence
is to use a <strong>for-in loop</strong>.</p>
</blockquote>
<p>Implying that iterating sequence by <code>forEach(_:)</code> or <code>for in</code>:</p>
<pre><code>let closedRange = 1...3
for element in closedRange { print(element) } // 1 2 3
closedRange.forEach { print($0) } // 1 2 3
</code></pre>
<p>Or (Array):</p>
<pre><code>let array = [1, 2, 3]
for element in array { print(element) } // 1 2 3
array.forEach { print($0) } // 1 2 3
</code></pre>
<p>Would gives the same output.</p>
<p>Why <code>forEach(_:)</code> even exist? i.e what is the benefit of using it instead of the <code>for in</code> loop? would they be the same from performance point view?</p>
<p>As an assumption, it could be a syntactic sugar especially when working with <em>functional programming</em>.</p> | 45,334,483 | 4 | 3 | null | 2017-07-26 16:58:07.133 UTC | 7 | 2021-03-22 12:15:31.95 UTC | 2017-07-26 17:38:24.05 UTC | null | 5,501,940 | null | 5,501,940 | null | 1 | 53 | swift|loops|foreach|sequence|for-in-loop | 19,406 | <p>There is no performance benefit offered by <code>forEach</code>. In fact, <a href="https://github.com/apple/swift/blob/1bae49950e9b4934b6fd4abecf68a10181e60736/stdlib/public/core/Sequence.swift#L1058" rel="noreferrer">if you look at the source code</a>, the <code>forEach</code> function actually simply performing <code>for</code>-<code>in</code>. For release builds, the performance overhead of this function over simply using <code>for</code>-<code>in</code> yourself is immaterial, though for debug builds, it results in an observable performance impact. </p>
<p>The main advantage of <code>forEach</code> is realized when you are doing functional programming, you can add it to a chain of functional calls, without having to save the prior result into a separate variable that you'd need if you used <code>for</code>-<code>in</code> syntax. So, instead of:</p>
<pre><code>let objects = array.map { ... }
.filter { ... }
for object in objects {
...
}
</code></pre>
<p>You can instead stay within functional programming patterns:</p>
<pre><code>array.map { ... }
.filter { ... }
.forEach { ... }
</code></pre>
<p>The result is functional code that is more concise with less syntactic noise.</p>
<p>FWIW, the documentation for <a href="https://developer.apple.com/documentation/swift/array/1689783-foreach" rel="noreferrer">Array</a>, <a href="https://developer.apple.com/documentation/swift/dictionary/1689593-foreach" rel="noreferrer">Dictionary</a>, and <a href="https://developer.apple.com/documentation/swift/sequence/2906738-foreach" rel="noreferrer">Sequence</a> all remind us of the limitations introduced by <code>forEach</code>, namely:</p>
<blockquote>
<ol>
<li><p>You cannot use a <code>break</code> or <code>continue</code> statement to exit the current
call of the <code>body</code> closure or skip subsequent calls.</p></li>
<li><p>Using the <code>return</code> statement in the <code>body</code> closure will exit only from
the current call to <code>body</code>, not from any outer scope, and won't skip
subsequent calls.</p></li>
</ol>
</blockquote> |
45,524,214 | How Do I Stop My Web Content From Shifting Left When The Vertical Scrollbar Appears? Roll-Up of Advice 2017 | <p>Many programmers have asked how to stop their web page content — especially their centered web page content (<code>margin: 0 auto;</code>) — from shifting (being pushed) horizontally when the vertical scroll bar appears. This has been an ongoing problem for Ajax users and people like me who use hidden divs and tabs to organize data.</p>
<p>The problem occurs when the currently displayed page changes such that the height of the displayed material (the inner window height) is suddenly greater than the physical window height.</p>
<p>The problem is exacerbated by the reality that all scrollbars are not created equal. Different browsers give their scroll bars different widths, and that difference cannot (or, at least, should not) be predicted. In short, the ideal solution is scrollbar width independent.</p>
<p>This, therefore, is a self-answered question that rolls all those answers with commentary on their usefullness (where possible) along with my own solution into a single answer as of August 5, 2017. I've marked as duplicates as many of the previous questions as I can find so that people can find a comprehensive discussion of the issue.</p>
<p><em>Please note that this answer addresses problems with BODY contents shifting. If you have a DIV with a fixed height that has shifting problems, you should set the DIV width to a fixed (<code>px</code>) width so its scrollbar floats above the text and add some right-hand padding to keep the text from falling beneath it. Contributors: <a href="https://stackoverflow.com/questions/18548465/prevent-scroll-bar-from-adding-up-to-the-width-of-page-on-chrome/18548709#18548709">Hashbrown</a>,
<a href="https://stackoverflow.com/questions/19208826/preventing-relayout-due-to-scrollbar/19209997#19209997">Avrahamcool</a>,
<a href="https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page/29579274#29579274">Edward Newsome</a></em></p> | 45,524,215 | 1 | 4 | null | 2017-08-05 16:39:36.99 UTC | 17 | 2022-09-16 15:23:48.877 UTC | 2017-08-05 20:55:34.97 UTC | null | 4,526,528 | null | 4,526,528 | null | 1 | 19 | javascript|jquery|html|css | 13,724 | <p>Before going into individual solutions, it should be mentioned that they break down into three categories: CSS-, CSS3-, and Javascript-based solutions.</p>
<p>The CSS solutions tend to be rigid but very predictable and very well supported.</p>
<p>The CSS3 solutions have a CPU calculation cost like Javascript, but are easy to implement. In years previous to 2017, however, they had sporadic support in browsers. That is improving over time. Ultimately, they will likely be the best solution, but my own investigations today have demonstrated the support simply isn't consistent enough yet and, besides, legacy browser support is non-existent.</p>
<p>The Javascript solutions (whether in straight Javascript or in jQuery) need extra coding to make them robust as they have no intrinsic support for (e.g.) window resizing. However, they're the most predictable and the most backward compatible while still preserving the aesthetics of the page. I consider the line for legacy browsers to be between IE6 and IE7. Frankly, my condolences to anyone still using a browser that old.</p>
<p>Please note that I <em><strong>have not</strong></em> included every CSS3 and Javascript solution previously posted to Stack Exchange. Some, though novel, had substantial weaknesses and so were not included here.</p>
<hr>
**Solution #1: The CSS Solution**
<p><em>Contributors: <a href="https://stackoverflow.com/questions/18548465/prevent-scroll-bar-from-adding-up-to-the-width-of-page-on-chrome/18548518#18548518">Hive7</a>, <a href="https://stackoverflow.com/questions/19208826/preventing-relayout-due-to-scrollbar/19209057#19209057">koningdavid</a>, <a href="https://stackoverflow.com/questions/9341465/prevent-a-centered-layout-from-shifting-its-position-when-scrollbar-appears/9341578#9341578">Christofer Eliasson</a>, <a href="https://stackoverflow.com/questions/7423706/keeping-a-web-page-centered-when-browser-scroll-bar-appears-and-disappears/7423725#7423725">Alec Gorge</a>, <a href="https://stackoverflow.com/questions/12968059/how-can-i-stop-the-scrollbar-from-displacing-my-page/12968136#12968136">Scott Bartell</a>, <a href="https://stackoverflow.com/questions/22212538/how-to-stop-bootstrap-3-1-1-from-shift-content-left-when-scroll-bar-appears/23730758#23730758">Shawn Taylor</a>, <a href="https://stackoverflow.com/questions/7369676/shifting-page-content-right-when-scroll-bar-becomes-visible/7369690#7369690">mVChr</a>, <a href="https://stackoverflow.com/questions/31716087/scrollbar-is-moving-page-content-to-the-left/31716367#31716367">fsn</a>, <a href="https://stackoverflow.com/questions/5605667/scrollbar-shifts-content/5605720#5605720">Damb</a>, <a href="https://stackoverflow.com/questions/5605667/scrollbar-shifts-content/5605792#5605792">Sparky</a>, <a href="https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page/7607206#7607206">Ruben</a>, <a href="https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page/1417954#1417954">Michael Krelin - hacker</a>, <a href="https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page/39335954#39335954">Melvin Guerrero</a></em></p>
<p>Force the srollbar to always be on.</p>
<pre><code><style>
html {
overflow-y: scroll;
}
</style>
</code></pre>
<p>This solution is basically guaranteed to always work (there are some exceptions, but they're very rare), but it is aesthetically unpleasing. The scrollbar will always be seen, whether it's needed or not. While concensus is to use this solution in the <code>html</code> tag, some people suggest using it in the <code>body</code> tag.</p>
<p><em>Consequences</em></p>
<p>Microsoft (IE10+) has implented floating scroll bars which means your page may not be centered in it like it would be in other browsers. However, this seems to be a very minor issue.</p>
<p>When using structured interfaces like FancyBox, Flex-Box, or Twitter Bootstrap Modal this can cause a double-scrollbar to appear as those interfaces create their own scrollbars.</p>
<p>Programmers should avoid using <code>overflow: scroll</code> as this will cause both the vertical and horizontal scrollbars to appear.</p>
<p><strong>Solution #1a: An Alternative</strong></p>
<p><em>Contributors: <a href="https://stackoverflow.com/questions/19208826/preventing-relayout-due-to-scrollbar/19209057#19209057">koningdavid</a>, <a href="https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page/32285511#32285511">Nikunj Madhogaria</a></em></p>
<p>A clever alternative, but one having only a minor aesthetic difference, is to do this:</p>
<pre><code><style>
html {
height: 101%;
}
</style>
</code></pre>
<p>This activates the scroll bar <em>background</em> but doesn't activate the scroll bar <em>tab</em> unless your vertical content actually overflows the bottom edge of the window. Nevertheless, it has the same weakness in that the scrollbar space is permanently consumed whether needed or not.</p>
<p><strong>Solution #1b: A More Modern Solution</strong></p>
<p><em>Contributors: <a href="https://stackoverflow.com/questions/18548465/prevent-scroll-bar-from-adding-up-to-the-width-of-page-on-chrome/39759119#39759119">Kyle Dumovic</a>, <a href="https://stackoverflow.com/questions/18548465/prevent-scroll-bar-from-adding-up-to-the-width-of-page-on-chrome/43912420#43912420">SimonDos</a></em></p>
<p>Browsers are beginning to pick up the use of the <code>overlay</code> value for scrollbars, mimicking the floating scrollbar of IE10+.</p>
<pre><code><style>
html {
overflow-y: overlay;
}
</style>
</code></pre>
<p>This solution mimics the floating scrollbar in IE10+, but it is not yet available in all browsers and still has some implementation quirks. This solution is known not to work for infrastructure environments like Bootstrap Modal.</p>
<hr>
**Solution #2: The CSS3 Solution**
<p>Use CSS3 to calculate widths. There are many ways to do this with advantages and disadvantages to each. Most disadvantages are due to (a) not knowing the actual scrollbar width, (b) dealing with screen resizing, and (c) the fact that CSS is slowly becoming yet-another-fully-functioning-programming language — like Javascript — but has not yet completely evolved into such. Whether or not it even makes sense for it to become such is a debate for another question.</p>
<blockquote>
<p>The argument that users may disable Javascript and so a CSS-only solution is preferable is becoming irrelevant. Client-side programming has become so ubiquitous that only the most paranoid of people are still disabling Javascript. Personally, I no longer consider this a tenable argument.</p>
</blockquote>
<p>It should be noted that some solutions modify <code>margin</code> and others modify <code>padding</code>. Those that modify <code>margin</code> have a common problem: if you have navigation bars, headers, borders, etc. that use a different color than the page background this solution will expose undesirable borders. It is likely that any solution using <code>margin</code> can be re-designed to use <code>padding</code> and vice-versa.</p>
<p><strong>Solution #2a: The HTML-based Solution</strong></p>
<p><em>Contributors: <a href="https://stackoverflow.com/questions/18548465/prevent-scroll-bar-from-adding-up-to-the-width-of-page-on-chrome/44000322#44000322">TranslucentCloud</a>, <a href="https://stackoverflow.com/questions/9341465/prevent-a-centered-layout-from-shifting-its-position-when-scrollbar-appears/42987298#42987298">Mihail Malostanidis</a></em></p>
<pre><code><style>
html {
margin-left: calc(100vw - 100%);
margin-right: 0;
}
</script>
</code></pre>
<p><strong>Solution #2b: The BODY-based Solution</strong></p>
<p><em>Contributors: <a href="https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page/39478654#39478654">Greg St.Onge</a>, <a href="https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page/25981719#25981719">Moesio</a>, <a href="https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page/42764105#42764105">Jonathan SI</a></em></p>
<pre><code><style>
body {
padding-left: 17px;
width: calc(100vw - 17px);
}
@media screen and (min-width: 1058px) {
body {
padding-left: 17px;
width: calc(100vw - 17px);
}
}
</style>
</code></pre>
<p><code>100vw</code> is 100% of the viewport width.</p>
<p><em>Consequences</em></p>
<p>Some users have suggested this solution creates undesirable screen noise when the window is resized (perhaps the calculation process is occuring multiple times during the resize process). A possible workaround is to avoid using <code>margin: 0 auto;</code> to center your content and instead use the following (the <code>1000px</code> and <code>500px</code> shown in the example represent your content maximum width and half that amount, respectively):</p>
<pre><code><style>
body {
margin-left: calc(50vw - 500px);
}
@media screen and (max-width: 1000px) {
body {
margin-left: 0;
}
}
</style>
</code></pre>
<p>This is a fixed-scrollbar-width solution, which isn't browser independent. To make it browser independent, you must include Javascript to determine the width of the scrollbars. An example that calculates the width but does not re-incorporate the value is:</p>
<p><em>Please note that the code snippet below has been posted multiple times on Stack Exchange and other locations on the Internet verbatim with no firm attribution.</em></p>
<pre><code>function scrollbarWidth() {
var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
// Append our div, do our calculation and then remove it
$('body').append(div);
var w1 = $('div', div).innerWidth();
div.css('overflow-y', 'scroll');
var w2 = $('div', div).innerWidth();
$(div).remove();
return (w1 - w2);
}
</code></pre>
<p><strong>Solution #2c: The DIV-based Solution</strong></p>
<p><em>Contributors: <a href="https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page/30293718#30293718">Rapti</a></em></p>
<p>Use CSS3 calculations applied directly to a container DIV element.</p>
<pre><code><body>
<div style="padding-left: calc(100vw - 100%);">
My Content
</div>
</body>
</code></pre>
<p><em>Consequences</em></p>
<p>Like all CSS3 solutions, this is not supported by all browsers. Even those browsers that support viewport calculations do not (as of the date of this writing) support its use arbitrarily.</p>
<p><strong>Solution #2d: Bootstrap Modal</strong></p>
<p><em>Contributors: <a href="https://stackoverflow.com/questions/9341465/prevent-a-centered-layout-from-shifting-its-position-when-scrollbar-appears/42987298#42987298">Mihail Malostanidis</a>, <a href="https://stackoverflow.com/questions/1417934/how-to-prevent-scrollbar-from-repositioning-web-page/31313306#31313306">kashesandr</a></em></p>
<p>Users of Twitter Bootstrap Modal have found it useful to apply the following CSS3 to their HTML element.</p>
<pre><code><style>
html {
width: 100%;
width: 100vw;
}
</style>
</code></pre>
<p>Another suggestion is to create a wrapper around your content wrapper that is used to auto-detect changes in the viewport width.</p>
<pre><code><style>
body {
overflow-x: hidden;
}
#wrap-wrap {
width: 100vw;
}
#content-wrap {
margin: 0 auto;
width: 800px;
}
</style>
</code></pre>
<p>I have not tried either of these as I do not use Bootstrap.</p>
<hr>
**Solution #3: The Javascript Solution**
<p><em>Contributors: <a href="https://stackoverflow.com/questions/5605667/scrollbar-shifts-content/5605759#5605759">Sam</a>, <a href="https://stackoverflow.com/users/4526528/jbh">JBH</a></em></p>
<p>This is my favorite solution as it deals with all the issues and is reasonably backward compatible to legacy browsers. Best of all, it's scrollbar-width independent.</p>
<pre><code><script>
function updateWindow(){
document.body.style.paddingLeft = (window.innerWidth - document.body.clientWidth);
document.body.onclick=function(){
document.body.style.paddingLeft = (window.innerWidth - document.body.clientWidth);
}
}
window.onload=updateWindow();
window.addEventListener("resize", updateWindow());
updateWindow();
</script>
</code></pre>
<p><em>Consequences</em></p>
<p>The final command to <code>updateWindow();</code> should occur just before the <code></body></code> tag to avoid problems with dynamically-loaded content such as Facebook Like-Boxes. It would seem that it's redundant to the <code>window.onload</code> event, but not every browser treats <code>onload</code> the same way. Some wait for asynchronous events. Others don't.</p>
<p>The function is executed each and every time a user clicks within the web page. Gratefully, modern computers are fast enough that this isn't much of an issue. Still….</p>
<p>Finally, the function should be executed after any div is asynchronously updated (AJAX). That is not shown in this example, but would be part of the ready-state condition. For example:</p>
<pre><code>xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
if(xmlhttp.responseText == 'false'){
//Error processing here
} else {
//Success processing here
updateWindow();
}
}
}
</code></pre>
<p><strong>Solution #3a: Measuring Scrollbar Widths</strong></p>
<p><em>Contributors: <a href="https://stackoverflow.com/questions/18548465/prevent-scroll-bar-from-adding-up-to-the-width-of-page-on-chrome/18548909#18548909">Lwyrn</a></em></p>
<p>This is a less valuable solution that takes the time to measure scrollbar widths.</p>
<pre><code><script>
var checkScrollBars = function(){
var b = $('body');
var normalw = 0;
var scrollw = 0;
if(b.prop('scrollHeight')>b.height()){
normalw = window.innerWidth;
scrollw = normalw - b.width();
$('#container').css({marginRight:'-'+scrollw+'px'});
}
}
</script>
<style>
body {
overflow-x: hidden;
}
</style>
</code></pre>
<p><em>Consequences</em></p>
<p>Like other solutions, this one permanently disables the horizontal scrollbar.</p> |
15,790,743 | Data.table meta-programming | <p>I think meta-programming is the right term here. </p>
<p>I want to be able to use data.table much like one would use MySQL in say a webapp. That is, web users use some web front-end (like Shiny server for example) to select a data-base, select columns to filter on, select columns to group-by, select columns to aggregate and aggregation functions. I want to use R and data.table as a backend for querying, aggregation etc. Assume that front end exists and R has these variables as character strings and they are validated etc. </p>
<p>I wrote the following function to build the data.table expression and use the parse/eval meta-programming functionality of R to run it. Is this a reasonable way to do this? </p>
<p>I includes all relevant code to test this. Source this code (after reading it for security!) and
run test_agg_meta() to test it. It is just a start. I could add more functionality. </p>
<p>But my main question is whether I am grossly over-thinking this. Is there is a more direct way to use data.table when all of the inputs are undetermined before hand without resorting to parse/eval meta-programming? </p>
<p>I am also aware of the "with" statement and some of the other sugarless-functional methods but don't know if they can take care of all cases. </p>
<pre><code>require(data.table)
fake_data<-function(num=12){
#make some fake data
x=1:num
lets=letters[1:num]
data=data.table(
u=rep(c("A","B","C"),floor(num/3)),
v=x %%2, w=lets, x=x, y=x^2, z=1-x)
return(data)
}
data_table_meta<-function(
#aggregate a data.table meta-programmatically
data_in=fake_data(),
filter_cols=NULL,
filter_min=NULL,
filter_max=NULL,
groupby_cols=NULL,
agg_cols=setdiff(names(data_in),groupby_cols),
agg_funcs=NULL,
verbose=F,
validate=T,
jsep="_"
){
all_cols=names(data_in)
if (validate) {
stopifnot(length(filter_cols) == length(filter_min))
stopifnot(length(filter_cols) == length(filter_max))
stopifnot(filter_cols %in% all_cols)
stopifnot(groupby_cols %in% all_cols)
stopifnot(length(intersect(agg_cols,groupby_cols)) == 0)
stopifnot((length(agg_cols) == length(agg_funcs)) | (length(agg_funcs)==1) | (length(agg_funcs)==0))
}
#build the command
#defaults
i_filter=""
j_select=""
n_agg_funcs=length(agg_funcs)
n_agg_cols=length(agg_cols)
n_groupby_cols=length(groupby_cols)
if (n_agg_funcs == 0) {
#NULL
print("NULL")
j_select=paste(agg_cols,collapse=",")
j_select=paste("list(",j_select,")")
} else {
agg_names=paste(agg_funcs,agg_cols,sep=jsep)
jsels=paste(agg_names,"=",agg_funcs,"(",agg_cols,")",sep="")
if (n_groupby_cols>0) jsels=c(jsels,"N_Rows_Aggregated=.N")
j_select=paste(jsels,collapse=",")
j_select=paste("list(",j_select,")")
}
groupby=""
if (n_groupby_cols>0) {
groupby=paste(groupby_cols,collapse=",")
groupby=paste("by=list(",groupby,")",sep="")
}
n_filter_cols=length(filter_cols)
if (n_filter_cols > 0) {
i_filters=rep("",n_filter_cols)
for (i in 1:n_filter_cols) {
i_filters[i]=paste(" (",filter_cols[i]," >= ",filter_min[i]," & ",filter_cols[i]," <= ",filter_max[i],") ",sep="")
}
i_filter=paste(i_filters,collapse="&")
}
command=paste("data_in[",i_filter,",",j_select,",",groupby,"]",sep="")
if (verbose == 2) {
print("all_cols:")
print(all_cols)
print("filter_cols:")
print(filter_cols)
print("agg_cols:")
print(agg_cols)
print("filter_min:")
print(filter_min)
print("filter_max:")
print(filter_max)
print("groupby_cols:")
print(groupby_cols)
print("agg_cols:")
print(agg_cols)
print("agg_funcs:")
print(agg_funcs)
print("i_filter")
print(i_filter)
print("j_select")
print(j_select)
print("groupby")
print(groupby)
print("command")
print(command)
}
print(paste("evaluating command:",command))
eval(parse(text=command))
}
my_agg<-function(data=fake_data()){
data_out=data[
i=x<=5,
j=list(
mean_x=mean(x),
mean_y=mean(y),
sum_z=sum(z),
N_Rows_Aggregated=.N
),
by=list(u,v)]
return(data_out)
}
my_agg_meta<-function(data=fake_data()){
#should give same results as my_agg
data_out=data_table_meta(data,
filter_cols=c("x"),
filter_min=c(-10000),
filter_max=c(5),
groupby_cols=c("u","v"),
agg_cols=c("x","y","z"),
agg_funcs=c("mean","mean","sum"),
verbose=T,
validate=T,
jsep="_")
return(data_out)
}
test_agg_meta<-function(){
stopifnot(all(my_agg()==my_agg_meta()))
print("Congrats, you passed the test")
}
</code></pre> | 15,791,747 | 1 | 2 | null | 2013-04-03 14:53:00.81 UTC | 24 | 2019-10-01 02:47:12.643 UTC | 2013-04-03 15:08:04.037 UTC | null | 1,024,495 | null | 1,024,495 | null | 1 | 23 | r|data.table | 2,139 | <p>While your functions certainly look interesting, I believe you are asking if there are other ways to go about it.<br>
Personally, I like to use something like this: </p>
<pre><code>## SAMPLE DATA
DT1 <- data.table(id=sample(LETTERS[1:4], 20, TRUE), Col1=1:20, Col2=rnorm(20))
DT2 <- data.table(id=sample(LETTERS[3:8], 20, TRUE), Col1=sample(100:500, 20), Col2=rnorm(20))
DT3 <- data.table(id=sample(LETTERS[19:20], 20, TRUE), Col1=sample(100:500, 20), Col2=rnorm(20))
</code></pre>
<h2>ACCESSING A TABLE BY REFERENCE TO THE TABLE NAME:</h2>
<p>This is straightforward, much like any object in <code>R</code></p>
<pre><code># use strings to select the table
tablesSelected <- "DT3"
# use get to access them
get(tablesSelected)
# and we can perform operations:
get(tablesSelected)[, list(C1mean=mean(Col1), C2mean=mean(Col2))]
</code></pre>
<h2>SELECTING COLUMNS BY REFERENCE</h2>
<p>To select columns by reference to their names, use the <code>.SDcols</code> argument.
Given a vector of column names: </p>
<pre><code>columnsSelected <- c("Col1", "Col2")
</code></pre>
<p>Assign that vector to the .SDcols argument: </p>
<pre><code>## Here we are simply accessing those columns
DT3[, .SD, .SDcols = columnsSelected]
</code></pre>
<p>We can also apply a function to each column named in the string vector: </p>
<pre><code>## apply a function to each column
DT3[, lapply(.SD, mean), .SDcols = columnsSelected]
</code></pre>
<p>Note that if our goal is simply to output the columns we can turn off <code>with</code>: </p>
<pre><code># This works for displaying
DT3[, columnsSelected, with=FALSE]
</code></pre>
<p>Note: a more "modern" way of doing this is to use the <code>..</code> shortcut to access <code>columnsSelected</code> from "up one level":</p>
<pre><code>DT3[ , ..columnsSelected]
</code></pre>
<p>However, if using <code>with=FALSE</code>, we cannot then operate directly on the columns in the usual fashion</p>
<pre><code>## This does NOT work:
DT3[, someFunc(columnsSelected), with=FALSE]
## This DOES work:
DT3[, someFunc(.SD), .SDcols=columnsSelected]
## This also works, but is less ideal, ie assigning to new columns is more cumbersome
DT3[, columnsSelected, with=FALSE][, someFunc(.SD)]
</code></pre>
<p>We can also use <code>get</code>, but it is a bit trickier.
<em>I am leaving it here for reference, but <code>.SDcols</code> is the way to go</em></p>
<pre><code>## we need to use `get`, but inside `j`
## AND IN A WRAPPER FUNCTION <~~~~~ THIS IS VITAL
DT3[, lapply(columnsSelected, function(.col) get(.col))]
## We can execute functions on the columns:
DT3[, lapply(columnsSelected, function(.col) mean( get(.col) ))]
## And of course, we can use more involved-functions, much like any *ply call:
# using .SDcols
DT3[, lapply(.SD, function(.col) c(mean(.col) + 2*sd(.col), mean(.col) - 2*sd(.col))), .SDcols = columnsSelected]
# using `get` and assigning the value to a var.
# Note that this method has memory drawbacks, so using .SDcols is preferred
DT3[, lapply(columnsSelected, function(.col) {TheCol <- get(.col); c(mean(TheCol) + 2*sd(TheCol), mean(TheCol) - 2*sd(TheCol))})]
</code></pre>
<p>For reference, if you try the following, you will notice that they do not produce the results we are after. </p>
<pre><code> ## this DOES NOT work (need ..columnsSelected)
DT3[, columnsSelected]
## netiher does this
DT3[, eval(columnsSelected)]
## still does not work:
DT3[, lapply(columnsSelected, get)]
</code></pre>
<p>If you want to change the name of the columns: </p>
<pre><code># Using the `.SDcols` method: change names using `setnames` (lowercase "n")
DT3[, setnames(.SD, c("new.Name1", "new.Name2")), .SDcols =columnsSelected]
# Using the `get` method:
## The names of the new columns will be the names of the `columnsSelected` vector
## Thus, if we want to preserve the names, use the following:
names(columnsSelected) <- columnsSelected
DT3[, lapply(columnsSelected, function(.col) get(.col))]
## we can also use this trick to give the columns new names
names(columnsSelected) <- c("new.Name1", "new.Name2")
DT3[, lapply(columnsSelected, function(.col) get(.col))]
</code></pre>
<p><em>Clearly, using .SDcols is easier and more elegant.</em></p>
<h3>What about <code>by</code>?</h3>
<pre><code># `by` is straight forward, you can use a vector of strings in the `by` argument.
# lets add another column to show how to use two columns in `by`
DT3[, secondID := sample(letters[1:2], 20, TRUE)]
# here is our string vector:
byCols <- c("id", "secondID")
# and here is our call
DT3[, lapply(columnsSelected, function(.col) mean(get(.col))), by=byCols]
</code></pre>
<hr>
<h2>PUTTING IT ALL TOGETHER</h2>
<p>We can access the data.table by reference to its name and then select its columns also by name: </p>
<pre><code>get(tablesSelected)[, .SD, .SDcols=columnsSelected]
## OR WITH MULTIPLE TABLES
tablesSelected <- c("DT1", "DT3")
lapply(tablesSelected, function(.T) get(.T)[, .SD, .SDcols=columnsSelected])
# we may want to name the vector for neatness, since
# the resulting list inherits the names.
names(tablesSelected) <- tablesSelected
</code></pre>
<h3>THIS IS THE BEST PART:</h3>
<p>Since so much in <code>data.table</code> is pass-by-reference, it is easy to have a list of tables, a separate list of columns to add and yet another list of columns to operate on, and put all together to add perform similar operations -- but with different inputs -- on all your tables.
As opposed to doing something similar with <code>data.frame</code>, there is no need to reassign the end result. </p>
<pre><code>newColumnsToAdd <- c("UpperBound", "LowerBound")
FunctionToExecute <- function(vec) c(mean(vec) - 2*sd(vec), mean(vec) + 2*sd(vec))
# note the list of column names per table!
columnsUsingPerTable <- list("DT1" = "Col1", DT2 = "Col2", DT3 = "Col1")
tablesSelected <- names(columnsUsingPerTable)
byCols <- c("id")
# TADA:
dummyVar <- # I use `dummyVar` because I do not want to display the output
lapply(tablesSelected, function(.T)
get(.T)[, c(newColumnsToAdd) := lapply(.SD, FunctionToExecute), .SDcols=columnsUsingPerTable[[.T]], by=byCols ] )
# Take a look at the tables now:
DT1
DT2
DT3
</code></pre> |
32,738,879 | Why is there no reserving constructor for std::string? | <p>There are several <a href="http://en.cppreference.com/w/cpp/string/basic_string">constructors</a> for <code>std::string</code>. I was looking for a way to avoid reallocation and I'm surprised that there is a fill constructor but no "reserve" constructor.</p>
<pre><code> std::string (size_t n, char c);
</code></pre>
<p>but no </p>
<pre><code> std::string (size_t n);
</code></pre>
<p>So do I have to call <code>reserve()</code> after it already allocated the default (16 bytes in my case), just to immediately reallocate it?</p>
<p>Is there a reason why there is no such constructor to reserve space directly when the object is created, instead of having to do it manually? Or am I missing something and there is some way to do this?</p>
<p>Using the fill constructor is a waste of time, because it will loop through the memory just to get overwritten, and also cause a wrong size, because <code>s.length()</code> reports <code>N</code> instead of <code>0</code>.</p> | 32,739,273 | 3 | 20 | null | 2015-09-23 11:52:28.02 UTC | 5 | 2019-08-28 14:02:28.687 UTC | 2015-09-23 13:49:16.78 UTC | null | 2,692,339 | null | 2,282,011 | null | 1 | 39 | c++|string | 8,650 | <p>This is all guesswork, but I'll try.</p>
<p>If you already know the size of the string that you need, you will most likely be copying data from somewhere else, e.g. from another string. In that case, you can call one of the constructors that accept <code>char *</code> or <code>const std::string &</code> to copy the data immediately.</p>
<p>Also, I can't see why using <code>reserve</code> right after constructing a string is a bad thing. While it is implementation-defined, I would assume that it would make sense for this code:</p>
<pre><code>std::string str;
str.reserve(100);
</code></pre>
<p>to allocate memory for a total of 100 elements, not 116 (as in "allocate 16 first, then free them and allocate 100 more"), thus having no performance impact over the non-existent reserve constructor.</p>
<p>Also, if you just want an <em>empty</em> string without the default allocation at all, you can presumably use <code>std::string str(0, ' ');</code> which invalidates the "<em>Using the fill constructor is a waste of time</em>" point.</p> |
50,746,465 | How do I call SQLitePCL.Batteries.Init().? | <p>I am attempting to create an SQLite database for my application and have come across this error. </p>
<blockquote>
<p>System.Exception: 'You need to call SQLitePCL.raw.SetProvider(). If
you are using a bundle package, this is done by calling
SQLitePCL.Batteries.Init().'</p>
</blockquote>
<p>I created a simple console app the run the exact same code for creation, with no issues. The code looks like this!</p>
<pre><code>using (var dataContext = new SampleDBContext())
{
dataContext.Accounts.Add(new Account() { AccountName = name, AccountBalance = balance });
}
public class SampleDBContext : DbContext
{
private static bool _created = false;
public SampleDBContext()
{
if (!_created)
{
_created = true;
Database.EnsureDeleted();
Database.EnsureCreated();
}
}
protected override void OnConfiguring(DbContextOptionsBuilder optionbuilder)
{
optionbuilder.UseSqlite(@"Data Source="Source folder"\Database.db");
}
public DbSet<Account> Accounts { get; set; }
}
</code></pre>
<p>Can anyone shed any light on the issue? I installed the same Nuget Packages on both projects, the only difference between the two is the Data Source and the POCO classes I used for the database.</p>
<p>Thanks.</p>
<p><strong>Edit</strong>
My program currently consists of a <code>Console application</code> that references a <code>.Net Framework Class Library</code>. The <code>Console application</code> simple has a constructor that looks like this:</p>
<pre><code>public Program()
{
using (var db = new FinancialContext())
{
db.Accounts.Add(new Account() { AccountName = "RBS", AccountBalance=20 });
}
}
</code></pre>
<p>The Class Library has a FinancialContext as Follows:</p>
<pre><code>public class FinancialContext : DbContext
{
public DbSet<Account> Accounts { get; set; }
public FinancialContext()
{
# Database.EnsureDeleted();
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionbuilder)
{
optionbuilder.UseSqlite(@"Data Source="Some Source Folder"\Database.db");
}
}
</code></pre>
<p>The Above error is shown at the # symbol point, is there a problem with the way I am coding? I would really like to know what the issue is so I can fix it properly rather than apply a 'fix'. Also I tried the suggestion in the comments, but putting the code line <code>SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_e_sqlite3());</code> in the <code>Console Application</code> gave the error <code>SQLitePCL</code> is not in the current context, which leaves me thinking I am missing a reference?</p> | 51,570,139 | 8 | 3 | null | 2018-06-07 16:48:38.697 UTC | 1 | 2022-03-17 14:22:54.22 UTC | 2018-06-07 22:39:34.737 UTC | null | 9,285,310 | null | 9,285,310 | null | 1 | 60 | c#|entity-framework|sqlite | 35,624 | <p>This happened to me when I tried to avoid any additional dependencies and went for the <code>Microsoft.EntityFrameworkCore.Sqlite.Core</code> package.</p>
<p>You should install and use the <code>Microsoft.EntityFrameworkCore.Sqlite</code> package instead, which has a dependency upon the <code>SQLitePCLRaw</code> package.</p> |
10,373,331 | NSOperation vs Grand Central Dispatch | <p>I'm learning about concurrent programming for iOS. So far I've read about <a href="http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/"><code>NSOperation</code>/<code>NSOperationQueue</code></a> and <a href="https://en.wikipedia.org/wiki/Grand_Central_Dispatch"><code>GCD</code></a>. <strong>What are the reasons for using <code>NSOperationQueue</code> over <code>GCD</code> and vice versa?</strong></p>
<p>Sounds like both <code>GCD</code> and <code>NSOperationQueue</code> abstract away the explicit creation of <code>NSThreads</code> from the user. However the relationship between the two approaches isn't clear to me so any feedback to appreciated!</p> | 10,375,616 | 9 | 3 | null | 2012-04-29 15:24:46.693 UTC | 228 | 2021-10-03 13:30:50.2 UTC | null | null | null | null | 879,664 | null | 1 | 486 | ios|concurrency|grand-central-dispatch|nsoperation|nsoperationqueue | 129,860 | <p><code>GCD</code> is a low-level C-based API that enables very simple use of a task-based concurrency model. <code>NSOperation</code> and <code>NSOperationQueue</code> are Objective-C classes that do a similar thing. <code>NSOperation</code> was introduced first, but as of <a href="https://developer.apple.com/documentation/foundation/nsoperation" rel="noreferrer">10.5</a> and <a href="https://developer.apple.com/documentation/foundation/nsoperation" rel="noreferrer">iOS 2</a>, <code>NSOperationQueue</code> and friends are internally implemented using <code>GCD</code>.</p>
<p>In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use <code>NSOperationQueue</code> instead of <code>GCD</code>, unless you need to do something that <code>NSOperationQueue</code> doesn't support.</p>
<p>Note that <code>NSOperationQueue</code> isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with <code>NSOperationQueue</code> that take a lot of work with pure <code>GCD</code>. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with <code>NSOperation</code>, very difficult with <code>GCD</code>.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with <code>NSOperation</code>. Take advantage of their work unless you have a reason not to.</p>
<p><strong>Caveat</strong>:
On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that <code>NSOperationQueue</code> provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.</p> |
25,145,552 | TFIDF for Large Dataset | <p>I have a corpus which has around 8 million news articles, I need to get the TFIDF representation of them as a sparse matrix. I have been able to do that using scikit-learn for relatively lower number of samples, but I believe it can't be used for such a huge dataset as it loads the input matrix into memory first and that's an expensive process.</p>
<p>Does anyone know, what would be the best way to extract out the TFIDF vectors for large datasets?</p> | 25,168,689 | 4 | 6 | null | 2014-08-05 18:09:09.77 UTC | 16 | 2021-06-01 03:16:36.563 UTC | null | null | null | null | 1,452,757 | null | 1 | 43 | python|lucene|nlp|scikit-learn|tf-idf | 29,697 | <p>Gensim has an efficient <a href="http://radimrehurek.com/gensim/intro.html" rel="noreferrer">tf-idf model</a> and does not need to have everything in memory at once.</p>
<p>Your corpus simply needs to be an iterable, so it does not need to have the whole corpus in memory at a time.</p>
<p>The <a href="https://github.com/piskvorky/gensim/blob/develop/gensim/scripts/make_wikicorpus.py" rel="noreferrer">make_wiki script</a> runs over Wikipedia in about 50m on a laptop according to the comments.</p> |
46,341,083 | Does asking twice give bad performance? | <p>I have a function:</p>
<pre><code>function getMilk() {
if($condition == true)
return "Milk for you, madam";
return false;
}
</code></pre>
<p>Example 1:</p>
<pre><code>if(getMilk())
echo getMilk();
</code></pre>
<p>Does the first example make PHP run for milk twice?</p>
<p>Example 2:</p>
<pre><code>echo getMilk(); // don't check for milk first, just get it if they have it
</code></pre>
<p>If I was PHP I would rather get the second example. Then I wouldn't have to run to the store checking for milk, then running once more to get it. </p>
<p>Would example 2 be faster/better, or doesn't it matter?</p> | 46,341,182 | 3 | 9 | null | 2017-09-21 10:05:38.537 UTC | 5 | 2018-10-31 19:00:48.853 UTC | 2018-10-31 19:00:48.853 UTC | null | 7,057,719 | null | 7,057,719 | null | 1 | 28 | php | 4,172 | <p>Yes, you are calling the function twice. Avoid doing that (because the function can be expensive to call) by doing one of the following:</p>
<pre><code>$getMilk = getMilk();
if($getMilk) echo $getMilk;
</code></pre>
<p>You can reduce this to a one line (but unreadable) format:</p>
<pre><code>if ($getMilk = getMilk()) echo $getMilk;
</code></pre>
<p>You can also use an inline <code>if</code> ternary, with a fallthrough:</p>
<pre><code>echo getMilk()?:""; //Will echo the result of getMilk() if there is any or nothing.
</code></pre> |
31,695,900 | What is the purpose of nameof? | <p>Version 6.0 got a new feature of <code>nameof</code>, but I can't understand the purpose of it, as it just takes the variable name and changes it to a string on compilation.</p>
<p>I thought it might have some purpose when using <code><T></code> but when I try to <code>nameof(T)</code> it just prints me a <code>T</code> instead of the used type.</p>
<p>Any idea on the purpose?</p> | 31,695,982 | 17 | 5 | null | 2015-07-29 09:04:10.41 UTC | 58 | 2021-09-15 04:39:49.63 UTC | 2015-08-03 18:40:01.71 UTC | null | 993,547 | null | 2,363,586 | null | 1 | 342 | c#|.net|c#-6.0|nameof | 205,837 | <p>What about cases where you want to reuse the name of a property, for example when throwing exception based on a property name, or handling a <code>PropertyChanged</code> event. There are numerous cases where you would want to have the name of the property.</p>
<p>Take this example:</p>
<pre><code>switch (e.PropertyName)
{
case nameof(SomeProperty):
{ break; }
// opposed to
case "SomeOtherProperty":
{ break; }
}
</code></pre>
<p>In the first case, renaming <code>SomeProperty</code> will cause a compilation error if you don't change both the property definition and the <code>nameof(SomeProperty)</code> expression. In the second case, renaming <code>SomeOtherProperty</code> or altering the <code>"SomeOtherProperty"</code> string will result in silently broken runtime behavior, with no error or warning at build time.</p>
<p>This is a very useful way to keep your code compiling and bug free (sort-of).</p>
<p>(A <a href="https://blogs.msdn.microsoft.com/ericlippert/2009/05/21/in-foof-we-trust-a-dialogue/" rel="noreferrer">very nice article from Eric Lippert</a> why <code>infoof</code> didn't make it, while <code>nameof</code> did)</p> |
33,746,434 | Double pointer vs array of pointers(**array vs *array[]) | <p>Im not clearly sure what is the difference between those 2. My professor wrote that **array is same as *array[] and we were presented an example where he used **array (so after classes I tried exchanging that with *array[] and it didn't work), could anyone tell me if those 2 are actually the same as he wrote?? Anyway the class was about dynamic memory allocation</p>
<p>@As soon as I changed the double pointer, this line started throwing error</p>
<pre><code> lines = malloc(sizeof(char*));
</code></pre>
<p>and a few others where the memory is beeing reallocated</p>
<p>@2 Hell yeah, here's the whole code</p>
<p>And for those comments bellow, nope there is nothing inside [] because his statement was</p>
<pre><code> **array = *array[]
</code></pre>
<p>BIG UPDATE</p>
<p>I am so sorry for any inconvenience, I was just too tired at the time of writing this post, here is the whole code with no edits</p>
<pre><code> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **lines; // global text buffer, organized as an array of lines
// --------------------------------------------------------------------------------
// initialize global buffer
void initialize()
{
lines = malloc(sizeof(char*));
lines[0] = NULL;
}
// --------------------------------------------------------------------------------
// return number of lines in buffer
int countLines()
{
int count = 0;
while(lines[count++]) ;
return count-1;
}
// --------------------------------------------------------------------------------
// print one line
void printLine(int line)
{
printf("Line %d: %p %p %s\n",line, &lines[line], lines[line], lines[line]);
}
// --------------------------------------------------------------------------------
// print all lines
void printAll()
{
int num_lines = countLines();
int line = 0;
printf("----- %d line(s) ----\n",num_lines);
while (line < num_lines)
printLine(line++);
printf("---------------------\n");
}
// --------------------------------------------------------------------------------
// free whole buffer
void freeAll()
{
int line = countLines();
while (line >= 0)
free(lines[line--]);
free(lines);
}
// --------------------------------------------------------------------------------
// insert a line before the line specified
void insertLine(int line, char *str)
{
int num_lines = countLines();
// increase lines size by one line pointer:
lines = realloc(lines, (num_lines+2) * sizeof(char*));
// move line pointers backwards:
memmove(&lines[line+1], &lines[line], (num_lines-line+1)*sizeof(char*));
// insert the new line:
lines[line] = malloc(strlen(str)+1);
strcpy(lines[line],str);
}
// --------------------------------------------------------------------------------
// remove the specified line
void removeLine(int line)
{
int num_lines = countLines();
// free the memory used by this line:
free(lines[line]);
// move line pointers forward:
memmove(&lines[line], &lines[line+1], (num_lines-line+1)*sizeof(char*));
// decrease lines size by one line pointer:
lines = realloc(lines, num_lines * sizeof(char*));
}
// --------------------------------------------------------------------------------
// insert a string into specified line at specified column
void insertString(int line, int col, char *str)
{
// make room for the new string:
lines[line] = realloc(lines[line], strlen(lines[line])+strlen(str)+1);
// move characters after col to the end:
memmove(lines[line]+col+strlen(str), lines[line]+col, strlen(lines[line])-col);
// insert string (without terminating 0-byte):
memmove(lines[line]+col, str, strlen(str));
}
// --------------------------------------------------------------------------------
// MAIN program
int main()
{
initialize();
printAll();
insertLine(0,"Das ist");
printAll();
insertLine(1,"Text");
printAll();
insertLine(1,"ein");
printAll();
insertLine(2,"kurzer");
printAll();
printf("lines[2][4] = %c\n",lines[2][4]);
insertString(2,0,"ziemlich ");
printAll();
removeLine(2);
printAll();
freeAll();
return 0;
}
</code></pre> | 33,748,099 | 3 | 14 | null | 2015-11-16 23:17:16.417 UTC | 9 | 2022-09-17 19:44:39.803 UTC | 2015-11-17 08:59:44.597 UTC | null | 2,599,301 | null | 2,599,301 | null | 1 | 19 | c|pointers|multidimensional-array|dynamic-memory-allocation | 52,017 | <p>If the code you reference in your question was given to you by your professor as an example of the use of pointer arrays of pointers to pointers, I'm not sure how much good that class will actually do. I suspect it was either provided as a debugging exercise or it may have been your attempt at a solution. Regardless, if you simply compile with <em>Warnings</em> enabled, you will find a number of problems that need attention before you advance to debugging your code.</p>
<p>Regarding the code you reference, while you are free to use a global text buffer, you are far better served by not using a global buffer and passing a pointer to your data as required. There are some instances, various callback functions, etc. that require global data, but as a rule of thumb, those are the exception and not the rule.</p>
<p>Your question basically boils down to "How do I properly use an array of pointers and double-pointers (pointer-to-pointer-to-type) variables. There is no way the topic can be completely covered in one answer because there are far too many situations and contexts where one or the other can be (or should be) used and why. However, a few examples will hopefully help you understand the basic differences.</p>
<p>Starting with the <em>array of pointers to type</em> (e.g. <code>char *array[]</code>). It is generally seen in that form as a function argument. When declared as a variable it is followed with an initialization. e.g.:</p>
<pre><code>char *array[] = { "The quick",
"brown fox",
"jumps over",
"the lazy dog." };
</code></pre>
<p><code>char *array[];</code> by itself as a variable declaration is invalid due to the missing array size between <code>[..]</code>. When used globally, as in your example, the compiler will accept the declaration, but will <em>warn</em> the declaration is assumed to have <em>one element</em>.</p>
<p>The elements of <code>array</code> declared above are pointers to type char. Specifically, the elements are pointers to the <em>string-literals</em> created by the declaration. Each of the strings can be accessed by the associated pointer in <code>array</code> as <code>array[0], ... array[3]</code>.</p>
<p>A <em>pointer to pointer to type</em> (double-pointer), is exactly what its name implies. It is a <em>pointer</em>, that holds <em>a pointer</em> as its value. In basic terms, it is a pointer that points to another pointer. It can be used to access the members of the array above by assigning the address of <code>array</code> like:</p>
<pre><code>char **p = array;
</code></pre>
<p>Where <code>p[1]</code> or <code>*(p + 1)</code> points to <code>"brown fox"</code>, etc. </p>
<p>Alternatively, a number of pointer to pointer to type can be dynamically allocated and used to create an array of pointers to type, that can then be allocated and reallocated to handle access or storage of an unknown number of elements. For example, a brief example to read an unknown number of lines from <code>stdin</code>, you might see:</p>
<pre><code>#define MAXL 128
#define MAXC 512
...
char **lines = NULL;
char buf[MAXC] = {0};
lines = malloc (MAXL * sizeof *lines);
size_t index = 0;
...
while (fgets (buf, MAXC, stdin)) {
lines[index++] = strdup (buf);
if (index == MAXL)
/* reallocate lines */
}
</code></pre>
<p>Above you have <code>lines</code>, a pointer-to-pointer-to-char, initially <code>NULL</code>, that is use to allocate <code>MAXL</code> (128) pointers-to-char. Lines are then read from <code>stdin</code> into <code>buf</code>, after each successful read, memory is allocated to hold the contents of <code>buf</code> and the resulting start address for each block of memory is assigned to each pointer <code>line[index]</code> where <code>index</code> is <code>0-127</code>, and upon increment of <code>index</code> to 128, <code>index</code> is reallocated to provide additional pointers and the read continues.</p>
<p>What makes the topic larger than can be handled in any one answer is that an <em>array of pointers</em> or <em>pointer to pointer to type</em> can be to any <code>type</code>. (<code>int</code>, <code>struct</code>, or as a member of a struct to different type, or <code>function</code>, etc...) They can be used <em>linked-lists</em>, in the return of directory listings (e.g <code>opendir</code>), or in any additional number of ways. They can be statically initialized, dynamically allocated, passed as function parameters, etc... There are just far too many different contexts to cover them all. But in all instances, they will follow the general rules seen here and in the other answer here and in 1,000's more answers here on StackOverflow. </p>
<p>I'll end with a short example you can use to look at the different basic uses of the array and double-pointer. I have provided additional comments in the source. This just provides a handful of different basic uses and of static declaration and dynamic allocation:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
/* array is a static array of 4 pointers to char, initialized to the
4 string-literals that a part of the declaration */
char *array[] = { "The quick",
"brown fox",
"jumps over",
"the lazy dog." };
/* p is a pointer-to-pointer-to-char assigned the address of array */
char **p = array;
/* lines is a pointer-to-pointer-to-char initialized to NULL, used
below to allocate 8 pointers and storage to hold 2 copes of array */
char **lines = NULL;
size_t narray = sizeof array/sizeof *array;
size_t i;
printf ("\nprinting each string-literal at the address stored by\n"
"each pointer in the array of ponters named 'array':\n\n");
for (i = 0; i < narray; i++)
printf (" %s\n", array[i]);
printf ("\nprinting each string using a pointer to pointer to char 'p':\n\n");
for (i = 0; i < narray; i++, p++)
printf (" %s\n", *p);
p = array;
printf ("\nprinting each line using a pointer to pointer"
" to char 'p' with array notation:\n\n");
for (i = 0; i < narray; i++)
printf (" %s\n", p[i]);
/* allocate 8 pointers to char */
lines = malloc (2 * narray * sizeof *lines);
/* allocate memory and copy 1st 4-strings to lines (long way) */
for (i = 0; i < narray; i++) {
size_t len = strlen (array[i]);
lines[i] = malloc (len * sizeof **lines + 1);
strncpy (lines[i], array[i], len);
lines[i][len] = 0;
}
/* allocate memory and copy 1st 4-strings to lines
(using strdup - short way) */
// for (i = 0; i < narray; i++)
// lines[i] = strdup (array[i]);
/* allocate memory and copy again as last 4-strings in lines */
p = array;
for (i = 0; i < narray; i++, p++)
lines[i+4] = strdup (*p);
p = lines; /* p now points to lines instead of array */
printf ("\nprinting each allocated line in 'lines' using pointer 'p':\n\n");
for (i = 0; i < 2 * narray; i++)
printf (" %s\n", p[i]);
/* free allocated memory */
for (i = 0; i < 2 * narray; i++)
free (lines[i]);
free (lines);
return 0;
}
</code></pre>
<p>Let me know if you have any questions. It a large topic with a relatively small set of rules that can be applied in whole lot of different ways and in different contexts.</p> |
53,292,263 | Send PathVariable @PostMapping in postman | <p>I want send path variable in post mapping, in postman software.I select post mapping body and then how to do? I checked with <a href="https://stackoverflow.com/questions/13715811/requestparam-vs-pathvariable">@RequestParam vs @PathVariable</a> example,all answers for get method, But I need answer for post method.</p>
<pre><code>@RestController
@RequestMapping("api/v1/customers")
public class CustomerController {
@PostMapping("/{code}")
public String postRequest(@PathVariable String code,@RequestBody CustomerDTO dto){
System.out.println(dto);
System.out.println(code);
return "Something";
}
}
</code></pre> | 53,292,496 | 3 | 7 | null | 2018-11-14 02:19:02.69 UTC | 5 | 2020-03-15 12:55:14.073 UTC | 2018-11-14 02:53:16.61 UTC | null | 10,649,469 | null | 10,649,469 | null | 1 | 11 | java|spring|spring-mvc | 51,727 | <p><a href="https://i.stack.imgur.com/L7Hly.png" rel="noreferrer"><img src="https://i.stack.imgur.com/L7Hly.png" alt="enter image description here"></a></p>
<p>select post -> add the url -> select body -> choose raw -> select JSON(application/json) -> add your json data -> click send </p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.