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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
165,539 |
iPhone Proximity Sensor
|
<p>Can the iPhone SDK take advantage of the iPhone's proximity sensors? If so, why hasn't anyone taken advantage of them? I could picture a few decent uses.</p>
<p>For example, in a racing game, you could put your finger on the proximity sensor to go instead of taking up screen real-estate with your thumb. Of course though, if this was your only option, then iPod touch users wouldn't be able to use the application.</p>
<p>Does the proximity sensor tell how close you are, or just that something is in front of it?</p>
| 168,561 | 13 | 1 | null |
2008-10-03 03:06:11.55 UTC
| 17 |
2013-07-17 06:46:47.58 UTC
| null | null | null |
Greg
| 13,009 | null | 1 | 20 |
iphone|api|sensors|proximity
| 52,254 |
<p>Assuming you mean the sensor that shuts off the screen when you hold it to your ear, I'm pretty sure that is just an infrared sensor inside the ear speaker. If you start the phone app (you don't have to be making a call) and hold something to cast a shadow over the ear speaker, you can make the display shut off.</p>
<p>When you asked this question it was not accessible via the public API. You can now access the sensor's state via UIDevice's <code>proximityState</code> property. However, it wouldn't be that useful for games, since it is only an on/off thing, not a near/far measure. Plus, it's only available on the iPhone and not the iPod touch.</p>
|
889,967 |
jQuery .load() call doesn't execute JavaScript in loaded HTML file
|
<p>This seems to be a problem related to Safari only. I've tried 4 on Mac and 3 on Windows and am still having no luck.</p>
<p>I'm trying to load an external HTML file and have the JavaScript that is embedded execute.</p>
<p>The code I'm trying to use is this:</p>
<pre><code>$("#myBtn").click(function() {
$("#myDiv").load("trackingCode.html");
});
</code></pre>
<p><code>trackingCode.html</code> looks like this (simple now, but will expand once/if I get this working):</p>
<pre><code><html>
<head>
<title>Tracking HTML File</title>
<script language="javascript" type="text/javascript">
alert("outside the jQuery ready");
$(function() {
alert("inside the jQuery ready");
});
</script>
</head>
<body>
</body>
</html>
</code></pre>
<p>I'm seeing both alert messages in IE (6 & 7) and Firefox (2 & 3). However, I am not able to see the messages in Safari (the last browser that I need to be concerned with - project requirements - please no flame wars).</p>
<p>Any thoughts on why Safari is ignoring the JavaScript in the <code>trackingCode.html</code> file?</p>
<p>Eventually I'd like to be able to pass JavaScript objects to this <code>trackingCode.html</code> file to be used within the jQuery ready call, but I'd like to make sure this is possible in all browsers before I go down that road.</p>
| 889,982 | 13 | 0 | null |
2009-05-20 20:07:50.723 UTC
| 31 |
2020-11-17 15:16:00.823 UTC
|
2017-07-23 15:42:25.09 UTC
| null | 438,581 | null | 8,320 | null | 1 | 85 |
jquery|ajax|safari
| 214,432 |
<p>You are loading an entire HTML page into your div, including the html, head and body tags. What happens if you do the load and just have the opening script, closing script, and JavaScript code in the HTML that you load?</p>
<p>Here is the driver page:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Load of Script</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#myButton").click(function() {
$("#myDiv").load("trackingCode.html");
});
});
</script>
</head>
<body>
<button id="myButton">Click Me</button>
<div id="myDiv"></div>
</body>
</html>
</code></pre>
<p>Here is the contents of trackingCode.html:</p>
<pre><code><script type="text/javascript">
alert("Outside the jQuery ready");
$(function() {
alert("Inside the jQuery ready");
});
</script>
</code></pre>
<p>This works for me in Safari 4.</p>
<p>Update: Added DOCTYPE and html namespace to match the code on my test environment. Tested with Firefox 3.6.13 and example code works.</p>
|
441,196 |
Why Java needs Serializable interface?
|
<p>We work heavily with serialization and having to specify Serializable tag on every object we use is kind of a burden. Especially when it's a 3rd-party class that we can't really change.</p>
<p>The question is: since Serializable is an empty interface and Java provides robust serialization once you add <code>implements Serializable</code> - why didn't they make everything serializable and that's it? </p>
<p>What am I missing?</p>
| 441,346 | 13 | 3 | null |
2009-01-13 22:55:28.077 UTC
| 48 |
2016-07-08 17:39:11.4 UTC
|
2009-01-13 23:00:23.153 UTC
|
Joel Coehoorn
| 3,043 |
uzhin
| 34,161 | null | 1 | 118 |
java|serialization
| 65,363 |
<p>Serialization is fraught with pitfalls. Automatic serialization support of this form makes the class internals part of the public API (which is why javadoc gives you the <a href="http://java.sun.com/javase/6/docs/api/serialized-form.html#java.net.URL" rel="noreferrer">persisted forms of classes</a>).</p>
<p>For long-term persistence, the class must be able to decode this form, which restricts the changes you can make to class design. This breaks encapsulation.</p>
<p>Serialization can also lead to security problems. By being able to serialize any object it has a reference to, a class can access data it would not normally be able to (by parsing the resultant byte data).</p>
<p>There are other issues, such as the serialized form of inner classes not being well defined.</p>
<p>Making all classes serializable would exacerbate these problems. Check out <a href="http://java.sun.com/docs/books/effective/" rel="noreferrer">Effective Java Second Edition</a>, in particular <em>Item 74: Implement Serializable judiciously</em>.</p>
|
16,804 |
Enterprise Reporting Solutions
|
<p>What options are there in the industry for enterprise reporting? I'm currently using SSRS 2005, and know that there is another version coming out with the new release of MSSQL.</p>
<p>But, it seems like it might also be a good time to investigate the market to see what else is out there.</p>
<p>What have you encountered? Do you like it/dislike it? Why?</p>
<p>Thank you.</p>
| 297,256 | 14 | 0 | null |
2008-08-19 19:38:38.64 UTC
| 24 |
2018-02-23 04:43:27.33 UTC
| null | null | null |
Jay Mooney
| 733 | null | 1 | 38 |
sql|reporting-services|reporting
| 7,561 |
<p>I've used Cognos Series 7, Cognos Series 8, Crystal Reports, Business Objects XI R2 WebIntelligence, Reporting Services 2000, Reporting Services 2005, and Reporting Services 2008. Here's my feedback on what I've learned:</p>
<p><strong>Reporting Services 2008/2005/2000</strong></p>
<p>PROS</p>
<ol>
<li><p>Cost: Cheapest enterprise business intelligence solution if you are using MS SQL Server as a back-end. You also have a best-in-class ETL solution at no additional cost if you throw in SSIS.</p></li>
<li><p>Most Flexible: Most flexible reporting solution I've ever used. It has always met all my business needs, particularly in its latest incarnation.</p></li>
<li><p>Easily Scalable: We initially used this as a departmental solution supporting about 20 users. We eventually expanded it to cover a few thousand users. Despite having a really bad quality virtual server located in a remote data center, we were able to scale to about 50-100 concurrent user requests. On good hardware at a consulting gig, I was able to scale it to a larger set of concurrent users without any issues. I've also seen implementations where multiple SSRS servers were deployed in different countries and SSIS was used to synch the data in the back-ends. This allowed for solid performance in a distributed manner at almost no additional cost.</p></li>
<li><p>Source Control Integration: This is CRITICAL to me when developing reports with my business intelligence teams. No other BI suite offers an out-of-box solution for this that I've ever used. Every other platform I used either required purchasing a 3rd party add-in or required you to promote reports between separate development, test, and production environments.</p></li>
<li><p>Analysis Services: I like the tight integration with Analysis Services between SSRS and SSIS. I've read about instances where Oracle and DB2 quotes include installing a SQL Server 2005 Analysis Services server for OLAP cubes.</p></li>
<li><p>Discoverability: No system has better discoverability than SSRS. There are more books, forums, articles, and code sites on SSRS than any other BI suite that I've ever used. If I needed to figuire out how to do something in SSRS, I could almost always find it with a few minutes or hours of work.</p></li>
</ol>
<p>CONS</p>
<ol>
<li><p>IIS Required for SSRS 2005/2000: Older versions of SSRS required installing IIS on the database server. This was not permissible from an internal controls perspective when I worked at a large bank. We eventually implemented SSRS without authorized approval from IT operations and basically asked for forgiveness later. <strong>This is not an issue in SSRS 2008 since IIS is no longer required.</strong></p></li>
<li><p>Report Builder: The web-based report builder was non-existant in SSRS 2000. The web-based report builder in SSRS 2005 was difficult to use and did not have enough functionality. The web-based report builder in SSRS 2008 is definitely better, but it is still too difficult to use for most business users.</p></li>
<li><p>Database Bias: It works best with Microsoft SQL Server. It isn't great with Oracle, DB2, and other back-ends.</p></li>
</ol>
<p><strong>Business Objects XI WebIntelligence</strong></p>
<p>PROS</p>
<ol>
<li><p>Ease of Use: Easiest to use for your average non-BI end-user for developing ad hoc reports.</p></li>
<li><p>Database Agnostic: Definitely a good solution if you expect to use Oracle, DB2, or another database back-end.</p></li>
<li><p>Performant: Very fast performance since most of the page navigations are basically file-system operations instead of database-calls.</p></li>
</ol>
<p>CONS</p>
<ol>
<li><p>Cost: Number one problem. If I want to scale up my implementation of Business Objects from 30 users to 1000 users, then SAP will make certain to charge you a few hundred thousands of dollars. And that's just for the Business Objects licenses. Add in the fact that you will also need database server licenses, you are now talking about a very expensive system. Of course, that could be the personal justification for getting Business Objects: if you can convince management to purchase a very expensive BI system, then you can probably convince management to pay for a large BI department.</p></li>
<li><p>No Source Control: Lack of out-of-the-box source control integration leads to errors in accidentally modifying and deploying old report definitions by mistake. The "work-around" for this is promote reports between environments -- a process that I do NOT like to do since it slows down report development and introduces environmental differences variables.</p></li>
<li><p>No HTML Email Support: You cannot send an HTML email via a schedule. I regularly do this in SSRS. You can buy an expensive 3rd party add-in to do this, but you shouldn't have to spend more money for this functionality.</p></li>
<li><p>Model Bias: Report development requires universes -- basically a data model. That's fine for ad hoc report development, but I prefer to use stored procedures to have full control of performance. I also like to build flat tables that are then queried to avoid costly complex joins during report run-time. It is silly to have to build universes that just contain flat tables that are only used by one report. You shouldn't have to build a model just to query a table. Store procedure support is also not supported out of the box without hacking the SQL Overrides.</p></li>
<li><p>Poor Parameter Support: Parameter support is terrible in BOXI WebIntelligence reports. Although I like the meta-data refresh options for general business users, it just isn't robust enough when trying to setup schedules. I almost always have to clone reports and alter the filters slightly which leads to unnecessary report definition duplication. SSRS beats this hands down, particularly since you can make the value and the label have different values -- unlike BOXI.</p></li>
<li><p>Inadequate Report Linking Support: I wanted to store one report definition in a central folder and then create linked reports for other users. However, I quickly found out end-users needed to have full rights on the parent object to use the object in their own folder. This defeated the entire purpose of using a linked report object. Give me SSRS!</p></li>
<li><p>Separate CMC: Why do you have to launch another application just to manage your object security? Worse, why isn't the functionality identical between CMC and InfoSys? For example, if you want to setup a scheduled report to retry on failed attempts, then you can specify the number of retries and the retry interval in CMC. However, you can't do this in InfoSys and you can't see the information either. InfoSys allows you to setup event-driven schedules and CMC does not support this feature.</p></li>
<li><p>Java Version Dependency: BOXI works great on end-user machines so long as they are running the same version of java as the server. However, once a newer version of java is installed on your machine, things starts to break. We're running Java 1.5 on our BOXI R2 server (the default java client) and almost everyone in the company is on Java 1.6. If you use Java 1.6, then prompts can freeze your IE and FoxFire sessions or crash your report builder unexpectedly.</p></li>
<li><p>Weak Discoverability: Aside from BOB (Business Objects Board), there isn't much out there on the Internet regarding troubleshooting Business Objects problems.</p></li>
</ol>
<p><strong>Cognos Series 8</strong></p>
<p>PROS</p>
<ol>
<li><p>Ease of Use: Although BOXI is easier to use for writing simple reports for general business users, Cognos is a close 2nd in this area.</p></li>
<li><p>Database Agnostic: Like BOXI this is definitely a good solution if you expect to use Oracle, DB2, or another database back-end.</p></li>
<li><p>FrameWork Manager: This is definitely a best-in-class meta-data repository. BOXI's universe builder wishes it was half as good. This tool is well suited to promoting packages across Development, Test, and Production environments.</p></li>
</ol>
<p>CONS</p>
<ol>
<li><p>Cost: Same issue as Business Objects. Similar cost structure. Similar database licensing requirements as well.</p></li>
<li><p>No Source Control: Same issue as Business Objects. I'm not aware of any 3rd party tools that resolve this issue, but they might exist.</p></li>
<li><p>Model Bias: Same issue as Business Objects. Has better support for stored procedures in FrameWork Manager, though.</p></li>
<li><p>Poor Parameter Support: Same issue as Business Objects. Has better support for creating prompt-pages if you can code in Java. Buggy behavior, though, when users click the back-button to return to the prompt-page. SSRS beats this out hands-down.</p></li>
<li><p>Inadequate Error Handling: Error messages in Cognos are nearly impossible to decipher. They generally give you a long negative number and a stack dump as part of the error message. I don't know how many times we "resolved" these error messages by rebuilding reports from scratch. For some reason, it is pretty easy to corrupt a report definition.</p></li>
<li><p>No Discoverability: It is very hard to track down any answers on how to troubleshoot problems or to implement functionality in Cognos. There just isn't adequate community support in Internet facing websites for the products.</p></li>
</ol>
<p>As you can guess from my answer, I believe Microsoft's BI suite is the best platform on the market. However, I must state that most articles I've read on comparisons of BI suites usually do not rate Microsoft's offering as well as SAP's Business Objects and Cognos's Series 8 products. Also, I've also seen Microsoft come out on the bottom in internal reviews of BI Suites in two separate companies after they were review by the reigning CIO's. In both instances, though, it seemed like it all boiled down to wanting to be perceived as a major department that justified a large operating budget.</p>
|
946,993 |
Intellij reformat on file save
|
<p>I remember seeing in either IntelliJ or Eclipse the setting to reformat (cleanup) files whenever they are saved. How do I find it (didn't find it in the settings)</p>
| 28,748,557 | 14 | 0 | null |
2009-06-03 20:22:01.08 UTC
| 115 |
2021-08-03 02:43:59.253 UTC
| null | null | null | null | 11,236 | null | 1 | 421 |
formatting|intellij-idea
| 239,639 |
<p>I suggest the <a href="https://plugins.jetbrains.com/plugin/7642?pr=idea_ce" rel="noreferrer">save actions plugin</a>. It also supports optimize imports and rearrange code.</p>
<p>Works well in combination with the <a href="https://plugins.jetbrains.com/plugin/6546?pr=idea_ce" rel="noreferrer">eclipse formatter plugin</a>.</p>
<p>Search and activate the plugin:</p>
<p><a href="https://i.stack.imgur.com/OxcsB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OxcsB.png" alt="enter image description here"></a></p>
<p>Configure it:</p>
<p><a href="https://i.stack.imgur.com/Hbcx8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Hbcx8.png" alt="enter image description here"></a></p>
<p><strong>Edit:</strong> it seems like it the recent version of Intellij the save action plugin is triggered by the automatic Intellij save. This can be quite annoying when it hits while still editing.</p>
<p>This github issue of the plugin gives a hint to some possible solutions:</p>
<p><a href="https://github.com/dubreuia/intellij-plugin-save-actions/issues/63" rel="noreferrer">https://github.com/dubreuia/intellij-plugin-save-actions/issues/63</a></p>
<p>I actually tried to assign reformat to <kbd>Ctrl</kbd>+<kbd>S</kbd> and it worked fine - saving is done automatically now.</p>
|
1,217,228 |
What is the Java equivalent for LINQ?
|
<p>What is Java equivalent for LINQ?</p>
| 1,217,229 | 34 | 9 | null |
2009-08-01 18:53:26.813 UTC
| 138 |
2019-10-18 22:37:50.313 UTC
|
2014-09-27 06:30:59.25 UTC
| null | 41,956 | null | 14,118 | null | 1 | 868 |
java|linq
| 337,930 |
<p>There is nothing like LINQ for Java.</p>
<p>...</p>
<p><strong>Edit</strong></p>
<p>Now with Java 8 we are introduced to the <a href="http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html" rel="noreferrer">Stream API</a>, this is a similar kind of thing when dealing with collections, but it is not quite the same as Linq.</p>
<p>If it is an ORM you are looking for, like Entity Framework, then you can try <a href="http://hibernate.org/orm/" rel="noreferrer">Hibernate</a></p>
<p>:-)</p>
|
10,564 |
How can I set up an editor to work with Git on Windows?
|
<p>I'm trying out <strong>Git on Windows</strong>. I got to the point of trying "git commit" and I got this error:</p>
<blockquote>
<p>Terminal is dumb but no VISUAL nor
EDITOR defined. Please supply the
message using either -m or -F option.</p>
</blockquote>
<p>So I figured out I need to have an environment variable called EDITOR. No problem. I set it to point to Notepad. That worked, almost. The default commit message opens in Notepad. But Notepad doesn't support bare line feeds. I went out and got <a href="http://notepad-plus.sourceforge.net/uk/site.htm" rel="noreferrer">Notepad++</a>, but I can't figure out how to get Notepad++ set up as the <code>%EDITOR%</code> in such a way that it works with Git as expected.</p>
<p>I'm not married to Notepad++. At this point I don't mind what editor I use. I just want to be able to <strong>type commit messages in an editor</strong> rather than the command line (with <code>-m</code>).</p>
<p>Those of you using Git on Windows: What tool do you use to edit your commit messages, and what did you have to do to make it work?</p>
| 773,973 | 36 | 7 | null |
2008-08-14 01:43:04.27 UTC
| 295 |
2022-08-17 11:57:36.867 UTC
|
2016-12-24 17:26:04.737 UTC
|
ΤΖΩΤΖΙΟΥ
| 1,002,260 |
Patrick McElhaney
| 437 | null | 1 | 627 |
windows|git|cygwin|editor
| 386,545 |
<p>Update September 2015 (6 years later)</p>
<p>The <a href="https://github.com/git-for-windows/git/releases/tag/v2.5.3.windows.1" rel="noreferrer">last release of git-for-Windows (2.5.3)</a> now includes:</p>
<blockquote>
<p>By configuring <strong><code>git config core.editor notepad</code></strong>, users <a href="https://github.com/git-for-windows/git/issues/381" rel="noreferrer">can now use <code>notepad.exe</code> as their default editor</a>.<br>
Configuring <code>git config format.commitMessageColumns 72</code> will be picked up by the notepad wrapper and line-wrap the commit message after the user edits it.</p>
</blockquote>
<p>See <a href="https://github.com/git-for-windows/build-extra/commit/69b301bbd7c18226c63d83638991cb2b7f84fb64" rel="noreferrer">commit 69b301b</a> by <a href="https://github.com/dscho" rel="noreferrer">Johannes Schindelin (<code>dscho</code>)</a>.</p>
<p>And Git 2.16 (Q1 2018) will show a message to tell the user that it is waiting for the user to finish editing when spawning an editor, in case the editor
opens to a hidden window or somewhere obscure and the user gets
lost.</p>
<p>See <a href="https://github.com/git/git/commit/abfb04d0c74cde804c734015ff5868a88c84fb6f" rel="noreferrer">commit abfb04d</a> (07 Dec 2017), and <a href="https://github.com/git/git/commit/a64f213d3fa13fa01e582b6734fe7883ed975dc9" rel="noreferrer">commit a64f213</a> (29 Nov 2017) by <a href="https://github.com/larsxschneider" rel="noreferrer">Lars Schneider (<code>larsxschneider</code>)</a>.<br>
Helped-by: <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano (<code>gitster</code>)</a>.<br>
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/0c69a132cb1adf0ce9f31e6631f89321e437cb76" rel="noreferrer">commit 0c69a13</a>, 19 Dec 2017)</sup></p>
<blockquote>
<h2><code>launch_editor()</code>: indicate that Git waits for user input</h2>
<p>When a graphical <code>GIT_EDITOR</code> is spawned by a Git command that opens
and waits for user input (e.g. "<code>git rebase -i</code>"), then the editor window
might be obscured by other windows.<br>
The user might be left staring at
the original Git terminal window without even realizing that s/he needs
to interact with another window before Git can proceed. To this user Git
appears hanging.</p>
<p>Print a message that Git is waiting for editor input in the original
terminal and get rid of it when the editor returns, if the terminal
supports erasing the last line</p>
</blockquote>
<hr>
<p>Original answer</p>
<p>I just tested it with git version 1.6.2.msysgit.0.186.gf7512 and Notepad++5.3.1</p>
<p>I prefer to <em>not</em> have to set an EDITOR variable, so I tried:</p>
<pre class="lang-bash prettyprint-override"><code>git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\""
# or
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\" %*"
</code></pre>
<p>That always gives:</p>
<pre><code>C:\prog\git>git config --global --edit
"c:\Program Files\Notepad++\notepad++.exe" %*: c:\Program Files\Notepad++\notepad++.exe: command not found
error: There was a problem with the editor '"c:\Program Files\Notepad++\notepad++.exe" %*'.
</code></pre>
<p>If I define a npp.bat including:</p>
<pre><code>"c:\Program Files\Notepad++\notepad++.exe" %*
</code></pre>
<p>and I type:</p>
<pre><code>C:\prog\git>git config --global core.editor C:\prog\git\npp.bat
</code></pre>
<p>It just works from the DOS session, <strong>but not from the git shell</strong>.<br>
(not that with the core.editor configuration mechanism, a script with "<code>start /WAIT...</code>" in it would not work, but only open a new DOS window)</p>
<hr>
<p><a href="https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/1431003#1431003">Bennett's answer</a> mentions the possibility to avoid adding a script, but to reference directly the program itself <strong>between simple quotes</strong>. Note the direction of the slashes! Use <code>/</code> NOT <code>\</code> to separate folders in the path name!</p>
<pre class="lang-bash prettyprint-override"><code>git config --global core.editor \
"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
</code></pre>
<p>Or if you are in a 64 bit system:</p>
<pre class="lang-bash prettyprint-override"><code>git config --global core.editor \
"'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
</code></pre>
<p>But I prefer using a script (see below): that way I can play with different paths or different options without having to register again a <code>git config</code>.</p>
<hr>
<p>The actual solution (with a script) was to realize that:<br>
<strong>what you refer to in the config file is actually a shell (<code>/bin/sh</code>) script</strong>, not a DOS script.</p>
<p>So what does work is:</p>
<pre><code>C:\prog\git>git config --global core.editor C:/prog/git/npp.bat
</code></pre>
<p>with <code>C:/prog/git/npp.bat</code>:</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"
</code></pre>
<p>or</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$*"
</code></pre>
<p>With that setting, I can do '<code>git config --global --edit</code>' from DOS or Git Shell, or I can do '<code>git rebase -i ...</code>' from DOS or Git Shell.<br>
Bot commands will trigger a new instance of notepad++ (hence the <code>-multiInst</code>' option), and wait for that instance to be closed before going on.</p>
<p>Note that I use only '/', not <code>\</code>'. And I <a href="https://stackoverflow.com/questions/623518/msysgit-on-windows-what-should-i-be-aware-of-if-any">installed msysgit using option 2.</a> (Add the <code>git\bin</code> directory to the <code>PATH</code> environment variable, but without overriding some built-in windows tools)</p>
<p>The fact that the notepad++ wrapper is called .bat is not important.<br>
It would be better to name it 'npp.sh' and to put it in the <code>[git]\cmd</code> directory though (or in any directory referenced by your PATH environment variable).</p>
<hr>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/255212#255212">How do I view ‘git diff’ output with visual diff program?</a> for the general theory</li>
<li><a href="https://stackoverflow.com/questions/780425/how-do-i-setup-diffmerge-with-msysgit-gitk/783667#783667">How do I setup DiffMerge with msysgit / gitk?</a> for another example of external tool (DiffMerge, and WinMerge)</li>
</ul>
<hr>
<p><a href="https://stackoverflow.com/users/2716305/lightfire228">lightfire228</a> adds <a href="https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/773973#comment74027740_773973">in the comments</a>:</p>
<blockquote>
<p>For anyone having an issue where N++ just opens a blank file, and git doesn't take your commit message, see "<a href="https://stackoverflow.com/q/30085970/6309">Aborting commit due to empty message</a>": change your <code>.bat</code> or <code>.sh</code> file to say:</p>
</blockquote>
<pre><code>"<path-to-n++" .git/COMMIT_EDITMSG -<arguments>.
</code></pre>
<blockquote>
<p>That will tell notepad++ to open the temp commit file, rather than a blank new one.</p>
</blockquote>
|
811,193 |
How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?
|
<p>vim shows on every line ending ^M</p>
<p>How I do to replace this with a 'normal' linebreak?</p>
| 22,816,221 | 37 | 4 | null |
2009-05-01 12:44:09.59 UTC
| 178 |
2020-12-03 18:42:51.94 UTC
|
2014-03-05 11:38:45.883 UTC
| null | 1,523,648 | null | 98,076 | null | 1 | 512 |
vim|line-breaks
| 413,000 |
<p>This is the only thing that worked for me:</p>
<blockquote>
<p>:e ++ff=dos</p>
</blockquote>
<p>Found it at: <a href="http://vim.wikia.com/wiki/File_format" rel="noreferrer">http://vim.wikia.com/wiki/File_format</a></p>
|
6,545,719 |
extjs grid - how to make column width 100%
|
<p>The property <code>width</code> is a pixel width.</p>
<pre><code>{
xtype: 'grid',
store: store,
selModel: Ext.create('Ext.selection.CheckboxModel', {
mode: 'SINGLE'
}),
layout: 'fit',
columns: [
{
text: "pum",
dataIndex: 'SRD_NAME_FL',
width: 400
}
],
columnLines: true
}
</code></pre>
<p>if i have only one column how can i make column width = 100%
or if i have several columns - how to make last column stretch to end of grid?</p>
| 6,546,243 | 5 | 0 | null |
2011-07-01 08:57:13.6 UTC
| 1 |
2015-08-25 12:22:15.363 UTC
|
2012-09-05 09:56:51.61 UTC
| null | 802,965 | null | 802,965 | null | 1 | 13 |
grid|extjs4
| 43,120 |
<p>For ExtJS3, set <code>forceFit</code> on the GridPanels <code>viewConfig</code>. See: <a href="http://dev.sencha.com/deploy/ext-3.4.0/docs/?class=Ext.grid.GridView">http://dev.sencha.com/deploy/ext-3.4.0/docs/?class=Ext.grid.GridView</a></p>
<p>For ExtJS 4 set <code>forceFit</code> directly on the GridPanel: <a href="http://docs.sencha.com/ext-js/4-0/#/api/-cfg-forceFit">http://docs.sencha.com/ext-js/4-0/#/api/-cfg-forceFit</a> and use it in conjunction with <code>flex</code> on your columns.</p>
<p><strong>Example for v4</strong></p>
<pre><code>var p = Ext.Create('Ext.grid.Panel',{
forceFit: true,
columns: [{
xtype: 'gridcolumn',
header: _ll.id,
sortable: true,
resizable: false,
flex: 0, //Will not be resized
width: 60,
dataIndex: 'Id'
}, {
xtype: 'gridcolumn',
header: __ll.num,
sortable: true,
resizable: true,
flex: 1,
width: 100,
dataIndex: 'number'
}
});
</code></pre>
<p><strong>Example for v3</strong></p>
<pre><code>var p = new Ext.grid.GridPanel({
viewConfig: {
forceFit: true
},
columns: [{
xtype: 'gridcolumn',
header: _ll.id,
sortable: true,
resizable: false,
fixed: true, //Will not be resized
width: 60,
dataIndex: 'Id'
}, {
xtype: 'gridcolumn',
header: __ll.num,
sortable: true,
resizable: true,
width: 100,
dataIndex: 'number'
}
});
</code></pre>
|
6,710,019 |
UITextField secureTextEntry - works going from YES to NO, but changing back to YES has no effect
|
<p>The above says it all- I have a UITextField set to secure, but want to give users the option to make it not secure (so they can see for sure what they typed if they are in a private area). However, suppose they hit the toggle by mistake, and want to change it back to secure mode? That does not work. I've tried everything - using -1 instead of YES, deleting the text and then putting it back. I'm at a total loss on other ideas. [Entered rdar://9781908]</p>
<p>EDIT: I believe this issue is fixed as of iOS5.</p>
| 7,137,588 | 5 | 2 | null |
2011-07-15 16:11:50.89 UTC
| 11 |
2016-08-09 21:36:42.797 UTC
|
2012-09-08 23:22:32.137 UTC
| null | 1,633,251 | null | 1,633,251 | null | 1 | 27 |
uitextfield
| 23,088 |
<p>It must be input-focus issue: when focused, UITextField can change only ON->OFF.
<br>
Try next trick to switch OFF->ON:</p>
<pre><code>textField.enabled = NO;
textField.secureTextEntry = YES;
textField.enabled = YES;
[textField becomeFirstResponder];
</code></pre>
<p>EDIT (dhoerl): In iOS 9.3, I found this works but there is a problem. If you enter say 3 characters in plain view, then switch to secure text, then type a character, the 3 pre-existing characters disappear. I tried all kinds of trick to clear, then reset the text without success. I finally tried just playing with the control by cutting and pasting - pasting into the newly-switched-to-secure-mode worked great. So I emulated it in code, and now it all works fine - no need to play with the responder either. Here is what I finally ended up with:</p>
<pre><code> if textview should go into secure mode and the textfield is not empty {
textField.text = ""
textField.secureTextEntry = true
UIPasteboard.generalPasteboard().string = password
textField.paste(self)
UIPasteboard.generalPasteboard().string = ""
}
</code></pre>
<p>I'd prefer to not have to do this paste, but if you want it seamless this is the only way I can find to do it.</p>
|
6,941,321 |
How to create custom Listeners in java?
|
<p>I want to know about how to set our own Listeners in java.For example I have a function that increments number from 1 to 100. i want to set a listener when the value reaches 50. How can i do that? Pls suggest me any tutorial.</p>
| 6,941,386 | 5 | 2 | null |
2011-08-04 12:23:18.29 UTC
| 11 |
2021-03-16 02:21:05.153 UTC
|
2011-08-04 12:35:37.517 UTC
| null | 314,862 | null | 617,302 | null | 1 | 39 |
java|interface|listener|observer-pattern
| 65,417 |
<p>Have a look at the source of any class that uses listeners. In fact it's quite easy:</p>
<ul>
<li>create an interface for your listener, e.g. <code>MyListener</code></li>
<li>maintain a list of <code>MyListener</code></li>
<li>upon each event that the listeners should listen to, iterate over the list and call the appropriate method with some event parameter(s)</li>
</ul>
<p>As for the observer pattern along with some Java code have a look at <a href="http://en.wikipedia.org/wiki/Observer_pattern">wikipedia</a>.</p>
|
6,468,813 |
Assign a login to a user created without login (SQL Server)
|
<p>I have got a user in my database that hasn't got an associated login. It seems to have been created without login.</p>
<p>Whenever I attempt to connect to the database with this user I get the following error:</p>
<pre><code>Msg 916, Level 14, State 1, Line 1
The server principal "UserName" is not able to access the database
"DatabaseName" under the current security context.
</code></pre>
<p>I'd like to specify a login for this user so that I can actually use it to access the database. I've tried the following script to associate a login with the user.</p>
<pre><code>USE [DatabaseName]
ALTER USER [UserName]
WITH LOGIN = [UserName]
</code></pre>
<p>But this gives me the following error:</p>
<pre><code>Msg 33016, Level 16, State 1, Line 2
The user cannot be remapped to a login. Remapping can only be done for users
that were mapped to Windows or SQL logins.
</code></pre>
<p>Is there any way I can assign a login to this user? I'd like to not have to start from scratch because this user has a lot of permissions that would need setting up again.</p>
<p><strong>Edit:</strong> in response to Philip Kelley's question, here's what I get when I run <code>select * from sys.database_principals where name = 'username'</code>.</p>
<p><img src="https://i.stack.imgur.com/lcfY8.gif" alt="SQL User"> </p>
<p>Apologies for the size of the image, you'll need to open it in a new tab to view it properly.</p>
<p><strong>Edit2:</strong></p>
<p>Ok, I've dropped the existing LOGIN as suggested by gbn, and I'm using the following script to create a new LOGIN with same SID as the user.</p>
<pre><code>CREATE LOGIN [UserName]
WITH PASSWORD=N'Password1',
DEFAULT_DATABASE=[DatabaseName],
CHECK_EXPIRATION=OFF,
CHECK_POLICY=OFF,
SID=0x0105000000000009030000001139F53436663A4CA5B9D5D067A02390
</code></pre>
<p>It's now giving me the following error message, it appears that the SID is too long for the LOGIN's SID field.</p>
<pre><code>Msg 15419, Level 16, State 1, Line 1
Supplied parameter sid should be binary(16).
</code></pre>
<p>Am I up the creek without a paddle?</p>
| 6,469,076 | 6 | 2 | null |
2011-06-24 13:55:23.163 UTC
| 13 |
2018-07-16 12:37:48.157 UTC
|
2011-06-24 15:21:06.45 UTC
| null | 39,277 | null | 39,277 | null | 1 | 53 |
sql-server|sql-server-2008
| 139,191 |
<p>You have an orphaned user and this can't be remapped with ALTER USER (yet) becauses there is no login to map to. So, you need run <a href="http://msdn.microsoft.com/en-us/library/ms189751.aspx" rel="noreferrer">CREATE LOGIN</a> first.</p>
<p>If the database level user is</p>
<ul>
<li>a Windows Login, the mapping will be fixed automatcially via the AD SID</li>
<li>a SQL Login, use "sid" from <a href="http://msdn.microsoft.com/en-us/library/ms187328.aspx" rel="noreferrer">sys.database_principals</a> for the SID option for the login</li>
</ul>
<p>Then run ALTER USER</p>
<p>Edit, after comments and updates</p>
<p>The sid from sys.database_principals is for a Windows login.</p>
<p>So trying to create and re-map to a SQL Login will fail</p>
<p>Run this to get the Windows login</p>
<pre><code>SELECT SUSER_SNAME(0x0105000000000009030000001139F53436663A4CA5B9D5D067A02390)
</code></pre>
|
6,692,031 |
Check if event is triggered by a human
|
<p>I have a handler attached to an event and I would like it to execute only if it is triggered by a human, and not by a trigger() method. How do I tell the difference?</p>
<p>For example,</p>
<pre><code>$('.checkbox').change(function(e){
if (e.isHuman())
{
alert ('human');
}
});
$('.checkbox').trigger('change'); //doesn't alert
</code></pre>
| 6,692,173 | 9 | 0 | null |
2011-07-14 10:50:43.037 UTC
| 35 |
2022-09-11 20:18:06.537 UTC
|
2019-12-12 15:03:24.797 UTC
| null | 1,262,820 | null | 219,931 | null | 1 | 149 |
javascript|jquery
| 70,371 |
<p>You can check <code>e.originalEvent</code>: if it's defined the click is human:</p>
<p>Look at the fiddle <a href="http://jsfiddle.net/Uf8Wv/" rel="noreferrer">http://jsfiddle.net/Uf8Wv/</a></p>
<pre><code>$('.checkbox').change(function(e){
if (e.originalEvent !== undefined)
{
alert ('human');
}
});
</code></pre>
<p>my example in the fiddle:</p>
<pre><code><input type='checkbox' id='try' >try
<button id='click'>Click</button>
$("#try").click(function(event) {
if (event.originalEvent === undefined) {
alert('not human')
} else {
alert(' human');
}
});
$('#click').click(function(event) {
$("#try").click();
});
</code></pre>
|
15,949,304 |
Turn off display errors using file "php.ini"
|
<p>I am trying to turn off all errors on my website. I have followed different tutorials on how to do this, but I keep getting read and open error messages. Is there something I am missing?</p>
<p>I have tried the following in my <em>php.ini</em> file:</p>
<pre><code>;Error display
display_startup_errors = Off
display_errors = Off
html_errors = Off
docref_root = 0
docref_ext = 0
</code></pre>
<p>For some reason when I do a fileopen() call for a file which does not exist, I still get the error displayed. This is not safe for a live website, for obvious reasons.</p>
| 15,949,445 | 12 | 3 | null |
2013-04-11 12:52:58.63 UTC
| 14 |
2020-07-30 23:50:25.433 UTC
|
2020-04-22 03:20:13.427 UTC
| null | 63,550 | null | 1,887,593 | null | 1 | 43 |
php
| 264,167 |
<p>I always use something like this in a configuration file:</p>
<pre><code>// Toggle this to change the setting
define('DEBUG', true);
// You want all errors to be triggered
error_reporting(E_ALL);
if(DEBUG == true)
{
// You're developing, so you want all errors to be shown
display_errors(true);
// Logging is usually overkill during development
log_errors(false);
}
else
{
// You don't want to display errors on a production environment
display_errors(false);
// You definitely want to log any occurring
log_errors(true);
}
</code></pre>
<p>This allows easy toggling between debug settings. You can improve this further by checking on which server the code is running (development, test, acceptance, and production) and change your settings accordingly.</p>
<p>Note that no errors will be logged if error_reporting is set to 0, as cleverly remarked by Korri.</p>
|
15,668,762 |
Google Maps with Bootstrap not responsive
|
<p>I'm using bootstrap and I embedded Google Maps API 3.</p>
<p><code>#map_canvas</code> isn't responsive; it's a fixed width.</p>
<p>Also, if I use <code>height: auto</code> and <code>width: auto</code> the map doesn't show up in the page.</p>
<p>Why?</p>
<pre><code><style type="text/css">
body {
padding-top: 60px;
padding-bottom: 40px;
}
#map_canvas {
height: 400px;
width: auto;
}
</style>
<div class="container">
<div class="row">
<div class="span6">
<div id="map_canvas"></div>
</div>
</div>
</div>
</code></pre>
| 15,668,970 | 11 | 0 | null |
2013-03-27 20:28:11.027 UTC
| 23 |
2021-11-19 19:32:33.557 UTC
|
2015-09-10 21:23:18.93 UTC
| null | 938,516 | null | 1,858,075 | null | 1 | 50 |
html|css|google-maps-api-3|twitter-bootstrap
| 71,900 |
<p><em><strong>REVISED: The Official Post is outdated, so I've updated my answer and improved the code.</strong></em></p>
<p>The following method <strong>does not require bootstrap or any other framework</strong>. It can be used independently to make any content responsive. To the parent element is applied a padding by calculating the <a href="http://en.wikipedia.org/wiki/Aspect_ratio" rel="noreferrer"><code>aspect ratio</code></a>. Then the child element is placed on top using absolute position.</p>
<p><strong>The HTML:</strong></p>
<pre><code><div class="iframe-container">
<!-- embed code here -->
</div>
</code></pre>
<p><strong>The CSS:</strong></p>
<pre><code>.iframe-container{
position: relative;
width: 100%;
padding-bottom: 56.25%; /* Ratio 16:9 ( 100%/16*9 = 56.25% ) */
}
.iframe-container > *{
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
</code></pre>
<hr />
<p>The following 'fiddle' has examples on how to make:</p>
<ul>
<li><strong>Responsive Google Map</strong></li>
<li><strong>Responsive OpenStreetMap</strong></li>
<li><strong>Responsive Vimeo Video</strong></li>
<li><strong>Responsive Youtube Video</strong></li>
</ul>
<h2>Demo: <a href="http://jsfiddle.net/LHQQZ/135/" rel="noreferrer">http://jsfiddle.net/LHQQZ/135/</a></h2>
|
15,723,628 |
Pandas - make a column dtype object or Factor
|
<p>In pandas, how can I convert a column of a DataFrame into dtype object?
Or better yet, into a factor? (For those who speak R, in Python, how do I <code>as.factor()</code>?)</p>
<p>Also, what's the difference between <code>pandas.Factor</code> and <code>pandas.Categorical</code>?</p>
| 15,723,905 | 3 | 0 | null |
2013-03-30 21:21:57.247 UTC
| 12 |
2021-05-13 12:12:56.66 UTC
|
2015-02-09 21:03:46.68 UTC
| null | 3,923,281 | null | 1,319,312 | null | 1 | 65 |
python|pandas
| 114,954 |
<p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="noreferrer"><code>astype</code></a> method to cast a Series (one column):</p>
<pre><code>df['col_name'] = df['col_name'].astype(object)
</code></pre>
<p>Or the entire DataFrame:</p>
<pre><code>df = df.astype(object)
</code></pre>
<hr />
<h3>Update</h3>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="noreferrer">Since version 0.15, you can use the category datatype</a> in a Series/column:</p>
<pre><code>df['col_name'] = df['col_name'].astype('category')
</code></pre>
<p><em>Note: <code>pd.Factor</code> was been deprecated and has been removed in favor of <code>pd.Categorical</code>.</em></p>
|
50,899,692 |
Most dominant color in RGB image - OpenCV / NumPy / Python
|
<p>I have a python image processing function, that uses tries to get the dominant color of an image. I make use of a function I found here <a href="https://github.com/tarikd/python-kmeans-dominant-colors/blob/master/utils.py" rel="noreferrer">https://github.com/tarikd/python-kmeans-dominant-colors/blob/master/utils.py</a></p>
<p>It works, but unfortunately I don't quite understand what it does and I learned that <code>np.histogram</code> is rather slow and I should use <code>cv2.calcHist</code> since it's 40x faster according to this: <a href="https://docs.opencv.org/trunk/d1/db7/tutorial_py_histogram_begins.html" rel="noreferrer">https://docs.opencv.org/trunk/d1/db7/tutorial_py_histogram_begins.html</a></p>
<p>I'd like to understand how I have to update the code to use <code>cv2.calcHist</code>, or better, which values I have to input.</p>
<p>My function</p>
<pre><code>def centroid_histogram(clt):
# grab the number of different clusters and create a histogram
# based on the number of pixels assigned to each cluster
num_labels = np.arange(0, len(np.unique(clt.labels_)) + 1)
(hist, _) = np.histogram(clt.labels_, bins=num_labels)
# normalize the histogram, such that it sums to one
hist = hist.astype("float")
hist /= hist.sum()
# return the histogram
return hist
</code></pre>
<p>The <code>pprint</code> of <code>clt</code> is this, not sure if this helps</p>
<pre><code>KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300,
n_clusters=1, n_init=10, n_jobs=1, precompute_distances='auto',
random_state=None, tol=0.0001, verbose=0)
</code></pre>
<p>My code can be found here: <a href="https://github.com/primus852/python-movie-barcode" rel="noreferrer">https://github.com/primus852/python-movie-barcode</a></p>
<p>I am a very beginner, so any help is highly appreciated.</p>
<p>As per request:</p>
<h3>Sample Image</h3>
<p><a href="https://i.stack.imgur.com/61LGC.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/61LGC.jpg" alt="Sample"></a></p>
<h3>Most dominant color:</h3>
<p><code>rgb(22,28,37)</code></p>
<h3>Computation time for the Histogram:</h3>
<p><code>0.021515369415283203s</code></p>
| 50,900,143 | 3 | 1 | null |
2018-06-17 19:11:05.56 UTC
| 9 |
2018-06-18 05:55:50.25 UTC
|
2018-06-18 05:55:50.25 UTC
| null | 3,293,881 | null | 1,092,632 | null | 1 | 21 |
python|python-3.x|numpy|opencv
| 22,497 |
<p>Two approaches using <code>np.unique</code> and <code>np.bincount</code> to get the most dominant color could be suggested. Also, in the linked page, it talks about <code>bincount</code> as a faster alternative, so that could be the way to go.</p>
<p><strong>Approach #1</strong></p>
<pre><code>def unique_count_app(a):
colors, count = np.unique(a.reshape(-1,a.shape[-1]), axis=0, return_counts=True)
return colors[count.argmax()]
</code></pre>
<p><strong>Approach #2</strong></p>
<pre><code>def bincount_app(a):
a2D = a.reshape(-1,a.shape[-1])
col_range = (256, 256, 256) # generically : a2D.max(0)+1
a1D = np.ravel_multi_index(a2D.T, col_range)
return np.unravel_index(np.bincount(a1D).argmax(), col_range)
</code></pre>
<p>Verification and timings on <code>1000 x 1000</code> color image in a dense range <code>[0,9)</code> for reproducible results -</p>
<pre><code>In [28]: np.random.seed(0)
...: a = np.random.randint(0,9,(1000,1000,3))
...:
...: print unique_count_app(a)
...: print bincount_app(a)
[4 7 2]
(4, 7, 2)
In [29]: %timeit unique_count_app(a)
1 loop, best of 3: 820 ms per loop
In [30]: %timeit bincount_app(a)
100 loops, best of 3: 11.7 ms per loop
</code></pre>
<p><strong>Further boost</strong></p>
<p>Further boost upon leveraging <a href="https://github.com/pydata/numexpr/blob/master/doc/user_guide.rst#enabling-intel-vml-support" rel="noreferrer"><code>multi-core</code> with <code>numexpr</code> module</a> for large data -</p>
<pre><code>import numexpr as ne
def bincount_numexpr_app(a):
a2D = a.reshape(-1,a.shape[-1])
col_range = (256, 256, 256) # generically : a2D.max(0)+1
eval_params = {'a0':a2D[:,0],'a1':a2D[:,1],'a2':a2D[:,2],
's0':col_range[0],'s1':col_range[1]}
a1D = ne.evaluate('a0*s0*s1+a1*s0+a2',eval_params)
return np.unravel_index(np.bincount(a1D).argmax(), col_range)
</code></pre>
<p>Timings -</p>
<pre><code>In [90]: np.random.seed(0)
...: a = np.random.randint(0,9,(1000,1000,3))
In [91]: %timeit unique_count_app(a)
...: %timeit bincount_app(a)
...: %timeit bincount_numexpr_app(a)
1 loop, best of 3: 843 ms per loop
100 loops, best of 3: 12 ms per loop
100 loops, best of 3: 8.94 ms per loop
</code></pre>
|
50,863,312 |
Jest gives `Cannot find module` when importing components with absolute paths
|
<p>Receiving the following error when running Jest</p>
<pre><code>Cannot find module 'src/views/app' from 'index.jsx'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
at Object.<anonymous> (src/index.jsx:4:12)
</code></pre>
<p>index.jsx </p>
<pre><code>import AppContainer from 'src/views/app';
</code></pre>
<p>package.json</p>
<pre><code> "jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,mjs}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleDirectories": [
"node_modules",
"src"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
]
},
</code></pre>
<p>My tests that run files that only contain relative paths in the tree run correctly.</p>
<p>To Clarify, I'm looking for how to configure Jest to not fail on absolute paths.</p>
| 50,863,637 | 11 | 2 | null |
2018-06-14 17:55:27.043 UTC
| 14 |
2022-08-19 11:58:14.48 UTC
|
2019-01-29 17:21:39.347 UTC
| null | 2,418,295 | null | 2,418,295 | null | 1 | 129 |
node.js|reactjs|npm|jestjs
| 180,428 |
<p>Since in <code>package.json</code> you have:</p>
<pre><code>"moduleDirectories": [
"node_modules",
"src"
]
</code></pre>
<p>Which says that each module you import will be looked into <code>node_modules</code> first and if not found will be looked into <code>src</code> directory.</p>
<p>Since it's looking into <code>src</code> directory you should use:</p>
<pre><code>import AppContainer from 'views/app';
</code></pre>
<p>Please note that this path is absolute to the <code>src</code> directory, you do not have to navigate to locate it as relative path.</p>
<p>OR you can configure your root directory in moduleDirectories inside your pakcage.json so that all your components could be imported as you want it.</p>
|
10,411,520 |
Export Grid view to excel and save excel file to folder
|
<p>I want to save excel file which export data of grid view. I have written code to export gridview data to excel but I don't know how to save exported file.</p>
<p>Following is my code to export gridview into excel :</p>
<pre><code>Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gvFiles.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
</code></pre>
| 10,412,559 | 7 | 4 | null |
2012-05-02 10:00:17.787 UTC
| 4 |
2017-11-29 05:32:24.543 UTC
|
2017-11-29 05:32:24.543 UTC
| null | 3,885,376 | null | 1,282,856 | null | 1 | 5 |
c#|asp.net
| 78,247 |
<p>You can do this:</p>
<pre><code>private void ExportGridView()
{
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
// Render grid view control.
gvFiles.RenderControl(htw);
// Write the rendered content to a file.
string renderedGridView = sw.ToString();
System.IO.File.WriteAllText(@"C:\Path\On\Server\ExportedFile.xlsx", renderedGridView);
}
</code></pre>
|
32,064,038 |
aws lambda function triggering multiple times for a single event
|
<p>I am using aws lambda function to convert uploaded wav file in a bucket to mp3 format and later move file to another bucket. It is working correctly. But there's a problem with triggering. When i upload small wav files,lambda function is called once. But when i upload a large sized wav file, this function is triggered multiple times.</p>
<p>I have googled this issue and found that it is stateless, so it will be called multiple times(not sure this trigger is for multiple upload or a same upload).</p>
<p><a href="https://aws.amazon.com/lambda/faqs/">https://aws.amazon.com/lambda/faqs/</a></p>
<p><strong>Is there any method to call this function once for a single upload?</strong></p>
| 35,968,356 | 4 | 3 | null |
2015-08-18 05:15:51.22 UTC
| 12 |
2022-08-29 11:45:21.753 UTC
|
2015-08-26 00:51:30.6 UTC
| null | 45,773 | null | 3,828,918 | null | 1 | 45 |
amazon-web-services|amazon-s3|aws-lambda
| 42,325 |
<p><strong>Short version:</strong>
Try increasing timeout setting in your lambda function configuration.</p>
<p><strong>Long version:</strong></p>
<p>I guess you are running into the lambda function being timed out here. </p>
<p>S3 events are asynchronous in nature and lambda function listening to S3 events is retried atleast 3 times before that event is rejected. You mentioned your lambda function is executed only once (with no error) during smaller sized upload upon which you do conversion and re-upload. There is a possibility that the time required for conversion and re-upload from your code is greater than the timeout setting of your lambda function.</p>
<p>Therefore, you might want to try increasing the timeout setting in your lambda function configuration.</p>
<p>By the way, one way to confirm that your lambda function is invoked multiple times is to look into cloudwatch logs for the event id (<em>67fe6073-e19c-11e5-1111-6bqw43hkbea3</em>) occurrence -</p>
<pre><code>START RequestId: 67jh48x4-abcd-11e5-1111-6bqw43hkbea3 Version: $LATEST
</code></pre>
<p>This event id represents a specific event for which lambda was invoked and should be same for all lambda executions that are responsible for the same S3 event.</p>
<p>Also, you can look for execution time (Duration) in the following log line that marks end of one lambda execution -</p>
<pre><code>REPORT RequestId: 67jh48x4-abcd-11e5-1111-6bqw43hkbea3 Duration: 244.10 ms Billed Duration: 300 ms Memory Size: 128 MB Max Memory Used: 20 MB
</code></pre>
<p>If not a solution, it will at least give you some room to debug in right direction. Let me know how it goes.</p>
|
13,511,340 |
UIBackgroundModes location and significant location changes with region monitoring
|
<p>I have an app that uses a combination of <code>startMonitoringForRegion:</code> and <code>startMonitoringSignificantLocationChanges</code> to keep aware of where the user is when the app is in the background. Does this mean that I need to include the <code>location</code> value for the <code>UIBackgroundModes</code> key in the <code>Info.plist</code>?</p>
<p>This is a quote from the docs:</p>
<blockquote>
<p>The significant-change location service is highly recommended for apps that do not need high-precision location data. With this service, location updates are generated only when the user’s location changes significantly; thus, it is ideal for social apps or apps that provide the user with noncritical, location-relevant information. If the app is suspended when an update occurs, the system wakes it up in the background to handle the update. If the app starts this service and is then terminated, the system relaunches the app automatically when a new location becomes available. This service is available in iOS 4 and later, and it is available only on devices that contain a cellular radio.</p>
<p>...</p>
<p>An app that provides continuous location updates to the user (even when in the background) can enable background location services by including the UIBackgroundModes key (with the location value) in its Info.plist file. The inclusion of this value in the UIBackgroundModes key does not preclude the system from suspending the app, but it does tell the system that it should wake up the app whenever there is new location data to deliver. Thus, this key effectively lets the app run in the background to process location updates whenever they occur.</p>
</blockquote>
<p>My interpretation of this is that the <code>location</code> value for the <code>UIBackgroundModes</code> key is only required if the app needs continuous location updates, like a sat nav app.</p>
<p>I have also tried running the app on a device without the <code>location</code> value for the <code>UIBackgroundModes</code> key and it continues to report significant location changes and when the a region is entered of exited.</p>
<p>Also, the only place that <code>UIBackgroundModes</code> is mentioned in the <a href="https://developer.apple.com/library/ios/#documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html" rel="noreferrer">CLLocationManager Class Reference</a> is in the <code>startUpdatingLocation</code> discussion, which I am not using.</p>
| 13,512,730 | 2 | 0 | null |
2012-11-22 11:04:10.457 UTC
| 8 |
2018-01-11 10:28:29.01 UTC
|
2020-06-20 09:12:55.06 UTC
| null | -1 | null | 617,579 | null | 1 | 17 |
iphone|objective-c|ios|core-location|cllocationmanager
| 12,457 |
<p>You're right about the <code>location</code> key, it's only required when your app needs high-precision location updates even when in the background. Something like Runkeeper uses this to allow it to keep tracking your location, even when you're using another app with multitasking. <a href="http://developer.apple.com/library/ios/#documentation/general/Reference/InfoPlistKeyReference/Articles/iPhoneOSKeys.html" rel="noreferrer">From the docs for iOS Keys: <code>UIBackgroundModes</code></a></p>
<blockquote>
<p>"location": The app provides location-based information to the user and requires
the use of the standard location services (as opposed to the
significant change location service) to implement this feature.</p>
</blockquote>
<p>And</p>
<blockquote>
<p>Where alternatives for running in the background exist, those alternatives should be used instead. For example, apps can use the signifiant location change interface to receive location events instead of registering as a background location app.</p>
</blockquote>
<p>Region monitoring will work without the <code>location</code> key. In fact, region monitoring will work without any special iOS keys being enabled.</p>
<p>You say that you're not using <code>CLLocationManager</code>, but if you're using region monitoring, you'll have to use that class. You need to set up a location manager delegate for your app to actually get the region notifications.</p>
|
13,468,020 |
High resolution screen shot in Android
|
<p>Is there any way to get a <strong>high resolution</strong> screen shot of a certain view in an activity. </p>
<p>I want to convert html content of my webview to PDF. For that I tried to take screen shot of the webview content and then converted it to PDF using itext. The resulted PDF is not in much more clarity. </p>
<p>My code:</p>
<pre><code> protected void takeimg() {
Picture picture = mWebView.capturePicture();
Bitmap b = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
// byte[] bt = b.getNinePatchChunk();
// Bitmap b;
// View v1 = mWebView.getRootView();
// v1.setDrawingCacheEnabled(true);
// b = Bitmap.createBitmap(v1.getDrawingCache());
// v1.setDrawingCacheEnabled(false);
FileOutputStream fos = null;
try {
File root = new File(Environment.getExternalStorageDirectory(),
"Sample");
if (!root.exists()) {
root.mkdir();
}
String sdcardhtmlpath = root.getPath().toString() + "/"
+ "temp_1.png";
fos = new FileOutputStream(sdcardhtmlpath);
// fos = openFileOutput("samsp_1.jpg", MODE_WORLD_WRITEABLE);
if (fos != null) {
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
// fos.write(bt);
fos.close();
}
} catch (Exception e) {
Log.e("takeimg", e.toString());
e.printStackTrace();
}
}
protected void pdfimg() {
Document mydoc = new Document(PageSize.A3);
try {
File root = new File(Environment.getExternalStorageDirectory(),
"Sample");
if (!root.exists()) {
root.mkdir();
}
String sdcardhtmlpath = root.getPath().toString() + "/";
mydoc.setMargins(0, 0, 0, 0);
PdfWriter.getInstance(mydoc, new FileOutputStream(sdcardhtmlpath
+ PDFfilename));
mydoc.open();
Image image1 = Image.getInstance(sdcardhtmlpath + "temp_1.jpg");
image1.scalePercent(95f);
mydoc.add(image1);
// mydoc.newPage();
mydoc.close();
} catch (Exception e) {
Log.e("pdi name", e.toString());
}
}
</code></pre>
| 13,602,615 | 4 | 3 | null |
2012-11-20 06:55:17.583 UTC
| 11 |
2012-12-13 18:44:08.947 UTC
|
2012-11-22 07:08:20.377 UTC
| null | 1,147,434 | null | 1,147,434 | null | 1 | 18 |
android|screenshot
| 8,203 |
<p><strong><em>Update: See Edit 3 for an answer to op's original question</em></strong></p>
<p>There are two options:</p>
<ol>
<li><p>Use a library to convert the HTML to PDF. This is by far the best option, since it will (probably) preserve text as vectors.</p></li>
<li><p>Get a high resolution render of the HTML and save it as a PNG (not PDF surely!).</p></li>
</ol>
<p>For HTML to PDF, <a href="http://code.google.com/p/wkhtmltopdf/" rel="noreferrer">wkhtmltopdf</a> looks like a good option, but it relies on Qt which you can't really use on Android. There are some other libraries but I doubt they do the PDF rendering very well.</p>
<p>For getting a high-res webview, you could try creating your own <code>WebView</code> and calling <code>onMeasure(...)</code> and <code>onLayout(...)</code> and pass appropriate parameters so the view is really big. Then call <code>onDraw(myOwnCanvas)</code> and the webview will draw itself to your canvas, which can be backed by a <code>Bitmap</code> using <code>Canvas.setBitmap()</code>.</p>
<p>You can probably copy the state into the new <code>WebView</code> using something like</p>
<pre><code>screenshotterWebview.onRestoreInstanceState(mWebView.onSaveInstanceState());
</code></pre>
<p>Orrr it may even be possible to use the same <code>WebView</code>, just temporarily resize it to be large, <code>onDraw()</code> it to your canvas, and resize it back again. That's getting very hacky though! </p>
<p>You might run into memory issues if you make it too big.</p>
<h1>Edit 1</h1>
<p>I thought of a third, exactly-what-you-want option, but it's kind of hardcore. You can create a custom <code>Canvas</code>, that writes to a PDF. In fact, it is <em>almost</em> easy, because underlying <code>Canvas</code> is Skia, which actually includes a PDF backend. Unfortunately you don't get access to it on Android, so you'll basically have to build your own copy of it on Android (there are instructions), and duplicate/override all the <code>Canvas</code> methods to point to your Skia instead of Androids. Note that there is a tempting <code>Picture.writeToStream()</code> method which serializes the Skia data, but unfortunately this format is not forwards or backwards compatible so if you use it your code will probably only work on a few versions of Android.</p>
<p>I'll update if/when I have fully working code.</p>
<h1>Edit 2</h1>
<p>Actually it is impossible to make your own "intercepting" <code>Canvas</code>. I started doing it and went through the tedious process of serializing all function calls. A few you can't do because they are hidden, but those didn't look important. But right at the end I came to serializing <code>Path</code> only to discover that it is write-only. That seems like a killer to me, so the only option is to interpret the result of <code>Picture.writeToStream()</code>. Fortunately there are only two versions of that format in use, and they are nearly identical.</p>
<h1>Edit 3 - Really simple way to get a high resolution <code>Bitmap</code> of a view</h1>
<p>Ok, it turns out just getting a high res bitmap of a view (which can be the entire app) is trivial. Here is how to get double resolution. Obviously all the bitmaps look a bit crap, but the text is rendered at full resolution:</p>
<pre><code>View window = activity.getWindow().getDecorView()
Canvas bitmapCanvas = new Canvas();
Bitmap bitmap = Bitmap.createBitmap(window.getWidth()*2, window.getHeight()*2, Bitmap.Config.ARGB_8888);
bitmapCanvas.setBitmap(bitmap);
bitmapCanvas.scale(2.0f, 2.0f);
window.draw(bitmapCanvas);
bitmap.compress(Bitmap.CompressFormat.PNG, 0, myOutputStream);
</code></pre>
<p>Works like a charm. I've now given up on getting a PDF screenshot with vector text. It's certainly possible, but very difficult. Instead I am working on getting a high-res PSD where each draw operation is a separate layer, which should be much easier.</p>
<h1>Edit 4</h1>
<p>Woa this is getting a bit long, but success! I've generated an <code>.xcf</code> (GIMP) and PDF where each layer is a different canvas drawing operation. It's not quite as fine-grained as I was expecting, but still, pretty useful!</p>
<p>Actually my code just outputs full-size PNGs and I used "Open as layers..." and "Autocrop layer" in GIMP to make these files, but of course you can do that in code if you like. I think I will turn this into a blog post.</p>
<p>Download the <a href="http://concentriclivers.com/misc/android_layout_test.xcf" rel="noreferrer">GIMP</a> or <a href="http://concentriclivers.com/misc/android_layout_test.xcf" rel="noreferrer">Photoshop</a> demo file (rendered at 3x resolution).</p>
|
13,268,796 |
Umask difference between 0022 and 022
|
<p>Is there any difference between umask <code>0022</code> and <code>022</code>? I want to change my umask to <code>022</code>. How can I do it? </p>
| 13,269,502 | 1 | 0 | null |
2012-11-07 11:26:18.087 UTC
| 6 |
2015-05-15 19:42:30.197 UTC
|
2015-05-15 19:24:32.933 UTC
| null | 445,131 | null | 279,372 | null | 1 | 27 |
unix|file-permissions|umask
| 87,434 |
<p>There is no difference between umask <code>0022</code> and umask <code>022</code>. </p>
<p>The octal umasks are calculated via the bitwise AND of the unary complement of the argument using bitwise NOT.</p>
<p><strong>Set the umask like this:</strong></p>
<pre><code>el@apollo:~$ umask 0077
el@apollo:~$ umask
0077
el@apollo:~$ umask 0022
el@apollo:~$ umask
0022
</code></pre>
<p><strong>Brief summary of umask value meanings:</strong></p>
<p>umask 077 - Assigns permissions so that only you have read/write access for files, and read/write/search for directories you own. All others have no access permissions to your files or directories.</p>
<p>umask 022 - Assigns permissions so that only you have read/write access for files, and read/write/search for directories you own. All others have read access only to your files, and read/search access to your directories.</p>
<p>umask 002 - Assigns permissions so that only you and members of your group have read/write access to files, and read/write/search access to directories you own. All others have read access only to your files, and read/search to your directories.</p>
<p><strong>For more information about what umask does:</strong></p>
<p>How to set your default umask, see this article: <a href="http://www.cyberciti.biz/tips/understanding-linux-unix-umask-value-usage.html" rel="noreferrer">http://www.cyberciti.biz/tips/understanding-linux-unix-umask-value-usage.html</a></p>
<p>If you want more detailed information this is an interesting article: <a href="http://articles.slicehost.com/2010/7/17/umask-and-unusual-file-permissions-and-types" rel="noreferrer">http://articles.slicehost.com/2010/7/17/umask-and-unusual-file-permissions-and-types</a></p>
<p>The answers to this post also offer some insight into umask bits:
<a href="https://stackoverflow.com/questions/4056912/question-about-umask-in-linux">https://stackoverflow.com/questions/4056912/question-about-umask-in-linux</a></p>
|
13,771,097 |
Server Too Busy in vs2012
|
<p>I've got vs2010 and vs2012 installed side by side. If I open up our MVC site in vs2010 and run it using the development web server it works fine, if I do the same thing in vs2012 I get "Server Too Busy" every single time for the first request to the site. Every request after the first request works fine.</p>
<p>Update: I've noticed in vs2012 it only happens of the project needs to build. If I haven't made any changes, ie the project doesn't need to build and I hit F5 to start it up and open up IE it works fine and I don't get the "Server Too Busy" message in the browser.</p>
| 24,310,228 | 8 | 4 | null |
2012-12-07 21:16:58.777 UTC
| 10 |
2018-01-25 12:22:05.39 UTC
|
2013-04-30 17:52:20.57 UTC
| null | 30,889 | null | 30,889 | null | 1 | 49 |
visual-studio-2012
| 21,378 |
<p>I have had this problem for my ASP.Net solution as well. There were no solutions for this problem on Stack Overflow or anywhere else.</p>
<p><strong>Setup</strong>:</p>
<p>Visual Studio 2013 (but I think it will also work for vs 2010/2012 ASP.Net web application IIS express setup).</p>
<p>Our production environment never had this problem because it was running on IIS.</p>
<p>I have tried a lot to fix it, but I found one specific solution. I set the <a href="https://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.delaynotificationtimeout.aspx" rel="nofollow"><code>delayNotificationTimeout</code></a> to 20 seconds, instead of the default of 5, which was not enough for our solutions to conjure up everything it needed to successfully run.</p>
<pre class="lang-xml prettyprint-override"><code><system.web>
<httpRuntime maxRequestLength="104850"
executionTimeout="600"
enableVersionHeader="false"
<b><i>delayNotificationTimeout="20"</i></b> />
</system.web>
</code></pre>
|
39,745,891 |
How to create a loader in Javascript waiting for a function to end?
|
<p>I have a function in Javascript (in the browser, not node.js) that it takes a lot of time to commit. I want that while the function is being processed, the browser will present a loader, so the user can understand that he/she has to wait.</p>
| 39,746,352 | 2 | 3 | null |
2016-09-28 11:15:56.237 UTC
| 1 |
2021-12-30 10:04:51.97 UTC
| null | null | null | null | 5,402,618 | null | 1 | 5 |
javascript|loader
| 38,352 |
<p>create a loader first :</p>
<pre><code><div class="loader" id="loader">
</div>
</code></pre>
<p>Then add the loader class in your CSS(css file of your loader class) :</p>
<pre><code> .loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.hide-loader{
display:none;
}
</code></pre>
<p>Add this js code to your JS file after your function executes completely,just hide the loader.</p>
<pre><code> $('#loader').addClass("hide-loader");
</code></pre>
|
20,695,595 |
Show Progress bar while downloading
|
<p>I want to show a progress bar showing percentage completed while my app is downloading some big files over the internet.
something like this :<img src="https://i.stack.imgur.com/flJB2.jpg" alt="enter image description here"></p>
| 20,696,013 | 4 | 2 | null |
2013-12-20 02:59:27.88 UTC
| 11 |
2014-08-01 15:07:28.31 UTC
|
2013-12-20 03:45:59.82 UTC
| null | 1,986,282 | null | 2,147,863 | null | 1 | 5 |
android|progress-bar
| 9,670 |
<p>xml file code:</p>
<pre><code> <ProgressBar
android:id="@+id/xml_reg_progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/common_left_right_margin"
android:layout_marginRight="@dimen/common_left_right_margin"
android:layout_marginTop="@dimen/reg_ph_linear_top_margin"
/>
</code></pre>
<p>you can change progressbar style as per your requirement.</p>
<p>this is java file code:</p>
<pre><code> protected static final int TIMER_RUNTIME = 180000; // in ms --> 10s
private ProgressBar progressTimer;
public void startTimer() {
final Thread timerThread = new Thread() {
@Override
public void run() {
mbActive = true;
try {
int waited = 0;
while (mbActive && (waited < TIMER_RUNTIME)) {
sleep(1000);
if (mbActive) {
waited += 1000;
updateProgress(waited);
}
}
} catch (InterruptedException e) {
// do nothing
} finally {
onContinue();
}
}
};
timerThread.start();
}
Handler handler = new Handler();
private void onContinue() {
handler.post(new Runnable() {
@Override
public void run() {
txtCallContactUsNumber
.setText(CommonVariable.CallForSupporMessage
+ contactInfo.MobileNo);
}
});
}
public void updateProgress(final int timePassed) {
if (null != progressTimer) {
// Ignore rounding error here
final int progress = progressTimer.getMax() * timePassed
/ TIMER_RUNTIME;
handler.post(new Runnable() {
@Override
public void run() {
Log.i("timePassed", "timePassed=" + timePassed);
DateFormat formatter = new SimpleDateFormat("mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timePassed);
String timer = formatter.format(calendar.getTime());
formatter.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
txtTimerCount.setText(formatter.format(timePassed));
}
});
progressTimer.setProgress(progress);
}
}
</code></pre>
<p>in my code this will call 1 second and get progress increment every 1 second.</p>
|
23,989,463 |
How to set tbody height with overflow scroll
|
<p>I am facing problem while setting tbody height width overflow scroll. </p>
<pre><code><style>
tbody{
height:50px;display:block;overflow:scroll
}
</style>
<h3>Table B</h3>
<table style="border: 1px solid red;width:300px;display:block">
<thead>
<tr>
<td>Name</td>
<td>phone</td>
</tr>
</thead>
<tbody style='height:50px;display:block;overflow:scroll'>
<tr>
<td>AAAA</td>
<td>323232</td>
</tr>
<tr>
<td>BBBBB</td>
<td>323232</td>
</tr>
<tr>
<td>CCCCC</td>
<td>3435656</td>
</tr>
</tbody>
</table>
</code></pre>
<p><a href="http://jsfiddle.net/amit4mins/f2XYF" rel="noreferrer">Visit my fiddle here</a></p>
<p>I want table B like Table A with overflow scroll.</p>
<p>Any help will be appreciated.</p>
<p>Many Thanks,
M.</p>
| 23,989,771 | 15 | 3 | null |
2014-06-02 07:35:58.807 UTC
| 65 |
2022-09-12 12:43:53.477 UTC
| null | null | null | null | 1,643,334 | null | 1 | 190 |
html|css
| 370,124 |
<p>If you want <code>tbody</code> to show a scrollbar, set its <code>display: block;</code>.</p>
<p>Set <code>display: table;</code> for the <code>tr</code> so that it keeps the behavior of a table.</p>
<p>To evenly spread the cells, use <code>table-layout: fixed;</code>.</p>
<p><strong><a href="http://jsfiddle.net/f2XYF/8/" rel="noreferrer">DEMO</a></strong> <img src="https://i.stack.imgur.com/s3sWE.jpg" alt="tbody scroll" /></p>
<hr />
<p>CSS:</p>
<pre><code>table, tr td {
border: 1px solid red
}
tbody {
display: block;
height: 50px;
overflow: auto;
}
thead, tbody tr {
display: table;
width: 100%;
table-layout: fixed;/* even columns width , fix width of table too*/
}
thead {
width: calc( 100% - 1em )/* scrollbar is average 1em/16px width, remove it from thead width */
}
table {
width: 400px;
}
</code></pre>
<hr />
<p>If <code>tbody</code> doesn't show a scroll, because content is less than <code>height</code> or <code>max-height</code>, set the scroll any time with: <code>overflow-y: scroll;</code>. <strong><a href="http://jsfiddle.net/f2XYF/16/" rel="noreferrer">DEMO 2</a></strong></p>
<hr />
<p><strong><code><editS/updateS></code></strong> 2019 - 04/2021</p>
<hr />
<ul>
<li><strong>Important note:</strong> this approach to making a table scrollable has drawbacks in some cases. (See comments below.) <em>some of the duplicate answers in this thread deserves the same warning by the way</em></li>
</ul>
<blockquote>
<p>WARNING: this solution disconnects the thead and tbody cell grids; which means that in most practical cases, you will not have the cell alignment you expect from tables. Notice this solution uses a hack to keep them sort-of aligned: thead { width: calc( 100% - 1em ) }</p>
</blockquote>
<ul>
<li><p>Anyhow, to set a scrollbar, a display reset is needed to get rid of the table-layout (which will never show scrollbar).</p>
</li>
<li><p>Turning the <code><table></code> into a grid via <code>display:grid</code>/<code>contents</code> will also leave a gap in between header and scrollable part, to mind about. (idem if built from divs)</p>
</li>
<li><p><code>overflow:overlay;</code> has not yet shown up in Firefox <em>( keep watching it)</em></p>
</li>
<li><p><code>position:sticky</code> will require a parent container which can be the scrolling one. make sure your <code>thead</code> can be sticky if you have a few rows and <code>rowspan/colspan</code> headers in it (it does not with chrome).</p>
</li>
</ul>
<p><strong>So far, there is no perfect solution yet via CSS only</strong>. there is a few average ways to choose along so it fits your own table (table-layout:fixed; is .. fixing table and column's width, but javascript could probably be used to reset those values => exit pure CSS)</p>
|
3,821,573 |
Change a style dynamically in WPF
|
<p>Is there a way to change(and apply) a style dynamically in WPF?</p>
<p>Say I have the style declared in XAML:</p>
<pre><code> <Style TargetType="local:MyLine"
x:Key="MyLineStyleKey" x:Name="MyLineStyleName">
<Setter Property="Fill" Value="Pink"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Fill" Value="Blue" />
</Trigger>
</Style.Triggers>
</Style>
</code></pre>
<ol>
<li><p>In a moment, I need to <strong>change</strong> the <code>Pink</code> color, to, say <code>Green</code>, and all lines with style <code>MyLineStyleKey</code> became Green. A line is Pink when released, and Blue when selected... Now, I needed to change the unselected property(Pink to Green)..., so this is not just setting it to an other color, the trigger (selection>Blue) will not work anymore...Is that possible? How?</p></li>
<li><p>Is that possible to <strong>bind</strong> to the Pink color in the Style, say, to a Button background, that will reflect the currently used style color?</p></li>
</ol>
<p>EDIT:<br>
For <strong>1</strong> I tried:</p>
<pre><code>Style s = (Style)this.Resources["MyLineStyleKey"];
(s.Setters[0] as Setter).Value = background;
(s.Setters[1] as Setter).Value = background;
</code></pre>
<p>but an exception occured: </p>
<blockquote>
<p>After a 'SetterBase' is in use
(sealed), it cannot be modified.</p>
</blockquote>
| 3,822,254 | 2 | 1 | null |
2010-09-29 12:32:22.213 UTC
| 6 |
2013-05-17 12:25:55.067 UTC
|
2011-08-16 16:02:40.937 UTC
| null | 305,637 | null | 185,593 | null | 1 | 20 |
wpf|styles
| 40,850 |
<p>Create a brush as a resource</p>
<pre><code><SolidColorBrush x:Key="MyFillBrush" Color="Pink" />
</code></pre>
<p>and refer to that in your style</p>
<pre><code><Style x:Key="MyShapeStyle" TargetType="Shape">
<Setter Property="Fill" Value="{DynamicResource MyFillBrush}" />
</Style>
...
<!-- Then further down you may use it like this -->
<StackPanel Width="100">
<Rectangle Style="{StaticResource MyShapeStyle}" Height="50" Margin="8" />
<Rectangle Style="{StaticResource MyShapeStyle}" Height="50" Margin="8" />
<Ellipse Style="{StaticResource MyShapeStyle}" Height="50" Margin="8" />
<Button Content="Click to change color" Click="Button_Click" Margin="8" />
</StackPanel>
</code></pre>
<p>Now to change the color of all shapes that use the "MyShapeStyle" style, you can do the following from your code-behind:</p>
<pre><code>private void Button_Click(object sender, RoutedEventArgs e)
{
Random r = new Random();
this.Resources["MyFillBrush"] = new SolidColorBrush(Color.FromArgb(
0xFF,
(byte)r.Next(255),
(byte)r.Next(255),
(byte)r.Next(255)));
}
</code></pre>
<p>The thing that makes this work is the fact that you use a <code>DynamicResource</code> for the brush reference in your style - this tells WPF to monitor that resource for changes. If you use a <code>StaticResource</code> instead, you won't get this behavior.</p>
|
3,952,476 |
How to remove a specific pair from a C++ multimap?
|
<pre><code>#include <map>
...
multimap<char,int> mymap;
mymap.insert(pair<char,int>('a',10));
mymap.insert(pair<char,int>('b',15));
mymap.insert(pair<char,int>('b',20));
mymap.insert(pair<char,int>('c',25));
</code></pre>
<p>Say I now want to remove one of the pairs I have just added to the map.</p>
<p>I have examples to remove an entire key entry, which for key 'b' would remove both 'b',15 and 'b',20.</p>
<p>But what is the code to remove just, say, the pair 'b',20?</p>
| 3,952,480 | 2 | 0 | null |
2010-10-17 07:58:33.4 UTC
| 5 |
2021-02-02 13:58:32.353 UTC
|
2021-02-02 13:58:32.353 UTC
| null | 82,515 | null | 82,515 | null | 1 | 29 |
c++|containers|multimap
| 20,221 |
<p>You can use <code>std::multimap<char, int>::equal_range</code>, which will give you an iterator range containing all pairs which have a certain key. So if you look for 'b', you will get an iterator range containing all pairs which have 'b' as the key. </p>
<p>You can then simply iterate over the range, and erase any pair you see fit, by erasing the iterator.</p>
<pre><code>multimap<char,int> mymap;
mymap.insert(pair<char,int>('a',10));
mymap.insert(pair<char,int>('b',15));
mymap.insert(pair<char,int>('b',20));
mymap.insert(pair<char,int>('c',25));
typedef multimap<char, int>::iterator iterator;
std::pair<iterator, iterator> iterpair = mymap.equal_range('b');
// Erase (b,15) pair
//
iterator it = iterpair.first;
for (; it != iterpair.second; ++it) {
if (it->second == 15) {
mymap.erase(it);
break;
}
}
</code></pre>
|
4,012,167 |
Java final modifier
|
<p>I was told that, I misunderstand effects of <code>final</code>. What are the effects of <code>final</code> keyword?</p>
<p>Here is short overview of what I think, I know:</p>
<blockquote>
<h3>Java final modifier (aka aggregation relation)</h3>
<p><strong>primitive variables</strong>: can be set only once. (memory and performance
gain)<br>
<strong>objects variables</strong>: may be modified, final applies to object
reference.<br>
<strong>fields</strong>: can be set only once.<br>
<strong>methods</strong>: can't be overridden, hidden.<br>
<strong>classes</strong>: can't be extended.<br>
<strong>garbage collection</strong>: will force Java generational garbage collection
mark-sweep to double sweep.</p>
</blockquote>
<h3>Can's and Cant's</h3>
<ul>
<li>Can make clone fail (this is both good and bad)</li>
<li>Can make immutable primitives aka const</li>
<li>Can make blank immutable - initialized at creation aka readonly</li>
<li>Can make objects shallowly immutable </li>
<li>Can make scope / visibility immutable</li>
<li>Can make method invocation overhead smaller (because it does not need virtual table)</li>
<li>Can make method arguments used as final (even if thy are not)</li>
<li>Can make objects threadsafe (if object is defined as final, it wont make method arguments final)</li>
<li>Can make mock tests (not that you could do anything about it - you can say bugs are intended)</li>
<li>Can't make friends (mutable with other friends and immutable for rest)</li>
<li>Can't make mutable that is changed to be immutable later (but can with factory pattern like fix)</li>
<li>Can't make array elements immutable aka deeply immutable</li>
<li>Can't make new instances of object (this is both good and bad)</li>
<li>Can't make serialization work</li>
</ul>
<p>There are no alternatives to <code>final</code>, but there is wrapper + private and enums.</p>
| 4,012,219 | 2 | 1 | null |
2010-10-25 06:06:42.063 UTC
| 48 |
2015-07-28 19:30:32.583 UTC
|
2010-10-28 23:39:04.76 UTC
| null | 97,754 | null | 97,754 | null | 1 | 54 |
java|final
| 35,543 |
<p>Answering each of your points in turn:</p>
<blockquote>
<p>primitive variables: can be set only once. (memory and performance gain)</p>
</blockquote>
<p>Yes, but no memory gain, and no performance gain. (Your supposed performance gain comes from setting only once ... not from <code>final</code>.)</p>
<blockquote>
<p>objects variables: may be modified, final applies to object reference.</p>
</blockquote>
<p>Yes. (However, this description miss the point that this is entirely consistent with the way that the rest of the Java language deals with the object / reference duality. For instance, when objects are passed as parameters and returned as results.)</p>
<blockquote>
<p>fields: can be set only once.</p>
</blockquote>
<p>The real answer is: same as for variables.</p>
<blockquote>
<p>methods: can't be overridden, hidden.</p>
</blockquote>
<p>Yes. But also note that what is going on here is that the <code>final</code> keyword is being used in a different syntactic context to mean something different to <code>final</code> for an field / variable.</p>
<blockquote>
<p>classes: can't be extended.</p>
</blockquote>
<p>Yes. But also see note above.</p>
<blockquote>
<p>garbage collection: will force Java generational garbage collection mark-sweep to double sweep.</p>
</blockquote>
<p>This is nonsense. The <code>final</code> keyword has no relevance <em>whatsoever</em> to garbage collection. You might be confusing <code>final</code> with finalization ... they are unrelated.</p>
<p>But even finalizers don't force an extra sweep. What happens is that an object that needs finalization is set on one side until the main GC finishes. The GC then runs the finalize method on the object and sets its flag ... and continues. The next time the GC runs, the object is treated as a normal object:</p>
<ul>
<li>if it is reachable it is marked and copied</li>
<li>if it is not reachable it is not marked.</li>
</ul>
<p>(Your characterization - "Java generational garbage collection mark-sweep" is garbled. A garbage collector can be either "mark-sweep" OR "generational" (a subclass of "copying"). It can't be both. Java normally uses generational collection, and only falls back to mark-sweep in emergencies; i.e. when running out of space or when a low pause collector cannot keep up.)</p>
<blockquote>
<p>Can make clone fail (this is both good and bad)</p>
</blockquote>
<p>I don't think so.</p>
<blockquote>
<p>Can make immutable primitives aka const</p>
</blockquote>
<p>Yes.</p>
<blockquote>
<p>Can make blank immutable - initialized at creation aka readonly</p>
</blockquote>
<p>Yes ... though I've never heard the term "blank immutable" used before.</p>
<blockquote>
<p>Can make objects shallowly immutable</p>
</blockquote>
<p>Object mutability is about whether observable state may change. As such, declaring attributes <code>final</code> may or may not make the object behave as immutable. Besides the notion of "shallowly immutable" is not well defined, not least because the notion of what "shallow" is cannot be mapped without deep knowledge of the class semantics.</p>
<p>(To be clear, the mutability of variables / fields is a well defined concept in the context of the JLS. It is just the concept of mutability of objects that is undefined from the perspective of the JLS.)</p>
<blockquote>
<p>Can make scope / visibility immutable</p>
</blockquote>
<p>Terminology error. Mutability is about object state. Visibility and scope are not.</p>
<blockquote>
<p>Can make method invocation overhead smaller (because it does not need virtual table)</p>
</blockquote>
<p>In practice, this is irrelevant. A modern JIT compiler does this optimization for non-final methods too, if they are not overridden by any class that the application actually uses. (Clever stuff happens ...)</p>
<blockquote>
<p>Can make method arguments used as final (even if thy are not)</p>
</blockquote>
<p>Huh? I cannot parse this sentence.</p>
<blockquote>
<p>Can make objects threadsafe </p>
</blockquote>
<p>In certain situations yes.</p>
<blockquote>
<p>(if object is defined as final, it wont make method arguments final)</p>
</blockquote>
<p>Yes, if you mean if <em>class</em> is final. Objects are not final.</p>
<blockquote>
<p>Can make mock tests (not that you could do anything about it - you can say bugs are intended)</p>
</blockquote>
<p>Doesn't parse.</p>
<blockquote>
<p>Can't make friends (mutable with other friends and immutable for rest)</p>
</blockquote>
<p>Java doesn't have "friends".</p>
<blockquote>
<p>Can't make mutable that is changed to be immutable later (but can with factory pattern like fix)</p>
</blockquote>
<p>Yes to the first, a <code>final</code> field can't be switched from mutable to immutable. </p>
<p>It is unclear what you mean by the second part. It is true that you can use a factory (or builder) pattern to construct immutable objects. However, if you use <code>final</code> for the object fields at no point will the object be mutable. </p>
<p>Alternatively, you can implement immutable objects that use non-final fields to represent immutable state, and you can design the API so that you can "flip a switch" to make a previously mutable object immutable from now onwards. But if you take this approach, you need to be a lot more careful with synchronization ... if your objects need to be thread-safe.</p>
<blockquote>
<p>Can't make array elements immutable aka deeply immutable</p>
</blockquote>
<p>Yes, but your terminology is broken; see comment above about "shallow mutability".</p>
<blockquote>
<p>Can't make new instances of object (this is both good and bad)</p>
</blockquote>
<p>No. There's nothing stopping you making a new instance of an object with final fields or a final class or final methods.</p>
<blockquote>
<p>Can't make serialization work</p>
</blockquote>
<p>No. Serialization works. (Granted, deserialization of <code>final</code> fields using a custom <code>readObject</code> method presents problems ... though you can work around them using reflection hacks.)</p>
<blockquote>
<p>There are no alternatives to final,</p>
</blockquote>
<p>Correct.</p>
<blockquote>
<p>but there is wrapper + private </p>
</blockquote>
<p>Yes, modulo that (strictly speaking) an unsynchronized getter for a non-final field may be non-thread-safe ... <em>even if it is initialized during object construction and then never changed</em>!</p>
<blockquote>
<p>and enums.</p>
</blockquote>
<p>Solves a different problem. And <code>enums</code> can be mutable.</p>
|
9,346,211 |
How to kill a process on a port on ubuntu
|
<p>I am trying to kill a process in the command line for a specific port in ubuntu.</p>
<p>If I run this command I get the port:</p>
<pre><code>sudo lsof -t -i:9001
</code></pre>
<p>so...now I want to run:</p>
<pre><code>sudo kill 'sudo lsof -t -i:9001'
</code></pre>
<p>I get this error message:</p>
<pre><code>ERROR: garbage process ID "lsof -t -i:9001".
Usage:
kill pid ... Send SIGTERM to every process listed.
kill signal pid ... Send a signal to every process listed.
kill -s signal pid ... Send a signal to every process listed.
kill -l List all signal names.
kill -L List all signal names in a nice table.
kill -l signal Convert between signal numbers and names.
</code></pre>
<p>I tried <code>sudo kill 'lsof -t -i:9001'</code> as well</p>
| 9,346,231 | 27 | 2 | null |
2012-02-19 02:44:33.583 UTC
| 291 |
2022-08-10 07:36:21.79 UTC
|
2019-10-29 17:49:24.497 UTC
| null | 13,302 | null | 1,203,556 | null | 1 | 793 |
ubuntu|port|kill
| 1,452,597 |
<p>You want to use backtick, not regular tick:</p>
<pre class="lang-sh prettyprint-override"><code>sudo kill -9 `sudo lsof -t -i:9001`
</code></pre>
<p>If that doesn't work, you could also use <code>$()</code> for command interpolation:</p>
<pre class="lang-sh prettyprint-override"><code>sudo kill -9 $(sudo lsof -t -i:9001)
</code></pre>
|
16,294,821 |
PHP string number concatenation messed up
|
<p>I got some PHP code here:</p>
<pre><code><?php
echo 'hello ' . 1 + 2 . '34';
?>
</code></pre>
<p>which outputs 234,</p>
<p>But when I add a number 11 before "hello":</p>
<pre><code><?php
echo '11hello ' . 1 + 2 . '34';
?>
</code></pre>
<p>It outputs 1334 rather than 245 (which I expected it to). Why is that?</p>
| 16,294,882 | 5 | 1 | null |
2013-04-30 07:48:57.943 UTC
| 0 |
2021-05-27 20:26:04.82 UTC
|
2021-05-27 20:26:04.82 UTC
| null | 63,550 | null | 2,334,972 | null | 1 | 15 |
php|string|concatenation|operator-keyword|operator-precedence
| 42,400 |
<p>That's strange...</p>
<p>But</p>
<pre><code><?php
echo '11hello ' . (1 + 2) . '34';
?>
</code></pre>
<p><em>or</em></p>
<pre><code><?php
echo '11hello ', 1 + 2, '34';
?>
</code></pre>
<p>fixes the issue.</p>
<hr />
<p><em><strong>UPDATE v1:</strong></em></p>
<p>I finally managed to get the proper answer:</p>
<p><code>'hello'</code> = <code>0</code> (contains no leading digits, so PHP assumes it is zero).</p>
<p>So <code>'hello' . 1 + 2</code> simplifies to <code>'hello1' + 2</code> is <code>2</code>. Because there aren't any leading digits in <code>'hello1'</code> it is zero too.</p>
<hr />
<p><code>'11hello '</code> = <code>11</code> (contains leading digits, so PHP assumes it is eleven).</p>
<p>So <code>'11hello ' . 1 + 2</code> simplifies to <code>'11hello 1' + 2</code> as <code>11 + 2</code> is <code>13</code>.</p>
<hr />
<p><em><strong>UPDATE v2:</strong></em></p>
<p>From <em><a href="http://www.php.net/manual/en/language.types.string.php" rel="nofollow noreferrer">Strings</a></em>:</p>
<blockquote>
<p>The value is given by the initial portion of the string. If the string
starts with valid numeric data, this will be the value used.
Otherwise, the value will be 0 (zero). Valid numeric data is an
optional sign, followed by one or more digits (optionally containing a
decimal point), followed by an optional exponent. The exponent is an
'e' or 'E' followed by one or more digits.</p>
</blockquote>
|
16,194,212 |
How to suppress warnings globally in an R Script
|
<p>I have a long R script that throws some warnings, which I can ignore.
I could use </p>
<pre><code>suppressWarnings(expr)
</code></pre>
<p>for single statements. But how can I suppress warnings in R globally? Is there an option for this?</p>
| 16,194,365 | 5 | 0 | null |
2013-04-24 14:09:30.167 UTC
| 44 |
2021-07-02 09:07:16.007 UTC
|
2015-04-07 12:55:37.307 UTC
| null | 190,277 | null | 1,863,648 | null | 1 | 210 |
r|warnings
| 253,863 |
<p>You could use</p>
<pre><code>options(warn=-1)
</code></pre>
<p>But note that turning off warning messages globally might not be a good idea.</p>
<p>To turn warnings back on, use</p>
<pre><code>options(warn=0)
</code></pre>
<p>(or whatever your default is for <code>warn</code>, see <a href="https://stackoverflow.com/a/32719422/2093469">this answer</a>)</p>
|
16,353,729 |
Why isn't my Pandas 'apply' function referencing multiple columns working?
|
<p>I have some problems with the Pandas apply function, when using multiple columns with the following dataframe</p>
<pre><code>df = DataFrame ({'a' : np.random.randn(6),
'b' : ['foo', 'bar'] * 3,
'c' : np.random.randn(6)})
</code></pre>
<p>and the following function</p>
<pre><code>def my_test(a, b):
return a % b
</code></pre>
<p>When I try to apply this function with :</p>
<pre><code>df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1)
</code></pre>
<p>I get the error message:</p>
<pre><code>NameError: ("global name 'a' is not defined", u'occurred at index 0')
</code></pre>
<p>I do not understand this message, I defined the name properly. </p>
<p>I would highly appreciate any help on this issue</p>
<p>Update</p>
<p>Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as:</p>
<pre><code>def my_test(a):
cum_diff = 0
for ix in df.index():
cum_diff = cum_diff + (a - df['a'][ix])
return cum_diff
</code></pre>
| 16,354,730 | 6 | 2 | null |
2013-05-03 07:25:48.87 UTC
| 90 |
2019-03-04 02:36:10.523 UTC
|
2019-03-04 02:36:10.523 UTC
| null | 202,229 | null | 2,331,506 | null | 1 | 250 |
python|python-2.7|pandas|dataframe|apply
| 428,378 |
<p>Seems you forgot the <code>''</code> of your string.</p>
<pre><code>In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)
In [44]: df
Out[44]:
a b c Value
0 -1.674308 foo 0.343801 0.044698
1 -2.163236 bar -2.046438 -0.116798
2 -0.199115 foo -0.458050 -0.199115
3 0.918646 bar -0.007185 -0.001006
4 1.336830 foo 0.534292 0.268245
5 0.976844 bar -0.773630 -0.570417
</code></pre>
<p>BTW, in my opinion, following way is more elegant:</p>
<pre><code>In [53]: def my_test2(row):
....: return row['a'] % row['c']
....:
In [54]: df['Value'] = df.apply(my_test2, axis=1)
</code></pre>
|
28,901,893 |
Why is main window of type double optional?
|
<p>When accessing <code>UIapplication's</code> main window it is returned as a <code>UIWindow??</code></p>
<pre><code>let view = UIApplication.sharedApplication().delegate?.window // view:UIWindow??
</code></pre>
<p>Why is it returning as a double optional and what does it mean and if put into a <code>if let</code> should I add one <code>!</code> after it?</p>
<pre><code>if let view = UIApplication.sharedApplication().delegate?.window!
</code></pre>
<p>My first though was to replace <code>?</code> with a <code>!</code> after delegate but that was not the solution.</p>
| 28,902,549 | 4 | 5 | null |
2015-03-06 15:22:01.16 UTC
| 10 |
2017-01-12 19:06:00.01 UTC
| null | null | null | null | 1,296,280 | null | 1 | 43 |
ios|swift|option-type|uiwindow
| 5,442 |
<p>@matt has the details, but there is a (somewhat horrible, somewhat awesome) workaround. (See edit below, though)</p>
<pre><code>let window = app.delegate?.window??.`self`()
</code></pre>
<p>I will leave the understanding of this line of code as an exercise for the reader.</p>
<p>OK, I lie, let's break it down.</p>
<pre><code>app.delegate?.window
</code></pre>
<p>OK, so far so good. At this point we have the <code>UIWindow??</code> that is giving us a headache (and I believe is a <strike>bug in Swift</strike> disconnect between Swift and Cocoa). We want to collapse it twice. We can do that with optional chaining (<code>?.</code>), but that unwraps and rewraps, so we're back where we started from. You can double-optional-chain, though, with <code>??.</code> which is bizarre, but works.</p>
<p>That's great, but <code>??</code> isn't a legal suffix operator. You have to actually chain to something. Well, we want to chain back to itself (i.e. "identity"). The <code>NSObject</code> protocol gives us an identity method: <code>self</code>.</p>
<p><code>self</code> is a method on <code>NSObject</code>, but it's also a reserved word in Swift, so the syntax for it is <code>`self`()</code></p>
<p>And so we get our madness above. Do with it as you will. </p>
<p>Note that since <code>??.</code> works, you don't technically need this. You can just accept that <code>view</code> is <code>UIWindow??</code> and use <code>??.</code> on it like <code>view??.frame</code>. It's a little noisy, but probably doesn't create any real problems for the few places it should be needed.</p>
<p>(*) I used to think of this as a bug in Swift, but it's not fixable directly by optional chaining. The problem is that there is no optional chaining past <code>window</code>. So I'm not sure where the right place to fix it is. Swift could allow a postfix-<code>?</code> to mean "flatten" without requiring chaining, but that feels odd. I guess the right operator would be interrobang <code>delegate?.window‽</code> :D I'm sure that wouldn't cause any confusion.</p>
<p>EDIT:</p>
<p><a href="https://twitter.com/jl_hfl/status/573880245578776577">Joseph Lord pointed out the better solution</a> (which is very similar to techniques I've been using to avoid trivial if-let, but hadn't thought of this way before):</p>
<pre><code>let window = app.delegate?.window ?? nil // UIWindow?
</code></pre>
<p>I agree with him that this is the right answer.</p>
|
17,260,258 |
Spring <constructor-arg> element must specify a ref or value
|
<p>I'm having a problem with Spring and constructor injection. I want to create dynamically objects with a name (<code>String</code>) and special id (<code>long</code>).</p>
<p>But when the spring.xml file is loaded an exception occurs.</p>
<blockquote>
<p>Exception in thread "main" java.lang.ExceptionInInitializerError</p>
<p>Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'someBean' defined in class path resource [spring.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [long]: Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments?</p>
</blockquote>
<p>My spring.xml:</p>
<pre><code> <bean id="someBean" class="someClass" >
<constructor-arg index="0" type="java.lang.String" value=""/>
<constructor-arg index="1" type="long" value=""/>
</bean>
</beans>
</code></pre>
<p>So what's wrong there? The constructor-arg has index 1 (and not 0, as the exception says)</p>
| 17,260,393 | 1 | 3 | null |
2013-06-23 11:23:59.933 UTC
| null |
2014-07-05 09:26:57.977 UTC
|
2020-06-20 09:12:55.06 UTC
| null | -1 | null | 752,301 | null | 1 | 10 |
java|spring|constructor-injection
| 42,619 |
<p>In the constructor arguments you can use either a primitive type <code>long</code> and value <code>0</code>, or a wrapper type <code>java.lang.Long</code> and an empty value. Also, to keep things under control, I would set a value of the second argument explicitly to 0.</p>
|
27,281,317 |
cx_Freeze - Preventing including unneeded packages
|
<p>I have coded a tiny python program using PyQt4. Now, I want to use cx_Freeze to create a standalone application. Everything works fine - cx_Freeze includes automatically all necessary modules; the resulting exe works.</p>
<p>The only problem is that cx_Freeze packs plenty of unneeded modules into the standalone. Even though I only use QtCore and QtGui, also modules like sqlite3, QtNetwork, or QtScript are included. Surprisingly, I find also PyQt5 dlls in the resulting folder. It seems to me as if cx_Freeze uses all PyQt packages that I have installed. The result is a 200Mb program - albeit I only wrote a tiny script.</p>
<p>How can I prevent this behaviour? </p>
<p>I use the following setup.py:</p>
<pre><code>import sys
from cx_Freeze import setup, Executable
setup(
name="MyProgram",
version="0.1",
description="MyDescription",
executables=[Executable("MyProgram.py", base = "Win32GUI")],
)
</code></pre>
<p>I tried explicitely excluding some packages (although it is quite messy to exclude all unused Qt modules) adding this code:</p>
<pre><code>build_exe_options = {"excludes": ["tkinter", "PyQt4.sqlite3",
"PyQt4.QtOpenGL4", "PyQt4.QtSql"]}
</code></pre>
<p>but the upper modules were still used. I also tried</p>
<pre><code>build_exe_options = {"excludes": ["tkinter", "PyQt4.sqlite3",
"QtOpenGL4", "QtSql"]}
</code></pre>
<p>with the same result. </p>
<p>In addition to the nedless Qt packages I find also unneded folders with names like "imageformats", "tcl", and "tk". How can I include <strong>only</strong> needed files in order to keep the standalone folder and installer as small as possible?</p>
<p>I googled this problem for hours but only found <a href="https://stackoverflow.com/questions/16769479/how-to-disable-cx-freeze-to-autodetect-all-modules">this thread</a> which did not help me. </p>
<p>I am running python 3.4.2 amd64 on windows 8.</p>
<p>I am happy about every solution that gives me the desired result "standalone" with a reasonable size. I tried also pyqtdeploy but ran into the error: Unknown module(s) in QT (but this is a different question).</p>
<h2>Edit:</h2>
<p>I am using two modules. One is the GUI class created by uic, "MyProgramGUIPreset". In this file there are the following import commands:</p>
<pre><code>from PyQt4 import QtCore, QtGui
from matplotlibwidget import MatplotlibWidget
</code></pre>
<p>In the main module I do the following imports:</p>
<pre><code>import MyProgramGUIPreset
import numpy as np
from PyQt4.QtGui import QApplication, QMainWindow, QMessageBox
import sys
from math import *
</code></pre>
<p>Maybe this helps to figuring out where the issue is.</p>
| 27,436,548 | 4 | 6 | null |
2014-12-03 20:48:11.683 UTC
| 8 |
2022-01-09 06:30:42.85 UTC
|
2017-05-23 12:09:00.433 UTC
| null | -1 | null | 4,321,462 | null | 1 | 21 |
python|deployment|pyqt|cx-freeze
| 20,804 |
<p>The reason for the not working "excludes" command was that I forgot to include the build options into the setup. After adding the respective line into the code excluding works:</p>
<pre><code>from cx_Freeze import setup, Executable
import sys
# exclude unneeded packages. More could be added. Has to be changed for
# other programs.
build_exe_options = {"excludes": ["tkinter", "PyQt4.QtSql", "sqlite3",
"scipy.lib.lapack.flapack",
"PyQt4.QtNetwork",
"PyQt4.QtScript",
"numpy.core._dotblas",
"PyQt5"],
"optimize": 2}
# Information about the program and build command. Has to be adjusted for
# other programs
setup(
name="MyProgram", # Name of the program
version="0.1", # Version number
description="MyDescription", # Description
options = {"build_exe": build_exe_options}, # <-- the missing line
executables=[Executable("MyProgram.py", # Executable python file
base = ("Win32GUI" if sys.platform == "win32"
else None))],
)
</code></pre>
<p>This decreased the program size from 230MB to 120MB. Nevertheless, I did not find a nice way of excluding all unneeded packages. By trial and error (deleting the biggest files in the build folder test-wise) I figured out which classes I can exclude. </p>
<p>I tried whether the matplotlib backends cause the problem and finally figured out that this is not the case. Nontheless, if anybody needs code to exclude all modules of a certain name scheme in a particular folder except some special ones, he may adjust the following to his needs:</p>
<pre><code>mplBackendsPath = os.path.join(os.path.split(sys.executable)[0],
"Lib/site-packages/matplotlib/backends/backend_*")
fileList = glob.glob(mplBackendsPath)
moduleList = []
for mod in fileList:
modules = os.path.splitext(os.path.basename(mod))[0]
if not module == "backend_qt4agg":
moduleList.append("matplotlib.backends." + modules)
build_exe_options = {"excludes": ["tkinter"] + moduleList, "optimize": 2}
</code></pre>
<p>I would be happy about more elegant solutions. Further ideas are still welcome. Nevertheless, I regard the problem as solved for me.</p>
|
19,640,055 |
Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad
|
<p>I have to implement the multiple markers functionality from array of addresses. The string of addresses are being fetched from the database.</p>
<p>My array of addresses looks like this</p>
<pre><code> var address = <?php echo $add_js ?>;
</code></pre>
<p>I have gone through so many examples on internet and even in this forum, but in most of the examples latitude and longitude is already available in those databases. Is there any way so that i use that array of address and put multiple markers on google map.
or any example where this type of concept is explained?!</p>
<p>I have practiced this example from JSFIDDLE but i am getting no output.</p>
<pre><code> <script>
var geocoder;
var map;
var markersArray = [];
function initialize()
{
geocoder = new google.maps.Geocoder();
latlang = geocoder.geocode( {
'address': 'New Delhi, India'},
function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
markersArray.push(marker);
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
var myOptions =
{
center: latlang, zoom: 5,
mapTypeId: google.maps.MapTypeId.SATELLITE,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
plotMarkers();
}
var locationsArray = new Array(
"New Delhi, India", "Gurgaon,Haryana, India", "Mumbai, India",
"Noida Sector-63,India","Banglore, Karnataka,India");
function plotMarkers(){
for(var i = 0; i < locationsArray.length; i++){
codeAddresses(locationsArray[i]);
}
}
function codeAddresses(address){
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
//markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</code></pre>
| 21,398,675 | 3 | 7 | null |
2013-10-28 16:25:20.983 UTC
| 33 |
2018-07-11 07:11:36.367 UTC
|
2014-01-28 06:43:34.85 UTC
| null | 2,568,747 | null | 2,568,747 | null | 1 | 29 |
javascript|arrays|google-maps|google-maps-api-3
| 125,249 |
<p>Answer to add multiple markers.</p>
<p><strong>UPDATE (GEOCODE MULTIPLE ADDRESSES)</strong></p>
<p>Here's the working Example Geocoding with multiple addresses.</p>
<pre><code> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var delay = 100;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(21.0000, 78.0000);
var mapOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = [
'New Delhi, India',
'Mumbai, India',
'Bangaluru, Karnataka, India',
'Hyderabad, Ahemdabad, India',
'Gurgaon, Haryana, India',
'Cannaught Place, New Delhi, India',
'Bandra, Mumbai, India',
'Nainital, Uttranchal, India',
'Guwahati, India',
'West Bengal, India',
'Jammu, India',
'Kanyakumari, India',
'Kerala, India',
'Himachal Pradesh, India',
'Shillong, India',
'Chandigarh, India',
'Dwarka, New Delhi, India',
'Pune, India',
'Indore, India',
'Orissa, India',
'Shimla, India',
'Gujarat, India'
];
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
</code></pre>
<p>As we can resolve this issue with <code>setTimeout()</code> function. </p>
<p>Still we should not geocode known locations every time you load your page as said by @geocodezip</p>
<p>Another alternatives of these are explained very well in the following links:</p>
<p><a href="https://gis.stackexchange.com/questions/15052/how-to-avoid-google-map-geocode-limit?newreg=fa34116a6a0c4b33a18f38ba7762263b">How To Avoid GoogleMap Geocode Limit!</a></p>
<p><a href="http://econym.org.uk/gmap/geomulti.htm" rel="nofollow noreferrer">Geocode Multiple Addresses Tutorial By Mike Williams</a></p>
<p><a href="https://developers.google.com/maps/articles/phpsqlsearch_v3" rel="nofollow noreferrer">Example by Google Developers</a></p>
|
17,575,375 |
How do I convert an Int to a String in C# without using ToString()?
|
<blockquote>
<p>Convert the following int argument into a string without using any native toString functionality.</p>
<pre><code>public string integerToString(int integerPassedIn){
//Your code here
}
</code></pre>
</blockquote>
<p>Since everything inherits from <code>Object</code> and <code>Object</code> has a <code>ToString()</code> method how would you convert an <code>int</code> to a <code>string</code> without using the native <code>ToString()</code> method?</p>
<p>The problem with string concatenation is that it will call <code>ToString()</code> up the chain until it hits one or hits the <code>Object</code> class.</p>
<p>How do you convert an integer to a string in C# without using <code>ToString()</code>?</p>
| 17,575,453 | 10 | 14 | null |
2013-07-10 15:55:01.053 UTC
| 24 |
2020-05-31 14:26:56.753 UTC
|
2018-04-18 14:42:24.623 UTC
| null | 5,175,709 | null | 2,051,392 | null | 1 | 58 |
c#|string|algorithm|int
| 21,149 |
<p>Something like this:</p>
<pre><code>public string IntToString(int a)
{
var chars = new[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var str = string.Empty;
if (a == 0)
{
str = chars[0];
}
else if (a == int.MinValue)
{
str = "-2147483648";
}
else
{
bool isNegative = (a < 0);
if (isNegative)
{
a = -a;
}
while (a > 0)
{
str = chars[a % 10] + str;
a /= 10;
}
if (isNegative)
{
str = "-" + str;
}
}
return str;
}
</code></pre>
<hr>
<p><strong>Update:</strong> Here's another version which is shorter and should perform much better, since it eliminates all string concatenation in favor of manipulating a fixed-length array. It supports bases up to 16, but it would be easy to extend it to higher bases. It could probably be improved further:</p>
<pre><code>public string IntToString(int a, int radix)
{
var chars = "0123456789ABCDEF".ToCharArray();
var str = new char[32]; // maximum number of chars in any base
var i = str.Length;
bool isNegative = (a < 0);
if (a <= 0) // handles 0 and int.MinValue special cases
{
str[--i] = chars[-(a % radix)];
a = -(a / radix);
}
while (a != 0)
{
str[--i] = chars[a % radix];
a /= radix;
}
if (isNegative)
{
str[--i] = '-';
}
return new string(str, i, str.Length - i);
}
</code></pre>
|
30,731,615 |
Floating Action Button not showing fully inside a fragment
|
<p>I am using FAB button along with RecyclerView in a Fragment. This Fragment is an instance of a TabViewPager. I am having a issue with the FAB button. I have placed the RecyclerView and the fab button inside a FrameLayout, where the FAB buttton is positioned bottom right. Now the problem that I am facing is the FAB button is not fully visible. Its half of the portion is hidden as shown in the screenshot below. Can any one help me to solve this issue. Thanks in advance. </p>
<p><img src="https://i.stack.imgur.com/FZ4da.png" alt="FAB with RecyclerView inside FrameLayout"></p>
<p><strong>Note:</strong> The FAB is aligning properly once it is scrolled. The problem arises only if it is ideal (before scrolling done). </p>
<p><strong>fragment.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="10dp"
app:backgroundTint="@color/red"
android:src="@drawable/ic_done"/>
</FrameLayout>
</code></pre>
<p><strong>tabviewpagerlayout.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways" />
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
</code></pre>
| 30,748,817 | 10 | 4 | null |
2015-06-09 12:08:07.617 UTC
| 24 |
2021-02-05 17:47:07.037 UTC
|
2015-06-10 06:24:54.093 UTC
| null | 3,298,272 | null | 3,298,272 | null | 1 | 52 |
android|android-fragments|floating-action-button|androiddesignsupport|android-coordinatorlayout
| 37,853 |
<p>You should move your FAB inside the <code>CoordinatorLayout</code>.
Something like this:</p>
<pre><code><android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.AppBarLayout>
<android.support.v7.widget.Toolbar
app:layout_scrollFlags="scroll|enterAlways" />
<android.support.design.widget.TabLayout/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_gravity="end|bottom"/>
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p>Then you can add the RecyclerView inside the viewPager in this way:</p>
<pre><code>Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new RecyclerViewFragment(), "Tab1");
viewPager.setAdapter(adapter);
</code></pre>
<p>where the RecyclerViewFragment layout is:</p>
<pre><code> <android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</code></pre>
|
26,252,938 |
FullCalendar TypeError: $(...).fullCalendar is not a function
|
<p>I was trying to put FullCalendar 2.1.1 but it is not working:</p>
<pre class="lang-html prettyprint-override"><code><link href='/css/fullcalendar.css' rel='stylesheet' />
<link href='/css/fullcalendar.min.css' rel='stylesheet' />
<link href='/css/fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='/js/moment.min.js'></script>
<script src='/js/jquery.min.js'></script>
<script src='/js/fullcalendar.min.js'></script>
<script src="/js/jquery-ui.custom.min.js"></script>
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
defaultDate: '2014-09-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
});
});
</script>
</code></pre>
<p>When I go to try open it I get the following errors:</p>
<pre><code>SyntaxError: missing ) after argument list ..."'").replace(/"/g,""").replace(/\n/g,"")}function P(t){returnt.replace(/
TypeError: $(...).fullCalendar is not a function
eventLimit: true, // allow "more" link when too many events
</code></pre>
<p>I have followed the Basic Usage Documentation but it still doesn't work.</p>
| 26,253,167 | 9 | 2 | null |
2014-10-08 08:59:44.427 UTC
| 3 |
2021-03-14 18:25:50.323 UTC
|
2019-06-08 11:26:20.83 UTC
| null | 10,607,772 | null | 3,983,283 | null | 1 | 23 |
javascript|jquery|fullcalendar
| 99,000 |
<p>I think you have problem with js try the below urls it may solve your problems,</p>
<pre><code><script src='http://fullcalendar.io/js/fullcalendar-2.1.1/lib/moment.min.js'></script>
<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery.min.js'></script>
<script src="http://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery-ui.custom.min.js"></script>
<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/fullcalendar.min.js'></script>
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
defaultDate: '2014-09-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
});
});
</script>
</code></pre>
<p>If the above code works then download the js files used in script tag</p>
|
10,133,946 |
DataGridView does not refresh after dataset update vb.net
|
<p>I have a vb.net form with a dataGridView</p>
<p>The dataGridView data source is the dgvTableAdapter with this sql statement</p>
<pre><code>SELECT membres.ID, membres.refere_par, bands.titre,
membres_1.prenom & ' ' & membres_1.nom AS reference_nom
FROM ((bands INNER JOIN membres ON bands.ID = membres.[band])
INNER JOIN membres membres_1 ON membres.refere_par = membres_1.ID)
</code></pre>
<p>I delete membres from the membres Table like this</p>
<pre><code>' Get member id
Dim userId As Integer
userId = DataGridView1.Item( 0,0).Value
' Delete the member
Me.MeoshowDataSet2.membres.FindByID(userId).Delete()
Me.MembresTableAdapter.Update(Me.MeoshowDataSet2)
' Refresh datagrid
dataGridView1.Refresh() ' does nothing
</code></pre>
<p>I know the delete statement works because I saw the changes in the database. If I close the form and reopen it, the dataGridView is up to date.</p>
<p>The membres table is an access table</p>
<p>I'm running the app in visual 2010 debug mode.</p>
| 10,134,076 | 5 | 0 | null |
2012-04-13 00:57:40.23 UTC
| null |
2021-03-02 07:32:16.117 UTC
| null | null | null | null | 648,798 | null | 1 | 4 |
vb.net|datagridview|dataset|tableadapter
| 51,069 |
<p>The usual way of doing this is to reset the <code>DataSource</code> of the <code>DataGridView</code>. </p>
<p>Try like this code (with correct code to provide the right table from the dataset):</p>
<pre><code>dataGridView1.DataSource = typeof(List);
dataGridView1.DataSource = dataset.Tables["your table"];
</code></pre>
<p>Calling <code>.Refresh()</code> doesn't work since it only forces a repaint, but the code that paints the grid doesn't know of the changes.</p>
|
32,037,893 |
Numpy: Fix array with rows of different lengths by filling the empty elements with zeros
|
<p>The functionality I am looking for looks something like this:</p>
<pre><code>data = np.array([[1, 2, 3, 4],
[2, 3, 1],
[5, 5, 5, 5],
[1, 1]])
result = fix(data)
print result
[[ 1. 2. 3. 4.]
[ 2. 3. 1. 0.]
[ 5. 5. 5. 5.]
[ 1. 1. 0. 0.]]
</code></pre>
<p>These data arrays I'm working with are really large so I would really appreciate the most efficient solution.</p>
<p>Edit: Data is read in from disk as a python list of lists.</p>
| 32,043,366 | 5 | 8 | null |
2015-08-16 17:20:55.84 UTC
| 7 |
2020-09-27 02:13:24.83 UTC
|
2017-02-08 15:34:23.157 UTC
| null | 2,909,415 | null | 2,909,415 | null | 1 | 33 |
python|arrays|performance|python-2.7|numpy
| 17,673 |
<p>This could be one approach -</p>
<pre><code>def numpy_fillna(data):
# Get lengths of each row of data
lens = np.array([len(i) for i in data])
# Mask of valid places in each row
mask = np.arange(lens.max()) < lens[:,None]
# Setup output array and put elements from data into masked positions
out = np.zeros(mask.shape, dtype=data.dtype)
out[mask] = np.concatenate(data)
return out
</code></pre>
<p>Sample input, output -</p>
<pre><code>In [222]: # Input object dtype array
...: data = np.array([[1, 2, 3, 4],
...: [2, 3, 1],
...: [5, 5, 5, 5, 8 ,9 ,5],
...: [1, 1]])
In [223]: numpy_fillna(data)
Out[223]:
array([[1, 2, 3, 4, 0, 0, 0],
[2, 3, 1, 0, 0, 0, 0],
[5, 5, 5, 5, 8, 9, 5],
[1, 1, 0, 0, 0, 0, 0]], dtype=object)
</code></pre>
|
5,475,003 |
Jquery – Select optgroup in select
|
<p>I have a select with 2 optgroups. Is there a way to call an function only if an option from the first optgroup is selected and call another function if an option from the second optgroup is selected?</p>
| 5,475,181 | 3 | 0 | null |
2011-03-29 15:29:39.967 UTC
| 2 |
2018-10-09 13:11:02.487 UTC
| null | null | null | null | 495,915 | null | 1 | 10 |
jquery|select|optgroup
| 39,000 |
<p>Sure.</p>
<p>HTML:</p>
<pre><code>What is your preferred vacation spot?<br>
<SELECT ID="my_select">
<OPTGROUP LABEL="OptGroup One." id="one">
<OPTION LABEL="Florida">Florida</OPTION>
<OPTION LABEL="Hawaii">Hawaii</OPTION>
<OPTION LABEL="Jersey">Jersey Shore</OPTION>
</OPTGROUP>
<OPTGROUP LABEL="OptGroup Two" id="two">
<OPTION LABEL="Paris">Paris</OPTION>
<OPTION LABEL="London">London</OPTION>
<OPTION LABEL="Florence">Florence</OPTION>
</OPTGROUP>
</SELECT>
</code></pre>
<p>JS:</p>
<pre><code>$("#my_select").change(function(){
var selected = $("option:selected", this);
if(selected.parent()[0].id == "one"){
//OptGroup 1, do something here..
} else if(selected.parent()[0].id == "two"){
//OptGroup 2, do something here
}
});
</code></pre>
<p><strong>Example here: <a href="http://jsfiddle.net/pyG2v/">http://jsfiddle.net/pyG2v/</a></strong></p>
|
18,455,282 |
How to create "svg" object without appending it?
|
<p>Consider the following code:</p>
<pre><code>var svg = d3.select('#somediv').append("svg").attr("width", w).attr("height", h);
</code></pre>
<p>I would like to refactor this code so that it reads more like this:</p>
<pre><code>var svg = makesvg(w, h);
d3.select("#somediv").append(svg);
</code></pre>
<p>Note that, in contrast to the situation shown in the first version, in this second version <code>append</code> <em>does not create</em> the "svg" object; it only appends it to <code>d3.select("#somediv")</code>.</p>
<p>The problem is how to implement the function <code>makesvg</code>. This in turn reduces to the problem: how to instantiate an "svg" object without using <code>append</code> to do this, since one could then do something like:</p>
<pre><code>function makesvg(width, height) {
return _makesvg().attr("width", w).attr("height", h);
}
</code></pre>
<p>So my question boils down to what is the generic equivalent of the hypothetical <code>_makesvg()</code> factory mentioned above?</p>
| 19,951,169 | 6 | 2 | null |
2013-08-27 00:54:38.46 UTC
| 5 |
2018-04-01 20:00:04.21 UTC
|
2014-05-07 14:24:51.107 UTC
| null | 24,874 | null | 559,827 | null | 1 | 38 |
javascript|d3.js
| 14,566 |
<p>You can use the following:</p>
<pre><code>var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
</code></pre>
<p>Note the use of <code>createElementNS</code>. This is required because <code>svg</code> elements are not in the same XHTML namespace as most HTML elements.</p>
<p>This code creates a new <code>svg</code> element, as you would regardless of using D3 or not, and then creates a selection over that single element.</p>
<p>This can be made marginally more succinct but clearer and less error prone as:</p>
<pre><code>var svg = document.createElementNS(d3.ns.prefix.svg, 'svg');
</code></pre>
|
18,532,539 |
Want to disable signals in Django testing
|
<p>So I have various signals and handlers which are sent across apps. However, when I perform tests / go into 'testing mode', I want these handlers to be disabled.</p>
<p>Is there a Django-specific way of disabling signals/handlers when in testing mode? I can think of a very simple way (of including the handlers within an if TESTING clause) but I was wondering if there was a better way built into Django?...</p>
| 18,532,655 | 9 | 1 | null |
2013-08-30 12:06:41.237 UTC
| 11 |
2022-01-25 12:22:48.35 UTC
| null | null | null | null | 2,564,502 | null | 1 | 46 |
django|django-testing|django-signals
| 19,534 |
<p>No, there is not. You can easily make a conditional connection though:</p>
<pre><code>import sys
if not 'test' in sys.argv:
signal.connect(listener, sender=FooModel)
</code></pre>
|
18,627,494 |
How do I assert that two HashMap with Javabean values are equal?
|
<p>I have two <code>HashMap<Integer, Question></code> maps that I would like to compare. <code>Question</code> in this case is a Javabean I have written.</p>
<p>How do I assert that both <code>HashMap</code> are equal? In this scenario, equal means that both <code>HashMap</code> contains exactly the same <code>Question</code> bean?</p>
<p>If it's at all relevant, I am writing a unit test using JUnit.</p>
| 18,651,532 | 9 | 1 | null |
2013-09-05 03:56:25.73 UTC
| 4 |
2022-03-27 15:12:48.86 UTC
| null | null | null | null | 1,170,681 | null | 1 | 16 |
java|hashmap|comparison
| 50,042 |
<p>Here is the solution I eventually ended up using which worked perfectly for unit testing purposes.</p>
<pre><code>for(Map.Entry<Integer, Question> entry : questionMap.entrySet()) {
assertReflectionEquals(entry.getValue(), expectedQuestionMap.get(entry.getKey()), ReflectionComparatorMode.LENIENT_ORDER);
}
</code></pre>
<p>This involves invoking <code>assertReflectionEquals()</code> from the <code>unitils</code> package.</p>
<pre><code><dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-core</artifactId>
<version>3.3</version>
<scope>test</scope>
</dependency>
</code></pre>
|
18,604,408 |
Convert Java string to Time, NOT Date
|
<p>I would like to convert a variable string to a Time type variable, not Date using Java. the string look like this 17:40</p>
<p>I tried using the code below but this instance is a date type variable not time</p>
<pre><code>String fajr_prayertime = prayerTimes.get(0);
DateFormat formatter = new SimpleDateFormat("HH:mm");
fajr_begins = (Date)formatter.parse(fajr_prayertime);
System.out.println(" fajr time " + fajr_begins);
</code></pre>
<p>However Netbean complains that I should insert an exception as below;</p>
<pre><code>DateFormat formatter = new SimpleDateFormat("HH:mm");
try {
fajr_begins = (Date)formatter.parse(fajr_prayertime);
} catch (ParseException ex) {
Logger.getLogger(JavaFXApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(" fajr time " + fajr_begins);
</code></pre>
<p>Any idea how I can get the time out of the string above.</p>
| 18,604,438 | 9 | 4 | null |
2013-09-04 02:16:24.663 UTC
| 7 |
2020-06-17 20:12:22.07 UTC
| null | null | null | null | 612,242 | null | 1 | 30 |
java|string|date|time
| 148,922 |
<pre><code>java.sql.Time timeValue = new java.sql.Time(formatter.parse(fajr_prayertime).getTime());
</code></pre>
|
19,883,531 |
nested try/except in Python
|
<pre><code>try:
commands
try:
commands
try:
commands
try:
commands
except:
commands
return to final commands
except:
commands
return to final commands
except:
commands
return to final commands
except:
commands
final commands
</code></pre>
<p>Which instruction have I to write in place of <code>return to final commands</code> to make that any <code>except</code> returns to the top-level instructions following the outer try? And is it an acceptable structure?</p>
<p>Edit: Here is a toy example (I know I can do it using <code>if</code>s, it's only an example; suppose you have to write it using <code>try</code>/<code>except</code>).</p>
<pre><code># calculate arcsin(log(sqrt(x)-4))
x = choose one yourself
try
x1=sqrt(x)
return to final message
try
x1=log(x1-4)
return to final message
try
x2=arcsin(x1)
return to final message
except
message="Impossible to calculate arcsin: maybe an argument outside [-1,+1]?"
except
message="Impossible to calculate logarithm: maybe a not positive argument?"
except
message="impossible to calculate square root: maybe a negative argument?"
final message:
print message
</code></pre>
| 19,887,222 | 1 | 2 | null |
2013-11-09 21:50:49.79 UTC
| 3 |
2014-04-02 21:10:34.483 UTC
|
2013-11-10 06:09:08.733 UTC
| null | 268,721 | null | 268,721 | null | 1 | 14 |
python|exception-handling|try-catch
| 44,200 |
<p>At the very least you should be able to reduce this structure to only 2 nested levels by reraising the exception to avoid the rest of the block:</p>
<pre><code># calculate arcsin(log(sqrt(x)-4))
x = ?
message = None
try:
try:
x1 = sqrt(x)
except Exception:
message = "can't take sqrt"
raise
try:
x1 = log(x1-4)
except Exception:
message = "can't compute log"
raise
try:
x2 = arcsin(x1)
except Exception:
message = "Can't calculate arcsin"
raise
except Exception:
print message
</code></pre>
<p>Really, this is not the way to do it, at least in this example. The problem is that you are trying to use exceptions like return error codes. What you should be doing is putting the error message into the exception. Also, normally the outer try/except would be in a higher level function:</p>
<pre><code>def func():
try:
y = calculate_asin_log_sqrt(x)
# stuff that depends on y goes here
except MyError as e:
print e.message
# Stuff that happens whether or not the calculation fails goes here
def calculate_asin_log_sqrt(x):
try:
x1 = sqrt(x)
except Exception:
raise MyError("Can't calculate sqrt")
try:
x1 = log(x1-4)
except Exception:
raise MyError("Can't calculate log")
try:
x2 = arcsin(x1)
except Exception:
raise MyError("Can't calculate arcsin")
return x2
</code></pre>
|
20,124,327 |
php shell_exec() command is not working
|
<p>I am trying to run a .sh file from php.
I tried doing it with shell_exec(). but its not working
I refered many questions related to this in stack overflow but could not solve</p>
<p>my php code is(web.php)</p>
<pre><code> <?php
echo shell_exec('/var/www/project/xxe.sh');
echo "done";
?>
</code></pre>
<p>only done is printed. but it is working from terminal(php /var/www/project/web.php)</p>
<p>In xxe.sh I am calling a python file</p>
<pre><code> python vin.py
</code></pre>
<p>I have also changed the file permission to 777 for both .sh n .py files
please help</p>
| 20,124,531 | 8 | 3 | null |
2013-11-21 14:58:53.11 UTC
| 5 |
2019-05-01 18:16:26.173 UTC
| null | null | null | null | 3,018,038 | null | 1 | 22 |
php|shell|python-2.7
| 94,310 |
<p>If it works well in shell, I think apache is chrooted. So php can't find /var/...</p>
<p>Or user of httpd user does not have permission to enter /var/...</p>
<p>If you are good at PHP. Open dir /var/... And readdir() and check dir exists and check file exists.</p>
<p>This question might help you. <a href="https://stackoverflow.com/questions/7188806/scanning-home-with-opendir">scanning /home/ with opendir()</a></p>
|
27,573,192 |
How do I set SSL protocol version in java? And how do I know which one? javax.net.ssl.SSLException: Received fatal alert: protocol_version
|
<p>I am using Apache HttpClient 4.3 to interact with the API of hubic.com. My minimal reproducable example is just a one liner:</p>
<pre class="lang-java prettyprint-override"><code>HttpClientBuilder.create().build().execute(new HttpGet("https://hubic.com"));
</code></pre>
<p>However that throws:</p>
<pre><code>Exception in thread "main" javax.net.ssl.SSLException: Received fatal alert: protocol_version
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1991)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1104)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:275)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:254)
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:117)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:314)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
</code></pre>
<p>Here is the output if I run with <code>System.setProperty("javax.net.debug", "all");</code>:</p>
<pre><code>trustStore is: /usr/lib/jvm/java-8-oracle/jre/lib/security/cacerts
trustStore type is : jks
trustStore provider is :
init truststore
adding as trusted cert: [... extremely large list ...]
trigger seeding of SecureRandom
done seeding SecureRandom
Ignoring unavailable cipher suite: TLS_DHE_DSS_WITH_AES_256_GCM_SHA384
Ignoring unavailable cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA
Ignoring unavailable cipher suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
Ignoring unavailable cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
Ignoring unavailable cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256
Ignoring unavailable cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
Ignoring unavailable cipher suite: TLS_RSA_WITH_AES_256_GCM_SHA384
Ignoring unavailable cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
Ignoring unavailable cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
Ignoring unavailable cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
Ignoring unavailable cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
Ignoring unavailable cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
Ignoring unavailable cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
Ignoring unavailable cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
Ignoring unavailable cipher suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 for SSLv3
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 for SSLv3
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256 for SSLv3
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 for SSLv3
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 for SSLv3
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 for SSLv3
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 for SSLv3
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 for TLSv1.1
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 for TLSv1.1
%% No cached client session
*** ClientHello, TLSv1.2
RandomCookie: GMT: 1402182685 bytes = { 227, 155, 148, 161, 7, 104, 221, 182, 254, 133, 216, 198, 118, 211, 223, 229, 43, 82, 207, 1, 102, 245, 112, 117, 253, 69, 43, 162 }
Session ID: {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods: { 0 }
Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
Extension signature_algorithms, signature_algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA224withECDSA, SHA224withRSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA, MD5withRSA
Extension server_name, server_name: [type=host_name (0), value=hubic.com]
***
[write] MD5 and SHA1 hashes: len = 225
0000: 01 00 00 DD 03 03 54 94 9C 1D E3 9B 94 A1 07 68 ......T........h
0010: DD B6 FE 85 D8 C6 76 D3 DF E5 2B 52 CF 01 66 F5 ......v...+R..f.
0020: 70 75 FD 45 2B A2 00 00 46 C0 23 C0 27 00 3C C0 pu.E+...F.#.'.<.
0030: 25 C0 29 00 67 00 40 C0 09 C0 13 00 2F C0 04 C0 %.).g.@...../...
0040: 0E 00 33 00 32 C0 2B C0 2F 00 9C C0 2D C0 31 00 ..3.2.+./...-.1.
0050: 9E 00 A2 C0 08 C0 12 00 0A C0 03 C0 0D 00 16 00 ................
0060: 13 C0 07 C0 11 00 05 C0 02 C0 0C 00 04 00 FF 01 ................
0070: 00 00 6E 00 0A 00 34 00 32 00 17 00 01 00 03 00 ..n...4.2.......
0080: 13 00 15 00 06 00 07 00 09 00 0A 00 18 00 0B 00 ................
0090: 0C 00 19 00 0D 00 0E 00 0F 00 10 00 11 00 02 00 ................
00A0: 12 00 04 00 05 00 14 00 08 00 16 00 0B 00 02 01 ................
00B0: 00 00 0D 00 1A 00 18 06 03 06 01 05 03 05 01 04 ................
00C0: 03 04 01 03 03 03 01 02 03 02 01 02 02 01 01 00 ................
00D0: 00 00 0E 00 0C 00 00 09 68 75 62 69 63 2E 63 6F ........hubic.co
00E0: 6D m
main, WRITE: TLSv1.2 Handshake, length = 225
[Raw write]: length = 230
0000: 16 03 03 00 E1 01 00 00 DD 03 03 54 94 9C 1D E3 ...........T....
0010: 9B 94 A1 07 68 DD B6 FE 85 D8 C6 76 D3 DF E5 2B ....h......v...+
0020: 52 CF 01 66 F5 70 75 FD 45 2B A2 00 00 46 C0 23 R..f.pu.E+...F.#
0030: C0 27 00 3C C0 25 C0 29 00 67 00 40 C0 09 C0 13 .'.<.%.).g.@....
0040: 00 2F C0 04 C0 0E 00 33 00 32 C0 2B C0 2F 00 9C ./.....3.2.+./..
0050: C0 2D C0 31 00 9E 00 A2 C0 08 C0 12 00 0A C0 03 .-.1............
0060: C0 0D 00 16 00 13 C0 07 C0 11 00 05 C0 02 C0 0C ................
0070: 00 04 00 FF 01 00 00 6E 00 0A 00 34 00 32 00 17 .......n...4.2..
0080: 00 01 00 03 00 13 00 15 00 06 00 07 00 09 00 0A ................
0090: 00 18 00 0B 00 0C 00 19 00 0D 00 0E 00 0F 00 10 ................
00A0: 00 11 00 02 00 12 00 04 00 05 00 14 00 08 00 16 ................
00B0: 00 0B 00 02 01 00 00 0D 00 1A 00 18 06 03 06 01 ................
00C0: 05 03 05 01 04 03 04 01 03 03 03 01 02 03 02 01 ................
00D0: 02 02 01 01 00 00 00 0E 00 0C 00 00 09 68 75 62 .............hub
00E0: 69 63 2E 63 6F 6D ic.com
[Raw read]: length = 5
0000: 15 03 00 00 02 .....
[Raw read]: length = 2
0000: 02 46 .F
main, READ: SSLv3 Alert, length = 2
main, RECV TLSv1.2 ALERT: fatal, protocol_version
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLException: Received fatal alert: protocol_version
</code></pre>
<p>No exception is thrown if I try to access e.g. <a href="https://google.com" rel="nofollow noreferrer">https://google.com</a>. So it guess SSL with Java cannot be completely broken on my system but it has to do with the combination with hubic.com.</p>
<p>The error <code>protocol_version</code> is not very helpful, but in <a href="https://stackoverflow.com/questions/16541627/javax-net-ssl-sslexception-received-fatal-alert-protocol-version">this question</a> it is suggested that my client uses another protocol version than the server (I guess "server and client could not agree on a protocol" would be more accurate).</p>
<p>How do I figure out which protocol versions the server will agree on and how do I enable those in my client? And should I worry about the issue (e.g. like does hubic only allow an old unsupported protocol? (Firefox certainly does not complain about anything unsecure).</p>
| 27,574,658 | 4 | 7 | null |
2014-12-19 20:07:41.25 UTC
| 8 |
2020-10-01 03:01:41.37 UTC
|
2017-05-23 12:34:40.763 UTC
| null | -1 | null | 327,301 | null | 1 | 2 |
java|ssl|apache-httpclient-4.x|hubic-api
| 47,186 |
<p>I see from the debug that Java does a TLS1.2 handshake instead of the more common SSLv23 handshake:</p>
<pre><code>main, WRITE: TLSv1.2 Handshake, length = 225
[Raw write]: length = 230
0000: 16 03 03 00
^^^^^ - TLS1.2 (SSL3.3)
</code></pre>
<p>The server itself can do only TLS1.0 and fails to just announce this older version.
I'm not familiar with Java, but you either need set the protocol version to TLSv1 or SSLv23 to speak with this server.</p>
<p>The following code would set only TLSv1 with Apache HttpClient:</p>
<pre><code>HttpClientBuilder
.create()
.setSslcontext(SSLContexts.custom().useProtocol("TLSv1").build())
.build()
.execute(new HttpGet("https://hubic.com"));
</code></pre>
<p>EDIT to include question from comment:</p>
<blockquote>
<p>If you say that the server "fails to just announce this older version", does that mean that the server is misconfigured? In this case, why don't Firefox&Chromium have any problems? </p>
</blockquote>
<p>If the client announces TLS1.2 in the ClientHello and the server can do only TLS1.0 it should announce this, i.e. reply with TLS1.0. The client can then close the connection if TLS1.0 is not good enough or continue with TLS1.0. But, in this case the server just told the client that it does not like this version and closed the connection. Firefox and others instead do a SSLv23 announcement, where they do a TLS1.0 handshake but also announce the best protocol version they support. This usually works good for older servers starting from SSL3.0 but also for newer servers.</p>
<p>You can check the behavior of the server with a recent Perl/IO::Socket::SSL and <a href="https://github.com/noxxi/p5-io-socket-ssl/blob/master/util/analyze-ssl.pl">this script</a>.</p>
<pre><code>$ perl analyze-ssl.pl hubic.com
-- hubic.com port 443
* maximum SSL version : TLSv1 (SSLv23)
* supported SSL versions with handshake used and preferred cipher(s):
* handshake protocols ciphers
* SSLv23 TLSv1 AES256-SHA
* TLSv1_2 FAILED: SSL connect attempt failed error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number
* TLSv1_1 FAILED: SSL connect attempt failed error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number
* TLSv1 TLSv1 AES256-SHA
* SSLv3 FAILED: SSL connect attempt failed because of handshake problems error:1409442E:SSL routines:SSL3_READ_BYTES:tlsv1 alert protocol version
</code></pre>
<p>Here you can see, that the hosts supports SSLv23 and TLSv1 handshakes, but not the used TLSv1_2 handshake.</p>
|
15,168,019 |
How to secure EmberJS or any Javascript MVC framework?
|
<p>I'm looking forward to start using <code>Ember.js</code> in a real life project, but as someone coming from a Java background, I always care about Security.</p>
<p>And when I say to my fellow Java developers, I start using a JavaScript MVC, they start saying it's not secure enough, as JavaScript is all about client-side there is always a way to hack around your JavaScript code, and know backdoors to your services and APIs.</p>
<p>So is there any good practice that can help prevent this kind of attacks, or at least trying to make it less effective?</p>
| 15,168,123 | 1 | 1 | null |
2013-03-01 22:36:43.45 UTC
| 15 |
2013-03-03 20:26:47.447 UTC
|
2013-03-01 22:55:49.56 UTC
| null | 417,685 | null | 32,704 | null | 1 | 11 |
javascript|security|model-view-controller|ember.js
| 5,521 |
<blockquote>
<p>There is always a way to hack around your javascript code, and know backdoors to your services and APIs.</p>
</blockquote>
<p>JavaScript presents few new problems for services and APIs that are already exposed to the web. Your server/service shouldn't blindly trust requests from the web, so using javascript doesn't alter your security posture, but it can lull people into a false sense of security by making them think they control the user-agent.</p>
<p>The basic rule of client/server security is still the same: <strong>don't trust the user-agent</strong> ; place the server and the client on different sides of a <a href="https://www.owasp.org/index.php/Trust_Boundary_Violation" rel="noreferrer">trust boundary</a>.</p>
<blockquote>
<p>A trust boundary can be thought of as line drawn through a program. On one side of the line, data is untrusted. On the other side of the line, data is assumed to be trustworthy. The purpose of validation logic is to allow data to safely cross the trust boundary--to move from untrusted to trusted.</p>
</blockquote>
<p>Validate everything that the server receives from the client, and, because XSS vulnerabilities are common and allow clients to access information sent to the client, send as little sensitive information to the client as possible.</p>
<p>When you do need to round-trip data from the server to the client and back, you can use a variety of techiniques.</p>
<ol>
<li>Cryptographically sign the data so that the server can verify that it was not tampered with.</li>
<li>Store the data in a side-table and only send an opaque, unguessable identifier.</li>
</ol>
<p>When you do need to send sensitive data to the client, you also have a variety of strategies:</p>
<ol>
<li>Store the data in HTTP-only cookies which get attached to requests but which are not readable by JavaScript</li>
<li>Divide your client into iframes on separate origins, and sequester the sensitive information in an iframe that is especially carefully reviewed, and has minimal excess functionality.</li>
</ol>
<hr>
<h1>Signing</h1>
<p>Signing solves the problem of verifying that data you received from an untrusted source is data that you previously verified. It does not solve the problem of eavesdropping (for that you need encryption) or of a client that decides not to return data or that decides to substituting different data signed with the same key.</p>
<p>Cryptographic signing of "pass-through" data is explained well by the <a href="https://docs.djangoproject.com/en/dev/topics/signing/" rel="noreferrer">Django</a> docs which also outline how their APIs can be used.</p>
<blockquote>
<p>The golden rule of Web application security is to never trust data from untrusted sources. Sometimes it can be useful to pass data through an untrusted medium. Cryptographically signed values can be passed through an untrusted channel safe in the knowledge that any tampering will be detected.</p>
<p>Django provides both a low-level API for signing values and a high-level API for setting and reading signed cookies, one of the most common uses of signing in Web applications.</p>
<p>You may also find signing useful for the following:</p>
<ol>
<li>Generating “recover my account” URLs for sending to users who have lost their password.</li>
<li>Ensuring data stored in hidden form fields has not been tampered with.</li>
<li>Generating one-time secret URLs for allowing temporary access to a protected resource, for example a downloadable file that a user has paid for.</li>
</ol>
</blockquote>
<hr>
<h1>Opaque Identifiers</h1>
<p>Opaque identifiers and side tables solve the same problem as signing, but require server-side storage, and requires that the machine that stored the data have access to the same DB as the machine that receives the identifier back.</p>
<p>Side tables with opaque, unguessable, identifiers can be easily understood by looking at this diagram</p>
<pre><code> Server DB Table
+--------------------+---------------------+
| Opaque Primary Key | Sensitive Info |
+--------------------+---------------------+
| ZXu4288a37b29AA084 | The king is a fink! |
| ... | ... |
+--------------------+---------------------+
</code></pre>
<p>You generate the key using a <a href="http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator" rel="noreferrer">random or secure pseudo-random number generator</a> and send the key to the client.</p>
<p>If the client has the key, all they know is that they possess a random number, and possibly that it is the same as some other random number they received from you, but cannot derive content from it.</p>
<p>If they tamper (send back a different key) then that will not be in your table (with very high likelihood) so you will have detected tampering.</p>
<p>If you send multiple keys to the same misbehaving client, they can of course substitute one for the other.</p>
<hr>
<h1><a href="https://www.owasp.org/index.php/HttpOnly" rel="noreferrer">HTTP-only cookies</a></h1>
<p>When you're sending a per-user-agent secret that you don't want it to accidentally leak to other user-agents, then HTTP-only cookies are a good option.</p>
<blockquote>
<p>If the HttpOnly flag (optional) is included in the HTTP response header, the cookie cannot be accessed through client side script (again if the browser supports this flag). As a result, even if a cross-site scripting (XSS) flaw exists, and a user accidentally accesses a link that exploits this flaw, the browser (primarily Internet Explorer) will not reveal the cookie to a third party.</p>
</blockquote>
<p>HttpOnly cookies are widely supported on modern browsers.</p>
<hr>
<h1>Sequestered iframes</h1>
<p>Dividing your application into multiple iframes is the best current way to allow your rich client to manipulate sensitive data while minimizing the risk of accidental leakage.</p>
<p>The basic idea is to have small programs (secure kernels) within a larger program so that your security sensitive code can be more carefully reviewed than the program as a whole. This is the same way that <a href="http://hillside.net/plop/2004/papers/mhafiz1/PLoP2004_mhafiz1_0.pdf" rel="noreferrer">qmail's cooperating suspicious processes</a> worked.</p>
<blockquote>
<p>Security Pattern: Compartmentalization [VM02]</p>
<h1>Problem</h1>
<p>A security failure in one part of a system allows
another part of the system to be exploited.</p>
<h1>Solution</h1>
<p>Put each part in a separate security domain. Even when
the security of one part is compromised, the other parts
remain secure.</p>
</blockquote>
<p><a href="http://stevehanov.ca/blog/index.php?id=109" rel="noreferrer">"Cross-frame communication the HTML5 way"</a> explains how iframes can communicate. Since they're on different domains, the security sensitive iframe knows that code on other domains can only communicate with it through these narrow channels.</p>
<blockquote>
<p>HTML allows you to embed one web page inside another, in the element. They remain essentially separated. The container web site is only allowed to talk to its web server, and the iframe is only allowed to talk to its originating server. Furthermore, because they have different origins, the browser disallows any contact between the two frames. That includes function calls, and variable accesses.</p>
<p>But what if you want to get some data in between the two separate windows? For example, a zwibbler document might be a megabyte long when converted to a string. I want the containing web page to be able to get a copy of that string when it wants, so it can save it. Also, it should be able to access the saved PDF, PNG, or SVG image that the user produces. HTML5 provides a restricted way to communicate between different frames of the same window, called window.postMessage().</p>
</blockquote>
<p>Now the security-sensitive frame can use standard verification techniques to vet data from the (possibly-compromised) less-sensitive frame.</p>
<p>You can have a large group of programmers working efficiently at producing a great application, while a much smaller group works on making sure that the sensitive data is properly handled.</p>
<p>Some downsides:</p>
<ol>
<li>Starting up an application is more complex because there is no single "load" event.</li>
<li>Iframe communication requires passing strings that need to be parsed, so the security-sensitive frame still needs to use secure parsing methods (no <code>eval</code> of the string from postMessage.)</li>
<li>Iframes are rectangular, so if the security-sensitive frame needs to present a UI, then it might not easily fit neatly into the larger application's UI.</li>
</ol>
|
15,316,398 |
Check a command's return code when subprocess raises a CalledProcessError exception
|
<p>I want to capture the <code>stdout</code> stream of a shell command in a python (3) script, and being able, at the same time, to check the return code of the shell command if it returns an error (that is, if its return code is not 0).</p>
<p><code>subprocess.check_output</code> seems to be the appropriate method to do this. From <code>subprocess</code>'s man page:</p>
<pre><code>check_output(*popenargs, **kwargs)
Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
</code></pre>
<p>Still, I don't succeed to obtain the return code from the shell command when it fails. My code looks like this:</p>
<pre><code>import subprocess
failing_command=['ls', 'non_existent_dir']
try:
subprocess.check_output(failing_command)
except:
ret = subprocess.CalledProcessError.returncode # <- this seems to be wrong
if ret in (1, 2):
print("the command failed")
elif ret in (3, 4, 5):
print("the command failed very much")
</code></pre>
<p>This code raises an exception in the handling of the exception itself:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 4, in <module>
AttributeError: type object 'CalledProcessError' has no attribute 'returncode'
</code></pre>
<p>I admit I don't know where I am wrong.</p>
| 15,316,680 | 2 | 0 | null |
2013-03-09 22:01:18.87 UTC
| 7 |
2017-11-21 00:20:40.407 UTC
|
2014-09-09 08:56:27.323 UTC
| null | 2,682,142 | null | 2,002,452 | null | 1 | 25 |
python|python-3.x|subprocess
| 59,358 |
<p>To get both the process output and the returned code:</p>
<pre><code>from subprocess import Popen, PIPE
p = Popen(["ls", "non existent"], stdout=PIPE)
output = p.communicate()[0]
print(p.returncode)
</code></pre>
<p><code>subprocess.CalledProcessError</code> is a class. To access <code>returncode</code> use the exception instance:</p>
<pre><code>from subprocess import CalledProcessError, check_output
try:
output = check_output(["ls", "non existent"])
returncode = 0
except CalledProcessError as e:
output = e.output
returncode = e.returncode
print(returncode)
</code></pre>
|
14,926,402 |
UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7
|
<p>I am getting this error</p>
<p><strong>java.lang.UnsupportedClassVersionError: JVMCFRE003 bad major version; class=map/CareMonths, offset=6</strong></p>
<p>My Eclipse's Java compiler is set to <code>1.6</code> and my installed Java SDK in C:\Program Files is <code>1.6.0</code>, but still I get this error when I install my app to Webshere Application Server V7. </p>
<p>What does <code>offset=6</code> mean? I want to compile using Java 6 and Websphere 7 supports Java 6.</p>
<p>I do see that the JDK in the IBM directory where server is installed is Java 7. Is that what is causing this? ....but again my workspace's Eclipse compiler is set to Java <code>1.6</code>.</p>
| 14,958,377 | 12 | 0 | null |
2013-02-17 21:40:48.15 UTC
| 8 |
2017-11-08 05:15:02.237 UTC
|
2013-02-19 13:19:11.803 UTC
| null | 1,305,344 | null | 1,884,445 | null | 1 | 41 |
java|eclipse|jakarta-ee|websphere-7|java-6
| 200,489 |
<p>WebSphere Application Server V7 does support <strong>Java Platform, Standard Edition (Java SE) 6</strong> (see <a href="http://pic.dhe.ibm.com/infocenter/wasinfo/v7r0/topic/com.ibm.websphere.nd.doc/info/ae/ae/rovr_specs.html#rovr_specs__anyappl">Specifications and API documentation</a> in the Network Deployment (All operating systems), Version 7.0 Information Center) and it's since <a href="http://pic.dhe.ibm.com/infocenter/wasinfo/v8r5/topic/com.ibm.websphere.nd.doc/ae/rovr_specs.html">the release V8.5 when Java 7 has been supported</a>.</p>
<p>I couldn't find the Java 6 SDK documentation, and could only consult <a href="http://publib.boulder.ibm.com/infocenter/java7sdk/v7r0/topic/com.ibm.java.messages/diag/appendixes/messages/messages.html">IBM JVM Messages</a> in <a href="http://www.ibm.com/developerworks/java/jdk/docs/java7/windows/index.html">Java 7 Windows documentation</a>. Alas, I couldn't find the error message in the documentation either.</p>
<p>Since <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/UnsupportedClassVersionError.html">java.lang.UnsupportedClassVersionError</a> is <em>"Thrown when the Java Virtual Machine attempts to read a class file and determines that the major and minor version numbers in the file are not supported."</em>, you ran into an issue of building the application with more recent version of Java than the one supported by the runtime environment, i.e. WebSphere Application Server 7.0.</p>
<p>I may be mistaken, but I think that <strong>offset=6</strong> in the message is to let you know what position caused the incompatibility issue to occur. It's irrelevant for you, for me, and for many other people, but some might find it useful, esp. when they generate bytecode themselves.</p>
<p>Run the <a href="http://pic.dhe.ibm.com/infocenter/wasinfo/v7r0/topic/com.ibm.websphere.nd.doc/info/ae/ae/rins_versionInfo.html">versionInfo</a> command to find out about the <strong>Installed Features</strong> of WebSphere Application Server V7, e.g.</p>
<pre><code>C:\IBM\WebSphere\AppServer>.\bin\versionInfo.bat
WVER0010I: Copyright (c) IBM Corporation 2002, 2005, 2008; All rights reserved.
WVER0012I: VersionInfo reporter version 1.15.1.47, dated 10/18/11
--------------------------------------------------------------------------------
IBM WebSphere Product Installation Status Report
--------------------------------------------------------------------------------
Report at date and time February 19, 2013 8:07:20 AM EST
Installation
--------------------------------------------------------------------------------
Product Directory C:\IBM\WebSphere\AppServer
Version Directory C:\IBM\WebSphere\AppServer\properties\version
DTD Directory C:\IBM\WebSphere\AppServer\properties\version\dtd
Log Directory C:\ProgramData\IBM\Installation Manager\logs
Product List
--------------------------------------------------------------------------------
BPMPC installed
ND installed
WBM installed
Installed Product
--------------------------------------------------------------------------------
Name IBM Business Process Manager Advanced V8.0
Version 8.0.1.0
ID BPMPC
Build Level 20121102-1733
Build Date 11/2/12
Package com.ibm.bpm.ADV.V80_8.0.1000.20121102_2136
Architecture x86-64 (64 bit)
Installed Features Non-production
Business Process Manager Advanced - Client (always installed)
Optional Languages German
Russian
Korean
Brazilian Portuguese
Italian
French
Hungarian
Simplified Chinese
Spanish
Czech
Traditional Chinese
Japanese
Polish
Romanian
Installed Product
--------------------------------------------------------------------------------
Name IBM WebSphere Application Server Network Deployment
Version 8.0.0.5
ID ND
Build Level cf051243.01
Build Date 10/22/12
Package com.ibm.websphere.ND.v80_8.0.5.20121022_1902
Architecture x86-64 (64 bit)
Installed Features IBM 64-bit SDK for Java, Version 6
EJBDeploy tool for pre-EJB 3.0 modules
Embeddable EJB container
Sample applications
Stand-alone thin clients and resource adapters
Optional Languages German
Russian
Korean
Brazilian Portuguese
Italian
French
Hungarian
Simplified Chinese
Spanish
Czech
Traditional Chinese
Japanese
Polish
Romanian
Installed Product
--------------------------------------------------------------------------------
Name IBM Business Monitor
Version 8.0.1.0
ID WBM
Build Level 20121102-1733
Build Date 11/2/12
Package com.ibm.websphere.MON.V80_8.0.1000.20121102_2222
Architecture x86-64 (64 bit)
Optional Languages German
Russian
Korean
Brazilian Portuguese
Italian
French
Hungarian
Simplified Chinese
Spanish
Czech
Traditional Chinese
Japanese
Polish
Romanian
--------------------------------------------------------------------------------
End Installation Status Report
--------------------------------------------------------------------------------
</code></pre>
|
19,663,427 |
jQuery set CSS background opacity
|
<p>I have a <code><div></code> whose transparency of its <em>background-color</em> (and not its contents) I'd like to change. A remote API sends me this colour:</p>
<pre><code>#abcdef
</code></pre>
<p>and I tell jQuery (1.9) to apply this colour via <code>.css</code>:</p>
<pre><code>$('div').css('background-color', '#abcdef');
</code></pre>
<p>The resultant div has a <code>background-color</code> style of not <code>#abcdef</code>, but rather its RGB representation of the same colour.</p>
<pre><code>background-color: rgb(171, 205, 239);
</code></pre>
<p>(Just an observation; not part of the problem)</p>
<hr>
<p>The project requirement has been changed such that I will now need to change the transparency of the background as well, to a set percentage (50%). My desired <code>background-color</code> attribute is thus</p>
<pre><code>background-color: rgba(171, 205, 239, 0.5);
</code></pre>
<p>, however, I cannot find a way to set this background-color attribute using just jQuery, a hex colour code, and still apply an alpha value. <code>opacity</code> affects contents of the div as well as the background, so it is not an option.</p>
<pre><code>$('div').css('background-color', '#abcdef')
.css('opacity', 0.5); // undesirable opacity changes to div's content
</code></pre>
<p>Given the string <code>#abcdef</code>, is it possible <em>only</em> by calculation (e.g. hex2dec) that I will be able to apply a background opacity to a div if I am given only a hex colour string?</p>
| 19,663,620 | 4 | 11 | null |
2013-10-29 16:02:41.083 UTC
| 3 |
2017-05-09 14:48:51.947 UTC
| null | null | null | null | 1,558,430 | null | 1 | 13 |
jquery|css
| 42,234 |
<p>try <code>parseInt(hex,16)</code> to convert hex string into decimal int</p>
<p>so in this case it'll be:</p>
<pre><code>var color = '#abcdef';
var rgbaCol = 'rgba(' + parseInt(color.slice(-6,-4),16)
+ ',' + parseInt(color.slice(-4,-2),16)
+ ',' + parseInt(color.slice(-2),16)
+',0.5)';
$('div').css('background-color', rgbaCol)
</code></pre>
<p>you should create a function out of this to use in your application.</p>
|
8,850,921 |
What is the effect of "list=list" in Python modules?
|
<p>I've seen following code in the python standard library <code>/usr/lib/python2.7/multiprocessing/dummy/__init__.py</code>:</p>
<pre><code>list = list
dict = dict
</code></pre>
<p>What does this idiom mean? My best guess is: "let's check if <code>dict</code> and <code>list</code> exist".
Is it just legacy code from the ancient times without <code>list</code> and <code>dict</code> in the <code>__builtins__</code>?</p>
<p>And I have another mad guess: <em>optimization</em> of lookup speed moving <code>list</code> from global scope to module scope. Is it sane assumption regarding the idiom? I see, that the assumption is wrong if I apply it to multiprocessing.</p>
| 8,850,976 | 1 | 3 | null |
2012-01-13 12:57:26.2 UTC
| 7 |
2012-01-14 09:43:32.737 UTC
|
2012-01-14 09:43:32.737 UTC
| null | 1,060,350 | null | 71,923 | null | 1 | 42 |
python
| 629 |
<p>Exports. You then can do:</p>
<pre><code>from multiprocessing.dummy import list
</code></pre>
<p>... which happens to be the regular <code>list</code>.</p>
<p>Without that line, there would be no <code>list</code> in the package <code>multiprocessing.dummy</code>.</p>
<p>This is sensible to have a uniform API across packages. Say all packages are supposed to offer a <code>list</code> class. Package <code>a</code> chooses to provide a custom implementation, package <code>b</code> however wants to use the <code>list</code> from <code>__builtins__</code>.</p>
<pre><code>powerful/__init__.py:
from powerfulinternals import PowerfulList as list
from simple.simpleinternals import Something as whoo
simple/__init__.py:
list = list
from simpleinternals import Something as whoo
application.py:
try:
import powerful as api
else:
import simple as api
mylist = api.list()
woot = api.whoo()
</code></pre>
<p>There more reason to do such things. For example to make it explicit what you are using.</p>
<pre><code>list = list
</code></pre>
<p>can also be seen as a statement "if you want to change the type of lists I'm using, change it here."</p>
<p>In this particular case, it is the former. The <code>list</code> and <code>dict</code> are exposed as:</p>
<pre><code>manager = multiprocessing.dummy.Manager()
l = manager.list()
d = manager.dict()
</code></pre>
<p>And the definition of <code>Manager</code> is:</p>
<pre><code>def Manager():
return sys.modules[__name__]
</code></pre>
<p>i.e. <code>Manager.list = list</code>.</p>
|
8,798,403 |
String is immutable. What exactly is the meaning?
|
<p>I wrote the following code on immutable Strings.</p>
<pre><code>public class ImmutableStrings {
public static void main(String[] args) {
testmethod();
}
private static void testmethod() {
String a = "a";
System.out.println("a 1-->" + a);
a = "ty";
System.out.println("a 2-->" + a);
}
}
</code></pre>
<p>Output:</p>
<pre><code>a 1-->a
a 2-->ty
</code></pre>
<p>Here the value of variable <code>a</code> has been changed (while many say that contents of the immutable objects cannot be changed). But what exactly does one mean by saying <strong><code>String</code> is immutable</strong>? Could you please clarify this topic for me?</p>
<p>source : <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="noreferrer">https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html</a></p>
| 17,942,294 | 19 | 4 | null |
2012-01-10 04:04:14.47 UTC
| 166 |
2018-07-17 13:06:51.353 UTC
|
2015-09-01 08:25:03.72 UTC
| null | 4,022,700 | null | 818,557 | null | 1 | 223 |
java|string|immutability
| 305,378 |
<p>Before proceeding further with the fuss of <em>immutability</em>, let's just take a look into the <code>String</code> class and its functionality a little before coming to any conclusion.</p>
<p>This is how <code>String</code> works:</p>
<pre><code>String str = "knowledge";
</code></pre>
<p>This, as usual, creates a string containing <code>"knowledge"</code> and assigns it a reference <code>str</code>. Simple enough? Lets perform some more functions:</p>
<pre><code> String s = str; // assigns a new reference to the same string "knowledge"
</code></pre>
<p>Lets see how the below statement works:</p>
<pre><code> str = str.concat(" base");
</code></pre>
<p>This appends a string <code>" base"</code> to <code>str</code>. But wait, how is this possible, since <code>String</code> objects are immutable? Well to your surprise, it is.</p>
<p>When the above statement is executed, the VM takes the value of <code>String str</code>, i.e. <code>"knowledge"</code> and appends <code>" base"</code>, giving us the value <code>"knowledge base"</code>. Now, since <code>String</code>s are immutable, the VM can't assign this value to <code>str</code>, so it creates a new <code>String</code> object, gives it a value <code>"knowledge base"</code>, and gives it a reference <code>str</code>.</p>
<p>An important point to note here is that, while the <code>String</code> object is immutable, <strong>its reference variable is not.</strong> So that's why, in the above example, the reference was made to refer to a newly formed <code>String</code> object.</p>
<p>At this point in the example above, we have two <code>String</code> objects: the first one we created with value <code>"knowledge"</code>, pointed to by <code>s</code>, and the second one <code>"knowledge base"</code>, pointed to by <code>str</code>. But, technically, we have three <code>String</code> objects, the third one being the literal <code>"base"</code> in the <code>concat</code> statement.</p>
<h1>Important Facts about String and Memory usage</h1>
<p>What if we didn't have another reference <code>s</code> to <code>"knowledge"</code>? We would have lost that <code>String</code>. However, it still would have existed, but would be considered lost due to having no references.
Look at one more example below</p>
<pre><code>String s1 = "java";
s1.concat(" rules");
System.out.println("s1 refers to "+s1); // Yes, s1 still refers to "java"
</code></pre>
<p><strong>What's happening:</strong> </p>
<ol>
<li>The first line is pretty straightforward: create a new <code>String</code> <code>"java"</code> and refer <code>s1</code> to it.</li>
<li>Next, the VM creates another new <code>String</code> <code>"java rules"</code>, but nothing
refers to it. So, the second <code>String</code> is instantly lost. We can't reach
it.</li>
</ol>
<p>The reference variable <code>s1</code> still refers to the original <code>String</code> <code>"java"</code>.</p>
<p>Almost every method, applied to a <code>String</code> object in order to modify it, creates new <code>String</code> object. So, where do these <code>String</code> objects go? Well, <em>these exist in memory, and one of the key goals of any programming language is to make efficient use of memory.</em></p>
<p>As applications grow, <em>it's very common for <code>String</code> literals to occupy large area of memory, which can even cause redundancy.</em> So, in order to make Java more efficient, <strong>the JVM sets aside a special area of memory called the "String constant pool".</strong></p>
<p>When the compiler sees a <code>String</code> literal, it looks for the <code>String</code> in the pool. If a match is found, the reference to the new literal is directed to the existing <code>String</code> and no new <code>String</code> object is created. The existing <code>String</code> simply has one more reference. Here comes the point of making <code>String</code> objects immutable:</p>
<p>In the <code>String</code> constant pool, a <code>String</code> object is likely to have one or many references. <em>If several references point to same <code>String</code> without even knowing it, it would be bad if one of the references modified that <code>String</code> value. That's why <code>String</code> objects are immutable.</em></p>
<p>Well, now you could say, <em>what if someone overrides the functionality of <code>String</code> class?</em> That's the reason that <strong>the <code>String</code> class is marked <code>final</code></strong> so that nobody can override the behavior of its methods.</p>
|
5,237,482 |
How do I execute an external program within C code in Linux with arguments?
|
<p>I want to execute another program within C code.
For example, I want to execute a command</p>
<pre><code>./foo 1 2 3
</code></pre>
<p><code>foo</code> is the program which exists in the same folder, and <code>1 2 3</code> are arguments.
<code>foo</code> program creates a file which will be used in my code.</p>
<p>How do I do this?</p>
| 5,237,520 | 7 | 2 | null |
2011-03-08 19:49:44.027 UTC
| 28 |
2022-03-02 00:45:29.797 UTC
|
2022-03-02 00:45:29.797 UTC
| null | 15,168 | null | 461,025 | null | 1 | 61 |
c|linux
| 172,648 |
<p>For a simple way, use <code>system()</code>:</p>
<pre><code>#include <stdlib.h>
...
int status = system("./foo 1 2 3");
</code></pre>
<p><code>system()</code> will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode (the command's exitcode gets multiplied by 256, so divide system()'s return value by that to get the actual exitcode: <code>int exitcode = status / 256</code>).</p>
<p><a href="https://linux.die.net/man/2/wait" rel="noreferrer">The manpage for <code>wait()</code></a> (in section 2, <code>man 2 wait</code> on your Linux system) lists the various macros you can use to examine the status, the most interesting ones would be <code>WIFEXITED</code> and <code>WEXITSTATUS</code>.</p>
<p>Alternatively, if you need to read foo's standard output, use <code>popen(3)</code>, which returns a file pointer (<code>FILE *</code>); interacting with the command's standard input/output is then the same as reading from or writing to a file.</p>
|
4,905,393 |
Scala: InputStream to Array[Byte]
|
<p>With Scala, what is the best way to read from an InputStream to a bytearray?</p>
<p>I can see that you can convert an InputStream to char array</p>
<pre><code>Source.fromInputStream(is).toArray()
</code></pre>
| 4,905,770 | 11 | 0 | null |
2011-02-05 05:58:16.163 UTC
| 8 |
2022-02-02 07:52:09.433 UTC
| null | null | null | null | 586,134 | null | 1 | 44 |
scala|bytearray|inputstream
| 37,727 |
<p>How about:</p>
<pre><code>Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray
</code></pre>
<p>Update: use LazyList instead of <code>Stream</code> (since <code>Stream</code> is deprecated in Scala 3)</p>
<pre><code>LazyList.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray
</code></pre>
|
16,873,363 |
Add <ul> <li> list in aspx from code-behind
|
<p>I am trying to make nested <code>ul</code> & <code>li</code> tags in code behind.
For that i wrote priliminary code in my <code>.aspx</code> page</p>
<pre><code><ul class="dropdown" runat="server" id="tabs"> </ul>
</code></pre>
<p>My C# Code </p>
<pre><code>DatTable dtOutput = Generix.getData("Get Some Data");
foreach (DataRow drOutput in dtOutput.Rows)
{
HtmlGenericControl li = new HtmlGenericControl("li");
tabs.Controls.Add(li);
HtmlGenericControl anchor = new HtmlGenericControl("a");
anchor.Attributes.Add("href", "#");
anchor.InnerText = Convert.ToString(drOutput["ModuleGroup"]);
li.Controls.Add(anchor);
HtmlGenericControl ul = new HtmlGenericControl("ul");
DatTable dtOutputList = Generix.getData("Get another set of Data");
foreach (DataRow drOutputList in dtOutputList.Rows)
{
HtmlGenericControl ili = new HtmlGenericControl("li");
ul.Controls.Add(ili);
HtmlGenericControl ianchor = new HtmlGenericControl("a");
foreach (DataColumn dcOutputList in dtOutputList.Columns)
{
ianchor.Attributes.Add("href", Convert.ToString(drOutputList["ModuleFileName"]));
}
ianchor.InnerText = Convert.ToString(drOutputList["ModuleName"]);
ili.Controls.Add(ianchor);
}
//tabs.Controls.Add(li);
}
</code></pre>
<p>When i run my project and do inspect element on my menu i see something like</p>
<pre><code><ul id="ctl00_tabs" class="dropdown">
<li class="">
<a href="#">Master</a>
</li>
<li class="">
<a href="#">Cards Management</a>
</li>
<li class="">
<a href="#">Authorization</a>
</li>
<li class="">
<a href="#">Loyalty</a>
</li>
<li class="">
<a href="#">Reports</a>
</li>
</ul>
</code></pre>
<p><strong>No Nested <code>ul</code> tags are created inside <code>li</code> ?? Why ??</strong></p>
<p>For example :-</p>
<pre><code><ul id="ctl00_tabs" class="dropdown">
<li class="">
<a href="#">Master</a>
<ul>
<li><a href="Some.aspx"><span>Some Name</span></a></li>
<li><a href="Some1.aspx"><span>Some Name 1</span></a></li>
</ul>
</li>
</ul>
</code></pre>
| 16,894,441 | 4 | 5 | null |
2013-06-01 13:45:14.72 UTC
| 2 |
2016-09-22 07:57:00.533 UTC
|
2013-06-03 09:49:22.363 UTC
| null | 1,169,180 | null | 1,169,180 | null | 1 | 6 |
c#|html|asp.net
| 72,695 |
<p>You see where you're calling <code>li.Controls.Add(anchor)</code>? You're not calling <code>li.Controls.Add(ul)</code> anywhere so your created <code>ul</code>s aren't actually being added anywhere on the page.</p>
|
16,628,394 |
How do you install the latest version of Xuggler (5.4, as of 18/05/2013) in eclipse?
|
<p>I have literally no clue where to start doing this. I've downloaded the necessary Jar's from the site, and done some research on how to install Xuggler in Eclipse, and everything is outdated or irrelevant.</p>
<p>My system is a 64-Bit Windows 8. Most things that worked in vista and windows 7 should be compatible with my system as long as they are also 64-bit compatible.
All I would like to be able to do is obviously run an application with it in Eclipse.</p>
<p>Any advice, helpful explanations would be much appreciated.</p>
| 16,640,999 | 3 | 0 | null |
2013-05-18 19:54:55.163 UTC
| 9 |
2017-04-05 17:24:36.713 UTC
|
2017-04-05 17:24:36.713 UTC
| null | 4,370,109 | null | 2,397,573 | null | 1 | 9 |
java|eclipse|installation|xuggler
| 16,391 |
<p>You can download Xuggler 5.4 <a href="https://files.liferay.com/mirrors/xuggle.googlecode.com/svn/trunk/repo/share/java/xuggle/xuggle-xuggler/5.4/" rel="nofollow noreferrer">here</a></p>
<p>and some more jar to make it work...</p>
<p><a href="http://commons.apache.org/proper/commons-cli/download_cli.cgi" rel="nofollow noreferrer">commons-cli-1.1.jar</a></p>
<p><a href="http://commons.apache.org/proper/commons-lang/download_lang.cgi" rel="nofollow noreferrer">commons-lang-2.1.jar</a></p>
<p><a href="http://logback.qos.ch/download.html" rel="nofollow noreferrer">logback-classic-1.0.0.jar</a></p>
<p><a href="http://logback.qos.ch/download.html" rel="nofollow noreferrer">logback-core-1.0.0.jar</a></p>
<p><a href="http://www.slf4j.org/download.html" rel="nofollow noreferrer">slf4j-api-1.6.4.jar</a></p>
<p>You can check which dependencies xuggler needs from <a href="https://github.com/xuggle/xuggle-xuggler/blob/master/ivy.xml" rel="nofollow noreferrer">here</a>:</p>
<p>Add this jars and xuggle-xuggler-5.4.jar to your project's build path and it s ready.</p>
<p>**version numbers may change</p>
|
12,480,762 |
How to make the header or footer of a ListView not clickable
|
<p>I'm adding a footer and header view to a <code>ListView</code> by using the methods <code>setHeaderView()</code> and <code>setFooterView()</code> and a <code>ViewInflater</code>. That works quite well. </p>
<p>But how could I prevent the header or footer view from firing <code>onListItemClick</code> events? Of course I can catch the event and check whether it came from a header or footer, but this only solves one part of the problem, as header and footer got still focused when clicked. </p>
| 12,481,083 | 1 | 0 | null |
2012-09-18 16:02:06.203 UTC
| 2 |
2014-02-28 01:56:07.737 UTC
|
2014-02-28 01:56:07.737 UTC
| null | 85,950 | null | 19,601 | null | 1 | 33 |
android|listview|android-listview
| 11,536 |
<p>Simply use the <a href="http://developer.android.com/reference/android/widget/ListView.html#addFooterView%28android.view.View,%20java.lang.Object,%20boolean%29" rel="noreferrer">ListView#addHeaderView(View v, Object data, boolean isSelectable);
</a> and matching <code>addFooter()</code> method.</p>
<hr>
<p><strong>The purpose of <code>Object data</code> parameter.</strong></p>
<p>The ListView source code describes the <code>data</code> parameter as:</p>
<blockquote>
<p>The data backing the view. This is returned from ListAdapter#getItem(int).</p>
</blockquote>
<p>Which means if I use <code>listView.getAdapter().getItem(0);</code> it will return the <code>data</code> Object from our header.</p>
<hr>
<p>I'll elaborate this with an example:</p>
<pre><code>listView = (ListView) findViewById(R.id.list);
String[] array = new String[] {"one", "two", "three"};
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array);
</code></pre>
<p>Next let's add a header and set the adapter:</p>
<pre><code>listView.addHeaderView(view, "Potato", false);
listView.setAdapter(adapter);
</code></pre>
<p>Later if we ask:</p>
<pre><code>Log.v("ListAdapter", listView.getAdapter().getItem(0)); // output: "Potato"
Log.v("ArrayAdapter", adapter.getItem(0)); // output: "one"
</code></pre>
|
12,107,263 |
Why is ValidationSummary(true) displaying an empty summary for property errors?
|
<p>I am having a slight issue with the use of <code>ValidationSummary(true)</code> to display model level errors. If the ModelState does not contain model errors (i.e. <code>ModelState.AddModelError("", "Error Description")</code>) but contains property errors (added using data annotations) it displays the validation summary with no error information (when you view the source). My css is therefore displaying an empty red box like so:</p>
<p><img src="https://i.stack.imgur.com/Cyoy8.png" alt="enter image description here"></p>
<p>If there are no property errors then no validation summary is displayed. With <code>ValidationSummary(true)</code> I would expect it to only display validation errors if there are model errors. What have I misunderstood?</p>
<p>I have a basic project as follows:</p>
<p><strong>Controller:</strong></p>
<pre><code>public class HomeController : Controller
{
public ViewResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
return View();
}
}
</code></pre>
<p><strong>Model:</strong></p>
<pre><code>public class IndexViewModel
{
[Required]
public string Name { get; set; }
}
</code></pre>
<p><strong>View:</strong></p>
<pre><code>@model IndexViewModel
@Html.ValidationSummary(true)
@using(@Html.BeginForm())
{
@Html.TextBoxFor(m => m.Name)
<input type="submit" value="submit" />
}
</code></pre>
| 12,111,297 | 11 | 1 | null |
2012-08-24 10:05:20.853 UTC
| 10 |
2020-07-10 14:55:59.557 UTC
|
2012-08-24 10:21:22.45 UTC
| null | 265,247 | null | 265,247 | null | 1 | 35 |
asp.net-mvc-3
| 28,969 |
<p>I think there is something wrong with the <code>ValidationSummary</code> helper method. You could easily create a custom helper method that wraps the built-in <code>ValidationSummary</code>.</p>
<pre><code>public static MvcHtmlString CustomValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors)
{
var htmlString = htmlHelper.ValidationSummary(excludePropertyErrors);
if (htmlString != null)
{
XElement xEl = XElement.Parse(htmlString.ToHtmlString());
var lis = xEl.Element("ul").Elements("li");
if (lis.Count() == 1 && lis.First().Value == "")
return null;
}
return htmlString;
}
</code></pre>
<p>Then from your view,</p>
<pre><code>@Html.CustomValidationSummary(true)
</code></pre>
|
12,154,129 |
How Can I Automatically Populate SQLAlchemy Database Fields? (Flask-SQLAlchemy)
|
<p>I've got a simple User model, defined like so:</p>
<pre><code># models.py
from datetime import datetime
from myapp import db
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
date_updated = db.Column(db.DateTime())
def __init__(self, email, password, date_updated=None):
self.email = email
self.password = password
self.date_updated = datetime.utcnow()
</code></pre>
<p>When I create a new User object, my <code>date_updated</code> field gets set to the current time. What I'd like to do is make it so that <em>whenever</em> I save changes to my User object my <code>date_updated</code> field is set to the current time automatically.</p>
<p>I've scoured the documentation, but for the life of me I can't seem to find any references to this. I'm very new to SQLAlchemy, so I really have no prior experience to draw from.</p>
<p>Would love some feedback, thank you.</p>
| 12,155,686 | 2 | 1 | null |
2012-08-28 06:50:19.43 UTC
| 8 |
2017-06-01 07:01:31.483 UTC
|
2012-08-28 06:54:55.503 UTC
| null | 398,670 | null | 194,175 | null | 1 | 36 |
database|postgresql|sqlalchemy|flask|flask-sqlalchemy
| 24,690 |
<p>Just add <code>server_default</code> or <code>default</code> argument to the column fields:</p>
<pre><code>created_on = db.Column(db.DateTime, server_default=db.func.now())
updated_on = db.Column(db.DateTime, server_default=db.func.now(), server_onupdate=db.func.now())
</code></pre>
<p>I prefer the <code>{created,updated}_on</code> column names. ;)</p>
<p>SQLAlchemy docs about <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/defaults.html#server-side-defaults" rel="noreferrer">column insert/update defaults</a>.</p>
<p><strong>[Edit]:</strong> Updated code to use <code>server_default</code> arguments in the code.</p>
<p><strong>[Edit 2]:</strong> Replaced <code>onupdate</code> with <code>server_onupdate</code> arguments.</p>
|
12,157,646 |
How to render offscreen on OpenGL?
|
<p>My aim is to render OpenGL scene without a window, directly into a file. The scene may be larger than my screen resolution is.</p>
<p>How can I do this?</p>
<p>I want to be able to choose the render area size to any size, for example 10000x10000, if possible?</p>
| 12,159,293 | 5 | 0 | null |
2012-08-28 10:46:28.94 UTC
| 40 |
2019-10-23 22:19:09.207 UTC
| null | null | null | null | 1,036,205 | null | 1 | 44 |
c++|windows|opengl|off-screen
| 64,276 |
<p>It all starts with <a href="https://www.khronos.org/opengl/wiki/GLAPI/glReadPixels" rel="noreferrer"><code>glReadPixels</code></a>, which you will use to transfer the pixels stored in a specific buffer on the GPU to the main memory (RAM). As you will notice in the documentation, there is no argument to choose which buffer. As is usual with OpenGL, the current buffer to read from is a state, which you can set with <code>glReadBuffer</code>.</p>
<p>So a very basic offscreen rendering method would be something like the following. I use c++ pseudo code so it will likely contain errors, but should make the general flow clear:</p>
<pre><code>//Before swapping
std::vector<std::uint8_t> data(width*height*4);
glReadBuffer(GL_BACK);
glReadPixels(0,0,width,height,GL_BGRA,GL_UNSIGNED_BYTE,&data[0]);
</code></pre>
<p>This will read the current back buffer (usually the buffer you're drawing to). You should call this before swapping the buffers. Note that you can also perfectly read the back buffer with the above method, clear it and draw something totally different before swapping it. Technically you can also read the front buffer, but this is often discouraged as theoretically implementations were allowed to make some optimizations that might make your front buffer contain rubbish.</p>
<p>There are a few drawbacks with this. First of all, we don't really do offscreen rendering do we. We render to the screen buffers and read from those. We can emulate offscreen rendering by never swapping in the back buffer, but it doesn't feel right. Next to that, the front and back buffers are optimized to display pixels, not to read them back. That's where <a href="https://www.khronos.org/opengl/wiki/Framebuffer_Object" rel="noreferrer">Framebuffer Objects</a> come into play.</p>
<p>Essentially, an FBO lets you create a non-default framebuffer (like the FRONT and BACK buffers) that allow you to draw to a memory buffer instead of the screen buffers. In practice, you can either draw to a texture or to a <a href="https://www.khronos.org/opengl/wiki/Renderbuffer_Object" rel="noreferrer">renderbuffer</a>. The first is optimal when you want to re-use the pixels in OpenGL itself as a texture (e.g. a naive "security camera" in a game), the latter if you just want to render/read-back. With this the code above would become something like this, again pseudo-code, so don't kill me if mistyped or forgot some statements.</p>
<pre><code>//Somewhere at initialization
GLuint fbo, render_buf;
glGenFramebuffers(1,&fbo);
glGenRenderbuffers(1,&render_buf);
glBindRenderbuffer(render_buf);
glRenderbufferStorage(GL_RENDERBUFFER, GL_BGRA8, width, height);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER,fbo);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, render_buf);
//At deinit:
glDeleteFramebuffers(1,&fbo);
glDeleteRenderbuffers(1,&render_buf);
//Before drawing
glBindFramebuffer(GL_DRAW_FRAMEBUFFER,fbo);
//after drawing
std::vector<std::uint8_t> data(width*height*4);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glReadPixels(0,0,width,height,GL_BGRA,GL_UNSIGNED_BYTE,&data[0]);
// Return to onscreen rendering:
glBindFramebuffer(GL_DRAW_FRAMEBUFFER,0);
</code></pre>
<p>This is a simple example, in reality you likely also want storage for the depth (and stencil) buffer. You also might want to render to texture, but I'll leave that as an exercise. In any case, you will now perform real offscreen rendering and it might work faster then reading the back buffer.</p>
<p>Finally, you can use <a href="https://www.khronos.org/opengl/wiki/Pixel_Buffer_Object" rel="noreferrer">pixel buffer objects</a> to make read pixels asynchronous. The problem is that <code>glReadPixels</code> blocks until the pixel data is completely transfered, which may stall your CPU. With PBO's the implementation may return immediately as it controls the buffer anyway. It is only when you map the buffer that the pipeline will block. However, PBO's may be optimized to buffer the data solely on RAM, so this block could take a lot less time. The read pixels code would become something like this:</p>
<pre><code>//Init:
GLuint pbo;
glGenBuffers(1,&pbo);
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
glBufferData(GL_PIXEL_PACK_BUFFER, width*height*4, NULL, GL_DYNAMIC_READ);
//Deinit:
glDeleteBuffers(1,&pbo);
//Reading:
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
glReadPixels(0,0,width,height,GL_BGRA,GL_UNSIGNED_BYTE,0); // 0 instead of a pointer, it is now an offset in the buffer.
//DO SOME OTHER STUFF (otherwise this is a waste of your time)
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo); //Might not be necessary...
pixel_data = glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
</code></pre>
<p>The part in caps is essential. If you just issue a <code>glReadPixels</code> to a PBO, followed by a <code>glMapBuffer</code> of that PBO, you gained nothing but a lot of code. Sure the <code>glReadPixels</code> might return immediately, but now the <code>glMapBuffer</code> will stall because it has to safely map the data from the read buffer to the PBO and to a block of memory in main RAM.</p>
<p>Please also note that I use GL_BGRA everywhere, this is because many graphics cards internally use this as the optimal rendering format (or the GL_BGR version without alpha). It should be the fastest format for pixel transfers like this. I'll try to find the nvidia article I read about this a few monts back.</p>
<p>When using OpenGL ES 2.0, <code>GL_DRAW_FRAMEBUFFER</code> might not be available, you should just use <code>GL_FRAMEBUFFER</code> in that case.</p>
|
12,186,698 |
Why does C++ allow unnamed function parameters?
|
<p>The following is a perfectly legal <code>C++</code> code</p>
<pre><code>void foo (int) {
cout << "Yo!" << endl;
}
int main (int argc, char const *argv[]) {
foo(5);
return 0;
}
</code></pre>
<p>I wonder, if there a value to ever leave unnamed parameters in functions, given the fact that they can't be referenced from within the function.</p>
<p>Why is this legal to begin with?</p>
| 12,186,734 | 4 | 3 | null |
2012-08-29 21:21:51.313 UTC
| 15 |
2018-10-23 02:35:02.78 UTC
|
2018-10-23 02:35:02.78 UTC
| null | 114,421 | null | 359,862 | null | 1 | 48 |
c++|function|parameters
| 19,513 |
<p>Yes, this is legal. This is useful for implementations of virtuals from the base class in implementations that do not intend on using the corresponding parameter: you must declare the parameter to match the signature of the virtual function in the base class, but you are not planning to use it, so you do not specify the name.</p>
<p>The other common case is when you provide a callback to some library, and you must conform to a signature that the library has established (thanks, <a href="https://stackoverflow.com/users/626853/aasmund-eldhuset">Aasmund Eldhuset</a> for bringing this up).</p>
<p>There is also a special case for <a href="http://www.learncpp.com/cpp-tutorial/97-overloading-the-increment-and-decrement-operators/" rel="noreferrer">defining your own post-increment and post-decrement operators</a>: they must have a signature with an <code>int</code> parameter, but that parameter is always unused. This convention is bordering on a hack in the language design, though.</p>
|
12,535,419 |
Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function
|
<p>I need to set a global variable from a function and am not quite sure how to do it.</p>
<pre><code># Set variables
$global:var1
$global:var2
$global:var3
function foo ($a, $b, $c)
{
# Add $a and $b and set the requested global variable to equal to it
$c = $a + $b
}
</code></pre>
<p>Call the function:</p>
<pre><code>foo 1 2 $global:var3
</code></pre>
<p>End result:</p>
<p>$global:var3 is set to 3</p>
<p>Or if I called the function like this:</p>
<pre><code>foo 1 2 $global:var2
</code></pre>
<p>End result:</p>
<p>$global:var2 is set to 3</p>
<p>I hope this example makes sense. The third variable passed to the function is the name of the variable it is to set.</p>
| 12,536,622 | 7 | 0 | null |
2012-09-21 17:35:56.067 UTC
| 18 |
2018-12-29 19:53:48.95 UTC
|
2016-01-20 00:27:26.397 UTC
| null | 63,550 | null | 1,342,015 | null | 1 | 61 |
powershell
| 329,619 |
<p>You can use the <code>Set-Variable</code> cmdlet. Passing <code>$global:var3</code> sends the <strong>value</strong> of <code>$var3</code>, which is not what you want. You want to send the <strong>name</strong>.</p>
<pre><code>$global:var1 = $null
function foo ($a, $b, $varName)
{
Set-Variable -Name $varName -Value ($a + $b) -Scope Global
}
foo 1 2 var1
</code></pre>
<p>This is not very good programming practice, though. Below would be much more straightforward, and less likely to introduce bugs later:</p>
<pre><code>$global:var1 = $null
function ComputeNewValue ($a, $b)
{
$a + $b
}
$global:var1 = ComputeNewValue 1 2
</code></pre>
|
3,693,323 |
How do I manipulate parse trees?
|
<p>I've been playing around with natural language parse trees and manipulating them in various ways. I've been using Stanford's Tregex and Tsurgeon tools but the code is a mess and doesn't fit in well with my mostly Python environment (those tools are Java and aren't ideal for tweaking). I'd like to have a toolset that would allow for easy hacking when I need more functionality. Are there any other tools that are well suited for doing pattern matching on trees and then manipulation of those matched branches?</p>
<p>For example, I'd like to take the following tree as input:</p>
<pre><code>(ROOT
(S
(NP
(NP (NNP Bank))
(PP (IN of)
(NP (NNP America))))
(VP (VBD used)
(S
(VP (TO to)
(VP (VB be)
(VP (VBN called)
(NP
(NP (NNP Bank))
(PP (IN of)
(NP (NNP Italy)))))))))))
</code></pre>
<p>and (this is a simplified example):</p>
<ol>
<li>Find any node with the label NP that has a first child with the label NP and some descendent named "Bank", and a second child with the label PP.</li>
<li>If that matches, then take all of the children of the PP node and move them to end of the matched NP's children.</li>
</ol>
<p>For example, take this part of the tree:</p>
<pre><code>(NP
(NP (NNP Bank))
(PP (IN of)
(NP (NNP America))))
</code></pre>
<p>and turn it into this:</p>
<pre><code>(NP
(NP (NNP Bank) (IN of) (NP (NNP America))))
</code></pre>
<p>Since my input trees are S-expressions I've considered using Lisp (embedded into my Python program) but it's been so long that I've written anything significant in Lisp that I have no idea where to even start.</p>
<p>What would be a good way to describe the patterns? What would be a good way to describe the manipulations? What's a good way to think about this problem?</p>
| 3,694,071 | 3 | 0 | null |
2010-09-12 01:03:10.95 UTC
| 12 |
2012-03-13 07:49:53.197 UTC
|
2010-09-12 11:03:28.07 UTC
| null | 86,542 | null | 279,104 | null | 1 | 15 |
lisp|nlp|pattern-matching|stanford-nlp|s-expression
| 3,762 |
<p>This is a typical case of using Lisp. You would need a function that maps another function over the tree.</p>
<p>Here is a procedural matching example using Common Lisp. There are matchers in Lisp that work over list structures, which could be used instead. Using a list matcher would simplify the example (see my other answer for an example using a pattern matcher).</p>
<p>The code:</p>
<pre><code>(defun node-children (node)
(rest node))
(defun node-name (node)
(second node))
(defun node-type (node)
(first node))
(defun treemap (tree matcher transformer)
(cond ((null tree) nil)
((consp tree)
(if (funcall matcher tree)
(funcall transformer tree)
(cons (node-type tree)
(mapcar (lambda (child)
(treemap child matcher transformer))
(node-children tree)))))
(t tree))))
</code></pre>
<p>The example:</p>
<pre><code>(defvar *tree*
'(ROOT
(S
(NP
(NP (NNP Bank))
(PP (IN of)
(NP (NNP America))))
(VP (VBD used)
(S
(VP (TO to)
(VP (VB be)
(VP (VBN called)
(NP
(NP (NNP Bank))
(PP (IN of)
(NP (NNP Italy))))))))))))
(defun example ()
(pprint
(treemap *tree*
(lambda (node)
(and (= (length (node-children node)) 2)
(eq (node-type (first (node-children node))) 'np)
(some (lambda (node)
(eq (node-name node) 'bank))
(children (first (node-children node))))
(eq (first (second (node-children node))) 'pp)))
(lambda (node)
(list (node-type node)
(append (first (node-children node))
(node-children (second (node-children node)))))))))
</code></pre>
<p>Running the example:</p>
<pre><code>CL-USER 75 > (example)
(ROOT
(S
(NP
(NP (NNP BANK) (IN OF) (NP (NNP AMERICA))))
(VP
(VBD USED)
(S
(VP
(TO TO)
(VP
(VB BE)
(VP
(VBN CALLED)
(NP
(NP
(NNP BANK)
(IN OF)
(NP (NNP ITALY)))))))))))
</code></pre>
|
38,346,013 |
Binary search in a Python list
|
<p>I am trying to perform a binary search on a list in python. List is created using command line arguments. User inputs the number he wants to look for in the array and he is returned the index of the element. For some reason, the program only outputs 1 and None. Code is below.
Any help is extremely appreciated. </p>
<pre><code>import sys
def search(list, target):
min = 0
max = len(list)-1
avg = (min+max)/2
while (min < max):
if (list[avg] == target):
return avg
elif (list[avg] < target):
return search(list[avg+1:], target)
else:
return search(list[:avg-1], target)
print "The location of the number in the array is", avg
# The command line argument will create a list of strings
# This list cannot be used for numeric comparisions
# This list has to be converted into a list of ints
def main():
number = input("Please enter a number you want to search in the array !")
index = int(number)
list = []
for x in sys.argv[1:]:
list.append(int(x))
print "The list to search from", list
print(search(list, index))
if __name__ == '__main__':
main()
CL :
Anuvrats-MacBook-Air:Python anuvrattiku$ python binary_search.py 1 3 4 6 8 9 12 14 16 17 27 33 45 51 53 63 69 70
Please enter a number you want to search in the array !69
The list to search from [1, 3, 4, 6, 8, 9, 12, 14, 16, 17, 27, 33, 45, 51, 53, 63, 69, 70]
0
Anuvrats-MacBook-Air:Python anuvrattiku$
</code></pre>
| 38,347,202 | 5 | 8 | null |
2016-07-13 08:09:48.72 UTC
| 4 |
2022-06-18 22:40:01.873 UTC
|
2016-07-13 08:19:32.707 UTC
| null | 4,254,959 | null | 4,254,959 | null | 1 | 5 |
python|python-2.7
| 44,259 |
<p>Well, there are some little mistakes in your code. To find them, you should either use a debugger, or at least add traces to understand what happens. Here is your original code with traces that make the problems self evident:</p>
<pre><code>def search(list, target):
min = 0
max = len(list)-1
avg = (min+max)/2
print list, target, avg
...
</code></pre>
<p>You can immediately see that:</p>
<ul>
<li>you search in a sub array that skips <code>avg-1</code> when you are <em>below</em> avg</li>
<li>as you search in a sub array you will get the index <em>in that subarray</em></li>
</ul>
<p>The fixes are now trivial:</p>
<pre><code>elif (list[avg] < target):
return avg + 1 + search(list[avg+1:], target) # add the offset
else:
return search(list[:avg], target) # sublist ends below the upper limit
</code></pre>
<p>That's not all, when you end the loop with <code>min == max</code>, you do not return anything (meaning you return None). And last but not least <strong>never</strong> use a name from the standard Python library for your own variables.</p>
<p>So here is the fixed code:</p>
<pre><code>def search(lst, target):
min = 0
max = len(lst)-1
avg = (min+max)/2
# uncomment next line for traces
# print lst, target, avg
while (min < max):
if (lst[avg] == target):
return avg
elif (lst[avg] < target):
return avg + 1 + search(lst[avg+1:], target)
else:
return search(lst[:avg], target)
# avg may be a partial offset so no need to print it here
# print "The location of the number in the array is", avg
return avg
</code></pre>
|
8,894,442 |
MVC Razor view nested foreach's model
|
<p>Imagine a common scenario, this is a simpler version of what I'm coming across. I actually have a couple of layers of further nesting on mine....</p>
<p>But this is the scenario</p>
<p>Theme contains List
Category contains List
Product contains List</p>
<p>My Controller provides a fully populated Theme, with all the Categories for that theme, the Products within this categories and the their orders.</p>
<p>The orders collection has a property called Quantity (amongst many others) that needs to be editable.</p>
<pre><code>@model ViewModels.MyViewModels.Theme
@Html.LabelFor(Model.Theme.name)
@foreach (var category in Model.Theme)
{
@Html.LabelFor(category.name)
@foreach(var product in theme.Products)
{
@Html.LabelFor(product.name)
@foreach(var order in product.Orders)
{
@Html.TextBoxFor(order.Quantity)
@Html.TextAreaFor(order.Note)
@Html.EditorFor(order.DateRequestedDeliveryFor)
}
}
}
</code></pre>
<p>If I use lambda instead then then I only seem to get a reference to the top Model object, "Theme" not those within the foreach loop.</p>
<p>Is what I'm trying to do there even possible or have I overestimated or misunderstood what is possible?</p>
<p>With the above I get an error on the TextboxFor, EditorFor, etc</p>
<blockquote>
<p>CS0411: The type arguments for method
'System.Web.Mvc.Html.InputExtensions.TextBoxFor(System.Web.Mvc.HtmlHelper,
System.Linq.Expressions.Expression>)'
cannot be inferred from the usage. Try specifying the type arguments
explicitly.</p>
</blockquote>
<p>Thanks.</p>
| 8,896,840 | 6 | 6 | null |
2012-01-17 12:16:47.19 UTC
| 64 |
2020-01-21 19:21:42.017 UTC
|
2012-01-17 12:28:02.137 UTC
| null | 705,657 | null | 705,657 | null | 1 | 94 |
c#|asp.net|asp.net-mvc-3|view|razor
| 106,399 |
<p>The quick answer is to use a <code>for()</code> loop in place of your <code>foreach()</code> loops. Something like:</p>
<pre><code>@for(var themeIndex = 0; themeIndex < Model.Theme.Count(); themeIndex++)
{
@Html.LabelFor(model => model.Theme[themeIndex])
@for(var productIndex=0; productIndex < Model.Theme[themeIndex].Products.Count(); productIndex++)
{
@Html.LabelFor(model=>model.Theme[themeIndex].Products[productIndex].name)
@for(var orderIndex=0; orderIndex < Model.Theme[themeIndex].Products[productIndex].Orders; orderIndex++)
{
@Html.TextBoxFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Quantity)
@Html.TextAreaFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Note)
@Html.EditorFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].DateRequestedDeliveryFor)
}
}
}
</code></pre>
<p>But this glosses over <em>why</em> this fixes the problem.</p>
<p>There are three things that you have at least a cursory understanding before you can resolve this issue. I have
to admit that I <a href="http://www.hanselman.com/blog/CargocultProgramming.aspx" rel="noreferrer">cargo-culted</a> this
for a long time when I started working with the framework. And it took me quite a while
to really get what was going on.</p>
<p>Those three things are:</p>
<ul>
<li>How do the <code>LabelFor</code> and other <code>...For</code> helpers work in MVC?</li>
<li>What is an Expression Tree?</li>
<li>How does the Model Binder work?</li>
</ul>
<p>All three of these concepts link together to get an answer.</p>
<h2>How do the <code>LabelFor</code> and other <code>...For</code> helpers work in MVC?</h2>
<p>So, you've used the <code>HtmlHelper<T></code> extensions for <code>LabelFor</code> and <code>TextBoxFor</code> and others, and
you probably noticed that when you invoke them, you pass them a lambda and it <em>magically</em> generates
some html. But how?</p>
<p>So the first thing to notice is the signature for these helpers. Lets look at the simplest overload for
<code>TextBoxFor</code></p>
<pre><code>public static MvcHtmlString TextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression
)
</code></pre>
<p>First, this is an extension method for a strongly typed <code>HtmlHelper</code>, of type <code><TModel></code>. So, to simply
state what happens behind the scenes, when razor renders this view it generates a class.
Inside of this class is an instance of <code>HtmlHelper<TModel></code> (as the property <code>Html</code>, which is why you can use <code>@Html...</code>),
where <code>TModel</code> is the type defined in your <code>@model</code> statement. So in your case, when you are looking at this view <code>TModel</code>
will always be of the type <code>ViewModels.MyViewModels.Theme</code>.</p>
<p>Now, the next argument is a bit tricky. So lets look at an invocation</p>
<pre><code>@Html.TextBoxFor(model=>model.SomeProperty);
</code></pre>
<p>It looks like we have a little lambda, And if one were to guess the signature, one might think that the type for
this argument would simply be a <code>Func<TModel, TProperty></code>, where <code>TModel</code> is the type of the view model and <code>TProperty</code>
is inferred as the type of the property.</p>
<p>But thats not quite right, if you look at the <em>actual</em> type of the argument its <code>Expression<Func<TModel, TProperty>></code>.</p>
<p>So when you normally generate a lambda, the compiler takes the lambda and compiles it down into MSIL, just like any other
function (which is why you can use delegates, method groups, and lambdas more or less interchangeably, because they are just
code references.)</p>
<p>However, when the compiler sees that the type is an <code>Expression<></code>, it doesn't immediately compile the lambda down to MSIL, instead it generates an
Expression Tree!</p>
<h2>What is an <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx" rel="noreferrer">Expression Tree</a>?</h2>
<p>So, what the heck is an expression tree. Well, it's not complicated but its not a walk in the park either. To quote ms:</p>
<p>| Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.</p>
<p>Simply put, an expression tree is a representation of a function as a collection of "actions".</p>
<p>In the case of <code>model=>model.SomeProperty</code>, the expression tree would have a node in it that says: "Get 'Some Property' from a 'model'"</p>
<p>This expression tree can be <em>compiled</em> into a function that can be invoked, but as long as it's an expression tree, it's just a collection of nodes.</p>
<h2>So what is that good for?</h2>
<p>So <code>Func<></code> or <code>Action<></code>, once you have them, they are pretty much atomic. All you can really do is <code>Invoke()</code> them, aka tell them to
do the work they are supposed to do.</p>
<p><code>Expression<Func<>></code> on the other hand, represents a collection of actions, which can be appended, manipulated, <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expressionvisitor.aspx" rel="noreferrer">visited</a>, or <a href="http://msdn.microsoft.com/en-us/library/bb345362.aspx" rel="noreferrer">compiled</a> and invoked.</p>
<h2>So why are you telling me all this?</h2>
<p>So with that understanding of what an <code>Expression<></code> is, we can go back to <code>Html.TextBoxFor</code>. When it renders a textbox, it needs
to generate a few things <em>about</em> the property that you are giving it. Things like <code>attributes</code> on the property for validation, and specifically
in this case it needs to figure out what to <em>name</em> the <code><input></code> tag.</p>
<p>It does this by "walking" the expression tree and building a name. So for an expression like <code>model=>model.SomeProperty</code>, it walks the expression
gathering the properties that you are asking for and builds <code><input name='SomeProperty'></code>.</p>
<p>For a more complicated example, like <code>model=>model.Foo.Bar.Baz.FooBar</code>, it might generate <code><input name="Foo.Bar.Baz.FooBar" value="[whatever FooBar is]" /></code></p>
<p>Make sense? It is not just the work that the <code>Func<></code> does, but <em>how</em> it does its work is important here.</p>
<p>(Note other frameworks like LINQ to SQL do similar things by walking an expression tree and building a different grammar, that this case a SQL query)</p>
<h2>How does the Model Binder work?</h2>
<p>So once you get that, we have to briefly talk about the model binder. When the form gets posted, it's simply like a flat
<code>Dictionary<string, string></code>, we have lost the hierarchical structure our nested view model may have had. It's the
model binder's job to take this key-value pair combo and attempt to rehydrate an object with some properties. How does it do
this? You guessed it, by using the "key" or name of the input that got posted.</p>
<p>So if the form post looks like</p>
<pre><code>Foo.Bar.Baz.FooBar = Hello
</code></pre>
<p>And you are posting to a model called <code>SomeViewModel</code>, then it does the reverse of what the helper did in the first place. It looks for
a property called "Foo". Then it looks for a property called "Bar" off of "Foo", then it looks for "Baz"... and so on...</p>
<p>Finally it tries to parse the value into the type of "FooBar" and assign it to "FooBar". </p>
<p><em>PHEW!!!</em></p>
<p>And voila, you have your model. The instance the Model Binder just constructed gets handed into requested Action.</p>
<hr>
<p>So your solution doesn't work because the <code>Html.[Type]For()</code> helpers need an expression. And you are just giving them a value. It has no idea
what the context is for that value, and it doesn't know what to do with it.</p>
<p>Now some people suggested using partials to render. Now this in theory will work, but probably not the way that you expect. When you render a partial, you are changing the type of <code>TModel</code>, because you are in a different view context. This means that you can describe
your property with a shorter expression. It also means when the helper generates the name for your expression, it will be shallow. It
will only generate based on the expression it's given (not the entire context).</p>
<p>So lets say you had a partial that just rendered "Baz" (from our example before). Inside that partial you could just say:</p>
<pre><code>@Html.TextBoxFor(model=>model.FooBar)
</code></pre>
<p>Rather than</p>
<pre><code>@Html.TextBoxFor(model=>model.Foo.Bar.Baz.FooBar)
</code></pre>
<p>That means that it will generate an input tag like this:</p>
<pre><code><input name="FooBar" />
</code></pre>
<p>Which, if you are posting this form to an action that is expecting a large deeply nested ViewModel, then it will try to hydrate a property
called <code>FooBar</code> off of <code>TModel</code>. Which at best isn't there, and at worst is something else entirely. If you were posting to a specific action that was accepting a <code>Baz</code>, rather than the root model, then this would work great! In fact, partials are a good way to change your view context, for example if you had a page with multiple forms that all post to different actions, then rendering a partial for each one would be a great idea.</p>
<hr>
<p>Now once you get all of this, you can start to do really interesting things with <code>Expression<></code>, by programatically extending them and doing
other neat things with them. I won't get into any of that. But, hopefully, this will
give you a better understanding of what is going on behind the scenes and why things are acting the way that they are.</p>
|
26,144,305 |
How to install subprocess module for python?
|
<p>pip is not able to find this module, as well as me on pypi website.
Could you please tell me the secret, how to install it?</p>
<p>I need the module to spawn new shell process via subprocess.call. I have seen a lot of examples, where people use <code>import subprocess</code>, but no one shows how it was installed.</p>
<p>Error, that i got (just in case i've lost my mind and does not understand what is going on):</p>
<pre><code>Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.
C:\Users\Alexander\Desktop\tests-runner>python run.py
Traceback (most recent call last):
File "run.py", line 165, in <module>
main()
File "run.py", line 27, in main
subprocess.call('py.test')
File "C:\Python27\lib\subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python27\lib\subprocess.py", line 710, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
</code></pre>
| 26,144,342 | 2 | 5 | null |
2014-10-01 14:56:48.5 UTC
| 6 |
2021-10-25 11:51:45.953 UTC
| null | null | null | null | 1,391,074 | null | 1 | 17 |
python|python-2.7|subprocess
| 112,684 |
<p>There is no need to install this module in Python 2.7. It is a standard module that is built in.</p>
<p>The <a href="https://docs.python.org/2/library/subprocess.html" rel="noreferrer">documentation</a> shows that it was added to the library for Python version 2.4. It's been with us for a long time now.</p>
<hr>
<p>The error that you show in your question update is nothing more prosaic than a file not found error. Likely the executable file that you are attempting to call <code>Popen</code> on cannot be found. </p>
<p>That traceback indicates that <code>subprocess</code> is installed and has been imported. The problem is simply that the call to <code>subprocess.call('py.test')</code> is failing. </p>
<hr>
<p>For future reference, this is the type of traceback you encounter when attempting to import a module that has not been installed:</p>
<pre>
>>> import foo
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named foo
</pre>
|
10,956,587 |
How to create a downloadable public link for files on server
|
<p>I am afraid my question could be very stupid, and also be duplicate. But I didn't manage to find what I want after looking for some similar questions on this site. </p>
<p>My question is simple, I have a big file, i.e. 1GB on my Ubuntu server, and I want to share this file with other users. How can I create a URL address for public users, in other words, when one user click this URL, the download will automatically start without demanding a username and password, just like we download many stuff (pdf, music) when we find an usable url with google. </p>
<p>Someone suggests me to setup an anonymous ftp. I think it's a possible solution, but I didn't succeed to accomplish it. Can some one give me more details how I achieve my goal, (with or without ftp will both ok). </p>
<p>Thanks for any help, and I am very grateful for some examples, or some tutorials !</p>
| 10,956,664 | 2 | 1 | null |
2012-06-08 22:09:32.457 UTC
| 9 |
2012-06-08 22:18:35.39 UTC
| null | null | null | null | 977,145 | null | 1 | 21 |
linux|http|ftp
| 27,468 |
<p>Install Apache2</p>
<pre><code>sudo apt-get install apache2
</code></pre>
<p>Place your into file the /var/www/ directory (might need root privileges for this)</p>
<pre><code>sudo cp yourfile /var/www/yourfile
</code></pre>
<p>Access the file with the following link:</p>
<pre><code>http://your-ip-address/yourfile
</code></pre>
<p>If your running under a router or firewall, you might have to open port 80 and forward it to your pc.</p>
|
11,139,605 |
Call a model method in a Controller
|
<p>I'm have some difficulties here, I am unable to successfully call a method which belongs to a <code>ProjectPage</code> <em>model</em> in the <code>ProjectPage</code> <em>controller</em>.</p>
<p>I have in my <code>ProjectPage</code> controller:</p>
<pre><code>def index
@searches = Project.published.financed
@project_pages = form_search(params)
end
</code></pre>
<p>And in my <code>ProjectPage</code> <em>model</em>:</p>
<pre><code>def form_search(searches)
searches = searches.where('amount > ?', params[:price_min]) if check_params(params[:price_min])
@project_pages = ProjectPage.where(:project_id => searches.pluck(:'projects.id'))
end
</code></pre>
<p>However, I am unable to successfully call the <code>form_search</code> <em>method</em>.</p>
| 11,140,145 | 3 | 0 | null |
2012-06-21 13:46:17.887 UTC
| 13 |
2016-01-27 20:08:37.347 UTC
|
2012-06-21 19:34:22.13 UTC
| null | 1,134,742 | null | 1,468,585 | null | 1 | 41 |
ruby-on-rails|methods|model|controller|instantiation
| 73,253 |
<p>To complete davidb's answer, two things you're doing wrong are:</p>
<p>1) you're calling a model's function from a controller, when the model function is only defined in the model itself. So you do need to call </p>
<pre><code>Project.form_search
</code></pre>
<p>and define the function with </p>
<pre><code>def self.form_search
</code></pre>
<p>2) you're calling params from the model. In the MVC architecture, the model doesn't know anything about the request, so params is not defined there. Instead, you'll need to pass the variable to your function like you're already doing...</p>
|
11,023,929 |
Using the "alternate screen" in a bash script
|
<p>The <em>alternate screen</em> is used by many "user-interactive" terminal applications like vim, htop, screen, alsamixer, less, ... It is like a different buffer of the terminal content, which disappears when the application exits, so the whole terminal gets restored and it looks like the application hasn't output anything.</p>
<p>I'd like to achieve exactly the same thing in my own shell (bash) script, except that it doesn't have to be that portable. I'd stick to linux only and xterm-based terminal emulators; but the solution should use something like <code>tput</code> if it's possible. However, I don't want to use some external scripting language (or even something like C).</p>
<p>Although I don't want to use C (as it should be a bash-script with as few dependencies as possible), I had a look into the source code of less. It seems to use terminfo as the database and looks up the "ti" terminal capability in its initialisation. When removing the line, it doesn't use the alternate sceen, so I assumed that I found the responsible code line.</p>
<p>However, I can't find such a capability in <code>man terminfo</code>. But maybe I'm on the wrong path finding a solution for this. Maybe terminfo / tput isn't my friend.</p>
<p>So (how) can I use the alternate screen in a bash script? Does somebody know a simple application in which source code I may find a hint? (C application or bash script or whatever...)</p>
| 11,024,208 | 3 | 0 | null |
2012-06-13 21:57:51.797 UTC
| 29 |
2022-05-21 21:10:58.333 UTC
| null | null | null | null | 592,323 | null | 1 | 59 |
linux|bash|terminal|terminfo
| 12,441 |
<p>You can switch to the alternate screen using this command:</p>
<pre><code>$ tput smcup
</code></pre>
<p>And back with:</p>
<pre><code>$ tput rmcup
</code></pre>
<p>These commands just output the appropriate escape sequences for your terminal. If it is an XTERM they will be equivalent to the (more known but less elegant or portable):</p>
<pre><code>$ echo -e "\e[?1049h"
</code></pre>
<p>And:</p>
<pre><code>$ echo -e "\e[?1049l"
</code></pre>
<p>For more terminal control commands see <code>man 5 terminfo</code>.</p>
|
11,068,800 |
Rails auto-assigning id that already exists
|
<p>I create a new record like so:</p>
<p><code>truck = Truck.create(:name=>name, :user_id=>2)</code></p>
<p>My database currently has several thousand entities for truck, but I assigned the id's to several of them, in a way that left some id's available. So what's happening is rails creates item with id = 150 and it works fine. But then it tries to create an item and assign it id = 151, but that id may already exist, so I'm seeing this error:</p>
<p><code>ActiveRecord::RecordNotUnique (PG::Error: ERROR: duplicate key value violates unique constraint "companies_pkey"
DETAIL: Key (id)=(151) already exists.</code></p>
<p>And the next time I run the action, it will simply assign the id 152, which will work fine if that value isn't already taken. How can I get rails to check whether an ID already exists before it assigns it?</p>
<p>Thanks!</p>
<p>EDIT</p>
<p>The Truck id is what is being duplicated. The user already exists and is a constant in this case. It actually is a legacy issue that I have to deal with. One option, is to re-create the table at let rails auto assign every id this time around. I'm beginning to think this may be the best choice because I'm have a few other problems, but the migration for doing this would be very complicated because Truck is a foreign key in so many other tables. Would there be a simple way to have rails create a new table with the same data already stored under Truck, with auto-assigned ID's and maintaining all existing relationships?</p>
| 11,068,971 | 5 | 5 | null |
2012-06-17 03:54:05.623 UTC
| 46 |
2019-07-03 06:08:24.183 UTC
|
2013-02-18 05:34:15.3 UTC
| null | 216,363 | null | 216,363 | null | 1 | 99 |
ruby-on-rails|ruby-on-rails-3|postgresql
| 28,272 |
<p>Rails is probably using the built-in PostgreSQL sequence. The idea of a sequence is that it is only used once.</p>
<p>The simplest solution is to set the sequence for your company.id column to the highest value in the table with a query like this:</p>
<pre><code>SELECT setval('company_id_seq', (SELECT max(id) FROM company));
</code></pre>
<p>I am guessing at your sequence name "company_id_seq", table name "company", and column name "id" ... please replace them with the correct ones. You can get the sequence name with <code>SELECT pg_get_serial_sequence('tablename', 'columname');</code> or look at the table definition with <code>\d tablename</code>.</p>
<p>An alternate solution is to override the save() method in your company class to manually set the company id for new rows before saving. </p>
|
11,341,660 |
Change EOL on multiple files in one go
|
<p>Is there any way in Notepad++ (or even with another tool) to change the line ending automatically <strong>on multiple files in one go</strong>?</p>
<p>i.e. convert a mix of windows EOL (<code>CRLF</code>) and UNIX EOL (<code>LF</code>) files to be all Windows EOL (<code>CRLF</code>)</p>
| 11,341,759 | 8 | 1 | null |
2012-07-05 09:38:59.333 UTC
| 27 |
2022-05-02 09:15:29.127 UTC
|
2014-08-03 21:34:20.183 UTC
| null | 369 | null | 1,052,126 | null | 1 | 105 |
notepad++|batch-processing|eol
| 98,519 |
<p>The <em>Replace</em> dialog can handle extended characters like EOL. Just change "Search Mode" to "Extended", and you can work with EOL (\r\n in Windows or \n in Unix), tabs (\t), etc. </p>
<p>You can also use the <em>Find in Files</em> tab of the dialog to do the replace across multiple files.</p>
<p><img src="https://i.stack.imgur.com/FQOUp.png" alt="Screenshot"></p>
|
13,079,387 |
How to add data by columns in csv file using R?
|
<p>I have information that is contained in vectors, for example:</p>
<pre><code>sequence1<-seq(1:20)
sequence2<-seq(21:40)
...
</code></pre>
<p>I want to append that data to a file, so I am using:</p>
<pre><code>write.table(sequence1,file="test.csv",sep=",",append=TRUE,row.names=FALSE,col.names=FALSE)
write.table(sequence2,file="test.csv",sep=",",append=TRUE,row.names=FALSE,col.names=FALSE)
</code></pre>
<p>But the issue is that this is added all in one column like:</p>
<pre><code>1
2
3
...
21
22
...
40
</code></pre>
<p>I want to add that data in columns so that it ends up like:</p>
<pre><code>1 21
2 22
3 23
... ...
20 40
</code></pre>
<p>How I can do that using R?</p>
| 13,079,410 | 4 | 1 | null |
2012-10-26 00:51:11.323 UTC
| 1 |
2015-07-15 05:06:22.27 UTC
|
2012-10-26 00:57:20.893 UTC
| null | 128,421 | null | 1,029,620 | null | 1 | 8 |
r|csv|append
| 43,979 |
<p><code>write.table</code> writes a data.frame or matrix to a file. If you want two write a two-column data.frame (or matrix) to a file using <code>write.table</code>, then you need to create such an object in <code>R</code></p>
<pre><code>x <- data.frame(sequence1, sequence2)
write.table(x, file = 'test.csv', row.names=FALSE,col.names=FALSE)
</code></pre>
<p>See <code>?write.table</code> for a very clear description of what the function does.</p>
<p>As stated by @JoshuaUlrich's comment, this is not really an <code>R</code> issue, you can't append a column to a csv file due to the way it is stored on disk.</p>
|
12,885,538 |
PHP Curl And Cookies
|
<p>I have some problem with PHP Curl and cookies authentication.</p>
<p>I have a file <strong>Connector.php</strong> which authenticates users on another server and returns the cookie of the current user.</p>
<p>The Problem is that I want to authenticate thousands of users with curl but it authenticates and saves COOKIES only for one user at a time.</p>
<p>The code for connector.php is this:</p>
<pre><code> <?php
if(!count($_REQUEST)) {
die("No Access!");
}
//Core Url For Services
define ('ServiceCore', 'http://example.com/core/');
//Which Internal Service Should Be Called
$path = $_GET['service'];
//Service To Be Queried
$url = ServiceCore.$path;
//Open the Curl session
$session = curl_init($url);
// If it's a GET, put the GET data in the body
if ($_GET['service']) {
//Iterate Over GET Vars
$postvars = '';
foreach($_GET as $key=>$val) {
if($key!='service') {
$postvars.="$key=$val&";
}
}
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $postvars);
}
//Create And Save Cookies
$tmpfname = dirname(__FILE__).'/cookie.txt';
curl_setopt($session, CURLOPT_COOKIEJAR, $tmpfname);
curl_setopt($session, CURLOPT_COOKIEFILE, $tmpfname);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_FOLLOWLOCATION, true);
// EXECUTE
$json = curl_exec($session);
echo $json;
curl_close($session);
?>
</code></pre>
<p>Here is the process of authentication:</p>
<ol>
<li>User enters username and password: <code>Connector.php?service=logon&user_name=user32&user_pass=123</code></li>
<li><code>Connector.php?service=logosessionInfo</code> returns info about the user based on the cookies saved earlier with logon service.</li>
</ol>
<p>The problem is that this code saves the cookie in one file for each user and can't handle multiple user authentications.</p>
| 44,300,788 | 6 | 3 | null |
2012-10-14 19:05:24.84 UTC
| 23 |
2020-05-19 15:20:21.41 UTC
|
2020-05-19 15:20:21.41 UTC
| null | 1,951,708 | null | 640,549 | null | 1 | 34 |
php|authentication|cookies|curl
| 177,185 |
<p>Solutions which are described above, even with unique CookieFile names, can cause a lot of problems on scale.</p>
<p>We had to serve a lot of authentications with this solution and our server went down because of high file read write actions.</p>
<p>The solution for this was to use Apache Reverse Proxy and omit CURL requests at all.</p>
<p>Details how to use Proxy on Apache can be found here:
<a href="https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html" rel="nofollow noreferrer">https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html</a></p>
|
13,222,468 |
Android Google Analytics - Connection to service failed
|
<p>Just started implementing Google Analytics V2 in my Android application, though I'm having troubles.</p>
<p>I believe I've set up an acount with a property and profiles correctly.
I've supplied my key in the analytics.xml file and in each activity I use the </p>
<p><code>EasyTracker.getInstance().activityStart(this);</code> in the onStart method</p>
<p>and </p>
<p><code>EasyTracker.getInstance().activityStop(this);</code> in the onStop method of every activity.</p>
<p>However I don't seem to see any results on the Google Analytics website. Moreover, I turned on the debug options and I can see in log cat various messages from Gav2 (Google Analytics), implying on a problem.</p>
<p>For example</p>
<pre><code>11-04 21:56:48.000: W/GAV2(6376): Thread[main,5,main]: **Connection to service failed 1**
11-04 21:56:48.040: W/GAV2(6376): Thread[main,5,main]: **Need to call initialize() and be in fallback mode to start dispatch.**
11-04 21:56:48.050: I/GAV2(6376): Thread[main,5,main]: ExceptionReporter created, original handler is com.keypod.utils.AppCrashExceptionHandler
11-04 21:56:50.055: I/GAV2(6376): Thread[GAThread,5,main]: No campaign data found.
11-04 21:56:50.060: I/GAV2(6376): Thread[GAThread,5,main]: putHit called
11-04 21:56:50.410: I/GAV2(6376): Thread[GAThread,5,main]: putHit called
11-04 21:56:53.035: I/GAV2(6376): Thread[Service Reconnect,5,main]: connecting to Analytics service
11-04 21:56:53.035: I/GAV2(6376): Thread[Service Reconnect,5,main]: connect: bindService returned false for Intent { act=com.google.android.gms.analytics.service.START (has extras) }
**11-04 21:56:53.035: W/GAV2(6376): Thread[Service Reconnect,5,main]: Connection to service failed 1
11-04 21:56:53.035: I/GAV2(6376): Thread[Service Reconnect,5,main]: falling back to local store**
11-04 21:56:53.040: I/GAV2(6376): Thread[GAThread,5,main]: Sending hit to store
11-04 21:56:53.100: I/GAV2(6376): Thread[GAThread,5,main]: Sending hit to store
11-04 21:56:53.150: V/GAV2(6376): Thread[GAThread,5,main]: dispatch running...
</code></pre>
<p>It seems like it can't connect and then it "fallsback" to local store.
Am I doing something wrong? Or should I just ignore that warning and wait for the results to show up on the site?</p>
<p>I followed Google's guide step-by-step.</p>
<p>Thanks!</p>
| 13,226,356 | 4 | 1 | null |
2012-11-04 20:17:11.027 UTC
| 5 |
2013-08-21 18:50:11.397 UTC
| null | null | null | null | 773,520 | null | 1 | 38 |
android|google-analytics
| 10,989 |
<p>I can now see results in my analytics page so apparently I just needed to wait.</p>
<p>Google should do something about that warning, it can be misleading.</p>
<p><em><strong>Update:</em></strong> An interesting thing I've noticed which may also help, Google Analytics web interface doesn't show data from the current day on default. In order to view the data collected from the current day, you need to click on the date range picker on the top-right side, and select the current day from the Calendar (or Today from the combobox).</p>
|
16,943,176 |
How to Deserialize XML using DataContractSerializer
|
<p>I'm trying to deserialize an xml document:</p>
<pre><code><?xml version="1.0"?>
<games xmlns = "http://serialize">
<game>
<name>TEST1</name>
<code>TESTGAME1</code>
<ugn>1111111</ugn>
<bets>
<bet>5,00</bet>
</bets>
</game>
<game>
<name>TEST2</name>
<code>TESTGAME2</code>
<ugn>222222</ugn>
<bets>
<bet>0,30</bet>
<bet>0,90</bet>
</bets>
</game>
</games>
</code></pre>
<p>.cs class:</p>
<pre><code>namespace XmlParse
{
using System.Collections.Generic;
using System.Runtime.Serialization;
[DataContract(Namespace = "http://serialize")]
public class game
{
#region Public Properties
[DataMember]
public string name { get; set; }
[DataMember]
public string code { get; set; }
[DataMember]
public long ugn { get; set; }
[DataMember]
public List<decimal> bets { get; set; }
#endregion
}
[KnownType(typeof(game))]
[DataContract(Namespace = "http://serialize")]
public class games
{
#region Public Properties
[DataMember]
public List<game> game { get; set; }
#endregion
}
}
</code></pre>
<p>Main:</p>
<pre><code>FileStream fs = new FileStream(Path.Combine(this.path, xmlDocumentName), FileMode.Open);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(games));
// Deserialize the data and read it from the instance.
games deserializedPerson = (games)ser.ReadObject(reader, true);
reader.Close();
fs.Close();
</code></pre>
<p>deserializedPerson shows count = 0</p>
<p>what gives?</p>
<p><img src="https://i.stack.imgur.com/X254m.png" alt="enter image description here"></p>
| 16,964,951 | 1 | 1 | null |
2013-06-05 14:56:31.907 UTC
| 4 |
2016-01-14 15:00:25.31 UTC
|
2013-06-06 15:29:18.747 UTC
| null | 455,042 | null | 455,042 | null | 1 | 19 |
c#|asp.net|.net|datacontractserializer|xml-deserialization
| 40,936 |
<p>I figured it out. Maybe there are other implementations but this works. For the life of me I couldn't find any examples that use List inside an object. Here is a working example:</p>
<p>XML document to parse:</p>
<pre><code><?xml version="1.0"?>
<games xmlns = "http://serialize">
<game>
<name>TEST1</name>
<code>TESTGAME1</code>
<ugn>1111111</ugn>
<bets>
<bet>5,00</bet>
</bets>
</game>
<game>
<name>TEST2</name>
<code>TESTGAME2</code>
<ugn>222222</ugn>
<bets>
<bet>0,30</bet>
<bet>0,90</bet>
</bets>
</game>
</games>
</code></pre>
<p>.cs class:</p>
<pre><code>namespace XmlParse
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
[DataContract(Name = "game", Namespace = "")]
public class Game
{
[DataMember(Name = "name", Order = 0)]
public string Name { get; private set; }
[DataMember(Name = "code", Order = 1)]
public string Code { get; private set; }
[DataMember(Name = "ugn", Order = 2)]
public string Ugn { get; private set; }
[DataMember(Name = "bets", Order = 3)]
public Bets Bets { get; private set; }
}
[CollectionDataContract(Name = "bets", ItemName = "bet", Namespace = "")]
public class Bets : List<string>
{
public List<decimal> BetList
{
get
{
return ConvertAll(y => decimal.Parse(y, NumberStyles.Currency));
}
}
}
[CollectionDataContract(Name = "games", Namespace = "")]
public class Games : List<Game>
{
}
}
</code></pre>
<p>Read and parse xml document:</p>
<pre><code>string fileName = Path.Combine(this.path, "Document.xml");
DataContractSerializer dcs = new DataContractSerializer(typeof(Games));
FileStream fs = new FileStream(fileName, FileMode.Open);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
Games games = (Games)dcs.ReadObject(reader);
reader.Close();
fs.Close();
</code></pre>
|
17,097,236 |
Replace invalid values with None in Pandas DataFrame
|
<p>Is there any method to replace values with <code>None</code> in Pandas in Python?</p>
<p>You can use <code>df.replace('pre', 'post')</code> and can replace a value with another, but this can't be done if you want to replace with <code>None</code> value, which if you try, you get a strange result.</p>
<p>So here's an example:</p>
<pre><code>df = DataFrame(['-',3,2,5,1,-5,-1,'-',9])
df.replace('-', 0)
</code></pre>
<p>which returns a successful result.</p>
<p>But,</p>
<pre><code>df.replace('-', None)
</code></pre>
<p>which returns a following result:</p>
<pre><code>0
0 - // this isn't replaced
1 3
2 2
3 5
4 1
5 -5
6 -1
7 -1 // this is changed to `-1`...
8 9
</code></pre>
<p>Why does such a strange result be returned?</p>
<p>Since I want to pour this data frame into MySQL database, I can't put <code>NaN</code> values into any element in my data frame and instead want to put <code>None</code>. Surely, you can first change <code>'-'</code> to <code>NaN</code> and then convert <code>NaN</code> to <code>None</code>, but I want to know why the dataframe acts in such a terrible way.</p>
<blockquote>
<p>Tested on pandas 0.12.0 dev on Python 2.7 and OS X 10.8. Python is a
pre-installed version on OS X and I installed pandas by using SciPy
Superpack script, for your information.</p>
</blockquote>
| 17,097,397 | 10 | 6 | null |
2013-06-13 21:17:31.31 UTC
| 24 |
2022-05-04 20:44:44.163 UTC
|
2019-04-21 03:13:30.763 UTC
| null | 4,909,087 | null | 2,360,798 | null | 1 | 111 |
python|pandas|dataframe|replace|nan
| 240,931 |
<p>Actually in later versions of pandas this will give a TypeError:</p>
<pre><code>df.replace('-', None)
TypeError: If "to_replace" and "value" are both None then regex must be a mapping
</code></pre>
<p>You can do it by passing either a list or a dictionary:</p>
<pre><code>In [11]: df.replace('-', df.replace(['-'], [None]) # or .replace('-', {0: None})
Out[11]:
0
0 None
1 3
2 2
3 5
4 1
5 -5
6 -1
7 None
8 9
</code></pre>
<p>But I recommend using NaNs rather than None:</p>
<pre><code>In [12]: df.replace('-', np.nan)
Out[12]:
0
0 NaN
1 3
2 2
3 5
4 1
5 -5
6 -1
7 NaN
8 9
</code></pre>
|
20,848,485 |
Spring-boot: cannot use persistence
|
<p>I am days into this, and - although I am learning a lot - starting to despair. </p>
<p>I have tried all the suggestions on this excellent question: </p>
<p><a href="https://stackoverflow.com/questions/1158159/no-persistence-provider-for-entitymanager-named">No Persistence provider for EntityManager named</a></p>
<p>I had this working at one point using the ubiquitous HibernateUtil class, but was told to move to a plain JPA style here:</p>
<p><a href="https://stackoverflow.com/questions/20804768/spring-restful-controller-method-improvement-suggestions">Spring RESTful controller method improvement suggestions</a></p>
<p>Unfortunately, I could not get the bean injection to work properly in spring-boot. Here is my attempt:</p>
<p><a href="https://stackoverflow.com/questions/20808290/spring-jpa-hibernate-no-qualifying-bean-of-type-javax-persistence-entitymanag">Spring JPA (Hibernate) No qualifying bean of type: javax.persistence.EntityManagerFactory</a></p>
<p>After much work down that path I ended up with a null entity manager. I found this and began to think it could not work:</p>
<p><a href="https://stackoverflow.com/questions/11256746/using-jpa2-in-tomcat-6-persitencecontext-doesnt-work-entitymanager-is-null">Using JPA2 in Tomcat 6: @PersitenceContext doesn't work, EntityManager is null</a></p>
<p>It seems to me like the EntityManagerFactory absolutely should be a bean in whatever context spring-boot creates, but ... whatever. I would think that at least this would work:</p>
<p>Application launch:</p>
<pre><code>@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</code></pre>
<p>Controller:</p>
<pre><code>@Controller
public class GetController {
private static final String PERSISTENCE_UNIT_NAME = "cpJpaPu";
@RequestMapping(value = "/user", method = RequestMethod.GET)
public @ResponseBody User getUser(@RequestParam(value="id", required=true) int id) {
User user = null;
EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = emf.createEntityManager();
UserDAO userDao = new UserDAO();
userDao.setEntityManager(em);
user = userDao.load(id);
return user;
}
}
</code></pre>
<p>DAO:</p>
<pre><code>public class UserDAO {
public EntityManager entityManager;
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityManager getEntityManager() {
return entityManager;
}
public void insert(User user) {
entityManager.persist(user);
}
public User load(int id) {
return entityManager.find(User.class, id);
}
}
</code></pre>
<p>/src/main/resources/persistence.xml:</p>
<pre><code><persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="cpJpaPu" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.mydomain.User</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.connection.username" value="user"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/mydb"/>
</properties>
</persistence-unit>
</persistence>
</code></pre>
<p>And it doesn't work:</p>
<pre><code>javax.persistence.PersistenceException: No Persistence provider for EntityManager named cpJpaPu
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
com.mydomain.GetController.getUser(GetController.java:25)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:947)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:878)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:946)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
</code></pre>
<p>--- Added Info ---</p>
<p>POM:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mygroup</groupId>
<artifactId>myartifact</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>0.5.0.M6</version>
</parent>
<dependencies>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<!-- Must override version or face stack traces -->
<version>4.3.0.Final</version>
</dependency>
<!-- Spring ORM, works with Hibernate -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<!-- Spring implementation of Jackson for RESTful JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- JDBC -->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<!-- Prevent logging conflicts -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<start-class>com.cloudfordev.controlpanel.Application</start-class>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
</project>
</code></pre>
| 20,858,963 | 5 | 7 | null |
2013-12-30 22:17:54.997 UTC
| 2 |
2018-08-10 02:42:12.427 UTC
|
2017-05-23 12:10:04.807 UTC
| null | -1 | null | 1,625,358 | null | 1 | 13 |
java|spring|hibernate|jpa|spring-boot
| 46,007 |
<p>This question was answered with a much better architecture over here:</p>
<p><a href="https://stackoverflow.com/questions/20808290/spring-jpa-hibernate-no-qualifying-bean-of-type-javax-persistence-entitymanag/20850535?noredirect=1#comment31278706_20850535">Spring JPA (Hibernate) No qualifying bean of type: javax.persistence.EntityManagerFactory</a></p>
|
25,933,532 |
HibernateException: Could not obtain transaction-synchronized Session for current thread
|
<p>I am getting error:</p>
<pre><code>Exception in thread "main" org.hibernate.HibernateException:
Could not obtain transaction-synchronized Session for current thread
</code></pre>
<p><strong>main</strong></p>
<pre><code>ppService.deleteProductPart(cPartId, productId);
</code></pre>
<p><strong>@Service("productPartService")</strong></p>
<pre><code>@Override
public void deleteProductPart(int cPartId, int productId) {
productPartDao.deleteProductPart(cPartId, productId);
}
</code></pre>
<p><strong>@Repository("productPartDAO")</strong></p>
<pre><code>@Override
public void deleteProductPart(ProductPart productPart) {
sessionFactory.getCurrentSession().delete(productPart);
}
@Override
public void deleteProductPart(int cPartId, int productId) {
ProductPart productPart = (ProductPart) sessionFactory.getCurrentSession()
.createCriteria("ProductPart")
.add(Restrictions.eq("part", cPartId))
.add(Restrictions.eq("product", productId)).uniqueResult();
deleteProductPart(productPart);
}
</code></pre>
<p>How to fix it?</p>
<p><strong>UPDATE:</strong></p>
<p>If I modify method like this:</p>
<pre><code>@Override
@Transactional
public void deleteProductPart(int cPartId, int productId) {
System.out.println(sessionFactory.getCurrentSession());
}
</code></pre>
<p>It returns: </p>
<pre><code>SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] collectionQueuedOps=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])
</code></pre>
<p>But if I remove <code>@Transactional</code> it ends up with exception:</p>
<pre><code>org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
</code></pre>
<p>I get it working by adding <code>@Transactional</code>, but now I am getting <code>org.hibernate.MappingException: Unknown entity: ProductPart</code> although I chained <code>.uniqueResult()</code> to <code>Criteria</code>. How to fix it?</p>
| 25,934,936 | 3 | 8 | null |
2014-09-19 12:04:50.47 UTC
| 2 |
2018-05-11 07:41:41.087 UTC
|
2015-11-08 14:05:42.02 UTC
| null | 2,674,303 | null | 480,632 | null | 1 | 9 |
java|spring|hibernate
| 41,220 |
<p>The error <code>org.hibernate.MappingException: Unknown entity: ProductPart</code> indicates there is no entity with name <code>ProductPart</code>. One way to fix this issue is to pass the <code>Class</code> object to <code>createCriteria</code> method as:</p>
<pre><code>createCriteria(ProductPart.class)
</code></pre>
<p>From API the difference in using String and Class is as follows:</p>
<p><a href="http://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html#createCriteria%28java.lang.String%29">Session.createCriteria(String)</a></p>
<pre><code>Create a new Criteria instance, for the given entity name.
</code></pre>
<p><a href="http://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html#createCriteria%28java.lang.Class%29">Session.createCriteria(Class)</a></p>
<blockquote>
<p>Create a new Criteria instance, for the given entity class, or a
superclass of an entity class, with the given alias.</p>
</blockquote>
<p>If you pass a String then hibernate looks for an entity whose name is declared as <code>ProductPart</code>.</p>
|
51,061,148 |
C vs C++ compilation incompatibility - does not name a type
|
<p>I am trying to use a supplier's library in combination with my C++ application. The library is largely based on C, which is normally not a problem with the <code>extern "C"</code> option, but I ran into an issue that the C++ compiler does not accept. </p>
<p>I simplified my code into the following example files. header.h represents a header from the suppier library, main.c/cpp are my own files. My real application is a C++ application, so I want to get it to work with main.cpp. </p>
<p>header.h (note the line <code>u64 u64;</code>):</p>
<pre><code>#ifndef HEADER_H
#define HEADER_H
#include <stdint.h>
typedef uint64_t u64;
union teststruct {
u64 u64;
struct {
u64 x:32;
u64 y:32;
} s;
};
#endif
</code></pre>
<p>main.c:</p>
<pre><code>#include <stdio.h>
#include "header.h"
int main() {
union teststruct a;
a.u64=5;
printf("%x\n", a.u64);
return 0;
}
</code></pre>
<p>main.cpp (same as main.c but with an extra <code>extern "C"</code> statement): </p>
<pre><code>#include <stdio.h>
extern "C" {
#include "header.h"
}
int main() {
union teststruct a;
a.u64=5;
printf("%x\n", a.u64);
return 0;
}
</code></pre>
<p>Compiling main.c using the line</p>
<pre><code>gcc -o test main.c
</code></pre>
<p>compiles without problems. However, compiling the C++ version using the g++ compiler with the command </p>
<pre><code>g++ -o test main.cpp
</code></pre>
<p>gives the following compiler errors:</p>
<pre><code>In file included from main.cpp:12:0:
header.h:11:9: error: ‘u64’ does not name a type
u64 x:32;
^
header.h:12:9: error: ‘u64’ does not name a type
u64 y:32;
^
</code></pre>
<p>The issue is that the supplier used the same name (u64) for both the type and the variable name, which seems like a bad idea to begin with, but gcc apparently accepts it. I do not want to change the library (i.e. header.h) as it is very large,this occurs a lot in the code, and I occasionally get updates for it. Is there a way to make g++ accept this combination, or a way to modify main.cpp to make it compile <em>without</em> changing header.h?</p>
| 51,061,476 | 3 | 4 | null |
2018-06-27 11:03:39.447 UTC
| 4 |
2018-06-28 09:39:45.58 UTC
| null | null | null | null | 5,295,802 | null | 1 | 53 |
c++|c|gcc|g++
| 5,049 |
<p><code>teststruct</code> defines a scope in C++. You can form the qualified id <code>teststruct::u64</code>. So the language rules for name lookup account for that, allowing members of classes and unions to hide identifiers in outer scope. Once <code>u64 u64;</code> is introduced, the unqualified <code>u64</code> cannot refer to the global <code>::u64</code>, only the member. And the member is not a type.</p>
<p>In C <code>union teststruct</code> does not define a scope. The field can only be used in member access, so there can never arise a conflict. As such the field need not hide the file scope type identifier.</p>
<p>There is nothing, as far as I can tell, that you may do in order to easily work around it. This library (which is a perfectly valid C library), is not a valid C++ library. No different than if it used <code>new</code> or <code>try</code> as variable names. It needs to be adapted.</p>
|
10,193,824 |
nohup error no such file or directory
|
<p>I am trying to run a string of <code>nohup</code> commands to get server statistics.
However I get an error of <em>'No such file or directory'</em>. Note that the 3 <code>nohup</code> calls are embedded in a script which is executed through a <code>cron</code> job. And the first <code>nohup</code> works but the other 2 return an error. Ironically enough, when run on a different server, the script works fine. </p>
<ul>
<li><p>Commands</p>
<pre><code>nohup vmpstat -a -n 60 1000 > myvmstats
</code></pre></li>
<li><p>(works) </p>
<pre><code>nohup mpstat -P ALL 1 1000 > mympstats
</code></pre></li>
<li><p>(returns: nohup cannot run command <code>mpstat</code>: no such file or directory)</p>
<pre><code>nohup iostat -t -x 60 1000 >myiostats
</code></pre></li>
<li><p>(returns: nohup cannot run command <code>iostat</code>: no such file or directory) </p></li>
</ul>
<p>Any idea what's wrong?</p>
| 10,282,875 | 2 | 6 | null |
2012-04-17 15:05:56.18 UTC
| 1 |
2013-09-11 06:03:08.263 UTC
|
2012-04-17 15:20:16.067 UTC
| null | 15,168 | null | 856,350 | null | 1 | 8 |
linux|shell|unix|nohup
| 48,640 |
<p>The usual problem with scripts that run from the command line and not when run by <code>cron</code> is 'environment'. There are many questions on SO where this is exemplified, including:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/4341324/perl-script-works-but-not-via-cron/4341351#4341351">Perl script works but not when via cron</a></li>
<li><a href="https://stackoverflow.com/questions/780072/why-does-my-command-line-not-run-from-cron/780091#780091">Why does my command line not run from cron?</a></li>
<li><a href="https://stackoverflow.com/questions/8812425/bash-script-not-executing-in-cron-correctly/8812493#8812493">Bash script not executing in cron correctly</a></li>
<li><a href="https://stackoverflow.com/questions/2229825/where-can-i-set-environment-variables-that-crontab-will-use">How can I set environment variables that crontab will use?</a></li>
</ul>
<p>For debugging purposes, add a command/line to the cron-run script that does:</p>
<pre><code>env > /tmp/cron.job
</code></pre>
<p>Review whether the PATH there includes what you expect, and in particular, whether it includes the directory (directories) where each of the three programs is installed. And do check that you run the programs you expect from the command line:</p>
<pre><code>which vmpstat mpstat iostat
</code></pre>
<p>It is a reasonable guess that the two 'missing' commands are not in a directory on PATH when your script is run by <code>cron</code>. And <code>cron</code> gives you a bare minimal environment; it is completely unlike <code>at</code> in that respect.</p>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/6028683/crontab-and-testing-a-command-to-be-executed/6028899#6028899">Crontab and testing a command to be executed</a></li>
<li><a href="https://stackoverflow.com/questions/9548595/how-do-i-add-pre-hook-and-post-hook-scripts-that-run-before-all-of-my-cron-jobs/9656386#9656386">How do I add pre-hook and post-hook scripts that run before all of my cron jobs?</a></li>
</ul>
|
9,891,460 |
iOS UILocalNotification - No delegate methods triggered when app is running in background and the icon is clicked upon notification
|
<p>iPhone version - 5.1 (9B176)</p>
<p>Below is the series of events during Local Notification where in which <code>didFinishLaunchingWithOptions</code> method is not invoked.</p>
<ol>
<li>App is running in background. </li>
<li>Got local notification - simple notification no dialog.</li>
<li>Click on the app icon which shows the badge number.</li>
</ol>
<p>Expected as per <a href="http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/IPhoneOSClientImp/IPhoneOSClientImp.html" rel="nofollow noreferrer">Apple documentation</a>: </p>
<blockquote>
<p>As a result of the presented notification, the user taps the action button of the alert or taps (or clicks) the application icon.
If the action button is tapped (on a device running iOS), the system launches the application and the application calls its delegate’s <code>didFinishLaunchingWithOptions</code> method (if implemented); it passes in the notification payload (for remote notifications) or the local-notification object (for local notifications).</p>
<p><strong>If the application icon is tapped on a device running iOS, the application calls the same method, but furnishes no information about the notification</strong> </p>
</blockquote>
<p>Actual :
<code>didFinishLaunchingWithOptions</code> <strong>NOT invoked</strong>. But <code>applicationWillEnterForeground</code> and <code>applicationDidBecomeActive</code> were invoked.</p>
| 9,891,596 | 1 | 1 | null |
2012-03-27 14:22:19.15 UTC
| 9 |
2015-06-25 07:06:48.693 UTC
|
2015-06-25 07:06:48.693 UTC
| null | 3,633,534 | null | 1,223,134 | null | 1 | 17 |
iphone|ios5|notifications|uilocalnotification|localnotification
| 10,298 |
<p>You are correct. The behavior is inconsistent with the documentation. Putting the documentation aside and focusing on actual behavior; The crux of the matter seems to be this: If your app becomes active by the user interacting with the notification you will receive a pointer to the notification, if the user taps your application icon directly you will not.</p>
<p>To illustrate. If you present an alert style notification and the user taps the action button, or if, as in your case, you present a banner notification and the user taps on that you will receive a pointer to the notification in one of two ways:</p>
<p><em>If your application was in the Not-Running state:</em></p>
<pre><code>-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
UILocalNotification *launchNote = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (launchNote){
// I recieved a notification while not running
}
}
</code></pre>
<p><em>If your application is running in any state:</em></p>
<pre><code>-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
// I recieved a notification
}
</code></pre>
<p>In the case where a user elects to cancel an alert style notification, that notification is gone.</p>
<p>The truly annoying an inconsistent part is that if you present a banner notification and the user taps your icon you seem to have no way of retrieving a reference to the presented notifications in the notification center. i.e. they do not appear in the <code>[[UIApplication sharedApplication] scheduledLocalNotifications]</code> array, presumably because they are no longer scheduled but are now presented.</p>
<p>So in short; The documentation is wrong. And there are other annoying inconsistencies. If this behavior is a problem for you you should file a bug with Apple.</p>
|
9,857,247 |
Can I Use JQuery Mobile With EmberJS?
|
<p>I want use JQuery mobile for the front-end of my mobile application, but I need a JavaScript MVC framework to do the back-end integration stuff and I'm looking at using EmberJS. Is there a guide for this kind of integration? Any pitfalls I should avoid? As a reference, I'm originally coming from a Sencha Touch 2.0 background.</p>
| 9,857,422 | 2 | 0 | null |
2012-03-25 01:41:11.537 UTC
| 10 |
2014-03-06 18:12:46.013 UTC
| null | null | null | null | 122,164 | null | 1 | 24 |
jquery|jquery-mobile|ember.js
| 9,742 |
<p>Hiya Hope following link helps you to right path for your questions: (Is there a guide for this kind of integration? )</p>
<p>Yep, you can <strong>Basic proof of concept Ember.js with Jquery Mobile</strong> => <a href="https://github.com/LuisSala/emberjs-jqm" rel="nofollow noreferrer">https://github.com/LuisSala/emberjs-jqm</a> </p>
<p>little start up tutorial: <a href="http://www.andymatthews.net/read/2012/03/07/Getting-Started-With-EmberJS" rel="nofollow noreferrer">http://www.andymatthews.net/read/2012/03/07/Getting-Started-With-EmberJS</a> </p>
<p>Article: <a href="http://www.infoq.com/articles/emberjs" rel="nofollow noreferrer">http://www.infoq.com/articles/emberjs</a></p>
<p>Ember Wiki has links to developer modules: <a href="https://github.com/emberjs/ember.js/wiki" rel="nofollow noreferrer">https://github.com/emberjs/ember.js/wiki</a></p>
<p>To start with and identify pitfalls:</p>
<p>(For proof of concept for your specific case you can also refer to the POC link I have shared above and glaze through the existing issues in stack overflow, Else I will go for head first and find out and fix the issues as go)</p>
<p><a href="https://stackoverflow.com/tags/emberjs/new">https://stackoverflow.com/tags/emberjs/new</a></p>
<p><a href="https://stackoverflow.com/questions/tagged/emberjs">https://stackoverflow.com/questions/tagged/emberjs</a></p>
<p><a href="https://stackoverflow.com/questions/9747966/how-to-make-emberjs-app-with-a-mobile-look-like-the-one-in-jquery-mobile">How to make emberjs app with a mobile look (like the one in jquery mobile)?</a></p>
<p>Hope this helps,</p>
<p>Cheers!</p>
|
10,069,121 |
no network in Android x86 on VirtualBox 4.1.2
|
<p>My issue is nearly identical to <a href="https://stackoverflow.com/questions/8227825/android-x86-porting-unable-to-make-it-work">this question</a>. I tried those solution and none worked. But I am using a different Android x86 image. I'm using the ICS (4.0-RC1) asus_laptop image. (I tried a different image previously and couldn't get it to install.)</p>
<p>I installed VirtualBox 4.1.12 on Kubuntu 12.04. I followed <a href="https://stackoverflow.com/questions/1554099/slow-android-emulator/6058689#6058689">these steps</a> and installed the <a href="http://code.google.com/p/android-x86/downloads/detail?name=android-x86-4.0-RC1-asus_laptop.iso&can=2&q=" rel="noreferrer">android-x86-4.0-RC1-asus_laptop.iso</a> image in my VM. It boots up and works correctly except for networking.</p>
<p>Alt-F1 <code>netcfg</code> shows no interfaces up except the lo (127.0.0.1). eth0, which should be available, is not shown. That prevents me from trying the <a href="http://osdir.com/ml/android-x86/2011-11/msg00352.html" rel="noreferrer">solution here</a>.</p>
<p>New references I'm checking out:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/9847285/android-ics-x86-on-virtualbox-with-internet-connection">Android ICS x86 on VirtualBox with Internet Connection</a></li>
<li><a href="http://groups.google.com/group/android-x86/browse_thread/thread/30fa23d81cddfab1/2e480f6b9cbf773d" rel="noreferrer">http://groups.google.com/group/android-x86/browse_thread/thread/30fa23d81cddfab1/2e480f6b9cbf773d</a></li>
<li><a href="https://stackoverflow.com/questions/7825934/how-to-setup-network-for-android-honeycomb-in-virtualbox">How to setup network for Android Honeycomb in VirtualBox?</a></li>
</ul>
| 10,134,671 | 7 | 1 | null |
2012-04-09 05:07:06.933 UTC
| 16 |
2020-02-18 10:59:52.263 UTC
|
2017-05-23 12:30:30.88 UTC
| null | -1 | null | 463,994 | null | 1 | 34 |
networking|ubuntu|virtualbox|android-x86|ifconfig
| 94,346 |
<p>The following works very good for me</p>
<pre><code>sudo vi /etc/init.sh
</code></pre>
<p>add 4 lines below to init.sh</p>
<pre><code>netcfg eth0 dhcp
echo nameserver <ip> > /etc/resolv.conf
dnsmasq
setprop net.dns1 8.8.8.8
</code></pre>
<p>on virtualbox set the network interface to bridged (PCnet Fast III) and that's all.</p>
|
10,250,055 |
SDURLCache with AFNetworking and offline mode not working
|
<p>I'm using <code>AFNetworking</code> and <code>SDURLCache</code> for all my networking operations.</p>
<p>I have <code>SDURLCache</code> set like this:</p>
<pre><code>SDURLCache *urlCache = [[SDURLCache alloc]
initWithMemoryCapacity:1024*1024*2 // 2MB mem cache
diskCapacity:1024*1024*15 // 15MB disk cache
diskPath:[SDURLCache defaultCachePath]];
[urlCache setMinCacheInterval:1];
[NSURLCache setSharedURLCache:urlCache];
</code></pre>
<p>All my request are using cachePolicy <code>NSURLRequestUseProtocolCachePolicy</code>, which according to apple docs works like this:</p>
<blockquote>
<p>If an NSCachedURLResponse does not exist for the request, then the
data is fetched from the originating source. If there is a cached
response for the request, the URL loading system checks the response
to determine if it specifies that the contents must be revalidated. If
the contents must be revalidated a connection is made to the
originating source to see if it has changed. If it has not changed,
then the response is returned from the local cache. If it has changed,
the data is fetched from the originating source.</p>
<p>If the cached response doesn’t specify that the contents must be revalidated, the maximum age or expiration specified in the response
is examined. If the cached response is recent enough, then the
response is returned from the local cache. If the response is
determined to be stale, the originating source is checked for newer
data. If newer data is available, the data is fetched from the
originating source, otherwise it is returned from the cache.</p>
</blockquote>
<p>So everything works perfectly even in airplane mode as long as the cache is not stale. When the cache expires (max-age and others), the failure block gets called.</p>
<p>I've been digging a little inside the <code>SDURLCache</code> and this method returns a response with valid data (I've parsed the data to a string and it contains the cached information)</p>
<pre><code>- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
request = [SDURLCache canonicalRequestForRequest:request];
NSCachedURLResponse *memoryResponse =
[super cachedResponseForRequest:request];
if (memoryResponse) {
return memoryResponse;
}
NSString *cacheKey = [SDURLCache cacheKeyForURL:request.URL];
// NOTE: We don't handle expiration here as even staled cache data is
// necessary for NSURLConnection to handle cache revalidation.
// Staled cache data is also needed for cachePolicies which force the
// use of the cache.
__block NSCachedURLResponse *response = nil;
dispatch_sync(get_disk_cache_queue(), ^{
NSMutableDictionary *accesses = [self.diskCacheInfo
objectForKey:kAFURLCacheInfoAccessesKey];
// OPTI: Check for cache-hit in in-memory dictionary before to hit FS
if ([accesses objectForKey:cacheKey]) {
response = [NSKeyedUnarchiver unarchiveObjectWithFile:
[_diskCachePath stringByAppendingPathComponent:cacheKey]];
if (response) {
// OPTI: Log entry last access time for LRU cache eviction
// algorithm but don't save the dictionary
// on disk now in order to save IO and time
[accesses setObject:[NSDate date] forKey:cacheKey];
_diskCacheInfoDirty = YES;
}
}
});
// OPTI: Store the response to memory cache for potential future requests
if (response) {
[super storeCachedResponse:response forRequest:request];
}
return response;
}
</code></pre>
<p>So at this point I have no idea what to do, because I believe that the response is handled by the OS and then <code>AFNetworking</code> receives a </p>
<pre><code>- (void)connection:(NSURLConnection *)__unused connection
didFailWithError:(NSError *)error
</code></pre>
<p>inside <code>AFURLConnectionOperation</code>.</p>
| 15,885,318 | 3 | 5 | null |
2012-04-20 16:34:10.9 UTC
| 15 |
2013-08-02 10:02:30.7 UTC
|
2013-02-18 05:01:21.653 UTC
| null | 113,079 | null | 359,467 | null | 1 | 37 |
iphone|objective-c|ios|caching|afnetworking
| 6,965 |
<p>Well I've finally reached a not so ugly workaround:</p>
<p><strong>First</strong></p>
<p>If you're using IOS5/IOS6 you can drop SDURLCache and use the native one:</p>
<pre><code>//Set Cache
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
diskCapacity:20 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
</code></pre>
<p>But remember that in IOS5 https requests wont be cached in IOS6 they will.</p>
<p><strong>Second</strong></p>
<p>We need to add the following frameworks to our <code>Prefix.pch</code> so AFNetworking can start monitoring our internet connection.</p>
<pre><code>#import <MobileCoreServices/MobileCoreServices.h>
#import <SystemConfiguration/SystemConfiguration.h>
</code></pre>
<p><strong>Third</strong></p>
<p>We need and AFHTTPClient instance so we can intercept every outgoing request and change his <code>cachePolicy</code></p>
<pre><code>-(NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters {
NSMutableURLRequest * request = [super requestWithMethod:method path:path parameters:parameters];
if (request.cachePolicy == NSURLRequestUseProtocolCachePolicy && self.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
request.cachePolicy = NSURLRequestReturnCacheDataDontLoad;
}
if (self.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown) {
puts("uknown reachability status");
}
return request;
}
</code></pre>
<p>With these peaces of code we can now detect when the wifi/3g is unavailable and the specify the request to use always the cache no matter what. (Offline Mode)</p>
<p><strong>Notes</strong></p>
<ul>
<li><p>I still don't know what to do when the <code>networkReachabilityStatus</code> is <code>AFNetworkReachabilityStatusUnknown</code> This can happen is a request is made as soon as the application starts and AF has not obtained the internet status yet.</p></li>
<li><p>Remember that in order for this to work the server has to set the correct cache headers in the http response.</p></li>
</ul>
<p><strong>UPDATE</strong></p>
<p>Looks like IOS6 has some problems loading cached responses in no-internet situations, so even if the request is cached and the request cache policy is seted to <code>NSURLRequestReturnCacheDataDontLoad</code> the request will fail.</p>
<p>So an ugly workaround is to modify <code>(void)connection:(NSURLConnection __unused *)connection
didFailWithError:(NSError *)error</code> in <code>AFURLConnectionOperation.m</code> to retrieve the cached response if the request fails but only for specific cache policies.</p>
<pre><code>- (void)connection:(NSURLConnection __unused *)connection
didFailWithError:(NSError *)error
{
self.error = error;
[self.outputStream close];
[self finish];
self.connection = nil;
//Ugly hack for making the request succeed if we can find a valid non-empty cached request
//This is because IOS6 is not handling cache responses right when we are in a no-connection sittuation
//Only use this code for cache policies that are supposed to listen to cache regarding it's expiration date
if (self.request.cachePolicy == NSURLRequestUseProtocolCachePolicy ||
self.request.cachePolicy == NSURLRequestReturnCacheDataElseLoad ||
self.request.cachePolicy == NSURLRequestReturnCacheDataDontLoad) {
NSCachedURLResponse * cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:self.request];
if (cachedResponse.data.length > 0) {
self.responseData = cachedResponse.data;
self.response = cachedResponse.response;
self.error = nil;
}
}
}
</code></pre>
|
10,248,000 |
Spring interface injection example
|
<p>No one so far was capable of providing a working correct example of interface injection in Spring Framework.</p>
<p>Martin Fowler article is not for mortals, everything else just words positioned in a very confusing way. I have surfed over THIRTY articles, where people either tell "Spring doesn't directly supports for interface injection"("and because I don't know exactly how I will only describe setter and constructor injections") or either "I will discuss it in my other threads" or either there will be few comments below saying that it is wrong example. I don't ask for explanation, I BEG for example.</p>
<p><strong>There are three types of injection: Constructor, Setter and Interface. Spring doesn't support the latest directly(as I have observed people saying). So how is it done exactly?</strong></p>
<p>Thank You,</p>
| 31,244,931 | 7 | 9 | null |
2012-04-20 14:16:01.807 UTC
| 16 |
2020-05-19 16:17:06.003 UTC
|
2020-05-19 16:13:35.767 UTC
| null | 5,377,805 | null | 873,139 | null | 1 | 40 |
java|spring|dependency-injection|interface
| 118,923 |
<p>According to <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-collaborators" rel="noreferrer">Variants of DI in spring</a></p>
<blockquote>
<p>DI exists in two major variants, Constructor-based dependency injection and Setter-based dependency injection.</p>
</blockquote>
<p>Also see <a href="http://www.springbyexample.org/examples/core-concepts-dependency-injection-to-the-rescue.html" rel="noreferrer">Interface injection is not implemented in Spring</a> clearly states it.</p>
<p>So there are only two variants of DI. So if documentation says nothing about interface injection, its clear that its not there. Those who believe that interface injection is done by providing setter method in interface answer me:</p>
<ol>
<li>Why spring ref doc left mention of interface injection?</li>
<li>Why can't interface injection via providing setter method <strong>NOT</strong> considered as setter injection itself. Why create special term for that when introduction of interface doesn't affect anything, I mean its still configured the same way. If they were different then how can one find it via seeing the config. Shouldn't it be transparent that in config and not seeing the impl that actually configured class implements some interface ?</li>
<li>Just like <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-class-instance-factory-method" rel="noreferrer">Instantiation using an instance factory method</a> and <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-class-static-factory-method" rel="noreferrer">Instantiation using an static factory method</a>, some bean attributes should clarify the interface injection?</li>
</ol>
|
9,999,713 |
HTML Text with tags to formatted text in an Excel cell
|
<p>Is there a way to take HTML and import it to excel so that it is formatted as rich text (preferably by using VBA)? Basically, when I paste to an Excel cell, I'm looking to turn this:</p>
<pre><code><html><p>This is a test. Will this text be <b>bold</b> or <i>italic</i></p></html>
</code></pre>
<p>into this:</p>
<p>This is a test. Will this text be <b>bold</b> or <i>italic</i></p>
| 10,001,494 | 7 | 0 | null |
2012-04-03 19:06:14.13 UTC
| 18 |
2022-01-07 10:30:26.807 UTC
|
2018-06-27 14:10:45.75 UTC
| null | 8,112,776 | null | 1,295,942 | null | 1 | 45 |
vba|excel|html-parsing
| 235,461 |
<p>Yes it is possible. In fact let Internet Explorer do the dirty work for you.</p>
<p><strong>MY ASSUMPTIONS</strong></p>
<ol>
<li>I am assuming that the html text is in Cell A1 of Sheet1. You can also use a variable instead.</li>
<li>If you have a column full of html values, then simply put the below code in a loop</li>
</ol>
<p><strong>CODE</strong></p>
<pre><code>Sub Sample()
Dim Ie As Object
Set Ie = CreateObject("InternetExplorer.Application")
With Ie
.Visible = False
.Navigate "about:blank"
.document.body.InnerHTML = Sheets("Sheet1").Range("A1").Value
.document.body.createtextrange.execCommand "Copy"
ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("A1")
.Quit
End With
End Sub
</code></pre>
<p><strong>SNAPSHOT</strong></p>
<p><img src="https://i.stack.imgur.com/gdvIp.png" alt="enter image description here" /></p>
|
9,835,553 |
How to backup Sql Database Programmatically in C#
|
<p>I want to write a code to backup my Sql Server 2008 Database using C# in .Net 4 FrameWork. Can anyone help in this.</p>
| 9,835,603 | 10 | 0 | null |
2012-03-23 07:34:47.667 UTC
| 19 |
2020-06-08 08:48:02.91 UTC
|
2012-10-02 11:02:02.917 UTC
| null | 3,714 |
user1287692
| null | null | 1 | 46 |
.net|database|sql-server-2008|c#-4.0|backup
| 129,105 |
<p>The following <a href="http://www.mssqltips.com/sqlservertip/1849/backup-and-restore-sql-server-databases-programmatically-with-smo/" rel="noreferrer">Link</a> has explained complete details about how to back sql server 2008 database using c#</p>
<p>Sql Database backup can be done using many way. You can either use Sql Commands like in the other answer or have create your own class to backup data.</p>
<p>But these are different mode of backup.</p>
<ol>
<li>Full Database Backup</li>
<li>Differential Database Backup</li>
<li>Transaction Log Backup</li>
<li>Backup with Compression</li>
</ol>
<p>But the disadvantage with this method is that it needs your sql management studio to be installed on your client system.</p>
|
10,002,704 |
How do I make bootstrap table rows clickable?
|
<p>I can hack this myself, but I think bootstrap has this capability.</p>
| 10,003,291 | 7 | 1 | null |
2012-04-03 23:03:42.437 UTC
| 17 |
2017-02-07 00:59:31.213 UTC
|
2012-04-03 23:42:31.53 UTC
| null | 13,969 | null | 13,969 | null | 1 | 69 |
css|html|twitter-bootstrap
| 188,743 |
<p>Using jQuery it's quite trivial. v2.0 uses the <code>table</code> class on all tables.</p>
<pre><code>$('.table > tbody > tr').click(function() {
// row was clicked
});
</code></pre>
|
9,766,014 |
Connect to mysql on Amazon EC2 from a remote server
|
<p>I want to connect to db on EC2 from my local machine, I am not able to do and have tried everything-
I am using this command to connect to EC2:</p>
<pre><code>mysql -uUSERNAME -hEC2_IP -pPASSWORD
</code></pre>
<p>This error is generated </p>
<blockquote>
<p>ERROR 2003 (HY000): Can't connect to MySQL server on 'IP' (110)</p>
</blockquote>
<p>I have modified my.cnf with </p>
<pre><code>skip networking
bind-address = 0.0.0.0
</code></pre>
<p>Still not able to connect to the database</p>
| 9,794,879 | 20 | 2 | null |
2012-03-19 06:42:38.363 UTC
| 37 |
2021-11-09 08:28:51.453 UTC
|
2016-05-24 12:08:22.263 UTC
| null | 5,447,994 | null | 1,230,483 | null | 1 | 78 |
mysql|amazon-ec2
| 171,470 |
<p>There could be one of the following reasons:</p>
<ol>
<li>You need make an entry in the Amazon Security Group to allow remote
access from your machine to Amazon EC2 instance. :- I believe this
is done by you as from your question it seems like you already made
an entry with 0.0.0.0, which allows everybody to access the machine.</li>
<li>MySQL not allowing user to connect from remote machine:- By
default MySql creates root user id with admin access. But root
id's access is limited to localhost only. This means that root user
id with correct password will not work if you try to access MySql
from a remote machine. To solve this problem, you need to
allow either the root user or some other DB user to access MySQL from remote
machine. I would not recommend allowing root user id accessing DB
from remote machine. You can use wildcard character % to specify any remote machine.</li>
<li>Check if machine's local firewall is not enabled. And if its enabled
then make sure that port 3306 is open.</li>
</ol>
<p>Please go through following link: <a href="http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html">How Do I Enable Remote Access To MySQL Database Server?</a></p>
|
8,219,008 |
Call functions from function inside an object (object literal)
|
<p>I'm learning to use object literals in JS, and I'm trying to get a function inside an object to run by calling it through another function in the same object. Why isn't the function "run" running when calling it from the function "init"?</p>
<pre><code>var RunApp = {
init: function(){
this.run()
},
run: function() {
alert("It's running!");
}
};
</code></pre>
| 8,219,018 | 3 | 0 | null |
2011-11-21 21:51:06.1 UTC
| 15 |
2022-06-22 04:39:23.373 UTC
|
2022-06-22 04:37:46.4 UTC
| null | 1,155,282 | null | 937,624 | null | 1 | 44 |
javascript|function|object-literal
| 80,078 |
<p>That code is only a <strong>declaration</strong>. You need to actually <em>call</em> the function:</p>
<pre><code>RunApp.init();
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/mattball/s6MJ5/" rel="nofollow noreferrer">http://jsfiddle.net/mattball/s6MJ5/</a></p>
|
11,863,499 |
Disable html input element by applying custom css class
|
<p>I want to disable my all input element of a div by applying my custom css class.
but i could not find any css attribute which can disable an input element.
currently what am i doing</p>
<pre><code> $('#div_sercvice_detail :input').attr('disabled', true);
$('#retention_interval_div :input').addClass("disabled");
</code></pre>
<p>which can disable all input element of div with css attr but i want to apply my custom class for disable all input with some extra css attributes</p>
<pre><code> $('#retention_interval_div :input').addClass("disabled");
</code></pre>
<p>class</p>
<pre><code>.disabled{
color : darkGray;
font-style: italic;
/*property for disable input element like*/
/*disabled:true; */
}
</code></pre>
<p>any suggestion for doing this with jquery without using .attr('disabled', true);?</p>
| 11,863,713 | 6 | 5 | null |
2012-08-08 11:25:45.11 UTC
| null |
2019-11-14 08:57:07.813 UTC
| null | null | null | null | 908,943 | null | 1 | 7 |
javascript|jquery|html|css
| 69,181 |
<p>There is no way to disable an element with just CSS, but you can create a style that will be applied to disabled elements:</p>
<pre><code><style>
#retention_interval_div input[type="text"]:disabled {
color : darkGray;
font-style: italic;
}
</style>
</code></pre>
<p>Then in your code you just have to say:</p>
<pre><code> $('#retention_interval_div :input').prop("disabled", true);
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/nnnnnn/DhgMq/">http://jsfiddle.net/nnnnnn/DhgMq/</a></p>
<p>(Of course, the <code>:disabled</code> CSS selector isn't supported in old browsers.)</p>
<p>Note that if you're using jQuery version >= 1.6 you should use <code>.prop()</code> instead of <code>.attr()</code> to change the disabled state.</p>
<p>The code you showed is not disabling the same elements that it applies the class to - the selectors are different. If that's just a typo then you can simplify it to one line:</p>
<pre><code>$('#retention_interval_div :input').addClass("disabled").attr('disabled', true);
</code></pre>
|
12,000,228 |
How to determine whether object reference is null?
|
<p>What is the best way to determine whether an object reference variable is <code>null</code>?</p>
<p>Is it the following?</p>
<pre><code>MyObject myObjVar = null;
if (myObjVar == null)
{
// do stuff
}
</code></pre>
| 12,000,254 | 5 | 1 | null |
2012-08-17 05:26:08.203 UTC
| 1 |
2021-07-14 20:25:59.497 UTC
|
2012-08-17 06:54:46.99 UTC
| null | 327,528 | null | 327,528 | null | 1 | 13 |
c#|object|null|visual-studio-2005|object-reference
| 55,571 |
<p>Yes, you are right, the following snippet is the way to go if you want to execute arbitrary code:</p>
<pre><code>MyObject myObjVar;
if (myObjVar == null)
{
// do stuff
}
</code></pre>
<p>BTW: Your code wouldn't compile the way it is now, because <code>myObjVar</code> is accessed before it is being initialized.</p>
|
11,529,070 |
Scroll to the center of viewport
|
<p>I would like to center a <code>div</code> by clicking it. So if I'm clicking a <code>div</code> I want it to scroll to the center of the browser viewport. I don't want to use anchor points like the guides and examples I've seen. How can I achieve this?</p>
| 11,531,265 | 4 | 7 | null |
2012-07-17 19:00:08.017 UTC
| 12 |
2020-12-08 09:36:15.08 UTC
|
2015-03-05 21:48:20.4 UTC
| null | 75,699 | null | 1,532,592 | null | 1 | 17 |
javascript|jquery|scroll|center|scrollto
| 36,342 |
<p>In some way you have to identify the clickable elements. I build an example, that uses the <code>class</code>-attribute for that.</p>
<h3>Step 1</h3>
<p>This is the script, that does the work:</p>
<pre class="lang-js prettyprint-override"><code>$('html,body').animate({
scrollTop: $(this).offset().top - ( $(window).height() - $(this).outerHeight(true) ) / 2
}, 200);
</code></pre>
<p>What you tried is to scroll the container to the top of the page. You also have to calculate and subtract the difference between the container height and the viewport height. Divide this by two (as you want to have the same space on top and bottom and you are ready to go.</p>
<h3>Step 2</h3>
<p>Then you add the click handler to all the elements:</p>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
$('.image').click( function() {
$('html,body').animate({ scrollTop: $(this).offset().top - ( $(window).height() - $(this).outerHeight(true) ) / 2 }, 200);
});
});
</code></pre>
<h3>Step 3</h3>
<p>Set up some HTML/CSS:</p>
<pre class="lang-html prettyprint-override"><code><style>
div.image {
border: 1px solid red;
height: 500px;
width: 500px;
}
</style>
<div class="image">1</div>
<div class="image">2</div>
<div class="image">3</div>
<div class="image">4</div>
<div class="image">5</div>
</code></pre>
<p>And you're done.</p>
<h3>Check out the demo</h3>
<p>Try it yourself <a href="http://jsfiddle.net/insertusernamehere/3T9Py/">http://jsfiddle.net/insertusernamehere/3T9Py/</a></p>
|
11,469,432 |
Entity Framework Code First Lazy Loading
|
<p>I am having two object classes</p>
<pre><code>public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
// Navigation
public ICollection<Product> Products { get; set; }
}
public class Product
{
public Guid Id { get; set; }
// Navigation
public User User { get; set; }
public Guid User_Id { get; set; }
public string Name { get; set; }
}
</code></pre>
<p>When i load a user using dataContext, i get the list of Products being null (this is ok).</p>
<p>If i add "virtual" keyword to Products list,</p>
<pre><code>public virtual ICollection<Product> Products { get; set; }
</code></pre>
<p>when i load the user, i get the Products list as well.</p>
<p>Why is this happening? I thought that "virtual" keyword is used for not loading the entities unless you explicit this (using an "Include" statement)</p>
<p>I think i got it all wrong</p>
| 11,469,605 | 2 | 2 | null |
2012-07-13 11:16:53.023 UTC
| 15 |
2012-07-13 11:27:39.607 UTC
|
2012-07-13 11:21:14.417 UTC
| null | 41,956 | null | 1,157,952 | null | 1 | 31 |
c#|entity-framework|entity-framework-4|ef-code-first|lazy-loading
| 45,183 |
<p>This is wrong</p>
<blockquote>
<p>"virtual" keyword is used for not loading the entities unless you
explicit this (using an "Include" statement)</p>
</blockquote>
<p>Lazy Loading means that entities will be automatically loaded when you first access collection or navigation property, and that will happen transparently, as though they were always loaded with parent object.</p>
<p>Using "include" is loading on demand, when you specify properties you want to query.</p>
<p>Existence of <code>virtual</code> keyword is related only to lazy loading. <code>virtual</code> keyword allows entity framework runtime create dynamic proxies for your entity classes and their properties, and by that support lazy loading. Without virtual, lazy loading will not be supported, and you get null on collection properties. </p>
<p>Fact is that you can use "include" in any case, but without lazy loading it is the only way to access collection and navigation properties.</p>
|
11,804,148 |
Parsing HTML to get text inside an element
|
<p>I need to get the text inside the two elements into a string:</p>
<pre class="lang-py prettyprint-override"><code>source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>"""
>>> text
'Martin Elias'
</code></pre>
<p>How could I achieve this?</p>
| 11,804,617 | 4 | 1 | null |
2012-08-03 22:31:15.09 UTC
| 10 |
2017-05-14 18:20:28.26 UTC
|
2012-08-03 22:33:02.597 UTC
| null | 246,246 | null | 1,044,378 | null | 1 | 32 |
python|html|python-2.x|html-parser
| 104,372 |
<p>I searched "python parse html" and this was the first result:
<a href="https://docs.python.org/2/library/htmlparser.html" rel="noreferrer">https://docs.python.org/2/library/htmlparser.html</a></p>
<p>This code is taken from the python docs</p>
<pre><code>from HTMLParser import HTMLParser
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print "Encountered a start tag:", tag
def handle_endtag(self, tag):
print "Encountered an end tag :", tag
def handle_data(self, data):
print "Encountered some data :", data
# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')
</code></pre>
<p>Here is the result:</p>
<pre><code>Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data : Parse me!
Encountered an end tag : h1
Encountered an end tag : body
Encountered an end tag : html
</code></pre>
<p>Using this and by looking at the code in HTMLParser I came up with this:</p>
<pre><code>class myhtmlparser(HTMLParser):
def __init__(self):
self.reset()
self.NEWTAGS = []
self.NEWATTRS = []
self.HTMLDATA = []
def handle_starttag(self, tag, attrs):
self.NEWTAGS.append(tag)
self.NEWATTRS.append(attrs)
def handle_data(self, data):
self.HTMLDATA.append(data)
def clean(self):
self.NEWTAGS = []
self.NEWATTRS = []
self.HTMLDATA = []
</code></pre>
<p>You can use it like this:</p>
<pre><code>from HTMLParser import HTMLParser
pstring = source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>"""
class myhtmlparser(HTMLParser):
def __init__(self):
self.reset()
self.NEWTAGS = []
self.NEWATTRS = []
self.HTMLDATA = []
def handle_starttag(self, tag, attrs):
self.NEWTAGS.append(tag)
self.NEWATTRS.append(attrs)
def handle_data(self, data):
self.HTMLDATA.append(data)
def clean(self):
self.NEWTAGS = []
self.NEWATTRS = []
self.HTMLDATA = []
parser = myhtmlparser()
parser.feed(pstring)
# Extract data from parser
tags = parser.NEWTAGS
attrs = parser.NEWATTRS
data = parser.HTMLDATA
# Clean the parser
parser.clean()
# Print out our data
print tags
print attrs
print data
</code></pre>
<p>Now you should be able to extract your data from those lists easily. I hope this helped!</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.