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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,915,829 | Learning C when you already know C++? | <p>I think I have an advanced knowledge of C++, and I'd like to learn C.</p>
<p>There are a lot of resources to help people going from C to C++, but I've not found anything useful to do the opposite of that. </p>
<p>Specifically:</p>
<ol>
<li>Are there widely used general purpose libraries every C programmer should know about (like boost for C++) ?</li>
<li>What are the most important C idioms (like RAII for C++) ?</li>
<li>Should I learn C99 and use it, or stick to C89 ?</li>
<li>Any pitfalls/traps for a C++ developer ?</li>
<li>Anything else useful to know ?</li>
</ol> | 1,917,084 | 10 | 0 | null | 2009-12-16 16:25:30.187 UTC | 16 | 2014-02-18 17:50:12.723 UTC | 2014-02-18 17:50:12.723 UTC | null | 191,367 | null | 191,367 | null | 1 | 22 | c++|c | 15,137 | <p>There's a lot here already, so maybe this is just a minor addition but here's what I find to be the biggest differences.</p>
<p>Library:</p>
<ul>
<li>I put this first, because this in my opinion this is the biggest difference in practice. The C standard library is very(!) sparse. It offers a bare minimum of services. For everything else you have to roll your own or find a library to use (and many people do). You have file I/O and some very basic string functions and math. For everything else you have to roll your own or find a library to use. I find I miss extended containers (especially maps) heavily when moving from C++ to C, but there are a lot of other ones.</li>
</ul>
<p>Idioms:</p>
<ul>
<li>Both languages have manual memory (resource) management, but C++ gives you some tools to hide the need. In C you will find yourself tracking resources by hand much more often, and you have to get used to that. Particular examples are arrays and strings (C++ <code>vector</code> and <code>string</code> save you a lot of work), smart pointers (you can't really do "smart pointers" as such in C. You <em>can</em> do reference counting, but you have to up and down the reference counts yourself, which is very error prone -- the reason smart pointers were added to C++ in the first place), and the lack of RAII generally which you will notice everywhere if you are used to the modern style of C++ programming.
<ul>
<li>You have to be explicit about construction and destruction. You can argue about the merits of flaws of this, but there's a lot more explicit code as a result.</li>
</ul></li>
<li>Error handling. C++ exceptions can be tricky to get right so not everyone uses them, but if you do use them you will find you have to pay a lot of attention to how you do error notification. Needing to check for return values on all important calls (some would argue <em>all</em> calls) takes a lot of discipline and a lot of C code out there doesn't do it.</li>
<li>Strings (and arrays in general) don't carry their sizes around. You have to pass a lot of extra parameters in C to deal with this.</li>
<li>Without namespaces you have to manage your global namespace carefully.
<ul>
<li>There's no explicit tying of functions to types as there is with <code>class</code> in C++. You have to maintain a convention of prefixing everything you want associated with a type.</li>
</ul></li>
<li>You will see a lot more macros. Macros are used in C in many places where C++ has language features to do the same, especially symbolic constants (C has <code>enum</code> but lots of older code uses <code>#define</code> instead), and for generics (where C++ uses templates).</li>
</ul>
<p>Advice:</p>
<ul>
<li>Consider finding an extended library for general use. Take a look at <a href="http://library.gnome.org/devel/glib/stable/" rel="noreferrer">GLib</a> or <a href="http://apr.apache.org/" rel="noreferrer">APR</a>.
<ul>
<li>Even if you don't want a full library consider finding a map / dictionary / hashtable for general use. Also consider bundling up a bare bones "string" type that contains a size.</li>
</ul></li>
<li>Get used to putting module or "class" prefixes on all public names. This is a little tedious but it will save you a lot of headaches.</li>
<li><p>Make heavy use of forward declaration to make types opaque. Where in C++ you might have private data in a header and rely on <code>private</code> is preventing access, in C you want to push implementation details into the source files as much as possible. (You actually want to do this in C++ too in my opinion, but C makes it easier, so more people do it.)</p>
<p>C++ reveals the implementation in the header, even though it technically hides it from access outside the class.</p>
<pre><code>// C.hh
class C
{
public:
void method1();
int method2();
private:
int value1;
char * value2;
};
</code></pre>
<p>C pushes the 'class' definition into the source file. The header is all forward declarations.</p>
<pre><code>// C.h
typedef struct C C; // forward declaration
void c_method1(C *);
int c_method2(C *);
// C.c
struct C
{
int value1;
char * value2;
};
</code></pre></li>
</ul> |
2,108,503 | Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain | <p>How do you fix this <strong>XCode error</strong> :</p>
<blockquote>
<p>Code Sign error: The identity 'iPhone Developer' doesn't match any
valid certificate/private key pair in the default keychain</p>
</blockquote> | 4,453,252 | 12 | 7 | null | 2010-01-21 10:43:33.917 UTC | 17 | 2013-06-10 11:08:16.793 UTC | 2013-06-10 11:08:16.793 UTC | null | 1,603,072 | null | 210,188 | null | 1 | 77 | iphone | 114,679 | <p>This happens if you forgot to change your build settings to <code>Simulator</code>. Unless you want to build to a device, in which case you should see the other answers.</p> |
8,765,879 | how to limit foreach loop to three loops | <p>how to limit this loop ..just thee loops..thanks for helping</p>
<pre><code><?php
foreach($section['Article'] as $article) :
?>
<tr>
<td>
<?php
if ($article['status'] == 1) {
echo $article['title'];
}
?>
</td>
<td>
<?php
if($article['status']== 1) {
echo '&nbsp;'.$html->link('View', '/articles/view/'.$article['id']);
}
?>
</td>
</tr>
<?php
endforeach;
?>
</code></pre> | 8,765,910 | 6 | 2 | null | 2012-01-06 23:35:30.077 UTC | 14 | 2019-08-01 09:11:39.227 UTC | 2012-08-01 07:50:16.447 UTC | null | 367,456 | null | 1,080,247 | null | 1 | 21 | php | 98,298 | <p>Slice the array.</p>
<pre><code>foreach(array_slice($section['Article'], 0, 3) as $article ):
</code></pre> |
8,486,414 | Check image dimensions (height and width) before uploading image using PHP | <p>How can I check for height and width before uploading image, using PHP.</p>
<p>Must I upload the image first and use "getimagesize()"? Or can I check this before uploading it using PHP?</p>
<pre><code><?php
foreach ($_FILES["files"]["error"] as $key => $error) {
if(
$error == UPLOAD_ERR_OK
&& $_FILES["files"]["size"][$key] < 500000
&& $_FILES["files"]["type"][$key] == "image/gif"
|| $_FILES["files"]["type"][$key] == "image/png"
|| $_FILES["files"]["type"][$key] == "image/jpeg"
|| $_FILES["files"]["type"][$key] == "image/pjpeg"
){
$filename = $_FILES["files"]["name"][$key];
if(HOW TO CHECK WIDTH AND HEIGHT)
{
echo '<p>image dimenssions must be less than 1000px width and 1000px height';
}
}
?>
</code></pre> | 8,486,471 | 8 | 2 | null | 2011-12-13 08:49:57.243 UTC | 5 | 2016-07-01 08:45:52.44 UTC | null | null | null | null | 673,108 | null | 1 | 30 | php|image|file-upload|dimensions | 96,611 | <p>You need something that is executed on the client before the actual upload happens.<br>
With (server-side) php you can check the dimension only after the file has been uploaded or with <a href="https://www.ibm.com/developerworks/library/os-php-v525/" rel="nofollow">upload hooks</a> <em>maybe</em> while the image is uploaded (from the image file header data). </p>
<p>So your options are flash, maybe html5 with its FileAPI (haven't tested that, maybe that's not doable), java-applet, silverlight, ...</p> |
46,562,561 | Apollo/GraphQL field type for object with dynamic keys | <p>Let's say my graphql server wants to fetch the following data as JSON where <code>person3</code> and <code>person5</code> are some id's:</p>
<pre><code>"persons": {
"person3": {
"id": "person3",
"name": "Mike"
},
"person5": {
"id": "person5",
"name": "Lisa"
}
}
</code></pre>
<p><strong>Question</strong>: How to create the schema type definition with apollo?</p>
<p>The keys <code>person3</code> and <code>person5</code> here are dynamically generated depending on my query (i.e. the <code>area</code> used in the query). So at another time I might get <code>person1</code>, <code>person2</code>, <code>person3</code> returned.
As you see <code>persons</code> is not an Iterable, so the following won't work as a graphql type definition I did with apollo:</p>
<pre><code>type Person {
id: String
name: String
}
type Query {
persons(area: String): [Person]
}
</code></pre>
<p>The keys in the <code>persons</code> object may always be different.</p>
<p>One solution of course would be to transform the incoming JSON data to use an array for <code>persons</code>, but is there no way to work with the data as such?</p> | 46,563,788 | 3 | 4 | null | 2017-10-04 10:24:38.057 UTC | 7 | 2021-07-26 01:58:06.76 UTC | 2017-10-04 11:09:47.073 UTC | null | 3,210,677 | null | 3,210,677 | null | 1 | 45 | graphql|apollo|apollo-server | 28,772 | <p>GraphQL relies on both the server and the client knowing ahead of time what fields are available available for each type. In some cases, the client can discover those fields (via introspection), but for the server, they always need to be known ahead of time. So to somehow dynamically generate those fields based on the returned data is not really possible.</p>
<p>You <strong>could</strong> utilize a custom <a href="https://github.com/taion/graphql-type-json" rel="noreferrer">JSON scalar</a> (graphql-type-json module) and return that for your query:</p>
<pre><code>type Query {
persons(area: String): JSON
}
</code></pre>
<p>By utilizing JSON, you bypass the requirement for the returned data to fit any specific structure, so you can send back whatever you want as long it's properly formatted JSON.</p>
<p>Of course, there's significant disadvantages in doing this. For example, you lose the safety net provided by the type(s) you would have previously used (literally any structure could be returned, and if you're returning the wrong one, you won't find out about it until the client tries to use it and fails). You also lose the ability to use resolvers for any fields within the returned data.</p>
<p>But... your funeral :)</p>
<p>As an aside, I would consider flattening out the data into an array (like you suggested in your question) before sending it back to the client. If you're writing the client code, and working with a dynamically-sized list of customers, chances are an array will be much easier to work with rather than an object keyed by id. If you're using React, for example, and displaying a component for each customer, you'll end up converting that object to an array to map it anyway. In designing your API, I would make client usability a higher consideration than avoiding additional processing of your data.</p> |
18,163,404 | spring mvc date format with form:input | <p>I have hibernate entity and a bean:</p>
<pre><code>@Entity
public class GeneralObservation {
@DateTimeFormat(pattern = "dd/MM/yyyy")
Date date;
@Column
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
</code></pre>
<p>also I have </p>
<pre><code>@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, false));
}
</code></pre>
<p>and </p>
<pre><code> form:input
id = "datepicker"
name="date"
itemLabel="date"
path="newObservation.date"
</code></pre>
<p>When I go to my url I see:</p>
<p><img src="https://i.stack.imgur.com/0NdXl.png" alt="my form"></p>
<p>How can I force it to have mm/DD/yyyy format? Thanx</p> | 18,686,172 | 4 | 6 | null | 2013-08-10 15:30:07.087 UTC | 9 | 2014-11-19 20:16:34.293 UTC | 2013-08-11 00:38:41.917 UTC | null | 1,941,151 | null | 517,073 | null | 1 | 20 | java|spring|spring-mvc|jpa|jstl | 91,216 | <p>The solution is to put<br>
<code><mvc:annotation-driven/></code>
to
mvc-dispatcher-servlet.xml
and also xmlns:mvc="http://www.springframework.org/schema/mvc"
to the begining of xml file.</p> |
18,014,834 | How to make line with rounded (smooth) corners with AndroidPlot | <p>I have a small problem with ploting my graph. On a picture below is what I have already done.</p>
<hr>
<p>The graph should represent the actual signal strength of available Wi-Fi network(s). It's a simple <code>XYPlot</code> here data are represented with <code>SimpleXYSeries</code> (values are dynamically created).</p>
<p>Here is a little snippet of code (only for example):</p>
<pre><code>plot = (XYPlot) findViewById(R.id.simplexyPlot);
series1 = new SimpleXYSeries(Arrays.asList(series1Numbers),
SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Link 1");
f1 = new LineAndPointFormatter(color.getColor(), null,
Color.argb(60, color.getRed(), color.getGreen(), color.getBlue()), null);
plot.addSeries(series1, f1);
</code></pre>
<p>The example in the picture is a dynamic simulation of dB changes. Everything works, I guess, correctly, but what I want to achieve is to have line with "rounded" corners (see the picture to see what I mean).</p>
<p>I already tried to customize LineFormatter:</p>
<pre><code>f1.getFillPaint().setStrokeJoin(Join.ROUND);
f1.getFillPaint().setStrokeWidth(8);
</code></pre>
<p>But this didn't work as expected.</p>
<p><img src="https://i.stack.imgur.com/VyH4R.png" alt="Enter image description here"></p>
<p>Note: The <a href="https://play.google.com/store/apps/details?id=com.farproc.wifi.analyzer" rel="noreferrer">Wifi Analyzer</a> application has a similar graph and its graph has the rounded corners I want. It looks like this:</p>
<p><img src="https://i.stack.imgur.com/jILfk.png" alt="Enter image description here"></p> | 18,353,513 | 6 | 3 | null | 2013-08-02 10:35:05.317 UTC | 8 | 2021-08-17 03:51:23.017 UTC | 2014-02-01 13:54:01.397 UTC | null | 63,550 | null | 1,331,415 | null | 1 | 11 | android|androidplot | 16,503 | <p>You can use <a href="http://developer.android.com/reference/android/graphics/Path.html#cubicTo%28float,%20float,%20float,%20float,%20float,%20float%29" rel="nofollow noreferrer">Path.cubicTo()</a> method. It draws a line using cubic spline algorithm which results in the smoothing effect you want.</p>
<p>Checkout the answer to a <a href="https://stackoverflow.com/questions/8287949/android-how-to-draw-a-smooth-line-following-your-finger">similar question here</a>, where a guy is talking about cubic splines. There is a short algorithm showing how to calculate input parameters for <code>Path.cubicTo()</code> method. You can play with divider values to achieve required smoothness. For example, in the picture below I divided by 5 instead of 3. Hope this helps. </p>
<p><img src="https://i.stack.imgur.com/JZ94U.png" alt="Example of a polylyne drawn using Path.cubicTo() method"></p>
<p>I have spent some time and implemented a <code>SplineLineAndPointFormatter</code> class, which does the stuff you need in androidplot library. It uses same technics. Here is how androidplot example applications looks like. You just need to use it instead of <code>LineAndPointFormatter</code>.</p>
<p><img src="https://i.stack.imgur.com/oNvG3.png" alt="Androidplot example with SplineLineAndPointFormatter"></p>
<p>Here is code example and the class I wrote.</p>
<pre><code>f1 = new SplineLineAndPointFormatter(color.getColor(), null,
Color.argb(60, color.getRed(), color.getGreen(), color.getBlue()), null);
plot.addSeries(series1, f1);
</code></pre>
<p>Here is the class doing the magic. It is based on version 0.6.1 of <a href="http://bitbucket.org/androidplot/androidplot" rel="nofollow noreferrer">androidplot</a> library.</p>
<pre><code>package com.androidplot.xy;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import com.androidplot.ui.SeriesRenderer;
import com.androidplot.util.ValPixConverter;
public class SplineLineAndPointFormatter extends LineAndPointFormatter {
public SplineLineAndPointFormatter() { }
public SplineLineAndPointFormatter(Integer lineColor, Integer vertexColor, Integer fillColor) {
super(lineColor, vertexColor, fillColor, null);
}
public SplineLineAndPointFormatter(Integer lineColor, Integer vertexColor, Integer fillColor, FillDirection fillDir) {
super(lineColor, vertexColor, fillColor, null, fillDir);
}
@Override
public Class<? extends SeriesRenderer> getRendererClass() {
return SplineLineAndPointRenderer.class;
}
@Override
public SeriesRenderer getRendererInstance(XYPlot plot) {
return new SplineLineAndPointRenderer(plot);
}
public static class SplineLineAndPointRenderer extends LineAndPointRenderer<BezierLineAndPointFormatter> {
static class Point {
public float x, y, dx, dy;
public Point(PointF pf) { x = pf.x; y = pf.y; }
}
private Point prev, point, next;
private int pointsCounter;
public SplineLineAndPointRenderer(XYPlot plot) {
super(plot);
}
@Override
protected void appendToPath(Path path, final PointF thisPoint, PointF lastPoint) {
pointsCounter--;
if (point == null) {
point = new Point(thisPoint);
point.dx = ((point.x - prev.x) / 5);
point.dy = ((point.y - prev.y) / 5);
return;
} else if (next == null) {
next = new Point(thisPoint);
} else {
prev = point;
point = next;
next = new Point(thisPoint);
}
point.dx = ((next.x - prev.x) / 5);
point.dy = ((next.y - prev.y) / 5);
path.cubicTo(prev.x + prev.dx, prev.y + prev.dy, point.x - point.dx, point.y - point.dy, point.x, point.y);
if (pointsCounter == 1) { // last point
next.dx = ((next.x - point.x) / 5);
next.dy = ((next.y - point.y) / 5);
path.cubicTo(point.x + point.dx, point.y + point.dy, next.x - next.dx, next.y - next.dy, next.x, next.y);
}
}
@Override
protected void drawSeries(Canvas canvas, RectF plotArea, XYSeries series, LineAndPointFormatter formatter) {
Number y = series.getY(0);
Number x = series.getX(0);
if (x == null || y == null) throw new IllegalArgumentException("no null values in xyseries permitted");
XYPlot p = getPlot();
PointF thisPoint = ValPixConverter.valToPix(x, y, plotArea,
p.getCalculatedMinX(), p.getCalculatedMaxX(), p.getCalculatedMinY(), p.getCalculatedMaxY());
prev = new Point(thisPoint);
point = next = null;
pointsCounter = series.size();
super.drawSeries(canvas, plotArea, series, formatter);
}
}
}
</code></pre> |
17,818,167 | Find a Pull Request on GitHub where a commit was originally created | <p>Pull Requests are great for understanding the larger thinking around a change or set of changes made to a repo. Reading pull requests are a great way to quickly "grok" a project as, instead of small atomic changes to the source, you get larger groupings of logical changes. Analogous to organizing the lines in your code into related "stanzas" to make it easier to read.</p>
<p>I find myself looking at a file or a commit, and I wonder if there is a way to backtrack the commit to the Pull Request that originally created it. That Pull Request would have been merged eventually, but not necessary with a merge-commit.</p> | 25,914,885 | 7 | 1 | null | 2013-07-23 18:28:19.717 UTC | 40 | 2022-05-12 10:43:40.283 UTC | 2021-01-09 03:20:20.31 UTC | null | 1,402,846 | null | 92,694 | null | 1 | 245 | git|github|pull-request | 80,270 | <p><strike>You can just go to GitHub and enter the SHA into the search bar, make sure you select the "Issues" link on the left.</strike></p>
<p><strong>UPDATED 13 July 2017</strong></p>
<p>Via the GitHub UI there is a now a really easy way to do this. If you are looking at a commit in the list of commits in a branch in the UI, click on the link to the commit itself. If there is a PR for that commit and it wasn't added directly to the branch, a link to the PR listing the PR number and the branch it went into will be directly under the commit message at the top of the page.
<a href="https://i.stack.imgur.com/AaTY4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AaTY4.png" alt="enter image description here" /></a></p>
<hr />
<p><a href="https://i.stack.imgur.com/UrVGx.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/UrVGx.gif" alt="Example of finding a PR by clicking on a link to the commit" /></a></p>
<p>If you have the commit SHA and nothing else and don't want to go digging around for it, just add <code>/commit/[commit SHA]</code> to the repo url, and you will see the commit page, with the PR link if it exists.
For example, if the SHA is 52797a7a3b087231e4e391e11ea861569205aaf4 and the repo is <a href="https://github.com/glimmerjs/glimmer-vm" rel="noreferrer">https://github.com/glimmerjs/glimmer-vm</a> , then go to <a href="https://github.com/glimmerjs/glimmer-vm/commit/52797a7a3b087231e4e391e11ea861569205aaf4" rel="noreferrer">https://github.com/glimmerjs/glimmer-vm/commit/52797a7a3b087231e4e391e11ea861569205aaf4</a></p> |
18,099,653 | Removing everything except numbers in a string | <p>I've made a small calculator in javascript where users enter the interest rate and amount the they want to borrow, and it calculates how much of an incentive they might get.</p>
<p>The problem is that I'm worried users will enter symbols, e.g. </p>
<blockquote>
<p>Loan amount: £360,000 - Interest Rate: 4.6%</p>
</blockquote>
<p>I'm not worried about the decimal places as these are needed and don't seem to affect the calculation, it's the symbols like £ and % which mess things up.</p>
<p>Is there a simple way to strip out these symbols from the code:</p>
<pre><code><td><input type="text" name="loan_amt" style="background-color:#FFF380;"></td>
<td><input type="text" name="interest_rate" style="background-color:#FFF380;"></td>
function Calculate()
{
var loan_amt = document.getElementById('loan_amt').value;
//this is how i get the loan amount entered
var interest_rate = document.getElementById('interest_rate').value;
//this is how i get the interest rate
alert (interest_rate);
}
</code></pre> | 18,099,759 | 7 | 4 | null | 2013-08-07 09:27:19.26 UTC | 3 | 2021-06-09 09:14:35.583 UTC | 2016-05-19 01:02:04.653 UTC | null | 5,818,631 | null | 2,660,049 | null | 1 | 55 | javascript|regex | 59,097 | <p>Note that you should use the correct DOM id to refer via getElementById.
You can use the <a href="http://www.w3schools.com/jsref/jsref_replace.asp" rel="noreferrer">.replace()</a> method for that:</p>
<pre><code>var loan_amt = document.getElementById('loan_amt');
loan_amt.value = loan_amt.value.replace(/[^0-9]/g, '');
</code></pre>
<p>But that will remove float point delimiter too. This is an answer to your question, but not a solution for your problem. To parse the user input as a number, you can use <a href="http://www.w3schools.com/jsref/jsref_parsefloat.asp" rel="noreferrer">parseFloat()</a> - I think that it will be more appropriate.</p> |
6,828,124 | How to find user control of an ASP.NET page inside of event of another user control on that ASP.NET page EDIT: different content placeholders? | <p>I have a ASP.NET page with 2 user controls registered. The first one has only one button in it. The second one is simple text and hidden on default. What I want is to make the second one visible when the button in the first one is clicked (that is on button click event). </p>
<p>ASP.NET page:</p>
<pre><code><%@ Page Title="" Language="C#" CodeFile="test.aspx.cs" Inherits="test" %>
<%@ Register Src="~/UC_button.ascx" TagName="button" TagPrefix="UC" %>
<%@ Register Src="~/UC_text.ascx" TagName="text" TagPrefix="UC" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MyTestContent" Runat="Server">
<UC:button ID="showbutton1" runat="server" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MyTestContent2" Runat="Server">
<UC:text runat="server" Visible="false" ID="text1" />
</asp:Content>
</code></pre>
<p>UC_Button.ascx.cs:</p>
<pre><code>protected void button1_Click(object sender, EventArgs e)
{
Button btnSender = (Button)sender;
Page parentPage = btnSender.Page;
UserControl UC_text = (UserControl)parentPage.FindControl("text1");
UC_text.Visible = true;
}
</code></pre>
<p>What am I doing wrong? I get well known <code>Object reference not set to an instance of an object.</code> error on that last line of the code.</p>
<p><strong>EDIT:</strong></p>
<p>One thing I forgot to mention when first posting this. User controls are in different <code><asp:Content></asp:Content></code> controls (I edited upper example). If I put them in the same placeholder code works just fine. If I put them in the separate content placeholders I can't find them in any way with findcontrol. Why is that and how can I find them?</p> | 6,844,214 | 4 | 0 | null | 2011-07-26 09:42:44.207 UTC | null | 2017-03-21 03:59:02.533 UTC | 2011-07-27 09:51:02.81 UTC | null | 672,630 | null | 672,630 | null | 1 | 3 | asp.net|user-controls|findcontrol|contentplaceholder | 42,381 | <p>Ok I found solution until better one comes my way. The problem is, as Jamie Dixon pointed out (thank you Jamie):</p>
<p><em><code>The FindControl method does not do a deep search for controls. It looks directly in the location you specify for the control you're requesting.</code></em></p>
<p>So because I have user controls in different contentplaceholders I must first find targeted placeholder (where the user control reside) and then I can search for user control inside it:</p>
<pre><code>protected void Dodaj_Feed_Panel_Click(object sender, EventArgs e)
{
ContentPlaceHolder MySecondContent = (ContentPlaceHolder)this.Parent.Parent.FindControl("MyTestContent2");
UserControl UC_text = (UserControl)MySecondContent.FindControl("text1");
UC_text.Visible = true;
}
</code></pre>
<p>what really annoys and confuses me is the <code>this.Parent.Parent</code> part because I know it's not the best solution (in case I change the hierarchy a bit this code will break). What this part of code actually does is that it goes two levels up in page hierarchy (that is page where both user controls are). I don't know what the difference with <code>this.Page</code> is because for me it means the same but is not working for me. </p>
<p>Long term solution would be something like server side "jQuery-like selectors" (it can found elements no matter where they are in hierarchy). Anyone has a better solution?</p> |
57,030,018 | React context with hooks prevent re render | <p>I use React context with hooks as a state manager for my React app. Every time the value changes in the store, all the components re-render. </p>
<p>Is there any way to prevent React component to re-render?</p>
<p>Store config:</p>
<pre><code>import React, { useReducer } from "react";
import rootReducer from "./reducers/rootReducer";
export const ApiContext = React.createContext();
export const Provider = ({ children }) => {
const [state, dispatch] = useReducer(rootReducer, {});
return (
<ApiContext.Provider value={{ ...state, dispatch }}>
{children}
</ApiContext.Provider>
);
};
</code></pre>
<p>An example of a reducer:</p>
<pre><code>import * as types from "./../actionTypes";
const initialState = {
fetchedBooks: null
};
const bookReducer = (state = initialState, action) => {
switch (action.type) {
case types.GET_BOOKS:
return { ...state, fetchedBooks: action.payload };
default:
return state;
}
};
export default bookReducer;
</code></pre>
<p>Root reducer, that can combine as many reducers, as possible:</p>
<pre><code>import userReducer from "./userReducer";
import bookReducer from "./bookReducer";
const rootReducer = ({ users, books }, action) => ({
users: userReducer(users, action),
books: bookReducer(books, action)
});
</code></pre>
<p>An example of an action:</p>
<pre><code>import * as types from "../actionTypes";
export const getBooks = async dispatch => {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1", {
method: "GET"
});
const payload = await response.json();
dispatch({
type: types.GET_BOOKS,
payload
});
};
export default rootReducer;
</code></pre>
<p>And here's the book component:</p>
<pre><code>import React, { useContext, useEffect } from "react";
import { ApiContext } from "../../store/StoreProvider";
import { getBooks } from "../../store/actions/bookActions";
const Books = () => {
const { dispatch, books } = useContext(ApiContext);
const contextValue = useContext(ApiContext);
useEffect(() => {
setTimeout(() => {
getBooks(dispatch);
}, 1000);
}, [dispatch]);
console.log(contextValue);
return (
<ApiContext.Consumer>
{value =>
value.books ? (
<div>
{value.books &&
value.books.fetchedBooks &&
value.books.fetchedBooks.title}
</div>
) : (
<div>Loading...</div>
)
}
</ApiContext.Consumer>
);
};
export default Books;
</code></pre>
<p>When the value changes in Books component, another my component Users re-renders:</p>
<pre><code>import React, { useContext, useEffect } from "react";
import { ApiContext } from "../../store/StoreProvider";
import { getUsers } from "../../store/actions/userActions";
const Users = () => {
const { dispatch, users } = useContext(ApiContext);
const contextValue = useContext(ApiContext);
useEffect(() => {
getUsers(true, dispatch);
}, [dispatch]);
console.log(contextValue, "Value from store");
return <div>Users</div>;
};
export default Users;
</code></pre>
<p>What's the best way to optimize context re-renders? Thanks in advance!</p> | 57,031,877 | 4 | 3 | null | 2019-07-14 18:20:54.643 UTC | 10 | 2020-04-14 15:09:57.177 UTC | 2019-07-14 23:57:56.693 UTC | null | 9,886,585 | null | 9,886,585 | null | 1 | 19 | javascript|reactjs|react-native|react-context | 23,273 | <p>I believe what is happening here is expected behavior. The reason it renders twice is because you are automatically grabbing a new book/user when you visit the book or user page respectively.</p>
<p>This happens because the page loads, then <code>useEffect</code> kicks off and grabs a book or user, then the page needs to re-render in order to put the newly grabbed book or user into the DOM.</p>
<p>I have modified your CodePen in order to show that this is the case.. If you disable 'autoload' on the book or user page (I added a button for this), then browse off that page, then browse back to that page, you will see it only renders once.</p>
<p>I have also added a button which allows you to grab a new book or user on demand... this is to show how only the page which you are on gets re-rendered.</p>
<p>All in all, this is expected behavior, to my knowledge.</p>
<p><a href="https://codesandbox.io/s/react-state-manager-hooks-context-lj5er?fontsize=14" rel="nofollow noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit react-state-manager-hooks-context"></a></p> |
39,990,017 | Should I commit the yarn.lock file and what is it for? | <p>Yarn creates a <code>yarn.lock</code> file after you perform a <code>yarn install</code>. </p>
<p>Should this be committed to the repository or ignored? What is it for?</p> | 39,992,365 | 9 | 4 | null | 2016-10-12 03:24:53.737 UTC | 60 | 2022-03-21 10:33:22.487 UTC | 2016-11-23 18:13:55.17 UTC | null | 6,650,102 | null | 1,403,314 | null | 1 | 498 | yarnpkg | 185,323 | <p>Yes, you should check it in, see <a href="https://yarnpkg.com/en/docs/migrating-from-npm" rel="noreferrer">Migrating from npm</a></p>
<p><strong>What is it for?</strong><br>
The npm client installs dependencies into the <code>node_modules</code> directory non-deterministically. This means that based on the order dependencies are installed, the structure of a node_modules directory could be different from one person to another. These differences can cause <em><strong>works on my machine</strong></em> bugs that take a long time to hunt down.</p>
<p>Yarn resolves these issues around versioning and non-determinism by using lock files and an install algorithm that is deterministic and reliable. These lock files lock the installed dependencies to a specific version and ensure that every install results in the exact same file structure in <code>node_modules</code> across all machines.</p> |
27,480,134 | Inserting Date() in to Mongodb through mongo shell | <p>I am inserting document through following query: </p>
<pre><code>db.collection.insert(
{
date: Date('Dec 12, 2014 14:12:00')
})
</code></pre>
<p>But it will give me an error. </p>
<p>How can I insert a date in my collection without getting an error?</p> | 27,480,559 | 2 | 2 | null | 2014-12-15 08:40:10.683 UTC | 4 | 2018-05-21 07:57:46.487 UTC | 2018-05-21 07:57:46.487 UTC | null | 4,015,870 | null | 3,528,347 | null | 1 | 16 | javascript|mongodb|mongodb-query | 39,611 | <p>You must be getting a different error as the code above will result in the <code>Date()</code> method returning the current date as a string, regardless of the arguments supplied with the object. From the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" rel="noreferrer">documentation</a>: <em>JavaScript Date objects can only be instantiated by calling JavaScript <code>Date</code> as a constructor: calling it as a regular function (i.e. without the <code>new</code> operator) will return a string rather than a <code>Date</code> object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.</em> </p>
<p>You might want to try this instead to get the correct date, bearing in mind that the month parameter of JavaScript's Date constructor is 0-based:</p>
<pre><code>var myDate = new Date(2014, 11, 12, 14, 12);
db.collection.insert({ "date": myDate });
</code></pre> |
27,613,310 | Rounding selected columns of data.table | <p>I have following data and code to round selected columns of this data.table:</p>
<pre><code>mydf = structure(list(vnum1 = c(0.590165705411504, -1.39939534199836,
0.720226053660755, -0.253198380120377, -0.783366825121657), vnum2 = c(0.706508400384337,
0.526770398486406, 0.863136084517464, 0.838245498016477, 0.556775856064633
), vch1 = structure(c(2L, 4L, 1L, 3L, 3L), .Label = c("A", "B",
"C", "E"), class = "factor")), .Names = c("vnum1", "vnum2", "vch1"
), row.names = c(NA, -5L), class = c("data.table", "data.frame"
))
</code></pre>
<pre><code>mydf[,round(.SD,1),]
</code></pre>
<blockquote>
<p>Error in Math.data.frame(list(vnum1 = c(0.590165705411504,
-1.39939534199836, : non-numeric variable in data frame: vch1</p>
</blockquote>
<pre><code>cbind(mydf[,3,with=F], mydf[,1:2,with=F][,round(.SD,1),])
</code></pre>
<pre><code> vch1 vnum1 vnum2
1: B 0.6 0.7
2: E -1.4 0.5
3: A 0.7 0.9
4: C -0.3 0.8
5: C -0.8 0.6
</code></pre>
<p>Is there a method with shorter code?</p> | 27,613,444 | 9 | 4 | null | 2014-12-23 02:35:26.207 UTC | 14 | 2022-09-19 08:43:33.493 UTC | 2022-09-19 08:43:33.493 UTC | null | 5,784,757 | null | 3,522,130 | null | 1 | 47 | r|data.table | 92,741 | <p>If you don't mind overwriting your original <code>mydf</code>:</p>
<pre><code>cols <- names(mydf)[1:2]
mydf[,(cols) := round(.SD,1), .SDcols=cols]
mydf
# vnum1 vnum2 vch1
#1: 0.6 0.7 B
#2: -1.4 0.5 E
#3: 0.7 0.9 A
#4: -0.3 0.8 C
#5: -0.8 0.6 C
</code></pre> |
723,791 | What are best practices for self-updating PHP+MySQL applications? | <p>It is pretty standard practice now for desktop applications to be self-updating. On the Mac, every non-Apple program that uses <a href="http://sparkle.andymatuschak.org/" rel="noreferrer">Sparkle</a> in my book is an instant win. For Windows developers, <a href="https://stackoverflow.com/questions/232347/how-should-i-implement-an-auto-updater">this has already been discussed at length</a>. I have not yet found information on self-updating web applications, and I hope you can help.</p>
<p>I am building a web application that is meant to be installed like Wordpress or Drupal - unzip it in a directory, hit some install page, and it's ready to go. In order to have broad server compatibility, I've been asked to use PHP and MySQL -- is that **MP? In any event, it has to be broadly cross-platform. For context, this is basically a unified web messaging application for small businesses. It's not another CMS platform, think webmail.</p>
<p>I want to know about self-updating web applications. First of all, (1) is this a bad idea? As of Wordpress 2.7 the automatic update is a single button, which seems easy, and yet I can imagine so many ways this could go terribly, terribly wrong. Also, isn't the idea that the web files are writable by the web process a security hole?</p>
<p>(2) Is it worth the development time? There are probably millions of WP installs in the world, so it's probably worth the time it took the WP team to make it easy, saving millions of man hours worldwide. I can only imagine a few thousand installs of my software -- is building self-upgrade worth the time investment, or can I assume that users sophisticated enough to download and install web software in the first place could go through an upgrade checklist?</p>
<p>If it's not a security disaster or waste of time, then (3) I'm looking for suggestions from anyone who has done it before. Do you keep a version table in your database? How do you manage DB upgrades? What method do you use for rolling back a partial upgrade in the context of a self-updating web application? Did using an ORM layer make it easier or harder? Do you keep a delta of version changes or do you just blow out the whole thing every time?</p>
<p>I appreciate your thoughts on this.</p> | 723,855 | 7 | 2 | null | 2009-04-07 00:58:47.343 UTC | 12 | 2012-05-23 10:26:00.7 UTC | 2017-05-23 12:25:51.337 UTC | null | -1 | null | 53,182 | null | 1 | 29 | php|mysql|security|upgrade | 8,144 | <p>Frankly, it really does depend on your userbase. There are tons of PHP applications that don't automatically upgrade themselves. Their users are either technical enough to handle the upgrade process, or just don't upgrade.</p>
<p>I purpose two steps:</p>
<p>1) Seriously ask yourself what your users are likely to really need. Will self-updating provide enough of a boost to adoption to justify the additional work? If you're confident the answer is yes, just do it.</p>
<p>Since you're asking here, I'd guess that you don't know yet. In that case, I purpose step 2:</p>
<p>2) Release version 1.0 without the feature. Wait for user feedback. Your users may immediately cry for a simpler upgrade process, in which case you should prioritize it. Alternately, you may find that your users are much more concerned with some other feature.</p>
<p>Guessing at what your users want without asking them is a good way to waste a lot of development time on things people don't actually need.</p> |
544,450 | Detecting honest web crawlers | <p>I would like to detect (on the server side) which requests are from bots. I don't care about malicious bots at this point, just the ones that are playing nice. I've seen a few approaches that mostly involve matching the user agent string against keywords like 'bot'. But that seems awkward, incomplete, and unmaintainable. So does anyone have any more solid approaches? If not, do you have any resources you use to keep up to date with all the friendly user agents?</p>
<p>If you're curious: I'm not trying to do anything against any search engine policy. We have a section of the site where a user is randomly presented with one of several slightly different versions of a page. However if a web crawler is detected, we'd always give them the same version so that the index is consistent.</p>
<p>Also I'm using Java, but I would imagine the approach would be similar for any server-side technology.</p> | 544,485 | 7 | 0 | null | 2009-02-13 01:55:33.483 UTC | 43 | 2022-08-08 15:08:28.853 UTC | 2013-01-26 11:03:21.617 UTC | null | 569,101 | CynicalTyler | 9,304 | null | 1 | 44 | c#|web-crawler|bots | 20,022 | <p>You can find a very thorough database of data on known "good" web crawlers in the robotstxt.org <a href="http://www.robotstxt.org/db.html" rel="noreferrer">Robots Database</a>. Utilizing this data would be far more effective than just matching <em>bot</em> in the user-agent.</p> |
115,850 | What pre-existing services exist for calculating distance between two addresses? | <p>I'd like to implement a way to display a list of stored addresses sorted by proximity to a given address.</p>
<p>Addresses in the list will be stored in a database table. Separate parts have separate fields (we have fields for postal code, city name, etc.) so it is not just a giant <code>varchar</code>. These are user-entered and due to the nature of the system may not always be complete (some may be missing postal code and others may have little more than city and state).</p>
<p>Though this is for an intranet application I have no problems using outside resources including accessing internet web services and such. I'd actually prefer that over rolling my own unless it would be trivial to do myself. If Google or Yahoo! already provides a free service, I'm more than willing to check it out. The keyword is it must be free, as I'm not at liberty to introduce any additional cost onto this project for this feature as it is already a bonus "perk" so to speak.</p>
<p>I'm thinking of this much like many brick & mortar shops do their "Find a Location" feature. Showing it in a simple table sorted appropriately and displaying distance (in, say, miles) is great. Showing a map mash-up is even cooler, but I can definitely live with just getting the distance back and me handling all of the subsequent display and sorting.</p>
<p>The problem with simple distance algorithms is the nature of the data. Since all or part of the address can be undefined, I don't have anything convenient like lat/long coords. Also, even if I make postal codes required, 90% of the addresses will probably have the same five postal codes.</p>
<p>While it need not be blisteringly fast, anything that takes more than seven seconds to show up on the page due to latency might be too long for the average user to wait, as we know. If such a hypothetical service supports sending a batch of addresses at once instead of querying one at a time, that'd be great. Still, I should not think the list of addresses would exceed 50 total, if that many.</p> | 115,902 | 8 | 0 | null | 2008-09-22 16:19:54.363 UTC | 10 | 2009-06-08 20:58:11.983 UTC | 2009-06-08 20:58:11.983 UTC | Yadyn | 7,290 | Yadyn | 7,290 | null | 1 | 12 | algorithm|geolocation|distance | 10,375 | <p><a href="http://code.google.com/apis/maps/documentation/services.html#Geocoding" rel="noreferrer">Google</a> and <a href="http://developer.yahoo.com/maps/rest/V1/geocode.html" rel="noreferrer">Yahoo!</a> both provide geocoding services for free. You can calculate distance using the <a href="http://en.wikipedia.org/wiki/Haversine_formula" rel="noreferrer">Haversine formula</a> (<a href="http://www.codeproject.com/KB/cs/distancebetweenlocations.aspx" rel="noreferrer">implemented in .NET or SQL</a>). Both services will let you do partial searches (zip code only, city only) and will let you know what the precision of their results are (so that you can exclude locations without meaningful information, though Yahoo! provides more precision info than Google).</p> |
718,479 | What is the best way to produce a tilde in LaTeX for a website? | <p>Following the <a href="https://stackoverflow.com/questions/682201/latex-tildes-and-verbatim-mode">previous questions</a> on this topic, when you produce a website in LaTeX what is the best way to produce a url that contains a tilde? <code>\verb</code> produces the upper tilde that does not read well, and <code>$\sim$</code> does not copy/pase well (adding a space when I do it). Solutions?</p>
<p>It seems like this should be one of those things that has a very easy fix... if it doesn't, why not?</p> | 718,484 | 9 | 1 | null | 2009-04-05 06:43:54.847 UTC | 2 | 2021-06-05 17:10:01.23 UTC | 2017-05-23 12:34:24.807 UTC | null | -1 | vgm64 | 51,532 | null | 1 | 14 | latex|tilde | 39,267 | <p>I'd look at the <a href="http://www.ctan.org/tex-archive/help/Catalogue/entries/url.html" rel="noreferrer"><code>url</code> package</a>.</p> |
230,407 | What is the unix command to see how much disk space there is and how much is remaining? | <p>I'm looking for the equivalent of right clicking on the drive in windows and seeing the disk space used and remaining info.</p> | 230,412 | 10 | 0 | null | 2008-10-23 16:26:24.32 UTC | 5 | 2018-12-24 09:16:22.657 UTC | 2008-10-23 17:08:25.187 UTC | Alex B | 6,180 | Brian | 700 | null | 1 | 22 | unix|aix|diskspace | 141,534 | <p>Look for the commands <code>du</code> (disk usage) and <code>df</code> (disk free)</p> |
177,514 | Good XMPP Java Libraries for server side? | <p>I was hoping to implement a simple XMPP server in Java. </p>
<p>What I need is a library which can parse and understand xmpp requests from a client. I have looked at Smack (mentioned below) and JSO. Smack appears to be client only so while it might help parsing packets it doesn't know how to respond to clients. Is JSO maintained it looks very old. The only promising avenue is to pull apart Openfire which is an entire commercial (OSS) XMPP server.</p>
<p>I was just hoping for a few lines of code on top of Netty or Mina, so I could get started processing some messages off the wire.</p>
<hr>
<p>Joe - </p>
<p>Well the answer to what I am trying to do is somewhat long - I'll try to keep it short. </p>
<p>There are two things, that are only loosely related:</p>
<p>1) I wanted to write an XMPP server because I imagine writing a custom protocol for two clients to communicate. Basically I am thinking of a networked iPhone app - but I didn't want to rely on low-level binary protocols because using something like XMPP means the app can "grow up" very quickly from a local wifi based app to an internet based one...</p>
<p>The msgs exchanged should be relatively low latency, so strictly speaking a binary protocol would be best, but I felt that it might be worth exploring if XMPP didn't introduce too much overhead such that I could use it and then reap benefits of it's extensability and flexability later.</p>
<p>2) I work for Terracotta - so I have this crazy bent to cluster everything. As soon as I started thinking about writing some custom server code, I figured I wanted to cluster it. Terracotta makes scaling out Java POJOs trivial, so my thought was to build a super simple XMPP server as a demonstration app for Terracotta. Basically each user would connect to the server over a TCP connection, which would register the user into a hashmap. Each user would have a LinkedBlockingQueue with a listener thread taking message from the queue. Then any connected user that wants to send a message to any other user (e.g. any old chat application) simply issues an XMPP message (as usual) to that user over the connection. The server picks it up, looks up the corresponding user object in a map and places the message onto the queue. Since the queue is clustered, regardless of wether the destination user is connected to the same physical server, or a different physical server, the message is delivered and the thread that is listening picks it up and sends it back down the destination user's tcp connection.</p>
<p>So - not too short of a summary I'm afraid. But that's what I want to do. I suppose I could just write a plugin for Openfire to accomplish #1 but I think it takes care of a lot of plumbing so it's harder to do #2 (especially since I was hoping for a very small amount of code that could fit into a simple 10-20kb Maven project).</p> | 177,581 | 10 | 4 | null | 2008-10-07 07:43:22.01 UTC | 38 | 2015-12-02 13:39:01.14 UTC | 2012-05-04 12:49:09.217 UTC | Taylor Gautier | 1,288 | Taylor Gautier | 19,013 | null | 1 | 63 | java|xmpp | 49,916 | <p><a href="http://xmpp.org/xmpp-software/libraries/" rel="noreferrer">http://xmpp.org/xmpp-software/libraries/</a> has a list of software libraries for XMPP. Here is an <em>outdated</em> snapshot of it:</p>
<p><h3>ActionScript</h3> </p>
<ul>
<li><a href="http://code.google.com/p/as3xmpp/" rel="noreferrer">as3xmpp</a></li>
</ul>
<p><h3>C</h3> </p>
<ul>
<li><a href="http://code.google.com/p/iksemel/" rel="noreferrer">iksemel</a></li>
<li><a href="http://www.onlinegamegroup.com/projects/libstrophe" rel="noreferrer">libstrophe</a></li>
<li><a href="http://www.loudmouth-project.org/" rel="noreferrer">Loudmouth</a></li>
</ul>
<p><h3>C++</h3> </p>
<ul>
<li><a href="http://camaya.net/gloox" rel="noreferrer">gloox</a></li>
<li><a href="http://delta.affinix.com/iris/" rel="noreferrer">Iris</a></li>
<li><a href="http://www.openaether.org/oajabber.html" rel="noreferrer">oajabber</a></li>
</ul>
<p><h3>C# / .NET / Mono</h3> </p>
<ul>
<li><a href="http://www.ag-software.de/index.php?page=agsxmpp-sdk" rel="noreferrer">agsXMPP SDK</a></li>
<li><a href="http://code.google.com/p/jabber-net/" rel="noreferrer">jabber-net</a></li>
</ul>
<p><h3>Erlang</h3> </p>
<ul>
<li><a href="http://support.process-one.net/doc/display/CONTRIBS/Jabberlang" rel="noreferrer">Jabberlang</a></li>
</ul>
<p><h3>Flash</h3> </p>
<ul>
<li><a href="http://www.igniterealtime.org/projects/xiff/" rel="noreferrer">XIFF</a></li>
</ul>
<p><h3>Haskell</h3> </p>
<ul>
<li><a href="http://www.dtek.chalmers.se/~henoch/text/hsxmpp.html" rel="noreferrer">hsxmpp</a></li>
</ul>
<p><h3>Java</h3> </p>
<ul>
<li><a href="http://freecode.com/projects/feridian" rel="noreferrer">Echomine Feridian</a></li>
<li><a href="http://java.net/projects/jso/" rel="noreferrer">Jabber Stream Objects (JSO)</a></li>
<li><a href="http://www.igniterealtime.org/projects/smack/index.jsp" rel="noreferrer">Smack</a></li>
</ul>
<p><h3>JavaScript</h3> </p>
<ul>
<li><a href="http://strophe.im/strophejs/" rel="noreferrer">strophe.js</a></li>
<li><a href="http://xmpp4js.sourceforge.net/" rel="noreferrer">xmpp4js</a></li>
</ul>
<p><h3>Lisp</h3> </p>
<ul>
<li><a href="http://common-lisp.net/project/cl-xmpp/" rel="noreferrer">cl-xmpp</a>
</li>
</ul>
<p><h3>Objective-C</h3> </p>
<ul>
<li><a href="http://code.google.com/p/xmppframework/" rel="noreferrer">xmppframework</a></li>
</ul>
<p><h3>Perl</h3> </p>
<ul>
<li><a href="http://www.ta-sa.org/projects/net_xmpp2.html" rel="noreferrer">AnyEvent::XMPP</a></li>
</ul>
<p><h3>PHP</h3> </p>
<ul>
<li><a href="https://area51.myyearbook.com/trac.cgi/wiki/Lightr" rel="noreferrer">Lightr</a></li>
<li><a href="http://code.google.com/p/xmpphp/" rel="noreferrer">xmpphp</a></li>
</ul>
<p><h3>Python</h3> </p>
<ul>
<li><a href="http://jabberpy.sourceforge.net/" rel="noreferrer">jabber.py</a></li>
<li><a href="http://pyxmpp.jajcus.net/" rel="noreferrer">pyxmpp</a></li>
<li><a href="http://code.google.com/p/sleekxmpp/" rel="noreferrer">SleekXMPP</a></li>
<li><a href="http://twistedmatrix.com/trac/" rel="noreferrer">Twisted Words</a></li>
<li><a href="http://code.google.com/p/xmpp-psn/" rel="noreferrer">xmpp-psn</a></li>
<li><a href="http://xmpppy.sourceforge.net/" rel="noreferrer">xmpppy</a></li>
</ul>
<p><h3>Ruby</h3> </p>
<ul>
<li><a href="http://xmpp4r.github.io/" rel="noreferrer">XMPP4R</a></li>
</ul>
<p><h3>Tcl</h3> </p>
<ul>
<li><a href="http://coccinella.im/jabberlib" rel="noreferrer">JabberLib</a></li>
</ul> |
1,147,706 | how to hide status bar when splash screen appears in iphone? | <p>Is there a way to hide the status bar when showing splash screen in iPhone
and then show again in application?</p> | 1,147,732 | 10 | 0 | null | 2009-07-18 14:40:28.267 UTC | 28 | 2021-10-13 06:58:01.297 UTC | 2021-10-13 06:58:01.297 UTC | null | 16,439,658 | null | 83,905 | null | 1 | 85 | objective-c|iphone|xcode|splash-screen|statusbar | 49,676 | <p>I'm pretty sure that if your Info.plist file has the <code>Status bar is initially hidden</code> value set to <code>YES</code>, then it won't show while your application is loading. Once your application has loaded, you can re-show the status bar using UIApplication's <code>setStatusBarHidden:animated:</code> method.</p> |
970,198 | How to mock the Request on Controller in ASP.Net MVC? | <p>I have a controller in C# using the ASP.Net MVC framework</p>
<pre><code>public class HomeController:Controller{
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
//do some ajaxy stuff
}
return View("Index");
}
}
</code></pre>
<p>I got some tips on mocking and was hoping to test the code with the following and RhinoMocks</p>
<pre><code>var mocks = new MockRepository();
var mockedhttpContext = mocks.DynamicMock<HttpContextBase>();
var mockedHttpRequest = mocks.DynamicMock<HttpRequestBase>();
SetupResult.For(mockedhttpContext.Request).Return(mockedHttpRequest);
var controller = new HomeController();
controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
var result = controller.Index() as ViewResult;
Assert.AreEqual("About", result.ViewName);
</code></pre>
<p>However I keep getting this error:</p>
<blockquote>
<p>Exception
System.ArgumentNullException:
System.ArgumentNullException : Value
cannot be null. Parameter name:
request at
System.Web.Mvc.AjaxRequestExtensions.IsAjaxRequest(HttpRequestBase
request)</p>
</blockquote>
<p>Since the <code>Request</code> object on the controller has no setter. I tried to get this test working properly by using recommended code from an answer below.</p>
<p>This used Moq instead of RhinoMocks, and in using Moq I use the following for the same test:</p>
<pre><code>var request = new Mock<HttpRequestBase>();
// Not working - IsAjaxRequest() is static extension method and cannot be mocked
// request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */);
// use this
request.SetupGet(x => x.Headers["X-Requested-With"]).Returns("XMLHttpRequest");
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);
var controller = new HomeController(Repository, LoginInfoProvider);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
var result = controller.Index() as ViewResult;
Assert.AreEqual("About", result.ViewName);
</code></pre>
<p>but get the following error:</p>
<blockquote>
<p>Exception System.ArgumentException:
System.ArgumentException : Invalid
setup on a non-overridable member: x
=> x.Headers["X-Requested-With"] at Moq.Mock.ThrowIfCantOverride(Expression
setup, MethodInfo methodInfo)</p>
</blockquote>
<p>Again, it seems like I cannot set the request header.
How do I set this value, in RhinoMocks or Moq?</p> | 970,272 | 10 | 3 | null | 2009-06-09 13:51:01.17 UTC | 48 | 2021-05-16 11:26:34.047 UTC | 2009-06-09 18:09:35.98 UTC | null | 85,231 | null | 85,231 | null | 1 | 184 | asp.net-mvc|unit-testing|mocking|rhino-mocks|moq | 96,226 | <p>Using <a href="https://github.com/Moq/moq4" rel="noreferrer">Moq</a>:</p>
<pre><code>var request = new Mock<HttpRequestBase>();
// Not working - IsAjaxRequest() is static extension method and cannot be mocked
// request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */);
// use this
request.SetupGet(x => x.Headers).Returns(
new System.Net.WebHeaderCollection {
{"X-Requested-With", "XMLHttpRequest"}
});
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);
var controller = new YourController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
</code></pre>
<p><strong>UPDATED:</strong></p>
<p>Mock <code>Request.Headers["X-Requested-With"]</code> or <code>Request["X-Requested-With"]</code> instead of <code>Request.IsAjaxRequest()</code>.</p> |
469,798 | Konami Code in C# | <p>I am looking to have a C# application implement the Konami Code to display an Easter Egg.
<a href="http://en.wikipedia.org/wiki/Konami_Code" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Konami_Code</a></p>
<p>What is the best way to do this?</p>
<p>This is in a standard C# windows forms app.</p> | 469,970 | 11 | 2 | null | 2009-01-22 16:17:17.74 UTC | 16 | 2016-11-26 01:33:29.083 UTC | 2015-06-12 12:42:22.257 UTC | Sam Meldrum | 1,015,495 | Anthony D | 52,622 | null | 1 | 24 | c#|.net|winforms | 9,531 | <p>In windows forms I would have a class that knows what the sequence is and holds the state of where you are in the sequence. Something like this should do it.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication3 {
public class KonamiSequence {
List<Keys> Keys = new List<Keys>{System.Windows.Forms.Keys.Up, System.Windows.Forms.Keys.Up,
System.Windows.Forms.Keys.Down, System.Windows.Forms.Keys.Down,
System.Windows.Forms.Keys.Left, System.Windows.Forms.Keys.Right,
System.Windows.Forms.Keys.Left, System.Windows.Forms.Keys.Right,
System.Windows.Forms.Keys.B, System.Windows.Forms.Keys.A};
private int mPosition = -1;
public int Position {
get { return mPosition; }
private set { mPosition = value; }
}
public bool IsCompletedBy(Keys key) {
if (Keys[Position + 1] == key) {
// move to next
Position++;
}
else if (Position == 1 && key == System.Windows.Forms.Keys.Up) {
// stay where we are
}
else if (Keys[0] == key) {
// restart at 1st
Position = 0;
}
else {
// no match in sequence
Position = -1;
}
if (Position == Keys.Count - 1) {
Position = -1;
return true;
}
return false;
}
}
}
</code></pre>
<p>To use it, you would need something in your Form's code responding to key up events. Something like this should do it:</p>
<pre><code> private KonamiSequence sequence = new KonamiSequence();
private void Form1_KeyUp(object sender, KeyEventArgs e) {
if (sequence.IsCompletedBy(e.KeyCode)) {
MessageBox.Show("KONAMI!!!");
}
}
</code></pre>
<p>Hopefully that's enough to give you what you need. For WPF you will need slight differences is very similar (see edit history #1).</p>
<p>EDIT: updated for winforms instead of wpf.</p> |
1,030,782 | The benefits and advantages of being a jack of all trades programmer? | <p>I've been doing web dev for 10 years now, mostly the MS stack but some LAMP as well. There are so many choices these days for programmers and the job market seems to be all over the place. </p>
<p>Before I dive into some new technology once again I was hoping to get some perspective from others in regards to additional benefits of being a jack of all trades developer other than having a broad marketable skill set? Chime in with your experience please.</p> | 1,032,507 | 12 | 4 | 2009-06-23 05:42:45.44 UTC | 2009-06-23 05:42:45.44 UTC | 11 | 2017-10-20 09:00:09.917 UTC | 2009-06-23 05:44:39.057 UTC | null | 61,027 | null | 110,897 | null | 1 | 10 | language-agnostic | 5,330 | <p>Here are some thoughts on the benefits of having diverse experience in the field of programming:</p>
<ul>
<li><strong>Each language and technology offers an opportunity to learn a different approach to problem solving.</strong> Having different problem solving techniques in your toolset is an invaluable way to stay relevant in a constantly changing field.</li>
<li><strong>Learning a new technology or language helps keep your mind sharp</strong> - it forces you to organize different yet similar domains of knowledge in your mind and helps keep your brain active.</li>
<li><strong>A diverse background is more appealing to employers</strong> because it implies that you are a motivated individual who pursues excellence in his or her field. If your background only demonstrates experience with one narrow technology, it can imply that you only like to work in your comfort zone, or worse, are inflexible in learning new skills.</li>
<li><strong>Different languages and technologies fit different problems differently.</strong> <em>'If all you have is a hammer everything looks like a nail'</em>, is the old adage. Knowing multiple technologies allows you to select the best one for the problem at hand.</li>
<li><strong>It broadens the group of people you can interact with and communicate with in your field</strong> - <em>'speaking the language'</em>, to steal a phrase, makes it easier for you to work with individuals who specialize in other technologies. For instance, a good understanding of SQL and database architecture makes it easier to interact with and understand the concerns of DBAs.</li>
<li><strong>It's fun</strong>. Personally, I find learning new concepts in my field a fun way to improve myself as a person. I like to learn.</li>
</ul> |
34,249 | Best algorithm to test if a linked list has a cycle | <p>What's the best (halting) algorithm for determining if a linked list has a cycle in it?</p>
<p>[Edit] Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better.</p>
<p>[Edit] Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph".</p> | 34,255 | 12 | 2 | null | 2008-08-29 09:30:05.51 UTC | 22 | 2022-03-25 10:18:55.68 UTC | 2011-10-18 17:18:38.86 UTC | cdleary | 976,554 | cdleary | 3,594 | null | 1 | 32 | algorithm|data-structures|linked-list | 20,671 | <p>Have two pointers iterating through the list; make one iterate through at twice the speed of the other, and compare their positions at each step. Off the top of my head, something like:</p>
<pre><code>node* tortoise(begin), * hare(begin);
while(hare = hare->next)
{
if(hare == tortoise) { throw std::logic_error("There's a cycle"); }
hare = hare->next;
if(hare == tortoise) { throw std::logic_error("There's a cycle"); }
tortoise = tortoise->next;
}
</code></pre>
<p>O(n), which is as good as you can get.</p> |
91,688 | What are the differences between a clustered and a non-clustered index? | <p>What are the differences between a <code>clustered</code> and a <code>non-clustered index</code>?</p> | 91,725 | 13 | 7 | null | 2008-09-18 11:14:23.283 UTC | 116 | 2021-07-20 07:11:28.597 UTC | 2018-03-23 07:05:10.277 UTC | Nigel Campbell | 3,876,565 | Eric Labashosky | 6,522 | null | 1 | 304 | sql-server|indexing|clustered-index|non-clustered-index | 293,703 | <p>Clustered Index</p>
<ul>
<li>Only one per table</li>
<li>Faster to read than non clustered as data is physically stored in index order</li>
</ul>
<p>Non Clustered Index</p>
<ul>
<li>Can be used many times per table</li>
<li>Quicker for insert and update operations than a clustered index</li>
</ul>
<p>Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations.</p>
<p>Because of the slower insert and update clustered indexes should be set on a field that is normally incremental ie Id or Timestamp.</p>
<p>SQL Server will normally only use an index if its selectivity is above 95%.</p> |
1,117,916 | Merge keys array and values array into an object in JavaScript | <p>I have:</p>
<pre><code>var keys = [ "height", "width" ];
var values = [ "12px", "24px" ];
</code></pre>
<p>And I'd like to convert it into this object:</p>
<pre><code>{ height: "12px", width: "24px" }
</code></pre>
<p>In Python, there's the simple idiom <code>dict(zip(keys,values))</code>. Is there something similar in jQuery or plain JavaScript, or do I have to do this the long way?</p> | 1,117,927 | 13 | 1 | null | 2009-07-13 06:18:22.393 UTC | 15 | 2021-08-26 13:55:42.383 UTC | 2020-05-15 03:13:16.187 UTC | null | 6,904,888 | null | 7,581 | null | 1 | 49 | javascript|json|object | 42,912 | <p>Simple JS function would be:</p>
<pre><code>function toObject(names, values) {
var result = {};
for (var i = 0; i < names.length; i++)
result[names[i]] = values[i];
return result;
}
</code></pre>
<p>Of course you could also actually implement functions like zip, etc as JS supports higher order types which make these functional-language-isms easy :D</p> |
57,923 | What exactly is "managed" code? | <p>I've been writing C / C++ code for almost twenty years, and I know Perl, Python, PHP, and some Java as well, and I'm teaching myself JavaScript. But I've never done any .NET, VB, or C# stuff. What exactly does <strong>managed</strong> code mean?</p>
<p>Wikipedia <a href="http://en.wikipedia.org/wiki/Managed_code" rel="noreferrer">describes it</a> simply as</p>
<blockquote>
<p>Code that executes under the management of a virtual machine</p>
</blockquote>
<p>and it specifically says that Java is (usually) managed code, so</p>
<ul>
<li><strong>why does the term only seem to apply to C# / .NET?</strong></li>
<li><strong>Can you compile C# into a .exe that contains the VM as well, or do you have to package it up and give it to another .exe (a la java)?</strong></li>
</ul>
<p>In a similar vein,</p>
<ul>
<li><strong>is .NET a <em>language</em> or a <em>framework</em>, and what exactly does "framework" mean here?</strong></li>
</ul>
<p>OK, so that's more than one question, but for someone who's been in the industry as long as I have, I'm feeling rather N00B-ish right now...</p> | 57,945 | 15 | 2 | null | 2008-09-11 23:38:58.157 UTC | 10 | 2016-09-13 20:56:08.813 UTC | 2016-05-21 08:35:41.403 UTC | Cristián Romo | 5,104,596 | Graeme | 1,821 | null | 1 | 57 | c#|.net|vb.net|managed-code | 25,298 | <p>When you compile C# code to a .exe, it is compiled to Common Intermediate Language(CIL) bytecode. Whenever you run a CIL executable it is executed on Microsofts Common Language Runtime(CLR) virtual machine. So no, it is not possible to include the VM withing your .NET executable file. You must have the .NET runtime installed on any client machines where your program will be running.</p>
<p>To answer your second question, .NET is a framework, in that it is a set of libraries, compilers and VM that is not language specific. So you can code on the .NET framework in C#, VB, C++ and any other languages which have a .NET compiler. </p>
<p><a href="https://bitbucket.org/brianritchie/wiki/wiki/.NET%20Languages" rel="noreferrer">https://bitbucket.org/brianritchie/wiki/wiki/.NET%20Languages</a></p>
<p>The above page has a listing of languages which have .NET versions, as well as links to their pages.</p> |
343,368 | error LNK2005: _DllMain@12 already defined in MSVCRT.lib | <p>I am getting this linker error.</p>
<blockquote>
<p><strong>mfcs80.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in MSVCRT.lib(dllmain.obj)</strong></p>
</blockquote>
<p>Please tell me the correct way of eliminating this bug. I read solution on microsoft support site about this bug but it didnt helped much.</p>
<p>I am using VS 2005 with Platform SDK</p> | 343,467 | 17 | 0 | null | 2008-12-05 10:01:43.533 UTC | 7 | 2021-11-10 04:53:23.443 UTC | 2015-07-08 10:20:49.76 UTC | null | 3,383,213 | mahesh | 38,038 | null | 1 | 38 | c++|visual-c++|linker | 56,573 | <p>If you read the linker error thoroughly, and apply some knowledge, you may get there yourself:</p>
<p>The linker links a number of compiled objects and libraries together to get a binary.</p>
<p>Each object/library describes</p>
<ul>
<li>what symbols it expects to be present in other objects</li>
<li>what symbols it defines</li>
</ul>
<p>If two objects define the same symbol, you get exactly this linker error. In your case, both mfcs80.lib and MSVCRT.lib define the _DllMain@12 symbol.</p>
<p>Getting rid of the error:</p>
<ol>
<li>find out which of both libraries you actually need</li>
<li>find out how to tell the linker not to use the other one (using e.g. the <a href="https://stackoverflow.com/questions/343368/error-lnk2005-dllmain12-already-defined-in-msvcrtlib#343413">tip from James Hopkin</a>)</li>
</ol> |
242,822 | Why would someone use WHERE 1=1 AND <conditions> in a SQL clause? | <p>Why would someone use <code>WHERE 1=1 AND <conditions></code> in a SQL clause (Either SQL obtained through concatenated strings, either view definition)</p>
<p>I've seen somewhere that this would be used to protect against SQL Injection, but it seems very weird.</p>
<p>If there is injection <code>WHERE 1 = 1 AND injected OR 1=1</code> would have the same result as <code>injected OR 1=1</code>.</p>
<p>Later edit: What about the usage in a view definition?</p>
<hr>
<p>Thank you for your answers.</p>
<p>Still,
I don't understand why would someone use this construction for defining a view, or use it inside a stored procedure.</p>
<p>Take this for example:</p>
<pre><code>CREATE VIEW vTest AS
SELECT FROM Table WHERE 1=1 AND table.Field=Value
</code></pre> | 242,831 | 21 | 2 | null | 2008-10-28 10:37:04.78 UTC | 84 | 2021-06-03 11:33:23.747 UTC | 2011-11-17 02:38:53.427 UTC | Thomas Owens | 54,680 | Bogdan Maxim | 23,795 | null | 1 | 304 | sql|dynamic-sql | 251,404 | <p>If the list of conditions is not known at compile time and is instead built at run time, you don't have to worry about whether you have one or more than one condition. You can generate them all like:</p>
<pre><code>and <condition>
</code></pre>
<p>and concatenate them all together. With the <code>1=1</code> at the start, the initial <code>and</code> has something to associate with.</p>
<p>I've never seen this used for any kind of injection protection, as you say it doesn't seem like it would help much. I <em>have</em> seen it used as an implementation convenience. The SQL query engine will end up ignoring the <code>1=1</code> so it should have no performance impact.</p> |
365,191 | How to get time difference in minutes in PHP | <p>How to calculate minute difference between two date-times in PHP?</p> | 365,214 | 21 | 0 | null | 2008-12-13 13:05:25.16 UTC | 72 | 2021-11-30 17:11:20.717 UTC | 2012-07-21 07:58:41.5 UTC | null | 812,149 | tomaszs | 38,940 | null | 1 | 327 | php|date|time|minute | 702,456 | <p>Subtract the past most one from the future most one and divide by 60. </p>
<p>Times are done in Unix format so they're just a big number showing the number of seconds from <code>January 1, 1970, 00:00:00 GMT</code></p> |
34,833,653 | filter spark dataframe with row field that is an array of strings | <p>Using Spark 1.5 and Scala 2.10.6</p>
<p>I'm trying to filter a dataframe via a field "tags" that is an array of strings. Looking for all rows that have the tag 'private'.</p>
<pre><code>val report = df.select("*")
.where(df("tags").contains("private"))
</code></pre>
<p>getting:</p>
<blockquote>
<p>Exception in thread "main" org.apache.spark.sql.AnalysisException:
cannot resolve 'Contains(tags, private)' due to data type mismatch:
argument 1 requires string type, however, 'tags' is of array
type.;</p>
</blockquote>
<p>Is the filter method better suited? </p>
<p>UPDATED:</p>
<p>the data is coming from cassandra adapter but a minimal example that shows what I'm trying to do and also gets the above error is:</p>
<pre><code> def testData (sc: SparkContext): DataFrame = {
val stringRDD = sc.parallelize(Seq("""
{ "name": "ed",
"tags": ["red", "private"]
}""",
"""{ "name": "fred",
"tags": ["public", "blue"]
}""")
)
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext.implicits._
sqlContext.read.json(stringRDD)
}
def run(sc: SparkContext) {
val df1 = testData(sc)
df1.show()
val report = df1.select("*")
.where(df1("tags").contains("private"))
report.show()
}
</code></pre>
<p>UPDATED: the tags array can be any length and the 'private' tag can be in any position</p>
<p>UPDATED: one solution that works: UDF</p>
<pre><code>val filterPriv = udf {(tags: mutable.WrappedArray[String]) => tags.contains("private")}
val report = df1.filter(filterPriv(df1("tags")))
</code></pre> | 34,843,830 | 2 | 5 | null | 2016-01-17 00:14:14.99 UTC | 3 | 2017-02-09 23:41:16.403 UTC | 2016-01-17 16:11:04.92 UTC | null | 7,223 | null | 7,223 | null | 1 | 19 | scala|apache-spark | 45,976 | <p>I think if you use <code>where(array_contains(...))</code> it will work. Here's my result:</p>
<pre><code>scala> import org.apache.spark.SparkContext
import org.apache.spark.SparkContext
scala> import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.DataFrame
scala> def testData (sc: SparkContext): DataFrame = {
| val stringRDD = sc.parallelize(Seq
| ("""{ "name": "ned", "tags": ["blue", "big", "private"] }""",
| """{ "name": "albert", "tags": ["private", "lumpy"] }""",
| """{ "name": "zed", "tags": ["big", "private", "square"] }""",
| """{ "name": "jed", "tags": ["green", "small", "round"] }""",
| """{ "name": "ed", "tags": ["red", "private"] }""",
| """{ "name": "fred", "tags": ["public", "blue"] }"""))
| val sqlContext = new org.apache.spark.sql.SQLContext(sc)
| import sqlContext.implicits._
| sqlContext.read.json(stringRDD)
| }
testData: (sc: org.apache.spark.SparkContext)org.apache.spark.sql.DataFrame
scala>
| val df = testData (sc)
df: org.apache.spark.sql.DataFrame = [name: string, tags: array<string>]
scala> val report = df.select ("*").where (array_contains (df("tags"), "private"))
report: org.apache.spark.sql.DataFrame = [name: string, tags: array<string>]
scala> report.show
+------+--------------------+
| name| tags|
+------+--------------------+
| ned|[blue, big, private]|
|albert| [private, lumpy]|
| zed|[big, private, sq...|
| ed| [red, private]|
+------+--------------------+
</code></pre>
<p>Note that it works if you write <code>where(array_contains(df("tags"), "private"))</code>, but if you write <code>where(df("tags").array_contains("private"))</code> (more directly analogous to what you wrote originally) it fails with <code>array_contains is not a member of org.apache.spark.sql.Column</code>. Looking at the source code for <code>Column</code>, I see there's some stuff to handle <code>contains</code> (constructing a <code>Contains</code> instance for that) but not <code>array_contains</code>. Maybe that's an oversight.</p> |
6,426,142 | How to append a string to each element of a Bash array? | <p>I have an array in Bash, each element is a string. How can I append another string to each element? In Java, the code is something like:</p>
<pre><code>for (int i=0; i<array.length; i++)
{
array[i].append("content");
}
</code></pre> | 6,426,365 | 4 | 1 | null | 2011-06-21 13:35:45.18 UTC | 13 | 2019-01-17 07:00:20.953 UTC | 2015-07-06 19:32:33.847 UTC | null | 1,245,190 | null | 486,720 | null | 1 | 55 | arrays|bash | 54,679 | <p>Tested, and it works:</p>
<pre><code>array=(a b c d e)
cnt=${#array[@]}
for ((i=0;i<cnt;i++)); do
array[i]="${array[i]}$i"
echo "${array[i]}"
done
</code></pre>
<p>produces:</p>
<pre><code>a0
b1
c2
d3
e4
</code></pre>
<p>EDIT: declaration of the <code>array</code> could be shortened to</p>
<pre><code>array=({a..e})
</code></pre>
<p>To help you understand arrays and their syntax in bash the <a href="http://www.gnu.org/software/bash/manual/bashref.html" rel="noreferrer">reference</a> is a good start. Also I recommend you <a href="http://wiki.bash-hackers.org/syntax/arrays" rel="noreferrer">bash-hackers</a> explanation.</p> |
6,918,623 | CURLOPT_FOLLOWLOCATION cannot be activated | <p>So I keep getting this annoying error on multiple servers(its a warning, so I'd ignore it, but I need the function)</p>
<blockquote>
<p>Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or an open_basedir is set in /home/xxx/public_html/xxx.php on line 56</p>
</blockquote>
<p>How would I go about fixing this via SSH? </p> | 6,918,685 | 5 | 1 | null | 2011-08-02 21:06:57.67 UTC | 3 | 2016-01-26 20:32:37.38 UTC | 2013-03-13 08:43:34.853 UTC | null | 367,456 | null | 810,304 | null | 1 | 16 | curl|php | 97,133 | <p>Set <code>safe_mode = Off</code> in your php.ini file (it's usually in /etc/ on the server). If that's already off, then look around for the <code>open_basedir</code> stuff in the php.ini file, and change it accordingly.</p>
<p>Basically, the follow location option has been disabled as a security measure, but PHP's built-in security features are usually more annoying than secure. In fact, <code>safe_mode</code> <a href="http://php.net/manual/en/features.safe-mode.php">is deprecated in PHP 5.3</a>.</p> |
6,647,783 | Check value of least significant bit (LSB) and most significant bit (MSB) in C/C++ | <p>I need to check the value of the least significant bit (LSB) and most significant bit (MSB) of an integer in C/C++. How would I do this?</p> | 6,647,792 | 5 | 0 | null | 2011-07-11 08:52:55.043 UTC | 11 | 2017-02-19 14:06:54.47 UTC | 2012-12-20 06:43:22.313 UTC | null | 922,184 | null | 554,785 | null | 1 | 27 | c++|c|integer|bit-manipulation|bit | 98,291 | <pre><code>//int value;
int LSB = value & 1;
</code></pre>
<p>Alternatively <em>(which is not theoretically portable, but practically it is - see Steve's comment)</em></p>
<pre><code>//int value;
int LSB = value % 2;
</code></pre>
<p><strong><em>Details:</em></strong>
The second formula is simpler. The % operator is the remainder operator. A number's LSB is 1 iff it is an odd number and 0 otherwise. So we check the remainder of dividing with 2. The logic of the first formula is this: number 1 in binary is this:</p>
<pre><code>0000...0001
</code></pre>
<p>If you binary-AND this with an arbitrary number, all the bits of the result will be 0 except the last one because 0 AND anything else is 0. The last bit of the result will be 1 iff the last bit of your number was 1 because <code>1 & 1 == 1</code> and <code>1 & 0 == 0</code></p>
<p><a href="http://www.cprogramming.com/tutorial/bitwise_operators.html" rel="noreferrer">This</a> is a good tutorial for bitwise operations. </p>
<p>HTH.</p> |
6,997,187 | How to check for empty value in Javascript? | <p>I am working on a method of retrieving an array of hidden inputs in my form like so</p>
<pre><code><input type="hidden" value="12:34:00" name="timetemp0">
<input type="hidden" value="14:45:00" name="timetemp1">
<input type="hidden" value="15:12:00" name="timetemp2">
<input type="hidden" value="16:42:12" name="timetemp3">
<input type="hidden" value="16:54:56" name="timetemp4">
<input type="hidden" value="17:03:10" name="timetemp5">
</code></pre>
<p>My javascript function retrieves these individually by using getElementsByName('timetemp'+i)</p>
<pre><code> for (i ; i < counter[0].value; i++)
{
//finds hidden element by using concatenation of base name plus counter
var timetemp = document.getElementsByName('timetemp'+i);
//if there is a value alert that value to user - this is just for testing purposes at the moment
//because there is only one of timetemp.i then it occupies position 0 in array
if (timetemp[0].value == null)
{
alert ('No value');
}
else
{
alert (timetemp[0].value);
}
}
</code></pre>
<p>So what should happen is it will alert the user of the value in that hidden input but if it comes accross an input with no value like this:</p>
<pre><code><input type="hidden" value="" name="timetemp16">
</code></pre>
<p>Then it will say "No value"</p>
<p>However th if function cannot seem to work with this:</p>
<p>I have tried:</p>
<ol>
<li><code>(timetemp[0].value == null)</code></li>
<li><code>(timetemp[0].value === null)</code></li>
<li><code>(timetemp[0].value == undefined)</code></li>
<li><code>(timetemp[0].value == '')</code></li>
</ol>
<p>It always seems to default to else clause.</p>
<p>Any ideas?</p> | 6,997,562 | 6 | 4 | null | 2011-08-09 13:48:27.953 UTC | 7 | 2022-06-12 13:23:42.53 UTC | 2016-09-30 09:22:20.623 UTC | null | 206,730 | null | 859,615 | null | 1 | 15 | javascript|html|null | 115,019 | <p>Comment as an answer:</p>
<pre><code>if (timetime[0].value)
</code></pre>
<p>This works because any variable in JS can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.</p> |
6,420,813 | width of grid view boundfield | <p>I can not set the width of bound field. Is there any problem in the following markup. </p>
<pre><code> <asp:BoundField DataField="UserName" HeaderText="User Name"
meta:resourcekey="BoundFieldUNCUserNameResource1">
<HeaderStyle Width="50%" />
</asp:BoundField>
</code></pre>
<p><img src="https://i.stack.imgur.com/LLkzH.png" alt="enter image description here"></p>
<p>Please refer to the image. I set width using the following. The yellow colored numbers are corresponding width. The marked user name is always Wrapped even I set a width to a large value (say 50%) and set Wrap="false".</p>
<pre><code><HeaderStyle Width="20%" Wrap="true" />
<ItemStyle Width="20%" Wrap="true" />
</code></pre> | 6,420,912 | 6 | 0 | null | 2011-06-21 05:39:16.517 UTC | 6 | 2020-06-29 21:00:04.247 UTC | 2013-12-06 05:26:27.167 UTC | null | 1,459,996 | null | 767,445 | null | 1 | 21 | asp.net|gridview|boundfield | 62,579 | <p>Try This:</p>
<p><code>ItemStyle-Width="50%" ItemStyle-Wrap="false"</code> in the BoundField tag</p> |
7,008,214 | php string to int | <pre><code>$a = '88';
$b = '88 8888';
echo (int)$a;
echo (int)$b;
</code></pre>
<p>as expected, both produce 88. Anyone know if there's a string to int function that will work for $b's value and produce 888888? I've googled around a bit with no luck.</p>
<p>Thanks</p> | 7,008,242 | 6 | 2 | null | 2011-08-10 08:58:57.057 UTC | 2 | 2019-01-25 15:05:54.56 UTC | null | null | null | null | 788,952 | null | 1 | 25 | php|string|int | 179,312 | <p>You can remove the spaces before casting to <code>int</code>:</p>
<pre><code>(int)str_replace(' ', '', $b);
</code></pre>
<p>Also, if you want to strip other commonly used digit delimiters (such as <code>,</code>), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):</p>
<pre><code>(int)str_replace(array(' ', ','), '', $b);
</code></pre> |
6,995,946 | Log4J: How do I redirect an OutputStream or Writer to logger's writer(s)? | <p>I have a method which runs asynchronously after start, using OutputStream or Writer as parameter.</p>
<p>It acts as a recording adapter for an OutputStream or Writer (<em>it's a third party API I can't change</em>).</p>
<p><strong>How could I pass Log4J's internal OutputStream or Writer to that method?</strong><br>
<em>...because Log4J swallows System.out and System.err, I was using before.</em></p> | 6,996,147 | 7 | 4 | null | 2011-08-09 12:08:28.2 UTC | 7 | 2022-02-16 10:07:48.793 UTC | 2011-08-09 12:33:09.187 UTC | null | 680,925 | null | 853,728 | null | 1 | 37 | java|logging|log4j|outputstream|writer | 47,238 | <p>My suggestion is, why dont you write your OutputStream then?! I was about to write one for you, but I found this good example on the net, check it out!</p>
<p><a href="https://web.archive.org/web/20130527080241/http://www.java2s.com/Open-Source/Java/Testing/jacareto/jacareto/toolkit/log4j/LogOutputStream.java.htm" rel="noreferrer">LogOutputStream.java</a></p>
<pre><code>/*
* Jacareto Copyright (c) 2002-2005
* Applied Computer Science Research Group, Darmstadt University of
* Technology, Institute of Mathematics & Computer Science,
* Ludwigsburg University of Education, and Computer Based
* Learning Research Group, Aachen University. All rights reserved.
*
* Jacareto is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* Jacareto is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with Jacareto; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
package jacareto.toolkit.log4j;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import java.io.OutputStream;
/**
* This class logs all bytes written to it as output stream with a specified logging level.
*
* @author <a href="mailto:[email protected]">Christian Spannagel</a>
* @version 1.0
*/
public class LogOutputStream extends OutputStream {
/** The logger where to log the written bytes. */
private Logger logger;
/** The level. */
private Level level;
/** The internal memory for the written bytes. */
private String mem;
/**
* Creates a new log output stream which logs bytes to the specified logger with the specified
* level.
*
* @param logger the logger where to log the written bytes
* @param level the level
*/
public LogOutputStream (Logger logger, Level level) {
setLogger (logger);
setLevel (level);
mem = "";
}
/**
* Sets the logger where to log the bytes.
*
* @param logger the logger
*/
public void setLogger (Logger logger) {
this.logger = logger;
}
/**
* Returns the logger.
*
* @return DOCUMENT ME!
*/
public Logger getLogger () {
return logger;
}
/**
* Sets the logging level.
*
* @param level DOCUMENT ME!
*/
public void setLevel (Level level) {
this.level = level;
}
/**
* Returns the logging level.
*
* @return DOCUMENT ME!
*/
public Level getLevel () {
return level;
}
/**
* Writes a byte to the output stream. This method flushes automatically at the end of a line.
*
* @param b DOCUMENT ME!
*/
public void write (int b) {
byte[] bytes = new byte[1];
bytes[0] = (byte) (b & 0xff);
mem = mem + new String(bytes);
if (mem.endsWith ("\n")) {
mem = mem.substring (0, mem.length () - 1);
flush ();
}
}
/**
* Flushes the output stream.
*/
public void flush () {
logger.log (level, mem);
mem = "";
}
}
</code></pre> |
57,630,924 | How many String objects would be created when concatenating multiple Strings? | <p>I was asked in an interview about the number of objects that will be created on the given problem:</p>
<pre><code>String str1 = "First";
String str2 = "Second";
String str3 = "Third";
String str4 = str1 + str2 + str3;
</code></pre>
<p>I answered that there would be <strong>6 objects</strong> created in the string pool.</p>
<blockquote>
<p>3 would be for each of the three variables.<br>
1 would be for <code>str1 + str2</code> (let's say <code>str</code>).<br>
1 would be for <code>str2 + str3</code>.<br>
1 would be for the <code>str + str3</code> (<code>str = str1 + str2</code>). </p>
</blockquote>
<p>Is the answer I gave correct? If not, what is the correct answer?</p> | 57,631,217 | 7 | 7 | null | 2019-08-23 17:48:47.937 UTC | 6 | 2019-08-28 10:04:10.273 UTC | 2019-08-24 10:52:01.773 UTC | null | 1,711,796 | null | 11,650,948 | null | 1 | 38 | java|string|string-concatenation|string-pool|string-building | 2,926 | <p>Any answer to your question will depend on the JVM implementation and the Java version currently being used. I think it's an unreasonable question to ask in an interview.</p>
<h2>Java 8</h2>
<p>On my machine, with Java 1.8.0_201, your snippet results in this bytecode</p>
<pre><code>L0
LINENUMBER 13 L0
LDC "First"
ASTORE 1
L1
LINENUMBER 14 L1
LDC "Second"
ASTORE 2
L2
LINENUMBER 15 L2
LDC "Third"
ASTORE 3
L3
LINENUMBER 16 L3
NEW java/lang/StringBuilder
DUP
INVOKESPECIAL java/lang/StringBuilder.<init> ()V
ALOAD 1
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
ALOAD 2
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
ALOAD 3
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
ASTORE 4
</code></pre>
<p>which proves that <strong>5 objects</strong> are being created (3 <code>String</code> literals*, 1 <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/StringBuilder.html" rel="noreferrer"><code>StringBuilder</code></a>, 1 dynamically produced <code>String</code> instance by <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/CharSequence.html#toString()" rel="noreferrer"><code>StringBuilder#toString</code></a>).</p>
<h2>Java 12</h2>
<p>On my machine, with Java 12.0.2, the bytecode is</p>
<pre><code>// identical to the bytecode above
L3
LINENUMBER 16 L3
ALOAD 1
ALOAD 2
ALOAD 3
INVOKEDYNAMIC makeConcatWithConstants(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; [
// handle kind 0x6 : INVOKESTATIC
java/lang/invoke/StringConcatFactory.makeConcatWithConstants(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;
// arguments:
"\u0001\u0001\u0001"
]
ASTORE 4
</code></pre>
<p>which <a href="https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/invoke/StringConcatFactory.html#makeConcatWithConstants(java.lang.invoke.MethodHandles.Lookup,java.lang.String,java.lang.invoke.MethodType,java.lang.String,java.lang.Object...)" rel="noreferrer">magically</a> changes "the correct answer" to <strong>4 objects</strong> since there is no intermediate <code>StringBuilder</code> involved.</p>
<hr>
<p>*Let's dig a bit deeper.</p>
<blockquote>
<h2><a href="https://docs.oracle.com/javase/specs/jls/se12/html/jls-12.html#jls-12.5" rel="noreferrer">12.5. Creation of New Class Instances</a></h2>
<p>A new class instance may be implicitly created in the following situations:</p>
<ul>
<li>Loading of a class or interface that contains a string literal (<a href="https://docs.oracle.com/javase/specs/jls/se12/html/jls-3.html#jls-3.10.5" rel="noreferrer">§3.10.5</a>) may create a new String object to represent the literal. (This will not occur if a string denoting the same sequence of Unicode code points has previously been interned.)</li>
</ul>
</blockquote>
<p>In other words, when you start an application, there are already objects in the String pool. You barely know what they are and where they come from (unless you scan all loaded classes for all literals they contain).</p>
<p>The <code>java.lang.String</code> class will be undoubtedly loaded as an essential JVM class, meaning all its literals will be created and placed into the pool. </p>
<p>Let's take a randomly selected snippet from the source code of <code>String</code>, pick a couple of literals from it, put a breakpoint at the very beginning of our programme, and examine if the pool contains these literals.</p>
<pre><code>public final class String
implements java.io.Serializable, Comparable<String>, CharSequence,
Constable, ConstantDesc {
...
public String repeat(int count) {
// ...
if (Integer.MAX_VALUE / count < len) {
throw new OutOfMemoryError("Repeating " + len + " bytes String " + count +
" times will produce a String exceeding maximum size.");
}
}
...
}
</code></pre>
<p>They are there indeed.</p>
<p><img src="https://i.stack.imgur.com/FHGAG.png" width="300">
<img src="https://i.stack.imgur.com/r1On1.png" width="300"></p>
<p><sup>As an interesting find, this IDEA's filtering has a side effect: the substrings I was looking for have been added to the pool as well. The pool size increased by one (<code>"bytes String"</code> was added) after I applied <code>this.contains("bytes String")</code>.</sup></p>
<p>Where does this leave us? </p>
<p>We have no idea whether <code>"First"</code> was created and interned before we call <code>String str1 = "First";</code>, so we can't state firmly that the line creates a new instance.</p> |
15,655,073 | setTimeout and window.location (location.href) not working | <p>I want to redirect user to index.php in 5 seconds, but it redirects me right away. I don't want to use jQuery in this simple code.</p>
<pre><code><script>
setTimeout(function(){location.href="index.php", 5000} );
</script>
</code></pre> | 15,655,220 | 3 | 3 | null | 2013-03-27 09:06:34.237 UTC | 1 | 2018-10-29 14:12:10.233 UTC | 2013-03-27 09:12:43.66 UTC | null | 2,118,700 | null | 1,860,890 | null | 1 | 14 | javascript | 70,968 | <p>This is the right way...</p>
<pre><code>setTimeout(function(){location.href="index.php"} , 5000);
</code></pre>
<p>You can check the docs here:</p>
<p><a href="https://developer.mozilla.org/en/docs/DOM/window.setTimeout" rel="noreferrer">https://developer.mozilla.org/en/docs/DOM/window.setTimeout</a></p>
<p><strong>Syntax :</strong></p>
<pre><code>var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code, [delay]);
</code></pre>
<p><strong>Example :</strong>
<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>WriteDatePlease();
setTimeout(function(){WriteDatePlease();} , 5000);
function WriteDatePlease(){
var currentDate = new Date()
var dateAndTime = "Last Sync: " + currentDate.getDate() + "/"
+ (currentDate.getMonth()+1) + "/"
+ currentDate.getFullYear() + " @ "
+ currentDate.getHours() + ":"
+ currentDate.getMinutes() + ":"
+ currentDate.getSeconds();
$('.result').append("<p>" + dateAndTime + "</p>");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="result"></div></code></pre>
</div>
</div>
</p> |
10,650,528 | Access to path **** is denied | <p>I know there is a ton of stuff on this already and have tried a few things but have had no luck in fixing it. </p>
<p>I have a C# program that has built an XML Document and im trying to save it to a folder thats in MyDocuments. I am getting the folliwing exception when calling the <code>XMLDoc.Save</code> function.</p>
<blockquote>
<p>Access to the path 'C:\Users\Ash\Documents\ConfigOutput' is denied</p>
</blockquote>
<p>I have visual studio running as administrator. Any thoughts on how to fix it?</p>
<p>I have tried saving onto the desktop and into the C:\ folder aswell. </p>
<p>I am using windows 7.</p>
<p>Running the built executable also doesnt seem to work.</p>
<p>Apologies guys it seems I was being stupid. I had indeed not added a filename to the output path. I'll not delete the question incase anyone else gets done by this gotcha! Thanks for all the help/comments.</p> | 10,651,042 | 5 | 4 | null | 2012-05-18 09:59:52.247 UTC | null | 2016-06-28 09:12:48.957 UTC | 2016-06-28 09:12:48.957 UTC | null | 975,520 | null | 589,195 | null | 1 | 8 | c# | 38,814 | <p>There are a few possibilities:</p>
<ul>
<li>ConfigOutput is a folder</li>
<li>ConfigOutput is a file that is in use (opened)</li>
<li>You're not logged in as User 'Ash'</li>
</ul>
<p>You should not normally have to run as Admin to write to your own Documents folder. </p> |
10,474,306 | What's the main benefit of using eval() in JavaScript? | <p>I know this may be a newbie question, but I'm curious as to the main benefit of <code>eval()</code> - where would it be used best? I appreciate any info.</p> | 10,474,424 | 15 | 5 | null | 2012-05-06 21:06:11.143 UTC | 11 | 2019-12-24 10:10:35.56 UTC | 2012-05-06 21:30:12.957 UTC | null | 763,029 | null | 763,029 | null | 1 | 51 | javascript|eval | 43,347 | <p>The <code>eval</code> function is best used: Never.</p>
<p>It's purpose is to evaluate a string as a Javascript expression. Example:</p>
<pre><code>eval('x = 42');
</code></pre>
<p>It has been used a lot before, because a lot of people didn't know how to write the proper code for what they wanted to do. For example when using a dynamic name for a field:</p>
<pre><code>eval('document.frm.'+frmName).value = text;
</code></pre>
<p>The proper way to do that would be:</p>
<pre><code>document.frm[frmName].value = text;
</code></pre>
<p>As the <code>eval</code> method executes the string as code, every time that it is used is a potential opening for someone to inject harmful code in the page. See <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting</a>.</p>
<p>There are a few legitimate uses for the <code>eval</code> function. It's however not likely that you will ever be in a situation where you actually will need it.</p> |
31,715,310 | Convert timestamp string to long in java | <p>I have to fetch time stamp from DB and retrieve only time and compare two time.</p>
<p>//below are the string values</p>
<pre><code> String st1 = "2015-07-24T09:39:14.000Z";
String st2 = "2015-07-24T09:45:44.000Z";
</code></pre>
<p>//retrieving only time <strong>09:39:14</strong></p>
<pre><code> String s = st1.substring(st1.indexOf("T") + 1, st1.indexOf(".0"));
</code></pre>
<p>//string to Long. </p>
<pre><code> Long time = Long.parseLong(s);
Long tim1=Long.valueOf(s).longValue();
</code></pre>
<p>Error:</p>
<pre><code>java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
</code></pre> | 31,715,446 | 6 | 3 | null | 2015-07-30 04:43:18.597 UTC | 1 | 2019-03-21 00:26:14.62 UTC | 2019-03-21 00:26:14.62 UTC | null | 4,257,225 | null | 4,257,225 | null | 1 | 8 | java|string|numberformatexception | 53,470 | <p>Another option is by using SimpleDateFormat (May not be the best compare to JODA Time)</p>
<pre><code>public static void main(String[] args) throws ParseException {
String st1 = "2015-07-24T09:39:14.000Z";
String st2 = "2015-07-24T09:45:44.000Z";
String time1 = st1.substring(st1.indexOf("T") + 1, st1.indexOf(".0"));
String time2 = st2.substring(st2.indexOf("T") + 1, st2.indexOf(".0"));
Date dateTime1 = new java.text.SimpleDateFormat("HH:mm").parse(time1);
Date dateTime2 = new java.text.SimpleDateFormat("HH:mm").parse(time2);
System.out.println(dateTime1.after(dateTime2));
}
</code></pre> |
10,312,521 | How do I fetch all Git branches? | <p>I cloned a Git repository containing many branches. However, <code>git branch</code> only shows one:</p>
<pre><code>$ git branch
* master
</code></pre>
<p>How would I pull all the branches locally so when I do <code>git branch</code>, it shows the following?</p>
<pre><code>$ git branch
* master
* staging
* etc...
</code></pre> | 10,312,587 | 36 | 10 | null | 2012-04-25 09:05:26.403 UTC | 695 | 2022-08-06 10:04:49.363 UTC | 2022-07-17 00:46:35.037 UTC | null | 365,102 | null | 651,174 | null | 1 | 2,096 | git|branch|git-branch | 2,226,135 | <h3>TL;DR answer</h3>
<pre class="lang-sh prettyprint-override"><code>git branch -r | grep -v '\->' | sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
git fetch --all
git pull --all
</code></pre>
<p>(It seems that pull fetches all branches from all remotes, but I always fetch first just to be sure.)</p>
<p>Run the first command only if there are remote branches on the server that aren't tracked by your local branches.</p>
<h3>Complete answer</h3>
<p>You can fetch all branches from all remotes like this:</p>
<pre><code>git fetch --all
</code></pre>
<p>It's basically a <a href="https://www.atlassian.com/git/tutorials/syncing/git-fetch" rel="noreferrer">power move</a>.</p>
<p><code>fetch</code> updates local copies of remote branches so this is always safe for your local branches <strong>BUT</strong>:</p>
<ol>
<li><p><code>fetch</code> will not <strong>update</strong> local branches (which <strong>track</strong> remote branches); if you want to update your local branches you still need to pull every branch.</p>
</li>
<li><p><code>fetch</code> will not <strong>create</strong> local branches (which <strong>track</strong> remote branches), you have to do this manually. If you want to list all remote branches:
<code>git branch -a</code></p>
</li>
</ol>
<p>To <strong>update</strong> local branches which track remote branches:</p>
<pre><code>git pull --all
</code></pre>
<p>However, this can be still insufficient. It will work only for your local branches which track remote branches. To track all remote branches execute this oneliner <strong>BEFORE</strong> <code>git pull --all</code>:</p>
<pre class="lang-sh prettyprint-override"><code>git branch -r | grep -v '\->' | sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
</code></pre>
<p>P.S. AFAIK <code>git fetch --all</code> and <code>git remote update</code> are equivalent.</p>
<hr />
<hr />
<p>Kamil Szot's <a href="https://stackoverflow.com/questions/10312521/how-to-fetch-all-git-branches#comment27984640_10312587">comment</a>, which folks have found useful.</p>
<blockquote>
<p>I had to use:</p>
<pre><code>for remote in `git branch -r`; do git branch --track ${remote#origin/} $remote; done
</code></pre>
<p>because your code created local branches named <code>origin/branchname</code> and
I was getting "refname 'origin/branchname' is ambiguous whenever I
referred to it.</p>
</blockquote> |
33,961,756 | Disabling Pylint no member- E1101 error for specific libraries | <p>Is there anyway to hide <code>E1101</code> errors for objects that are created from a specific library? Our large repository is littered with <code>#pylint: disable=E1101</code> around various objects created by pandas.</p>
<p>For example, pylint will throw a no member error on the following code:</p>
<pre><code>import pandas.io.data
import pandas as pd
spy = pandas.io.data.DataReader("SPY", "yahoo")
spy.to_csv("test.csv")
spy = pd.read_csv("test.csv")
close_px = spy.ix["2012":]
</code></pre>
<p>Will have the following errors:</p>
<pre><code>E: 6,11: Instance of 'tuple' has no 'ix' member (no-member)
E: 6,11: Instance of 'TextFileReader' has no 'ix' member (no-member)
</code></pre> | 35,106,735 | 3 | 5 | null | 2015-11-27 16:48:01.087 UTC | 5 | 2019-06-21 09:02:22.927 UTC | 2015-11-27 22:24:23.797 UTC | null | 1,064,197 | null | 1,064,197 | null | 1 | 42 | pandas|pylint | 22,515 | <p>You can mark their attributes as dynamically generated using <code>generated-members</code> option.</p>
<p>E.g. for pandas:</p>
<pre><code>generated-members=pandas.*
</code></pre> |
22,736,641 | XOR on two lists in Python | <p>I'm a beginner in Python, and I have to do the XOR between two lists (the first one with the length : 600 and the other 60)</p>
<p>I really don't know how to do that, if somebody can explain me how, it will be a pleasure.</p>
<p>I have to do that to find the BPSK signal module, and I'm wondering on how doing that with two lists that haven't the same length. I saw this post : <a href="https://stackoverflow.com/questions/16312730/comparing-two-lists-and-only-printing-the-differences-xoring-two-lists">Comparing two lists and only printing the differences? (XORing two lists)</a> but the length of lists is the same</p>
<p>Thanks for your help, and sry for my bad english
Rom</p> | 22,736,711 | 2 | 2 | null | 2014-03-29 20:42:08.503 UTC | 1 | 2014-03-30 00:24:11.62 UTC | 2017-05-23 12:06:48.517 UTC | null | -1 | user3464216 | null | null | 1 | 18 | python|list|python-2.7|xor | 47,015 | <p>Given sequences <code>seq1</code> and <code>seq2</code>, you can calculate the <a href="http://docs.python.org/2/library/stdtypes.html#set.symmetric_difference" rel="noreferrer">symmetric difference</a> with</p>
<pre><code>set(seq1).symmetric_difference(seq2)
</code></pre>
<p>For example,</p>
<pre><code>In [19]: set([1,2,5]).symmetric_difference([1,2,9,4,8,9])
Out[19]: {4, 5, 8, 9}
</code></pre>
<p>Tip: Generating the set with the smaller list is generally faster:</p>
<pre><code>In [29]: %timeit set(range(60)).symmetric_difference(range(600))
10000 loops, best of 3: 25.7 µs per loop
In [30]: %timeit set(range(600)).symmetric_difference(range(60))
10000 loops, best of 3: 41.5 µs per loop
</code></pre>
<p>The reason why you may want to use <code>symmetric difference</code> instead of <code>^</code> (despite the beauty of its syntax) is because the <code>symmetric difference</code> method can take a list as input. <code>^</code> requires both inputs be sets. Converting <em>both</em> lists into sets is a little more computation than is minimally required.</p>
<hr>
<p>This question has been marked of as a duplicate of <a href="https://stackoverflow.com/questions/16312730/comparing-two-lists-and-only-printing-the-differences-xoring-two-lists">this question</a>
That question, however, is seeking a solution to this problem without using sets.</p>
<p>The accepted solution,</p>
<pre><code>[a for a in list1+list2 if (a not in list1) or (a not in list2)]
</code></pre>
<p>is not the recommended way to XOR two lists if sets are allowed. For one thing, it's over 100 times slower:</p>
<pre><code>In [93]: list1, list2 = range(600), range(60)
In [94]: %timeit [a for a in list1+list2 if (a not in list1) or (a not in list2)]
100 loops, best of 3: 3.35 ms per loop
</code></pre> |
22,715,086 | Scheduling Python Script to run every hour accurately | <p>Before I ask, <strong>Cron Jobs and Task Scheduler</strong> will be my last options, this script will be used across Windows and Linux and I'd prefer to have a coded out method of doing this than leaving this to the end user to complete.</p>
<p>Is there a library for Python that I can use to schedule tasks? I will need to run a function once every hour, however, over time if I run a script once every hour and use .sleep, "once every hour" will run at a different part of the hour from the previous day due to the delay inherent to executing/running the script and/or function.</p>
<p>What is the <strong>best</strong> way to schedule a function to run at a specific time of day (more than once) <em>without</em> using a Cron Job or scheduling it with Task Scheduler?</p>
<p><em>Or if this is not possible, I would like your input as well.</em></p>
<h2><strong>AP Scheduler fit my needs exactly.</strong></h2>
<h3>Version < 3.0</h3>
<pre><code>import datetime
import time
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.daemonic = False
sched.start()
def job_function():
print("Hello World")
print(datetime.datetime.now())
time.sleep(20)
# Schedules job_function to be run once each minute
sched.add_cron_job(job_function, minute='0-59')
</code></pre>
<p>out:</p>
<pre><code>>Hello World
>2014-03-28 09:44:00.016.492
>Hello World
>2014-03-28 09:45:00.0.14110
</code></pre>
<h3>Version > 3.0</h3>
<p>(From Animesh Pandey's answer below)</p>
<pre><code>from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('interval', seconds=10)
def timed_job():
print('This job is run every 10 seconds.')
@sched.scheduled_job('cron', day_of_week='mon-fri', hour=10)
def scheduled_job():
print('This job is run every weekday at 10am.')
sched.configure(options_from_ini_file)
sched.start()
</code></pre> | 22,715,345 | 14 | 3 | null | 2014-03-28 14:05:37.127 UTC | 75 | 2022-07-12 20:05:58.59 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,453,153 | null | 1 | 90 | python|python-3.x|cron|scheduled-tasks|cron-task | 200,171 | <p>Maybe this can help: <a href="http://apscheduler.readthedocs.io/" rel="noreferrer">Advanced Python Scheduler</a></p>
<p>Here's a small piece of code from their documentation:</p>
<pre><code>from apscheduler.schedulers.blocking import BlockingScheduler
def some_job():
print "Decorated job"
scheduler = BlockingScheduler()
scheduler.add_job(some_job, 'interval', hours=1)
scheduler.start()
</code></pre> |
13,478,464 | How to send data from JQuery AJAX request to Node.js server | <p><strong>What i want to do:</strong><br>
Simply send some data (json for example), to a node.js http server, using jquery ajax requests.</p>
<p>For some reason, i can't manage to get the data on the server, cause it never fires the 'data' event of the request.</p>
<p><strong>Client code:</strong></p>
<pre><code>$.ajax({
url: server,
dataType: "jsonp",
data: '{"data": "TEST"}',
jsonpCallback: 'callback',
success: function (data) {
var ret = jQuery.parseJSON(data);
$('#lblResponse').html(ret.msg);
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
}
});
</code></pre>
<p><strong>Server code:</strong></p>
<pre><code>var http = require('http');
http.createServer(function (req, res) {
console.log('Request received');
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.on('data', function (chunk) {
console.log('GOT DATA!');
});
res.end('callback(\'{\"msg\": \"OK\"}\')');
}).listen(8080, '192.168.0.143');
console.log('Server running at http://192.168.0.143:8080/');
</code></pre>
<p>As i said, it never gets into the 'data' event of the request.</p>
<p><strong>Comments:</strong><br>
1. It logs the 'Request received' message;<br>
2. The response is fine, im able to handle it back on the client, with data;</p>
<p>Any help? Am i missing something?</p>
<p>Thank you all in advance.</p>
<p><strong>EDIT:</strong><br>
Commented final version of the code, based on the answer:</p>
<p><strong>Client code:</strong>
<br></p>
<pre><code>$.ajax({
type: 'POST' // added,
url: server,
data: '{"data": "TEST"}',
//dataType: 'jsonp' - removed
//jsonpCallback: 'callback' - removed
success: function (data) {
var ret = jQuery.parseJSON(data);
$('#lblResponse').html(ret.msg);
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
}
});
</code></pre>
<p><br>
<strong>Server code:</strong><br></p>
<pre><code>var http = require('http');
http.createServer(function (req, res) {
console.log('Request received');
res.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*' // implementation of CORS
});
req.on('data', function (chunk) {
console.log('GOT DATA!');
});
res.end('{"msg": "OK"}'); // removed the 'callback' stuff
}).listen(8080, '192.168.0.143');
console.log('Server running at http://192.168.0.143:8080/');
</code></pre>
<p><br>
Since i want to allow Cross-Domain requests, i added an implementation of <a href="http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing">CORS</a>.</p>
<p>Thanks!</p> | 13,479,273 | 1 | 2 | null | 2012-11-20 17:14:44.487 UTC | 12 | 2012-11-20 21:08:26.747 UTC | 2012-11-20 21:08:26.747 UTC | null | 608,097 | null | 608,097 | null | 1 | 20 | node.js|jquery|request | 61,606 | <p>To get the 'data' event to fire on the node.js server side, you have to POST the data. That is, the 'data' event only responds to POSTed data. Specifying 'jsonp' as the data format forces a GET request, since jsonp is defined in the jquery documentation as:</p>
<blockquote>
<p>"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback</p>
</blockquote>
<p>Here is how you modify the client to get your data event to fire.</p>
<h3>Client:</h3>
<pre><code><html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.8.3.min.js"></script>
</head>
<body>
response here: <p id="lblResponse">fill me in</p>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'http://192.168.0.143:8080',
// dataType: "jsonp",
data: '{"data": "TEST"}',
type: 'POST',
jsonpCallback: 'callback', // this is not relevant to the POST anymore
success: function (data) {
var ret = jQuery.parseJSON(data);
$('#lblResponse').html(ret.msg);
console.log('Success: ')
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
},
});
});
</script>
</body>
</html>
</code></pre>
<p>Some helpful lines to help you debug the server side:</p>
<h3>Server:</h3>
<pre><code>var http = require('http');
var util = require('util')
http.createServer(function (req, res) {
console.log('Request received: ');
util.log(util.inspect(req)) // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) // this line logs just the method and url
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.on('data', function (chunk) {
console.log('GOT DATA!');
});
res.end('callback(\'{\"msg\": \"OK\"}\')');
}).listen(8080);
console.log('Server running on port 8080');
</code></pre>
<p>The purpose of the data event on the node side is to build up the body - it fires multiple times per a single http request, once for each chunk of data that it receives. This is the asynchronous nature of node.js - the server does other work in between receiving chunks of data.</p> |
13,436,467 | JavaScript NoSQL Injection prevention in MongoDB | <p>How can I prevent JavaScript NoSQL injections into MongoDB?</p>
<p>I am working on a Node.js application and I am passing <code>req.body</code>, which is a json object, into the mongoose model's save function. I thought there were safeguards behind the scenes, but this doesn't appear to be the case.</p> | 13,438,800 | 4 | 6 | null | 2012-11-18 01:00:02.917 UTC | 8 | 2019-10-22 23:15:58.41 UTC | 2016-07-16 21:50:58.953 UTC | null | 1,476,885 | null | 1,810,660 | null | 1 | 26 | javascript|node.js|mongodb|mongoose|javascript-injection | 25,872 | <p><strong>Note</strong>
My answer is incorrect. Please refer to other answers.</p>
<p>--</p>
<p>As a client program assembles a query in MongoDB, it builds a BSON object,
not a string. Thus traditional SQL injection attacks are not a problem. </p>
<p>For details follow the <a href="http://docs.mongodb.org/manual/faq/developers/#how-does-mongodb-address-sql-or-query-injection" rel="nofollow noreferrer">documentation</a></p>
<p><strong>UPDATE</strong></p>
<p>Avoid expression like <code>eval</code> which can execute arbitrary JS. If you are taking input from user and running <code>eval</code> like expressions without cleaning the input you can screw up. As pointed by JoBu1324, operations like <code>where</code>, <code>mapReduce</code> and <code>group</code> permit to execute JS expressions directly.</p> |
13,416,502 | Django: Search form in Class Based ListView | <p>I am trying to realize a <code>Class Based ListView</code> which displays a selection of a table set. If the site is requested the first time, the dataset should be displayed. I would prefer a POST submission, but GET is also fine.</p>
<p>That is a problem, which was easy to handle with <code>function based views</code>, however with class based views I have a hard time to get my head around.</p>
<p>My problem is that I get a various number of error, which are caused by my limited understanding of the classed based views. I have read various documentations and I understand views for direct query requests, but as soon as I would like to add a form to the query statement, I run into different error. For the code below, I receive an <code>ValueError: Cannot use None as a query value</code>.</p>
<p><strong>What would be the best practise work flow for a class based ListView depending on form entries (otherwise selecting the whole database)?</strong></p>
<p>This is my sample code:</p>
<p><strong>models.py</strong></p>
<pre><code>class Profile(models.Model):
name = models.CharField(_('Name'), max_length=255)
def __unicode__(self):
return '%name' % {'name': self.name}
@staticmethod
def get_queryset(params):
date_created = params.get('date_created')
keyword = params.get('keyword')
qset = Q(pk__gt = 0)
if keyword:
qset &= Q(title__icontains = keyword)
if date_created:
qset &= Q(date_created__gte = date_created)
return qset
</code></pre>
<p><strong>forms.py</strong></p>
<pre><code>class ProfileSearchForm(forms.Form):
name = forms.CharField(required=False)
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>class ProfileList(ListView):
model = Profile
form_class = ProfileSearchForm
context_object_name = 'profiles'
template_name = 'pages/profile/list_profiles.html'
profiles = []
def post(self, request, *args, **kwargs):
self.show_results = False
self.object_list = self.get_queryset()
form = form_class(self.request.POST or None)
if form.is_valid():
self.show_results = True
self.profiles = Profile.objects.filter(name__icontains=form.cleaned_data['name'])
else:
self.profiles = Profile.objects.all()
return self.render_to_response(self.get_context_data(object_list=self.object_list, form=form))
def get_context_data(self, **kwargs):
context = super(ProfileList, self).get_context_data(**kwargs)
if not self.profiles:
self.profiles = Profile.objects.all()
context.update({
'profiles': self.profiles
})
return context
</code></pre>
<p>Below I added the FBV which does the job. <strong>How can I translate this functionality into a CBV?</strong>
It seems to be so simple in function based views, but not in class based views.</p>
<pre><code>def list_profiles(request):
form_class = ProfileSearchForm
model = Profile
template_name = 'pages/profile/list_profiles.html'
paginate_by = 10
form = form_class(request.POST or None)
if form.is_valid():
profile_list = model.objects.filter(name__icontains=form.cleaned_data['name'])
else:
profile_list = model.objects.all()
paginator = Paginator(profile_list, 10) # Show 10 contacts per page
page = request.GET.get('page')
try:
profiles = paginator.page(page)
except PageNotAnInteger:
profiles = paginator.page(1)
except EmptyPage:
profiles = paginator.page(paginator.num_pages)
return render_to_response(template_name,
{'form': form, 'profiles': suppliers,},
context_instance=RequestContext(request))
</code></pre> | 13,528,456 | 7 | 4 | null | 2012-11-16 12:22:04.207 UTC | 20 | 2022-04-21 21:53:21.27 UTC | 2012-11-24 22:36:10.08 UTC | null | 631,348 | null | 729,241 | null | 1 | 31 | django|forms|listview|django-class-based-views | 49,419 | <p>I think your goal is trying to filter queryset based on form submission, if so, by using GET :</p>
<pre><code>class ProfileSearchView(ListView)
template_name = '/your/template.html'
model = Person
def get_queryset(self):
name = self.kwargs.get('name', '')
object_list = self.model.objects.all()
if name:
object_list = object_list.filter(name__icontains=name)
return object_list
</code></pre>
<p>Then all you need to do is write a <code>get</code> method to render template and context.</p>
<p>Maybe not the best approach. By using the code above, you no need define a Django form.</p>
<p>Here's how it works : Class based views separates its way to render template, to process form and so on. Like, <code>get</code> handles GET response, <code>post</code> handles POST response, <code>get_queryset</code> and <code>get_object</code> is self explanatory, and so on. The easy way to know what's method available, fire up a shell and type :</p>
<p><code>from django.views.generic import ListView</code> if you want to know about <code>ListView</code></p>
<p>and then type <code>dir(ListView)</code>. There you can see all the method defined and go visit the source code to understand it. The <code>get_queryset</code> method used to get a queryset. Why not just define it like this, it works too :</p>
<pre><code>class FooView(ListView):
template_name = 'foo.html'
queryset = Photo.objects.all() # or anything
</code></pre>
<p>We can do it like above, but we can't do dynamic filtering by using that approach. By using <code>get_queryset</code> we can do dynamic filtering, using any data/value/information we have, it means we also can use <code>name</code> parameter that is sent by <code>GET</code>, and it's available on <code>kwargs</code>, or in this case, on <code>self.kwargs["some_key"]</code> where <code>some_key</code> is any parameter you specified</p> |
13,532,084 | Set rowSpan or colSpan of a child of a GridLayout programmatically? | <p>I have a <code>GridLayout</code> with 5 columns and 3 rows. Now I can insert arbitrary child views, which is great. Even better is, that I can assign <code>columnSpan=2</code> to some item in order to span it to 2 columns (the same with rowSpan).</p>
<p>The problem now is, that I cannot assign rowSpan or columnSpan programmatically (i.e. at runtime). Some search suggested something like this:</p>
<pre><code>layoutParams.columnSpec = GridLayout.spec(0, columnSpan);
</code></pre>
<p>But I don't quite understand what the parameters of spec mean (start and size). The documentation is also quite poor at this point.</p>
<p>Any help is highly appreciated!</p> | 13,536,958 | 6 | 0 | null | 2012-11-23 15:38:06.357 UTC | 12 | 2022-05-20 11:49:27.887 UTC | 2017-10-04 23:22:44.357 UTC | null | 3,755,692 | null | 1,463,757 | null | 1 | 34 | android|html|grid-layout|html-table|columnspan | 61,762 | <p>OK, I spent some hours figuring out what's going on here. Well, I didn't find any working way to set columnSpan or rowSpan at runtime.</p>
<p>But I found a solution that works (at least for me):</p>
<h3>Java code</h3>
<pre><code>private LinearLayout addNewSpannedView(Integer resourceId, ViewGroup rootElement) {
return (LinearLayout) ((ViewGroup) getLayoutInflater().inflate(resourceId, rootElement, true)).getChildAt(rootElement.getChildCount() - 1);
}
// set columnSpan depending on some logic (gridLayout is the layout to add the view's to -> in my case these are LinearLayouts)
shape = addNewSpannedView(columnSpan == 1 ? R.layout.grid_ll_col_span_1 : R.layout.grid_ll_col_span_2, gridLayout);
</code></pre>
<h3>grid_ll_col_span_2.xml</h3>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/shapeWidth"
android:layout_height="wrap_content"
android:layout_columnSpan="2"/>
</code></pre>
<p>Hint: It's very important, that you set the width and height attribute, <strong>before</strong> inflate() adds the view to the root element (i.e. the parent element).</p>
<p>I hope, someone can use this ;-)</p> |
13,713,572 | How is dynamic programming different from greedy algorithms? | <p>In the book I am using <a href="https://rads.stackoverflow.com/amzn/click/com/0201743957" rel="noreferrer" rel="nofollow noreferrer">Introduction to the Design & Analysis of Algorithms</a>, <em>dynamic programming</em> is said to focus on the <strong>Principle of Optimality</strong>, "An optimal solution to any instance of an optimization problem is composed of optimal solutions to its subinstances".</p>
<p>Whereas, the <em>greedy technique</em> focuses on expanding partially constructed solutions until you arrive at a solution for a complete problem. It is then said, it must be "the best local choice among all feasible choices available on that step".</p>
<p>Since both involve local optimality, isn't one a subset of the other?</p> | 13,713,735 | 7 | 3 | null | 2012-12-04 23:05:14.373 UTC | 28 | 2019-02-22 14:22:25.197 UTC | 2015-05-24 18:52:41 UTC | null | 3,924,118 | null | 27,483 | null | 1 | 43 | algorithm|dynamic-programming|greedy | 33,778 | <p>Dynamic programming is applicable to problems exhibiting the properties of:</p>
<ul>
<li>overlapping subproblems, and</li>
<li>optimal substructure.</li>
</ul>
<p>Optimal substructure means that you can greedily solve subproblems and combine the solutions to solve the larger problem. <strong>The difference between dynamic programming and greedy algorithms is that with dynamic programming, there are overlapping subproblems, and those subproblems are solved using memoization</strong>. "Memoization" is the technique whereby solutions to subproblems are used to solve other subproblems more quickly.</p>
<p>This answer has gotten some attention, so I'll give some examples.</p>
<p>Consider the problem "Making change with dollars, nickels, and pennies." This is a greedy problem. It exhibits optimal substructure because you can solve for the number of dollars. Then, solve for the number of nickels. Then the number of pennies. You can then combine the solutions to these subproblems efficiently. It does not really exhibit overlapping subproblems since solving each subproblem doesn't help much with the others (maybe a little bit).</p>
<p>Consider the problem "Fibonnaci numbers." It exhibits optimal substructure because you can solve F(10) from F(9) and F(8) efficiently (by addition). These subproblems overlap because they both share F(7). If you memoize the result of F(7) when you're solving F(8), you can solve F(9) more quickly.</p>
<p>In response to the comment about dynamic programming having to do with "reconsidering decisions": This is obviously not true for any linear dynamic programming algorithm like <a href="http://en.wikipedia.org/wiki/Maximum_subarray_problem" rel="noreferrer">the maximum subarray problem</a> or the Fibonacci problem above.</p>
<p>Essentially, imagine a problem having optimal substructure as a directed acyclic graph whose nodes represent subproblems (wherein the whole problem is represented by a node whose indegree is zero), and whose directed edges represent dependencies between subproblems. Then, a greedy problem is a tree (all nodes except the root have unit indegree). A dynamic programming problem has some nodes with indegree greater than one. This illustrates the overlapping subproblems.</p> |
3,821,468 | SQL atomic increment and locking strategies - is this safe? | <p>I have a question about SQL and locking strategies. As an example, suppose I have a view counter for the images on my website. If I have a sproc or similar to perform the following statements:</p>
<pre><code>START TRANSACTION;
UPDATE images SET counter=counter+1 WHERE image_id=some_parameter;
COMMIT;
</code></pre>
<p>Assume that the counter for a specific image_id has value '0' at time t0. If two sessions updating the same image counter, s1 and s2, start concurrently at t0, is there any chance that these two sessions both read the value '0', increase it to '1' and both try to update the counter to '1', so the counter will get value '1' instead of '2'?</p>
<pre><code>s1: begin
s1: begin
s1: read counter for image_id=15, get 0, store in temp1
s2: read counter for image_id=15, get 0, store in temp2
s1: write counter for image_id=15 to (temp1+1), which is 1
s2: write counter for image_id=15 to (temp2+1), which is also 1
s1: commit, ok
s2: commit, ok
</code></pre>
<p>End result: incorrect value '1' for image_id=15, should have been 2.</p>
<p>My questions are: </p>
<ol>
<li>Is this scenario possible?</li>
<li>If so, does the transaction isolation level matter?</li>
<li>Is there a conflict resolver which would detect such a conflict as an error?</li>
<li>Can one use any special syntax in order to avoid a problem (something like Compare And Swap (CAS) or explicit locking techniques)?</li>
</ol>
<p>I'm interested in a general answer, but if there are none I'm interested in MySql and InnoDB-specific answers, since I'm trying to use this technique to implement sequences on InnoDB.</p>
<p>EDIT:
The following scenario could also be possible, resulting in the same behavior. I'm assuming that we are in isolation level READ_COMMITED or higher, so that s2 gets the value from the start of the transaction although s1 already wrote '1' to the counter.</p>
<pre><code>s1: begin
s1: begin
s1: read counter for image_id=15, get 0, store in temp1
s1: write counter for image_id=15 to (temp1+1), which is 1
s2: read counter for image_id=15, get 0 (since another tx), store in temp2
s2: write counter for image_id=15 to (temp2+1), which is also 1
s1: commit, ok
s2: commit, ok
</code></pre> | 3,821,780 | 2 | 1 | null | 2010-09-29 12:15:34.64 UTC | 15 | 2010-12-13 14:33:09.567 UTC | 2010-09-29 12:44:36.63 UTC | null | 83,741 | null | 83,741 | null | 1 | 47 | sql|locking|atomic|increment | 15,643 | <p><code>UPDATE</code> query places an update lock on the pages or records it reads.</p>
<p>When a decision is made whether to update the record, the lock is either lifted or promoted to the exclusive lock.</p>
<p>This means that in this scenario:</p>
<pre><code>s1: read counter for image_id=15, get 0, store in temp1
s2: read counter for image_id=15, get 0, store in temp2
s1: write counter for image_id=15 to (temp1+1), which is 1
s2: write counter for image_id=15 to (temp2+1), which is also 1
</code></pre>
<p><code>s2</code> will wait until <code>s1</code> decides whether to write the counter or not, and this scenario is in fact impossible.</p>
<p>It will be this:</p>
<pre><code>s1: place an update lock on image_id = 15
s2: try to place an update lock on image_id = 15: QUEUED
s1: read counter for image_id=15, get 0, store in temp1
s1: promote the update lock to the exclusive lock
s1: write counter for image_id=15 to (temp1+1), which is 1
s1: commit: LOCK RELEASED
s2: place an update lock on image_id = 15
s2: read counter for image_id=15, get 1, store in temp2
s2: write counter for image_id=15 to (temp2+1), which is 2
</code></pre>
<p>Note that in <code>InnoDB</code>, <code>DML</code> queries do not lift the update locks from the records they read.</p>
<p>This means that in case of a full table scan, the records that were read but decided not to update, will still remain locked until the end of the transaction and cannot be updated from another transaction.</p> |
45,553,339 | How use Kotlin enum with Retrofit? | <p>How can I parse JSON to model with enum?</p>
<p>Here is my enum class:</p>
<pre><code>enum class VehicleEnumEntity(val value: String) {
CAR("vehicle"),
MOTORCYCLE("motorcycle"),
VAN("van"),
MOTORHOME("motorhome"),
OTHER("other")
}
</code></pre>
<p>and I need to parse <code>type</code> into an enum</p>
<blockquote>
<p>"vehicle": {
"data": {
"type": "vehicle",
"id": "F9dubDYLYN"
}
}</p>
</blockquote>
<p><strong>EDIT</strong></p>
<p>I have tried standard way, just pass my enum to POJO and it always null</p> | 45,553,707 | 2 | 6 | null | 2017-08-07 18:18:48.793 UTC | 6 | 2022-02-06 11:21:32.943 UTC | 2017-08-07 18:47:14.633 UTC | null | 1,011,435 | null | 3,198,230 | null | 1 | 32 | android|enums|gson|kotlin|retrofit2 | 17,912 | <pre><code>enum class VehicleEnumEntity(val value: String) {
@SerializedName("vehicle")
CAR("vehicle"),
@SerializedName("motorcycle")
MOTORCYCLE("motorcycle"),
@SerializedName("van")
VAN("van"),
@SerializedName("motorhome")
MOTORHOME("motorhome"),
@SerializedName("other")
OTHER("other")
}
</code></pre>
<p><a href="https://stackoverflow.com/a/18851314/1011435">Source</a></p> |
28,498,295 | Spring Boot ConflictingBeanDefinitionException: Annotation-specified bean name for @Controller class | <p>I keep getting the <code>ConflictingBeanDefinitionException</code> error in my Spring boot application. I am not entirely sure as to how to address it, I have several <code>@Configuration</code> annotated classes helping to set up Thymeleaf, Spring Security and Web. Why is the application trying to setup the <code>homeController</code> twice? (and where is it trying to do this?)</p>
<p>The error is:</p>
<pre><code>org.springframework.beans.factory.BeanDefinitionStoreException:
Failed to parse configuration class [org.kemri.wellcome.hie.Application]; nested exception is org.springframework.context.annotation.ConflictingBeanDefinitionException:
Annotation-specified bean name 'homeController' for bean class [org.kemri.wellcome.hie.HomeController] conflicts with existing, non-compatible bean definition of same name and class [org.kemri.wellcome.hie.controller.HomeController]
</code></pre>
<p>My spring boot main application initializer:</p>
<pre><code>@EnableScheduling
@EnableAspectJAutoProxy
@EnableCaching
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
</code></pre>
<p>My database config file:</p>
<pre><code>@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages="org.kemri.wellcome.hie.repositories")
@PropertySource("classpath:application.properties")
public class DatabaseConfig {
@Autowired
private Environment env;
@Autowired
private DataSource dataSource;
@Autowired
private LocalContainerEntityManagerFactoryBean entityManagerFactory;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driverClassName"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory =
new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource);
// Classpath scanning of @Component, @Service, etc annotated class
entityManagerFactory.setPackagesToScan(
env.getProperty("spring.jpa.hibernate.entitymanager.packagesToScan"));
// Vendor adapter
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
// Hibernate properties
Properties additionalProperties = new Properties();
additionalProperties.put(
"hibernate.dialect",
env.getProperty("spring.jpa.hibernate.dialect"));
additionalProperties.put(
"hibernate.showsql",
env.getProperty("spring.jpa.hibernate.showsql"));
additionalProperties.put(
"hibernate.hbm2ddl.auto",
env.getProperty("spring.jpa.hibernate.hbm2ddl.auto"));
entityManagerFactory.setJpaProperties(additionalProperties);
return entityManagerFactory;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager =
new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
entityManagerFactory.getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
</code></pre>
<p>My Thymeleaf config file:</p>
<pre><code>@Configuration
public class ThymeleafConfig {
@Bean
public ServletContextTemplateResolver templateResolver(){
ServletContextTemplateResolver thymeTemplateResolver = new ServletContextTemplateResolver();
thymeTemplateResolver.setPrefix("/WEB-INF/views/");
thymeTemplateResolver.setSuffix(".html");
thymeTemplateResolver.setTemplateMode("HTML5");
return thymeTemplateResolver;
}
@Bean
public SpringSecurityDialect springSecurityDialect(){
SpringSecurityDialect dialect = new SpringSecurityDialect();
return dialect;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.addTemplateResolver(templateResolver());
Set<IDialect> dialects = new HashSet<IDialect>();
dialects.add(springSecurityDialect());
engine.setAdditionalDialects(dialects);
return engine;
}
@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setViewClass(ThymeleafTilesView.class);
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
</code></pre>
<p>}</p>
<p>My Web config class:</p>
<pre><code>@Configuration
@PropertySource("classpath:application.properties")
public class WebConfig extends WebMvcAutoConfigurationAdapter {
@Autowired
private Environment env;
@Bean
public JavaMailSenderImpl javaMailSenderImpl() {
JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
mailSenderImpl.setHost(env.getProperty("smtp.host"));
mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class));
mailSenderImpl.setProtocol(env.getProperty("smtp.protocol"));
mailSenderImpl.setUsername(env.getProperty("smtp.username"));
mailSenderImpl.setPassword(env.getProperty("smtp.password"));
Properties javaMailProps = new Properties();
javaMailProps.put("mail.smtp.auth", true);
javaMailProps.put("mail.smtp.starttls.enable", true);
mailSenderImpl.setJavaMailProperties(javaMailProps);
return mailSenderImpl;
}
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager();
}
}
</code></pre>
<p>My controller (where there is an error setting up the controller)</p>
<pre><code>@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "index.html";
}
}
</code></pre>
<p>What might be causing the <code>ConflictingBeanDefinitionException</code> error for my controller class?</p> | 28,503,680 | 7 | 5 | null | 2015-02-13 11:10:57.403 UTC | 2 | 2021-09-13 21:28:47.073 UTC | 2020-10-19 12:43:09.227 UTC | null | 1,746,685 | null | 1,384,464 | null | 1 | 26 | java|spring|spring-mvc|spring-security|spring-boot | 62,371 | <p>The solution, as I found out, is to disable double initialization by including a filter in the component scan. In my case:</p>
<pre><code>@EnableScheduling
@EnableAspectJAutoProxy
@EnableCaching
@Configuration
@ComponentScan(basePackages = { "org.kemri.wellcome.hie" },
excludeFilters = {@Filter(value = Controller.class, type = FilterType.ANNOTATION)})
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</code></pre> |
9,198,440 | is there a maximum size to android internal storage allocated for an app? | <p>I want to save a json file with all the application data (something similar to preference) but im not sure what is the limit size, because if the app cant use this file it will not function probably. is this information known beforehand and the OS reserve some space for your app or its based on the size available. </p>
<p>Update:
I dont really care about External storage since is not always available in the device and could be changed (SD card) and i could check for <a href="https://stackoverflow.com/questions/2652935/android-internal-phone-storage">internal storage using this</a> but this is not what i want to know, What i want to know if there's a memory size allocated for internal storage for the device ? </p> | 9,198,511 | 5 | 2 | null | 2012-02-08 17:31:29.343 UTC | 10 | 2021-04-09 07:58:28.863 UTC | 2017-05-23 10:30:46.61 UTC | null | -1 | null | 302,707 | null | 1 | 46 | android|storage|android-sdcard | 38,503 | <p>If you use <a href="http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29" rel="noreferrer"><code>Environment.getExternalStorageDirectory()</code></a> (or <a href="http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir%28java.lang.String%29" rel="noreferrer"><code>Context.getExternalFilesDir()</code></a> for API level 8 and up) as the place for your json file, then I believe the size will be limited by the available space in the external storage (usually an SD card). For most devices, I believe there are no fixed limits built into Android for external file storage. (Internal storage is a different matter. Device manufacturers can impose quite restrictive limits, perhaps as low as 100MB shared among all applications.)</p>
<p>UPDATE: Note that according to the <a href="http://static.googleusercontent.com/external_content/untrusted_dlcp/source.android.com/en/us/compatibility/android-2.3-cdd.pdf" rel="noreferrer">compatibility definition for Android 2.3</a> (Section 7.6.1), devices should have quite a bit of memory:</p>
<blockquote>
<p>Device implementations MUST have at least 150MB of non-volatile storage available for user data. That is, the /data partition MUST be at least 150MB.</p>
<p>Beyond the requirements above, device implementations SHOULD have at least 1GB of non-volatile storage available for user data. Note that this
higher requirement is planned to become a hard minimum in a future version of Android. Device implementations are strongly encouraged to meet
these requirements now, or else they may not be eligible for compatibility for a future version of Android.</p>
</blockquote>
<p>This space is shared by all applications, so it can fill up. There is no guaranteed minimum storage available for each app. (Such a guaranteed minimum would be worthless for apps that need to store more than the minimum and would be a waste for apps that store less.)</p>
<p><strong>Edit</strong>: From the <a href="http://static.googleusercontent.com/external_content/untrusted_dlcp/source.android.com/en/us/compatibility/android-4.0-cdd.pdf" rel="noreferrer">compatibility definition for Android 4.0</a></p>
<blockquote>
<p>Device implementations MUST have at least 350MB of non-volatile storage available for user data. That is, the /data partition MUST be at least 350MB.</p>
</blockquote>
<p>From the <a href="http://static.googleusercontent.com/external_content/untrusted_dlcp/source.android.com/en/us/compatibility/android-4.3-cdd.pdf" rel="noreferrer">compatibility definition for Android 4.3</a></p>
<blockquote>
<p>Device implementations MUST have at least 512MB of non-volatile storage available for user data. That is, the /data partition MUST be at least 512MB.</p>
</blockquote>
<p>Interestingly, the recommendation that implementations SHOULD provide at least 1GB has stayed the same.</p> |
16,054,596 | Change color of non-transparent parts of png in Java | <p>I am trying to automatically change the color for a set of icons.
Every icon has a white filled layer and the other part is transparent.
Here is an example: (in this case it's green, just to make it visible)</p>
<p><img src="https://i.stack.imgur.com/NWvnS.png" alt="icon search"></p>
<p>I tried to do the following:</p>
<pre><code>private static BufferedImage colorImage(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
for (int xx = 0; xx < width; xx++) {
for (int yy = 0; yy < height; yy++) {
Color originalColor = new Color(image.getRGB(xx, yy));
System.out.println(xx + "|" + yy + " color: " + originalColor.toString() + "alpha: "
+ originalColor.getAlpha());
if (originalColor.equals(Color.WHITE) && originalColor.getAlpha() == 255) {
image.setRGB(xx, yy, Color.BLUE.getRGB());
}
}
}
return image;
}
</code></pre>
<p>The problem I have is that every pixel I get has the same value:</p>
<pre><code>32|18 color: java.awt.Color[r=255,g=255,b=255]alpha: 255
</code></pre>
<p>So my result is just a colored square.
How can I achieve to change the color of the non-transparent parts only? And why is it, that all pixels have even the same alpha value? I guess that's my main problem: That the alpha value isn't read correctly.</p> | 16,054,867 | 4 | 0 | null | 2013-04-17 07:58:48.41 UTC | 12 | 2022-01-23 12:02:11.333 UTC | 2017-04-26 10:01:06.29 UTC | null | 1,177,083 | null | 1,177,083 | null | 1 | 19 | java|image|colors|png|transparency | 17,302 | <p>The problem is, that </p>
<pre><code>Color originalColor = new Color(image.getRGB(xx, yy));
</code></pre>
<p>discards all the alpha values. Instead you have to use </p>
<pre><code> Color originalColor = new Color(image.getRGB(xx, yy), true);
</code></pre>
<p>to keep alpha values available.</p> |
16,543,446 | how to make leaflet map height variable | <p>In my Application I was making div of map as</p>
<pre><code><div id="map" style="height: 610px; width:100%"></div>
</code></pre>
<p>but to make my map responsive I want to make height also 100%, if I make <code>height: 100%</code> then it is not working.</p>
<p>How can I make height also variable like width so that map can be seen properly on any device.</p>
<p>Demo : <a href="http://jsfiddle.net/CcYp6/">http://jsfiddle.net/CcYp6/</a></p>
<p>If you change height & width of map then you will not get map.</p> | 16,543,492 | 4 | 2 | null | 2013-05-14 12:41:36.923 UTC | 6 | 2021-12-10 06:17:58.223 UTC | 2013-05-14 13:02:38.967 UTC | null | 1,498,159 | null | 1,498,159 | null | 1 | 40 | css|leaflet | 62,911 | <p>You need to set the parent elements to <code>height: 100%;</code> first</p>
<pre><code>html, body {
height: 100%;
}
</code></pre>
<p><a href="http://jsfiddle.net/y8m7z/" rel="noreferrer"><strong>Demo</strong></a></p>
<p><a href="http://jsfiddle.net/y8m7z/1/" rel="noreferrer"><strike>Demo</strike></a> (This won't work as no parent height is defined)</p>
<p>Explanation: Why do you need to do that? So when you specify an element's height in <code>%</code> then the 1st question that arises is: <code>100%</code> of what?
By default, a div has height of <code>0px</code>, so <code>100%</code> for a div simply won't work, but setting the parent elements <code>height</code> to <code>100%;</code> will work.</p> |
16,493,368 | Can TortoiseMerge be used as a difftool with Windows Git Bash? | <p>I'm just starting to work with Git. I would like to use TortoiseMerge as the difftool and mergetool.</p>
<p>In my <code>$HOME/.gitconfig</code> I have the following sections. I've removed the user and color sections for this question.</p>
<pre><code>[merge]
tool = tortoisemerge
[mergetool "tortoisemerge"]
cmd = \"TortoiseMerge.exe\" -base:\"$BASE\" -mine:\"$LOCAL\" -theirs:\"$REMOTE\" -merged:\"$MERGED\"
[diff]
tool = tortoisemerge
[difftool "tortoisemerge"]
cmd = \"TortoiseMerge.exe\" -base:\"$BASE\" -mine:\"$LOCAL\" -theirs:\"$REMOTE\" -merged:\"$MERGED\"
</code></pre>
<p>If I type tortoisemerge at the Git Bash prompt it loads. It is known to be on the path. But if I type the command I get the following error.</p>
<pre><code>Rich:mygittest (master *)
$ git difftool
error: 'tortoisemerge' can only be used to resolve merges
merge tool candidates: kompare emerge vimdiff
No known merge resolution program available.
external diff died, stopping at readme.txt.
Rich:mygittest (master *)
$
</code></pre>
<p>What am I not understanding to make this work?
Tortoisemerge is installed with TortoiseSVN.</p> | 16,494,703 | 7 | 0 | null | 2013-05-11 03:10:27.21 UTC | 14 | 2022-03-17 01:30:41.443 UTC | 2020-07-16 10:13:32.88 UTC | null | 5,534,993 | null | 439,320 | null | 1 | 52 | git|tortoisegit|git-diff|tortoisegitmerge | 19,046 | <p>The following settings work fine for me. However, I am using TortoiseGit not TortoiseSVN. Notice the difference in the parameters for diff.</p>
<pre><code>[diff]
tool = tortoisediff
[difftool]
prompt = false
[merge]
tool = tortoisemerge
[mergetool]
prompt = false
keepBackup = false
[difftool "tortoisediff"]
cmd = \""c:/Program Files/TortoiseGIT/bin/TortoiseGitMerge.exe"\" -mine "$REMOTE" -base "$LOCAL"
[mergetool "tortoisemerge"]
cmd = \""c:/Program Files/TortoiseGIT/bin/TortoiseGitMerge.exe"\" -base "$BASE" -theirs "$REMOTE" -mine "$LOCAL" -merged "$MERGED"
</code></pre> |
41,762,947 | How to get and print response from Httpclient.SendAsync call | <p>I'm trying to get a response from a HTTP request but i seem to be unable to. I have tried the following:</p>
<pre><code>public Form1() {
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("someUrl");
string content = "someJsonString";
HttpRequestMessage sendRequest = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
sendRequest.Content = new StringContent(content,
Encoding.UTF8,
"application/json");
</code></pre>
<p>Send message with:</p>
<pre><code> ...
client.SendAsync(sendRequest).ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
} // end public Form1()
</code></pre>
<p>With this code, i get back the status code and some header info, but i do not get back the response itself. I have tried also: </p>
<pre><code> HttpResponseMessage response = await client.SendAsync(sendRequest);
</code></pre>
<p>but I'm then told to create a async method like the following to make it work</p>
<pre><code>private async Task<string> send(HttpClient client, HttpRequestMessage msg)
{
HttpResponseMessage response = await client.SendAsync(msg);
string rep = await response.Content.ReadAsStringAsync();
}
</code></pre>
<p>Is this the preferred way to send a 'HttpRequest', obtain and print the response? I'm unsure what method is the right one.</p> | 41,764,220 | 1 | 6 | null | 2017-01-20 11:46:11.073 UTC | 1 | 2022-08-16 09:48:28.483 UTC | 2018-01-16 12:38:53.65 UTC | null | 4,390,133 | null | 7,127,982 | null | 1 | 6 | c#|asynchronous|httpclient | 50,129 | <p>here is a way to use <code>HttpClient</code>, and this should read the response of the request, in case the request return status 200, (the request is not <code>BadRequest</code> or <code>NotAuthorized</code>)</p>
<pre><code>string url = 'your url here';
// usually you create on HttpClient per Application (it is the best practice)
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).GetAwaiter().GetResult())
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
</code></pre>
<p>and for full details and to see how to use <code>async/await</code> with <code>HttpClient</code> you could read the details of <a href="https://stackoverflow.com/a/33031778/4390133">this answer</a></p> |
60,518,658 | How to get logs of deployment from Kubernetes? | <p>I am creating an InfluxDB deployment in a Kubernetes cluster (v1.15.2), this is my yaml file:</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: monitoring-influxdb
namespace: kube-system
spec:
replicas: 1
template:
metadata:
labels:
task: monitoring
k8s-app: influxdb
spec:
containers:
- name: influxdb
image: registry.cn-hangzhou.aliyuncs.com/google_containers/heapster-influxdb-amd64:v1.5.2
volumeMounts:
- mountPath: /data
name: influxdb-storage
volumes:
- name: influxdb-storage
emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
labels:
task: monitoring
# For use as a Cluster add-on (https://github.com/kubernetes/kubernetes/tree/master/cluster/addons)
# If you are NOT using this as an addon, you should comment out this line.
kubernetes.io/cluster-service: 'true'
kubernetes.io/name: monitoring-influxdb
name: monitoring-influxdb
namespace: kube-system
spec:
ports:
- port: 8086
targetPort: 8086
selector:
k8s-app: influxdb
</code></pre>
<p>And this is the pod status:</p>
<pre><code>$ kubectl get deployment -n kube-system
NAME READY UP-TO-DATE AVAILABLE AGE
coredns 1/1 1 1 163d
kubernetes-dashboard 1/1 1 1 164d
monitoring-grafana 0/1 0 0 12m
monitoring-influxdb 0/1 0 0 11m
</code></pre>
<p>Now, I've been waiting 30 minutes and there is still no pod available, how do I check the deployment log from command line? I could not access the Kubernetes dashboard now. I am searching a command to get the pod log, but now there is no pod available. I already tried to add label in node:</p>
<pre><code>kubectl label nodes azshara-k8s03 k8s-app=influxdb
</code></pre>
<p>This is my deployment describe content:</p>
<pre><code>$ kubectl describe deployments monitoring-influxdb -n kube-system
Name: monitoring-influxdb
Namespace: kube-system
CreationTimestamp: Wed, 04 Mar 2020 11:15:52 +0800
Labels: k8s-app=influxdb
task=monitoring
Annotations: kubectl.kubernetes.io/last-applied-configuration:
{"apiVersion":"extensions/v1beta1","kind":"Deployment","metadata":{"annotations":{},"name":"monitoring-influxdb","namespace":"kube-system"...
Selector: k8s-app=influxdb,task=monitoring
Replicas: 1 desired | 0 updated | 0 total | 0 available | 0 unavailable
StrategyType: RollingUpdate
MinReadySeconds: 0
RollingUpdateStrategy: 1 max unavailable, 1 max surge
Pod Template:
Labels: k8s-app=influxdb
task=monitoring
Containers:
influxdb:
Image: registry.cn-hangzhou.aliyuncs.com/google_containers/heapster-influxdb-amd64:v1.5.2
Port: <none>
Host Port: <none>
Environment: <none>
Mounts:
/data from influxdb-storage (rw)
Volumes:
influxdb-storage:
Type: EmptyDir (a temporary directory that shares a pod's lifetime)
Medium:
SizeLimit: <unset>
OldReplicaSets: <none>
NewReplicaSet: <none>
Events: <none>
</code></pre>
<p>This is another way to get logs:</p>
<pre><code>$ kubectl -n kube-system logs -f deployment/monitoring-influxdb
error: timed out waiting for the condition
</code></pre>
<p>There is no output for this command:</p>
<pre><code>kubectl logs --selector k8s-app=influxdb
</code></pre>
<p>There is all my pod in kube-system namespace:</p>
<pre><code>~/Library/Mobile Documents/com~apple~CloudDocs/Document/k8s/work/heapster/heapster-deployment ⌚ 11:57:40
$ kubectl get pods -n kube-system
NAME READY STATUS RESTARTS AGE
coredns-569fd64d84-5q5pj 1/1 Running 0 46h
kubernetes-dashboard-6466b68b-z6z78 1/1 Running 0 11h
traefik-ingress-controller-hx4xd 1/1 Running 0 11h
</code></pre> | 62,831,466 | 3 | 4 | null | 2020-03-04 03:30:29.117 UTC | 7 | 2021-06-29 08:33:06.177 UTC | 2021-06-29 08:33:06.177 UTC | null | 16,281,483 | null | 2,628,868 | null | 1 | 45 | kubernetes | 48,776 | <pre class="lang-sh prettyprint-override"><code>kubectl logs deployment/<name-of-deployment> # logs of deployment
kubectl logs -f deployment/<name-of-deployment> # follow logs
</code></pre> |
17,537,687 | If Cell in Range Contains Value Then Insert Comment in Adjacent Cell | <p>I hope the title clarifies the objective. All of my attempts fail miserably, for example:</p>
<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)
With Range("A1:A10") = "blah"
Range("A1:A10").Offset(0, 1).AddComment "fee"
Range("A1:A10").Offset(0, 2).AddComment "fi"
Range("A1:A10").Offset(0, 3).AddComment "fo"
End With
End Sub
</code></pre>
<p>I have also tried this approach:</p>
<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)
For Each cell In Range("A1:A10")
If cell.Value = "blah" Then
cell.Value.Offset(0, 1).AddComment "fee"
cell.Value.Offset(0, 2).AddComment "fi"
cell.Value.Offset(0, 3).AddComment "fo"
End If
Next
End Sub
</code></pre>
<p>And this:</p>
<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)
With Range(Target.Offset(0, 1).Address).AddComment
Range(Target).Offset(0, 1).Comment.Visible = False
Range(Target).Offset(0, 1).Comment.Text Text:="fee"
End With
End Sub
</code></pre>
<p>Note that the code is intended to be an event handler inserted in a particular worksheet. I clearly misunderstand VBA syntax with respect to ranges. Any assistance in making any of these subs work would be most appreciated.</p>
<p>Follow up: Tim's suggestion to use Worksheet_Calculate worked like a charm. I was able to accomplish my objective with this final variation on Tim's code:</p>
<pre><code>Private Sub Worksheet_Calculate()
Dim rng As Range, cell As Range
'see if any changes are in the monitored range...
Set rng = Range("A1:A10")
If Not rng Is Nothing Then
For Each cell In rng.Cells
If cell.Value = "blah" Then
cell.Offset(0, 1).AddComment "fee"
cell.Offset(0, 2).AddComment "fi"
cell.Offset(0, 3).AddComment "fo"
End If
Next
End If
End Sub
</code></pre> | 17,537,877 | 1 | 0 | null | 2013-07-08 23:36:26.777 UTC | 1 | 2013-07-09 17:01:42.803 UTC | 2018-07-09 19:34:03.733 UTC | null | -1 | null | 2,487,576 | null | 1 | 4 | vba|excel | 41,526 | <pre><code>Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range, cell as Range
On Error Goto haveError
'see if any changes are in the monitored range...
Set rng = Application.Intersect(Target, Me.Range("A1:A10"))
If Not rng is Nothing Then
'Next line prevents code updates from re-triggering this...
' (Not really needed if you're only adding comments)
Application.EnableEvents=False
For Each cell In rng.Cells
If cell.Value = "blah" Then
cell.Offset(0, 1).AddComment "fee"
cell.Offset(0, 2).AddComment "fi"
cell.Offset(0, 3).AddComment "fo"
End If
Next
Application.EnableEvents=True
End If
Exit Sub
haveError:
msgbox Err.Description
Application.EnableEvents=True
End Sub
</code></pre> |
17,539,236 | How to replace/name keys in a Javascript key:value object? | <p>How should I replace the key strings in a Javascript key:value hash map (as an object)?</p>
<p>This is what I have so far:</p>
<pre><code>var hashmap = {"aaa":"foo", "bbb":"bar"};
console.log("before:");
console.log(hashmap);
Object.keys(hashmap).forEach(function(key){
key = key + "xxx";
console.log("changing:");
console.log(key);
});
console.log("after:");
console.log(hashmap);
</code></pre>
<p>See it running in this <a href="http://jsbin.com/idobuc/1/edit" rel="noreferrer">jsbin</a>.</p>
<p>The "before" and "after" hashmaps are the same, so the <code>forEach</code> seems to be in a different scope. How can I fix it? Perhaps there are better ways of doing this?</p> | 17,539,261 | 5 | 1 | null | 2013-07-09 03:06:52.543 UTC | 3 | 2022-06-09 06:17:23.193 UTC | 2018-10-31 14:55:54.267 UTC | null | 114,900 | null | 733,034 | null | 1 | 13 | javascript | 64,292 | <p>It has nothing to do with scope. <code>key</code> is just a local variable, it's not an alias for the actual object key, so assigning it doesn't change the object.</p>
<pre><code>Object.keys(hashmap).forEach(function(key) {
var newkey = key + "xxx";
hashmap[newkey] = hashmap[key];
delete hashmap[key];
});
</code></pre> |
11,499,287 | Editing data from MySQL via PHP | <p>I am running into a frustrating problem with a PHP script that's supposed to allow me to edit individual rows within my MySQL database.</p>
<p>This is the file where all of the rows from the database are displayed; it works just like it's supposed to. </p>
<pre><code><table cellpadding="10">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>E-mail</td>
<td>Phone</td>
</tr>
<?php
$username="username here";
$password="password here";
$database="database name here";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM students";
$result=mysql_query($query);
mysql_close();
while ($row=mysql_fetch_array($result)){
echo ("<tr><td>$row[id]</td>");
echo ("<td>$row[first]</td>");
echo ("<td>$row[last]</td>");
echo ("<td>$row[email]</td>");
echo ("<td>$row[phone]</td>");
echo ("<td><a href=\"StudentEdit.php?id=$row[id]\">Edit</a></td></tr>");
}
echo "</table>";
?>
</code></pre>
<p>As you can see, each row has an "Edit" link that is supposed to allow the user to edit that individual student's data. Here, then, is StudentEdit.php:</p>
<pre><code><?php
$username="username";
$password="password";
$database="database";
mysql_connect(localhost,$username,$password);
$student_id = $_GET[id];
$query = "SELECT * FROM students WHERE id = '$student_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
mysql_close();
?>
<form method="post" action="EditStudentData.php" />
<table>
<tr>
<td><input type="hidden" name="id" value="<? echo "$row[id]" ?>"></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" name="first" value="<? echo "$row[first]" ?>"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="last" value="<? echo "$row[last]" ?>"></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="text" name="phone" value="<? echo "$row[phone]" ?>"></td>
</tr>
<tr>
<td>E-mail:</td>
<td><input type="text" name="email" value="<?echo "$row[email]" ?>"></td>
</tr>
</table>
</form>
</code></pre>
<p>When I execute this, however, I get the following error message:</p>
<p>Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home4/lukaspl1/public_html/StudentEdit.php on line 12</p>
<p>Any ideas what's wrong, and how to fix it?</p>
<p>Thank you in advance!</p> | 11,499,460 | 9 | 2 | null | 2012-07-16 06:44:11.25 UTC | 5 | 2021-09-28 16:19:02.457 UTC | null | null | null | null | 1,010,462 | null | 1 | 4 | php|mysql | 46,387 | <p><strong>StudentEdit.php:</strong> you forgot to call <code>@mysql_select_db($database) or die( "Unable to select database");</code> before you executed the query</p> |
21,517,102 | Regex to match md5 hashes | <p>What type of regex should be used to match a md5 hash. </p>
<p>how to validate this type of string <code>00236a2ae558018ed13b5222ef1bd987</code></p>
<p>i tried something like this: <code>('/^[a-z0-9]/')</code> but it didnt work.</p>
<p>how to achieve this? thanks</p> | 21,517,123 | 2 | 7 | null | 2014-02-02 22:28:31.533 UTC | 0 | 2014-02-02 22:38:03.69 UTC | null | null | null | null | 2,244,946 | null | 1 | 23 | php|regex|match | 41,064 | <p>This is a PCRE that will match a MD5 hash:</p>
<pre><code>define('R_MD5_MATCH', '/^[a-f0-9]{32}$/i');
if(preg_match(R_MD5_MATCH, $input_string)) {
echo "It matches.";
} else {
echo "It does not match.";
}
</code></pre> |
19,813,719 | await keyword blocks main thread | <p>So I have the following code</p>
<pre><code>private async void button1_Click(object sender, EventArgs e)
{
await DoSomethingAsync();
MessageBox.Show("Test");
}
private async Task DoSomethingAsync()
{
for (int i = 0; i < 1000000000; i++)
{
int a = 5;
}; // simulate job
MessageBox.Show("DoSomethingAsync is done");
await DoSomething2Async();
}
private async Task DoSomething2Async()
{
for (int i = 0; i < 1000000000; i++)
{
int a = 5;
} // simulate job
MessageBox.Show("DoSomething2Async is done");
}
</code></pre>
<p>Until both MessageBoxes are shown the main thread is block (I mean the application itself is frozen). There is obviously something wrong with my code and I can't figure out what. I've never used async/await before. this is my first attempt.</p>
<p><strong>EDIT:</strong></p>
<p>Actually what i want to do is to start Execution of <code>DoSomethingAsync</code> asynchronously so that when button is clicked the <code>MessageBox.Show("Test");</code> would execute even though the DoSomethingAsync is incomplete.</p> | 19,813,877 | 4 | 4 | null | 2013-11-06 13:44:33.337 UTC | 12 | 2021-12-30 11:07:59.563 UTC | 2018-02-07 14:51:20.083 UTC | null | 2,463,281 | null | 2,463,281 | null | 1 | 22 | c#|async-await | 23,152 | <p>I think you misunderstand what async means. <strong>It doesn't mean that the method runs in another thread!!</strong></p>
<p>An async method runs synchronously until the first <code>await</code>, then returns a <code>Task</code> to the caller (unless it's <code>async void</code>, then it returns nothing). When the task that is being awaited completes, execution resumes after the <code>await</code>, usually on the same thread (if it has a <code>SynchronizationContext</code>).</p>
<p>In your case, the <code>Thread.Sleep</code> is before the first await, so it's executed synchronously, before control is returned to the caller. But even if it was after the <code>await</code>, it would still block the UI thread, unless you specifically configured the the awaiter not to capture the synchronization context (using <code>ConfigureAwait(false)</code>).</p>
<p><code>Thread.Sleep</code> is a blocking method. If you want an async equivalent, use <code>await Task.Delay(3000)</code>, as suggested in Sriram Sakthivel's answer. It will return immediately, and resume after 3 seconds, without blocking the UI thread.</p>
<p>It's a common misconception that async is related to multithreading. It can be, but in many cases it's not. A new thread is not implicitly spawned just because the method is <code>async</code>; for a new thread to spawn, it has to be done explicitly at some point. If you specifically want the method to run on a different thread, use <code>Task.Run</code>.</p> |
17,161,285 | Exception :com.sun.jersey.spi.inject.Errors$ErrorMessagesException | <p>I am using the Jersey API for the web services. I am sending the multipart data from client to server. I am getting exception when web services start to execute.</p>
<pre><code>@POST
@Path("uploadphoto")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/plain")
public String uploadNotices(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "d:/" + fileDetail.getFileName();
// save it
try {
writeToFile(uploadedInputStream, uploadedFileLocation);
} catch(Exception e) {
return "no";
}
return "yes";
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws Exception {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
}
</code></pre>
<p>Stacktrace:</p>
<pre><code>SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for method public java.lang.String com.homebulletin.resources.NoticeResources.uploadNotices(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at parameter at index 0
SEVERE: Missing dependency for method public java.lang.String com.homebulletin.resources.NoticeResources.uploadNotices(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at parameter at index 1
SEVERE: Method, public java.lang.String com.homebulletin.resources.NoticeResources.uploadNotices(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition), annotated with POST of resource, class com.homebulletin.resources.NoticeResources, is not recognized as valid resource method.
Jun 18, 2013 10:55:17 AM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:760)
at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319)
at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609)
at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
Jun 18, 2013 10:55:17 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet Home Bulletin
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:760)
at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319)
at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609)
at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
</code></pre> | 17,161,572 | 11 | 1 | null | 2013-06-18 05:39:08.42 UTC | 3 | 2020-09-04 20:07:02.543 UTC | 2018-10-03 08:06:02.333 UTC | null | 839,554 | null | 2,455,259 | null | 1 | 23 | java|jakarta-ee|jersey | 57,848 | <p>It seems your missing few jars in your project.Try adding these to your project:</p>
<blockquote>
<p><strong>jersey-multipart.jar</strong></p>
<p><strong>mimepull.jar</strong></p>
</blockquote>
<p>If you are using maven, you can add this dependency:</p>
<pre><code><dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.8</version>
</dependency>
</code></pre>
<p>Change the version of jar if you need</p>
<p><strong>Also make sure that the version of your jersey-multipart jar should be same as the version of jersey bundle jar</strong></p> |
17,612,364 | Difference between save and saveOrUpdate method hibernate | <p>Normally I had read about save() method generates new identifier for object and only fire <strong>INSERT</strong> and save it, it does not update it, while saveOrUpdate() method may <strong>INSERT</strong> or <strong>UPDATE</strong> record.</p>
<p>But as per my experience, Here I can explains better by sample code,</p>
<p>Suppose there is <strong>Class A</strong>, and I find record from <strong>Table A</strong> by</p>
<pre><code>A a = getHibernateTemplate.findById(7);
</code></pre>
<p>So now I get a persistent object, </p>
<p>And now I am trying to save record with save method by simply modifying some of fields,</p>
<p>Now I am firing, </p>
<pre><code>getHibernateTemplate.save(a);
</code></pre>
<p>So it just <strong>update existing record</strong>, but as per my knowledge <strong>it should create new record</strong>.</p>
<p>I may be wrong about certian things, can someone clear about this?</p> | 17,612,564 | 4 | 1 | null | 2013-07-12 10:02:34.997 UTC | 7 | 2015-10-05 16:18:35.603 UTC | null | null | null | null | 1,508,629 | null | 1 | 25 | java|hibernate | 91,146 | <p><strong>save</strong></p>
<p>Save <code>method</code> stores an <code>object</code> into the database. It will Persist the given transient instance, first assigning a generated identifier.
It <code>returns</code> the <strong>id</strong> of the entity created.</p>
<p>Whereas,</p>
<p><strong>SaveOrUpdate()</strong></p>
<p>Calls either <code>save()</code> or <code>update()</code> on the basis of identifier exists or not. e.g if identifier exists, <code>update()</code> will be called or else <code>save()</code> will be called.</p>
<p>There are many more like <strong>persist(), merge(), saveOrUpdateCopy()</strong>. Almost all are same giving slight different functionality and usability.</p>
<p>For more, you can read this.
<a href="https://stackoverflow.com/questions/161224/what-are-the-differences-between-the-different-saving-methods-in-hibernate">What are the differences between the different saving methods in Hibernate?</a><a href="https://stackoverflow.com/questions/161224/what-are-the-differences-between-the-different-saving-methods-in-hibernate"></a> </p> |
17,520,964 | How to create ArrayList (ArrayList<Integer>) from array (int[]) in Java | <p>I have seen the question: <a href="https://stackoverflow.com/questions/157944/how-to-create-arraylist-arraylistt-from-array-t">Create ArrayList from array</a></p>
<p>However when I try that solution with following code, it doesn't quite work in all the cases:</p>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class ToArrayList {
public static void main(String[] args) {
// this works
String[] elements = new String[] { "Ryan", "Julie", "Bob" };
List<String> list = new ArrayList<String>(Arrays.asList(elements));
System.out.println(list);
// this works
List<Integer> intList = null;
intList = Arrays.asList(3, 5);
System.out.println(intList);
int[] intArray = new int[] { 0, 1 };
// this doesn't work!
intList = new ArrayList<Integer>(Arrays.asList(intArray));
System.out.println(intList);
}
}
</code></pre>
<p>What am I doing wrong here? Shouldn't the code <code>intList = new ArrayList<Integer>(Arrays.asList(intArray));</code> compile just fine?</p> | 17,520,983 | 5 | 2 | null | 2013-07-08 07:15:52.927 UTC | 15 | 2014-11-02 09:47:13.053 UTC | 2017-05-23 11:46:58.05 UTC | null | -1 | null | 1,119,997 | null | 1 | 29 | java|arrays|generics|collections | 103,296 | <p>The problem in</p>
<pre><code>intList = new ArrayList<Integer>(Arrays.asList(intArray));
</code></pre>
<p>is that <code>int[]</code> is considered as a single <code>Object</code> instance since a primitive array extends from <code>Object</code>. This would work if you have <code>Integer[]</code> instead of <code>int[]</code> since now you're sending an array of <code>Object</code>.</p>
<pre><code>Integer[] intArray = new Integer[] { 0, 1 };
//now you're sending a Object array
intList = new ArrayList<Integer>(Arrays.asList(intArray));
</code></pre>
<p>From your comment: if you want to still use an <code>int[]</code> (or another primitive type array) as main data, then you need to create an additional array with the wrapper class. For this example:</p>
<pre><code>int[] intArray = new int[] { 0, 1 };
Integer[] integerArray = new Integer[intArray.length];
int i = 0;
for(int intValue : intArray) {
integerArray[i++] = intValue;
}
intList = new ArrayList<Integer>(Arrays.asList(integerArray));
</code></pre>
<p>But since you're already using a <code>for</code> loop, I wouldn't mind using a temp wrapper class array, just add your items directly into the list:</p>
<pre><code>int[] intArray = new int[] { 0, 1 };
intList = new ArrayList<Integer>();
for(int intValue : intArray) {
intList.add(intValue);
}
</code></pre> |
17,474,412 | Removing Ignored Android Studio (or Intellij) Update Builds | <p>When an Android Studio update is posted and you mistakenly click on <code>Ignore This Update</code> how do you apply the update without having to reinstall Android Studio?</p> | 17,474,413 | 4 | 1 | null | 2013-07-04 16:00:17.63 UTC | 10 | 2019-11-02 15:15:47.923 UTC | null | null | null | null | 1,373,278 | null | 1 | 46 | android|intellij-idea|updates|android-studio | 9,130 | <p><strong>Update</strong></p>
<p>As of the latest version of Android Studio, there is now a Preference in the UI <a href="https://stackoverflow.com/a/46999038/1373278">noted in an answer by Yogesh Umesh Vaity</a></p>
<p><strong>Original Answer</strong></p>
<p>The simple way to revert a mistaken choice is to close Android Studio then edit <code>other.xml</code> file and remove the <code>myIgnoredBuildNumbers</code> option block:</p>
<pre class="lang-xml prettyprint-override"><code><option name="myIgnoredBuildNumbers">
<value>
<list size="1">
<item index="0" class="java.lang.String" itemvalue="130.729444" />
</list>
</value>
</option>
</code></pre>
<p>Technically you should edit the <code>size</code> and remove the <code>item</code> in question but after some testing the next time you ignore a build the <code>myIgnoredBuildNumbers</code> block will be rebuilt.</p>
<p>The <code>other.xml</code> file can be found at:</p>
<ul>
<li>OSX: <code>~/Library/Preferences/AndroidStudio/options/other.xml</code></li>
<li>WIN: <code>%HOMEPATH%\.AndroidStudio\config\options\other.xml</code></li>
<li>NIX: <code>~/.AndroidStudio/config/options/other.xml</code></li>
</ul>
<p>The same can be done in <code>Intellij</code> in the following paths:</p>
<ul>
<li>OSX: <code>~/Library/Preferences/IdeaIC12/options/other.xml</code></li>
<li>WIN: <code>%HOMEPATH%\.IdeaIC12\options\other.xml</code></li>
</ul>
<p>As of Android Studio 1.2(possibly earlier), the ignored builds block is defined in updates.xml within the same directory as other.xml </p> |
17,202,128 | Rounded cornes (border radius) Safari issue | <pre class="lang-css prettyprint-override"><code>.activity_rounded {
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
-khtml-border-radius: 50%;
border: 3px solid #fff;
behavior: url(css/PIE.htc);
}
</code></pre>
<pre class="lang-html prettyprint-override"><code><img src="img/demo/avatar_3.jpg" class="activity_rounded" alt="" />
</code></pre>
<p>This is my CSS & HTML. I want to make an image look like a circle. Everything works fine in IE8+, Google Chrome, and Mozilla Firefox. But Safari is acting kinda strange. Here is a demo picture:</p>
<p><img src="https://i.stack.imgur.com/UzhHI.png" alt="enter image description here" /></p> | 17,210,864 | 11 | 7 | null | 2013-06-19 21:59:43.26 UTC | 15 | 2022-06-19 07:41:28.843 UTC | 2022-06-19 07:41:28.843 UTC | null | 11,870,285 | null | 867,418 | null | 1 | 61 | html|css | 96,571 | <p>To illustrate the problem in Safari, let's begin with a plain image.</p>
<p><img src="https://i.stack.imgur.com/yVesQ.png" height="150"></p>
<p>Here we have an image of 100px x 100px. Adding a border of 3px increases the element dimensions to 106px x 106px:</p>
<p><img src="https://i.stack.imgur.com/aCk3m.png" height="160"></p>
<p>Now we give it a border radius of 20%:</p>
<p><img src="https://i.stack.imgur.com/7eWED.png" height="120"></p>
<p>You can see it starts cropping from the outer boundary of the element, not from the image itself.</p>
<p>Further increasing the magnitude to 50%:</p>
<p><img src="https://i.stack.imgur.com/WFLco.png" height="120"></p>
<p>And changing the border color to white:</p>
<p><img src="https://i.stack.imgur.com/xdGQc.png" height="120"></p>
<p>You can now see how the issue arises.</p>
<p>Because of such behavior of the browser, when creating an image in a circle with a border, we have to make sure both the image and the border are given a border radius. One way to ensure this is to separate the border from the image by placing the image inside a container, and apply border radius to both of them.</p>
<pre><code><div class="activity_rounded"><img src="http://placehold.it/100" /></div>
</code></pre>
<pre class="lang-css prettyprint-override"><code>.activity_rounded {
display: inline-block;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
-khtml-border-radius: 50%;
border: 3px solid #fff;
}
.activity_rounded img {
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
-khtml-border-radius: 50%;
vertical-align: middle;
}
</code></pre>
<p>And now we have a nice circle border around the image on Safari.</p>
<p><img src="https://i.stack.imgur.com/hP6OO.png" height="120"></p>
<p>See <a href="http://jsfiddle.net/3XSJN/1/">DEMO</a>.</p> |
18,348,797 | Why is it considered bad practice in Java to call a method from within a constructor? | <p>In Java, why is it considered bad practice to call a method from within a constructor? Is it especially bad if the method is computationally heavy?</p> | 18,369,062 | 3 | 3 | null | 2013-08-21 04:20:11.463 UTC | 18 | 2020-01-12 05:06:08.217 UTC | 2020-01-12 05:06:08.217 UTC | null | 3,204,692 | null | 2,380,088 | null | 1 | 25 | java | 21,738 | <p>First, in general there's no problem with calling methods in a constructor. The issues are specifically with the particular cases of calling overridable methods of the constructor's class, and of passing the object's <code>this</code> reference to methods (including constructors) of other objects.</p>
<p>The reasons for avoiding overridable methods and "leaking <code>this</code>" can be complicated, but they basically are all concerned with preventing use of incompletely initialised objects.</p>
<h2>Avoid calling overridable methods</h2>
<p>The reasons for avoiding calling overridable methods in constructors are a consequence of the instance creation process defined in <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.5" rel="noreferrer">§12.5</a> of the Java Language Specification (JLS).</p>
<p>Among other things, the process of §12.5 ensures that when instantiating a derived class<sup>[1]</sup>, the initialisation of its base class (i.e. setting its members to their initial values and execution of its constructor) occurs before its own initialisation. This is intended to allow consistent initialisation of classes, through two key principles:</p>
<ol>
<li>The initialisation of each class can focus on initialising only the members it explicitly declares itself, safe in the knowledge that all other members inherited from the base class have already been initialised.</li>
<li>The initialisation of each class can safely use members of its base class as inputs to the initialisation of its own members, as it is guaranteed they've been properly initialised by the time the initialisation of the class occurs.</li>
</ol>
<p>There is, however, a catch: Java allows dynamic dispatch in constructors<sup>[2]</sup>. This means that if a base class constructor executing as part of the instantiation of a derived class calls a method that exists in the derived class, it is called in the context of that derived class.</p>
<p>The direct consequence of all of this is that when instantiating a derived class, the base class constructor is called before the derived class is initialised. If that constructor makes a call to a method that is overridden by the derived class, it is the derived class method (not the base class method) that is called, <strong>even though the derived class has not yet been initialised</strong>. Evidently this is a problem if that method uses any members of the derived class, since they haven't been initialised yet.</p>
<p>Clearly, the issue is a result of the base class constructor calling methods that can be overriden by the derived class. To prevent the issue, constructors should only call methods of their own class that are final, static or private, as these methods cannot be overridden by derived classes. Constructors of final classes may call any of their methods, as (by definition) they cannot be derived from.</p>
<p><a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#d5e14764" rel="noreferrer">Example 12.5-2</a> of the JLS is a good demonstration of this issue:</p>
<pre><code>class Super {
Super() { printThree(); }
void printThree() { System.out.println("three"); }
}
class Test extends Super {
int three = (int)Math.PI; // That is, 3
void printThree() { System.out.println(three); }
public static void main(String[] args) {
Test t = new Test();
t.printThree();
}
}
</code></pre>
<p>This program prints <code>0</code> then <code>3</code>. The sequence of events in this example is as follows:</p>
<ol>
<li><code>new Test()</code> is called in the <code>main()</code> method.</li>
<li>Since <code>Test</code> has no explicit constructor, the default constructor of its superclass (namely <code>Super()</code>) is called.</li>
<li>The <code>Super()</code> constructor calls <code>printThree()</code>. This is dispatched to the overriden version of the method in the <code>Test</code> class.</li>
<li>The <code>printThree()</code> method of the <code>Test</code> class prints the current value of the <code>three</code> member variable, which is the default value <code>0</code> (since the <code>Test</code> instance hasn't been initialised yet).</li>
<li>The <code>printThree()</code> method and <code>Super()</code> constructor each exit, and the <code>Test</code> instance is initialised (at which point <code>three</code> is then set to <code>3</code>).</li>
<li>The <code>main()</code> method calls <code>printThree()</code> again, which this time prints the expected value of <code>3</code> (since the <code>Test</code> instance has now been initialised).</li>
</ol>
<p>As described above, §12.5 states that (2) must happen before (5), to ensure that <code>Super</code> is initialised before <code>Test</code> is. However, dynamic dispatch means that the method call in (3) is run in the context of the uninitialised <code>Test</code> class, leading to the unexpected behaviour.</p>
<h2>Avoid leaking <code>this</code></h2>
<p>The restriction against passing <code>this</code> from a constructor to another object is a little easier to explain.</p>
<p>Basically, an object cannot be considered fully initialised until its constructor has completed execution (since its purpose is to complete the initialisation of the object). So, if the constructor passes the object's <code>this</code> to another object, that other object then has a reference to the object even though it hasn't been fully initialised (since its constructor is still running). If the other object then attempts to access an uninitialised member or call a method of the original object that relies on it being fully initialised, unexpected behaviour is likely to result.</p>
<p>For an example of how this can result in unexpected behaviour, please refer to <a href="http://www.ibm.com/developerworks/java/library/j-jtp0618/index.html#2" rel="noreferrer">this article</a>.</p>
<p><hr/>
[1] Technically, every class in Java except <code>Object</code> is a derived class - I just use the terms 'derived class' and 'base class' here to outline the relationship between the particular classes in question.<br>
[2] There's no reason given in the JLS (as far as I'm aware) as to why this is the case. The alternative - disallowing dynamic dispatch in constructors - would make the whole issue moot, which is probably exactly why C++ doesn't allow it.</p> |
23,348,456 | Modify CSS classes using Javascript | <p>I was wondering if there is an easy way to change the CSS classes in JavaScript.
I have gone through all other similar questions here and I couldn't find an straight-forward and simple solution.</p>
<p>what I'm trying to do is to set the width and height of a <code><div></code> to match an image that I have on my site (upon loading). I already know the picture dimensions and I can set my CSS to that - but I want my script to figure this out on its own.</p>
<p>After hours of r&d (I'm a beginner), this is what I came up with:</p>
<pre><code>var myImg = new Image();
myImg.src = "img/default.jpg";
myImg.onload = function(){
var imgWidth = this.width;
var imgHeight = this.height;
document.getElementById("myBg").setAttribute('style', "height :"+ imgHeight + "px");
document.getElementById("myBg").setAttribute('style', "width :"+ imgWidth + "px");
};
</code></pre>
<p>However, this only sets the width of the element with id "myBg". If I reverse the order of the height and width, then it only sets the height to the image's height.
It seems like first it sets the height of the element to the image height but right after it moves to the next statement to set the width, the height value goes back to what it what defined originally in css.</p>
<p>I did further research online and seems like changing the css (inserting new attributes, removing, etc.) using JavaScript is not an easy task. It is done through </p>
<pre><code>document.styleSheets[i].cssRules[i] or document.styleSheets[i].addRule
</code></pre>
<p>type of commands, but all the tutorials online and here on stackoverflow were confusing and complicated.</p>
<p>I was wondering if anyone familiar with document.styleSheets can explain this to me simply?</p>
<p>Imagine I have this class in my separate css file:</p>
<pre><code>.container
{
height: 600px;
width: 500px;
}
</code></pre>
<p>I want the height and width to change to the dimension of the picture upon loading. How do I do this? </p>
<ul>
<li>I don't want to define a new "style" element in my html file, I want to change the css file.</li>
<li>I'm not supposed to know the image dimension before it loads to the page.</li>
<li>no jquery please, I want to do this using only standard JavaScript.</li>
</ul>
<p>Thank you.</p> | 23,348,564 | 3 | 6 | null | 2014-04-28 18:22:12.497 UTC | 7 | 2018-10-09 08:10:17.6 UTC | 2014-04-28 18:32:35.223 UTC | null | 1,326,008 | null | 1,326,008 | null | 1 | 29 | javascript|css | 73,200 | <p>The reason only one or the other works is because in your second line of code, you destroy the whole <code>style</code> attribute, and recreate it. Note that <code>setAttribute()</code> overwrites the whole attribute.</p>
<p>A better solution would be to use the <code>element.style</code> property, not the attribute;</p>
<pre><code>var bg = document.getElementById("myBg");
bg.style.width = imgWidth + "px";
bg.style.height = imgHeight + "px";
</code></pre>
<p>You can grab all elements with class <code>container</code> and apply it to each of them like this:</p>
<pre><code>var elements = document.querySelectorAll('.container');
for(var i=0; i<elements.length; i++){
elements[i].style.width = imgWidth + "px";
elements[i].style.height = imgHeight + "px";
}
</code></pre>
<p>Note <code>querySelectorAll</code> isn't supported by IE7 or lower, if you need those then there are shims for <code>getElementsByClassName()</code> here on SO.</p> |
5,264,355 | RSpec failure: could not find table after migration...? | <p>I have a naked rails 3 app with one model, generated using <code>rails g model User</code>.</p>
<p>I've added a factory (using <code>factory_girl_rails</code>):</p>
<pre><code>Factory.define :user do |f|
f.email "[email protected]"
f.password "blah"
f.password_confirmation "blah"
f.display_name "neezer"
end
</code></pre>
<p>Then I've added one test:</p>
<pre><code>require 'spec_helper'
describe User do
subject { Factory :user }
it "can be created from a factory" do
subject.should_not be_nil
subject.should be_kind_of User
end
end
</code></pre>
<p>Then I <em>migrate my database</em> using <code>rake db:migrate</code>.</p>
<p>Then I run the test using <code>rspec spec</code>, and the test fails with the following:</p>
<pre class="lang-none prettyprint-override"><code>Failures:
1) User can be created from a factory
Failure/Error: subject { Factory :user }
ActiveRecord::StatementInvalid:
Could not find table 'users'
# ./spec/models/user_spec.rb:5:in `block (2 levels) in <top (required)>'
# ./spec/models/user_spec.rb:8:in `block (2 levels) in <top (required)>'
</code></pre>
<p>I'm confused, because I did just migrate my database, and my <code>schema.db</code> file reflects that there is a users table present, so what gives?</p>
<p>I know this is a beginner question, but banging my head against a wall isn't working...</p>
<pre class="lang-none prettyprint-override"><code>factory_girl (1.3.3)
factory_girl_rails (1.0.1)
rails (3.0.5)
rspec-rails (2.5.0)
sqlite3 (1.3.3)
</code></pre> | 5,264,371 | 3 | 0 | null | 2011-03-10 18:53:54.247 UTC | 16 | 2014-08-04 09:53:28.557 UTC | 2014-08-03 19:03:02.99 UTC | user456814 | null | null | 32,154 | null | 1 | 29 | ruby-on-rails|ruby-on-rails-3|rspec|factory-bot | 10,320 | <p>Try to execute </p>
<pre><code>rake db:test:prepare
</code></pre>
<p>This should fix your tests db.</p> |
5,476,673 | CSS Justify text, fill space with dots | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/3097851/fill-available-spaces-between-labels-with-dots-or-hyphens">Fill available spaces between labels with dots or hyphens</a> </p>
</blockquote>
<p>Any way to format text like this with simple CSS? I have a DB of different products with their drugs and doses and want to display them uniformly, but without monospaced fonts.</p>
<pre><code>Drug 1 ............ 10ml
Another drug ...... 50ml
Third ............. 100ml
</code></pre> | 5,476,886 | 3 | 6 | null | 2011-03-29 17:44:10.9 UTC | 6 | 2011-08-11 07:00:58.22 UTC | 2017-05-23 12:02:48.803 UTC | null | -1 | null | 2,542 | null | 1 | 35 | css|xhtml | 35,798 | <p>Here's an elegant and unobtrusive one with some limitations (see below).</p>
<p><a href="http://jsfiddle.net/j6JWT/7/">JSFiddle</a></p>
<p>CSS:</p>
<pre><code>dl { width: 400px }
dt { float: left; width: 300px; overflow: hidden; white-space: nowrap }
dd { float: left; width: 100px; overflow: hidden }
dt:after { content: " .................................................................................." }
</code></pre>
<p>HTML:</p>
<pre><code><dl>
<dt>Drug 1</dt>
<dd>10ml</dd>
<dt>Another drug</dt>
<dd>50ml</dd>
<dt>Third</dt>
<dd>100ml</dd>
</dl>
</code></pre>
<p>limitations:</p>
<ul>
<li><p>Doesn't work in IE < 8</p></li>
<li><p>Accepts only literal characters in the <code>content</code> property, no HTML entities, so no <code>&middot;</code> for example. (This is no problem as @Radek points out, as UTF-8 characters should be able to serve almost every need here).</p></li>
</ul> |
5,210,778 | Elegant way to make all dirs in a path | <p>Here are four paths:</p>
<pre><code>p1=r'\foo\bar\foobar.txt'
p2=r'\foo\bar\foo\foo\foobar.txt'
p3=r'\foo\bar\foo\foo2\foobar.txt'
p4=r'\foo2\bar\foo\foo\foobar.txt'
</code></pre>
<p>The directories may or may not exist on a drive. What would be the most elegant way to create the directories in each path?</p>
<p>I was thinking about using <code>os.path.split()</code> in a loop, and checking for a dir with <code>os.path.exists</code>, but I don't know it there's a better approach.</p> | 5,210,790 | 3 | 1 | null | 2011-03-06 13:32:26.81 UTC | 6 | 2020-07-29 12:33:41.943 UTC | null | null | null | null | 559,807 | null | 1 | 65 | python|path | 32,393 | <p>You are looking for <a href="http://docs.python.org/library/os.html#os.makedirs" rel="noreferrer"><code>os.makedirs()</code></a> which does exactly what you need.</p>
<p>The documentation states:</p>
<blockquote>
<p>Recursive directory creation function.
Like mkdir(), but makes all
intermediate-level directories needed
to contain the leaf directory. Raises
an error exception if the leaf
directory already exists or cannot be
created.</p>
</blockquote>
<p>Because it fails if the leaf directory already exists you'll want to test for existence before calling <code>os.makedirs()</code>.</p> |
5,200,187 | Convert InputStream to BufferedReader | <p>I'm trying to read a text file line by line using InputStream from the assets directory in Android.</p>
<p>I want to convert the InputStream to a BufferedReader to be able to use the readLine().</p>
<p>I have the following code:</p>
<pre><code>InputStream is;
is = myContext.getAssets().open ("file.txt");
BufferedReader br = new BufferedReader (is);
</code></pre>
<p>The third line drops the following error:</p>
<pre>Multiple markers at this line
The constructor BufferedReader (InputStream) is undefinded.</pre>
<p>What I'm trying to do in C++ would be something like:</p>
<pre><code>StreamReader file;
file = File.OpenText ("file.txt");
line = file.ReadLine();
line = file.ReadLine();
...
</code></pre>
<p>What am I doing wrong or how should I do that? Thanks!</p> | 5,200,207 | 3 | 0 | null | 2011-03-04 22:56:53.61 UTC | 23 | 2019-10-10 16:48:32.05 UTC | 2019-10-10 16:48:32.05 UTC | null | 140,750 | null | 591,452 | null | 1 | 166 | java|android|inputstream|readline|bufferedreader | 205,519 | <p><code>BufferedReader</code> can't wrap an <code>InputStream</code> directly. It wraps another <code>Reader</code>. In this case you'd want to do something like:</p>
<pre><code>BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
</code></pre> |
9,606,614 | Cleaning noise out of Java stack traces | <p>My Java stack traces have a lot of entries that I don't care about, showing method invocation going through proxies and Spring reflection methods and stuff like that. It can make it pretty hard to pick out the part of the stack trace that's actually from my code. Ruby on Rails includes a "stack trace cleaner" where you can specify a list of stack trace patterns to omit from printed stack traces - what's the best way to do something like that, universally, for Java?</p>
<p>It'd be best if this worked everywhere, including in the Eclipse jUnit runner.</p> | 9,607,068 | 6 | 4 | null | 2012-03-07 17:51:59.397 UTC | 6 | 2019-08-18 03:11:55.07 UTC | null | null | null | null | 11,284 | null | 1 | 33 | java|exception|stack-trace | 8,365 | <p><a href="/questions/tagged/eclipse" class="post-tag" title="show questions tagged 'eclipse'" rel="tag">eclipse</a> has a preference <strong>Stack trace filter patterns</strong> (look at <em>java</em> > <em>junit</em> or search for <code>stacktrace</code> in the preferences). You can ignore packages (also with wildcards), classes or methods. Does work for direct Test calls (via <em>Run as <a href="/questions/tagged/junit" class="post-tag" title="show questions tagged 'junit'" rel="tag">junit</a> Test</em>), not for commandline runs like <code>ant</code> or <code>maven</code>.</p> |
9,570,642 | Send SMS programmatically, without the SMS composer window | <p>Until yesterday I thought that it was not possible to send background SMS without using the IOS SMS interface (Which many people here assure also). However, today I downloaded a new app called SmartSender, which schedules your SMS and then sends it automatically.</p>
<p>I tested it and the SMS is not actually sent on background, but a local notification appears and when you click on it to bring app to foreground, the SMS is sent automatically.</p>
<p>How could this be achieved?</p>
<p>Maybe Apple approved the app because the interface is very clear on what you are doing and what you are sending, but how can you send SMS without showing the interface?</p>
<hr>
<p>Update: The scheduled SMS appear on my phone Messages app as sent, so I don't think that they are using another service to send SMS, also the receiver phone is indicated that the SMS was sent from my phone.</p>
<hr>
<p>Update 2: OK I'm using and watching the app doing this, so IT IS POSSIBLE without showing the default interface, I'm not asking whether this can be done or not. I am using it with all internet connections turned OFF, and the message is sent from MY PHONE so it appears on the MESSAGES APP. So the app is not using any third party service.</p>
<hr>
<p>Update 3: I will accept my own answer, in fact it is not possible; however it was when the question was answered. The App in question has now specified in its description that it won't work in iOS 6, so I think Apple patched some bug that could be exploited to achieve this functionality.</p> | 13,143,305 | 6 | 5 | null | 2012-03-05 16:56:28.777 UTC | 9 | 2014-11-26 13:32:25 UTC | 2012-11-25 18:49:05.583 UTC | null | 815,724 | null | 505,152 | null | 1 | 15 | iphone|interface|sms | 25,944 | <p>In fact it is not possible; however it was when the question was answered. </p>
<p>The App in question has now specified in its description that it won't work under IOS 6, so I think apple patched some bug that could be exploited to achieve this functionality.</p> |
18,372,961 | How to search a file in PhpStorm? | <ol>
<li><p>Eclipse has this feature where you can <em>search any file in your folder</em>. Is there any such feature in PhpStorm?</p></li>
<li><p>Is there a shortcut for indentation and how can I customize that?</p></li>
</ol>
<p>Googled it, but no results.</p> | 18,373,397 | 5 | 5 | null | 2013-08-22 06:16:18.247 UTC | 11 | 2019-06-14 10:04:36.917 UTC | 2016-04-20 04:18:35.537 UTC | null | 1,402,846 | null | 2,463,734 | null | 1 | 87 | php|phpstorm | 88,647 | <p>From the Menu of PHPStorm Choose <strong>Navigate</strong> -> <strong>File</strong> or use the shortcut <kbd>ALT</kbd>+<kbd>SHIFT</kbd>+<kbd>O</kbd> or <kbd>CMD</kbd>+<kbd>SHIFT</kbd>+<kbd>O</kbd> or <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>N</kbd> (as per the edit). Type the required file name you want to search. Done.</p>
<p><strong>Screenshot for your understanding.</strong></p>
<p><img src="https://i.stack.imgur.com/jhoKy.png" alt="enter image description here"></p> |
18,759,206 | How to add subview inside UIAlertView for iOS 7? | <p>I am having an application on iTunes store which displays some <code>UILabel</code> and <code>UIWebView</code> on <code>UIAlertView</code>. According to session video, <code>addSubView</code> for <code>UIAlertView</code> will not work. They have talked about <code>ContentView</code>. But in the GM Seeds SDK, I could not find that property and there seems to be no other way.</p>
<p>The only thing I can do is to create a custom subclass of <code>UIView</code> and make it work like <code>UIAertView</code>. Can you suggest any other simple solution?</p>
<p>Thanks for the help.</p> | 21,067,447 | 6 | 4 | null | 2013-09-12 08:28:32.893 UTC | 15 | 2014-11-04 20:27:30.117 UTC | 2014-07-20 15:04:36.35 UTC | null | 2,792,531 | null | 1,168,908 | null | 1 | 22 | ios|objective-c|ios7|uialertview | 41,461 | <p>You can really change <em>accessoryView</em> to <em>customContentView</em> in iOS7 (and it seems that in iOS8 as well) UIAlertView</p>
<pre><code>[alertView setValue:customContentView forKey:@"accessoryView"];
</code></pre>
<p>Try this code:</p>
<pre><code>UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"TEST" message:@"subview" delegate:nil cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
[av setValue:v forKey:@"accessoryView"];
v.backgroundColor = [UIColor yellowColor];
[av show];
</code></pre>
<p>Remember that you need set custom <em>accessoryView</em> before the call <em>[alertView show]</em></p>
<p><img src="https://i.stack.imgur.com/Iljbt.png" alt="enter image description here"></p> |
18,406,369 | Qt: can't find -lGL error | <p>I just reinstalled QtCreator, created new project (<em>Qt Application</em>) an got this after compilation: </p>
<pre><code>/usr/bin/ld: **cannot find -lGL**
collect2: error: ld returned 1 exit status
make: *** [untitled1] Error 1
18:07:41: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project untitled1 (kit: Desktop Qt 5.1.0 GCC 32bit)
When executing step 'Make'
</code></pre>
<p>(<em>Project is empty, I did'n commit any changes</em>)</p>
<blockquote>
<p>Qt Creator 2.7.2<br>
Based on Qt 5.1.0 (32 bit)<br>
Ubuntu 13.04</p>
</blockquote>
<p>How do I solve this problem?</p> | 18,503,519 | 8 | 3 | null | 2013-08-23 15:18:28.483 UTC | 32 | 2020-05-16 08:23:07.037 UTC | 2014-04-21 06:45:37.85 UTC | null | 2,682,142 | null | 1,953,342 | null | 1 | 122 | c++|qt|compiler-construction|qt-creator|ubuntu-13.04 | 103,995 | <p>You should install package "libgl1-mesa-dev":</p>
<pre><code>sudo apt install libgl1-mesa-dev
</code></pre> |
15,422,527 | Best practices: how do you list required dependencies in your setup.py? | <p>This is how I do it currently:</p>
<pre><code>import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
requires = [
'pyramid',
'pyramid_debugtoolbar',
'waitress',
'requests',
'mock',
'gunicorn',
'mongoengine',
]
setup(name='repoapi',
version='0.0',
description='repoapi',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=requires,
test_suite="repoapi",
entry_points="""\
[paste.app_factory]
main = repoapi:main
""",
)
</code></pre>
<p>Is this an okay way? I have some troubles. For example, for pyramid, I cannot use the system-wide nosetests plugin to run tests. I need to install <code>pyramid</code> in the global python site-packages!</p>
<p>But I don't want that. So I must install nose in the virtualenv of this project. But I don't want it to be a dependency. I don't feel like it should belong to <code>requires</code>. It isn't. Yet, I also don't want to install by hand all the time. Yeah I know I have a lot of I don't want to do this and that...</p>
<p>But how would you solve that? I don't want to tamper the global python site-packages, but I want to install nose as part of the virtualenv.</p>
<p>Also, pip install requirement files. It's slightly more accurate because I don't need to specify the version manually and I don't need to be afraid of updating setup.py manually. Just throw <code>pip freeze > file.txt</code> and done.</p>
<p>However, pip can return garbage because we throw garbage packages into virtualenv. </p>
<p>So many blades. What's the best practice? How do you deal with these issues? </p>
<p>Maybe I missed it, but <a href="https://github.com/django/django/blob/master/setup.py" rel="noreferrer">https://github.com/django/django/blob/master/setup.py</a>, how did Django do it?</p> | 15,422,703 | 2 | 1 | null | 2013-03-15 00:09:33.307 UTC | 12 | 2020-04-16 11:09:16.363 UTC | 2018-01-18 10:22:09.683 UTC | null | 509,706 | null | 230,884 | null | 1 | 59 | python | 42,185 | <p>You can split up your requirements into "install" dependencies and "test" dependencies like this:</p>
<pre><code>import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
install_requires = [
'pyramid',
'pyramid_debugtoolbar',
'waitress',
'requests',
'gunicorn',
'mongoengine',
]
tests_require = [
'mock',
'nose',
]
setup(name='repoapi',
...
install_requires=install_requires,
tests_require=tests_require,
test_suite="nose.collector",
...
)
</code></pre>
<p>This way, when someone installs the package, only the "install" dependencies are installed. So, if someone only wants to use the package (and they aren't interested in running the tests), then they don't have to install the test dependencies. </p>
<p>When you do want to run the tests, you can use this:</p>
<pre><code>$ python setup.py test
</code></pre>
<p>Per the <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html?highlight=tests_require#new-and-changed-setup-keywords" rel="noreferrer">docs</a>:</p>
<blockquote>
<p>Note that these required projects will not be installed on the system where the tests are run, but only downloaded to the project’s setup directory if they’re not already installed locally.</p>
</blockquote>
<p>Once the "test" dependencies are in place, then it will run the "test_suite" command. Since you mentioned nose as your preferred test runner, I showed how you <a href="https://nose.readthedocs.org/en/latest/setuptools_integration.html" rel="noreferrer">use "nose.collector"</a> to configure that.</p>
<p>Incidentally, the Django setup.py is not the cleanest example for understanding the basics of setuptools. I think the <a href="https://github.com/getsentry/sentry/blob/master/setup.py" rel="noreferrer">Sentry setup.py</a> is a better example to learn from.</p> |
15,315,452 | Selecting with complex criteria from pandas.DataFrame | <p>For example I have simple DF:</p>
<pre><code>import pandas as pd
from random import randint
df = pd.DataFrame({'A': [randint(1, 9) for x in range(10)],
'B': [randint(1, 9)*10 for x in range(10)],
'C': [randint(1, 9)*100 for x in range(10)]})
</code></pre>
<p>Can I select values from 'A' for which corresponding values for 'B' will be greater than 50, and for 'C' - not equal to 900, using methods and idioms of Pandas?</p> | 15,315,507 | 5 | 2 | null | 2013-03-09 20:17:49.17 UTC | 147 | 2022-07-22 01:28:55.677 UTC | 2022-07-22 01:28:55.677 UTC | null | 19,123,103 | null | 1,818,608 | null | 1 | 327 | python|pandas | 833,481 | <p>Sure! Setup:</p>
<pre><code>>>> import pandas as pd
>>> from random import randint
>>> df = pd.DataFrame({'A': [randint(1, 9) for x in range(10)],
'B': [randint(1, 9)*10 for x in range(10)],
'C': [randint(1, 9)*100 for x in range(10)]})
>>> df
A B C
0 9 40 300
1 9 70 700
2 5 70 900
3 8 80 900
4 7 50 200
5 9 30 900
6 2 80 700
7 2 80 400
8 5 80 300
9 7 70 800
</code></pre>
<p>We can apply column operations and get boolean Series objects:</p>
<pre><code>>>> df["B"] > 50
0 False
1 True
2 True
3 True
4 False
5 False
6 True
7 True
8 True
9 True
Name: B
>>> (df["B"] > 50) & (df["C"] == 900)
0 False
1 False
2 True
3 True
4 False
5 False
6 False
7 False
8 False
9 False
</code></pre>
<p>[Update, to switch to new-style <code>.loc</code>]:</p>
<p>And then we can use these to index into the object. For read access, you can chain indices:</p>
<pre><code>>>> df["A"][(df["B"] > 50) & (df["C"] == 900)]
2 5
3 8
Name: A, dtype: int64
</code></pre>
<p>but you can get yourself into trouble because of the difference between a view and a copy doing this for write access. You can use <code>.loc</code> instead:</p>
<pre><code>>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"]
2 5
3 8
Name: A, dtype: int64
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"].values
array([5, 8], dtype=int64)
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"] *= 1000
>>> df
A B C
0 9 40 300
1 9 70 700
2 5000 70 900
3 8000 80 900
4 7 50 200
5 9 30 900
6 2 80 700
7 2 80 400
8 5 80 300
9 7 70 800
</code></pre>
<p>Note that I accidentally typed <code>== 900</code> and not <code>!= 900</code>, or <code>~(df["C"] == 900)</code>, but I'm too lazy to fix it. Exercise for the reader. :^)</p> |
28,177,917 | Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined | <p>I am trying to grab a webpage and load into a bootstrap 2.3.2 popover. So far I have:</p>
<pre><code>$.ajax({
type: "POST",
url: "AjaxUpdate/getHtml",
data: {
u: 'http://stackoverflow.com'
},
dataType: 'html',
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(jqXHR, textStatus, errorThrown);
}
}).done(function(html) {
console.log(' here is the html ' + html);
$link = $('<a href="myreference.html" data-html="true" data-bind="popover"'
+ ' data-content="' + html + '">');
console.log('$link', $link);
$(this).html($link);
// Trigger the popover to open
$link = $(this).find('a');
$link.popover("show");
</code></pre>
<p>When I activate this code I get the error:</p>
<blockquote>
<p>Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined</p>
</blockquote>
<p>What is the problem here and how can I fix it?</p>
<p><kbd><strong><a href="http://jsfiddle.net/kc11/q3vr5t00/2/">jsfiddle</a></strong></kbd></p> | 28,179,245 | 3 | 2 | null | 2015-01-27 18:56:06.44 UTC | 7 | 2021-04-23 09:39:57.847 UTC | 2015-01-27 21:10:23.663 UTC | null | 1,960,455 | null | 1,592,380 | null | 1 | 67 | javascript|jquery|twitter-bootstrap | 99,295 | <p>The reason for the error is the <code>$(this).html($link);</code> in your <code>.done()</code> callback.</p>
<p><code>this</code> in the callback refers to the <code>[...]object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax)[...]</code> and not to the <code>$(".btn.btn-navbar")</code> (Or whatever you expect where it should refer to).</p>
<p>The error is thrown because jQuery will internally call <code>.createDocumentFragment()</code> on the <code>ownerDocument</code> of object you pass with <code>this</code> when you execute <code>$(this).html($link);</code> but in your code the <code>this</code> is not a DOMElement, and does not have a <code>ownerDocument</code>. Because of that <code>ownerDocument</code> is <code>undefined</code> and thats the reason why <code>createDocumentFragment</code> is called on <code>undefined</code>.</p>
<p>You either need to use the <a href="https://api.jquery.com/jquery.ajax/" rel="noreferrer"><code>context</code></a> option for your <code>ajax</code> request. Or you need to save a <em>reference</em> to the DOMElement you want to change in a variable that you can access in the callback.</p> |
7,837,330 | Generic one-to-one relation in Django | <p>I need to set up one-to-one relation which must also be generic. May be you can advice me a better design. So far I came up to the following models</p>
<pre><code>class Event(models.Model):
# skip event related fields...
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = ('content_type', 'object_id')
class Action1(models.Model):
# skip action1 related fields...
events = generic.GenericRelation(Event, content_type_field='content_type', object_id_field='object_id')
@property
def event(self):
return self.events.get() # <<<<<< Is this reasonable?
class Action2(models.Model):...
</code></pre>
<p>In Django Admin in event list I want to collect all actions, and from there I want go to admin pages for actions. Is it possible to avoid creating <code>event</code> property in the action models? Is there a better solution? It would be nice to combine the field <code>events</code> and the property <code>event</code> in a single definition. The project I am working with uses Django 1.1</p> | 9,295,723 | 2 | 1 | null | 2011-10-20 14:18:48.473 UTC | 4 | 2022-06-03 19:20:17.91 UTC | 2011-10-23 18:20:24.7 UTC | null | 179,581 | null | 179,581 | null | 1 | 28 | python|django|django-models|django-admin|one-to-one | 8,082 | <p>I recently <a href="https://stackoverflow.com/questions/9199000/reversing-a-unique-generic-foreign-key-and-returning-an-object-as-opposed-to-a">came across this problem</a>. What you have done is fine, but you can generalise it a little bit more by creating a mixin that reverses the relationship transparently:</p>
<pre><code>class Event(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = ('content_type', 'object_id')
class EventMixin(object):
@property
def get_event(self):
ctype = ContentType.objects.get_for_model(self.__class__)
try:
event = Event.objects.get(content_type__pk = ctype.id, object_id=self.id)
except:
return None
return event
class Action1(EventMixin, models.Model):
# Don't need to mess up the models fields (make sure the mixing it placed before models.Model)
...
</code></pre>
<p>and </p>
<pre><code>action = Action1.object.get(id=1)
event = action.get_event
</code></pre>
<p>You might want to add caching to the reverse relationship too</p> |
9,642,205 | How to force a script reload and re-execute? | <p>I have a page that is loading a script from a third party (news feed). The <code>src</code> url for the script is assigned dynamically on load up (per third party code).</p>
<pre><code><div id="div1287">
<!-- dynamically-generated elements will go here. -->
</div>
<script id="script0348710783" type="javascript/text">
</script>
<script type="javascript/text">
document.getElementById('script0348710783').src='http://oneBigHairyURL';
</script>
</code></pre>
<p>The script loaded from <code>http://oneBigHairyURL</code> then creates and loads elements with the various stuff from the news feed, with pretty formatting, etc. into <code>div1287</code> (the Id "div1287" is passed in <code>http://oneBigHairyURL</code> so the script knows where to load the content).</p>
<p>The only problem is, it only loads it once. I'd like it to reload (and thus display new content) every n seconds.</p>
<p>So, I thought I'd try this:</p>
<pre><code><div id="div1287">
<!-- dynamically-generated elements will go here. -->
</div>
<script id="script0348710783" type="javascript/text">
</script>
<script type="javascript/text">
loadItUp=function() {
alert('loading...');
var divElement = document.getElementById('div1287');
var scrElement = document.getElementById('script0348710783');
divElement.innerHTML='';
scrElement.innerHTML='';
scrElement.src='';
scrElement.src='http://oneBigHairyURL';
setTimeout(loadItUp, 10000);
};
loadItUp();
</script>
</code></pre>
<p>I get the alert, the div clears, but no dynamically-generated HTML is reloaded to it.</p>
<p>Any idea what I'm doing wrong?</p> | 9,642,359 | 6 | 8 | null | 2012-03-09 23:10:28.697 UTC | 29 | 2022-05-19 19:38:18.317 UTC | 2012-03-09 23:19:55.59 UTC | null | 751,484 | null | 751,484 | null | 1 | 105 | javascript|html|feed|script-tag | 242,682 | <p>How about adding a new script tag to <head> with the script to (re)load? Something like below:</p>
<pre><code><script>
function load_js()
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.src= 'source_file.js';
head.appendChild(script);
}
load_js();
</script>
</code></pre>
<p>The main point is inserting a new script tag -- you can remove the old one without consequence. You may need to add a timestamp to the query string if you have caching issues.</p> |
31,176,592 | How to scale an image to cover entire parent div? | <p><a href="http://jsfiddle.net/Log82brL/15/" rel="nofollow noreferrer">http://jsfiddle.net/Log82brL/15/</a></p>
<p>This <code><img></code> isn't shrink wrapping as I would expect with <code>min-width:100%</code></p>
<p>I'm trying to shrink the <code><img></code> until either height or width matches the container</p>
<p>Click anywhere in the <code><iframe></code> to toggle container shapes</p>
<p>Please try to edit the <code><img></code> CSS:</p>
<ol>
<li>MAINTAIN ASPECT RATIO</li>
<li>COVER ENTIRE SURFACE AREA OF CONTAINER DIV</li>
<li><strong>ONLY EDIT THE IMAGE</strong></li>
</ol>
<p>My question is specifically: scale an <code><img></code> to maintain aspect ratio but cover the entire surface of parent <code><div></code> even as the parent <code><div></code> resizes.</p>
<p>Maybe I could somehow use css flex box-layout or something? Maybe a transform?</p> | 31,355,127 | 12 | 7 | null | 2015-07-02 05:57:36.63 UTC | 6 | 2022-08-31 15:26:22.58 UTC | 2022-08-31 15:26:22.58 UTC | null | 1,264,804 | null | 1,487,102 | null | 1 | 29 | javascript|html|image|css | 32,562 | <p><a href="http://jsfiddle.net/Log82brL/7/" rel="noreferrer">http://jsfiddle.net/Log82brL/7/</a></p>
<pre><code>#img {
width: 100%;
height: 100%;
object-fit: cover;
}
</code></pre>
<p>object-fit: cover allows the replaced content is sized to maintain its aspect ratio while filling the element’s entire content box: its concrete object size is resolved as a cover constraint against the element’s used width and height.</p> |
5,412,019 | How to get the last month data and month to date data | <p>Need help in writing the query to get the last month data as well as month to date data.</p>
<p>If today's date is Mar 23 2011, I need to retrieve the data from last month and the data till todays date(means Mar 23 2011). </p>
<p>If date is Apr 3 2011, data should consists of March month data and the data till Apr 3rd 2011. </p>
<p>Thanks,</p>
<p>Shahsra</p> | 5,412,138 | 4 | 0 | null | 2011-03-23 21:45:22.55 UTC | 7 | 2020-09-21 03:33:14.673 UTC | 2011-03-23 21:49:47.443 UTC | null | 78,522 | null | 543,509 | null | 1 | 11 | sql|sql-server|tsql|sql-server-2008 | 56,452 | <pre><code>Today including time info : getdate()
Today without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 0)
Tomorrow without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Beginning of current month : DATEADD(month, datediff(month, 0, getdate()), 0)
Beginning of last month : DATEADD(month, datediff(month, 0, getdate())-1, 0)
</code></pre>
<p>so most likely</p>
<pre><code>WHERE dateColumn >= DATEADD(month, datediff(month, 0, getdate())-1, 0)
AND dateColumn < DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
</code></pre> |
4,935,655 | How to trap the backspace key using jQuery? | <p>It does not appear the jQuery keyup, keydown, or keypress methods are fired when the backspace key is pressed. How would I trap the pressing of the backspace key?</p> | 4,936,565 | 4 | 4 | null | 2011-02-08 16:36:00.867 UTC | 7 | 2015-09-04 18:21:19.79 UTC | null | null | null | null | 94,508 | null | 1 | 36 | jquery | 123,713 | <p>try this one :</p>
<pre><code> $('html').keyup(function(e){if(e.keyCode == 8)alert('backspace trapped')})
</code></pre> |
5,272,216 | Is it possible to install both 32bit and 64bit Java on Windows 7? | <p>Is it possible to install both 32bit and 64bit Java on Windows 7?</p>
<p>I have some applications that I can run under 64bit, but there are some that only run under 32bit.</p> | 5,272,255 | 4 | 4 | null | 2011-03-11 11:17:19.22 UTC | 17 | 2017-04-20 13:29:18.66 UTC | 2012-12-18 03:07:04.67 UTC | null | 815,724 | null | 229,510 | null | 1 | 82 | windows-7|32bit-64bit|java | 188,329 | <p>Yes, it is absolutely no problem. You could even have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.</p>
<p>In fact, i have such a setup myself.</p> |
5,384,847 | Adding an item to an associative array | <pre class="lang-php prettyprint-override"><code>//go through each question
foreach($file_data as $value) {
//separate the string by pipes and place in variables
list($category, $question) = explode('|', $value);
//place in assoc array
$data = array($category => $question);
print_r($data);
}
</code></pre>
<p>This is not working as it replaces the value of data. How can I have it add an associative value each loop though? <code>$file_data</code> is an array of data that has a dynamic size.</p> | 5,384,855 | 5 | 0 | null | 2011-03-21 23:11:23.09 UTC | 20 | 2022-09-19 05:50:18.07 UTC | 2021-02-03 09:31:28.813 UTC | null | 11,044,542 | null | 185,672 | null | 1 | 105 | php|arrays|associative-array | 287,788 | <p>I think you want <code>$data[$category] = $question;</code></p>
<p>Or in case you want an array that maps categories to array of questions:</p>
<pre><code>$data = array();
foreach($file_data as $value) {
list($category, $question) = explode('|', $value, 2);
if(!isset($data[$category])) {
$data[$category] = array();
}
$data[$category][] = $question;
}
print_r($data);
</code></pre> |
5,335,745 | How do I handle multiple kinds of missingness in R? | <p>Many surveys have codes for different kinds of missingness. For instance, a codebook might indicate:</p>
<blockquote>
<p>0-99 Data</p>
<p>-1 Question not asked</p>
<p>-5 Do not know</p>
<p>-7 Refused to respond</p>
<p>-9 Module not asked</p>
</blockquote>
<p>Stata has a beautiful facility for handling these multiple kinds of missingness, in that it allows you to assign a generic . to missing data, but more specific kinds of missingness (.a, .b, .c, ..., .z) are allowed as well. All the commands which look at missingness report answers for all the missing entries however specified, but you can sort out the various kinds of missingness later on as well. This is particularly helpful when you believe that refusal to respond has different implications for the imputation strategy than does question not asked.</p>
<p>I have never run across such a facility in R, but I would really like to have this capability. Are there any ways of marking several different types of NA? I could imagine creating more data (either a vector of length nrow(my.data.frame) containing the types of missingness, or a more compact index of which rows had what types of missingness), but that seems pretty unwieldy.</p> | 5,341,302 | 6 | 0 | null | 2011-03-17 06:43:11.693 UTC | 12 | 2013-08-25 17:03:06.22 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 636,656 | null | 1 | 19 | r|data-structures|stata|survey|missing-data | 1,660 | <p>I know what you look for, and that is not implemented in R. I have no knowledge of a package where that is implemented, but it's not too difficult to code it yourself.</p>
<p>A workable way is to add a dataframe to the attributes, containing the codes. To prevent doubling the whole dataframe and save space, I'd add the indices in that dataframe instead of reconstructing a complete dataframe.</p>
<p>eg :</p>
<pre><code>NACode <- function(x,code){
Df <- sapply(x,function(i){
i[i %in% code] <- NA
i
})
id <- which(is.na(Df))
rowid <- id %% nrow(x)
colid <- id %/% nrow(x) + 1
NAdf <- data.frame(
id,rowid,colid,
value = as.matrix(x)[id]
)
Df <- as.data.frame(Df)
attr(Df,"NAcode") <- NAdf
Df
}
</code></pre>
<p>This allows to do :</p>
<pre><code>> Df <- data.frame(A = 1:10,B=c(1:5,-1,-2,-3,9,10) )
> code <- list("Missing"=-1,"Not Answered"=-2,"Don't know"=-3)
> DfwithNA <- NACode(Df,code)
> str(DfwithNA)
'data.frame': 10 obs. of 2 variables:
$ A: num 1 2 3 4 5 6 7 8 9 10
$ B: num 1 2 3 4 5 NA NA NA 9 10
- attr(*, "NAcode")='data.frame': 3 obs. of 4 variables:
..$ id : int 16 17 18
..$ rowid: int 6 7 8
..$ colid: num 2 2 2
..$ value: num -1 -2 -3
</code></pre>
<p>The function can also be adjusted to add an extra attribute that gives you the label for the different values, see also <a href="https://stackoverflow.com/questions/5333280/what-is-the-official-way-of-creating-structuring-maintaining-and-updating-dat">this question</a>. You could backtransform by :</p>
<pre><code>ChangeNAToCode <- function(x,code){
NAval <- attr(x,"NAcode")
for(i in which(NAval$value %in% code))
x[NAval$rowid[i],NAval$colid[i]] <- NAval$value[i]
x
}
> Dfback <- ChangeNAToCode(DfwithNA,c(-2,-3))
> str(Dfback)
'data.frame': 10 obs. of 2 variables:
$ A: num 1 2 3 4 5 6 7 8 9 10
$ B: num 1 2 3 4 5 NA -2 -3 9 10
- attr(*, "NAcode")='data.frame': 3 obs. of 4 variables:
..$ id : int 16 17 18
..$ rowid: int 6 7 8
..$ colid: num 2 2 2
..$ value: num -1 -2 -3
</code></pre>
<p>This allows to change only the codes you want, if that ever is necessary. The function can be adapted to return all codes when no argument is given. Similar functions can be constructed to extract data based on the code, I guess you can figure that one out yourself.</p>
<p>But in one line : using attributes and indices might be a nice way of doing it.</p> |
12,148,281 | Mask String with characters | <p>Hey guy's I tried to find a way to hide a string, but the code that I found just work with my application... Is there a way to hide the characters in a string with either <code>*</code> or <code>-</code> and if there is can someone please explain </p> | 12,148,388 | 5 | 4 | null | 2012-08-27 19:25:36.553 UTC | 2 | 2020-03-12 02:47:10.287 UTC | 2020-02-21 14:28:37.987 UTC | null | 6,904,888 | null | 1,617,498 | null | 1 | 8 | java | 46,332 | <p>Is this for making a password? Consider the following:</p>
<pre><code>class Password {
final String password; // the string to mask
Password(String password) { this.password = password; } // needs null protection
// allow this to be equal to any string
// reconsider this approach if adding it to a map or something?
public boolean equals(Object o) {
return password.equals(o);
}
// we don't need anything special that the string doesnt
public int hashCode() { return password.hashCode(); }
// send stars if anyone asks to see the string - consider sending just
// "******" instead of the length, that way you don't reveal the password's length
// which might be protected information
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; < password.length(); i++)
sb.append("*");
return sb.toString();
}
}
</code></pre>
<p>Or for the hangman approach</p>
<pre><code>class Hangman {
final String word;
final BitSet revealed;
public Hangman(String word) {
this.word = word;
this.revealed = new BitSet(word.length());
reveal(' ');
reveal('-');
}
public void reveal(char c) {
for(int i = 0; i < word.length; i++) {
if(word.charAt(i) == c) revealed.set(i);
}
}
public boolean solve(String guess) {
return word.equals(guess);
}
public String toString() {
StringBuilder sb = new StringBuilder(word.length());
for(int i = 0; i < word.length; i++) {
char c = revealed.isSet(i) ? word.charAt(i) : "*";
}
return sb.toString();
}
}
</code></pre> |
12,627,422 | Custom Texture Shader in Three.js | <p>I'm just looking to create a very simple Fragment Shader that draws a specified texture to the mesh. I've looked at a handful of custom fragment shaders that accomplished the same and built my own shaders and supporting JS code around it. However, it's just not working. Here's a working abstraction of the code I'm trying to run:</p>
<p><strong>Vertex Shader</strong></p>
<pre class="lang-js prettyprint-override"><code><script id="vertexShader" type="x-shader/x-vertex">
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix *
modelViewMatrix *
vec4(position,1.0);
}
</script>
</code></pre>
<p><strong>Fragment Shader</strong></p>
<pre class="lang-js prettyprint-override"><code><script id="fragmentShader" type="x-shader/x-fragment">
uniform sampler2D texture1;
varying vec2 vUv;
void main() {
gl_FragColor = texture2D(texture1, vUv); // Displays Nothing
//gl_FragColor = vec4(0.5, 0.2, 1.0, 1.0); // Works; Displays Flat Color
}
</script>
</code></pre>
<p><strong>Scene Code</strong></p>
<pre class="lang-js prettyprint-override"><code><script>
// Initialize WebGL Renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
var canvas = document.getElementById('canvas').appendChild(renderer.domElement);
// Initialize Scenes
var scene = new THREE.Scene();
// Initialize Camera
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 100);
camera.position.z = 10;
// Create Light
var light = new THREE.PointLight(0xFFFFFF);
light.position.set(0, 0, 500);
scene.add(light);
// Create Ball
var vertShader = document.getElementById('vertexShader').innerHTML;
var fragShader = document.getElementById('fragmentShader').innerHTML;
var uniforms = {
texture1: { type: 't', value: 0, texture: THREE.ImageUtils.loadTexture( 'texture.jpg' ) }
};
var material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: vertShader,
fragmentShader: fragShader
});
var ball = new THREE.Mesh(new THREE.SphereGeometry(1, 50, 50), material);
scene.add(ball);
// Render the Scene
renderer.render(scene, camera);
</script>
</code></pre>
<p><code>texture.jpg</code> exists, and displays when mapped to a <code>MeshLambertMaterial</code>. When switching my fragment shader to a simple color (Commented out in code) it properly displays the ball.</p>
<p>Running this displays nothing at all. I don't get any errors, the ball just doesn't appear at all.</p>
<p>I know I must be doing something fundamentally wrong, but I've been looking over the same examples in which this code seems to work for a couple days now and I feel like I'm bashing my head against a wall. Any help would be appreciated!</p>
<p>Edit: I am using Three.js Revision 51</p> | 12,628,857 | 1 | 1 | null | 2012-09-27 18:00:35.12 UTC | 12 | 2018-08-08 19:53:54.177 UTC | 2015-08-16 02:32:20.157 UTC | null | 1,704,159 | null | 1,704,159 | null | 1 | 34 | shader|textures|three.js|fragment-shader | 34,062 | <p>You are still using the old syntax for uniforms</p>
<pre><code>var uniforms = {
texture1: {
type: "t",
value: 0,
texture: THREE.ImageUtils.loadTexture("texture.jpg")
}
};
</code></pre>
<p>This is the new syntax </p>
<pre><code>var uniforms = {
texture1: { type: "t", value: THREE.ImageUtils.loadTexture( "texture.jpg" ) }
};
</code></pre> |
12,400,071 | ServiceStack: RESTful Resource Versioning | <p>I've taken a read to the <a href="https://github.com/ServiceStack/ServiceStack/wiki/Advantages-of-message-based-web-services">Advantages of message based web services</a> article and am wondering if there is there a recommended style/practice to versioning Restful resources in ServiceStack? The different versions could render different responses or have different input parameters in the Request DTO.</p>
<p>I'm leaning toward a URL type versioning (i.e /v1/movies/{Id}), but I have seen other practices that set the version in the HTTP headers (i.e Content-Type: application/vnd.company.myapp-v2). </p>
<p>I'm hoping a way that works with the metadata page but not so much a requirement as I've noticed simply using folder structure/ namespacing works fine when rendering routes.</p>
<p>For example (this doesn't render right in the metadata page but performs properly if you know the direct route/url)</p>
<ul>
<li>/v1/movies/{id}</li>
<li>/v1.1/movies/{id}</li>
</ul>
<p>Code</p>
<pre><code>namespace Samples.Movies.Operations.v1_1
{
[Route("/v1.1/Movies", "GET")]
public class Movies
{
...
}
}
namespace Samples.Movies.Operations.v1
{
[Route("/v1/Movies", "GET")]
public class Movies
{
...
}
}
</code></pre>
<p>and corresponding services...</p>
<pre><code>public class MovieService: ServiceBase<Samples.Movies.Operations.v1.Movies>
{
protected override object Run(Samples.Movies.Operations.v1.Movies request)
{
...
}
}
public class MovieService: ServiceBase<Samples.Movies.Operations.v1_1.Movies>
{
protected override object Run(Samples.Movies.Operations.v1_1.Movies request)
{
...
}
}
</code></pre> | 12,413,091 | 3 | 0 | null | 2012-09-13 05:40:28.853 UTC | 38 | 2012-10-17 01:52:17.423 UTC | null | null | null | null | 1,667,502 | null | 1 | 39 | servicestack | 10,589 | <h2>Try to evolve (not re-implement) existing services</h2>
<p>For versioning, you are going to be in for a world of hurt if you try to maintain different static types for different version endpoints. We initially started down this route but as soon as you start to support your first version the development effort to maintain multiple versions of the same service explodes as you will need to either maintain manual mapping of different types which easily leaks out into having to maintain multiple parallel implementations, each coupled to a different versions type - a massive violation of DRY. This is less of an issue for dynamic languages where the same models can easily be re-used by different versions.</p>
<h2>Take advantage of built-in versioning in serializers</h2>
<p>My recommendation is not to explicitly version but take advantage of the versioning capabilities inside the serialization formats. </p>
<p>E.g: you generally don't need to worry about versioning with JSON clients as the versioning capabilities of the <a href="https://github.com/ServiceStack/ServiceStack.Redis/wiki/MigrationsUsingSchemalessNoSql">JSON and JSV Serializers are much more resilient</a>.</p>
<h3>Enhance your existing services defensively</h3>
<p>With XML and DataContract's you can freely add and remove fields without making a breaking change. If you add <code>IExtensibleDataObject</code> to your response DTO's you also have a potential to access data that's not defined on the DTO. My approach to versioning is to program defensively so not to introduce a breaking change, you can verify this is the case with Integration tests using old DTOs. Here are some tips I follow:</p>
<ul>
<li>Never change the type of an existing property - If you need it to be a different type add another property and use the old/existing one to determine the version</li>
<li>Program defensively realize what properties don't exist with older clients so don't make them mandatory.</li>
<li>Keep a single global namespace (only relevant for XML/SOAP endpoints)</li>
</ul>
<p>I do this by using the [assembly] attribute in the <strong>AssemblyInfo.cs</strong> of each of your DTO projects:</p>
<pre><code>[assembly: ContractNamespace("http://schemas.servicestack.net/types",
ClrNamespace = "MyServiceModel.DtoTypes")]
</code></pre>
<p>The assembly attribute saves you from manually specifying explicit namespaces on each DTO, i.e:</p>
<pre><code>namespace MyServiceModel.DtoTypes {
[DataContract(Namespace="http://schemas.servicestack.net/types")]
public class Foo { .. }
}
</code></pre>
<p>If you want to use a different XML namespace than the default above you need to register it with:</p>
<pre><code>SetConfig(new EndpointHostConfig {
WsdlServiceNamespace = "http://schemas.my.org/types"
});
</code></pre>
<h2>Embedding Versioning in DTOs</h2>
<p>Most of the time, if you program defensively and evolve your services gracefully you wont need to know exactly what version a specific client is using as you can infer it from the data that is populated. But in the rare cases your services needs to tweak the behavior based on the specific version of the client, you can embed version information in your DTOs. </p>
<p>With the first release of your DTOs you publish, you can happily create them without any thought of versioning.</p>
<pre><code>class Foo {
string Name;
}
</code></pre>
<p>But maybe for some reason the Form/UI was changed and you no longer wanted the Client to use the ambiguous <strong>Name</strong> variable and you also wanted to track the specific version the client was using:</p>
<pre><code>class Foo {
Foo() {
Version = 1;
}
int Version;
string Name;
string DisplayName;
int Age;
}
</code></pre>
<p>Later it was discussed in a Team meeting, DisplayName wasn't good enough and you should split them out into different fields:</p>
<pre><code>class Foo {
Foo() {
Version = 2;
}
int Version;
string Name;
string DisplayName;
string FirstName;
string LastName;
DateTime? DateOfBirth;
}
</code></pre>
<p>So the current state is that you have 3 different client versions out, with existing calls that look like:</p>
<p>v1 Release:</p>
<pre><code>client.Post(new Foo { Name = "Foo Bar" });
</code></pre>
<p>v2 Release:</p>
<pre><code>client.Post(new Foo { Name="Bar", DisplayName="Foo Bar", Age=18 });
</code></pre>
<p>v3 Release:</p>
<pre><code>client.Post(new Foo { FirstName = "Foo", LastName = "Bar",
DateOfBirth = new DateTime(1994, 01, 01) });
</code></pre>
<p>You can continue to handle these different versions in the same implementation (which will be using the latest v3 version of the DTOs) e.g:</p>
<pre><code>class FooService : Service {
public object Post(Foo request) {
//v1:
request.Version == 0
request.Name == "Foo"
request.DisplayName == null
request.Age = 0
request.DateOfBirth = null
//v2:
request.Version == 2
request.Name == null
request.DisplayName == "Foo Bar"
request.Age = 18
request.DateOfBirth = null
//v3:
request.Version == 3
request.Name == null
request.DisplayName == null
request.FirstName == "Foo"
request.LastName == "Bar"
request.Age = 0
request.DateOfBirth = new DateTime(1994, 01, 01)
}
}
</code></pre> |
12,268,835 | Is it possible to run python SimpleHTTPServer on localhost only? | <p>I have a vpn connection and when I'm running python -m SimpleHTTPServer, it serves on 0.0.0.0:8000, which means it can be accessed via localhost <strong>and</strong> via my real ip.
I don't want robots to scan me and interested that the server will be accessed only via localhost.</p>
<p>Is it possible? </p>
<pre><code>python -m SimpleHTTPServer 127.0.0.1:8000 # doesn't work.
</code></pre>
<p>Any other simple http server which can be executed instantly using the command line is also welcome.</p> | 12,268,922 | 3 | 3 | null | 2012-09-04 17:50:44.63 UTC | 34 | 2018-09-12 17:13:09.367 UTC | 2018-09-12 17:13:09.367 UTC | null | 745,828 | null | 1,639,431 | null | 1 | 100 | python|http|command-line|python-2.x|simplehttpserver | 121,101 | <p>If you read the source you will see that only the port can be overridden on the command line. If you want to change the host it is served on, you will need to implement the <code>test()</code> method of the <code>SimpleHTTPServer</code> and <code>BaseHTTPServer</code> yourself. But that should be really easy.</p>
<p>Here is how you can do it, pretty easily:</p>
<pre><code>import sys
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
def test(HandlerClass=SimpleHTTPRequestHandler,
ServerClass=BaseHTTPServer.HTTPServer):
protocol = "HTTP/1.0"
host = ''
port = 8000
if len(sys.argv) > 1:
arg = sys.argv[1]
if ':' in arg:
host, port = arg.split(':')
port = int(port)
else:
try:
port = int(sys.argv[1])
except:
host = sys.argv[1]
server_address = (host, port)
HandlerClass.protocol_version = protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == "__main__":
test()
</code></pre>
<p>And to use it: </p>
<pre><code>> python server.py 127.0.0.1
Serving HTTP on 127.0.0.1 port 8000 ...
> python server.py 127.0.0.1:9000
Serving HTTP on 127.0.0.1 port 9000 ...
> python server.py 8080
Serving HTTP on 0.0.0.0 port 8080 ...
</code></pre> |
24,267,080 | Calling stored procedure using VBA | <p>I am working in Access 2010 user front-end with a Microsoft SQL Server 2008 back-end.</p>
<p>The tables in Access are all linked to the SQL server database.</p>
<p>I have a stored procedure that inserts new values (supplied by the parameters) into a table.</p>
<p>I asked a similar question previously and got a good answer <a href="https://stackoverflow.com/questions/24248870/calling-stored-procedure-while-passing-parameters-from-access-module-in-vba">Calling Stored Procedure while passing parameters from Access Module in VBA</a> </p>
<p>I do not know how to find the information required for making a connection string (ex: I don't know the provider/server name/server address).</p>
<p>I found a question on here that stated "If you already have an Access linked table pointing to the SQL Server database then you can simply use its <code>.Connect</code> string with a DAO.QueryDef object to execute the Stored Procedure" - <a href="https://stackoverflow.com/questions/18664139/connection-string-for-access-to-call-sql-server-stored-procedure">Connection string for Access to call SQL Server stored procedure</a></p>
<p>I tried to implement this code. To pass parameters, I tried using a previous example.</p>
<p>I got the error</p>
<blockquote>
<p>call failed</p>
</blockquote>
<p>at the line <code>Set rst = qdf.OpenRecordset(dbOpenSnapshot)</code> (not to mention my passing parameters code is probably way off). </p>
<pre><code>Set qdf = CurrentDb.CreateQueryDef("")
qdf.Connect = CurrentDb.TableDefs("tblInstrumentInterfaceLog").Connect
qdf.sql = "EXEC dbo.upInsertToInstrumentInterfaceLog"
qdf.ReturnsRecords = True
Set rst = qdf.OpenRecordset(dbOpenSnapshot)
qdf.Parameters.Append qdf.CreateParameter("@BatchID", adVarChar, adParamInput, 60, BatchID)
qdf.Parameters.Append qdf.CreateParameter("@InstrumentName", adVarChar, adParamInput, 60, InstrumentName)
qdf.Parameters.Append qdf.CreateParameter("@FileName", adVarChar, adParamInput, 60, FileName)
qdf.Parameters.Append qdf.CreateParameter("@QueueId", adVarChar, adParamInput, 60, QuenueId)
rst.Close
Set rst = Nothing
Set qdf = Nothing
</code></pre>
<p>Could anyone tell me what could be wrong with my code and why I am getting this error? </p> | 24,269,044 | 2 | 5 | null | 2014-06-17 14:57:31.433 UTC | 7 | 2020-07-08 19:46:10.597 UTC | 2020-07-08 19:46:10.597 UTC | null | 8,422,953 | null | 3,661,943 | null | 1 | 11 | sql-server|vba|ms-access|stored-procedures | 49,508 | <p>Victoria,</p>
<p>You can run a stored procedure using ADO, like below...</p>
<pre><code>Set mobjConn = New ADODB.Connection
mobjConn.Open "your connection string"
Set mobjCmd = New ADODB.Command
With mobjCmd
.ActiveConnection = mobjConn
.CommandText = "your stored procedure"
.CommandType = adCmdStoredProc
.CommandTimeout = 0
.Parameters.Append .CreateParameter("your parameter name", adInteger, adParamInput, , your parameter value)
' repeat as many times as you have parameters
.Execute
End With
</code></pre>
<p>To get your connection string, you can use the line</p>
<pre><code>Debug.Print CurrentDb.TableDefs("tblInstrumentInterfaceLog").Connect
</code></pre>
<p>in the Immediate Window and that should show you a connection string which you can use.</p>
<p>Would you try that and let me know if you have any problems.</p>
<p>Ash</p> |
22,493,723 | Node.js Asynchronous Library Comparison - Q vs Async | <p>I have used <a href="https://github.com/kriskowal/q">kriskowal's Q library</a> for a project (web scraper / human-activity simulator) and have become acquainted with promises, returning them and resolving/rejecting them, and the library's basic asynchronous control flow methods and error-throwing/catching mechanisms have proven essential.</p>
<p>I have encountered some issues though. My <code>promise.then</code> calls and my callbacks have the uncanny tendency to form pyramids. Sometimes it's for scoping reasons, other times it's to guarantee a certain order of events. (I suppose I might be able to fix some of these problems by refactoring, but going forward I want to avoid "callback hell" altogether.) </p>
<p>Also, debugging is very frustrating. I spend a lot of time <code>console.log</code>-ing my way to the source of errors and bugs; after I finally find them I will start throwing errors there and catching them somewhere else with <code>promise.finally</code>, but the process of locating the errors in the first place is arduous.</p>
<p>Also, in my project, <strong>order matters</strong>. I need to do pretty much everything sequentially. Oftentimes I find myself generating arrays of functions that return promises and then chaining them to each other using <code>Array.prototype.reduce</code>, which I don't think I should have to do.</p>
<p>Here is an example of one of my methods that uses this reduction technique:</p>
<pre><code>removeItem: function (itemId) {
var removeRegexp = new RegExp('\\/stock\\.php\\?remove=' + itemId);
return this.getPage('/stock.php')
.then(function (webpage) {
var
pageCount = 5,
promiseFunctions = [],
promiseSequence;
// Create an array of promise-yielding functions that can run sequentially.
_.times(pageCount, function (i) {
var promiseFunction = function () {
var
promise,
path;
if (i === 0) {
promise = Q(webpage);
} else {
path = '/stock.php?p=' + i;
promise = this.getPage(path);
}
return promise.then(function (webpage) {
var
removeMatch = webpage.match(removeRegexp),
removePath;
if (removeMatch !== null) {
removePath = removeitemMatch[0];
return this.getPage(removePath)
.delay(1000)
// Stop calling subsequent promises.
.thenResolve(true);
}
// Don't stop calling subsequent promises.
return false;
}.bind(this));
}.bind(this);
promiseFunctions.push(promiseFunction);
}, this);
// Resolve the promises sequentially but stop early if the item is found.
promiseSequence = promiseFunctions.reduce(function (soFar, promiseFunction, index) {
return soFar.then(function (stop) {
if (stop) {
return true;
} else {
return Q.delay(1000).then(promiseFunction);
}
});
}, Q());
return promiseSequence;
}.bind(this))
.fail(function (onRejected) {
console.log(onRejected);
});
},
</code></pre>
<p>I have other methods that do basically the same thing but which are suffering from much worse indentation woes.</p>
<p>I'm considering refactoring my project using <a href="https://github.com/caolan/async">coalan's async library</a>. It seems similar to Q, but I want to know exactly how they differ. The impression I am getting is that async more "callback-centric" while Q is "promise-centric".</p>
<p><strong>Question:</strong> Given my problems and project requirements, what would I gain and/or lose by using async over Q? How do the libraries compare? (Particularly in terms of executing series of tasks sequentially and debugging/error-handling?)</p> | 26,883,101 | 3 | 7 | null | 2014-03-19 00:11:49.07 UTC | 10 | 2015-12-19 10:47:26.323 UTC | 2014-03-19 01:16:38.32 UTC | null | 1,468,130 | null | 1,468,130 | null | 1 | 28 | javascript|node.js|asynchronous|q | 12,956 | <p>Both libraries are good. I have discovered that they serve separate purposes and can be used in tandem.</p>
<p>Q provides the developer with promise objects, which are future representations of values. Useful for time travelling.</p>
<p>Async provides the developer with asynchronous versions of control structures and aggregate operations.</p>
<p>An example from one attempt at a linter implementation demonstrates a potential unity among libraries:</p>
<pre><code>function lint(files, callback) {
// Function which returns a promise.
var getMerged = merger('.jslintrc'),
// Result objects to invoke callback with.
results = [];
async.each(files, function (file, callback) {
fs.exists(file, function (exists) {
// Future representation of the file's contents.
var contentsPromise,
// Future representation of JSLINT options from .jslintrc files.
optionPromise;
if (!exists) {
callback();
return;
}
contentsPromise = q.nfcall(fs.readFile, file, 'utf8');
optionPromise = getMerged(path.dirname(file));
// Parallelize IO operations.
q.all([contentsPromise, optionPromise])
.spread(function (contents, option) {
var success = JSLINT(contents, option),
errors,
fileResults;
if (!success) {
errors = JSLINT.data().errors;
fileResults = errors.reduce(function (soFar, error) {
if (error === null) {
return soFar;
}
return soFar.concat({
file: file,
error: error
});
}, []);
results = results.concat(fileResults);
}
process.nextTick(callback);
})
.catch(function (error) {
process.nextTick(function () {
callback(error);
});
})
.done();
});
}, function (error) {
results = results.sort(function (a, b) {
return a.file.charCodeAt(0) - b.file.charCodeAt(0);
});
callback(error, results);
});
}
</code></pre>
<p>I want to do something potentially-blocking for each file. So <code>async.each</code> is the obvious choice. I can parallelize <em>related</em> operations <em>per-iteration</em> with <code>q.all</code> and reuse my option values if they apply to 2 or more files.</p>
<p>Here, Async and Q each influence the control flow of the program, and Q represents values resolving to file contents sometime in the future. The libraries work well together. One does not need to "choose one over the other".</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.