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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15,288,519 | Set minimum and maximum characters in a regular expression | <p>I've written a <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a> that matches any number of letters with any number of single spaces between the letters. I would like that regular expression to also enforce a minimum and maximum number of characters, but I'm not sure how to do that (or if it's possible).</p>
<p>My regular expression is:</p>
<pre><code>[A-Za-z](\s?[A-Za-z])+
</code></pre>
<p>I realized it was only matching two sets of letters surrounding a single space, so I modified it slightly to fix that. The original question is still the same though.</p>
<p>Is there a way to enforce a minimum of three characters and a maximum of 30?</p> | 15,288,528 | 4 | 6 | null | 2013-03-08 07:03:18.073 UTC | 5 | 2022-07-02 12:43:16.537 UTC | 2019-07-31 16:03:14.403 UTC | null | 63,550 | null | 1,313,268 | null | 1 | 29 | java|regex | 85,647 | <p>Yes</p>
<p>Just like <code>+</code> means one or more you can use <code>{3,30}</code> to match between 3 and 30</p>
<p>For example <code>[a-z]{3,30}</code> matches between 3 and 30 lowercase alphabet letters</p>
<p>From the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html">documentation of the Pattern class</a></p>
<blockquote>
<pre><code>X{n,m} X, at least n but not more than m times
</code></pre>
</blockquote>
<p>In your case, matching 3-30 letters followed by spaces could be accomplished with:</p>
<pre><code>([a-zA-Z]\s){3,30}
</code></pre>
<p>If you require trailing whitespace, if you don't you can use: (2-29 times letter+space, then letter)</p>
<pre><code>([a-zA-Z]\s){2,29}[a-zA-Z]
</code></pre>
<p>If you'd like whitespaces to count as characters you need to divide that number by 2 to get</p>
<pre><code>([a-zA-Z]\s){1,14}[a-zA-Z]
</code></pre>
<p>You can add <code>\s?</code> to that last one if the trailing whitespace is optional. These were all tested on <a href="http://www.regexplanet.com/advanced/java/index.html">RegexPlanet</a></p>
<p>If you'd like the entire string altogether to be between 3 and 30 characters you can use lookaheads adding <code>(?=^.{3,30}$)</code> at the beginning of the RegExp and removing the other size limitations</p>
<p>All that said, in all honestly I'd probably just test the <code>String</code>'s <code>.length</code> property. It's more readable.</p> |
15,418,467 | How can I write these variables into one line of code in C#? | <p>I am new to C#, literally on page 50, and i am curious as to how to write these variables in one line of code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace consoleHelloWorld
{
class Program
{
static void Main(string[] args)
{
int mon = DateTime.Today.Month;
int da = DateTime.Today.Day;
int yer = DateTime.Today.Year;
var time = DateTime.Now;
Console.Write(mon);
Console.Write("." + da);
Console.WriteLine("." + yer);
}
}
}
</code></pre>
<p>I am coming from JavaScript where to do this it would look like this:</p>
<pre><code>document.write(mon+'.'+da+'.'+yer);
</code></pre>
<p>Any help here is appreciated.</p> | 15,418,489 | 10 | 0 | null | 2013-03-14 19:28:08.293 UTC | 4 | 2019-01-10 12:33:53.947 UTC | null | null | null | null | 2,140,496 | null | 1 | 30 | c#|console|int|var|console.writeline | 151,334 | <p>Look into <a href="https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting" rel="noreferrer">composite formatting</a>:</p>
<pre><code>Console.WriteLine("{0}.{1}.{2}", mon, da, yer);
</code></pre>
<p>You could also write (although it's not really recommended):</p>
<pre><code>Console.WriteLine(mon + "." + da + "." + yer);
</code></pre>
<p>And, with the release of C# 6.0, you have string interpolation expressions:</p>
<pre><code>Console.WriteLine($"{mon}.{da}.{yer}"); // note the $ prefix.
</code></pre> |
43,658,481 | Passing props dynamically to dynamic component in VueJS | <p>I've a dynamic view: </p>
<pre><code><div id="myview">
<div :is="currentComponent"></div>
</div>
</code></pre>
<p>with an associated Vue instance:</p>
<pre><code>new Vue ({
data: function () {
return {
currentComponent: 'myComponent',
}
},
}).$mount('#myview');
</code></pre>
<p>This allows me to change my component dynamically.</p>
<p>In my case, I have three different components: <code>myComponent</code>, <code>myComponent1</code>, and <code>myComponent2</code>. And I switch between them like this:</p>
<pre><code>Vue.component('myComponent', {
template: "<button @click=\"$parent.currentComponent = 'myComponent1'\"></button>"
}
</code></pre>
<p>Now, I'd like to pass props to <code>myComponent1</code>.</p>
<p>How can I pass these props when I change the component type to <code>myComponent1</code>?</p> | 43,658,979 | 6 | 5 | null | 2017-04-27 12:55:11.39 UTC | 46 | 2022-08-12 08:48:18.71 UTC | 2017-04-27 13:23:58.69 UTC | null | 2,678,454 | null | 2,190,535 | null | 1 | 163 | javascript|vue.js|vuejs2|vue-component | 106,621 | <p>To pass props dynamically, you can add the <code>v-bind</code> directive to your dynamic component and pass an object containing your prop names and values:</p>
<p>So your dynamic component would look like this:</p>
<pre><code><component :is="currentComponent" v-bind="currentProperties"></component>
</code></pre>
<p>And in your Vue instance, <code>currentProperties</code> can change based on the current component:</p>
<pre><code>data: function () {
return {
currentComponent: 'myComponent',
}
},
computed: {
currentProperties: function() {
if (this.currentComponent === 'myComponent') {
return { foo: 'bar' }
}
}
}
</code></pre>
<p>So now, when the <code>currentComponent</code> is <code>myComponent</code>, it will have a <code>foo</code> property equal to <code>'bar'</code>. And when it isn't, no properties will be passed.</p> |
38,233,060 | define_method: How to dynamically create methods with arguments | <p>I want to create a bunch of methods for a find_by feature. I don't want to write the same thing over and over again so I want to use metaprogramming.</p>
<p>Say I want to create a method for finding by name, accepting the name as an argument. How would I do it? I've used define_method in the past but I didn't have any arguments for the method to take.
Here's my (bad) approach</p>
<pre><code>["name", "brand"].each do |attribute|
define_method("self.find_by_#{attribute}") do |attr_|
all.each do |prod|
return prod if prod.attr_ == attr_
end
end
end
</code></pre>
<p>Any thoughts? Thanks in advance.</p> | 38,233,191 | 3 | 4 | null | 2016-07-06 20:20:43.673 UTC | 4 | 2017-11-23 20:14:34.927 UTC | null | null | null | null | 6,090,706 | null | 1 | 40 | ruby|metaprogramming | 36,219 | <p>If I understand your question correctly, you want something like this:</p>
<pre><code>class Product
class << self
[:name, :brand].each do |attribute|
define_method :"find_by_#{attribute}" do |value|
all.find {|prod| prod.public_send(attribute) == value }
end
end
end
end
</code></pre>
<p>(I'm assuming that the <code>all</code> method returns an Enumerable.)</p>
<p>The above is more-or-less equivalent to defining two class methods like this:</p>
<pre><code>class Product
def self.find_by_name(value)
all.find {|prod| prod.name == value }
end
def self.find_by_brand(value)
all.find {|prod| prod.brand == value }
end
end
</code></pre> |
27,972,232 | No configuration setting found for key typesafe config | <p>Im trying to implement a configuration tool <a href="https://github.com/typesafehub/config">typesafehub/config</a>
im using this code </p>
<pre><code> val conf = ConfigFactory.load()
val url = conf.getString("add.prefix") + id + "/?" + conf.getString("add.token")
</code></pre>
<p>And the location of the property file is <strong>/src/main/resources/application.conf</strong></p>
<p>But for some reason i'm receiving </p>
<pre><code>com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'add'
</code></pre>
<p>File content </p>
<pre><code>add {
token = "access_token=6235uhC9kG05ulDtG8DJDA"
prefix = "https://graph.facebook.com/v2.2/"
limit = "&limit=250"
comments="?pretty=0&limit=250&access_token=69kG05ulDtG8DJDA&filter=stream"
feed="/feed?limit=200&access_token=623501EuhC9kG05ulDtG8DJDA&pretty=0"
}
</code></pre>
<p>Everything looks configured correctly ?? do i missed something .</p>
<p>thanks,</p>
<p>miki </p> | 27,982,298 | 11 | 3 | null | 2015-01-15 20:16:14.96 UTC | 2 | 2022-09-19 14:00:34.53 UTC | 2015-01-16 11:08:57.933 UTC | null | 817,571 | null | 817,571 | null | 1 | 28 | scala|typesafe-config | 71,630 | <p>The error message is telling you that whatever configuration got read, it didn't include a top level setting named <code>add</code>. The <code>ConfigFactory.load</code> function will attempt to load the configuration from a variety of places. By default it will look for a file named <code>application</code> with a suffix of <code>.conf</code> or <code>.json</code>. It looks for that file as a Java resource on your class path. However, various system properties will override this default behavior.</p>
<p>So, it is likely that what you missed is one of these:</p>
<ul>
<li>Is it possible that <code>src/main/resources</code> is not on your class path? </li>
<li>Are the <code>config.file</code>, <code>config.resource</code> or <code>config.url</code> properties set?</li>
<li>Is your <code>application.conf</code> file empty?</li>
<li>Do you have an <code>application.conf</code> that would be found earlier in your class path?</li>
<li>Is the key: <code>add</code> defined in the <code>application.conf</code>?</li>
</ul> |
7,997,666 | Storing Blocks in an Array | <p>In Objective-C, I know that blocks are considered objects, so I was wondering if it was possible to store them in an array. This begs the question, are blocks first class objects or are they just treated like objects for the sake of passing them between objects? If they are first class objects, then shouldn't they be storable in arrays? </p> | 7,999,115 | 2 | 0 | null | 2011-11-03 15:38:43.923 UTC | 30 | 2018-11-27 09:19:51.893 UTC | 2016-01-23 08:44:49.9 UTC | null | 25,646 | null | 22,913 | null | 1 | 52 | objective-c|memory-management|objective-c-blocks | 19,896 | <blockquote>
<p><strong>EDIT: Without going into too much detail, under ARC, you can now add blocks to collections like any other object</strong> (see discussion).</p>
</blockquote>
<p>I've left the original answer intact below, since it contains some interesting technical details.</p>
<hr>
<blockquote>
<p>This begs the question, are blocks first class objects or are they
just treated like objects for the sake of passing them between
objects? If they are first class objects, then shouldn't they be
storable in arrays?</p>
</blockquote>
<p>Blocks are Objective-C objects that very much behave like every other NSObject, with a couple of key differences:</p>
<ul>
<li><p>Blocks are always generated by the compiler. They are effectively "alloc/init"ed at runtime as execution passes over the blocks declaration.</p></li>
<li><p>Blocks are initially created on the stack. Block_copy() or the <code>copy</code> method <em>must be used</em> to move the Block to the heap if the Block is to outlive the current scope (see ARC point below).</p></li>
<li><p>Blocks don't really have a callable API beyond memory management.</p></li>
<li><p>To put a Block into a Collection, <strong>it must first be copied</strong>. <strike>Always. Including under ARC.</strike> <em>(See comments.)</em> If you don't, there is risk that the stack allocated Block will be <code>autoreleased</code> and your app will later crash.</p></li>
<li><p>Copying a stack based block will copy all of the captured state, too. If you are making multiple copies of a block, it is more efficient to copy it once, then copy the copy (because copying the copy just bumps the retain count since Blocks are immutable).</p></li>
<li><p>Under ARC, returning a Block from a method or function "just works"; it'll be automatically copied to the heap and the return will effectively be an autoreleased Block (the compiler may optimize away the autorelease in certain circumstances). Even with ARC, you still need to copy the block before sticking it into a collection.</p></li>
</ul>
<p>I've written a couple of blog posts both providing an <a href="http://www.friday.com/bbum/2009/08/29/basic-blocks/">introduction to blocks</a> and some <a href="http://www.friday.com/bbum/2009/08/29/blocks-tips-tricks/">tips and tricks</a>. You might find them interesting.</p>
<p>And, yes, adding 'em to dictionaries is quite useful. I've written a couple of bits of code where I dropped blocks into dictionaries as command handlers where the key was the command name. Very handy.</p> |
9,047,134 | How to change the color of an image on hover | <p>I need to change the background color of an image. The image is a circle image with white background, I need when you hover over it change the background of the circle image to blue. I need only the circle to be change.</p>
<p>My HTML code is</p>
<pre><code><div class="fb-icon">
<a href="http://www.facebook.com/mypage" target="_blank">
<img src="images/fb_normal.png" alt="Facebook">
</a>
</div>
</code></pre>
<p>In CSS I wrote:</p>
<pre><code>.fb-icon:hover {
background: blue;
}
</code></pre>
<p>The above code gives me blue color but as a frame around the circle icon. what I need is to change the background of the circle itself. Imagine it's like a signal it's white when you hover by mouse it goes to blue. </p>
<p>Please I need a solution if it can be done by CSS or whatever. Sorry if I make it too long.</p>
<p>The problem: <a href="http://tinypic.com/view.php?pic=2u9h5jd&s=5" rel="noreferrer">link</a></p> | 9,047,410 | 8 | 6 | null | 2012-01-28 17:09:27.067 UTC | 4 | 2021-08-04 00:19:50.297 UTC | 2012-01-28 19:40:55.81 UTC | null | 1,173,709 | null | 1,173,709 | null | 1 | 15 | html|css | 184,614 | <p>Ideally you should use a transparent PNG with the circle in white and the background of the image transparent. Then you can set the <code>background-color</code> of the <code>.fb-icon</code> to blue on hover. So you're CSS would be:</p>
<pre><code>fb-icon{
background:none;
}
fb-icon:hover{
background:#0000ff;
}
</code></pre>
<p>Additionally, if you don't want to use PNG's you can also use a sprite and alter the background position. A sprite is one large image with a collection of smaller images which can be used as a background image by changing the background position. So for eg, if your original circle image with the white background is <strong>100px X 100px</strong>, you can increase the height of the image to <strong>100px X 200px</strong>, so that the top half is the original image with the white background, while the lower half is the new image with the blue background. Then you set setup your CSS as:</p>
<pre><code>fb-icon{
background:url('path/to/image/image.png') no-repeat 0 0;
}
fb-icon:hover{
background:url('path/to/image/image.png') no-repeat 0 -100px;
}
</code></pre> |
9,098,507 | Why is this PHP call to json_encode silently failing - inability to handle single quotes? | <p>I have a <code>stdClass</code> object called <code>$post</code> that, when dumped via <code>print_r()</code>, returns the following:</p>
<pre><code>stdClass Object (
[ID] => 12981
[post_title] => Alumnus' Dinner Coming Soon
[post_parent] => 0
[post_date] => 2012-01-31 12:00:51
)
</code></pre>
<p>Echoing the result from calling <code>json_encode()</code> on this object results in the following:</p>
<pre><code>{
"ID": "12981",
"post_title": null,
"post_parent": "0",
"post_date": "2012-01-31 12:00:51"
}
</code></pre>
<p>I'm assuming that something with the single quote is causing <code>json_encode</code> to choke, but I don't know what format is needed to escape that. Any ideas?</p>
<p>EDIT: Fixed mismatch in code examples. I'm running PHP version 5.3.8</p>
<p>EDIT2: Directly after encoding the object, I did this: </p>
<pre><code>echo json_last_error() == JSON_ERROR_UTF8;
</code></pre>
<p>This printed <code>1</code>, which means that the following error occurred: "Malformed UTF-8 characters, possibly incorrectly encoded". <a href="http://www.php.net/manual/en/function.json-last-error.php" rel="noreferrer">json_last_error()</a></p>
<p>EDIT3: Calling <code>utf8_decode()</code> on the post title resulted in the following: "Alumnus? Dinner Coming Soon". This data is being pulled from a MySQL database - the post title in particular is a text field, UTF-8 encoded. Maybe this single-quote is improperly encoded? The thing is, I have a SQL GUI app, and it appears correctly in that.</p> | 9,099,949 | 5 | 8 | null | 2012-02-01 15:29:06.787 UTC | 8 | 2019-04-29 21:27:11.847 UTC | 2012-02-01 16:06:25.663 UTC | null | 404,917 | null | 404,917 | null | 1 | 45 | php|json | 65,040 | <p>You need to set the connection encoding before executing queries. How this is done depends on the API you are using to connect:</p>
<ul>
<li>call <code>mysql_set_charset("utf8")</code> if you use the <a href="http://php.net/manual/en/book.mysql.php">old, deprecated API</a>.</li>
<li>call <code>mysqli_set_charset("utf8")</code> if you use <a href="http://php.net/manual/en/book.mysqli.php">mysqli</a></li>
<li>add the <a href="http://php.net/manual/en/ref.pdo-mysql.connection.php"><code>charset</code> parameter</a> to the connection string if you use PDO and PHP >= 5.3.6. In earlier versions you need to execute <code>SET NAMES utf8</code>.</li>
</ul>
<p>When you obtain data from MySQL any text will be encoded in "client encoding", which is likely <a href="http://en.wikipedia.org/wiki/Windows-1252">windows-1252</a> if you don't configure it otherwise. The character that is causing your problem is the "curly quote", seen as <code>92</code> in the hex dump, which confirms that the mysql client is encoding text in windows-1252.</p>
<p>Another thing you might consider is pass all text through <code>utf8_encode</code>, but in this case it wouldn't produce the correct result. PHP's <code>utf8_encode</code> converts <strong>iso-8859-1</strong>-encoded text. In this encoding \x92 is a non-printable control character, which would be converted into a non-printable control character in utf-8. You could use <code>str_replace("\x92", "'", $input)</code> to fix the problem for this particular character, but if there's any chance there will be any other non-ascii characters in the database you'll want to have the client use UTF-8.</p> |
65,277,843 | Flutter: List is deprecated? | <p>After upgrading to the latest version of flutter, I get a deprecation warning for all my Lists.</p>
<pre><code>List<MyClass> _files = List<MyClass>();
=>'List' is deprecated and shouldn't be used.
</code></pre>
<p>Unfortunately, it does not give a hint of what to replace it with.
So what are we supposed to use instead now?</p>
<ul>
<li>Dart SDK version: 2.12.0-141.0.dev</li>
<li>Flutter: Channel master, 1.25.0-9.0.pre.42</li>
</ul> | 65,278,011 | 4 | 3 | null | 2020-12-13 16:19:48.957 UTC | 7 | 2021-05-07 10:02:24.8 UTC | 2020-12-17 18:11:22.683 UTC | null | 3,719,922 | null | 3,719,922 | null | 1 | 60 | flutter|dart | 34,048 | <p>Ok found it, it's just how to instantiate it:</p>
<pre><code>List<MyClass> _files = [];
</code></pre>
<p><strong>Edit</strong>: maybe the most common ones, a bit more detailed according to the <a href="https://master-api.flutter.dev/flutter/dart-core/List-class.html" rel="noreferrer">docs</a>:</p>
<p>Fixed-length list of size 0</p>
<pre><code>List<MyClass> _list = List<MyClass>.empty();
</code></pre>
<p>Growable list</p>
<pre><code>List<MyClass> _list = [];
//or
List<MyClass> _list = List<MyClass>.empty(growable: true);
</code></pre>
<p>Fixed length with predefined fill</p>
<pre><code>int length = 3;
String fill = "test";
List<String> _list = List<String>.filled(length ,fill , growable: true);
// => ["test", "test", "test"]
</code></pre>
<p>List with generate function</p>
<pre><code>int length = 3;
MyClass myFun(int idx) => MyClass(id: idx);
List<MyClass> _list = List.generate(length, myFun, growable: true);
// => [Instance of 'MyClass', Instance of 'MyClass', Instance of 'MyClass']
</code></pre> |
30,904,190 | one-time binding with ng-if in angular? | <p>If I have a view that does:</p>
<pre><code><div ng-repeat="foo in foos">
<p ng-if="bar">omg lol</p>
<p ng-if="!bar">lol omg</p>
</div>
</code></pre>
<p>I am actually creating (2 * foos.length) + 1 $$watchers, which is really not good. I have found several sources online that say you can do ng-if="::bar", but the number of watchers does not change when I do that. Is there a way to force ng-if to be a one time binding?</p>
<p>It is really, really dumb to have to do:</p>
<pre><code><div ng-repeat="foo in foos" ng-if="bar">
<p>omg lol</p>
</div>
<div ng-repeat="foo in foos" ng-if="!bar">
<p>lol omg</p>
</div>
</code></pre>
<p>Which I believe will give me something like 4 $$watchers instead... So I am looking for an alternative to avoid having to be silly like that.</p> | 30,905,003 | 2 | 11 | null | 2015-06-17 23:33:36.45 UTC | 4 | 2017-07-07 11:43:42.56 UTC | 2016-10-12 21:32:34.597 UTC | null | 1,009,603 | null | 594,763 | null | 1 | 30 | angularjs | 23,017 | <p>Just extending my comments to answer. </p>
<p>Angular 1.3 one-time binding syntax (<code>::</code>) indeed will remove unnecessary watches. Just that you need to measure the watches a while after you set the relevant data. Here is why it is. When you set a one-time bound property on the view, angular will set a temporary watch on it until it gets a <em>defined</em> value, i.e anything but <code>undefined</code>. This approach is there for a reason - in order to support the bound values that are populated via a deferred operation like ajax call, timeout, promise chain resolution etc.. Without this <code>::</code> will not work successfully on anything but pre-populated bound values.</p>
<p>So just make sure that you set some value at some point in time to the one-time bound values. Don't let it remain undefined.</p>
<p>Say when you have a condition <code><div ng-if="::lol"></div></code> repeated 100 times. Just make sure when you bind the value to the repeater or some operation that determines the status of <code>lol</code> even if that operation fails (say a ajax call error) still set a value (even <code>null</code> is also a value in javascript) to it. Watches will be removed after the upcoming digest cycle which renders the respective DOM bindings.</p>
<p>In your specific plunker you could as well do:</p>
<pre><code><ul ng-repeat="item in items" ng-if="::lol">
<li>{{ ::item }}</li>
</ul>
</code></pre>
<p>instead of</p>
<pre><code><ul ng-repeat="item in items">
<li ng-if="::lol">{{ ::item }}</li>
</ul>
</code></pre> |
5,568,033 | Convert a string's character encoding from windows-1252 to utf-8 | <p>I had converted a Word Document(docx) to html, the converted html has windows-1252 as its character encoding. In .Net for this 1252 character encoding all the special characters are being displayed as '�'. This html is being displayed in a Rad Editor which displays correctly if the html is in Utf-8 format. </p>
<p>I had tried the following code but no vein</p>
<pre><code>Encoding wind1252 = Encoding.GetEncoding(1252);
Encoding utf8 = Encoding.UTF8;
byte[] wind1252Bytes = wind1252.GetBytes(strHtml);
byte[] utf8Bytes = Encoding.Convert(wind1252, utf8, wind1252Bytes);
char[] utf8Chars = new char[utf8.GetCharCount(utf8Bytes, 0, utf8Bytes.Length)];
utf8.GetChars(utf8Bytes, 0, utf8Bytes.Length, utf8Chars, 0);
string utf8String = new string(utf8Chars);
</code></pre>
<p>Any suggestions on how to convert the html into UTF-8?</p> | 5,569,501 | 4 | 2 | null | 2011-04-06 14:29:55.893 UTC | 3 | 2012-04-12 02:11:50.7 UTC | 2011-04-06 14:32:04.353 UTC | null | 1,583 | null | 694,988 | null | 1 | 23 | c#|asp.net | 87,523 | <p>Actually the problem lies here</p>
<pre><code>byte[] wind1252Bytes = wind1252.GetBytes(strHtml);
</code></pre>
<p>We should not get the bytes from the html String. I tried the below code and it worked.</p>
<pre><code>Encoding wind1252 = Encoding.GetEncoding(1252);
Encoding utf8 = Encoding.UTF8;
byte[] wind1252Bytes = ReadFile(Server.MapPath(HtmlFile));
byte[] utf8Bytes = Encoding.Convert(wind1252, utf8, wind1252Bytes);
string utf8String = Encoding.UTF8.GetString(utf8Bytes);
public static byte[] ReadFile(string filePath)
{
byte[] buffer;
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
try
{
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
sum += count; // sum is a buffer offset for next reading
}
finally
{
fileStream.Close();
}
return buffer;
}
</code></pre> |
5,105,379 | Parsing HTML String | <p>Is there a way to parse HTML string in .Net code behind like DOM parsing...</p>
<p>i.e. GetElementByTagName("abc").GetElementByTagName("tag")</p>
<p>I've this code chunk...</p>
<pre><code>private void LoadProfilePage()
{
string sURL;
sURL = "http://www.abcd1234.com/abcd1234";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
//WebProxy myProxy = new WebProxy("myproxy",80);
//myProxy.BypassProxyOnLocal = true;
//wrGETURL.Proxy = WebProxy.GetDefaultProxy();
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
if (objStream != null)
{
StreamReader objReader = new StreamReader(objStream);
string sLine = objReader.ReadToEnd();
if (String.IsNullOrEmpty(sLine) == false)
{
....
}
}
}
</code></pre> | 5,105,397 | 5 | 1 | null | 2011-02-24 13:37:22.227 UTC | 1 | 2021-06-09 20:19:05.783 UTC | null | null | null | null | 93,963 | null | 1 | 14 | c#|.net|html|parsing | 62,004 | <p>You can use the excellent <a href="http://html-agility-pack.net/" rel="nofollow noreferrer">HTML Agility Pack</a>.</p>
<blockquote>
<p>This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).</p>
</blockquote> |
4,978,000 | Static method in Java can be accessed using object instance | <p>In Java static methods are created to access it without any object instance. It makes some sense to me. But recently I came across one strange thing that, static method in Java can also be accessed through its object instance. This looks pretty wierd to me. Does anyone of you know why this feature is provided by Java? Whats the significance of allowing static methods getting accessed with as well as without instance?</p> | 4,978,063 | 5 | 1 | null | 2011-02-12 12:15:00.133 UTC | 5 | 2013-06-21 16:58:17.857 UTC | null | null | null | null | 605,985 | null | 1 | 32 | java|methods|static | 42,004 | <p>A benefit of this is that it allows you to take an instance method and turn it into a static method without having to modify any existing code (other than the class) and thus allowing for backwards compatibility. I've found this useful as many times I've come across utility methods that can be made static - I can just add the <code>static</code> modifier and continue on my way.</p> |
4,981,241 | no default constructor exists for class | <pre><code>#include "Includes.h"
enum BlowfishAlgorithm
{
ECB,
CBC,
CFB64,
OFB64,
};
class Blowfish
{
public:
struct bf_key_st
{
unsigned long P[18];
unsigned long S[1024];
};
Blowfish(BlowfishAlgorithm algorithm);
void Dispose();
void SetKey(unsigned char data[]);
unsigned char Encrypt(unsigned char buffer[]);
unsigned char Decrypt(unsigned char buffer[]);
char EncryptIV();
char DecryptIV();
private:
BlowfishAlgorithm _algorithm;
unsigned char _encryptIv[200];
unsigned char _decryptIv[200];
int _encryptNum;
int _decryptNum;
};
class GameCryptography
{
public:
Blowfish _blowfish;
GameCryptography(unsigned char key[]);
void Decrypt(unsigned char packet[]);
void Encrypt(unsigned char packet[]);
Blowfish Blowfish;
void SetKey(unsigned char k[]);
void SetIvs(unsigned char i1[],unsigned char i2[]);
};
GameCryptography::GameCryptography(unsigned char key[])
{
}
</code></pre>
<p>Error:IntelliSense: no default constructor exists for class "Blowfish" ???!</p> | 4,981,313 | 5 | 3 | null | 2011-02-12 23:13:11.91 UTC | 8 | 2021-11-05 08:18:11.347 UTC | 2020-11-22 07:49:08.43 UTC | null | 589,259 | null | 584,081 | null | 1 | 46 | c++|class|constructor|class-design|default-constructor | 177,883 | <p>If you define a class without any constructor, the compiler will synthesize a constructor for you (and that will be a default constructor -- i.e., one that doesn't require any arguments). If, however, you <em>do</em> define a constructor, (even if it does take one or more arguments) the compiler will <em>not</em> synthesize a constructor for you -- at that point, you've taken responsibility for constructing objects of that class, so the compiler "steps back", so to speak, and leaves that job to you.</p>
<p>You have two choices. You need to either provide a default constructor, or you need to supply the correct parameter when you define an object. For example, you could change your constructor to look something like:</p>
<pre><code>Blowfish(BlowfishAlgorithm algorithm = CBC);
</code></pre>
<p>...so the ctor could be invoked without (explicitly) specifying an algorithm (in which case it would use CBC as the algorithm).</p>
<p>The other alternative would be to explicitly specify the algorithm when you define a Blowfish object:</p>
<pre><code>class GameCryptography {
Blowfish blowfish_;
public:
GameCryptography() : blowfish_(ECB) {}
// ...
};
</code></pre>
<p>In C++ 11 (or later) you have one more option available. You can define your constructor that takes an argument, but then tell the compiler to generate the constructor it would have if you didn't define one:</p>
<pre><code>class GameCryptography {
public:
// define our ctor that takes an argument
GameCryptography(BlofishAlgorithm);
// Tell the compiler to do what it would have if we didn't define a ctor:
GameCryptography() = default;
};
</code></pre>
<p>As a final note, I think it's worth mentioning that ECB, CBC, CFB, etc., are modes of operation, not really encryption algorithms themselves. Calling them algorithms won't bother the compiler, but <em>is</em> unreasonably likely to cause a problem for others reading the code.</p> |
5,192,862 | How to convert long to int in .net? | <p>I am developing window phone 7 application in silverlight. I am new to the window phone 7 application. I have the long value in String format as follows</p>
<pre><code>String Am = AmountTextBox.Text.ToString()
</code></pre>
<p>The AmountTextBox.Text.ToString() in the above code is long value which is in string format. I want to store a 15 digit inter value in my application.</p>
<p>I found the following link for conversion.</p>
<p><a href="https://stackoverflow.com/questions/858904/can-i-convert-long-to-int">Can I convert long to int?</a></p>
<p>How should I convert a long value which is in string format to int ? Can you please provide me any code or link through which I can resolve the above issue ? If I am doing anything wrong then please guide me.</p> | 5,192,935 | 7 | 4 | null | 2011-03-04 11:01:24.24 UTC | 2 | 2020-11-17 22:33:10.963 UTC | 2017-05-23 12:26:13.973 UTC | null | -1 | null | 265,103 | null | 1 | 27 | c#|casting | 107,622 | <p>You can't store a 15 digit integer since the maximum value for an integer is 2,147,483,647.</p>
<p>What's wrong with a <code>long</code>-Value?</p>
<p>You could use <a href="http://msdn.microsoft.com/de-de/library/zc2x2b1h%28v=VS.80%29.aspx" rel="noreferrer">TryParse()</a> to get the <code>long</code>-Value from yout user input:</p>
<pre><code>String Am = AmountTextBox.Text.ToString();
long l;
Int64.TryParse(Am, out l);
</code></pre>
<p>It will return <code>false</code> if the text can't be converted to <code>long</code>, so it's pretty safe to use.</p>
<p>Otherwise, converting a <code>long</code> to <code>int</code> is a easy as </p>
<pre><code>int i = (int)yourLongValue;
</code></pre>
<p>if you're happy with discarding MSBs and taking LSBs.</p> |
5,155,479 | How do I check if the useragent is an ipad or iphone? | <p>I'm using a C# asp.net website. </p>
<p>How can I check if the user using ipad or iphone? How can I check the platform? </p>
<p>For example, if the user enter the website from ipad I'd like to display"Hello ipad user"</p> | 5,155,658 | 9 | 4 | null | 2011-03-01 13:59:00.813 UTC | 5 | 2020-07-17 13:11:55.13 UTC | 2011-08-29 19:33:58.477 UTC | null | 18,821 | null | 146,864 | null | 1 | 37 | c#|.net|iphone|asp.net|ipad | 63,445 | <p>For iPad <a href="http://msdn.microsoft.com/en-us/library/system.web.httprequest.useragent.aspx" rel="noreferrer">user agent</a> is something like:</p>
<blockquote>
<p>Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10</p>
</blockquote>
<p>and for iPhone its somthing like:</p>
<blockquote>
<p>Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3</p>
</blockquote>
<p>Any many more depending on the version and wheather its iPhone 3 or 4</p>
<p>so better just do a substring search for iPhone and iPad <em>as suggested by another answer</em></p> |
5,244,129 | Use RSA private key to generate public key? | <p>I don't really understand this one:</p>
<p>According to <a href="https://www.madboa.com/geek/openssl/#key-rsa" rel="noreferrer">https://www.madboa.com/geek/openssl/#key-rsa</a>, you can generate a public key from a private key.</p>
<pre><code>openssl genrsa -out mykey.pem 1024
openssl rsa -in mykey.pem -pubout > mykey.pub
</code></pre>
<p>My initial thinking was that they are generated in a pair together.</p>
<p>Does the RSA private key contain the sum? Or the public key?</p> | 5,246,045 | 10 | 5 | null | 2011-03-09 10:03:47.7 UTC | 202 | 2022-05-27 05:02:43.6 UTC | 2021-09-24 08:26:34.793 UTC | null | 775,954 | null | 577,436 | null | 1 | 519 | openssl|rsa|public-key-encryption | 692,147 | <pre><code>openssl genrsa -out mykey.pem 1024
</code></pre>
<p>will actually produce a public - private key pair. The pair is stored in the generated <code>mykey.pem</code> file.</p>
<pre><code>openssl rsa -in mykey.pem -pubout > mykey.pub
</code></pre>
<p>will extract the public key and print that out. <a href="http://www.devco.net/archives/2006/02/13/public_-_private_key_encryption_using_openssl.php" rel="noreferrer">Here</a> is a link to a page that describes this better. </p>
<p>EDIT: Check the examples section <a href="http://www.openssl.org/docs/apps/rsa.html" rel="noreferrer">here</a>. To just output the public part of a private key:</p>
<pre><code>openssl rsa -in key.pem -pubout -out pubkey.pem
</code></pre>
<p>To get a usable public key for SSH purposes, use <a href="https://stackoverflow.com/a/23413167/293064">ssh-keygen</a>:</p>
<pre><code>ssh-keygen -y -f key.pem > key.pub
</code></pre> |
5,496,464 | Write a non-recursive traversal of a Binary Search Tree using constant space and O(n) run time | <p><strong>This is not homework, this is an interview question.</strong></p>
<p>The catch here is that the algorithm should be constant space.
I'm pretty clueless on how to do this without a stack, I'd post what I've written using a stack, but it's not relevant anyway.</p>
<p>Here's what I've tried: I attempted to do a pre-order traversal and I got to the left-most node, but I'm stuck there. I don't know how to "recurse" back up without a stack/parent pointer.</p>
<p>Any help would be appreciated.</p>
<p>(I'm tagging it as Java since that's what I'm comfortable using, but it's pretty language agnostic as is apparent.)</p> | 5,496,559 | 10 | 5 | null | 2011-03-31 07:19:40.197 UTC | 27 | 2016-02-27 01:21:38.463 UTC | null | null | null | null | 183,037 | null | 1 | 50 | java|binary-tree|traversal|tree-traversal | 41,579 | <p>I didn't think it through entirely, but i think it's possible as long as you're willing to mess up your tree in the process.</p>
<p>Every Node has 2 pointers, so it could be used to represent a doubly-linked list. Suppose you advance from Root to Root.Left=Current. Now Root.Left pointer is useless, so assign it to be Current.Right and proceed to Current.Left. By the time you reach leftmost child, you'll have a linked list with trees hanging off of some nodes. Now iterate over that, repeating the process for every tree you encounter as you go</p>
<p>EDIT: thought it through. Here's the algorithm that prints in-order:</p>
<pre><code>void traverse (Node root) {
traverse (root.left, root);
}
void traverse (Node current, Node parent) {
while (current != null) {
if (parent != null) {
parent.left = current.right;
current.right = parent;
}
if (current.left != null) {
parent = current;
current = current.left;
} else {
print(current);
current = current.right;
parent = null;
}
}
}
</code></pre> |
4,903,939 | LibXML2.dylib and Xcode4 | <p>I just downloaded Xcode 4 and I cant seem to run my application as the MGTwitter... classes are complaining of a non inclusion error of LibXML2. I have imported it into the frameworks folder, and I have put the following in the header bit in the build settings</p>
<pre><code>$(SDKROOT)/usr/include/libxml2
</code></pre>
<p>But I am still getting 65 errors.</p>
<p>Any ideas how to fix this?</p> | 4,904,022 | 11 | 2 | null | 2011-02-04 23:29:49.883 UTC | 11 | 2015-04-05 13:32:44.613 UTC | 2011-06-13 22:43:32.173 UTC | null | 1,288 | null | 556,479 | null | 1 | 11 | iphone|objective-c|xcode4|libxml2|mgtwitterengine | 19,635 | <p>Try this:</p>
<p><code>"$(SDK_DIR)"/usr/include/libxml2</code></p> |
12,415,715 | Take the time from the datetime and convert it into seconds? | <p>I am running SQL Server 2005. Technically I know how to take the time from a tsql datetime.</p>
<pre><code>CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond
</code></pre>
<p>The problem is that I have a datetime field and I need to essentially grab the time portion convert that to an integer specifically seconds. Then I need to do a bunch of arithmetic on this integer that I won't discuss here. I have searched on stackoverflow and haven't found a question that is specific to this question. Any ideas? I am really looking for best practices here, I am worried about creating a udf for this specific purpose as it completely throws the query optimizer out the window.</p>
<p>I have seen this webpage so please don't paste this. :</p>
<p><a href="http://forums.devx.com/showthread.php?171561-TSQL-Converting-HH-MM-SS-to-seconds">http://forums.devx.com/showthread.php?171561-TSQL-Converting-HH-MM-SS-to-seconds</a></p> | 12,415,760 | 3 | 1 | null | 2012-09-13 22:30:59.43 UTC | 3 | 2018-02-06 13:16:46.313 UTC | 2017-10-04 10:58:56.073 UTC | null | 542,251 | null | 1,028,312 | null | 1 | 12 | tsql|sql-server-2005 | 63,976 | <p>Use <a href="http://msdn.microsoft.com/en-us/library/ms174420.aspx" rel="noreferrer"><code>DATEPART</code></a>:</p>
<pre><code>(DATEPART(HOUR, GETDATE()) * 3600) +
(DATEPART(MINUTE, GETDATE()) * 60) +
(DATEPART(SECOND, GETDATE()))
</code></pre> |
12,161,425 | Why is my Symfony 2.0 site running slowly on Vagrant with Linux host? | <p>I've got a Symfony 2.0 application running using Vagrant with a Linux guest and host O/S (Ubuntu). However, it runs slowly (e.g. several seconds for a page to load, often more than 10s) and I can't work out why. My colleagues who are running the site locally rather than on Vagrant VM have it running faster.</p>
<p>I've read elsewhere that Vagrant VMs run very slowly if NFS isn't enabled, but I have enabled that. I'm also using the APC cache to try and speed things up, but still the problems remain.</p>
<p>I ran xdebug against my site using the instructions at <a href="http://webmozarts.com/2009/05/01/speedup-performance-profiling-for-your-symfony-app" rel="noreferrer">http://webmozarts.com/2009/05/01/speedup-performance-profiling-for-your-symfony-app</a>, but I'm not clear where to start with analysing the data from this. I've got as far as opening it in KCacheGrind and looking for the high numbers under "Incl." and "Self", but this has just shown that <code>php::session_start</code> takes quite a long time.</p>
<p>Any suggestions as to what I should be trying here? Sorry for the slightly broad question, but I'm stumped!</p> | 26,253,403 | 5 | 4 | null | 2012-08-28 14:23:12.813 UTC | 9 | 2018-09-13 08:04:54.473 UTC | null | null | null | null | 328,817 | null | 1 | 17 | symfony|vagrant | 12,656 | <p>Where I work, we've tried out two solutions to the problem of Vagrant + Symfony being slow. I recommend the second one (nfs and bind mounts).</p>
<p><strong>The rsync approach</strong></p>
<p>To begin with, we used <a href="https://docs.vagrantup.com/v2/synced-folders/rsync.html" rel="nofollow noreferrer">rsync</a>. Our approach was slightly different to that outlined in <a href="https://stackoverflow.com/a/12168060/328817">AdrienBrault's answer</a>. Rather, we had code like the following in our <code>Vagrantfile</code>:</p>
<pre class="lang-ruby prettyprint-override"><code>config.vm.define :myproj01 do |myproj|
# Networking & Port Forwarding
myproj.vm.network :private_network, type: "dhcp"
# NFS Share
myproj.vm.synced_folder ".", "/home/vagrant/current", type: 'rsync', rsync__exclude: [
"/.git/",
"/vendor/",
"/app/cache/",
"/app/logs/",
"/app/uploads/",
"/app/downloads/",
"/app/bootstrap.php.cache",
"/app/var",
"/app/config/parameters.yml",
"/composer.phar",
"/web/bundles",
"/web/uploads",
"/bin/behat",
"/bin/doctrine*",
"/bin/phpunit",
"/bin/webunit",
]
# update VM sooner after files changed
# see https://github.com/smerrill/vagrant-gatling-rsync#working-with-this-plugin
config.gatling.latency = 0.5
end
</code></pre>
<p>As you might notice from the above, we kept files in sync using the <a href="https://github.com/smerrill/vagrant-gatling-rsync" rel="nofollow noreferrer">Vagrant gatling rsync plugin</a>.</p>
<p><strong>The improved NFS approach, using bind mounts (recommended solution)</strong></p>
<p>The rsync approach solves the speed issue, but we found some problems with it. In particular, the one-way nature of it (as opposed to sharing folders) was annoying when files (like <code>composer.lock</code> or Doctrine migrations) were generated on the VM, or when we wanted to access code in <code>/vendor</code>. We had to SFTP in to copy things back - and, in the case of new files, do it before they were cleared by the next run of the gatling plugin!</p>
<p>Therefore, we moved to a solution which uses <a href="http://backdrift.org/how-to-use-bind-mounts-in-linux" rel="nofollow noreferrer">binding mounts</a> to handle folders like cache and logs differently. Not having those shared increased the speed dramatically.</p>
<p>The relevant bits of the Vagrantfile are as follows:</p>
<pre><code># Binding mounts for folders with dynamic data in them
# This must happen before provisioning, and on every subsequent reboot, hence run: "always"
config.vm.provision "shell",
inline: "/home/vagrant/current/bin/bind-mounts",
run: "always"
</code></pre>
<p>The <code>bind-mounts</code> script referenced above looks like this:</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/bash
mkdir -p ~vagrant/current/app/downloads/
mkdir -p ~vagrant/current/app/uploads/
mkdir -p ~vagrant/current/app/var/
mkdir -p ~vagrant/current/app/cache/
mkdir -p ~vagrant/current/app/logs/
mkdir -p ~vagrant/shared/app/downloads/
mkdir -p ~vagrant/shared/app/uploads/
mkdir -p ~vagrant/shared/app/var/
mkdir -p ~vagrant/shared/app/cache/
mkdir -p ~vagrant/shared/app/logs/
sudo mount -o bind ~vagrant/shared/app/downloads/ ~/current/app/downloads/
sudo mount -o bind ~vagrant/shared/app/uploads/ ~/current/app/uploads/
sudo mount -o bind ~vagrant/shared/app/var/ ~/current/app/var/
sudo mount -o bind ~vagrant/shared/app/cache/ ~/current/app/cache/
sudo mount -o bind ~vagrant/shared/app/logs/ ~/current/app/logs/
</code></pre>
<p>NFS + binding mounts is the approach I'd recommend.</p> |
12,289,235 | Simple and fast matrix-vector multiplication in C / C++ | <p>I need frequent usage of <code>matrix_vector_mult()</code> which multiplies matrix with vector, and below is its implementation.</p>
<p><strong>Question: Is there a simple way to make it significantly, at least twice, faster?</strong></p>
<p>Remarks: 1) The size of the matrix is about 300x50. It doesn't change during the
run. 2) It must work on both Windows and Linux.</p>
<pre><code>double vectors_dot_prod(const double *x, const double *y, int n)
{
double res = 0.0;
int i;
for (i = 0; i < n; i++)
{
res += x[i] * y[i];
}
return res;
}
void matrix_vector_mult(const double **mat, const double *vec, double *result, int rows, int cols)
{ // in matrix form: result = mat * vec;
int i;
for (i = 0; i < rows; i++)
{
result[i] = vectors_dot_prod(mat[i], vec, cols);
}
}
</code></pre> | 12,289,513 | 3 | 6 | null | 2012-09-05 20:27:14.883 UTC | 6 | 2017-10-24 13:43:17.57 UTC | null | null | null | null | 105,037 | null | 1 | 20 | c++|c|matrix | 38,877 | <p>This is something that in theory a good compiler should do by itself, however I made a try with my system (g++ 4.6.3) and got about twice the speed on a 300x50 matrix by hand unrolling 4 multiplications (about 18us per matrix instead of 34us per matrix):</p>
<pre><code>double vectors_dot_prod2(const double *x, const double *y, int n)
{
double res = 0.0;
int i = 0;
for (; i <= n-4; i+=4)
{
res += (x[i] * y[i] +
x[i+1] * y[i+1] +
x[i+2] * y[i+2] +
x[i+3] * y[i+3]);
}
for (; i < n; i++)
{
res += x[i] * y[i];
}
return res;
}
</code></pre>
<p>I expect however the results of this level of micro-optimization to vary wildly between systems.</p> |
12,059,307 | Multiple application context, multiple dispatcher servlets? | <p>Until now I used to think that a web-application can have only one <code>dispatcher-servlet</code> which we define in <code>web.xml</code><br></p>
<ul>
<li>Am I right in thinking so?</li>
<li>Can i have multiple dispatcher servlets in a single web application? If yes, How?</li>
<li>What is a situation we might need this in?</li>
<li>Can there only be a single application context in the entire web application?</li>
<li>How can we define multiple application contexts?</li>
<li>Can a <code>dispatcher-servlet</code> exist in a non-spring application? </li>
</ul> | 12,059,602 | 2 | 1 | null | 2012-08-21 16:33:56.647 UTC | 11 | 2019-10-02 09:45:27.4 UTC | 2019-10-02 09:45:27.4 UTC | null | 157,882 | null | 973,391 | null | 1 | 25 | spring|spring-mvc|servlets | 13,170 | <blockquote>
<p>Can you have multiple dispatcher servlets in a single web application ?</p>
</blockquote>
<p>Of course, quoting the <a href="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html">official documentation</a> (<strong>bold</strong> is actually there as well!)</p>
<blockquote>
<p><strong>A web application can define any number of DispatcherServlets</strong>. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded by ContextLoaderListener, if any, will be shared.</p>
</blockquote>
<hr>
<blockquote>
<p>How?</p>
</blockquote>
<p>Just declare several servlets with different names but using <code>org.springframework.web.servlet.DispatcherServlet</code> class. Also make sure <code>yourServletName-servlet.xml</code> file is available.</p>
<hr>
<blockquote>
<p>What is a situation we might need this in ?</p>
</blockquote>
<p><code>DispatcherServlet</code> is very flexible. Not only Spring MVC uses it, but also Spring WS, Spring support for <a href="/questions/tagged/hessian" class="post-tag" title="show questions tagged 'hessian'" rel="tag">hessian</a>, etc.</p>
<hr>
<blockquote>
<p>Also, can there only be a single application context in the entire web application ?</p>
</blockquote>
<p>Answered already, also in the quoted documentation: one application context per <code>DispatcherServlet</code> + one main web application context.</p>
<hr>
<blockquote>
<p>How can we define multiple application contexts ?</p>
</blockquote>
<p>See above, just create multiple <code>DispatcherServlet</code>s.</p>
<hr>
<blockquote>
<p>Can a dispatcher servlet exist in a non-spring application ?</p>
</blockquote>
<p><code>DispatcherServlet</code> is a Spring context (Spring application) on its own, thus: no. On the hand <code>DispatcherServlet</code> can be declared in an application not having parent (main) application context, thus: yes.</p> |
12,626,096 | Why has atomicAdd not been implemented for doubles? | <p>Why hasnt <code>atomicAdd()</code> for doubles been implemented explicitly as a part of CUDA 4.0 or higher?</p>
<p>From the appendix F Page 97 of the <a href="http://developer.download.nvidia.com/compute/DevZone/docs/html/C/doc/CUDA_C_Programming_Guide.pdf">CUDA programming guide 4.1</a> the following versions of
atomicAdd have been implemented.</p>
<pre><code>int atomicAdd(int* address, int val);
unsigned int atomicAdd(unsigned int* address,
unsigned int val);
unsigned long long int atomicAdd(unsigned long long int* address,
unsigned long long int val);
float atomicAdd(float* address, float val)
</code></pre>
<p>The same page goes on to give a small implementation of atomicAdd for doubles as follows
which I have just started using in my project. </p>
<pre><code>__device__ double atomicAdd(double* address, double val)
{
unsigned long long int* address_as_ull =
(unsigned long long int*)address;
unsigned long long int old = *address_as_ull, assumed;
do {
assumed = old;
old = atomicCAS(address_as_ull, assumed,
__double_as_longlong(val +
__longlong_as_double(assumed)));
} while (assumed != old);
return __longlong_as_double(old);
}
</code></pre>
<p>Why not define the above code as a part of CUDA ? </p> | 12,631,797 | 1 | 1 | null | 2012-09-27 16:37:08.953 UTC | 8 | 2016-10-19 10:19:40.917 UTC | 2012-09-28 05:08:24.313 UTC | null | 749,748 | null | 505,306 | null | 1 | 36 | cuda | 9,092 | <p>Edit: As of CUDA 8, double-precision <code>atomicAdd()</code> is implemented in CUDA with hardware support in SM_6X (Pascal) GPUs.</p>
<p><s>Currently, no CUDA devices support <code>atomicAdd</code> for <code>double</code> in hardware.</s> As you noted, it can be implemented in terms of <code>atomicCAS</code> on 64-bit integers, but there is a non-trivial performance cost for that. </p>
<p>Therefore, the CUDA software team chose to document a correct implementation as an option for developers, rather than make it part of the CUDA standard library. This way developers are not unknowingly opting in to a performance cost they don't understand.</p>
<p>Aside: I don't think this question should be closed as "not constructive". I think it's a perfectly valid question, +1.</p> |
12,564,777 | How do I do a schema only backup and restore in PostgreSQL? | <p>How do I take a schema level backup in PostgreSQL database and restore on the another database? Is there any single command available for this? For example, can I pg_dump and restore in single line?</p> | 12,564,792 | 4 | 0 | null | 2012-09-24 12:07:39.237 UTC | 11 | 2019-10-11 06:32:55.363 UTC | 2017-05-24 19:50:17.02 UTC | null | 33,264 | user1671630 | null | null | 1 | 44 | postgresql|pg-dump | 109,843 | <pre><code>pg_dump --schema=masters oldDB > masters1.sql
cat masters1.sql | psql newDB
</code></pre>
<p>or </p>
<p>in single command you can do by this </p>
<pre><code>pg_dump oldDB --schema masters | psql -h localhost newDB;
</code></pre> |
12,490,015 | Visual Studio can't 'see' my included header files | <p>I created an empty 'Demo' project in Visual Studio 2008 and added some existing projects to my solution. Included "MyHeader.h" (other project's header) in <code>main.cpp</code> file which is in 'Demo'. Also added header files' path in "Tools/Option/VC++ Directories/Include files" section. But intellisense says: "File <code>MyHeader.h</code> not found in current source file's directory or in build system paths..."</p>
<p>How the problem can be fixed?</p> | 12,490,073 | 15 | 2 | null | 2012-09-19 07:11:18.76 UTC | 3 | 2022-03-27 05:54:01.013 UTC | 2022-03-27 05:54:01.013 UTC | null | 11,573,842 | null | 1,622,006 | null | 1 | 49 | c++|visual-studio-2008|include | 171,527 | <p>If you choose <code>Project</code> and then <code>All Files</code> in the menu, all files should be displayed in the Solution Explorer that are physically in your project map, but not (yet) included in your project. If you right click on the file you want to add in the Solution Explorer, you can include it.</p> |
12,442,892 | Eclipse Android - Logcat Clearing too Fast | <p>I have been using Eclipse for Android (most up to date version), for a while with no problems with the Logcat. For an unknown reason, Logcat is no longer retaining the debug messages. Logcat is getting cleared in about 5 seconds . Is there any way to prevent the auto-clearing of Logcat messages? Otherwise I am unable to read the messages. </p> | 12,443,115 | 3 | 0 | null | 2012-09-15 22:13:05.277 UTC | 9 | 2017-04-01 14:11:51.457 UTC | 2013-12-25 07:03:22.45 UTC | null | 2,571,277 | null | 1,017,063 | null | 1 | 50 | android|eclipse|logcat | 16,554 | <p>Change your LogCat buffer length:</p>
<p>Window / Preferences / Android / LogCat / Maximum number of LogCat messages in buffer <strong>_</strong></p>
<p>Set it to 0 for unlimited size (thanks to the commenter below)</p> |
12,062,946 | Why do I want to avoid non-default constructors in fragments? | <p>I am creating an app with <code>Fragments</code> and in one of them, I created a non-default constructor and got this warning:</p>
<pre><code>Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead
</code></pre>
<p>Can someone tell me why this is not a good idea? </p>
<p>Can you also suggest how I would accomplish this:</p>
<pre><code>public static class MenuFragment extends ListFragment {
public ListView listView1;
Categories category;
//this is my "non-default" constructor
public MenuFragment(Categories category){
this.category = category;
}....
</code></pre>
<p>Without using the non-default constructor? </p> | 12,063,777 | 6 | 9 | null | 2012-08-21 20:57:50.337 UTC | 42 | 2020-03-15 21:02:38.637 UTC | 2014-10-14 15:41:11.673 UTC | null | 2,401,535 | null | 1,283,845 | null | 1 | 175 | android|android-fragments | 93,006 | <p>Make a bundle object and insert your data (in this example your <code>Category</code> object). Be careful, you can't pass this object directly into the bundle, unless it's serializable.
I think it's better to build your object in the fragment, and put only an id or something else into bundle. This is the code to create and attach a bundle:</p>
<pre><code>Bundle args = new Bundle();
args.putLong("key", value);
yourFragment.setArguments(args);
</code></pre>
<p>After that, in your fragment access data:</p>
<pre><code>Type value = getArguments().getType("key");
</code></pre>
<p>That's all.</p> |
3,886,593 | How to check if std::map contains a key without doing insert? | <p>The only way I have found to check for duplicates is by inserting and checking the <code>std::pair.second</code> for <code>false</code>, but the problem is that this still inserts something if the key is unused, whereas what I want is a <code>map.contains(key);</code> function.</p> | 3,886,599 | 3 | 1 | null | 2010-10-07 23:13:21.1 UTC | 29 | 2022-05-30 21:10:01.16 UTC | 2014-04-18 21:34:42.373 UTC | null | 834,176 | null | 146,780 | null | 1 | 176 | c++|stl|map | 203,272 | <p>Use <code>my_map.count( key )</code>; it can only return 0 or 1, which is essentially the Boolean result you want.</p>
<p>Alternately <code>my_map.find( key ) != my_map.end()</code> works too.</p> |
22,727,107 | How to find the last field using 'cut' | <p><em>Without</em> using <code>sed</code> or <code>awk</code>, <em>only</em> <code>cut</code>, how do I get the last field when the number of fields are unknown or change with every line?</p> | 22,727,211 | 12 | 11 | null | 2014-03-29 04:43:37.15 UTC | 89 | 2021-05-20 13:09:32.573 UTC | 2017-02-05 20:29:52.367 UTC | null | 3,266,847 | null | 3,262,003 | null | 1 | 461 | linux|bash|cut | 384,188 | <p>You could try something like this:</p>
<pre><code>echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev
</code></pre>
<p><strong>Explanation</strong></p>
<ul>
<li><code>rev</code> reverses "maps.google.com" to be <code>moc.elgoog.spam</code></li>
<li><code>cut</code> uses dot (ie '.') as the delimiter, and chooses the first field, which is <code>moc</code></li>
<li>lastly, we reverse it again to get <code>com</code></li>
</ul> |
8,915,797 | Calling a function through its address in memory in c / c++ | <p>Given knowledge of the prototype of a function and its address in memory, is it possible to call this function from another process or some piece of code that knows nothing but the prototype and memory address? If possible, how can a returned type be handled back in the code?</p> | 8,915,871 | 6 | 7 | null | 2012-01-18 19:04:40.913 UTC | 16 | 2020-11-12 22:37:04.21 UTC | null | null | null | null | 991,484 | null | 1 | 33 | c++|c|function-call|memory-address | 48,146 | <p>On modern operating systems, each <strong><em>process has its own address space</em></strong> and addresses are only valid within a process. If you want to execute code in some other process, you either have to <strong><em>inject a shared library</em></strong> or <strong><em>attach your program as a debugger</em></strong>. </p>
<p>Once you are in the other program's address space, this code <strong><em>invokes a function at an arbitrary address</em></strong>:</p>
<pre><code>typedef int func(void);
func* f = (func*)0xdeadbeef;
int i = f();
</code></pre> |
22,369,168 | OpenCV imwrite() not saving image | <p>I am trying to save an image from OpenCV on my mac and I am using the following code and so far it has not been working.</p>
<pre><code>cv::imwrite("/Users/nickporter/Desktop/Gray_Image.jpg", cvImage);
</code></pre>
<p>Can anyone see why this might not be saving?</p> | 22,370,078 | 7 | 5 | null | 2014-03-13 04:36:12.157 UTC | 5 | 2019-10-25 20:02:01.433 UTC | 2015-07-16 13:25:08.707 UTC | null | 2,589,776 | user2780240 | null | null | 1 | 15 | c++|opencv | 77,888 | <p>OpenCV does have problems in saving to <code>JPG</code> images sometimes, try to save to <code>BMP</code> instead:</p>
<pre><code>cv::imwrite("/Users/nickporter/Desktop/Gray_Image.bmp", cvImage);
</code></pre>
<p>Also, before this, make sure you image <code>cvImage</code> is valid. You can check it by showing the image first:</p>
<pre><code>namedWindow("image", WINDOW_AUTOSIZE);
imshow("image", cvImage);
waitKey(30);
</code></pre> |
22,404,060 | Fortran - Cython Workflow | <p>I would like to set up a workflow to reach fortran routines from Python using Cython on a Windows Machine </p>
<p>after some searching I found :
<a href="http://www.fortran90.org/src/best-practices.html#interfacing-with-c" rel="noreferrer">http://www.fortran90.org/src/best-practices.html#interfacing-with-c</a> and <a href="https://stackoverflow.com/tags/fortran-iso-c-binding/info">https://stackoverflow.com/tags/fortran-iso-c-binding/info</a></p>
<p>and some code pices:</p>
<p>Fortran side:</p>
<p>pygfunc.h:</p>
<pre><code>void c_gfunc(double x, int n, int m, double *a, double *b, double *c);
</code></pre>
<p>pygfunc.f90</p>
<pre><code>module gfunc1_interface
use iso_c_binding
use gfunc_module
implicit none
contains
subroutine c_gfunc(x, n, m, a, b, c) bind(c)
real(C_FLOAT), intent(in), value :: x
integer(C_INT), intent(in), value :: n, m
type(C_PTR), intent(in), value :: a, b
type(C_PTR), value :: c
real(C_FLOAT), dimension(:), pointer :: fa, fb
real(C_FLOAT), dimension(:,:), pointer :: fc
call c_f_pointer(a, fa, (/ n /))
call c_f_pointer(b, fb, (/ m /))
call c_f_pointer(c, fc, (/ n, m /))
call gfunc(x, fa, fb, fc)
end subroutine
end module
</code></pre>
<p>gfunc.f90</p>
<pre><code>module gfunc_module
use iso_c_binding
implicit none
contains
subroutine gfunc(x, a, b, c)
real, intent(in) :: x
real, dimension(:), intent(in) :: a, b
real, dimension(:,:), intent(out) :: c
integer :: i, j, n, m
n = size(a)
m = size(b)
do j=1,m
do i=1,n
c(i,j) = exp(-x * (a(i)**2 + b(j)**2))
end do
end do
end subroutine
end module
</code></pre>
<p>Cython side:</p>
<p>pygfunc.pyx</p>
<pre><code>cimport numpy as cnp
import numpy as np
cdef extern from "./pygfunc.h":
void c_gfunc(double, int, int, double *, double *, double *)
cdef extern from "./pygfunc.h":
pass
def f(float x, a=-10.0, b=10.0, n=100):
cdef cnp.ndarray ax, c
ax = np.arange(a, b, (b-a)/float(n))
n = ax.shape[0]
c = np.ndarray((n,n), dtype=np.float64, order='F')
c_gfunc(x, n, n, <double *> ax.data, <double *> ax.data, <double *> c.data)
return c
</code></pre>
<p>and the setup file:</p>
<pre><code>from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
ext_modules = [Extension('pygfunc', ['pygfunc.pyx'])]
setup(
name = 'pygfunc',
include_dirs = [np.get_include()],
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules )
</code></pre>
<p>all the files ar in one directory</p>
<p>the fortran files compile ( using NAG Fortran Builder ) pygfunc compiles</p>
<p>but linking them throws a:</p>
<p>error LNK2019: unresolved external symbol _c_gfunc referenced
in function ___pyx_pf_7pygfunc_f </p>
<p>and of course:</p>
<p>fatal error LNK1120: 1 unresolved externals </p>
<p>What am I missing ? or is this way to set up a workflow between Python and Fortran damned from the beginning ?</p>
<p>THX
Martin</p> | 22,524,071 | 1 | 5 | null | 2014-03-14 11:44:08.83 UTC | 19 | 2014-03-20 05:25:55.637 UTC | 2017-05-23 12:33:57.923 UTC | null | -1 | null | 3,362,131 | null | 1 | 21 | python|fortran|cython|fortran-iso-c-binding | 4,959 | <p>Here's a minimum working example.
I used gfortran and wrote the compile commands directly into the setup file.</p>
<p><code>gfunc.f90</code></p>
<pre><code>module gfunc_module
implicit none
contains
subroutine gfunc(x, n, m, a, b, c)
double precision, intent(in) :: x
integer, intent(in) :: n, m
double precision, dimension(n), intent(in) :: a
double precision, dimension(m), intent(in) :: b
double precision, dimension(n, m), intent(out) :: c
integer :: i, j
do j=1,m
do i=1,n
c(i,j) = exp(-x * (a(i)**2 + b(j)**2))
end do
end do
end subroutine
end module
</code></pre>
<p><code>pygfunc.f90</code></p>
<pre><code>module gfunc1_interface
use iso_c_binding, only: c_double, c_int
use gfunc_module, only: gfunc
implicit none
contains
subroutine c_gfunc(x, n, m, a, b, c) bind(c)
real(c_double), intent(in) :: x
integer(c_int), intent(in) :: n, m
real(c_double), dimension(n), intent(in) :: a
real(c_double), dimension(m), intent(in) :: b
real(c_double), dimension(n, m), intent(out) :: c
call gfunc(x, n, m, a, b, c)
end subroutine
end module
</code></pre>
<p><code>pygfunc.h</code></p>
<pre><code>extern void c_gfunc(double* x, int* n, int* m, double* a, double* b, double* c);
</code></pre>
<p><code>pygfunc.pyx</code></p>
<pre><code>from numpy import linspace, empty
from numpy cimport ndarray as ar
cdef extern from "pygfunc.h":
void c_gfunc(double* a, int* n, int* m, double* a, double* b, double* c)
def f(double x, double a=-10.0, double b=10.0, int n=100):
cdef:
ar[double] ax = linspace(a, b, n)
ar[double,ndim=2] c = empty((n, n), order='F')
c_gfunc(&x, &n, &n, <double*> ax.data, <double*> ax.data, <double*> c.data)
return c
</code></pre>
<p><code>setup.py</code></p>
<pre><code>from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# This line only needed if building with NumPy in Cython file.
from numpy import get_include
from os import system
# compile the fortran modules without linking
fortran_mod_comp = 'gfortran gfunc.f90 -c -o gfunc.o -O3 -fPIC'
print fortran_mod_comp
system(fortran_mod_comp)
shared_obj_comp = 'gfortran pygfunc.f90 -c -o pygfunc.o -O3 -fPIC'
print shared_obj_comp
system(shared_obj_comp)
ext_modules = [Extension(# module name:
'pygfunc',
# source file:
['pygfunc.pyx'],
# other compile args for gcc
extra_compile_args=['-fPIC', '-O3'],
# other files to link to
extra_link_args=['gfunc.o', 'pygfunc.o'])]
setup(name = 'pygfunc',
cmdclass = {'build_ext': build_ext},
# Needed if building with NumPy.
# This includes the NumPy headers when compiling.
include_dirs = [get_include()],
ext_modules = ext_modules)
</code></pre>
<p><code>test.py</code></p>
<pre><code># A script to verify correctness
from pygfunc import f
print f(1., a=-1., b=1., n=4)
import numpy as np
a = np.linspace(-1, 1, 4)**2
A, B = np.meshgrid(a, a, copy=False)
print np.exp(-(A + B))
</code></pre>
<p>Most of the changes I made aren't terribly fundamental. Here are the important ones.</p>
<ul>
<li><p>You were mixing double precision and single precision floating point numbers. <em>Don't do that.</em> Use real (Fortran), float (Cython), and float32 (NumPy) together and use double precision (Fortran), double (Cyton), and float64 (NumPy) together. Try not to mix them unintentionally. I assumed you wanted doubles in my example.</p></li>
<li><p>You should pass all variables to Fortran as pointers. It does not match the C calling convention in that regard. The iso_c_binding module in Fortran only matches the C naming convention. Pass arrays as pointers with their size as a separate value. There may be other ways of doing this, but I don't know any.</p></li>
</ul>
<p>I also added some stuff in the setup file to show where you can add some of the more useful extra arguments when building.</p>
<p>To compile, run <code>python setup.py build_ext --inplace</code>. To verify that it works, run the test script.</p>
<p>Here is the example shown on fortran90.org: <a href="https://github.com/arrghb2012/fortran90/tree/master/fcython_mesh">mesh_exp</a></p>
<p>Here are two more that I put together some time ago: <a href="https://github.com/byuimpact/numerical_computing/tree/develop/Python/cython_wrapping/ftridiag">ftridiag</a>, <a href="https://github.com/byuimpact/numerical_computing/tree/develop/Python/cython_wrapping/fssor">fssor</a>
I'm certainly not an expert at this, but these examples may be a good place to start.</p> |
11,152,956 | Example of code to implement a PDF reader | <p>I want to implement a PDF reader in the application that I am doing, I have found several APIs, but none of them were open source.</p>
<p>Does any of you guys know a good free alternative?</p>
<hr />
<h2 id="slight-adaptation-of-dipak-keshariyas-solution-made-by-the-op">Slight adaptation of <a href="https://stackoverflow.com/a/11153601/505893">Dipak Keshariya's solution</a> made by the OP</h2>
<p><strong>First Class</strong></p>
<pre><code>package android.pdf.reader;
import java.io.File;
import java.io.FilenameFilter;
import net.sf.andpdf.pdfviewer.PdfViewerActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class First extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File images = Environment.getExternalStorageDirectory();
File[] imagelist = images.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return ((name.endsWith(".pdf")));
}
});
String[] pdflist = new String[imagelist.length];
for(int i = 0;i<imagelist.length;i++)
{
pdflist[i] = imagelist[i].getName();
}
this.setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, pdflist));
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Object[] imagelist;
String path = ((File) imagelist[(int)id]).getAbsolutePath();
openPdfIntent(path);
}
private void openPdfIntent(String path)
{
try
{
final Intent intent = new Intent(First.this, Second.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
</code></pre>
<p><strong>Second Class</strong></p>
<pre><code>package android.pdf.reader;
import net.sf.andpdf.pdfviewer.PdfViewerActivity;
import android.os.Bundle;
public class Second extends PdfViewerActivity
{
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
public int getPreviousPageImageResource() {
return R.drawable.left_arrow;
}
public int getNextPageImageResource() {
return R.drawable.right_arrow;
}
public int getZoomInImageResource() {
return R.drawable.zoom_in;
}
public int getZoomOutImageResource() {
return R.drawable.zoom_out;
}
public int getPdfPasswordLayoutResource() {
return R.layout.pdf_file_password;
}
public int getPdfPageNumberResource() {
return R.layout.dialog_pagenumber;
}
public int getPdfPasswordEditField() {
return R.id.etPassword;
}
public int getPdfPasswordOkButton() {
return R.id.btOK;
}
public int getPdfPasswordExitButton() {
return R.id.btExit;
}
public int getPdfPageNumberEditField() {
return R.id.pagenum_edit;
}
}
</code></pre> | 11,153,601 | 3 | 3 | null | 2012-06-22 08:48:48.38 UTC | 27 | 2021-07-29 00:30:08.147 UTC | 2021-07-29 00:30:08.147 UTC | null | 5,529,263 | user1369422 | null | null | 1 | 10 | android|pdf | 91,199 | <p>Use below code for that.</p>
<p>First.java</p>
<pre><code>public class First extends ListActivity {
String[] pdflist;
File[] imagelist;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
File images = Environment.getExternalStorageDirectory();
imagelist = images.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return ((name.endsWith(".pdf")));
}
});
pdflist = new String[imagelist.length];
for (int i = 0; i < imagelist.length; i++) {
pdflist[i] = imagelist[i].getName();
}
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, pdflist));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String path = imagelist[(int) id].getAbsolutePath();
openPdfIntent(path);
}
private void openPdfIntent(String path) {
try {
final Intent intent = new Intent(First.this, Second.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>Second.java</p>
<pre><code>public class Second extends PdfViewerActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
public int getPreviousPageImageResource() {
return R.drawable.left_arrow;
}
public int getNextPageImageResource() {
return R.drawable.right_arrow;
}
public int getZoomInImageResource() {
return R.drawable.zoom_in;
}
public int getZoomOutImageResource() {
return R.drawable.zoom_out;
}
public int getPdfPasswordLayoutResource() {
return R.layout.pdf_file_password;
}
public int getPdfPageNumberResource() {
return R.layout.dialog_pagenumber;
}
public int getPdfPasswordEditField() {
return R.id.etPassword;
}
public int getPdfPasswordOkButton() {
return R.id.btOK;
}
public int getPdfPasswordExitButton() {
return R.id.btExit;
}
public int getPdfPageNumberEditField() {
return R.id.pagenum_edit;
}
}
</code></pre>
<p>And declared both activities into your manifest file.</p> |
11,128,464 | git-upload-pack: command not found | <p>I've read this answer about eight-five times, but there's something I'm not understanding correctly:</p>
<p><a href="https://stackoverflow.com/questions/225291/git-upload-pack-command-not-found-how-to-fix-this-correctly">git-upload-pack: command not found, how to fix this correctly</a></p>
<p>When I try to clone a repository on my server, I get the following:</p>
<pre><code>bash: git-upload-pack: command not found
</code></pre>
<p>But when I clone by giving clone the <code>-u /usr/local/bin/git-upload-pack</code> option, all works well.</p>
<p>I guess this makes sense, since that's the position of the git-upload-pack on my server.</p>
<p>The top answer suggests my .bashrc file on server needs to be updated to reflect this, as the result of <code>ssh you@remotemachine echo \$PATH</code> does not return <code>/usr/local/bin</code>. (It returns <code>/usr/bin:/bin:/usr/sbin:/sbin</code>).</p>
<p>But when I look at my .bashrc file, it contains:</p>
<pre><code>export PATH=/usr/local/bin:$PATH
</code></pre>
<p>So now I'm confused.</p>
<p>What do I need to do to avoid using the <code>-u /usr/local/bin/git-upload-pack</code> option every time? Why does <code>ssh you@remotemachine echo \$PATH</code> not return <code>/usr/local/bin</code>? Is this something to do with login and non-login shells?</p>
<p>Please help! Thanks in advance.</p> | 11,247,426 | 5 | 1 | null | 2012-06-20 21:25:41.603 UTC | 8 | 2016-04-29 06:29:49.39 UTC | 2017-05-23 10:30:55.833 UTC | null | -1 | null | 290,820 | null | 1 | 23 | git|bash|shell|command-line | 38,293 | <p>This is connected to this issue: </p>
<p><a href="https://serverfault.com/questions/130834/svnssh-getting-bash-to-load-my-path-over-ssh">https://serverfault.com/questions/130834/svnssh-getting-bash-to-load-my-path-over-ssh</a></p>
<p>Ssh is not loading your environment by default when sending a command without going to interactive mode.</p>
<p>good solution is the one with .ssh/environment file:</p>
<p>in /etc/ssh/sshd_config add:</p>
<pre><code>PermitUserEnvironment yes
</code></pre>
<p>Then just create .ssh/ directory and dump envronment to .ssh/enviroment:</p>
<pre><code>cd ~/
mkdir .ssh
env > .ssh/environment
</code></pre>
<p>Restart SSH</p>
<pre><code>/etc/init.d/sshd restart
</code></pre>
<p>Now when you do this from your local machine:</p>
<pre><code>ssh [email protected] "which git-upload-pack"
</code></pre>
<p>you s'd get </p>
<pre><code>/usr/local/bin/git-upload-pack
</code></pre>
<p>and git clone s'd work. </p> |
11,175,288 | Maven deploy: forcing the deploy even if artifact already exists | <p>I'm building a project, which is made up from several (sometimes unrelated) modules and some more non standard java modules (built with ANT).</p>
<p>Each maven module is deployed to the releases repository on completion.</p>
<p>If the build fails in the middle, I might have some modules already deployed, so if I try to rebuild, the new attempt to deploy will fail since the artifacts are already deployed.</p>
<p>Is it possible to force a deploy or instead, remove the deployed artifact before I deploy again?</p> | 11,322,263 | 3 | 8 | null | 2012-06-24 05:54:03.707 UTC | 7 | 2016-10-28 12:49:02.42 UTC | null | null | null | null | 1,300,730 | null | 1 | 24 | maven | 48,685 | <p>It sounds like the middleware admins have configured your remote repo instance (Nexus or Artifactory or whatever) to not allow artifact redeployment, and as @khmarbaise says there are good reasons for that. Nexus can be configured to allow artifact deletion by users in a particular role or with artifact deletion privileges. If your admins have it set up that way perhaps you can request the delete privilege and remove the offending artifacts. Or, perhaps the Nexus admin will agree to do it for you.</p>
<p>If neither of these is possible, here are some things to try which might keep this from happening in the future:</p>
<ol>
<li>If you are using the <code>release</code> plugin, do a dry run (<code>-DdryRun=true</code> on the release:prepare command line) first. Maven should report any errors without committing to SCM.</li>
<li>Try running <code>mvn install</code> on your group of projects first. This will install the artifacts to your local repo, not the remote. If there's a problem you can whack the artifacts out of your local repo and start from scratch, repeating until you get a complete build.</li>
<li>If you are running a multi-module build, there are <a href="http://www.sonatype.com/books/mvnref-book/reference/_using_advanced_reactor_options.html" rel="noreferrer">command line options</a> that allow resuming a Maven build from a particular project forward.</li>
<li>Define <code>-Dmaven.deploy.skip=true</code> on the Maven command line. This is similar to suggestion #2, except Maven will actually load & configure the <a href="http://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html" rel="noreferrer">deploy plugin</a>, it just won't do the actual deploy to the remote repo. Once everything works, remove the skip property.</li>
</ol> |
10,967,105 | JSON.stringify escaping without need | <p>JSON.stringify is converting my json object to the following string</p>
<blockquote>
<p>{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}</p>
</blockquote>
<p>When it should not be escaped. The result should be as the string quoted below</p>
<blockquote>
<p>{"2003":{"1":{"2":["test"],"3":["test2"]}}}</p>
</blockquote>
<p>Rather than use a general replace of all the escaped quotes and remove ones that could be in the input. How can I set JSON.stringify to not double escape the variables?</p> | 10,967,131 | 2 | 2 | null | 2012-06-10 07:47:23.86 UTC | 10 | 2021-06-18 08:13:54.703 UTC | null | null | null | null | 1,095,495 | null | 1 | 31 | javascript|jquery|json|serialization | 51,577 | <p>You are stringifying a string, not an object:</p>
<pre><code>var str = '{"2003":{"1":{"2":["test"],"3":["test2"]}}}';
var obj = {"2003":{"1":{"2":["test"],"3":["test2"]}}};
console.log( JSON.stringify(str) ); // {\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}
console.log( JSON.stringify(obj) ); // {"2003":{"1":{"2":["test"],"3":["test2"]}}}
</code></pre> |
11,444,164 | How to create a new DateTime object in a specific time zone (preferably the default time zone of my app, not UTC)? | <p>I have set the time zone in <code>/config/application.rb</code>, and I expect all times generated in my app to be in this time zone by default, yet when I create a new <code>DateTime</code> object (using <code>.new</code>), it creates it in <code>GMT</code>. How can I get it to be in my app's time zone?</p>
<p><strong>config/application.rb</strong></p>
<pre class="lang-ruby prettyprint-override"><code>config.time_zone = 'Pacific Time (US & Canada)'
</code></pre>
<p><strong>irb</strong></p>
<pre class="lang-ruby prettyprint-override"><code>DateTime.now
# => Wed, 11 Jul 2012 19:04:56 -0700
mydate = DateTime.new(2012, 07, 11, 20, 10, 0)
# => Wed, 11 Jul 2012 20:10:00 +0000 # GMT, but I want PDT
</code></pre>
<p>Using <code>in_time_zone</code> doesn't work because that just converts the GMT time to PDT time, which is the wrong time:</p>
<pre class="lang-ruby prettyprint-override"><code>mydate.in_time_zone('Pacific Time (US & Canada)')
# => Wed, 11 Jul 2012 13:10:00 PDT -07:00 # wrong time (I want 20:10)
</code></pre> | 11,444,393 | 6 | 0 | null | 2012-07-12 02:12:26.063 UTC | 4 | 2022-06-30 09:23:49.397 UTC | 2022-06-30 09:23:49.397 UTC | null | 74,089 | null | 664,833 | null | 1 | 45 | ruby-on-rails|datetime|timezone|ruby-on-rails-3.1|activesupport | 46,974 | <p>You can use ActiveSupport's <a href="http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html" rel="noreferrer">TimeWithZone</a> (<code>Time.zone</code>) object to create and parse dates in the time zone of your application:</p>
<pre><code>1.9.3p0 :001 > Time.zone.now
=> Wed, 11 Jul 2012 19:47:03 PDT -07:00
1.9.3p0 :002 > Time.zone.parse('2012-07-11 21:00')
=> Wed, 11 Jul 2012 21:00:00 PDT -07:00
</code></pre> |
11,109,836 | Test for string equality / string comparison in Fish shell? | <p>How do you compare two strings in Fish (like <code>"abc" == "def"</code> in other languages)?</p>
<p>So far, I've used a combination of <code>contains</code> (turns out that <code>contains "" $a</code> only returns <code>0</code> if <code>$a</code> is the empty string, although that hasn't seemed to work for me in all cases) and <code>switch</code> (with a <code>case "what_i_want_to_match"</code> and a <code>case '*'</code>). Neither of these methods seem particularly... correct, though.</p> | 11,110,226 | 2 | 4 | null | 2012-06-19 21:36:57.283 UTC | 6 | 2019-06-22 15:14:52.293 UTC | 2016-03-06 03:52:55.85 UTC | null | 402,884 | null | 445,398 | null | 1 | 55 | fish | 25,930 | <pre><code> if [ "abc" != "def" ]
echo "not equal"
end
not equal
if [ "abc" = "def" ]
echo "equal"
end
if [ "abc" = "abc" ]
echo "equal"
end
equal
</code></pre>
<p>or one liner:</p>
<pre><code>if [ "abc" = "abc" ]; echo "equal"; end
equal
</code></pre> |
11,140,483 | How to get list of files with a specific extension in a given folder? | <p>I want to get the file names of all files that have a specific extension in a given folder (and recursively, its subfolders). That is, the file name (and extension), not the full file path. This is incredibly simple in languages like Python, but I'm not familiar with the constructs for this in C++. How can it be done?</p> | 11,142,540 | 6 | 2 | null | 2012-06-21 14:32:59.437 UTC | 17 | 2020-11-13 20:51:36.583 UTC | 2017-09-12 10:30:34.82 UTC | null | 462,608 | null | 1,098,714 | null | 1 | 62 | c++|filesystems|file-management | 98,314 | <pre><code>#define BOOST_FILESYSTEM_VERSION 3
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
/**
* \brief Return the filenames of all files that have the specified extension
* in the specified directory and all subdirectories.
*/
std::vector<fs::path> get_all(fs::path const & root, std::string const & ext)
{
std::vector<fs::path> paths;
if (fs::exists(root) && fs::is_directory(root))
{
for (auto const & entry : fs::recursive_directory_iterator(root))
{
if (fs::is_regular_file(entry) && entry.path().extension() == ext)
paths.emplace_back(entry.path().filename());
}
}
return paths;
}
</code></pre> |
11,426,087 | nginx error "conflicting server name" ignored | <pre><code>server {
#listen 80; ## listen for ipv4; this line is default and implied
#listen [::]:80 default ipv6only=on; ## listen for ipv6
#root /usr/share/nginx/www;
root /home/ubuntu/node-login;
# Make site accessible from
server_name ec2-xx-xx-xxx-xxx.us-west-1.compute.amazonaws.com;
location /{
proxy_pass http://127.0.0.1:8000/;
proxy_redirect off;
}
</code></pre>
<p>}</p>
<p>this results in nignx error [warn] conflicting server name "ec2..." on 0.0.0.0:80 ignored
I dont understand, any explanation appreciated. Thanks.</p> | 14,011,446 | 3 | 8 | null | 2012-07-11 05:28:51.25 UTC | 24 | 2016-02-01 19:57:12.637 UTC | null | null | null | null | 1,447,121 | null | 1 | 150 | nginx | 269,769 | <p>I assume that you're running a Linux, and you're using gEdit to edit your files. In the <code>/etc/nginx/sites-enabled</code>, it may have left a temp file e.g. <code>default~</code> (watch the <code>~</code>). </p>
<p>Depending on your editor, the file could be named <code>.save</code> or something like it. Just run <code>$ ls -lah</code> to see which files are unintended to be there and remove them (Thanks <a href="https://stackoverflow.com/users/82028/tisch">@Tisch</a> for this).</p>
<p>Delete this file, and it will solve your problem.</p> |
12,722,468 | org.json.JSONObject cannot be converted to JSONArray in android | <p>When I try in my localhost it work find. this is the JSON that provide by my localhost.</p>
<p>Y it error in this url <a href="http://api.androidhive.info/contacts/">http://api.androidhive.info/contacts/</a></p>
<pre><code> [{
"id": "1",
"first_name": "man",
"last_name": "woman",
"username": "man",
"password": "4f70432e6369
70de9929bcc6f1b72412",
"email": "[email protected]",
"url": "http:\/\/localhost\/adchara1\/"
}, {
"id": "6",
"first_name": "first",
"last_name": "Last
Name",
"username": "user",
"password": "1a1dc91c907325c69271ddf0c944bc72",
"email": "0",
"url": "ht
tp:\/\/api.androidhive.info\/contacts\/"
}, {
"id": "7",
"first_name": "1",
"last_name": "2",
"username": "us45",
"password": "33d8f54e33896a5722
7b18642979e558",
"email": "[email protected]",
"url": "http:\/\/ugirusgiarto.wordpress.com\/2011\
/10\/27\/json-php-mysql-with-asynctask-progressdialog\/"
}, {
"id": "9",
"first_name": "First Name",
"last_name": "Last
Name",
"username": "Username",
"password": "dc647eb65e6711e155375218212b3964",
"email": "woman@gm
ail.com",
"url": "http:\/\/mobile.cs.fsu.edu\/parse-json-objects-in-asynctask\/"
}]
</code></pre>
<p>x</p>
<p>MainActivity</p>
<pre><code>public class MainActivity extends Activity {
TextView text_1, text_2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new task().execute();
}
class task extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(
MainActivity.this);
InputStream is = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Download data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
@Override
protected Void doInBackground(String... params) {
// String url_select = "http://192.168.10.111/adchara1/";
String url_select = "http://api.androidhive.info/contacts/";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
for (int i = 0; i < Jarray.length(); i++) {
JSONObject Jasonobject = null;
text_1 = (TextView) findViewById(R.id.txt1);
Jasonobject = Jarray.getJSONObject(i);
// get an output on the screen
String id = Jasonobject.getString("id");
String name = Jasonobject.getString("name");
String email = Jasonobject.getString("email");
String address = Jasonobject.getString("address");
String gender = Jasonobject.getString("gender");
text_1.append("\n" + id + "\t\t" + name + "\t\t\t"
+ email + "\t\t\t\t" + address + "\t\t\t\t" + gender
+ "\t\t\t\t" + "\n");
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
</code></pre>
<p>ERROR</p>
<pre><code>Error parsing data org.json.JSONException: Value {
"contacts": [{
"id": "c200",
"gender": "male",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Ravi Tamada"
}, {
"id": "c201",
"gender": "male",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Johnny Depp"
}, {
"id": "c202",
"gender": "male",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Leonardo Dicaprio"
}, {
"id": "c203",
"gender": "male",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "John Wayne"
}, {
"id": "c204",
"gender": "female",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Angelina Jolie"
}, {
"id": "c205",
"gender": "female",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Dido"
}, {
"id": "c206",
"gender": "female",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Adele"
}, {
"id": "c207",
"gender": "male",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Hugh Jackman"
}, {
"id": "c208",
"gender": "male",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Will Smith"
}, {
"id": "c209",
"gender": "male",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Clint Eastwood"
}, {
"id": "c2010",
"gender": "male",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Barack Obama"
}, {
"id": "c2011",
"gender": "female",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Kate Winslet"
}, {
"id": "c2012",
"gender": "male",
"phone": {
"office": "00 000000",
"home": "00 000000",
"mobile": "+91 0000000000"
},
"address": "xx-xx-xxxx,x - street, x - country",
"email": "[email protected]",
"name": "Eminem"
}]
}
of type org.json.JSONObject cannot be converted to JSONArray
</code></pre> | 12,722,563 | 6 | 1 | null | 2012-10-04 07:42:39.613 UTC | 2 | 2018-09-22 20:46:53.32 UTC | 2012-10-04 07:46:45.667 UTC | null | 1,522,562 | null | 1,340,175 | null | 1 | 11 | android|json|url | 62,452 | <p>You could try this:</p>
<pre><code>JSONObject object = new JSONObject(result);
JSONArray Jarray = object.getJSONArray("contacts");
for (int i = 0; i < Jarray.length(); i++)
{
JSONObject Jasonobject = Jarray.getJSONObject(i);
}
</code></pre> |
13,007,123 | Modular Program Design - Combining Monad Transformers in Monad Agnostic functions | <p>I am trying to come up with a modular program design and I, once again, kindly request your help.</p>
<p>As a follow-up to these following posts <a href="https://stackoverflow.com/questions/12968351/monad-transformers-vs-passing-parameters-to-functions">Monad Transformers vs passing Parameters</a> and <a href="https://stackoverflow.com/questions/3077866/large-scale-design-in-haskell/3077912#3077912">Large Scale Design in Haskell</a>, I am trying to build two independent modules that use Monad Transformers but expose Monad-agnostic functions, then combine a Monad-agnostic function from each of these modules into a new Monad-agnostic function.</p>
<p>I have been unable to run the combining function e.g. how do I call <code>mainProgram</code> using <code>runReaderT</code> in the example below ?.</p>
<p>The subsidiary question is: is there a better way to achieve the same modular design goal ?</p>
<hr>
<p>The example has two mock modules (but compiles), one that performs logging and one that reads an user input and manipulates it. The combining function reads the user input, logs it and prints it.</p>
<pre><code>{-# LANGUAGE FlexibleContexts #-}
module Stackoverflow2 where
import Control.Monad.Reader
----
---- From Log Module - Writes the passed message in the log
----
data LogConfig = LC { logFile :: FilePath }
doLog :: (MonadIO m, MonadReader LogConfig m) => String -> m ()
doLog _ = undefined
----
---- From UserProcessing Module - Reads the user Input and changes it to the configured case
----
data MessageCase = LowerCase | UpperCase deriving (Show, Read)
getUserInput :: (MonadReader MessageCase m, MonadIO m) => m String
getUserInput = undefined
----
---- Main program that combines the two
----
mainProgram :: (MonadReader MessageCase m, MonadReader LogConfig m, MonadIO m) => m ()
mainProgram = do input <- getUserInput
doLog input
liftIO $ putStrLn $ "Entry logged: " ++ input
</code></pre> | 13,008,595 | 2 | 0 | null | 2012-10-22 07:55:43.253 UTC | 12 | 2012-10-22 21:54:31.033 UTC | 2017-05-23 12:23:56.677 UTC | null | -1 | null | 1,263,942 | null | 1 | 15 | haskell|monad-transformers | 1,323 | <p>Your <code>mainProgram</code> signature is problematic, because the <code>MonadReader</code> typeclass contains the functional dependency <code>MonadReader r m | m -> r</code>. This essentially means that a single concrete type cannot have a <code>MonadReader</code> instance for multiple different types. So when you say that the type <code>m</code> has both instances <code>MonadReader MessageCase</code> and <code>MonadReader LogConfig</code> it goes against the dependency declaration.</p>
<p>The easiest solution is to change <code>mainProgram</code> to have a non-generic type:</p>
<pre><code>mainProgram :: ReaderT MessageCase (ReaderT LogConfig IO) ()
mainProgram = do input <- getUserInput
lift $ doLog input
liftIO $ putStrLn $ "Entry logged: " ++ input
</code></pre>
<p>This also requires the explicit <code>lift</code> for <code>doLog</code>.</p>
<p>Now you can run the <code>mainProgram</code> by running each <code>ReaderT</code> separately, like this:</p>
<pre><code>main :: IO ()
main = do
let messageCase = undefined :: MessageCase
logConfig = undefined :: LogConfig
runReaderT (runReaderT mainProgram messageCase) logConfig
</code></pre>
<p>If you want to have a generic function that uses two different <code>MonadReader</code> instances, you need to make it explicit in the signature that one reader is a monad transformer on top of the other reader.</p>
<pre><code>mainProgram :: (MonadTrans mt, MonadReader MessageCase (mt m), MonadReader LogConfig m, MonadIO (mt m), MonadIO m) => mt m ()
mainProgram = do input <- getUserInput
lift $ doLog input
liftIO $ putStrLn $ "Entry logged: " ++ input
</code></pre>
<p>However, this has the unfortunate effect that the function is no longer fully generic, because the order in which the two readers appear in the monad stack is locked. Maybe there is a cleaner way to achieve this, but I wasn't able to figure one out from the top of my head without sacrificing (even more) genericity.</p> |
12,715,139 | Python, WSGI, multiprocessing and shared data | <p>I am a bit confused about multiproessing feature of mod_wsgi and about a general design of WSGI applications that would be executed on WSGI servers with multiprocessing ability. </p>
<p>Consider the following directive:</p>
<pre><code>WSGIDaemonProcess example processes=5 threads=1
</code></pre>
<p>If I understand correctly, mod_wsgi will spawn 5 Python (e.g. CPython) processes and any of these processes can receive a request from a user. </p>
<p>The documentation says that:</p>
<blockquote>
<p>Where shared data needs to be visible to all application instances, regardless of which child process they execute in, and changes made to
the data by one application are immediately available to another,
including any executing in another child process, an external data
store such as a database or shared memory must be used. Global
variables in normal Python modules cannot be used for this purpose.</p>
</blockquote>
<p>But in that case it gets really heavy when one wants to be sure that an app runs in any WSGI conditions (including multiprocessing ones). </p>
<p>For example, a simple variable which contains the current amount of connected users - should it be process-safe read/written from/to memcached, or a DB or (if such out-of-the-standard-library mechanisms are available) shared memory? </p>
<p>And will the code like</p>
<pre><code>counter = 0
@app.route('/login')
def login():
...
counter += 1
...
@app.route('/logout')
def logout():
...
counter -= 1
...
@app.route('/show_users_count')
def show_users_count():
return counter
</code></pre>
<p>behave unpredictably in multiprocessing environment?</p>
<p>Thank you!</p> | 12,782,760 | 3 | 5 | null | 2012-10-03 19:06:06.573 UTC | 13 | 2016-09-27 21:31:41.31 UTC | 2012-10-05 19:29:38.66 UTC | null | 240,950 | null | 240,950 | null | 1 | 26 | python|multiprocessing|mod-wsgi|wsgi | 20,101 | <p>There are several aspects to consider in your question. </p>
<p>First, the interaction between apache MPM's and mod_wsgi applications. If you run the mod_wsgi application in embedded mode (no <code>WSGIDaemonProcess</code> needed, <code>WSGIProcessGroup %{GLOBAL}</code>) you inherit multiprocessing/multithreading from the apache MPM's. This should be the fastest option, and you end up having multiple processes and multiple threads per process, depending on your MPM configuration. On the contrary if you run mod_wsgi in daemon mode, with <code>WSGIDaemonProcess <name> [options]</code> and <code>WSGIProcessGroup <name></code>, you have fine control on multiprocessing/multithreading at the cost of a small <a href="http://code.google.com/p/modwsgi/wiki/PerformanceEstimates" rel="noreferrer">overhead</a>.</p>
<p>Within a single apache2 server you may define zero, one, or more named <code>WSGIDaemonProcess</code>es, and each application can be run in one of these processes (<code>WSGIProcessGroup <name></code>) or run in embedded mode with <code>WSGIProcessGroup %{GLOBAL}</code>.</p>
<p>You can check multiprocessing/multithreading by inspecting the <code>wsgi.multithread</code> and <code>wsgi.multiprocess</code> variables.</p>
<p>With your configuration <code>WSGIDaemonProcess example processes=5 threads=1</code> you have 5 independent processes, each with a single thread of execution: no global data, no shared memory, since you are not in control of spawning subprocesses, but mod_wsgi is doing it for you. To share a global state you already listed some possible options: a DB to which your processes interface, some sort of file system based persistence, a daemon process (started outside apache) and socket based IPC.</p>
<p>As pointed out by Roland Smith, the latter could be implemented using a high level API by <a href="http://docs.python.org/library/multiprocessing.html#managers" rel="noreferrer"><code>multiprocessing.managers</code></a>: outside apache you create and start a <code>BaseManager</code> server process</p>
<pre><code>m = multiprocessing.managers.BaseManager(address=('', 12345), authkey='secret')
m.get_server().serve_forever()
</code></pre>
<p>and inside you apps you <code>connect</code>:</p>
<pre><code>m = multiprocessing.managers.BaseManager(address=('', 12345), authkey='secret')
m.connect()
</code></pre>
<p>The example above is dummy, since <code>m</code> has no useful method registered, but <a href="http://docs.python.org/library/multiprocessing.html#using-a-remote-manager" rel="noreferrer">here</a> (python docs) you will find how to create and <em>proxy</em> an object (like the <code>counter</code> in your example) among your processes.</p>
<p>A final comment on your example, with <code>processes=5 threads=1</code>. I understand that this is just an example, but in real world applications I suspect that performance will be comparable with respect to <code>processes=1 threads=5</code>: you should go into the intricacies of sharing data in multiprocessing only if the expected performance boost over the 'single process many threads' model is significant. </p> |
12,869,614 | Iterate an array, n items at a time | <p>I have an array: </p>
<pre><code>[1,2,3,4,5,6,7,8,9,0]
</code></pre>
<p>that I'd like to iterate 3 at a time, which produces</p>
<pre><code>1,2,3 and 4,5,6 and 7,8,9 and 0
</code></pre>
<p>What's the best way to do this in Ruby?</p> | 12,869,638 | 2 | 0 | null | 2012-10-13 03:16:28.76 UTC | 5 | 2012-10-13 03:21:58.833 UTC | null | null | null | null | 796,004 | null | 1 | 51 | ruby | 17,953 | <p>You are looking for <a href="http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_slice">#each_slice</a>.</p>
<pre><code>data.each_slice(3) {|slice| ... }
</code></pre> |
12,690,557 | Mercurial / hg - abort: outstanding uncommitted merges | <p>I have a master repo on host1 and made an update to a repo on host2. I <code>hg push</code>ed the changes from host2 to host1 with</p>
<pre><code>[mpenning@host2 login]$ hg push ssh://host1//opt/python/login
</code></pre>
<p>However, when I try to update or merge, I get</p>
<pre><code>[mpenning@host1 login]$ hg update
abort: outstanding uncommitted merges
[mpenning@host1 login]$ hg merge
abort: outstanding uncommitted merges
[mpenning@host1 login]$
</code></pre>
<p>I also tried a <code>hg pull</code> from host1, but that didn't work either...</p>
<pre><code>[mpenning@host1 login]$ hg pull ssh://host2//opt/python/login
running ssh host2 'hg -R /opt/python/login serve --stdio'
mpenning@host2's password:
pulling from ssh://host2//opt/python/login
searching for changes
no changes found
[mpenning@host1 login]$ hg merge
abort: outstanding uncommitted merges
[mpenning@host1 login]$
</code></pre>
<p>What do I need to do to update my master repo on host1 with the changes from host2?</p>
<hr>
<p>More information about the repo on host1...</p>
<pre><code>[mpenning@host1 login]$ hg parents
changeset: 27:6d530d533997
user: Mike Pennington <[email protected]>
date: Wed Sep 26 11:44:51 2012 -0500
files: mp_getconf.py
description:
fix issue where config retrieval was broken
changeset: 29:eaf3b5aacfe6
user: Mike Pennington <[email protected]>
date: Wed Sep 26 11:43:15 2012 -0500
files: mp_getconf.py
description:
fix artifact of using the script to run generic commands, but this broke config retrieval
[mpenning@host1 login]$
</code></pre> | 12,690,559 | 2 | 0 | null | 2012-10-02 12:47:45.143 UTC | 13 | 2017-08-31 18:23:46.627 UTC | 2017-08-31 18:23:46.627 UTC | null | -1 | null | 667,301 | null | 1 | 55 | mercurial | 48,907 | <p><code>hg update --clean -r tip</code> resolved the problem...</p>
<pre><code>[mpenning@host1 login]$ hg update --clean -r tip
resolving manifests
getting Protocol.py
getting Session.py
getting mp_getconf.py
getting mp_runcmd.py
4 files updated, 0 files merged, 0 files removed, 0 files unresolved
[mpenning@host1 login]$ hg up
resolving manifests
0 files updated, 0 files merged, 0 files removed, 0 files unresolved
[mpenning@host1 login]$
</code></pre> |
11,405,493 | How to get everything after a certain character? | <p>I've got a string and I'd like to get everything after a certain value. The string always starts off with a set of numbers and then an underscore. I'd like to get the rest of the string after the underscore. So for example if I have the following strings and what I'd like returned:</p>
<pre><code>"123_String" -> "String"
"233718_This_is_a_string" -> "This_is_a_string"
"83_Another Example" -> "Another Example"
</code></pre>
<p>How can I go about doing something like this?</p> | 11,405,509 | 9 | 0 | null | 2012-07-10 01:35:19.23 UTC | 36 | 2021-12-24 11:20:32.587 UTC | 2018-02-20 23:25:52.377 UTC | null | 4,059,832 | null | 1,048,676 | null | 1 | 185 | php|string | 348,151 | <p>The <a href="http://php.net/strpos" rel="noreferrer"><code>strpos()</code></a> finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.</p>
<pre><code>$data = "123_String";
$whatIWant = substr($data, strpos($data, "_") + 1);
echo $whatIWant;
</code></pre>
<hr>
<p>If you also want to check if the underscore character (<code>_</code>) exists in your string before trying to get it, you can use the following:</p>
<pre><code>if (($pos = strpos($data, "_")) !== FALSE) {
$whatIWant = substr($data, $pos+1);
}
</code></pre> |
11,209,639 | Can I write into the console in a unit test? If yes, why doesn't the console window open? | <p>I have a test project in Visual Studio. I use <em>Microsoft.VisualStudio.TestTools.UnitTesting</em>.</p>
<p>I add this line in one of my unit tests:</p>
<pre><code>Console.WriteLine("Some foo was very angry with boo");
Console.ReadLine();
</code></pre>
<p>When I run the test, the test passes, but the console window is not opened at all.</p>
<p>Is there a way to make the console window available to be interacted via a unit test?</p> | 11,209,805 | 12 | 4 | null | 2012-06-26 14:28:50.913 UTC | 21 | 2020-07-27 14:29:25.113 UTC | 2020-07-27 14:06:08.84 UTC | null | 63,550 | null | 136,141 | null | 1 | 190 | c#|.net|visual-studio|unit-testing|console-application | 212,571 | <p>NOTE: The original answer below should work for any version of Visual Studio up through Visual Studio 2012. Visual Studio 2013 does not appear to have a Test Results window any more. Instead, if you need test-specific output you can use @Stretch's suggestion of <code>Trace.Write()</code> to write output to the Output window.</p>
<hr />
<p>The <code>Console.Write</code> method does not write to the "console" -- it writes to whatever is hooked up to the standard output handle for the running process. Similarly, <code>Console.Read</code> reads input from whatever is hooked up to the standard input.</p>
<p>When you run a unit test through Visual Studio 2010, standard output is redirected by the test harness and stored as part of the test output. You can see this by right-clicking the Test Results window and adding the column named "Output (StdOut)" to the display. This will show anything that was written to standard output.</p>
<p>You <em>could</em> manually open a console window, using <a href="https://en.wikipedia.org/wiki/Platform_Invocation_Services" rel="noreferrer">P/Invoke</a> as <a href="https://stackoverflow.com/questions/11209639/can-i-write-into-the-console-in-a-unit-test-if-yes-why-doesnt-the-console-win/11209736#11209736">sinni800 says</a>. From reading the <code>AllocConsole</code> documentation, it appears that the function will reset <code>stdin</code> and <code>stdout</code> handles to point to the new console window. (I'm not 100% sure about that; it seems kind of wrong to me if I've already redirected <code>stdout</code> for Windows to steal it from me, but I haven't tried.)</p>
<p>In general, though, I think it's a bad idea; if all you want to use the console for is to dump more information about your unit test, the output is there for you. Keep using <code>Console.WriteLine</code> the way you are, and check the output results in the Test Results window when it's done.</p> |
16,667,148 | Instead of NULL how do I show `0` in result with SELECT statement sql? | <p>I have one <code>stored procedure</code> which is giving me an output (I stored it in a #temp table) and that output I'm passing to another <code>scalar function</code>.</p>
<blockquote>
<p>Instead of NULL how do I show <code>0</code> in result with SELECT statement sql?</p>
</blockquote>
<p>For example stored proc is having select statement like follwing :</p>
<pre><code>SELECT Ename , Eid , Eprice , Ecountry from Etable
Where Ecountry = 'India'
</code></pre>
<p>Which is giving me output like</p>
<pre><code>Ename Eid Eprice Ecountry
Ana 12 452 India
Bin 33 NULL India
Cas 11 NULL India
</code></pre>
<p>Now instead of showing <code>NULL</code> how can I show price as <code>0</code> ?</p>
<p>What should be mention in <code>SELECT</code> statement to make <code>NULL</code> as <code>0</code> ?</p> | 16,667,170 | 6 | 0 | null | 2013-05-21 09:56:44.413 UTC | 9 | 2020-12-18 10:32:25.593 UTC | null | null | null | null | 428,073 | null | 1 | 24 | sql|sql-server|tsql | 101,330 | <p>Use <a href="http://msdn.microsoft.com/en-us/library/ms190349.aspx" rel="noreferrer"><code>coalesce()</code></a>:</p>
<pre><code>select coalesce(Eprice, 0) as Eprice
</code></pre>
<p>In SQL Server only, you can save two characters with <a href="http://msdn.microsoft.com/en-us/library/ms184325.aspx" rel="noreferrer"><code>isnull()</code></a>:</p>
<pre><code>select isnull(Eprice, 0) as Eprice
</code></pre> |
17,076,372 | ruby sort_by multiple fields | <p>I'm running Ruby 1.9.3p392.</p>
<pre><code>Item = Struct.new( :name, :dir, :sort_dir )
entries = ftp.list()
entries.map!{|e| Net::FTP::List.parse(e) }.map!{|e| Item.new( e.basename, e.dir?, (e.dir? ? 0 : 1) ) }
render json: entries.sort_by{ |e| [ e.sort_dir, e.name ]}
</code></pre>
<p>For some reason, I am not getting the results back as expected. </p>
<p>I do get all folders first followed by all files, however, the name sorting is failing.</p>
<p>As an example, I get these for my folders:</p>
<ol>
<li>content</li>
<li>images</li>
<li>bin</li>
</ol>
<p>For files:</p>
<ol>
<li>global.asax</li>
<li>web.config</li>
<li>favicon.ico</li>
</ol>
<p>It groups the dir/file portion correct, but the names are sorted incorrectly.</p>
<p>The output to the console looks like this after sorting:</p>
<pre><code>#<struct FtpController::Item name="Content", dir=true, sort_dir=0>
#<struct FtpController::Item name="Images", dir=true, sort_dir=0>
#<struct FtpController::Item name="Scripts", dir=true, sort_dir=0>
#<struct FtpController::Item name="Views", dir=true, sort_dir=0>
#<struct FtpController::Item name="bin", dir=true, sort_dir=0>
#<struct FtpController::Item name="Global.asax", dir=false, sort_dir=1>
#<struct FtpController::Item name="Web.config", dir=false, sort_dir=1>
#<struct FtpController::Item name="favicon.ico", dir=false, sort_dir=1>
#<struct FtpController::Item name="packages.config", dir=false, sort_dir=1>
#<struct FtpController::Item name="robots.txt", dir=false, sort_dir=1>
</code></pre> | 17,076,703 | 1 | 0 | null | 2013-06-12 22:20:24.91 UTC | 3 | 2013-06-13 00:45:51.347 UTC | 2013-06-13 00:45:51.347 UTC | null | 128,421 | null | 319,518 | null | 1 | 37 | ruby|sorting | 30,828 | <p>Your sorting works correctly in MRI Ruby 1.8.7, 1.9.3, and 2.0.0:</p>
<pre><code>Item = Struct.new(:name, :dir, :sort_dir)
entries = [Item.new('favicon.ico', false, 1), Item.new('bin', true, 0),
Item.new('web.config', false, 1), Item.new('images', true, 0),
Item.new('global.asax', false, 1), Item.new('content', true, 0)]
entries.sort_by{|e| [e.sort_dir, e.name]}
# => [#<struct Item name="bin", dir=true, sort_dir=0>,
# #<struct Item name="content", dir=true, sort_dir=0>,
# #<struct Item name="images", dir=true, sort_dir=0>,
# #<struct Item name="favicon.ico", dir=false, sort_dir=1>,
# #<struct Item name="global.asax", dir=false, sort_dir=1>,
# #<struct Item name="web.config", dir=false, sort_dir=1>]
</code></pre>
<p>Have you tried outputting the result of your <code>sort_by</code> to a console? I'm not familiar with the <code>render json:</code> portion of your code, but perhaps that's where things are going wrong. My best guess is that somehow in the conversion to JSON (if that's what it does) the sorting is getting messed up.</p>
<p>My other idea is that perhaps you expect <code>sort_by</code> to modify <code>entries</code>; it does not. If you want <code>entries</code> itself to be sorted after the call, use <code>sort_by!</code> (note the <code>!</code> at the end of the method name).</p>
<p><strong>Update:</strong> It looks like the issue is that you want a case-insensitive search. Simply adding <code>upcase</code> should do the trick:</p>
<pre><code>entries.sort_by{|e| [e.sort_dir, e.name.upcase]}
</code></pre> |
16,775,197 | Building and running app via Gradle and Android Studio is slower than via Eclipse | <p>I have a multi-project (~10 modules) of which building takes about 20-30 seconds each time. When I press Run in Android Studio, I have to wait every time to rebuild the app, which is extremely slow.</p>
<p>Is it possible to automate building process in Android Studio? Or do you have any advice on how to make this process faster?</p>
<p>In Eclipse, thanks to automatic building, running the same project on an emulator takes about 3-5 seconds.</p>
<p>This is my build.gradle file (app module):</p>
<pre><code>buildscript {
repositories {
maven { url 'http://repo1.maven.org/maven2' }
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4'
}
}
apply plugin: 'android'
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
compile project(':libraries:SharedLibs')
compile project(':libraries:actionbarsherlock')
compile project(':libraries:FacebookSDK')
compile project(':libraries:GooglePlayServices')
compile project(':libraries:HorizontalGridView')
compile project(':libraries:ImageViewTouch')
compile project(':libraries:SlidingMenu')
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 8
targetSdkVersion 16
}
}
</code></pre> | 19,500,539 | 28 | 12 | null | 2013-05-27 14:20:09.883 UTC | 257 | 2020-10-06 09:14:07.3 UTC | 2015-10-09 12:49:57.3 UTC | null | 3,684,713 | null | 2,021,293 | null | 1 | 473 | android|gradle|android-studio|build.gradle | 225,682 | <h2>Hardware</h2>
<p>I'm sorry, but upgrading development station to SSD and tons of ram has probably a bigger influence than points below combined. </p>
<h2>Tools versions</h2>
<p>Increasing build performance has major priority for the development teams, so make sure you are using latest <a href="https://docs.gradle.org/current/release-notes" rel="noreferrer">Gradle</a> and <a href="http://tools.android.com/tech-docs/new-build-system" rel="noreferrer">Android Gradle Plugin</a>.</p>
<h2>Configuration File</h2>
<p>Create a file named <code>gradle.properties</code> in whatever directory applies:</p>
<ul>
<li><code>/home/<username>/.gradle/</code> (Linux)</li>
<li><code>/Users/<username>/.gradle/</code> (Mac)</li>
<li><code>C:\Users\<username>\.gradle</code> (Windows)</li>
</ul>
<p>Append:</p>
<pre><code># IDE (e.g. Android Studio) users:
# Settings specified in this file will override any Gradle settings
# configured through the IDE.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# The Gradle daemon aims to improve the startup and execution time of Gradle.
# When set to true the Gradle daemon is to run the build.
# TODO: disable daemon on CI, since builds should be clean and reliable on servers
org.gradle.daemon=true
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# https://medium.com/google-developers/faster-android-studio-builds-with-dex-in-process-5988ed8aa37e#.krd1mm27v
org.gradle.jvmargs=-Xmx5120m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
org.gradle.parallel=true
# Enables new incubating mode that makes Gradle selective when configuring projects.
# Only relevant projects are configured which results in faster builds for large multi-projects.
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:configuration_on_demand
org.gradle.configureondemand=true
# Set to true or false to enable or disable the build cache.
# If this parameter is not set, the build cache is disabled by default.
# http://tools.android.com/tech-docs/build-cache
android.enableBuildCache=true
</code></pre>
<p>Gradle properties works local if you place them at <code>projectRoot\gradle.properties</code> and globally if you place them at <code>user_home\.gradle\gradle.properties</code>. Properties applied if you run gradle tasks from console or directly from idea:</p>
<h2>IDE Settings</h2>
<p>It is possible to tweak Gradle-IntelliJ integration from the IDE settings GUI. Enabling "offline work" (check answer from <a href="https://stackoverflow.com/a/23648341/624706">yava</a> below) will disable real network requests on every "sync gradle file".</p>
<p><img src="https://i.stack.imgur.com/hGnDg.png" alt="IDE settings"></p>
<h2>Native multi-dex</h2>
<p>One of the slowest steps of the apk build is converting java bytecode into single dex file. Enabling native multidex (minSdk 21 for debug builds only) will help the tooling to reduce an amount of work (check answer from <a href="https://stackoverflow.com/a/30070657/624706">Aksel Willgert</a> below).</p>
<h2>Dependencies</h2>
<p>Prefer <code>@aar</code> dependencies over library sub-projects. </p>
<p>Search aar package on <a href="http://search.maven.org/" rel="noreferrer">mavenCentral</a>, <a href="https://bintray.com/bintray/jcenter" rel="noreferrer">jCenter</a> or use <a href="https://jitpack.io/" rel="noreferrer">jitpack.io</a> to build any library from github. If you are not editing sources of the dependency library you should not build it every time with your project sources. </p>
<h2>Antivirus</h2>
<p>Consider to exclude project and cache files from antivirus scanning. This is obviously a trade off with security (don't try this at home!). But if you switch between branches a lot, then antivirus will rescan files before allowing gradle process to use it, which slows build time (in particular AndroidStudio sync project with gradle files and indexing tasks). Measure build time and process CPU with and without antivirus enabled to see if it is related. </p>
<h2>Profiling a build</h2>
<p>Gradle has built-in support for <a href="https://docs.gradle.org/current/userguide/tutorial_gradle_command_line.html#sec:profiling_build" rel="noreferrer">profiling projects</a>. Different projects are using a different combination of plugins and custom scripts. Using <code>--profile</code> will help to find bottlenecks. </p> |
25,807,545 | What is "Constrain to margin" in Storyboard in Xcode 6 | <p>I am Working with autolayout and constraints and found there is a <code>Constrain to margins</code> option in Xcode 6 which was not present in Xcode 5 and is checked by default.</p>
<p>I created a test project then I added a <code>UITableView</code> on a ViewController with the frame set to the same size as view and added constraints</p>
<p><strong>Xcode 6</strong>
You can see here even though tableview has the same frame as view Xcode suggests to add -16 as constraint whereas Xcode 5 would suggest adding spacing 0.</p>
<p><img src="https://i.stack.imgur.com/aZF5T.png" alt="With Constrain to margin checked"></p>
<p>Now when you uncheck "Constrain to margin" option it behaves same as Xcode 5 and would suggest adding 0 as constraint </p>
<p><img src="https://i.stack.imgur.com/ncu1i.png" alt="With Constrain to margin UnChecked"></p>
<p>Also, I found that once I add constraint with Constrain to margin checked, I am no longer able to open the storyboard file in Xcode 5 so it's definitely something new in Xcode 6</p>
<p>Hopefully, I am able to explain my question properly. I would like to understand what "Constrain to margin" actually does and when I should and should not use it. I do apologize if it's something very simple and obvious.</p>
<p><strong>EDIT</strong></p>
<p>I found something about layout margins in <a href="https://developer.apple.com/LIBRARY/PRERELEASE/IOS/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instp/UIView/layoutMargins" rel="noreferrer">discussion here</a> , I wonder if it's related to this.</p> | 28,692,783 | 3 | 7 | null | 2014-09-12 11:42:52.783 UTC | 150 | 2019-07-17 17:12:31.48 UTC | 2019-07-17 17:12:31.48 UTC | null | 1,032,372 | null | 2,321,467 | null | 1 | 256 | ios|xcode|storyboard|autolayout|xcode6 | 92,408 | <p>I don't understand at all why people are complaining that "<em>Margins would cause an outright crash on anything prior to iOS 8.</em>"</p>
<blockquote>
<p>Setting your constraints relative to margin in a xib file or storyboard <strong>DOES NOT</strong> make your app crash on iOS7, and it <strong>DOES NOT</strong> make a UI difference on your iOS7 device neither, as long as you don't touch the <code>UIView.layoutMargins</code> and <code>UIView.preservesSuperviewLayoutMargins</code> properties in your code.</p>
</blockquote>
<h3>What is Margins in iOS8</h3>
<p>Layout margins represent padding around the <strong>interior</strong> of a <code>UIView</code> that the layout system can use when laying out subviews - to ensure that a gap is left between the edge of a view and a subview. In this respect it is very much like the padding property associated with blocks in CSS.</p>
<p><img src="https://dl.dropboxusercontent.com/s/8y3tavoeoritz19/Screen%20Shot%202558-02-23%20at%204.04.17%20PM.png?dl=0" alt="enter image description here" /></p>
<p>By default, a <code>UIView</code> has layout margins of 8 points on each side, and this can not be changed in <strong>Interface Builder</strong>. However, by setting the <code>UIView.layoutMargins</code> property in the code, which is only available on iOS8, you are able to adjust these values.</p>
<blockquote>
<p>You can get IB to display the margins with <strong>Editor > Canvas > Show Layout Rectangles:</strong>
<img src="https://dl.dropboxusercontent.com/s/yahgyf9jnumbovl/show_layout_rectangles.png?dl=0" alt="enter image description here" /></p>
</blockquote>
<p>Margins can be used to help layout your views and subviews. Every <code>UIView</code> come with margins by default, but they only affect view placement when you set up a constraint that is related to a margin.</p>
<h3>How to use Margins</h3>
<p>The only way to use margins in Interface Builder is to check the <strong>Relative to margin</strong> option while configuring your constraints. This is how you direct your constraint to <em>Use margins instead of edges when laying out my view.</em></p>
<p><img src="https://dl.dropboxusercontent.com/s/jea4s3m8zey4q6l/Screen%20Shot%202558-02-23%20at%204.57.25%20PM.png?dl=0" alt="enter image description here" /></p>
<p>Let's take a look at four different ways of setting up a leading constraint between a view and its subview. For each constraint we review the <strong>first association described will be the subview's leading</strong>, and the <strong>second will be superview's leading</strong>. What you want to pay close attention to is the check and uncheck status of the <strong>Relative to margin</strong> option of each constraint end, because that defines whether the constraint is tied to the margin or the edge of the view.</p>
<ol>
<li>First item(uncheck), second item(check): In this case, we're declaring that subview's left edge should align to superview's left margin(as shown in this image).</li>
</ol>
<p><img src="https://dl.dropboxusercontent.com/s/r1bnsky2mahq9mw/Screen%20Shot%202558-02-23%20at%205.13.32%20PM.png?dl=0" alt="enter image description here" /></p>
<ol start="2">
<li>First item(uncheck), second item(uncheck): Both using edge, <strong>not margin</strong>. In this case, we're declaring that subview's left edge should align to superview's left edge.</li>
</ol>
<p><img src="https://dl.dropboxusercontent.com/s/ncj55zl5mz78r4z/Screen%20Shot%202558-02-23%20at%205.18.30%20PM.png?dl=0" alt="enter image description here" /></p>
<ol start="3">
<li>First item(check), second item(uncheck): In this case, we're declaring that subview's left margin should align to superview's left edge. This kind of layout actually makes the subview overlap the superview.</li>
</ol>
<p><img src="https://dl.dropboxusercontent.com/s/cc6a8gaxnz18cbu/Screen%20Shot%202558-02-23%20at%205.23.36%20PM.png?dl=0" alt="enter image description here" /></p>
<ol start="4">
<li>First item(check), second item(check). This actually has a same effect as case 2, since both subview and superview has a same default margin. We're declaring that subview's left margin should align to superview's left margin.</li>
</ol>
<p><img src="https://dl.dropboxusercontent.com/s/ncj55zl5mz78r4z/Screen%20Shot%202558-02-23%20at%205.18.30%20PM.png?dl=0" alt="enter image description here" /></p>
<h3>What is good about Margins</h3>
<p>This new feature (iOS8) only impacts UI development if you decide to use margins.</p>
<p>By using margins you can adjust the placement of multiple subviews that share a common relation to a shared superview by changing the value of a single property. This is a clear win over setting all associated constraints with fixed values, because if you need to update all the spacing, instead of changing each value one by one, you can simultaneously modify all relevant placement by updating the superview's margin with a single line of code like this one:</p>
<pre><code>self.rootView.layoutMargins = UIEdgeInsetsMake(0, 50, 0, 0);
</code></pre>
<p>To illustrate this benefit, in the following case all subviews' left edges are aligned to their superview's left margin. Thus, changing superview's left margin will affect all subviews at the same time.</p>
<p><img src="https://dl.dropboxusercontent.com/s/ggmjfujf1vm9by0/Screen%20Shot%202558-02-23%20at%205.47.24%20PM.png?dl=0" alt="enter image description here" /></p> |
10,086,989 | .htaccess file to allow access to images folder to view pictures? | <p>I have an images folder at the following URL.</p>
<pre><code>www.mysite.com/uploads/
</code></pre>
<p>On a different page:</p>
<pre><code>www.mysite.com/search.php/
</code></pre>
<p>I am trying to access the images wherein, with a correct tag link, however I get the :</p>
<pre><code>Forbidden
You don't have permission to access /uploads/ on this server.
</code></pre>
<p>So I went and started dabbling with a <code>.htaccess</code> file, and I have no idea what I am doing ,I tried looking at some documentation but with no luck, I even took an example off another question..Here is how my <code>.htaccess</code> file looks atm:</p>
<pre><code><FilesMatch "\.(gif|jpe?g|png)$">
Order allow,deny
Allow from all
</FilesMatch>
<Directory /uploads>
# All access controls and authentication are disabled
# in this directory
Satisfy Any
Allow from all
</Directory>
</code></pre>
<p>Any ideas on how I can have it allow access to that folder?</p> | 10,091,039 | 4 | 5 | null | 2012-04-10 10:26:01.29 UTC | 4 | 2020-12-20 06:53:10.977 UTC | 2012-04-10 10:30:02.32 UTC | null | 765,890 | null | 1,225,935 | null | 1 | 18 | php|apache|.htaccess | 115,925 | <pre><code><Directory /uploads>
Options +Indexes
</Directory>
</code></pre> |
9,849,776 | Calling a mapreduce job from a simple java program | <p>I have been trying to call a mapreduce job from a simple java program in the same package.. I tried to refer the mapreduce jar file in my java program and call it using the <code>runJar(String args[])</code> method by also passing the input and output paths for the mapreduce job.. But the program dint work.. </p>
<hr>
<p>How do I run such a program where I just use pass input, output and jar path to its main method?? Is it possible to run a mapreduce job (jar) through it?? I want to do this because I want to run several mapreduce jobs one after another where my java program vl call each such job by referring its jar file.. If this gets possible, I might as well just use a simple servlet to do such calling and refer its output files for the graph purpose..</p>
<hr>
<pre><code>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author root
*/
import org.apache.hadoop.util.RunJar;
import java.util.*;
public class callOther {
public static void main(String args[])throws Throwable
{
ArrayList arg=new ArrayList();
String output="/root/Desktp/output";
arg.add("/root/NetBeansProjects/wordTool/dist/wordTool.jar");
arg.add("/root/Desktop/input");
arg.add(output);
RunJar.main((String[])arg.toArray(new String[0]));
}
}
</code></pre> | 9,850,096 | 6 | 0 | null | 2012-03-24 06:56:02.613 UTC | 25 | 2019-01-17 02:22:39.37 UTC | 2012-03-25 07:37:50.873 UTC | null | 1,289,587 | null | 1,289,587 | null | 1 | 21 | java|hadoop|mapreduce | 34,140 | <p>Oh please don't do it with <code>runJar</code>, the Java API is very good.</p>
<p>See how you can start a job from normal code:</p>
<pre><code>// create a configuration
Configuration conf = new Configuration();
// create a new job based on the configuration
Job job = new Job(conf);
// here you have to put your mapper class
job.setMapperClass(Mapper.class);
// here you have to put your reducer class
job.setReducerClass(Reducer.class);
// here you have to set the jar which is containing your
// map/reduce class, so you can use the mapper class
job.setJarByClass(Mapper.class);
// key/value of your reducer output
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
// this is setting the format of your input, can be TextInputFormat
job.setInputFormatClass(SequenceFileInputFormat.class);
// same with output
job.setOutputFormatClass(TextOutputFormat.class);
// here you can set the path of your input
SequenceFileInputFormat.addInputPath(job, new Path("files/toMap/"));
// this deletes possible output paths to prevent job failures
FileSystem fs = FileSystem.get(conf);
Path out = new Path("files/out/processed/");
fs.delete(out, true);
// finally set the empty out path
TextOutputFormat.setOutputPath(job, out);
// this waits until the job completes and prints debug out to STDOUT or whatever
// has been configured in your log4j properties.
job.waitForCompletion(true);
</code></pre>
<p>If you are using an external cluster, you have to put the following infos to your configuration via:</p>
<pre><code>// this should be like defined in your mapred-site.xml
conf.set("mapred.job.tracker", "jobtracker.com:50001");
// like defined in hdfs-site.xml
conf.set("fs.default.name", "hdfs://namenode.com:9000");
</code></pre>
<p>This should be no problem when the <code>hadoop-core.jar</code> is in your application containers classpath.
But I think you should put some kind of progress indicator to your web page, because it may take minutes to hours to complete a hadoop job ;)</p>
<p><strong>For YARN (> Hadoop 2)</strong></p>
<p>For YARN, the following configurations need to be set.</p>
<pre><code>// this should be like defined in your yarn-site.xml
conf.set("yarn.resourcemanager.address", "yarn-manager.com:50001");
// framework is now "yarn", should be defined like this in mapred-site.xm
conf.set("mapreduce.framework.name", "yarn");
// like defined in hdfs-site.xml
conf.set("fs.default.name", "hdfs://namenode.com:9000");
</code></pre> |
9,798,010 | CSS Transitions with :before and :after pseudo elements | <p>Can't seem to animate pseudo elements with -webkit-transition. The fiddle below shows what I mean when run in Chrome/Safari, I guess this isn't supported right now?</p>
<p><a href="http://jsfiddle.net/4rnsx/130/" rel="noreferrer">http://jsfiddle.net/4rnsx/130/</a></p> | 14,506,626 | 3 | 0 | null | 2012-03-21 02:53:57.56 UTC | 4 | 2013-07-23 11:43:50.673 UTC | 2012-03-21 15:45:03.417 UTC | null | 106,224 | null | 229,581 | null | 1 | 30 | css|webkit|css-transitions|pseudo-element | 41,926 | <p>Fixed in Google Chrome on January 3rd, 2013.</p>
<p>By now (I do update this list) it's supported in:</p>
<ul>
<li>FireFox 4.0 and above</li>
<li>Chrome 26 and above</li>
<li>IE 10 and above</li>
</ul>
<p>Waiting for Safari and Chrome for Android to pull these updates.</p>
<p>You can <a href="http://codepen.io/anon/pen/lBIxu">test it yourself in your browser</a>, or</p>
<p>See the <a href="http://css-tricks.com/transitions-and-animations-on-css-generated-content/">browser support table</a>.</p> |
9,783,765 | What is sharedUserId in Android, and how is it used? | <p>I am confused in sharedUserID.what is use of sharedUserId?How to use?Where to use in android? </p> | 9,784,342 | 2 | 1 | null | 2012-03-20 08:52:49.907 UTC | 16 | 2022-07-28 10:40:45.59 UTC | 2014-01-16 04:21:57.443 UTC | null | 864,358 | null | 1,266,092 | null | 1 | 69 | java|android|android-intent|android-emulator|android-ndk | 63,967 | <p>SharedUserId is used to share the data,processes etc between two or more applications.
It is defined in AndroidManifest.xml like,</p>
<pre><code><manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:sharedUserId="android.uid.shared"
android:sharedUserLabel="@string/sharedUserLabel"
...>
</code></pre>
<p>and define the shared parameter in Android.mk for that app, like</p>
<pre><code>LOCAL_CERTIFICATE := shared
</code></pre>
<p>Hope its helpful to you.</p> |
9,708,902 | In practice, what are the main uses for the "yield from" syntax in Python 3.3? | <p>I'm having a hard time wrapping my brain around <a href="http://www.python.org/dev/peps/pep-0380/" rel="noreferrer">PEP 380</a>.</p>
<ol>
<li>What are the situations where <code>yield from</code> is useful?</li>
<li>What is the classic use case?</li>
<li>Why is it compared to micro-threads?</li>
</ol>
<p>So far I have used generators, but never really used coroutines (introduced by <a href="http://www.python.org/dev/peps/pep-0342/" rel="noreferrer">PEP-342</a>). Despite some similarities, generators and coroutines are basically two different concepts. Understanding coroutines (not only generators) is the key to understanding the new syntax.</p>
<p>IMHO <strong>coroutines are the most obscure Python feature</strong>, most books make it look useless and uninteresting.</p>
<hr />
<p>Thanks for the great answers, but special thanks to <a href="https://stackoverflow.com/users/500584/agf">agf</a> and his comment linking to <a href="http://www.dabeaz.com/coroutines/" rel="noreferrer">David Beazley presentations</a>.</p> | 26,109,157 | 10 | 2 | null | 2012-03-14 19:33:41.833 UTC | 390 | 2022-08-11 10:11:49.267 UTC | 2022-02-17 13:39:10.267 UTC | null | 4,298,200 | null | 444,036 | null | 1 | 597 | python|yield | 206,683 | <p>Let's get one thing out of the way first. The explanation that <code>yield from g</code> is equivalent to <code>for v in g: yield v</code> <strong>does not even begin to do justice</strong> to what <code>yield from</code> is all about. Because, let's face it, if all <code>yield from</code> does is expand the <code>for</code> loop, then it does not warrant adding <code>yield from</code> to the language and preclude a whole bunch of new features from being implemented in Python 2.x.</p>
<p>What <code>yield from</code> does is it <strong><em>establishes a transparent bidirectional connection between the caller and the sub-generator</em></strong>:</p>
<ul>
<li><p>The connection is "transparent" in the sense that it will propagate everything correctly too, not just the elements being generated (e.g. exceptions are propagated).</p></li>
<li><p>The connection is "bidirectional" in the sense that data can be both sent <em>from</em> and <em>to</em> a generator.</p></li>
</ul>
<p>(<em>If we were talking about TCP, <code>yield from g</code> might mean "now temporarily disconnect my client's socket and reconnect it to this other server socket".</em>)</p>
<p>BTW, if you are not sure what <em>sending data to a generator</em> even means, you need to drop everything and read about <em>coroutines</em> first—they're very useful (contrast them with <em>subroutines</em>), but unfortunately lesser-known in Python. <a href="http://dabeaz.com/coroutines/" rel="noreferrer">Dave Beazley's Curious Course on Coroutines</a> is an excellent start. <a href="http://dabeaz.com/coroutines/Coroutines.pdf" rel="noreferrer">Read slides 24-33</a> for a quick primer.</p>
<h2>Reading data from a generator using yield from</h2>
<pre><code>def reader():
"""A generator that fakes a read from a file, socket, etc."""
for i in range(4):
yield '<< %s' % i
def reader_wrapper(g):
# Manually iterate over data produced by reader
for v in g:
yield v
wrap = reader_wrapper(reader())
for i in wrap:
print(i)
# Result
<< 0
<< 1
<< 2
<< 3
</code></pre>
<p>Instead of manually iterating over <code>reader()</code>, we can just <code>yield from</code> it.</p>
<pre><code>def reader_wrapper(g):
yield from g
</code></pre>
<p>That works, and we eliminated one line of code. And probably the intent is a little bit clearer (or not). But nothing life changing.</p>
<h2>Sending data to a generator (coroutine) using yield from - Part 1</h2>
<p>Now let's do something more interesting. Let's create a coroutine called <code>writer</code> that accepts data sent to it and writes to a socket, fd, etc.</p>
<pre><code>def writer():
"""A coroutine that writes data *sent* to it to fd, socket, etc."""
while True:
w = (yield)
print('>> ', w)
</code></pre>
<p>Now the question is, how should the wrapper function handle sending data to the writer, so that any data that is sent to the wrapper is <em>transparently</em> sent to the <code>writer()</code>?</p>
<pre><code>def writer_wrapper(coro):
# TBD
pass
w = writer()
wrap = writer_wrapper(w)
wrap.send(None) # "prime" the coroutine
for i in range(4):
wrap.send(i)
# Expected result
>> 0
>> 1
>> 2
>> 3
</code></pre>
<p>The wrapper needs to <em>accept</em> the data that is sent to it (obviously) and should also handle the <code>StopIteration</code> when the for loop is exhausted. Evidently just doing <code>for x in coro: yield x</code> won't do. Here is a version that works.</p>
<pre><code>def writer_wrapper(coro):
coro.send(None) # prime the coro
while True:
try:
x = (yield) # Capture the value that's sent
coro.send(x) # and pass it to the writer
except StopIteration:
pass
</code></pre>
<p>Or, we could do this.</p>
<pre><code>def writer_wrapper(coro):
yield from coro
</code></pre>
<p>That saves 6 lines of code, make it much much more readable and it just works. Magic!</p>
<h2>Sending data to a generator yield from - Part 2 - Exception handling</h2>
<p>Let's make it more complicated. What if our writer needs to handle exceptions? Let's say the <code>writer</code> handles a <code>SpamException</code> and it prints <code>***</code> if it encounters one.</p>
<pre><code>class SpamException(Exception):
pass
def writer():
while True:
try:
w = (yield)
except SpamException:
print('***')
else:
print('>> ', w)
</code></pre>
<p>What if we don't change <code>writer_wrapper</code>? Does it work? Let's try</p>
<pre><code># writer_wrapper same as above
w = writer()
wrap = writer_wrapper(w)
wrap.send(None) # "prime" the coroutine
for i in [0, 1, 2, 'spam', 4]:
if i == 'spam':
wrap.throw(SpamException)
else:
wrap.send(i)
# Expected Result
>> 0
>> 1
>> 2
***
>> 4
# Actual Result
>> 0
>> 1
>> 2
Traceback (most recent call last):
... redacted ...
File ... in writer_wrapper
x = (yield)
__main__.SpamException
</code></pre>
<p>Um, it's not working because <code>x = (yield)</code> just raises the exception and everything comes to a crashing halt. Let's make it work, but manually handling exceptions and sending them or throwing them into the sub-generator (<code>writer</code>)</p>
<pre><code>def writer_wrapper(coro):
"""Works. Manually catches exceptions and throws them"""
coro.send(None) # prime the coro
while True:
try:
try:
x = (yield)
except Exception as e: # This catches the SpamException
coro.throw(e)
else:
coro.send(x)
except StopIteration:
pass
</code></pre>
<p>This works.</p>
<pre><code># Result
>> 0
>> 1
>> 2
***
>> 4
</code></pre>
<p>But so does this!</p>
<pre><code>def writer_wrapper(coro):
yield from coro
</code></pre>
<p>The <code>yield from</code> transparently handles sending the values or throwing values into the sub-generator.</p>
<p>This still does not cover all the corner cases though. What happens if the outer generator is closed? What about the case when the sub-generator returns a value (yes, in Python 3.3+, generators can return values), how should the return value be propagated? <a href="https://www.python.org/dev/peps/pep-0380/#formal-semantics" rel="noreferrer">That <code>yield from</code> transparently handles all the corner cases is really impressive</a>. <code>yield from</code> just magically works and handles all those cases.</p>
<p>I personally feel <code>yield from</code> is a poor keyword choice because it does not make the <em>two-way</em> nature apparent. There were other keywords proposed (like <code>delegate</code> but were rejected because adding a new keyword to the language is much more difficult than combining existing ones.</p>
<p>In summary, it's best to think of <code>yield from</code> as a <strong><code>transparent two way channel</code></strong> between the caller and the sub-generator.</p>
<p>References:</p>
<ol>
<li><a href="http://www.python.org/dev/peps/pep-0380/" rel="noreferrer">PEP 380</a> - Syntax for delegating to a sub-generator (Ewing) [v3.3, 2009-02-13]</li>
<li><a href="http://www.python.org/dev/peps/pep-0342/" rel="noreferrer">PEP 342</a> -
Coroutines via Enhanced Generators (GvR, Eby) [v2.5, 2005-05-10]</li>
</ol> |
7,945,253 | Java EE perspective in eclipse | <p>I have Standard version of eclipse Galileo. Now I want to develop enterprise applications on it. Any idea how can I get Java EE perspective? How to install Java EE tools in the standard version? </p> | 7,962,763 | 3 | 1 | null | 2011-10-30 13:43:49.05 UTC | null | 2013-12-26 15:51:03.66 UTC | null | null | null | null | 389,192 | null | 1 | 9 | eclipse|jakarta-ee | 45,847 | <p>The standard edition can be upgraded to J2EE edition by installing the different plug-ins like WTP and so on.
Did you try to look at the update site for Galileo?</p> |
11,541,863 | What is the VBA code to emulate selecting a block with the CTRL+A shortcut? | <p>In earlier versions of Excel, pressing CTRL+A in a worksheet would literally select all cells. In Excel 2010 (not sure about 2007 or 2003), I've noticed that if you press CTRL+A within a block of cells that contain values, it seems to know to select only the cells in that block. For example, if all cells in range A1:D10 contain values and you hit CTRL+A while the active cell is in that range, it will select only A1:D10. If you press CTRL+A again, only then will it actually select all cells in the worksheet.</p>
<p>So I recorded a macro to see what macro code was being generated when I do this, but it actually writes <code>Range("A1:D10").Select</code> when I hit CTRL+A. This is limiting and not dynamic because now I have to write my own logic to determine the boundaries around the active cell. That's not difficult with methods like <code>ActiveCell.End(xlDown)</code>, but I'd like to not have to reinvent a wheel here.</p>
<p>Is there some Excel VBA method like <code>ActiveCell.GetOuterRange.Select</code>? That would be nice.</p> | 11,541,956 | 1 | 0 | null | 2012-07-18 12:53:04.947 UTC | 5 | 2015-03-02 21:10:13.917 UTC | 2018-07-09 19:34:03.733 UTC | null | -1 | null | 701,346 | null | 1 | 15 | excel|range|excel-2010|vba | 53,843 | <p>For all dirty cells you can;</p>
<pre><code>ActiveSheet.UsedRange.Select
</code></pre>
<p>Or for cells surrounding the current cell in a contiguous fashion you can;</p>
<pre><code>ActiveCell.CurrentRegion.Select
</code></pre> |
11,566,967 | python: raise child_exception, OSError: [Errno 2] No such file or directory | <p>I execute a command in python using subprocess.popen() function like the following:</p>
<pre><code>omp_cmd = 'cat %s | omp -h %s -u %s -w %s -p %s -X -' %(temp_xml, self.host_IP, self.username, self.password, self.port)
xmlResult = Popen(omp_cmd, stdout=PIPE, stderr=STDOUT)
</code></pre>
<p>In the shell it runs fine without error, but in python I get:</p>
<pre><code> File "/home/project/vrm/apps/audit/models.py", line 148, in sendOMP
xmlResult = Popen(omp_cmd, stdout=PIPE, stderr=STDOUT)
File "/usr/local/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/local/lib/python2.7/subprocess.py", line 1228, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
</code></pre>
<p>I searched the error but none of them solved my problem. Does anyone know what's the cause of this issue? Thanks.</p> | 11,566,986 | 2 | 0 | null | 2012-07-19 18:19:46.01 UTC | 3 | 2017-11-19 20:57:43.66 UTC | null | null | null | null | 636,625 | null | 1 | 20 | python|popen | 52,106 | <p>If you're going to pass the command as a string to <code>Popen</code> and if the commands have pipes to other commands in there, you need to use the <code>shell=True</code> keyword.</p>
<p>I'm not particularly familiar with the <code>omp</code> command, but this smells an awful lot like a useless use of cat. I would think that a better way to achieve this would be to:</p>
<pre><code>import shlex
omp_cmd = 'omp -h %s -u %s -w %s -p %s -X %s' %(self.host_IP, self.username, self.password, self.port, temp_xml)
xmlResult = Popen(shlex.split(omp_cmd), stdout=PIPE, stderr=STDOUT)
</code></pre>
<p>Or, if it's not a useless use of cat (You really do need to pipe the file in via stdin), you can do that with subprocess too:</p>
<pre><code>import shlex
omp_cmd = 'omp -h %s -u %s -w %s -p %s -X -' %(self.host_IP, self.username, self.password)
with open(temp_xml) as stdin:
xmlResult = Popen(shlex.split(omp_cmd), stdin=stdin, stdout=PIPE, stderr=STDOUT)
</code></pre> |
11,499,574 | Toggle button using two image on different state | <p>I need to make a toggle button using two image instead of ON/OFF state.</p>
<p>At off state i set a background image.But the OFF text can not removed while i use background image.</p>
<p>And i can not set another image on ON state by clicking the toggle button :(
I am new in android.
I hope you guys help me get out of this problem</p> | 11,499,595 | 3 | 1 | null | 2012-07-16 07:07:35.26 UTC | 34 | 2020-12-28 08:29:43.553 UTC | null | null | null | null | 1,400,291 | null | 1 | 104 | android|togglebutton | 110,611 | <p>Do this:</p>
<pre><code><ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/check" <!--check.xml-->
android:layout_margin="10dp"
android:textOn=""
android:textOff=""
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_centerVertical="true"/>
</code></pre>
<p>create check.xml in drawable folder</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>
</code></pre> |
11,520,492 | Difference between del, remove, and pop on lists | <p>Is there any difference between these three methods to remove an element from a list?</p>
<pre><code>>>> a = [1, 2, 3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a = [1, 2, 3]
>>> del a[1]
>>> a
[1, 3]
>>> a = [1, 2, 3]
>>> a.pop(1)
2
>>> a
[1, 3]
</code></pre> | 11,520,540 | 12 | 1 | null | 2012-07-17 10:21:41.26 UTC | 359 | 2022-03-30 05:11:28.357 UTC | 2022-03-30 05:11:28.357 UTC | null | 365,102 | null | 1,477,714 | null | 1 | 1,169 | python|list | 1,988,916 | <p>The effects of the three different methods to remove an element from a list:</p>
<p><code>remove</code> removes the <em>first</em> matching <em>value</em>, not a specific index:</p>
<pre><code>>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]
</code></pre>
<p><code>del</code> removes the item at a specific index:</p>
<pre><code>>>> a = [9, 8, 7, 6]
>>> del a[1]
>>> a
[9, 7, 6]
</code></pre>
<p>and <code>pop</code> removes the item at a specific index and returns it.</p>
<pre><code>>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]
</code></pre>
<p>Their error modes are different too:</p>
<pre><code>>>> a = [4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
</code></pre> |
11,896,304 | Openssl is not recognized as an internal or external command | <p>I wish to generate an application signature for my app which will later be integrated with Facebook. In one of Facebook's tutorials, I found this command:</p>
<pre><code>keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
</code></pre>
<p>In the tutorial, it says that by running this cmd, my process of generating the signature will start.</p>
<p>However, this command gives an error:</p>
<pre><code>openssl is not recognized as an internal or external command
</code></pre>
<p>How can I get rid of this?</p> | 11,896,406 | 22 | 6 | null | 2012-08-10 06:04:04.053 UTC | 60 | 2022-06-29 10:18:19.897 UTC | 2017-09-09 07:52:20.593 UTC | null | 5,099,203 | null | 1,368,964 | null | 1 | 208 | java|android|facebook-android-sdk|keytool | 261,761 | <p>Well at the place of OpenSSL ... you have to put actually the path to your OpenSSL folder that you have downloaded. Your actual command should look like this:</p>
<pre><code>keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | "C:\Users\abc\openssl\bin\openssl.exe" sha1 -binary | "C:\Users\abc\openssl\bin\openssl.exe" base64
</code></pre>
<p>Remember, the path that you will enter will be the path where you have installed the OpenSSL.</p>
<p><strong>Edit:</strong></p>
<p>you can download OpenSSL for windows 32 and 64 bit from the respective links below:</p>
<p><a href="http://code.google.com/p/openssl-for-windows/downloads/detail?name=openssl-0.9.8k_X64.zip" rel="noreferrer">OpenSSL for 64 Bits</a></p>
<p><a href="https://code.google.com/p/openssl-for-windows/downloads/detail?name=openssl-0.9.8k_WIN32.zip" rel="noreferrer">OpenSSL for 32 Bits</a></p> |
20,153,388 | Meteor's accounts-ui-bootstrap-3 {{loginButtons}} not displaying | <p>After installing <code>bootstrap-3</code> and <code>accounts-ui-bootstrap-3</code>, the <code>ui-accounts</code> login widget did not appear when <code>{{ loginButtons }}</code> is used. Instead a <code><div></code> is found in its place but no widget is visible.</p>
<p>Are there additional steps that is missing for the widget to be displayed?</p>
<p><strong>Adding Bootstrap 3 packages</strong></p>
<pre><code>mrt add bootstrap-3
mrt add accounts-ui-bootstrap-3
</code></pre>
<p><strong>main.html</strong></p>
<pre><code><body>
{{> header}}
</body>
<template name="header">
<div class="navbar navbar-fixed-top navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">My Bootstrap 3 App</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li>{{ loginButtons }}</li>
</ul>
</div><!-- /.nav-collapse -->
</div><!-- /.container -->
</div>
</template>
</code></pre>
<p><strong>Output of {{ loginButtons}}</strong></p>
<pre><code><div id="login-buttons" class="login-buttons-dropdown-align-right"></div>
</code></pre>
<p><img src="https://i.stack.imgur.com/crBqg.png" alt="enter image description here"></p>
<hr>
<h2>Update</h2>
<p><strong>Misaligned <code>{{ loginButtons }}</code></strong></p>
<p><img src="https://i.stack.imgur.com/qDMSA.png" alt="enter image description here"></p>
<p><strong>Properly aligned example in docs</strong></p>
<p><img src="https://i.stack.imgur.com/HYMkt.png" alt="enter image description here"></p> | 21,862,158 | 6 | 5 | null | 2013-11-22 19:54:29.153 UTC | 9 | 2016-06-05 15:16:37.443 UTC | 2013-11-24 09:03:41.42 UTC | null | 1,016,716 | null | 741,099 | null | 1 | 10 | javascript|node.js|meteor|twitter-bootstrap-3|meteorite | 7,964 | <p>To whoever finds this and wonders why this is happening, the solution is pretty simple. Just remove the standard accounts-ui package from meteor by typing <code>meteor remove accounts-ui</code>. Apparently the standard package overrides the CSS classes of the bootstrap-3 styled accounts ui.</p> |
20,113,586 | Restore deleted records in PostgreSQL | <p>I accidentally deleted all the records from 3 tables in PostgreSQL. How can i restore the data?</p> | 20,113,772 | 1 | 5 | null | 2013-11-21 05:57:35.013 UTC | 2 | 2013-11-21 18:04:13.797 UTC | 2013-11-21 18:04:13.797 UTC | null | 15,785 | null | 2,526,714 | null | 1 | 17 | sql|database|postgresql | 61,610 | <p>This is a similar problem as discussed here:</p>
<p><a href="https://stackoverflow.com/questions/12472318/can-i-rollback-a-transaction-ive-already-committed-data-loss">Can I rollback a transaction I've already committed? (data loss)</a></p>
<p>Basically, restore from backup. If you can't, you <em>might</em> be able to recover with <code>pg_dirtyread</code>.</p>
<p>If you don't have backups, stop the whole server, take a disk image of the drive, and contact a $lots data recovery expert.</p> |
3,303,801 | How to achieve a dynamic controller and action method in ASP.NET MVC? | <p>In Asp.net MVC the url structure goes like </p>
<p><a href="http://example.com/" rel="noreferrer">http://example.com/</a>{controller}/{action}/{id}</p>
<p>For each "controller", say <a href="http://example.com/blog" rel="noreferrer">http://example.com/blog</a>, there is a BlogController.</p>
<p>But my {controller} portion of the url is not decided pre-hand, but it is dynamically determined at run time, how do I create a "dynamic controller" that maps anything to the same controller which then based on the value and determines what to do?</p>
<p>Same thing with {action}, if the {action} portion of my url is also dynamic, is there a way to program this scenario? </p> | 3,305,937 | 4 | 0 | null | 2010-07-21 20:57:56.157 UTC | 14 | 2021-03-02 20:15:17.66 UTC | 2016-12-29 17:54:17.96 UTC | null | 1,033,581 | null | 32,240 | null | 1 | 29 | asp.net-mvc-2|asp.net-mvc-routing|asp.net-mvc-controller | 25,781 | <p>Absolutely! You'll need to override the <code>DefaultControllerFactory</code> to find a custom controller if one doesn't exist. Then you'll need to write an <code>IActionInvoker</code> to handle dynamic action names.</p>
<p>Your controller factory will look something like:</p>
<pre class="lang-cs prettyprint-override"><code>public class DynamicControllerFactory : DefaultControllerFactory
{
private readonly IServiceLocator _Locator;
public DynamicControllerFactory(IServiceLocator locator)
{
_Locator = locator;
}
protected override Type GetControllerType(string controllerName)
{
var controllerType = base.GetControllerType(controllerName);
// if a controller wasn't found with a matching name, return our dynamic controller
return controllerType ?? typeof (DynamicController);
}
protected override IController GetControllerInstance(Type controllerType)
{
var controller = base.GetControllerInstance(controllerType) as Controller;
var actionInvoker = _Locator.GetInstance<IActionInvoker>();
if (actionInvoker != null)
{
controller.ActionInvoker = actionInvoker;
}
return controller;
}
}
</code></pre>
<p>Then your action invoker would be like:</p>
<pre class="lang-cs prettyprint-override"><code>public class DynamicActionInvoker : ControllerActionInvoker
{
private readonly IServiceLocator _Locator;
public DynamicActionInvoker(IServiceLocator locator)
{
_Locator = locator;
}
protected override ActionDescriptor FindAction(ControllerContext controllerContext,
ControllerDescriptor controllerDescriptor, string actionName)
{
// try to match an existing action name first
var action = base.FindAction(controllerContext, controllerDescriptor, actionName);
if (action != null)
{
return action;
}
// @ray247 The remainder of this you'd probably write on your own...
var actionFinders = _Locator.GetAllInstances<IFindAction>();
if (actionFinders == null)
{
return null;
}
return actionFinders
.Select(f => f.FindAction(controllerContext, controllerDescriptor, actionName))
.Where(d => d != null)
.FirstOrDefault();
}
}
</code></pre>
<p>You can see a lot more of this code <a href="http://github.com/ryanohs/DynamicServices/tree/master/src/DynamicServices.Mvc/" rel="noreferrer">here</a>. It's an old first draft attempt by myself and a coworker at writing a fully dynamic MVC pipeline. You're free to use it as a reference and copy what you want.</p>
<p><strong>Edit</strong></p>
<p>I figured I should include some background about what that code does. We were trying to dynamically build the MVC layer around a domain model. So if your domain contained a Product class, you could navigate to <code>products\alls</code> to see a list of all products. If you wanted to add a product, you'd navigate to <code>product\add</code>. You could go to <code>product\edit\1</code> to edit a product. We even tried things like allowing you to edit properties on an entity. So <code>product\editprice\1?value=42</code> would set the price property of product #1 to 42. (My paths might be a little off, I can't recall the exact syntax anymore.) Hope this helps!</p> |
3,271,478 | Check list of words in another string | <p>I can do such thing in python:</p>
<pre><code>l = ['one', 'two', 'three']
if 'some word' in l:
...
</code></pre>
<p>This will check if 'some word' exists in the list. But can I do reverse thing?</p>
<pre><code>l = ['one', 'two', 'three']
if l in 'some one long two phrase three':
...
</code></pre>
<p>I have to check whether some words from array are in the string. I can do this using cycle but this way has more lines of code.</p> | 3,271,485 | 4 | 3 | null | 2010-07-17 12:33:26.303 UTC | 51 | 2017-09-21 22:46:37.127 UTC | 2017-09-21 22:46:37.127 UTC | null | 2,246,488 | null | 87,152 | null | 1 | 164 | python|list | 246,460 | <pre><code>if any(word in 'some one long two phrase three' for word in list_):
</code></pre> |
3,451,389 | Regular Expression for Range (2-16) | <p>I want to match a number between 2-16, spanning 1 digit to 2 digits.</p>
<p>Regular-Expressions.info <a href="http://www.regular-expressions.info/numericranges.html" rel="noreferrer">has examples</a> for 1 or 2 digit ranges, but not something that spans both:</p>
<blockquote>
<p>The regex <code>[0-9]</code> matches single-digit numbers 0 to 9. <code>[1-9][0-9]</code> matches double-digit numbers 10 to 99.</p>
</blockquote>
<p>Something like <code>^[2-9][1-6]$</code> matches 21 or even 96! Any help would be appreciated.</p> | 3,451,397 | 5 | 0 | null | 2010-08-10 16:53:37.66 UTC | 7 | 2021-10-25 20:36:23.963 UTC | 2020-02-11 17:34:50.863 UTC | null | 241,211 | null | 360,635 | null | 1 | 24 | regex | 56,926 | <pre><code>^([2-9]|1[0-6])$
</code></pre>
<p>will match either a single digit between 2 and 9 inclusive, or a 1 followed by a digit between 0 and 6, inclusive.</p> |
3,545,191 | How to cancel search highlight in Eclipse | <p>When I search something in Eclipse, the search items stay highlighted for some time. How do I remove this after I have found what I was looking for?</p> | 3,545,215 | 5 | 0 | null | 2010-08-23 06:35:49.653 UTC | 3 | 2019-04-03 22:24:02.893 UTC | 2013-02-07 00:51:54.663 UTC | null | 979,401 | null | 184,730 | null | 1 | 59 | eclipse | 15,989 | <p>Remove your matches in the search view, that will remove the highlighting. I.e., click the button with the two X's in the search view.</p>
<p>If you cannot see that view, navigate to window -> show view -> Search</p> |
3,856,413 | Call Class Method From Another Class | <p>Is there a way to call the method of a class from another class? I am looking for something like PHP's <code>call_user_func_array()</code>.
Here is what I want to happen:</p>
<pre><code>class A:
def method1(arg1, arg2):
...
class B:
A.method1(1, 2)
</code></pre> | 3,856,502 | 5 | 3 | null | 2010-10-04 14:56:35.17 UTC | 33 | 2022-04-17 02:54:27.4 UTC | 2022-04-17 02:49:39.663 UTC | null | 365,102 | null | 8,804 | null | 1 | 80 | python | 359,337 | <p>update: Just saw the reference to <code>call_user_func_array</code> in your post. that's different. use <code>getattr</code> to get the function object and then call it with your arguments</p>
<pre><code>class A(object):
def method1(self, a, b, c):
# foo
method = A.method1
</code></pre>
<p><code>method</code> is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate <code>A.method1</code> with one of the two decorators discussed below, pass it an instance of <code>A</code> as the first argument or access the method on an instance of <code>A</code>.</p>
<pre><code>a = A()
method = a.method1
method(1, 2)
</code></pre>
<hr>
<p>You have three options for doing this</p>
<ol>
<li>Use an instance of <code>A</code> to call <code>method1</code> (using two possible forms)</li>
<li>apply the <code>classmethod</code> decorator to <code>method1</code>: you will no longer be able to reference <code>self</code> in <code>method1</code> but you will get passed a <code>cls</code> instance in it's place which is <code>A</code> in this case.</li>
<li>apply the <code>staticmethod</code> decorator to <code>method1</code>: you will no longer be able to reference <code>self</code>, or <code>cls</code> in <code>staticmethod1</code> but you can hardcode references to <code>A</code> into it, though obviously, these references will be inherited by all subclasses of <code>A</code> unless they specifically override <code>method1</code> and do not call <code>super</code>.</li>
</ol>
<p>Some examples:</p>
<pre><code>class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
def method1(self, a, b):
return a + b
@staticmethod
def method2(a, b):
return a + b
@classmethod
def method3(cls, a, b):
return cls.method2(a, b)
t = Test1() # same as doing it in another class
Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2) # form two (the common one) essentially reduces to form one
Test1.method2(1, 2) #the static method can be called with just arguments
t.method2(1, 2) # on an instance or the class
Test1.method3(1, 2) # ditto for the class method. It will have access to the class
t.method3(1, 2) # that it's called on (the subclass if called on a subclass)
# but will not have access to the instance it's called on
# (if it is called on an instance)
</code></pre>
<p>Note that in the same way that the name of the <code>self</code> variable is entirely up to you, so is the name of the <code>cls</code> variable but those are the customary values.</p>
<p>Now that you know how to do it, I would seriously think about <em>if</em> you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python. </p> |
3,495,092 | Read from file or stdin | <p>I am writing a utility which accepts either a filename, or reads from stdin.</p>
<p>I would like to know the most robust / fastest way of checking to see if stdin exists (data is being piped to the program) and if so reading that data in. If it doesn't exist, the processing will take place on the filename given. I have tried using the following the test for size of <code>stdin</code> but I believe since it's a stream and not an actual file, it's not working as I suspected it would and it's always printing <code>-1</code>. I know I could always read the input 1 character at a time while != EOF but I would like a more generic solution so I could end up with either a fd or a FILE* if stdin exists so the rest of the program will function seamlessly. I would also like to be able to know its size, pending the stream has been closed by the previous program.</p>
<pre><code>long getSizeOfInput(FILE *input){
long retvalue = 0;
fseek(input, 0L, SEEK_END);
retvalue = ftell(input);
fseek(input, 0L, SEEK_SET);
return retvalue;
}
int main(int argc, char **argv) {
printf("Size of stdin: %ld\n", getSizeOfInput(stdin));
exit(0);
}
</code></pre>
<p>Terminal:</p>
<pre><code>$ echo "hi!" | myprog
Size of stdin: -1
</code></pre> | 3,495,410 | 6 | 0 | null | 2010-08-16 16:16:38.03 UTC | 14 | 2015-01-26 09:45:39.933 UTC | 2014-10-22 12:06:47.427 UTC | null | 321,731 | null | 292,023 | null | 1 | 31 | c|file|io|stream|stdin | 123,419 | <p>First, ask the program to tell you what is wrong by checking the <code>errno</code>, which is set on failure, such as during <code>fseek</code> or <code>ftell</code>.</p>
<p>Others (tonio & LatinSuD) have explained the mistake with handling stdin versus checking for a filename. Namely, first check <code>argc</code> (argument count) to see if there are any command line parameters specified <code>if (argc > 1)</code>, treating <code>-</code> as a special case meaning <code>stdin</code>. </p>
<p>If no parameters are specified, then assume input is (going) to come from <code>stdin</code>, which is a <strong>stream</strong> not file, and the <code>fseek</code> function fails on it.</p>
<p>In the case of a stream, where you cannot use file-on-disk oriented library functions (i.e. <code>fseek</code> and <code>ftell</code>), you simply have to count the number of bytes read (including trailing newline characters) until receiving <strong>EOF</strong> (end-of-file).</p>
<p>For usage with large files you could speed it up by using <code>fgets</code> to a char array for more efficient reading of the bytes in a (text) file. For a binary file you need to use <code>fopen(const char* filename, "rb")</code> and use <code>fread</code> instead of <code>fgetc/fgets</code>.</p>
<p>You could also check the for <code>feof(stdin)</code> / <code>ferror(stdin)</code> when using the byte-counting method to detect any errors when reading from a stream.</p>
<p>The sample below should be C99 compliant and portable.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
long getSizeOfInput(FILE *input){
long retvalue = 0;
int c;
if (input != stdin) {
if (-1 == fseek(input, 0L, SEEK_END)) {
fprintf(stderr, "Error seek end: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (-1 == (retvalue = ftell(input))) {
fprintf(stderr, "ftell failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (-1 == fseek(input, 0L, SEEK_SET)) {
fprintf(stderr, "Error seek start: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
} else {
/* for stdin, we need to read in the entire stream until EOF */
while (EOF != (c = fgetc(input))) {
retvalue++;
}
}
return retvalue;
}
int main(int argc, char **argv) {
FILE *input;
if (argc > 1) {
if(!strcmp(argv[1],"-")) {
input = stdin;
} else {
input = fopen(argv[1],"r");
if (NULL == input) {
fprintf(stderr, "Unable to open '%s': %s\n",
argv[1], strerror(errno));
exit(EXIT_FAILURE);
}
}
} else {
input = stdin;
}
printf("Size of file: %ld\n", getSizeOfInput(input));
return EXIT_SUCCESS;
}
</code></pre> |
3,248,909 | regex allow only numbers or empty string | <p>Can someone help me create this regex. I need it to check to see if the string is either entirely whitespace(empty) or if it only contains positive whole numbers. If anything else it fails. This is what I have so far.</p>
<pre><code>/^\s*|[0-9][0-9]*/
</code></pre> | 3,248,929 | 6 | 1 | null | 2010-07-14 17:44:52.007 UTC | 6 | 2022-09-15 11:32:57.523 UTC | null | null | null | null | 391,516 | null | 1 | 33 | regex | 84,254 | <p>You're looking for:</p>
<pre><code>/^(\s*|\d+)$/
</code></pre>
<p>If you want a positive number without leading zeros, use <code>[1-9][0-9]*</code></p>
<p>If you don't care about whitespaces <em>around</em> the number, you can also try:</p>
<pre><code>/^\s*\d*\s*$/
</code></pre>
<p>Note that you don't want to allow partial matching, for example <strong><code>123</code></strong><code>abc</code>, so you need the start and end anchors: <code>^...$</code>.<br>
Your regex has a common mistake: <code>^\s*|\d+$</code>, for example, does not enforce a whole match, as is it the same as <code>(^\s*)|(\d+$)</code>, reading, Spaces at the start, or digits at the end.</p> |
3,225,386 | If I do a `typedef` in C or C++, when should I add `_t` at the end of typedef'ed type? | <p>I am confused when should I add the trailing <code>_t</code> to <code>typedef</code>'ed types?</p>
<p>For example, should I do this:</p>
<pre><code>typedef struct image image_t;
</code></pre>
<p>or this:</p>
<pre><code>typedef struct image image;
</code></pre>
<p>What are the general rules?</p>
<p>Another example, should I do this:</p>
<pre><code>typdef enum { ARRAY_CLOSED, ARRAY_OPEN, ARRAY_HALFOPEN } array_type_t;
</code></pre>
<p>or this:</p>
<pre><code>typdef enum { ARRAY_CLOSED, ARRAY_OPEN, ARRAY_HALFOPEN } array_type;
</code></pre>
<p>Please enlighten me.</p>
<p>Thanks, Boda Cydo.</p> | 3,225,396 | 6 | 6 | null | 2010-07-12 01:42:39.137 UTC | 11 | 2015-04-12 13:19:48.963 UTC | null | null | null | null | 257,942 | null | 1 | 52 | c++|c|typedef | 16,639 | <p>In POSIX, names ending with <code>_t</code> are reserved, so if you are targeting a POSIX system (e.g., Linux), you should not end your types with <code>_t</code>.</p> |
3,637,984 | What does Collection.Contains() use to check for existing objects? | <p>I have a strongly typed list of custom objects, <code>MyObject</code>, which has a property <code>Id</code>, along with some other properties.</p>
<p>Let's say that the <code>Id</code> of a <code>MyObject</code> defines it as unique and I want to check if my collection doesn't already have a <code>MyObject</code> object that has an <code>Id</code> of 1 before I add my new <code>MyObject</code> to the collection.</p>
<p>I want to use <code>if(!List<MyObject>.Contains(myObj))</code>, but how do I enforce the fact that only one or two properties of <code>MyObject</code> define it as unique?</p>
<p>I can use <code>IComparable</code>? Or do I only have to override an <code>Equals</code> method? If so, I'd need to inherit something first, is that right?</p> | 3,638,114 | 6 | 0 | null | 2010-09-03 17:11:10.203 UTC | 4 | 2019-12-20 22:30:20.22 UTC | 2019-12-20 22:30:20.22 UTC | null | 4,404,544 | null | 62,068 | null | 1 | 58 | c#|collections|contains | 55,715 | <p><code>List<T>.Contains</code> uses <code>EqualityComparer<T>.Default</code>, which in turn uses <code>IEquatable<T></code> if the type implements it, or <code>object.Equals</code> otherwise.</p>
<p>You could just implement <code>IEquatable<T></code> but it's a good idea to override <code>object.Equals</code> if you do so, and a <strong>very</strong> good idea to override <code>GetHashCode()</code> if you do that:</p>
<pre><code>public class SomeIDdClass : IEquatable<SomeIDdClass>
{
private readonly int _id;
public SomeIDdClass(int id)
{
_id = id;
}
public int Id
{
get { return _id; }
}
public bool Equals(SomeIDdClass other)
{
return null != other && _id == other._id;
}
public override bool Equals(object obj)
{
return Equals(obj as SomeIDdClass);
}
public override int GetHashCode()
{
return _id;
}
}
</code></pre>
<p>Note that the hash code relates to the criteria for equality. This is vital.</p>
<p>This also makes it applicable for any other case where equality, as defined by having the same ID, is useful. If you have a one-of requirement to check if a list has such an object, then I'd probably suggest just doing:</p>
<pre><code>return someList.Any(item => item.Id == cmpItem.Id);
</code></pre> |
3,500,829 | SQL Express connection string: mdf file location relative to application location | <p>I am using SQL Express databases as part of a unit test project in c#. My databases is located here:</p>
<pre class="lang-none prettyprint-override"><code>./Databases/MyUnitTestDB.mdf
</code></pre>
<p>I would like to use a relative path or variable in the <code>app.config</code> rather than having my connection string defined as:</p>
<pre class="lang-none prettyprint-override"><code>AttachDbFilename=C:\blah\blah\blah\yea\yea\yea\MyApplication\Databases\MyUnitTestDB.mdf
</code></pre>
<p>I have seen the use of <code>|DataDirectory|</code> but am I correct in thinking this is only applicable to web applications?</p>
<p>I want to control this in the application configuration file, as in production the application uses a hosted sql database.</p> | 3,501,950 | 7 | 0 | null | 2010-08-17 08:57:05.447 UTC | 19 | 2016-09-05 08:29:14.12 UTC | 2015-05-14 14:35:32.903 UTC | null | 419,956 | null | 132,754 | null | 1 | 49 | c#|sql|connection-string|database-connection|sql-server-express | 69,532 | <p>Thanks everyone, I used a combination of your responses.</p>
<p>In my app.config file my connection string is defined as follows</p>
<pre><code><add name="MyConnectionString"
connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" />
</code></pre>
<p>In my unit test class I set the DataDirectory property using the following</p>
<pre><code>[TestInitialize]
public void TestInitialize()
{
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases"));
// rest of initialize implementation ...
}
</code></pre> |
3,321,492 | Git alias with positional parameters | <p>Basically I'm trying to alias:</p>
<pre><code>git files 9fa3
</code></pre>
<p>...to execute the command:</p>
<pre><code>git diff --name-status 9fa3^ 9fa3
</code></pre>
<p>but git doesn't appear to pass positional parameters to the alias command. I have tried:</p>
<pre><code>[alias]
files = "!git diff --name-status $1^ $1"
files = "!git diff --name-status {1}^ {1}"
</code></pre>
<p>...and a few others but those didn't work.</p>
<p>The degenerate case would be:</p>
<pre><code>$ git echo_reverse_these_params a b c d e
e d c b a
</code></pre>
<p>...how can I make this work?</p> | 3,322,412 | 7 | 5 | null | 2010-07-23 19:03:23.243 UTC | 80 | 2021-08-26 01:35:27.563 UTC | 2014-06-24 00:07:06.533 UTC | user456814 | null | null | 400,575 | null | 1 | 314 | git|command|parameters|position|alias | 77,918 | <p>A shell function could help on this:</p>
<pre><code>[alias]
files = "!f() { git diff --name-status \"$1^\" \"$1\"; }; f"
</code></pre>
<p>An alias without <code>!</code> is treated as a Git command; e.g. <code>commit-all = commit -a</code>.</p>
<p>With the <code>!</code>, it's run as its own command in the shell, letting you use stronger magic like this.</p>
<p><strong>UPD</strong><br />
Because commands are executed at the root of repository you may use <code>${GIT_PREFIX}</code> variable when referring to the file names in commands</p> |
3,241,086 | How to schedule to run first Sunday of every month | <p>I am using Bash on RedHat. I need to schedule a cron job to run at at 9:00 AM on first Sunday of every month. How can I do this?</p> | 3,242,169 | 11 | 0 | null | 2010-07-13 20:12:11.81 UTC | 28 | 2022-09-23 10:48:04.827 UTC | 2018-07-14 21:57:23.113 UTC | null | 1,709,587 | null | 212,211 | null | 1 | 74 | bash|shell|cron|redhat | 115,575 | <p>You can put something like this in the <code>crontab</code> file:</p>
<pre><code>00 09 * * 7 [ $(date +\%d) -le 07 ] && /run/your/script
</code></pre>
<p>The <code>date +%d</code> gives you the number of the current day, and then you can check if the day is less than or equal to 7. If it is, run your command.</p>
<p>If you run this script only on Sundays, it should mean that it runs only on the first Sunday of the month.</p>
<p>Remember that in the <code>crontab</code> file, the formatting options for the <code>date</code> command should be escaped.</p> |
8,171,865 | Performance Counter - System.InvalidOperationException: Category does not exist | <p>I have following class that returns number of current Request per Second of IIS. I call RefreshCounters every minute in order to keep Requests per Second value refreshed (because it is average and if I keep it too long old value will influence result too much)... and when I need to display current RequestsPerSecond I call that property.</p>
<pre><code>public class Counters
{
private static PerformanceCounter pcReqsPerSec;
private const string counterKey = "Requests_Sec";
public static object RequestsPerSecond
{
get
{
lock (counterKey)
{
if (pcReqsPerSec != null)
return pcReqsPerSec.NextValue().ToString("N2"); // EXCEPTION
else
return "0";
}
}
}
internal static string RefreshCounters()
{
lock (counterKey)
{
try
{
if (pcReqsPerSec != null)
{
pcReqsPerSec.Dispose();
pcReqsPerSec = null;
}
pcReqsPerSec = new PerformanceCounter("W3SVC_W3WP", "Requests / Sec", "_Total", true);
pcReqsPerSec.NextValue();
PerformanceCounter.CloseSharedResources();
return null;
}
catch (Exception ex)
{
return ex.ToString();
}
}
}
}
</code></pre>
<p>The problem is that following Exception is <em>sometimes</em> thrown:</p>
<pre><code>System.InvalidOperationException: Category does not exist.
at System.Diagnostics.PerformanceCounterLib.GetCategorySample(String machine,\ String category)
at System.Diagnostics.PerformanceCounter.NextSample()
at System.Diagnostics.PerformanceCounter.NextValue()
at BidBop.Admin.PerfCounter.Counters.get_RequestsPerSecond() in [[[pcReqsPerSec.NextValue().ToString("N2");]]]
</code></pre>
<p>Am I not closing previous instances of PerformanceCounter properly? What am I doing wrong so that I end up with that exception sometimes?</p>
<p><strong>EDIT:</strong>
And just for the record, I am hosting this class in IIS website (that is, of course, hosted in App Pool which has administrative privileges) and invoking methods from ASMX service. Site that uses Counter values (displays them) calls RefreshCounters every 1 minute and RequestsPerSecond every 5 seconds; RequestPerSecond are cached between calls.</p>
<p>I am calling RefreshCounters every 1 minute because values tend to become "stale" - too influenced by older values (that were actual 1 minute ago, for example).</p> | 8,265,208 | 5 | 1 | null | 2011-11-17 17:49:54.143 UTC | 8 | 2014-11-04 09:17:21.593 UTC | 2011-11-25 06:06:00.203 UTC | null | 237,858 | null | 237,858 | null | 1 | 13 | c#|asp.net|iis|performancecounter | 18,630 | <p>Antenka has led you in a good direction here. You should not be disposing and re-creating the performance counter on every update/request for value. There is a cost for instantiating the performance counters and the first read can be inaccurate as indicated in the quote below. Also your <code>lock() { ... }</code> statements are very broad (they cover a lot of statements) and will be slow. Its better to have your locks as small as possible. I'm giving Antenka a voteup for the quality reference and good advice!</p>
<p>However, I think I can provide a better answer for you. I have a fair bit of experience with monitoring server performance and understand exactly what you need. One problem your code doesn't take into account is that whatever code is displaying your performance counter (.aspx, .asmx, console app, winform app, etc) could be requesting this statistic at any rate; it could be requested once every 10 seconds, maybe 5 times per second, you don't know and shouldn't care. So you need to separate the PerformanceCounter collection code from that does the monitoring from the code that actually reports the current Requests / Second value. And for performance reasons, I'm also going to show you how to setup the performance counter on first request and then keep it going until nobody has made any requests for 5 seconds, then close/dispose the PerformanceCounter properly.</p>
<pre><code>public class RequestsPerSecondCollector
{
#region General Declaration
//Static Stuff for the polling timer
private static System.Threading.Timer pollingTimer;
private static int stateCounter = 0;
private static int lockTimerCounter = 0;
//Instance Stuff for our performance counter
private static System.Diagnostics.PerformanceCounter pcReqsPerSec;
private readonly static object threadLock = new object();
private static decimal CurrentRequestsPerSecondValue;
private static int LastRequestTicks;
#endregion
#region Singleton Implementation
/// <summary>
/// Static members are 'eagerly initialized', that is,
/// immediately when class is loaded for the first time.
/// .NET guarantees thread safety for static initialization.
/// </summary>
private static readonly RequestsPerSecondCollector _instance = new RequestsPerSecondCollector();
#endregion
#region Constructor/Finalizer
/// <summary>
/// Private constructor for static singleton instance construction, you won't be able to instantiate this class outside of itself.
/// </summary>
private RequestsPerSecondCollector()
{
LastRequestTicks = System.Environment.TickCount;
// Start things up by making the first request.
GetRequestsPerSecond();
}
#endregion
#region Getter for current requests per second measure
public static decimal GetRequestsPerSecond()
{
if (pollingTimer == null)
{
Console.WriteLine("Starting Poll Timer");
// Let's check the performance counter every 1 second, and don't do the first time until after 1 second.
pollingTimer = new System.Threading.Timer(OnTimerCallback, null, 1000, 1000);
// The first read from a performance counter is notoriously inaccurate, so
OnTimerCallback(null);
}
LastRequestTicks = System.Environment.TickCount;
lock (threadLock)
{
return CurrentRequestsPerSecondValue;
}
}
#endregion
#region Polling Timer
static void OnTimerCallback(object state)
{
if (System.Threading.Interlocked.CompareExchange(ref lockTimerCounter, 1, 0) == 0)
{
if (pcReqsPerSec == null)
pcReqsPerSec = new System.Diagnostics.PerformanceCounter("W3SVC_W3WP", "Requests / Sec", "_Total", true);
if (pcReqsPerSec != null)
{
try
{
lock (threadLock)
{
CurrentRequestsPerSecondValue = Convert.ToDecimal(pcReqsPerSec.NextValue().ToString("N2"));
}
}
catch (Exception) {
// We had problem, just get rid of the performance counter and we'll rebuild it next revision
if (pcReqsPerSec != null)
{
pcReqsPerSec.Close();
pcReqsPerSec.Dispose();
pcReqsPerSec = null;
}
}
}
stateCounter++;
//Check every 5 seconds or so if anybody is still monitoring the server PerformanceCounter, if not shut down our PerformanceCounter
if (stateCounter % 5 == 0)
{
if (System.Environment.TickCount - LastRequestTicks > 5000)
{
Console.WriteLine("Stopping Poll Timer");
pollingTimer.Dispose();
pollingTimer = null;
if (pcReqsPerSec != null)
{
pcReqsPerSec.Close();
pcReqsPerSec.Dispose();
pcReqsPerSec = null;
}
}
}
System.Threading.Interlocked.Add(ref lockTimerCounter, -1);
}
}
#endregion
}
</code></pre>
<p>Ok now for some explanation. </p>
<ol>
<li>First you'll notice this class is designed to be a static singleton.
You can't load multiple copies of it, it has a private constructor
and and eagerly initialized internal instance of itself. This makes
sure you don't accidentally create multiple copies of the same
<code>PerformanceCounter</code>.</li>
<li>Next you'll notice in the private constructor (this will only run
once when the class is first accessed) we create both the
<code>PerformanceCounter</code> and a timer which will be used to poll the
<code>PerformanceCounter</code>.</li>
<li>The Timer's callback method will create the <code>PerformanceCounter</code> if
needed and get its next value is available. Also every 5 iterations
we're going to see how long its been since your last request for the
<code>PerformanceCounter</code>'s value. If it's been more than 5 seconds, we'll
shutdown the polling timer as its unneeded at the moment. We can
always start it up again later if we need it again.</li>
<li>Now we have a static method called <code>GetRequestsPerSecond()</code> for you to
call which will return the current value of the RequestsPerSecond
<code>PerformanceCounter</code>.</li>
</ol>
<p>The benefits of this implementation are that you only create the performance counter once and then keep using until you are finished with it. Its easy to use because you simple call <code>RequestsPerSecondCollector.GetRequestsPerSecond()</code> from wherever you need it (.aspx, .asmx, console app, winforms app, etc). There will always be only one <code>PerformanceCounter</code> and it will always be polled at exactly 1 times per second regardless of how quickly you call <code>RequestsPerSecondCollector.GetRequestsPerSecond()</code>. It will also automatically close and dispose of the <code>PerformanceCounter</code> if you haven't requested its value in more than 5 seconds. Of course you can adjust both the timer interval and the timeout milliseconds to suit your needs. You could poll faster and timeout in say 60 seconds instead of 5. I chose 5 seconds as it proves that it works very quickly while debugging in visual studio. Once you test it and know it works, you might want a longer timeout.</p>
<p>Hopefully this helps you not only better use PerformanceCounters, but also feel safe to reuse this class which is separate from whatever you want to display the statistics in. Reusable code is always a plus!</p>
<p><strong>EDIT:</strong> As a follow up question, what if you want to performance some cleanup or babysitting task every 60 seconds while this performance counter is running? Well we already have the timer running every 1 second and a variable tracking our loop iterations called <code>stateCounter</code> which is incremented on each timer callback. So you could add in some code like this:</p>
<pre><code>// Every 60 seconds I want to close/dispose my PerformanceCounter
if (stateCounter % 60 == 0)
{
if (pcReqsPerSec != null)
{
pcReqsPerSec.Close();
pcReqsPerSec.Dispose();
pcReqsPerSec = null;
}
}
</code></pre>
<p>I should point out that this performance counter in the example should not "go stale". I believe 'Request / Sec" should be an <em>average</em> and not a <em>moving average</em> statistic. But this sample just illustrates a way you <strong><em>could</em></strong> do any type of cleanup or "babysitting" of your <code>PerformanceCounter</code> on a regular time interval. In this case we are closing and disposing the performance counter which will cause it to be recreated on next timer callback. You could modify this for your use case and according the specific PerformanceCounter you are using. Most people reading this question/answer should not need to do this. Check the documentation for your desired PerformanceCounter to see if it is a continuous count, an average, a moving average, etc... and adjust your implementation appropriately.</p> |
8,093,023 | Dynamically updating an AutoCompleteTextView adapter | <p>I want to periodically change the suggestions given by an AutoCompleteTextview by getting the list from a RESTful web service, and can't get it working smoothly. I set up a hard-coded list of suggestions to make sure it's working:</p>
<pre><code>ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, new String[] {"Hi", "Ho"});
speciesName.setAdapter(adapter);//my autocomplete tv
</code></pre>
<p>I have got a TextWatcher on the textview and when the text changes that launches a non-blocking call to get a new list of suggestions -- this part which gets a new list is working fine. Then I want to reset the adapter, like so:</p>
<pre><code>public void setOptionsAndUpdate(String[] options) {
Log.d(TAG, "setting options");
//speciesName.setAdapter((ArrayAdapter<String>)null);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, options);
speciesName.setAdapter(adapter);
}
</code></pre>
<p>This method is called, but doesn't work -- the list of suggestions either disappears or the displayed suggestions remain unchanged despite the call to <code>setAdapter</code>.</p>
<p>Is this even the right approach? I looked at <code>SimpleCursorAdapter</code> but couldn't see how to register my web service as a content provider. (It's of the form <a href="http://www.blah.com/query?term=XX" rel="noreferrer">http://www.blah.com/query?term=XX</a>, where the XX is the input from my app, and the response is a JSON Array of strings.)</p> | 8,142,962 | 5 | 1 | null | 2011-11-11 11:02:14.027 UTC | 22 | 2018-08-12 11:51:10.607 UTC | 2015-04-29 15:41:33.943 UTC | null | 56,285 | null | 589,352 | null | 1 | 41 | android|autocomplete|autocompletetextview | 47,038 | <p>This is how I update my AutoCompleteTextView:</p>
<pre><code>String[] data = terms.toArray(new String[terms.size()]); // terms is a List<String>
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(activity, android.R.layout.simple_dropdown_item_1line, data);
keywordField.setAdapter(adapter); // keywordField is a AutoCompleteTextView
if(terms.size() < 40) keywordField.setThreshold(1);
else keywordField.setThreshold(2);
</code></pre>
<p>Now of course, this is static and doesn't deal with an over-the-air suggestions but, I can also suggest you to notify adapter for the changes after you assign it to the AutoCompleteTextView:</p>
<pre><code>adapter.notifyDataSetChanged();
</code></pre>
<p>Hope this helps.</p>
<p>-serkan </p> |
8,292,661 | How to delete a node with 2 children nodes in a binary search tree? | <p>How to delete a node with 2 children nodes in a binary tree?</p>
<p>Is there any kind of method to remove it? I googled it. But didn't get clear idea about it. Anybody explain it with diagrammatic representation? </p>
<p><a href="http://www.algolist.net/img/bst-remove-case-2-1.png" rel="noreferrer">How to delete the node '5' from the this image and what might be the outcome?</a></p> | 8,292,694 | 8 | 0 | null | 2011-11-28 07:31:19.503 UTC | 4 | 2018-01-11 09:21:44.513 UTC | null | null | null | null | 974,155 | null | 1 | 5 | data-structures|binary-search-tree | 66,350 | <p>you replace said node with the left most child on its right side, or the right most child on its left side. You then delete the child from the bottom that it was replaced with.</p>
<p>Deleting five could yield either a tree with 3 as its root or 18 as its root, depending on which direction you take.</p>
<p>It looks like you got that image from this site: <a href="http://www.algolist.net/Data_structures/Binary_search_tree/Removal">http://www.algolist.net/Data_structures/Binary_search_tree/Removal</a></p>
<p>It shows the algorithm you want with images too.</p> |
8,286,352 | How to save an image locally using Python whose URL address I already know? | <p>I know the URL of an image on Internet.</p>
<p>e.g. <a href="http://www.digimouth.com/news/media/2011/09/google-logo.jpg" rel="noreferrer">http://www.digimouth.com/news/media/2011/09/google-logo.jpg</a>, which contains the logo of Google.</p>
<p>Now, how can I download this image using Python without actually opening the URL in a browser and saving the file manually.</p> | 8,286,449 | 18 | 1 | null | 2011-11-27 14:46:37.667 UTC | 77 | 2022-06-30 04:26:09.68 UTC | 2013-11-03 21:21:17.567 UTC | null | 321,731 | null | 992,808 | null | 1 | 195 | python|web-scraping | 324,446 | <h1>Python 2</h1>
<p>Here is a more straightforward way if all you want to do is save it as a file:</p>
<pre><code>import urllib
urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
</code></pre>
<p>The second argument is the local path where the file should be saved.</p>
<h1>Python 3</h1>
<p>As SergO suggested the code below should work with Python 3.</p>
<pre><code>import urllib.request
urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
</code></pre> |
4,082,298 | Scatter plot with a huge amount of data | <p>I would like to use <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="noreferrer">Matplotlib</a> to generate a scatter plot with a huge amount of data (about 3 million points). Actually I've 3 vectors with the same dimension and I use to plot in the following way.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from numpy import *
from matplotlib import rc
import pylab
from pylab import *
fig = plt.figure()
fig.subplots_adjust(bottom=0.2)
ax = fig.add_subplot(111)
plt.scatter(delta,vf,c=dS,alpha=0.7,cmap=cm.Paired)
</code></pre>
<p>Nothing special actually. But it takes too long to generate it actually (I'm working on my MacBook Pro 4 GB RAM with Python 2.7 and Matplotlib 1.0). Is there any way to improve the speed?</p> | 4,088,897 | 3 | 3 | null | 2010-11-02 21:35:30.92 UTC | 8 | 2010-12-12 22:06:17.643 UTC | 2010-12-12 22:06:17.643 UTC | null | 63,550 | null | 462,901 | null | 1 | 22 | python|numpy|matplotlib | 49,144 | <p>You could take the heatmap approach shown <a href="https://stackoverflow.com/questions/2369492/generate-a-heatmap-in-matplotlib-using-a-scatter-data-set">here</a>. In this example the color represents the quantity of data in the bin, not the median value of the dS array, but that should be easy to change. More later if you are interested.</p> |
4,706,960 | How to return a variable from a javascript function into html body | <p>I am still new to javascript, and I am trying to get a function to return a variable using html & javascript. Basically the function should just return whichever radio button that the user clicks on, although at the moment I don't see anything being returned at all.</p>
<p>The function is here: </p>
<pre><code><script type="text/javascript">
function GetSelectedItem() {
var chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
}
return chosen
</script>
</code></pre>
<p>And then in the html section I have these radio buttons, and my attempt to get the variable "chosen" output to the screen.</p>
<pre><code> <form name = f1><Input type = radio Name = r1 Value = "ON" onClick=GetSelectedItem()>On
<Input type = radio Name = r1 Value = "OFF" onClick =GetSelectedItem()>Off</form>
<script type ="text/javascript">document.write(chosen)</script>
</code></pre>
<p>At the moment nothing seems to be getting returned from the function (although if I output the variable 'chosen' inside the function then it is working correctly.</p>
<p>Thanks in advance!</p> | 4,706,999 | 4 | 7 | null | 2011-01-16 17:45:18.813 UTC | 4 | 2015-12-03 14:57:09.777 UTC | null | null | null | null | 381,158 | null | 1 | 13 | javascript|html | 101,582 | <p>Here's a little simpler approach.</p>
<p>First, make a few corrections to your HTML, and create a container to display the output:</p>
<pre><code><form name = "f1"> <!-- the "this" in GetSelectedItem(this) is the input -->
<input type = "radio" Name = "r1" Value = "ON" onClick="GetSelectedItem(this)">On
<input type = "radio" Name = "r1" Value = "OFF" onClick ="GetSelectedItem(this)">Off
</form>
<div id="output"></div>
</code></pre>
<p>Then change your script to this:</p>
<pre><code><script type="text/javascript">
// Grab the output eleent
var output = document.getElementById('output');
// "el" is the parameter that references the "this" argument that was passed
function GetSelectedItem(el) {
output.innerHTML = el.value; // set its content to the value of the "el"
}
</script>
</code></pre>
<p>...and place it just inside the closing <code></body></code> tag.</p>
<p><a href="http://www.jsfiddle.net/xxwa7/" rel="noreferrer"><i><b>Click here to test a working example.</b> <sup>(jsFiddle)</i></sup></a></p> |
4,629,198 | Best way to build an application based on R? | <p>I'm looking for suggestions on how to go about building an application that uses <code>R</code> for analytics, table generation, and plotting. What I have in mind is an application that:</p>
<ul>
<li>displays various data tables in different tabs, somewhat like in Excel, and the columns should be sortable by clicking. </li>
<li>takes user input parameters in some dialog windows.</li>
<li>displays plots dynamically (i.e. user-input-dependent) either in a tab or in a new pop-up window/frame</li>
</ul>
<p>Note that I am <em>not</em> talking about a general-purpose fron-end/GUI for exploring data with <code>R</code> (like say <code>Rattle</code>), but a specific application.
Some questions I'd like to see addressed are:</p>
<ul>
<li>Is an entirely R-based approach even possible ( on Windows ) ? The following passage from the <code>Rattle</code> article in <code>R</code>-Journal intrigues me:</li>
</ul>
<blockquote>
<p>It is interesting to note that the
first implementation of Rattle
actually used Python for implementing
the callbacks and R for the
statistics, using <code>rpy</code>. The release
of <code>RGtk2</code> allowed the interface el-
ements of <code>Rattle</code> to be written
directly in R so that <code>Rattle</code> is a
<strong>fully R-based application</strong></p>
</blockquote>
<ul>
<li><p>If it's better to use another language for the GUI part, which language is best suited for this? I'm looking for a language where it's relatively "painless" to build the GUI, and that also integrates very well with <code>R</code>. From this StackOverflow question <a href="https://stackoverflow.com/questions/3691944/how-should-i-do-rapid-gui-development-for-r-and-octave-methods-possibly-with-pyt">How should I do rapid GUI development for R and Octave methods (possibly with Python)?</a> I see that <code>Python</code> + <code>PyQt4</code> + <code>QtDesigner</code> + <code>RPy2</code> seems to be the best combo. Is that the consensus ?</p></li>
<li><p>Anyone have pointers to specific (open source) applications of the type I describe, as examples that I can learn from? </p></li>
</ul> | 4,629,608 | 4 | 3 | null | 2011-01-07 18:59:42.917 UTC | 24 | 2011-01-09 20:04:00.027 UTC | 2017-05-23 12:09:27.04 UTC | null | -1 | null | 415,690 | null | 1 | 30 | python|user-interface|r | 6,481 | <p>There are lots of ways to do this, including the python approach you mention. If you want to do it solely within R and if your aims are modest enough, the gWidgets package can be used. This exposes some of the features of either RGtk2, tcltk or qtbase (see the qtinterfaces project on r-forge) in a manner that is about as painless as can be. If you want more, look at using those packages directly. I'd recommend RGtk2 if you are going to share with others and if not, qtbase or tcltk.</p> |
4,795,929 | How to change the App ID associated with my (Xcode managed) Team Provisioning Profile | <p>I constantly struggle to get my codesigning to work. I'm trying to get a good generic provisioning profile that will work for all my apps during development. They're always failing codesign, but they also always install on my phone. Go figure.</p>
<p>I've created an App ID called <code>##########.mydomainname.*</code> and associated it with my development certificate, but when the <code>Team Provisioning Profile: *</code> is generated, it uses an App ID that I made when I first signed up over a year ago. I don't know if this is a problem, but I want to try associating the <code>Team Provisioning Profile: *</code> with my <code>##########.mydomainname.*</code> App ID. I'm so sick of constantly fiddling with provisioning - eventually I get it to work, but it's never the same recipe.</p>
<p>Can I somehow edit the App ID used in a profile?</p>
<p>UPDATE: Marking question as answered, but it looks like the answer is that you can't do what I'm asking.</p> | 4,796,819 | 5 | 1 | null | 2011-01-25 16:14:24.573 UTC | 3 | 2015-06-25 23:24:18.18 UTC | 2011-01-29 16:34:08.78 UTC | null | 382,275 | null | 382,275 | null | 1 | 20 | xcode|ios|provisioning|app-id | 43,221 | <p>You can't edit exisiting AppID's, but you can associate existing provisioning profile with new AppID or create new one.</p> |
4,828,296 | How many threads can I run concurrently? | <p>A comment to <a href="https://stackoverflow.com/questions/4816839/feedback-from-threads-to-main-program/">another of my questions</a> says that I can only run "so many" threads concurrently, a notion which I have seen elsewhere.</p>
<p>As a threading novice, how can I determine the maximum number of threads to use? Or is this a "how long is a piece of string" question? What does it depends on? Hardware config or what?</p>
<p>(VB in MS Visual Studio with .Net 3.5, if that matters) </p>
<hr>
<p>Update: is anyone aware of any s/w tool which could suggest a number of threads (or tasks), or should I just code my own which keeps trying different numbers until throughput drops?</p>
<hr>
<p>[Upperdate] Almost seven years later & we now have <a href="https://softwarerecs.stackexchange.com/">a software recommendations site</a>, so I <a href="https://softwarerecs.stackexchange.com/questions/46195/tool-to-tell-me-the-optimal-number-of-threads">asked</a> if there is a tool to help with this.</p> | 4,828,359 | 7 | 2 | null | 2011-01-28 12:38:05.917 UTC | 12 | 2020-05-04 18:07:16.643 UTC | 2020-05-04 18:07:16.643 UTC | null | 562,769 | null | 192,910 | null | 1 | 41 | .net|vb.net|multithreading|.net-3.5 | 81,387 | <p>It depends on hardware as you're (probably) not using a theoretical computer but a physical hardware one, so you have limited resources.</p>
<p>Read: <a href="http://blogs.msdn.com/b/oldnewthing/archive/2005/07/29/444912.aspx" rel="noreferrer">Does Windows have a limit of 2000 threads per process?</a></p>
<p>Furthermore, even if you could run 5000+ threads, depending on your hardware, that could run much slower than a 10 thread equivalent program. I think you should take a look at <a href="http://msdn.microsoft.com/en-us/library/h4732ks0.aspx" rel="noreferrer">thread pooling</a>.</p> |
4,148,499 | How to style a checkbox using CSS | <p>I am trying to style a checkbox using the following:</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-html lang-html prettyprint-override"><code><input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" /></code></pre>
</div>
</div>
</p>
<p>But the style is not applied. The checkbox still displays its default style. How do I give it the specified style?</p> | 4,148,544 | 41 | 4 | null | 2010-11-10 19:57:01.05 UTC | 389 | 2022-08-17 15:38:11.467 UTC | 2019-07-17 15:35:22.96 UTC | null | 63,550 | null | 395,881 | null | 1 | 1,030 | html|css|checkbox | 2,268,746 | <p>UPDATE:</p>
<p>The below answer references the state of things before widespread availability of CSS 3. In modern browsers (including Internet Explorer 9 and later) it is more straightforward to create checkbox replacements with your preferred styling, without using JavaScript.</p>
<p>Here are some useful links:</p>
<ul>
<li><a href="http://www.inserthtml.com/2012/06/custom-form-radio-checkbox/" rel="noreferrer">Creating Custom Form Checkboxes with Just CSS</a></li>
<li><a href="http://csscheckbox.com" rel="noreferrer">Easy CSS Checkbox Generator</a></li>
<li><a href="http://css-tricks.com/the-checkbox-hack/" rel="noreferrer">Stuff You Can Do With The Checkbox Hack</a></li>
<li><a href="http://www.css3.com/implementing-custom-checkboxes-and-radio-buttons-with-css3/" rel="noreferrer">Implementing Custom Checkboxes and Radio Buttons with CSS3</a></li>
<li><a href="https://www.paulund.co.uk/how-to-style-a-checkbox-with-css" rel="noreferrer">How to Style a Checkbox With CSS</a></li>
</ul>
<p>It is worth noting that the fundamental issue has not changed. You still can't apply styles (borders, etc.) directly to the checkbox element and have those styles affect the display of the HTML checkbox. What has changed, however, is that it's now possible to hide the actual checkbox and replace it with a styled element of your own, using nothing but CSS. In particular, because CSS now has a widely supported <code>:checked</code> selector, you can make your replacement correctly reflect the checked status of the box.</p>
<hr />
<p>OLDER ANSWER</p>
<p>Here's <a href="http://www.456bereastreet.com/archive/200701/styling_form_controls_with_css_revisited/" rel="noreferrer">a useful article about styling checkboxes</a>. Basically, that writer found that it varies tremendously from browser to browser, and that many browsers always display the default checkbox no matter how you style it. So there really isn't an easy way.</p>
<p>It's not hard to imagine a workaround where you would use JavaScript to overlay an image on the checkbox and have clicks on that image cause the real checkbox to be checked. Users without JavaScript would see the default checkbox.</p>
<p>Edited to add: here's <a href="https://web.archive.org/web/20160430165815/http://ryanfait.com:80/resources/custom-checkboxes-and-radio-buttons/#" rel="noreferrer">a nice script that does this for you</a>; it hides the real checkbox element, replaces it with a styled span, and redirects the click events.</p> |
14,410,520 | Google Drive API doesn't play well with ProGuard (NPE) | <p>Currently, I'm having experience that, a piece of code, which makes use of Google Drive API <strong>is running fine without introducing ProGuard.</strong></p>
<p>However, after introducing ProGuard, I'm getting the following run-time error.</p>
<pre><code> at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.google.api.client.util.Types.getActualParameterAtPosition(Types.java:329)
at com.google.api.client.util.Types.getIterableParameter(Types.java:309)
at com.google.api.client.json.JsonParser.parseValue(JsonParser.java:546)
at com.google.api.client.json.JsonParser.parse(JsonParser.java:350)
at com.google.api.client.json.JsonParser.parseValue(JsonParser.java:586)
at com.google.api.client.json.JsonParser.parse(JsonParser.java:289)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:76)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:71)
at com.google.api.client.http.HttpResponse.parseAs(HttpResponse.java:491)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:456)
at com.jstock.c.b.a(CloudFile.java:136)
</code></pre>
<p>Note, the crash happens at my code (which is com.jstock.c.b.a if I retrace using mapping.txt)</p>
<pre><code>// request is Files.List
FileList files = request.execute();
</code></pre>
<p>In my proguard, I thought having the following 2 key instructions, able to prevent the crash from happen : <strong>I tell ProGuard never touch on jackson and Google libraries.</strong></p>
<pre><code>-keep class org.codehaus.** { *; }
-keep class com.google.** { *; }
-keep interface org.codehaus.** { *; }
-keep interface com.google.** { *; }
</code></pre>
<p>But that doesn't work. NPE still happen at <a href="http://grepcode.com/file/repo1.maven.org/maven2/com.google.http-client/google-http-client/1.7.0-beta/com/google/api/client/util/Types.java#329" rel="noreferrer">Types.java</a></p>
<p>Note that, I had another try is that, I thought <strong>obfuscate</strong> process causes NPE happens. Hence, I try to disable it using <code>-dontobfuscate</code>. But this time, I will not able to generate APK file, and getting a popular error message : <strong>Conversion to Dalvik format failed with error 1</strong></p>
<p>Here is the proguard configuration which causes NPE at Google Drive API.</p>
<pre><code>-optimizationpasses 1
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
# Comment out the following line, will cause popular "Conversion to Dalvik format failed with error 1"
##-dontobfuscate
-dontwarn sun.misc.Unsafe
-dontwarn com.google.common.collect.MinMaxPriorityQueue
-dontwarn javax.swing.**
-dontwarn java.awt.**
-dontwarn org.jasypt.encryption.pbe.**
-dontwarn java.beans.**
-dontwarn org.joda.time.**
-dontwarn com.google.android.gms.**
-dontwarn org.w3c.dom.bootstrap.**
-dontwarn com.ibm.icu.text.**
-dontwarn demo.**
# Hold onto the mapping.text file, it can be used to unobfuscate stack traces in the developer console using the retrace tool
-printmapping mapping.txt
# Keep line numbers so they appear in the stack trace of the develeper console
-keepattributes *Annotation*,EnclosingMethod,SourceFile,LineNumberTable
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep class com.actionbarsherlock.** { *; }
-keep interface com.actionbarsherlock.** { *; }
# https://sourceforge.net/p/proguard/discussion/182456/thread/e4d73acf
-keep class org.codehaus.** { *; }
-keep class com.google.** { *; }
-keep interface org.codehaus.** { *; }
-keep interface com.google.** { *; }
-assumenosideeffects class android.util.Log {
public static int d(...);
public static int i(...);
public static int e(...);
public static int v(...);
}
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
-assumenosideeffects class android.util.Log {
public static *** d(...);
public static *** v(...);
public static *** i(...);
}
-keepclasseswithmembers class com.google.common.base.internal.Finalizer{
<methods>;
}
</code></pre>
<p>Is there anything else I can try?</p>
<p>I'm not sure it might be caused by the combination of the libraries. (Although things run pretty well without introducing ProGuard)</p>
<p><img src="https://i.stack.imgur.com/xGnnV.png" alt="enter image description here"></p>
<p>If I look at the NPE crash location (Types.getActualParameterAtPosition(Types.java:329))</p>
<pre><code>private static Type getActualParameterAtPosition(Type type, Class<?> superClass, int position) {
ParameterizedType parameterizedType = Types.getSuperParameterizedType(type, superClass);
Type valueType = parameterizedType.getActualTypeArguments()[position];
// this is normally a type variable, except in the case where the class of iterableType is
// superClass, e.g. Iterable<String>
if (valueType instanceof TypeVariable<?>) {
Type resolve = Types.resolveTypeVariable(Arrays.asList(type), (TypeVariable<?>) valueType);
if (resolve != null) {
return resolve;
}
}
return valueType;
}
</code></pre>
<p>I suspect <code>Types.getSuperParameterizedType</code> returning <code>null</code>. So, I further look into <code>Types.getSuperParameterizedType</code>.</p>
<pre><code>public static ParameterizedType getSuperParameterizedType(Type type, Class<?> superClass) {
if (type instanceof Class<?> || type instanceof ParameterizedType) {
outer: while (type != null && type != Object.class) {
Class<?> rawType;
if (type instanceof Class<?>) {
// type is a class
rawType = (Class<?>) type;
} else {
// current is a parameterized type
ParameterizedType parameterizedType = (ParameterizedType) type;
rawType = getRawClass(parameterizedType);
// check if found Collection
if (rawType == superClass) {
// return the actual collection parameter
return parameterizedType;
}
if (superClass.isInterface()) {
for (Type interfaceType : rawType.getGenericInterfaces()) {
// interface type is class or parameterized type
Class<?> interfaceClass =
interfaceType instanceof Class<?> ? (Class<?>) interfaceType : getRawClass(
(ParameterizedType) interfaceType);
if (superClass.isAssignableFrom(interfaceClass)) {
type = interfaceType;
continue outer;
}
}
}
}
// move on to the super class
type = rawType.getGenericSuperclass();
}
}
return null;
}
</code></pre>
<p><strong>What is the possible root cause that may cause <code>getSuperParameterizedType</code> returning <code>null</code>, after processed by ProGuard?</strong></p> | 14,504,602 | 6 | 0 | null | 2013-01-19 02:20:46.147 UTC | 10 | 2015-07-19 13:16:07.007 UTC | 2013-01-22 05:27:02.56 UTC | null | 28,380 | null | 72,437 | null | 1 | 26 | android|google-api|google-drive-api|proguard|google-api-java-client | 6,303 | <p>A combination of the following has worked for me:</p>
<pre><code>-keep class com.google.** { *;}
-keep interface com.google.** { *;}
-dontwarn com.google.**
-dontwarn sun.misc.Unsafe
-dontwarn com.google.common.collect.MinMaxPriorityQueue
-keepattributes *Annotation*,Signature
-keep class * extends com.google.api.client.json.GenericJson {
*;
}
-keep class com.google.api.services.drive.** {
*;
}
</code></pre>
<p>This provided a working proguard compatible solution for a recent Google Drive project.</p>
<p>Cannot take all credit for this solution though, originally found at this link <a href="http://softwyer.wordpress.com/2012/10/20/android-google-drive-sdk-and-proguard/">here</a></p> |
14,784,630 | Converting Decimal to Binary Java | <p>I am trying to convert decimal to binary numbers from the user's input using Java. </p>
<p>I'm getting errors.</p>
<pre><code>package reversedBinary;
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
if (number <0)
System.out.println("Error: Not a positive integer");
else {
System.out.print("Convert to binary is:");
System.out.print(binaryform(number));
}
}
private static Object binaryform(int number) {
int remainder;
if (number <=1) {
System.out.print(number);
}
remainder= number %2;
binaryform(number >>1);
System.out.print(remainder);
{
return null;
} } }
</code></pre>
<p>How do I convert Decimal to Binary in Java?</p> | 14,784,683 | 27 | 6 | null | 2013-02-09 03:29:40.783 UTC | 25 | 2022-07-21 04:48:47.427 UTC | 2015-09-27 20:06:25.04 UTC | null | 445,131 | null | 2,039,574 | null | 1 | 33 | java|binary|decimal | 270,719 | <p>Your <code>binaryForm</code> method is getting caught in an infinite recursion, you need to return if <code>number <= 1</code>:</p>
<pre><code>import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number = in.nextInt();
if (number < 0) {
System.out.println("Error: Not a positive integer");
} else {
System.out.print("Convert to binary is:");
//System.out.print(binaryform(number));
printBinaryform(number);
}
}
private static void printBinaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number % 2;
printBinaryform(number >> 1);
System.out.print(remainder);
}
}
</code></pre> |
14,888,822 | parse html inside ng-bind using angularJS | <p>I'm having issue with angularJs. My application requests some data from the server and one of the values from the data returned from the server is a string of html. I am binding it in my angular template like this </p>
<pre><code><div>{{{item.location_icons}}</div>
</code></pre>
<p>but as you might expect what I see is not the icons images but the markup
basically the stuff in the div looks like</p>
<pre><code> "<i class='my-icon-class'/>"
</code></pre>
<p>which is not what I want. </p>
<p>anyone know what I can do to parse the html in the transclusion </p> | 14,888,940 | 3 | 0 | null | 2013-02-15 05:31:15 UTC | 6 | 2018-02-28 13:43:04.43 UTC | 2015-08-26 12:58:18.623 UTC | null | 3,576,214 | null | 1,914,652 | null | 1 | 41 | javascript|angularjs|html-parsing | 77,322 | <p>You want to use <code>ng-bind-html</code> and <code>ng-bind-html-unsafe</code> for that kind of purpose.</p>
<p>The examples are shown <a href="https://docs.angularjs.org/api/ngSanitize/service/$sanitize#examples" rel="noreferrer">here</a></p> |
14,845,203 | Altering an Enum field using Alembic | <p>How can I add an element to an Enum field in an alembic migration when using a version of PostgreSQL older than 9.1 (which adds the ALTER TYPE for enums)? <a href="https://stackoverflow.com/questions/1771543/postgresql-updating-an-enum-type">This</a> SO question explains the direct process, but I'm not quite sure how best to translate that using alembic.</p>
<p>This is what I have:</p>
<pre><code>new_type = sa.Enum('nonexistent_executable', 'output_limit_exceeded',
'signal', 'success', 'timed_out', name='status')
old_type = sa.Enum('nonexistent_executable', 'signal', 'success', 'timed_out',
name='status')
tcr = sa.sql.table('testcaseresult',
sa.Column('status', new_type, nullable=False))
def upgrade():
op.alter_column('testcaseresult', u'status', type_=new_type,
existing_type=old_type)
def downgrade():
op.execute(tcr.update().where(tcr.c.status==u'output_limit_exceeded')
.values(status='timed_out'))
op.alter_column('testcaseresult', u'status', type_=old_type,
existing_type=new_type)
</code></pre>
<p>The above unfortunately only produces <code>ALTER TABLE testcaseresult ALTER COLUMN status TYPE status</code> upon upgrade, which essentially does nothing.</p> | 14,845,740 | 14 | 0 | null | 2013-02-13 01:53:19.837 UTC | 20 | 2022-06-08 09:40:11.343 UTC | 2018-07-30 10:59:45.473 UTC | null | 1,709,587 | null | 176,978 | null | 1 | 73 | python|postgresql|sqlalchemy|alembic | 49,102 | <p>I decided to try to follow the <a href="https://stackoverflow.com/questions/1771543/postgresql-updating-an-enum-type">postgres approach</a> as directly as possible and came up with the following migration.</p>
<pre><code>from alembic import op
import sqlalchemy as sa
old_options = ('nonexistent_executable', 'signal', 'success', 'timed_out')
new_options = sorted(old_options + ('output_limit_exceeded',))
old_type = sa.Enum(*old_options, name='status')
new_type = sa.Enum(*new_options, name='status')
tmp_type = sa.Enum(*new_options, name='_status')
tcr = sa.sql.table('testcaseresult',
sa.Column('status', new_type, nullable=False))
def upgrade():
# Create a tempoary "_status" type, convert and drop the "old" type
tmp_type.create(op.get_bind(), checkfirst=False)
op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE _status'
' USING status::text::_status')
old_type.drop(op.get_bind(), checkfirst=False)
# Create and convert to the "new" status type
new_type.create(op.get_bind(), checkfirst=False)
op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE status'
' USING status::text::status')
tmp_type.drop(op.get_bind(), checkfirst=False)
def downgrade():
# Convert 'output_limit_exceeded' status into 'timed_out'
op.execute(tcr.update().where(tcr.c.status==u'output_limit_exceeded')
.values(status='timed_out'))
# Create a tempoary "_status" type, convert and drop the "new" type
tmp_type.create(op.get_bind(), checkfirst=False)
op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE _status'
' USING status::text::_status')
new_type.drop(op.get_bind(), checkfirst=False)
# Create and convert to the "old" status type
old_type.create(op.get_bind(), checkfirst=False)
op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE status'
' USING status::text::status')
tmp_type.drop(op.get_bind(), checkfirst=False)
</code></pre>
<p>It appears that alembic has no direct support for the <code>USING</code> statement in its <code>alter_table</code> method.</p> |
14,740,705 | Difference between GeoJSON and TopoJSON | <p>What is the difference between GeoJSON and TopoJSON and when would I use one over the other?</p>
<p>The <a href="https://github.com/mbostock/topojson/" rel="noreferrer">description of TopoJSON on GitHub</a> implies the TopoJSON files are 80% smaller. So why not just use TopoJSON all the time?</p> | 14,765,321 | 3 | 0 | null | 2013-02-06 23:14:07.8 UTC | 36 | 2017-08-24 08:41:11.943 UTC | 2017-03-14 15:42:56.827 UTC | null | 1,974,961 | null | 451,139 | null | 1 | 99 | d3.js|gis|geojson|topojson | 41,838 | <p>If you care about file size or topology, then use TopoJSON. If you don’t care about either, then use GeoJSON for simplicity’s sake.</p>
<p>The primary advantage of TopoJSON is size. By eliminating redundancy and using a more efficent fixed-precision integer encoding of coordinates, TopoJSON files are often an order of magnitude smaller than GeoJSON files. The secondary advantage of TopoJSON files is that encoding the topology has useful applications, such as topology-preserving simplification (similar to <a href="http://www.cartogis.org/docs/proceedings/2006/bloch_harrower.pdf" rel="noreferrer">MapShaper</a>) and automatic mesh generation (as in the state-state boundaries in <a href="http://bl.ocks.org/4060606" rel="noreferrer">this example choropleth</a>).</p>
<p>These advantages come at a cost: a more complex file format. In JavaScript, for example, you’d typically use the <a href="https://github.com/topojson/topojson/" rel="noreferrer">TopoJSON client library</a> to convert TopoJSON to GeoJSON for use with standard tools such as <a href="https://github.com/d3/d3-geo/blob/master/README.md#geoPath" rel="noreferrer">d3.geoPath</a>. (In Python, you can use <a href="https://github.com/sgillies/topojson/blob/master/topojson.py" rel="noreferrer">topojson.py</a>.) Also, TopoJSON’s integer format requires quantizing coordinates, which means that it can introduce rounding error if you’re not careful. (See the documentation for <code>topojson -q</code>.)</p>
<p>For server-side manipulation of geometries that does not require topology, then GeoJSON is probably the simpler choice. Otherwise, if you need topology or want to send the geometry over the wire to a client, then use TopoJSON.</p> |
5,898,199 | Fatal error 'stdio.h' not found | <p>Why am I getting this message? The compiler is clang. Here is a simple program where it occurs for examples sake:</p>
<pre><code>#include<stdio.h>
int fib(int);
int main()
{
int i;
scanf("%d",&i);
printf("The fibonacci number that is %i'th in the sequence is %i \n", i, fib(i));
return 0;
}
int fib(int n)
{
if (n==1 || n==0) return 1;
else return fib(n-1)+fib(n-2);
}
</code></pre> | 5,898,279 | 2 | 4 | null | 2011-05-05 13:09:15.923 UTC | null | 2019-12-05 18:29:27.967 UTC | 2011-05-05 13:19:36.117 UTC | null | 597,893 | null | 597,893 | null | 1 | 4 | c | 51,713 | <h2>Assuming C</h2>
<p><code><stdio.h></code> is one of the standard C headers. Your compiler complains that it can not find this header. This means that your standard library is broken.</p>
<p>Consider reinstalling your compiler.</p>
<h2>Assuming C++</h2>
<p><code><stdio.h></code> is the C standard header, with C++ we use <code><cstdio></code> instead. Though <code><stdio.h></code> is still required to exist in C++, so this probably isn't the problem.</p>
<hr>
<p>Apart from these assumptions, it seems most likely (by your coding style and tags) that you are using C. Try this as some example code. This is guaranteed (by me) to compile on a working C compiler, if it doesn't then your compiler is horribly broken and you must install another one/reinstall:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
printf("Hello World!\n");
return EXIT_SUCCESS;
}
</code></pre> |
24,255,205 | Error Loading extension section usr_cert | <p>I am running openvpn on an Ubuntu 14.04 box. The setup was fine until an OpenSSL upgrade, then when I try to create new client cert with easy-rsa, I got this message:</p>
<pre><code>root@:easy-rsa# ./pkitool onokun
Using Common Name: onokun
Generating a 2048 bit RSA private key
.+++
........+++
writing new private key to 'onokun.key'
-----
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Error Loading extension section usr_cert
3074119356:error:0E06D06C:configuration file routines:NCONF_get_string:no value:conf_lib.c:335:group=CA_default name=email_in_dn
3074119356:error:2207507C:X509 V3 routines:v2i_GENERAL_NAME_ex:missing value:v3_alt.c:537:
3074119356:error:22098080:X509 V3 routines:X509V3_EXT_nconf:error in extension:v3_conf.c:93:name=subjectAltName, value=onokun
</code></pre>
<p>This problem is different from a reported bug that the <code>which opensslcnf</code> script can not find an matching version of <code>openssl.cnf</code> to use (above message shows <code>openssl-1.0.0.cnf</code>). I performed a Google search but did not find an answer.</p>
<p>Here are some environment information:</p>
<pre><code>## openvpn
OpenVPN 2.3.2 i686-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Feb 4 2014
Originally developed by James Yonan
## openssl
OpenSSL 1.0.1f 6 Jan 2014
## dpkg --get-selections | grep ssl
libgnutls-openssl27:i386 install
libio-socket-ssl-perl install
libnet-smtp-ssl-perl install
libnet-ssleay-perl install
libssl-dev:i386 install
libssl-doc install
libssl0.9.8:i386 install
libssl1.0.0:i386 install
openssl install
ssl-cert install
</code></pre>
<p>What should I look at to solve this? Thanks,</p> | 24,258,005 | 5 | 0 | null | 2014-06-17 03:18:57.877 UTC | 1 | 2017-10-31 19:56:30.483 UTC | 2015-02-27 23:56:30.843 UTC | null | 608,639 | null | 2,533,426 | null | 1 | 13 | ssl|openssl|openvpn | 50,273 | <blockquote>
<pre><code>Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Error Loading extension section usr_cert
</code></pre>
</blockquote>
<p>I don't have a <code>/etc/openvpn/easy-rsa/openssl-1.0.0.cnf</code>, so take this with a grain of salt...</p>
<p><code>opensslconf.h</code> from OpenSSL's distribution <em>does</em> include that section:</p>
<pre><code>openssl-1.0.1h$ grep -R usr_cert *
apps/openssl-vms.cnf:x509_extensions = usr_cert # The extensions to add to the cert
apps/openssl-vms.cnf:[ usr_cert ]
apps/openssl.cnf:x509_extensions = usr_cert # The extensions to add to the cert
apps/openssl.cnf:[ usr_cert ]
</code></pre>
<p>Can you restore an old version of <code>/etc/openvpn/easy-rsa/openssl-1.0.0.cnf</code>?</p>
<p>Here's the section from <code>apps/openssl.cnf</code>. You might consider adding it to Easy RSA's configuration file if its missing. First, try an empty section. Then try adding the original code back.</p>
<pre><code>[ usr_cert ]
# These extensions are added when 'ca' signs a request.
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints=CA:FALSE
# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.
# This is OK for an SSL server.
# nsCertType = server
# For an object signing certificate this would be used.
# nsCertType = objsign
# For normal client use this is typical
# nsCertType = client, email
# and for everything including object signing:
# nsCertType = client, email, objsign
# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
# This will be displayed in Netscape's comment listbox.
nsComment = "OpenSSL Generated Certificate"
# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move
# Copy subject details
# issuerAltName=issuer:copy
#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName
# This is required for TSA certificates.
# extendedKeyUsage = critical,timeStamping
</code></pre> |
2,475,450 | Extracting images from a PDF | <p>I am having a little query regarding Extracting specifically images ( only images ) from a supplied PDF document in iPhone Application.</p>
<p>I have gone through the documentation of apple - But I am failure to find it.</p>
<p>I have done following efforts to have the Image from PDF Document.</p>
<pre><code>-(IBAction)btnTappedImages:(id)sender{
// MyGetPDFDocumentRef is custom c method
// & filePath is path to pdf document.
CGPDFDocumentRef document = MyGetPDFDocumentRef ([filePath UTF8String]);
int pgcnt = CGPDFDocumentGetNumberOfPages( document );
for( int i1 = 0; i1 < pgcnt; ++i1 ) {
// 1. Open Document page
CGPDFPageRef pg = CGPDFDocumentGetPage (document, i1+1);
if( !pg ) {
NSLog(@"Couldn't open page.");
}
// 2. get page dictionary
CGPDFDictionaryRef dict = CGPDFPageGetDictionary( pg );
if( !dict ) {
NSLog(@"Couldn't open page dictionary.");
}
// 3. get page contents stream
CGPDFStreamRef cont;
if( !CGPDFDictionaryGetStream( dict, "Contents", &cont ) ) {
NSLog(@"Couldn't open page stream.");
}
// 4. copy page contents steam
// CFDataRef contdata = CGPDFStreamCopyData( cont, NULL );
// 5. get the media array from stream
CGPDFArrayRef media;
if( !CGPDFDictionaryGetArray( dict, "MediaBox", &media ) ) {
NSLog(@"Couldn't open page Media.");
}
// 6. open media & get it's size
CGPDFInteger mediatop, medialeft;
CGPDFReal mediaright, mediabottom;
if( !CGPDFArrayGetInteger( media, 0, &mediatop ) || !CGPDFArrayGetInteger( media, 1, &medialeft ) || !CGPDFArrayGetNumber( media, 2, &mediaright ) || !CGPDFArrayGetNumber( media, 3, &mediabottom ) ) {
NSLog(@"Couldn't open page Media Box.");
}
// 7. set media size
double mediawidth = mediaright - medialeft, mediaheight = mediabottom - mediatop;
// 8. get media resources
CGPDFDictionaryRef res;
if( !CGPDFDictionaryGetDictionary( dict, "Resources", &res ) ) {
NSLog(@"Couldn't Open Page Media Reopsources.");
}
// 9. get xObject from media resources
CGPDFDictionaryRef xobj;
if( !CGPDFDictionaryGetDictionary( res, "XObject", &xobj ) ) {
NSLog(@"Couldn't load page Xobjects.");
}
char imagestr[16];
sprintf( imagestr, "Im%d", i1 );
// 10. get x object stream
CGPDFStreamRef strm;
if( !CGPDFDictionaryGetStream( xobj, imagestr, &strm ) ) {
NSLog(@"Couldn't load stream for xObject");
}
// 11. get dictionary from xObject Stream
CGPDFDictionaryRef strmdict = CGPDFStreamGetDictionary( strm );
if( !strmdict ) {
NSLog(@"Failed to load dictionary for xObject");
}
// 12. get type of xObject
const char * type;
if( !CGPDFDictionaryGetName( strmdict, "Type", &type ) || strcmp(type, "XObject" ) ) {
NSLog(@"Couldn't load xObject Type");
}
// 13. Check weather subtype is image or not
const char * subtype;
if( !CGPDFDictionaryGetName( strmdict, "Subtype", &subtype ) || strcmp( subtype, "Image" ) ) {
NSLog(@"xObject is not image");
}
// 14. Bits per component
CGPDFInteger bitsper;
if( !CGPDFDictionaryGetInteger( strmdict, "BitsPerComponent",&bitsper ) || bitsper != 1 ) {
NSLog(@"Bits per component not loaded");
}
// 15. Type of filter of image
const char * filter;
if( !CGPDFDictionaryGetName( strmdict, "Filter", &filter ) || strcmp( filter, "FlateDecode" ) ) {
NSLog(@"Filter not loaded");
}
// 16. Image height width
CGPDFInteger width, height;
if( !CGPDFDictionaryGetInteger( strmdict, "Width", &width ) || !CGPDFDictionaryGetInteger( strmdict, "Height", &height ) ) {
NSLog(@"Image Height - width not loaded.");
}
// 17. Load image bytes & verify it
CGPDFDataFormat fmt = CGPDFDataFormatRaw;
CFDataRef data = CGPDFStreamCopyData( strm, &fmt );
int32_t len = CFDataGetLength( data );
const void * bytes = CFDataGetBytePtr( data );
// now I have bytes for images in "bytes" pointer the problem is how to covert it into UIImage
NSLog(@"Image bytes length - %i",len);
int32_t rowbytes = (width + 7) / 8;
if( rowbytes * height != len ) {
NSLog(@"Invalid Image");
}
double xres = width / mediawidth * 72.0, yres = height / mediaheight * 72.0;
xres = round( xres * 1000 ) / 1000;
yres = round( yres * 1000 ) / 1000;
}
}
</code></pre> | 2,492,305 | 3 | 0 | null | 2010-03-19 06:46:56.343 UTC | 19 | 2018-02-02 12:24:52.427 UTC | 2018-02-02 12:24:52.427 UTC | null | 472,495 | null | 140,765 | null | 1 | 5 | iphone|objective-c|xcode|pdf|cfdata | 11,711 | <p>Yes ! I found it. But It looks very scary - huge code.</p>
<pre><code>NSMutableArray *aRefImgs;
void setRefImgs(NSMutableArray *ref){
aRefImgs=ref;
}
NSMutableArray* ImgArrRef(){
return aRefImgs;
}
CGPDFDocumentRef MyGetPDFDocumentRef (const char *filename) {
CFStringRef path;
CFURLRef url;
CGPDFDocumentRef document;
path = CFStringCreateWithCString (NULL, filename,kCFStringEncodingUTF8);
url = CFURLCreateWithFileSystemPath (NULL, path, kCFURLPOSIXPathStyle, 0);
CFRelease (path);
document = CGPDFDocumentCreateWithURL (url);// 2
CFRelease(url);
int count = CGPDFDocumentGetNumberOfPages (document);// 3
if (count == 0) {
printf("`%s' needs at least one page!", filename);
return NULL;
}
return document;
}
CGFloat *decodeValuesFromImageDictionary(CGPDFDictionaryRef dict, CGColorSpaceRef cgColorSpace, NSInteger bitsPerComponent) {
CGFloat *decodeValues = NULL;
CGPDFArrayRef decodeArray = NULL;
if (CGPDFDictionaryGetArray(dict, "Decode", &decodeArray)) {
size_t count = CGPDFArrayGetCount(decodeArray);
decodeValues = malloc(sizeof(CGFloat) * count);
CGPDFReal realValue;
int i;
for (i = 0; i < count; i++) {
CGPDFArrayGetNumber(decodeArray, i, &realValue);
decodeValues[i] = realValue;
}
} else {
size_t n;
switch (CGColorSpaceGetModel(cgColorSpace)) {
case kCGColorSpaceModelMonochrome:
decodeValues = malloc(sizeof(CGFloat) * 2);
decodeValues[0] = 0.0;
decodeValues[1] = 1.0;
break;
case kCGColorSpaceModelRGB:
decodeValues = malloc(sizeof(CGFloat) * 6);
for (int i = 0; i < 6; i++) {
decodeValues[i] = i % 2 == 0 ? 0 : 1;
}
break;
case kCGColorSpaceModelCMYK:
decodeValues = malloc(sizeof(CGFloat) * 8);
for (int i = 0; i < 8; i++) {
decodeValues[i] = i % 2 == 0 ? 0.0 :
1.0;
}
break;
case kCGColorSpaceModelLab:
// ????
break;
case kCGColorSpaceModelDeviceN:
n =
CGColorSpaceGetNumberOfComponents(cgColorSpace) * 2;
decodeValues = malloc(sizeof(CGFloat) * (n *
2));
for (int i = 0; i < n; i++) {
decodeValues[i] = i % 2 == 0 ? 0.0 :
1.0;
}
break;
case kCGColorSpaceModelIndexed:
decodeValues = malloc(sizeof(CGFloat) * 2);
decodeValues[0] = 0.0;
decodeValues[1] = pow(2.0,
(double)bitsPerComponent) - 1;
break;
default:
break;
}
}
return (CGFloat *)CFMakeCollectable(decodeValues);
}
UIImage *getImageRef(CGPDFStreamRef myStream) {
CGPDFArrayRef colorSpaceArray = NULL;
CGPDFStreamRef dataStream;
CGPDFDataFormat format;
CGPDFDictionaryRef dict;
CGPDFInteger width, height, bps, spp;
CGPDFBoolean interpolation = 0;
// NSString *colorSpace = nil;
CGColorSpaceRef cgColorSpace;
const char *name = NULL, *colorSpaceName = NULL, *renderingIntentName = NULL;
CFDataRef imageDataPtr = NULL;
CGImageRef cgImage;
//maskImage = NULL,
CGImageRef sourceImage = NULL;
CGDataProviderRef dataProvider;
CGColorRenderingIntent renderingIntent;
CGFloat *decodeValues = NULL;
UIImage *image;
if (myStream == NULL)
return nil;
dataStream = myStream;
dict = CGPDFStreamGetDictionary(dataStream);
// obtain the basic image information
if (!CGPDFDictionaryGetName(dict, "Subtype", &name))
return nil;
if (strcmp(name, "Image") != 0)
return nil;
if (!CGPDFDictionaryGetInteger(dict, "Width", &width))
return nil;
if (!CGPDFDictionaryGetInteger(dict, "Height", &height))
return nil;
if (!CGPDFDictionaryGetInteger(dict, "BitsPerComponent", &bps))
return nil;
if (!CGPDFDictionaryGetBoolean(dict, "Interpolate", &interpolation))
interpolation = NO;
if (!CGPDFDictionaryGetName(dict, "Intent", &renderingIntentName))
renderingIntent = kCGRenderingIntentDefault;
else{
renderingIntent = kCGRenderingIntentDefault;
// renderingIntent = renderingIntentFromName(renderingIntentName);
}
imageDataPtr = CGPDFStreamCopyData(dataStream, &format);
dataProvider = CGDataProviderCreateWithCFData(imageDataPtr);
CFRelease(imageDataPtr);
if (CGPDFDictionaryGetArray(dict, "ColorSpace", &colorSpaceArray)) {
cgColorSpace = CGColorSpaceCreateDeviceRGB();
// cgColorSpace = colorSpaceFromPDFArray(colorSpaceArray);
spp = CGColorSpaceGetNumberOfComponents(cgColorSpace);
} else if (CGPDFDictionaryGetName(dict, "ColorSpace", &colorSpaceName)) {
if (strcmp(colorSpaceName, "DeviceRGB") == 0) {
cgColorSpace = CGColorSpaceCreateDeviceRGB();
// CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
spp = 3;
} else if (strcmp(colorSpaceName, "DeviceCMYK") == 0) {
cgColorSpace = CGColorSpaceCreateDeviceCMYK();
// CGColorSpaceCreateWithName(kCGColorSpaceGenericCMYK);
spp = 4;
} else if (strcmp(colorSpaceName, "DeviceGray") == 0) {
cgColorSpace = CGColorSpaceCreateDeviceGray();
// CGColorSpaceCreateWithName(kCGColorSpaceGenericGray);
spp = 1;
} else if (bps == 1) { // if there's no colorspace entry, there's still one we can infer from bps
cgColorSpace = CGColorSpaceCreateDeviceGray();
// colorSpace = NSDeviceBlackColorSpace;
spp = 1;
}
}
decodeValues = decodeValuesFromImageDictionary(dict, cgColorSpace, bps);
int rowBits = bps * spp * width;
int rowBytes = rowBits / 8;
// pdf image row lengths are padded to byte-alignment
if (rowBits % 8 != 0)
++rowBytes;
// maskImage = SMaskImageFromImageDictionary(dict);
if (format == CGPDFDataFormatRaw)
{
sourceImage = CGImageCreate(width, height, bps, bps * spp, rowBytes, cgColorSpace, 0, dataProvider, decodeValues, interpolation, renderingIntent);
CGDataProviderRelease(dataProvider);
cgImage = sourceImage;
// if (maskImage != NULL) {
// cgImage = CGImageCreateWithMask(sourceImage, maskImage);
// CGImageRelease(sourceImage);
// CGImageRelease(maskImage);
// } else {
// cgImage = sourceImage;
// }
} else {
if (format == CGPDFDataFormatJPEGEncoded){ // JPEG data requires a CGImage; AppKit can't decode it {
sourceImage =
CGImageCreateWithJPEGDataProvider(dataProvider,decodeValues,interpolation,renderingIntent);
CGDataProviderRelease(dataProvider);
cgImage = sourceImage;
// if (maskImage != NULL) {
// cgImage = CGImageCreateWithMask(sourceImage,maskImage);
// CGImageRelease(sourceImage);
// CGImageRelease(maskImage);
// } else {
// cgImage = sourceImage;
// }
}
// note that we could have handled JPEG with ImageIO as well
else if (format == CGPDFDataFormatJPEG2000) { // JPEG2000 requires ImageIO {
CFDictionaryRef dictionary = CFDictionaryCreate(NULL, NULL, NULL, 0, NULL, NULL);
sourceImage=
CGImageCreateWithJPEGDataProvider(dataProvider, decodeValues, interpolation, renderingIntent);
// CGImageSourceRef cgImageSource = CGImageSourceCreateWithDataProvider(dataProvider, dictionary);
CGDataProviderRelease(dataProvider);
cgImage=sourceImage;
// cgImage = CGImageSourceCreateImageAtIndex(cgImageSource, 0, dictionary);
CFRelease(dictionary);
} else // some format we don't know about or an error in the PDF
return nil;
}
image=[UIImage imageWithCGImage:cgImage];
return image;
}
@implementation DashBoard
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
filePath=[[NSString alloc] initWithString:[[NSBundle mainBundle] pathForResource:@"per" ofType:@"pdf"]];
}
-(IBAction)btnTappedText:(id)sender{
if(arrImgs!=nil && [arrImgs retainCount]>0 ) { [arrImgs release]; arrImgs=nil; }
arrImgs=[[NSMutableArray alloc] init];
setRefImgs(arrImgs);
// if(nxtTxtDtlVCtr!=nil && [nxtTxtDtlVCtr retainCount]>0) { [nxtTxtDtlVCtr release]; nxtTxtDtlVCtr=nil; }
// nxtTxtDtlVCtr=[[TxtDtlVCtr alloc] initWithNibName:@"TxtDtlVCtr" bundle:nil];
// nxtTxtDtlVCtr.str=StringRef();
// [self.navigationController pushViewController:nxtTxtDtlVCtr animated:YES];
// 1. Open Document page
CGPDFDocumentRef document = MyGetPDFDocumentRef ([filePath UTF8String]);
int pgcnt = CGPDFDocumentGetNumberOfPages( document );
for( int i1 = 0; i1 < pgcnt; ++i1 ) {
CGPDFPageRef pg = CGPDFDocumentGetPage (document, i1+1);
if( !pg ) {
NSLog(@"Couldn't open page.");
} else {
// 2. get page dictionary
CGPDFDictionaryRef dict = CGPDFPageGetDictionary( pg );
if( !dict ) {
NSLog(@"Couldn't open page dictionary.");
} else {
// 3. get page contents stream
CGPDFStreamRef cont;
if( !CGPDFDictionaryGetStream( dict, "Contents", &cont ) ) {
NSLog(@"Couldn't open page stream.");
} else {
// 4. copy page contents steam
// CFDataRef contdata = CGPDFStreamCopyData( cont, NULL );
// 5. get the media array from stream
CGPDFArrayRef media;
if( !CGPDFDictionaryGetArray( dict, "MediaBox", &media ) ) {
NSLog(@"Couldn't open page Media.");
} else {
// 6. open media & get it's size
CGPDFInteger mediatop, medialeft;
CGPDFReal mediaright, mediabottom;
if( !CGPDFArrayGetInteger( media, 0, &mediatop ) || !CGPDFArrayGetInteger( media, 1, &medialeft ) || !CGPDFArrayGetNumber( media, 2, &mediaright ) || !CGPDFArrayGetNumber( media, 3, &mediabottom ) ) {
NSLog(@"Couldn't open page Media Box.");
} else {
// 7. set media size
// double mediawidth = mediaright - medialeft, mediaheight = mediabottom - mediatop;
// 8. get media resources
CGPDFDictionaryRef res;
if( !CGPDFDictionaryGetDictionary( dict, "Resources", &res ) ) {
NSLog(@"Couldn't Open Page Media Reopsources.");
} else {
// 9. get xObject from media resources
CGPDFDictionaryRef xobj;
if( !CGPDFDictionaryGetDictionary( res, "XObject", &xobj ) ) {
NSLog(@"Couldn't load page Xobjects.");
} else {
CGPDFDictionaryApplyFunction(xobj, pdfDictionaryFunction, NULL);
}
}
}
}
}
}
}
}
NSLog(@"Total images are - %i",[arrImgs count]);
if(nxtImgVCtr!=nil && [nxtImgVCtr retainCount]>0 ) { [nxtImgVCtr release]; nxtImgVCtr=nil; }
nxtImgVCtr=[[ImgVCtr alloc] initWithNibName:@"ImgVCtr" bundle:nil];
nxtImgVCtr.arrImg=arrImgs;
[self.navigationController pushViewController:nxtImgVCtr animated:YES];
}
</code></pre> |
22,592,686 | Compiling Python 3.4 is not copying pip | <p>I have compiled Python 3.4 from the sources on Linux Mint, but for some reason it is not copying <code>pip</code> to its final compiled folder (after the <code>make install</code>).</p>
<p>Any ideas?</p> | 22,594,608 | 3 | 0 | null | 2014-03-23 15:12:38.98 UTC | 4 | 2016-11-07 14:52:07.553 UTC | 2016-10-01 02:40:36.847 UTC | null | 832,230 | null | 565,977 | null | 1 | 30 | python|compilation|pip|python-3.4 | 22,198 | <p>Just sorted it out. Here it is how to compile python from the sources.</p>
<pre><code>$ ./configure --prefix=/home/user/sources/compiled/python3.4_dev --with-ensurepip=install
$ make
$ make install
</code></pre>
<p>If you get "Ignoring ensurepip failure: pip 1.5.4 requires SSL/TLS" error:</p>
<pre><code>$ sudo apt-get install libssl-dev openssl
$ ls
2to3 idle3 pip3.5 python3 python3.5m pyvenv
2to3-3.5 idle3.5 pydoc3 python3.5 python3.5m-config pyvenv-3.5
easy_install-3.5 pip3 pydoc3.5 python3.5-config python3-config
</code></pre>
<p>As you can see pip is copied into target folder, the <code>--with-ensurepip=install</code> is important.</p> |
56,014,935 | Problem with play-services-measurement-base on ionic | <p>I have a problem on an ionic project that it started happening yesterday without modifying any dependency.</p>
<p>When I run <code>ionic cordova run android</code> I have this error:</p>
<pre><code>The library com.google.android.gms:play-services-measurement-base is being requested by various other libraries at [[16.5.0,16.5.0], [16.4.0,16.4.0]], but resolves to 16.5.0. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.
</code></pre>
<p>But I didn't installed any dependency in these days.</p>
<p>This is my <code>cordova plugins</code> list:</p>
<pre><code>cordova-fabric-plugin 1.1.14-dev "cordova-fabric-plugin"
cordova-plugin-advanced-http 2.0.9 "Advanced HTTP plugin"
cordova-plugin-app-version 0.1.9 "AppVersion"
cordova-plugin-appminimize 1.0.1 "AppMinimize"
cordova-plugin-apprate 1.4.0 "AppRate"
cordova-plugin-appsee 2.6.0 "Appsee"
cordova-plugin-badge 0.8.8 "Badge"
cordova-plugin-datepicker 0.9.3 "DatePicker"
cordova-plugin-device 2.0.2 "Device"
cordova-plugin-dialogs 2.0.1 "Notification"
cordova-plugin-facebook4 3.2.0 "Facebook Connect"
cordova-plugin-file 6.0.1 "File"
cordova-plugin-firebase 2.0.5 "Google Firebase Plugin"
cordova-plugin-freshchat 1.2.0 "Freshchat plugin for Phonegap"
cordova-plugin-geolocation 4.0.1 "Geolocation"
cordova-plugin-globalization 1.11.0 "Globalization"
cordova-plugin-inappbrowser 3.0.0 "InAppBrowser"
cordova-plugin-inapppurchase-fixed 1.1.0 "In App Purchase"
cordova-plugin-insomnia 4.3.0 "Insomnia (prevent screen sleep)"
cordova-plugin-local-notification 0.9.0-beta.2 "LocalNotification"
cordova-plugin-media 5.0.2 "Media"
cordova-plugin-nativegeocoder 3.2.2 "NativeGeocoder"
cordova-plugin-nativestorage 2.3.2 "NativeStorage"
cordova-plugin-network-information 2.0.1 "Network Information"
cordova-plugin-splashscreen 5.0.2 "Splashscreen"
cordova-plugin-statusbar 2.4.2 "StatusBar"
cordova-plugin-whitelist 1.3.3 "Whitelist"
cordova-plugin-x-socialsharing 5.4.4 "SocialSharing"
cordova-support-google-services 1.2.1 "cordova-support-google-services"
es6-promise-plugin 4.2.2 "Promise"
ionic-plugin-deeplinks 1.0.19 "Ionic Deeplink Plugin"
nl.kingsquare.cordova.background-audio 1.0.1 "background-audio"
pushwoosh-cordova-plugin 7.13.0 "Pushwoosh"
</code></pre>
<p>I found these dependencies in my <code>platforms/android/app/build.gradle</code> (if it's good to know):</p>
<pre><code>dependencies {
implementation fileTree(dir: 'libs', include: '*.jar')
// SUB-PROJECT DEPENDENCIES START
implementation(project(path: ":CordovaLib"))
compile "com.android.support:support-v4:24.1.1+"
compile "com.squareup.okhttp3:okhttp-urlconnection:3.10.0"
compile "com.google.android.gms:play-services-tagmanager:+"
compile "com.google.firebase:firebase-core:+"
compile "com.google.firebase:firebase-messaging:+"
compile "com.google.firebase:firebase-config:+"
compile "com.google.firebase:firebase-perf:+"
compile "com.android.support:support-v4:26.+"
compile "com.android.support:support-v4:27.+"
compile "com.android.support:appcompat-v7:27.+"
compile "com.android.support:recyclerview-v7:27.+"
compile "com.android.support:design:27.+"
compile "com.android.support.constraint:constraint-layout:1.0.2"
compile "com.github.bumptech.glide:glide:4.7.1"
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:1.1.60"
compile "com.pushwoosh:pushwoosh:5.13.0"
compile "com.pushwoosh:pushwoosh-amazon:5.13.0"
compile "com.pushwoosh:pushwoosh-badge:5.13.0"
compile "com.pushwoosh:pushwoosh-inbox:5.13.0"
compile "com.pushwoosh:pushwoosh-inbox-ui:5.13.0"
compile "com.facebook.android:facebook-android-sdk:4.38.1"
compile "com.appsee:appsee-android:2.6.0"
// SUB-PROJECT DEPENDENCIES END
}
</code></pre>
<p>I don't know where to search. I found a workaround that is disabling version check of GoogleServicesPlugin in the <code>platforms/android/build.gradle</code> making: <code>com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true</code> but it doesn't work for me.</p>
<p>Thanks in advance.</p>
<p><strong>EDIT</strong>: It seems like i'm not the only one. <a href="https://forum.ionicframework.com/t/ionic-4-cordova-run-android-firebase-error-all-of-a-sudden/163204/8" rel="noreferrer">Here</a>.</p> | 56,028,118 | 11 | 0 | null | 2019-05-07 03:00:07.89 UTC | 12 | 2019-10-03 19:25:08.243 UTC | 2019-05-07 18:01:54.65 UTC | null | 7,314,014 | null | 7,314,014 | null | 1 | 55 | android|ionic-framework|android-gradle-plugin|ionic3|ionic-native | 18,103 | <p>No solutions posted here worked for me. A wonderful person opened a <a href="https://github.com/arnesson/cordova-plugin-firebase/pull/1058" rel="noreferrer">pull request</a> in the <code>cordova-firebase-plugin</code> official repo and it works.</p>
<p>Steps I did:</p>
<p>1 - Remove cordova-firebase-plugin with <code>ionic cordova plugin remove cordova-plugin-firebase</code></p>
<p>2 - Install: <code>ionic cordova plugin add cordova-plugin-firebasex</code></p>
<p>3 - <code>rm -rf node_modules/ plugins/ platforms/android package-lock.json</code></p>
<p>4 - <code>ionic cordova platform add android && npm install</code></p>
<p>And now it's working.</p> |
41,881,169 | navigation property should be virtual - not required in ef core? | <p>As I remember in EF <a href="https://stackoverflow.com/questions/25715474/why-navigation-properties-are-virtual-by-default-in-ef">navigation property should be virtual</a>:</p>
<pre><code>public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Tags { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
</code></pre>
<p>But I look at <a href="https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro" rel="noreferrer">EF Core</a> and don't see it as virtual:</p>
<pre><code>public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
</code></pre>
<p>Is it not required anymore?</p> | 41,881,299 | 5 | 0 | null | 2017-01-26 19:14:38.223 UTC | 19 | 2021-10-28 14:45:15.623 UTC | 2017-05-23 12:18:22.57 UTC | null | -1 | null | 240,564 | null | 1 | 95 | c#|entity-framework|virtual|entity-framework-core|navigation-properties | 67,538 | <p><code>virtual</code> was never <strong>required</strong> in EF. It was needed only if you want lazy loading support.</p>
<p>Since <a href="https://docs.microsoft.com/en-us/ef/core/querying/related-data" rel="noreferrer">Lazy loading is not yet supported by EF Core</a>, currently <code>virtual</code> have no special meaning. It would when (and if) they add lazy loading support (there is a <a href="https://github.com/aspnet/EntityFramework/wiki/Roadmap" rel="noreferrer">plan</a> for doing so).</p>
<p><strong>Update:</strong> Starting with EF Core 2.1, <a href="https://docs.microsoft.com/en-us/ef/core/querying/related-data#lazy-loading" rel="noreferrer">Lazy loading</a> is now supported. But if you don't add <a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Proxies/" rel="noreferrer">Microsoft.EntityFrameworkCore.Proxies</a> package and enable it via <code>UseLazyLoadingProxies</code>, the original answer still applies.</p>
<p>However if you do so, the thing's totally changed due to the lack of the opt-in control in the initial implementation - it <em>requires</em> <strong>all</strong> your navigation properties to be <code>virtual</code>. Which makes no sense to me, you'd better not use that until it gets fixed. If you really need lazy loading, use the alternative <a href="https://docs.microsoft.com/en-us/ef/core/querying/related-data/lazy#lazy-loading-without-proxies" rel="noreferrer">Lazy loading without proxies</a> approach, in which case again <code>virtual</code> doesn't matter.</p> |
3,106,459 | How to POST an xml element in python | <p>Basically I have this xml element (xml.etree.ElementTree) and I want to POST it to a url. Currently I'm doing something like</p>
<pre><code>xml_string = xml.etree.ElementTree.tostring(my_element)
data = urllib.urlencode({'xml': xml_string})
response = urllib2.urlopen(url, data)
</code></pre>
<p>I'm pretty sure that works and all, but was wondering if there is some better practice or way to do it without converting it to a string first.</p>
<p>Thanks!</p> | 3,106,518 | 3 | 1 | null | 2010-06-24 00:18:42.29 UTC | 9 | 2013-09-25 20:58:38.68 UTC | null | null | null | null | 354,817 | null | 1 | 13 | python|xml|post|urllib2 | 20,055 | <p>If this is your own API, I would consider POSTing as <code>application/xml</code>. The default is <code>application/x-www-form-urlencoded</code>, which is meant for HTML form data, not a single XML document.</p>
<pre><code>req = urllib2.Request(url=url,
data=xml_string,
headers={'Content-Type': 'application/xml'})
urllib2.urlopen(req)
</code></pre> |
2,541,526 | Delegate OpenID to Google (NOT Google Apps) | <p>Is it possible to use my personal website/blog to login to sites that use <em>openid</em>, and delegating to my Google account?</p>
<hr>
<p>OK, I searched this question on SO but no good answer. After spent some time I figured out how to do it. I'm going to answer this myself as a way to share it.</p> | 2,545,245 | 3 | 5 | 2010-03-29 21:51:38.107 UTC | 2010-03-29 21:51:38.107 UTC | 56 | 2015-05-14 02:43:36.373 UTC | 2013-08-03 20:28:33.103 UTC | null | 365,265 | null | 184,061 | null | 1 | 85 | openid|google-oauth|delegation | 9,548 | <p><strong>Now it is possible delegate OpenID to your Google account (not Google Apps)</strong>. </p>
<p>No, this is <em>not</em> using the <a href="http://openid-provider.appspot.com/" rel="noreferrer">demo OpenID provider</a> using App Engine. This is your REAL Google account! </p>
<p>First you need to enable your <a href="http://www.google.com/profiles/" rel="noreferrer">Google Profiles</a>. Try to view your profile and edit it, there should be an option to set your Profile URL. You have two choices there: either use your Gmail account name (without the @gmail.com part) as your profile id, or a random number assigned to you. It's up to you to decide which one to use. Either way, that id is your profile id below. </p>
<p>Now add the following HTML code to your delegating page: </p>
<pre><code><link rel="openid2.provider" href="https://www.google.com/accounts/o8/ud?source=profiles" />
<link rel="openid2.local_id" href="https://profiles.google.com/[YOUR PROFILE ID]" />
</code></pre>
<p>And it's done. Now try login SO with your custom url! </p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.