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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
45,799,650 | Git bash Error: Could not fork child process: There are no available terminals (-1) | <p>I have had up to 8 git bash terminals running at the same time before. </p>
<p>Currently I have only 2 up.</p>
<p>I have not seen this error before and I am not understanding what is causing it.</p>
<p>Any help would be appreciated!</p>
<p>Picture attached:</p>
<p><a href="https://i.stack.imgur.com/Tps5X.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Tps5X.png" alt="enter image description here"></a></p> | 45,803,951 | 32 | 4 | null | 2017-08-21 14:27:30.227 UTC | 33 | 2022-03-14 18:07:53.017 UTC | null | null | null | null | 6,817,698 | null | 1 | 222 | git|terminal|git-bash | 110,542 | <p>Found a similar issue and solution in <a href="https://groups.google.com/forum/#!topic/git-for-windows/EO27WWvHx64" rel="noreferrer">google groups</a></p>
<blockquote>
<p>I opened a windows command prompt and ran the command</p>
<pre><code>$ tasklist
</code></pre>
<p>It looks as though the ssh connections I had made in my git bash shells weren't being closed when those windows were closed and were hanging the available git bash shell windows.</p>
<p>This may be a dangerous solution but from the windows command prompt I ran</p>
<pre><code>$ taskkill /F /IM ssh.exe
</code></pre>
<p>Everything appears to be working again after this. It may not have directly been an issue of orphan processes, but this worked for at least for me.</p>
</blockquote>
<p>Additional note: you can also kill other processes, for example like:</p>
<pre><code>$ taskkill /F /IM vim.exe
</code></pre> |
19,385,882 | How to use char from keyboard in if statement [Java] | <p>I am having a bit of a problem with my code. I need to make a temperature conversion from Celsius to Fahrenheit and vice-versa with the user choosing either "F" or "C" (lower or upper case) but cannot seem to figure out how to do it properly. I don't know how to have it recognize that the variable is supposed to be entered via the keyboard.</p>
<pre><code> Scanner Keyboard = new Scanner(System.in);
System.out.println("Type C to convert from Fahrenheit to Celsius or" +
"F to convert from Celsius to Fahrenheit.");
char choice = Keyboard.nextLine().charAt(0);
//Get user input on whether to do F to C or C to F
if (choice == F) //Fahrenheit to Celsius
{
System.out.println("Please enter the temperature in Fahrenheit:");
double C = Keyboard.nextDouble();
double SaveC = C;
C = (((C-32)*5)/9);
System.out.println(SaveC + " degrees in Fahrenheit is equivalent to " + C + " degrees in Celsius.");
}
else if (choice == C)
{
System.out.println("Please enter the temperature in Celsius:");
double F = Keyboard.nextDouble();
double SaveF = F;
F = (((F*9)/5)+32);
System.out.println(SaveF +" degrees in Celsius is equivalent to " + F + " degrees in Fahrenheit.");
}
else if (choice != C && choice != F)
{
System.out.println("You've entered an invalid character.");
}
</code></pre> | 19,385,987 | 3 | 2 | null | 2013-10-15 16:04:01.803 UTC | null | 2021-12-15 17:04:25.373 UTC | 2021-12-15 17:04:25.373 UTC | null | 3,016,293 | null | 2,883,232 | null | 1 | 1 | java | 64,085 | <p>When comparing with the <code>choice</code> variable your F and C characters should be wrapped in single quotes to make them <em><a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.4" rel="nofollow">character literals</a></em>. Use <code>||</code> (meaning 'or') to test for upper or lower case. I.e.,</p>
<pre><code>if (choice == 'F' || choice == 'f')
...
else if (choice == 'C' || choice == 'c')
...
else
...
</code></pre> |
24,770,887 | Remove key-value pair from JSON object | <p>I have this JSON object below;</p>
<pre><code>[
{
XXX: "2",
YYY: "3",
ZZZ: "4"
},
{
XXX: "5",
YYY: "6",
ZZZ: "7"
},
{
XXX: "1",
YYY: "2",
ZZZ: "3"
}
]
</code></pre>
<p>I want to remove the YYY key-value from the json object such that the new json object will look like this;</p>
<pre><code>[
{
XXX: "2",
ZZZ: "4"
},
{
XXX: "5",
ZZZ: "7"
},
{
XXX: "1",
ZZZ: "3"
}
]
</code></pre>
<p>I tried <code>delete jsonObject['YYY']</code> but this is not correct. How can this be done in javascript? Thank you.</p> | 24,770,914 | 6 | 2 | null | 2014-07-16 01:39:19.057 UTC | 5 | 2021-09-19 20:08:29.1 UTC | null | null | null | null | 1,709,088 | null | 1 | 30 | javascript|json | 105,879 | <p>What you call your "JSON Object" is really a JSON Array of Objects. You have to iterate over each and delete each member individually:</p>
<pre><code>for(var i = 0; i < jsonArr.length; i++) {
delete jsonArr[i]['YYY'];
}
</code></pre> |
611,094 | Async process start and wait for it to finish | <p>I am new to the thread model in .NET. What would you use to:</p>
<ol>
<li>Start a process that handles a file <code>(process.StartInfo.FileName = fileName;)</code>.</li>
<li>Wait for the user to close the process OR abandon the thread after some time.</li>
<li>If the user closed the process, delete the file.</li>
</ol>
<p>Starting the process and waiting should be done on a different thread than the main thread, because this operation should not affect the application.</p>
<p>Example:</p>
<p>My application produces an html report. The user can right click somewhere and say "View Report" - now I retrieve the report contents in a temporary file and launch the process that handles html files i.e. the default browser. The problem is that I cannot cleanup, i.e. delete the temp file.</p> | 72,733,683 | 6 | 7 | null | 2009-03-04 15:35:17.867 UTC | 14 | 2022-06-24 10:30:58.71 UTC | 2022-06-23 16:34:00.383 UTC | Bogdan Gavril | 11,178,549 | Bogdan Gavril | 21,634 | null | 1 | 37 | c#|.net|multithreading|asynchronous|process | 75,162 | <p>The .NET 5 introduced the new API <a href="https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.waitforexitasync" rel="nofollow noreferrer"><code>Process.WaitForExitAsync</code></a>, that allows to wait asynchronously for the completion of a process. It offers the same functionality with the existing <a href="https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.waitforexit" rel="nofollow noreferrer"><code>Process.WaitForExit</code></a>, with the only difference being that the waiting is asynchronous, so it does not block the calling thread.</p>
<p>Usage example:</p>
<pre><code>private async void button1_Click(object sender, EventArgs e)
{
string filePath = Path.Combine
(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
Guid.NewGuid().ToString() + ".txt"
);
File.WriteAllText(filePath, "Hello World!");
try
{
using Process process = new();
process.StartInfo.FileName = "Notepad.exe";
process.StartInfo.Arguments = filePath;
process.Start();
await process.WaitForExitAsync();
}
finally
{
File.Delete(filePath);
}
MessageBox.Show("Done!");
}
</code></pre>
<p>In the above example the UI remains responsive while the user interacts with the opened file. The UI thread would be blocked if the <code>WaitForExit</code> had been used instead.</p> |
1,338,224 | How do I get the Window object from the Document object? | <p>I can get <code>window.document</code> but how can I get <code>document.window</code>? I need to know how to do this in all browsers.</p> | 1,338,279 | 6 | 3 | null | 2009-08-27 00:06:59.09 UTC | 3 | 2019-01-30 16:35:39.09 UTC | 2019-01-30 16:35:39.09 UTC | null | 4,298,200 | null | 92,259 | null | 1 | 63 | javascript|html|document | 81,807 | <p><a href="http://www.w3schools.com/HTMLDOM/dom_obj_window.asp" rel="nofollow noreferrer">The Window object is the top level object in the JavaScript hierarchy</a>, so just refer to it as window</p>
<p><strong>Edit:</strong>
Original answer before <a href="http://promotejs.com/" rel="nofollow noreferrer">Promote JS</a> effort. <a href="https://developer.mozilla.org/en-US/docs/JavaScript_technologies_overview" rel="nofollow noreferrer">JavaScript technologies overview</a> on Mozilla Developer Network says:</p>
<blockquote>
<p>In a browser environment, this global object is the window object.</p>
</blockquote>
<p><strong>Edit 2:</strong>
After reading the author's comment to his question (and getting downvotes), this seems to be related to the iframe's document window. Take a look at <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.parent" rel="nofollow noreferrer">window.parent</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.top" rel="nofollow noreferrer">window.top</a> and maybe compare them to infer your document window.</p>
<pre><code>if (window.parent != window.top) {
// we're deeper than one down
}
</code></pre> |
1,092,405 | counting duplicates in a sorted sequence using command line tools | <p>I have a command (cmd1) that greps through a log file to filter out a set of numbers. The numbers are
in random order, so I use sort -gr to get a reverse sorted list of numbers. There may be duplicates within
this sorted list. I need to find the count for each unique number in that list. </p>
<p>For e.g. if the output of cmd1 is:</p>
<pre><code>100
100
100
99
99
26
25
24
24
</code></pre>
<p>I need another command that I can pipe the above output to, so that, I get:</p>
<pre><code>100 3
99 2
26 1
25 1
24 2
</code></pre> | 1,092,488 | 6 | 2 | null | 2009-07-07 13:40:26.277 UTC | 15 | 2022-08-10 11:04:55.197 UTC | 2016-05-16 01:46:57.68 UTC | null | 93,540 | null | 119,622 | null | 1 | 92 | bash|command-line|sorting|count|duplicates | 77,640 | <p>how about;</p>
<pre><code>$ echo "100 100 100 99 99 26 25 24 24" \
| tr " " "\n" \
| sort \
| uniq -c \
| sort -k2nr \
| awk '{printf("%s\t%s\n",$2,$1)}END{print}'
</code></pre>
<p>The result is :</p>
<pre><code>100 3
99 2
26 1
25 1
24 2
</code></pre> |
110,575 | Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection? | <p>Earlier today a question was asked regarding <a href="https://stackoverflow.com/questions/110458/what-percentage-of-my-time-will-be-spent-in-user-input-verfication-during-web-d">input validation strategies in web apps</a>.</p>
<p>The top answer, at time of writing, suggests in <code>PHP</code> just using <code>htmlspecialchars</code> and <code>mysql_real_escape_string</code>. </p>
<p>My question is: Is this always enough? Is there more we should know? Where do these functions break down?</p> | 110,576 | 6 | 0 | null | 2008-09-21 08:58:26.37 UTC | 126 | 2017-03-17 19:02:46.927 UTC | 2017-05-23 10:30:52.59 UTC | null | -1 | Cheekysoft | 1,820 | null | 1 | 116 | php|security|xss|sql-injection | 70,847 | <p>When it comes to database queries, always try and use prepared parameterised queries. The <code>mysqli</code> and <code>PDO</code> libraries support this. This is infinitely safer than using escaping functions such as <code>mysql_real_escape_string</code>.</p>
<p>Yes, <code>mysql_real_escape_string</code> is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors.</p>
<p>Imagine the following SQL:</p>
<pre><code>$result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']);
</code></pre>
<p>You should be able to see that this is vulnerable to exploit.<br>
Imagine the <code>id</code> parameter contained the common attack vector:</p>
<pre><code>1 OR 1=1
</code></pre>
<p>There's no risky chars in there to encode, so it will pass straight through the escaping filter. Leaving us:</p>
<pre><code>SELECT fields FROM table WHERE id= 1 OR 1=1
</code></pre>
<p>Which is a lovely SQL injection vector and would allow the attacker to return all the rows.
Or</p>
<pre><code>1 or is_admin=1 order by id limit 1
</code></pre>
<p>which produces</p>
<pre><code>SELECT fields FROM table WHERE id=1 or is_admin=1 order by id limit 1
</code></pre>
<p>Which allows the attacker to return the first administrator's details in this completely fictional example.</p>
<p>Whilst these functions are useful, they must be used with care. You need to ensure that all web inputs are validated to some degree. In this case, we see that we can be exploited because we didn't check that a variable we were using as a number, was actually numeric. In PHP you should widely use a set of functions to check that inputs are integers, floats, alphanumeric etc. But when it comes to SQL, heed most the value of the prepared statement. The above code would have been secure if it was a prepared statement as the database functions would have known that <code>1 OR 1=1</code> is not a valid literal.</p>
<p>As for <code>htmlspecialchars()</code>. That's a minefield of its own.</p>
<p>There's a real problem in PHP in that it has a whole selection of different html-related escaping functions, and no clear guidance on exactly which functions do what. </p>
<p>Firstly, if you are inside an HTML tag, you are in real trouble. Look at</p>
<pre><code>echo '<img src= "' . htmlspecialchars($_GET['imagesrc']) . '" />';
</code></pre>
<p>We're already inside an HTML tag, so we don't need < or > to do anything dangerous. Our attack vector could just be <code>javascript:alert(document.cookie)</code></p>
<p>Now resultant HTML looks like</p>
<pre><code><img src= "javascript:alert(document.cookie)" />
</code></pre>
<p>The attack gets straight through. </p>
<p>It gets worse. Why? because <code>htmlspecialchars</code> (when called this way) only encodes double quotes and not single. So if we had </p>
<pre><code>echo "<img src= '" . htmlspecialchars($_GET['imagesrc']) . ". />";
</code></pre>
<p>Our evil attacker can now inject whole new parameters</p>
<pre><code>pic.png' onclick='location.href=xxx' onmouseover='...
</code></pre>
<p>gives us</p>
<pre><code><img src='pic.png' onclick='location.href=xxx' onmouseover='...' />
</code></pre>
<p>In these cases, there is no magic bullet, you just have to santise the input yourself. If you try and filter out bad characters you will surely fail. Take a whitelist approach and only let through the chars which are good. Look at the <a href="http://ha.ckers.org/xss.html" rel="noreferrer">XSS cheat sheet</a> for examples on how diverse vectors can be</p>
<p>Even if you use <code>htmlspecialchars($string)</code> outside of HTML tags, you are still vulnerable to multi-byte charset attack vectors.</p>
<p>The most effective you can be is to use the a combination of mb_convert_encoding and htmlentities as follows.</p>
<pre><code>$str = mb_convert_encoding($str, 'UTF-8', 'UTF-8');
$str = htmlentities($str, ENT_QUOTES, 'UTF-8');
</code></pre>
<p>Even this leaves IE6 vulnerable, because of the way it handles UTF. However, you could fall back to a more limited encoding, such as ISO-8859-1, until IE6 usage drops off.</p>
<p>For a more in-depth study to the multibyte problems, see <a href="https://stackoverflow.com/a/12118602/1820">https://stackoverflow.com/a/12118602/1820</a></p> |
42,154,602 | How to get form data in Flask? | <p>I need get data from form.</p>
<p>I use JavaScript to create form:</p>
<pre><code><script>
function checkAuth() {
var user = ADAL.getCachedUser();
if (user) {
var form = $('<form style="position: absolute; width: 0; height: 0; opacity: 0; display: none; visibility: hidden;" method="POST" action= "{{ url_for("general.microsoft") }}">');
form.append('<input type="hidden" name="token" value="' + ADAL.getCachedToken(ADAL.config.clientId) + '">');
form.append('<input type="hidden" name="json" value="' + encodeURIComponent(JSON.stringify(user)) + '">');
$("body").append(form);
form.submit();
}
}
</script>
</code></pre>
<p>then I need to get data from the input field which <code>name="json"</code>.</p>
<p>Here is my view function: </p>
<pre><code>@general.route("/microsoft/", methods=["GET", "POST"])
@csrf.exempt
def microsoft():
form = cgi.FieldStorage()
name = form['json'].value
return name
</code></pre>
<p>But I get an error:</p>
<p><code>builtins.KeyError KeyError: 'json'</code></p>
<p>Help me get data from form.</p> | 42,154,919 | 1 | 2 | null | 2017-02-10 08:20:01.627 UTC | 9 | 2021-09-04 07:31:23.327 UTC | 2017-02-10 09:45:32.883 UTC | null | 5,511,849 | user7378646 | null | null | 1 | 32 | javascript|python|json|flask | 126,195 | <p>You can get form data from Flask's request object with the <code>form</code> attribute:</p>
<pre><code>from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
data = request.form['input_name'] # pass the form field name as key
...
</code></pre>
<p>You can also set a default value to avoid 400 errors with the <code>get()</code> method since the <code>request.form</code> attribute is a dict-like object:</p>
<pre><code>from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
default_value = '0'
data = request.form.get('input_name', default_value)
...
</code></pre> |
39,200,572 | Error 'String or binary data would be truncated' in Microsoft SQL | <p>I got this error when inserting data to Microsoft SQL.</p>
<blockquote>
<p>error: ('22001', '[22001] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]String or binary data would be truncated. (8152) (SQLParamData); [01000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The statement has been terminated. (3621)')</p>
</blockquote>
<p>FYI, I use Python 2.7 and <code>pyodbc</code> library.</p>
<p>What is that error about? What should I do to solve it?</p> | 39,200,573 | 2 | 10 | null | 2016-08-29 07:21:05.743 UTC | 3 | 2018-11-24 14:25:12.98 UTC | 2018-11-24 14:25:12.98 UTC | null | 1,564,659 | null | 1,564,659 | null | 1 | 12 | python|sql|sql-server|database|python-2.7 | 51,304 | <p>Based on this link: <a href="http://www.sql-server-performance.com/2007/string-or-binary-data-truncated/" rel="noreferrer">http://www.sql-server-performance.com/2007/string-or-binary-data-truncated/</a></p>
<blockquote>
<p>This error message appears when you try to insert a string with more characters than the column can maximal accommodate.</p>
</blockquote> |
32,195,346 | Show a 404 page if route not found in Laravel 5.1 | <p>I am trying to figure out to show 404 page not found if a route is not found. I followed many tutorials, but it doesn't work.
I have <code>404.blade.php</code> in <code>\laravel\resources\views\errors</code></p>
<p>Also in handler.php</p>
<pre><code>public function render($request, Exception $e)
{
if ($e instanceof TokenMismatchException) {
// redirect to form an example of how i handle mine
return redirect($request->fullUrl())->with(
'csrf_error',
"Opps! Seems you couldn't submit form for a longtime. Please try again"
);
}
/*if ($e instanceof CustomException) {
return response()->view('errors.404', [], 500);
}*/
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
return response(view('error.404'), 404);
return parent::render($request, $e);
}
</code></pre>
<p>If I enter wrong URL in browser, it returns a blank page. I have </p>
<pre><code>'debug' => env('APP_DEBUG', true),
</code></pre>
<p>in app.php.</p>
<p>Can anyone help me how to show a 404 page if route is not found? Thank you.</p> | 34,791,686 | 7 | 7 | null | 2015-08-25 04:06:36.92 UTC | 4 | 2021-03-05 18:17:10.767 UTC | 2015-08-25 04:56:44.36 UTC | null | 3,739,665 | null | 3,739,665 | null | 1 | 22 | php|laravel|laravel-5.1 | 63,555 | <p>I recieved 500 errors instead of 404 errors. I solved the problem like this:</p>
<p>In the app/Exceptions/Handler.php file, there is a <strong>render</strong> function.</p>
<p>Replace the function with this function:</p>
<pre><code>public function render($request, Exception $e)
{
if ($this->isHttpException($e)) {
switch ($e->getStatusCode()) {
// not authorized
case '403':
return \Response::view('errors.403',array(),403);
break;
// not found
case '404':
return \Response::view('errors.404',array(),404);
break;
// internal error
case '500':
return \Response::view('errors.500',array(),500);
break;
default:
return $this->renderHttpException($e);
break;
}
} else {
return parent::render($request, $e);
}
}
</code></pre>
<p>You can then use views that you save in views/errors/404.blade.php, and so on.</p> |
18,133,812 | Where is the x86-64 System V ABI documented? | <p>The x86-64 System V ABI (used on everything except Windows) used to live at <a href="http://x86-64.org/documentation/abi.pdf" rel="noreferrer">http://x86-64.org/documentation/abi.pdf</a>, but that site has now fallen off the internet.</p>
<p>Is there a new authoritative home for the document?</p> | 40,348,010 | 3 | 4 | null | 2013-08-08 18:50:55.893 UTC | 34 | 2022-08-01 04:31:47.453 UTC | 2017-10-21 00:24:35.617 UTC | null | 224,132 | null | 943,619 | null | 1 | 80 | linux|assembly|x86-64|calling-convention|abi | 33,635 | <p>The System V AMD64 psABI document is maintained as LaTeX sources <a href="https://gitlab.com/x86-psABIs/x86-64-ABI" rel="nofollow noreferrer">on GitLab</a>. Similarly the i386 psABI is a separate <a href="https://gitlab.com/x86-psABIs/i386-ABI" rel="nofollow noreferrer">GitLab repo</a>. (Formerly on <a href="https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI" rel="nofollow noreferrer">github</a>). Those pages have info on where revisions are discussed.<br />
The x32 ABI (32-bit pointers in long mode) is part of the x86-64 aka AMD64 ABI doc. See Chapter 10: ILP32 Programming Model.</p>
<p>The GitLab repo auto-builds <strong><a href="https://gitlab.com/x86-psABIs/x86-64-ABI/-/jobs/artifacts/master/raw/x86-64-ABI/abi.pdf?job=build" rel="nofollow noreferrer">a PDF of the current x86-64 version</a></strong>, but not i386.</p>
<p>See also the <a href="/questions/tagged/x86" class="post-tag" title="show questions tagged 'x86'" rel="tag">x86</a> <a href="https://stackoverflow.com/tags/x86/info">tag wiki</a> for other guides / references / links.</p>
<hr />
<p>The last version on Github was <a href="https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf" rel="nofollow noreferrer">x86-64 version 1.0 draft (January 2018)</a>. As of July 2022, the current version is still 1.0, with the word Draft being removed by late 2018.</p>
<p>Github also hosts a PDF of <a href="https://github.com/hjl-tools/x86-psABI/wiki/intel386-psABI-1.1.pdf" rel="nofollow noreferrer">i386 ABI version 1.1</a>.<br />
(Note that most non-Linux OSes use an older version of the i386 ABI which doesn't require 16-byte stack alignment, only 4. GCC ended up depending on <code>-mpreferred-stack-boundary=4</code> 16-byte alignment for its SSE code-gen (perhaps unintentionally), and eventually the ABI got updated for Linux to enshrine that as an official requirement. I attempted a summary in a <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=40838#c91" rel="nofollow noreferrer">comment on GCC bug #40838</a>. This breaks backwards compat with some hand-written asm that calls other functions.)</p>
<p>Unofficially, <a href="https://stackoverflow.com/questions/36706721/is-a-sign-or-zero-extension-required-when-adding-a-32bit-offset-to-a-pointer-for/36760539#36760539">sign-extending narrow args to 32-bit is required</a> (for both i386 and amd64), because clang depends on it. Hopefully a future ABI revision will document that. GCC and/or clang now have some options to control that (TODO dig up what they were called), but the default is still the same as of 2022.</p>
<hr />
<h3>Naming: psABI</h3>
<p>The <em>Processor Supplement</em> (psABI) docs are designed as a supplement to the less-frequently-updated <a href="http://www.sco.com/developers/gabi/" rel="nofollow noreferrer">System V gABI</a> (generic), hosted on SCO's website.</p>
<hr />
<p><strong>Other links</strong></p>
<p>Also <a href="https://refspecs.linuxfoundation.org/" rel="nofollow noreferrer">https://refspecs.linuxfoundation.org/</a> hosts a copy of the gABI from 1997.</p>
<p><a href="https://uclibc.org/specs.html" rel="nofollow noreferrer">https://uclibc.org/specs.html</a> has psABI links for various non-x86 ISAs. (Although for example the ARM one only seems to document the ELF file layout, not the calling convention or process startup state.) <a href="https://uclibc.org/docs/psABI-x86_64.pdf" rel="nofollow noreferrer">https://uclibc.org/docs/psABI-x86_64.pdf</a> is an outdated copy of the x86-64 psABI (0.99.7 from 2014). The version on GitHub has clearer wording of a few things and bugfixes in some examples.</p>
<hr />
<p>Related: <em><a href="https://stackoverflow.com/questions/2535989/what-are-the-calling-conventions-for-unix-linux-system-calls-on-i386-and-x86-6">What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64</a> describes</em> the system-call calling convention for x86-64 SysV (as well as i386 Linux vs. FreeBSD).</p>
<p>It also summarizes the function calling conventions for integer args.
System calls don't take FP or SSE/AVX vector args, or structs by value, so the function-calling convention is more complicated.</p>
<hr />
<p><strong><a href="http://agner.org/optimize/" rel="nofollow noreferrer">Agner Fog has a calling conventions guide</a></strong> (covering Windows vs. Sys V, and the various conventions for 32-bit, and tips/tricks for writing functions you can use on either platform). This is a separate PDF from his optimization and microarchitecture guides and instruction tables (which are essential reading if you care about performance.)</p>
<p>Wikipedia has an <a href="https://en.wikipedia.org/wiki/X86_calling_conventions" rel="nofollow noreferrer">x86 calling conventions</a> article which describes various conventions, but mostly not in enough detail to use them for anything other than simple integer args. (e.g. no description of struct-packing rules).</p>
<hr />
<h2>Related: <em>C++</em> ABI</h2>
<p>GCC and Clang (on all architectures) use the C++ ABI originally developed for Itanium. <a href="https://itanium-cxx-abi.github.io/cxx-abi/" rel="nofollow noreferrer">https://itanium-cxx-abi.github.io/cxx-abi/</a>. This is relevant for example for what requirements a C++ struct/class need to be passed in registers (e.g. being an aggregate according to some definition), vs. when a struct/class always needs to have an address and get passed by reference, even when it's small enough to pack into 2 registers. These rules depend on stuff having a non-trivial constructor or destructor.</p> |
17,743,757 | How to concatenate strings in windows batch file for loop? | <p>I'm familiar with Unix shell scripting, but new to windows scripting. </p>
<p>I have a list of strings containing str1, str2, str3...str10. I want to do like this:</p>
<pre><code>for string in string_list
do
var = string+"xyz"
svn co var
end
</code></pre>
<p>I do found some thread describing how to concatenate string in batch file. But it somehow doesn't work in for loop. So I'm still confusing about the batch syntax.</p> | 17,745,392 | 3 | 1 | null | 2013-07-19 10:21:22.757 UTC | 10 | 2020-05-26 04:26:38.76 UTC | 2013-07-19 11:36:13.187 UTC | null | 1,324,345 | null | 2,288,882 | null | 1 | 62 | windows|batch-file | 289,751 | <p>In batch you could do it like this:</p>
<pre><code>@echo off
setlocal EnableDelayedExpansion
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do (
set "var=%%sxyz"
svn co "!var!"
)
</code></pre>
<p>If you don't need the variable <code>!var!</code> elsewhere in the loop, you could simplify that to</p>
<pre><code>@echo off
setlocal
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do svn co "%%sxyz"
</code></pre>
<p>However, like C.B. I'd prefer PowerShell if at all possible:</p>
<pre><code>$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object {
$var = "${_}xyz" # alternatively: $var = $_ + 'xyz'
svn co $var
}
</code></pre>
<p>Again, this could be simplified if you don't need <code>$var</code> elsewhere in the loop:</p>
<pre><code>$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }
</code></pre> |
22,966,578 | await Task.WhenAll() vs Task.WhenAll().Wait() | <p>I have a method that produces an array of tasks (<a href="https://stackoverflow.com/questions/22961890/c-sharp-how-to-wait-until-all-tasks-are-finished-before-running-code">See my previous post about threading</a>) and at the end of this method I have the following options:</p>
<pre><code>await Task.WhenAll(tasks); // done in a method marked with async
Task.WhenAll(tasks).Wait(); // done in any type of method
Task.WaitAll(tasks);
</code></pre>
<p>Basically I am wanting to know what the difference between the two <code>whenall</code>s are as the first one doesn't seem to wait until tasks are completed where as the second one does, but I'm not wanting to use the second one if it's not asynchronus.</p>
<p>I have included the third option as I understand that this will lock the current thread until all the tasks have completed processing (seemingly synchronously instead of asynchronus) - please correct me if I am wrong about this one</p>
<p>Example function with await:</p>
<pre><code>public async void RunSearchAsync()
{
_tasks = new List<Task>();
Task<List<SearchResult>> products = SearchProductsAsync(CoreCache.AllProducts);
Task<List<SearchResult>> brochures = SearchProductsAsync(CoreCache.AllBrochures);
_tasks.Add(products);
_tasks.Add(brochures);
await Task.WhenAll(_tasks.ToArray());
//code here hit before all _tasks completed but if I take off the async and change the above line to:
// Task.WhenAll(_tasks.ToArray()).Wait();
// code here hit after _tasks are completed
}
</code></pre> | 22,966,985 | 2 | 4 | null | 2014-04-09 15:02:11.927 UTC | 5 | 2022-03-08 01:16:08.297 UTC | 2017-09-18 08:55:01.847 UTC | null | 1,790,982 | null | 1,790,982 | null | 1 | 28 | multithreading|async-await|c#-5.0 | 24,353 | <p><code>await</code> will return to the caller, and resume method execution when the awaited task completes.</p>
<p><code>WhenAll</code> will <em>create</em> a task <strong>When All</strong> all the tasks are complete.</p>
<p><code>WaitAll</code> will block the creation thread (main thread) until all the tasks are complete.</p> |
2,062,875 | Show UTF-8 characters in console | <p>How can I print UTF8 characters in the console? </p>
<p>With <code>Console.Writeline("îăşâţ")</code> I see <code>îasât</code> in console.</p> | 2,062,917 | 5 | 0 | null | 2010-01-14 08:07:08.207 UTC | 1 | 2019-05-05 19:41:41.61 UTC | 2019-05-05 15:52:48.12 UTC | lutz | 6,186,333 | null | 119,749 | null | 1 | 37 | c# | 41,888 | <p>There are some hacks you can find that demonstrate how to write multibyte character sets to the Console, but they are unreliable. They require your console font to be one that supports it, and in general, are something I would avoid. (All of these techniques break if your user doesn't do extra work on their part... so they are not reliable.)</p>
<p>If you need to write Unicode output, I highly recommend making a GUI application to handle this, instead of using the Console. It's fairly easy to make a simple GUI to just write your output to a control which supports Unicode.</p> |
1,486,300 | Javascript type of custom object | <p>How can I check if my javascript object is of a certain type.</p>
<pre><code>var SomeObject = function() { }
var s1 = new SomeObject();
</code></pre>
<p>In the case above <code>typeof s1</code> will return "object". That's not very helpful. Is there some way to check if s1 is of type SomeObject ?</p> | 1,486,312 | 5 | 0 | null | 2009-09-28 10:12:19.027 UTC | 12 | 2019-04-04 17:40:51.67 UTC | null | null | null | null | 56,648 | null | 1 | 63 | javascript | 33,527 | <p>Yes, using <code>instanceof</code> (<a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/instanceof_Operator" rel="noreferrer">MDN link</a> | <a href="http://ecma-international.org/ecma-262/5.1/#sec-11.8.6" rel="noreferrer">spec link</a>):</p>
<pre><code>if (s1 instanceof SomeObject) { ... }
</code></pre> |
1,809,347 | How can I record a conversation / phone call on iOS? | <p>Is it theoretically possible to record a phone call on iPhone?</p>
<p>I'm accepting answers which:</p>
<ul>
<li>may or may not require the phone to be jailbroken</li>
<li>may or may not pass apple's guidelines due to use of private API's (I don't care; it is not for the App Store)</li>
<li>may or may not use private SDKs</li>
</ul>
<p>I don't want answers just bluntly saying "Apple does not allow that".
I know there would be no official way of doing it, and certainly not for an App Store application, and I know there are call recording apps which place outgoing calls through their own servers.</p> | 21,571,219 | 5 | 0 | null | 2009-11-27 15:25:00.087 UTC | 75 | 2016-01-13 21:36:03.4 UTC | 2016-01-13 21:36:03.4 UTC | null | 2,756,409 | null | 94,918 | null | 1 | 67 | ios|iphone|audio|audio-recording | 55,542 | <p>Here you go. Complete working example. Tweak should be loaded in <code>mediaserverd</code> daemon. It will record every phone call in <code>/var/mobile/Media/DCIM/result.m4a</code>. Audio file has two channels. Left is microphone, right is speaker. On iPhone 4S call is recorded only when the speaker is turned on. On iPhone 5, 5C and 5S call is recorded either way. There might be small hiccups when switching to/from speaker but recording will continue.</p>
<pre><code>#import <AudioToolbox/AudioToolbox.h>
#import <libkern/OSAtomic.h>
//CoreTelephony.framework
extern "C" CFStringRef const kCTCallStatusChangeNotification;
extern "C" CFStringRef const kCTCallStatus;
extern "C" id CTTelephonyCenterGetDefault();
extern "C" void CTTelephonyCenterAddObserver(id ct, void* observer, CFNotificationCallback callBack, CFStringRef name, void *object, CFNotificationSuspensionBehavior sb);
extern "C" int CTGetCurrentCallCount();
enum
{
kCTCallStatusActive = 1,
kCTCallStatusHeld = 2,
kCTCallStatusOutgoing = 3,
kCTCallStatusIncoming = 4,
kCTCallStatusHanged = 5
};
NSString* kMicFilePath = @"/var/mobile/Media/DCIM/mic.caf";
NSString* kSpeakerFilePath = @"/var/mobile/Media/DCIM/speaker.caf";
NSString* kResultFilePath = @"/var/mobile/Media/DCIM/result.m4a";
OSSpinLock phoneCallIsActiveLock = 0;
OSSpinLock speakerLock = 0;
OSSpinLock micLock = 0;
ExtAudioFileRef micFile = NULL;
ExtAudioFileRef speakerFile = NULL;
BOOL phoneCallIsActive = NO;
void Convert()
{
//File URLs
CFURLRef micUrl = CFURLCreateWithFileSystemPath(NULL, (CFStringRef)kMicFilePath, kCFURLPOSIXPathStyle, false);
CFURLRef speakerUrl = CFURLCreateWithFileSystemPath(NULL, (CFStringRef)kSpeakerFilePath, kCFURLPOSIXPathStyle, false);
CFURLRef mixUrl = CFURLCreateWithFileSystemPath(NULL, (CFStringRef)kResultFilePath, kCFURLPOSIXPathStyle, false);
ExtAudioFileRef micFile = NULL;
ExtAudioFileRef speakerFile = NULL;
ExtAudioFileRef mixFile = NULL;
//Opening input files (speaker and mic)
ExtAudioFileOpenURL(micUrl, &micFile);
ExtAudioFileOpenURL(speakerUrl, &speakerFile);
//Reading input file audio format (mono LPCM)
AudioStreamBasicDescription inputFormat, outputFormat;
UInt32 descSize = sizeof(inputFormat);
ExtAudioFileGetProperty(micFile, kExtAudioFileProperty_FileDataFormat, &descSize, &inputFormat);
int sampleSize = inputFormat.mBytesPerFrame;
//Filling input stream format for output file (stereo LPCM)
FillOutASBDForLPCM(inputFormat, inputFormat.mSampleRate, 2, inputFormat.mBitsPerChannel, inputFormat.mBitsPerChannel, true, false, false);
//Filling output file audio format (AAC)
memset(&outputFormat, 0, sizeof(outputFormat));
outputFormat.mFormatID = kAudioFormatMPEG4AAC;
outputFormat.mSampleRate = 8000;
outputFormat.mFormatFlags = kMPEG4Object_AAC_Main;
outputFormat.mChannelsPerFrame = 2;
//Opening output file
ExtAudioFileCreateWithURL(mixUrl, kAudioFileM4AType, &outputFormat, NULL, kAudioFileFlags_EraseFile, &mixFile);
ExtAudioFileSetProperty(mixFile, kExtAudioFileProperty_ClientDataFormat, sizeof(inputFormat), &inputFormat);
//Freeing URLs
CFRelease(micUrl);
CFRelease(speakerUrl);
CFRelease(mixUrl);
//Setting up audio buffers
int bufferSizeInSamples = 64 * 1024;
AudioBufferList micBuffer;
micBuffer.mNumberBuffers = 1;
micBuffer.mBuffers[0].mNumberChannels = 1;
micBuffer.mBuffers[0].mDataByteSize = sampleSize * bufferSizeInSamples;
micBuffer.mBuffers[0].mData = malloc(micBuffer.mBuffers[0].mDataByteSize);
AudioBufferList speakerBuffer;
speakerBuffer.mNumberBuffers = 1;
speakerBuffer.mBuffers[0].mNumberChannels = 1;
speakerBuffer.mBuffers[0].mDataByteSize = sampleSize * bufferSizeInSamples;
speakerBuffer.mBuffers[0].mData = malloc(speakerBuffer.mBuffers[0].mDataByteSize);
AudioBufferList mixBuffer;
mixBuffer.mNumberBuffers = 1;
mixBuffer.mBuffers[0].mNumberChannels = 2;
mixBuffer.mBuffers[0].mDataByteSize = sampleSize * bufferSizeInSamples * 2;
mixBuffer.mBuffers[0].mData = malloc(mixBuffer.mBuffers[0].mDataByteSize);
//Converting
while (true)
{
//Reading data from input files
UInt32 framesToRead = bufferSizeInSamples;
ExtAudioFileRead(micFile, &framesToRead, &micBuffer);
ExtAudioFileRead(speakerFile, &framesToRead, &speakerBuffer);
if (framesToRead == 0)
{
break;
}
//Building interleaved stereo buffer - left channel is mic, right - speaker
for (int i = 0; i < framesToRead; i++)
{
memcpy((char*)mixBuffer.mBuffers[0].mData + i * sampleSize * 2, (char*)micBuffer.mBuffers[0].mData + i * sampleSize, sampleSize);
memcpy((char*)mixBuffer.mBuffers[0].mData + i * sampleSize * 2 + sampleSize, (char*)speakerBuffer.mBuffers[0].mData + i * sampleSize, sampleSize);
}
//Writing to output file - LPCM will be converted to AAC
ExtAudioFileWrite(mixFile, framesToRead, &mixBuffer);
}
//Closing files
ExtAudioFileDispose(micFile);
ExtAudioFileDispose(speakerFile);
ExtAudioFileDispose(mixFile);
//Freeing audio buffers
free(micBuffer.mBuffers[0].mData);
free(speakerBuffer.mBuffers[0].mData);
free(mixBuffer.mBuffers[0].mData);
}
void Cleanup()
{
[[NSFileManager defaultManager] removeItemAtPath:kMicFilePath error:NULL];
[[NSFileManager defaultManager] removeItemAtPath:kSpeakerFilePath error:NULL];
}
void CoreTelephonyNotificationCallback(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
NSDictionary* data = (NSDictionary*)userInfo;
if ([(NSString*)name isEqualToString:(NSString*)kCTCallStatusChangeNotification])
{
int currentCallStatus = [data[(NSString*)kCTCallStatus] integerValue];
if (currentCallStatus == kCTCallStatusActive)
{
OSSpinLockLock(&phoneCallIsActiveLock);
phoneCallIsActive = YES;
OSSpinLockUnlock(&phoneCallIsActiveLock);
}
else if (currentCallStatus == kCTCallStatusHanged)
{
if (CTGetCurrentCallCount() > 0)
{
return;
}
OSSpinLockLock(&phoneCallIsActiveLock);
phoneCallIsActive = NO;
OSSpinLockUnlock(&phoneCallIsActiveLock);
//Closing mic file
OSSpinLockLock(&micLock);
if (micFile != NULL)
{
ExtAudioFileDispose(micFile);
}
micFile = NULL;
OSSpinLockUnlock(&micLock);
//Closing speaker file
OSSpinLockLock(&speakerLock);
if (speakerFile != NULL)
{
ExtAudioFileDispose(speakerFile);
}
speakerFile = NULL;
OSSpinLockUnlock(&speakerLock);
Convert();
Cleanup();
}
}
}
OSStatus(*AudioUnitProcess_orig)(AudioUnit unit, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inNumberFrames, AudioBufferList *ioData);
OSStatus AudioUnitProcess_hook(AudioUnit unit, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inNumberFrames, AudioBufferList *ioData)
{
OSSpinLockLock(&phoneCallIsActiveLock);
if (phoneCallIsActive == NO)
{
OSSpinLockUnlock(&phoneCallIsActiveLock);
return AudioUnitProcess_orig(unit, ioActionFlags, inTimeStamp, inNumberFrames, ioData);
}
OSSpinLockUnlock(&phoneCallIsActiveLock);
ExtAudioFileRef* currentFile = NULL;
OSSpinLock* currentLock = NULL;
AudioComponentDescription unitDescription = {0};
AudioComponentGetDescription(AudioComponentInstanceGetComponent(unit), &unitDescription);
//'agcc', 'mbdp' - iPhone 4S, iPhone 5
//'agc2', 'vrq2' - iPhone 5C, iPhone 5S
if (unitDescription.componentSubType == 'agcc' || unitDescription.componentSubType == 'agc2')
{
currentFile = &micFile;
currentLock = &micLock;
}
else if (unitDescription.componentSubType == 'mbdp' || unitDescription.componentSubType == 'vrq2')
{
currentFile = &speakerFile;
currentLock = &speakerLock;
}
if (currentFile != NULL)
{
OSSpinLockLock(currentLock);
//Opening file
if (*currentFile == NULL)
{
//Obtaining input audio format
AudioStreamBasicDescription desc;
UInt32 descSize = sizeof(desc);
AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &desc, &descSize);
//Opening audio file
CFURLRef url = CFURLCreateWithFileSystemPath(NULL, (CFStringRef)((currentFile == &micFile) ? kMicFilePath : kSpeakerFilePath), kCFURLPOSIXPathStyle, false);
ExtAudioFileRef audioFile = NULL;
OSStatus result = ExtAudioFileCreateWithURL(url, kAudioFileCAFType, &desc, NULL, kAudioFileFlags_EraseFile, &audioFile);
if (result != 0)
{
*currentFile = NULL;
}
else
{
*currentFile = audioFile;
//Writing audio format
ExtAudioFileSetProperty(*currentFile, kExtAudioFileProperty_ClientDataFormat, sizeof(desc), &desc);
}
CFRelease(url);
}
else
{
//Writing audio buffer
ExtAudioFileWrite(*currentFile, inNumberFrames, ioData);
}
OSSpinLockUnlock(currentLock);
}
return AudioUnitProcess_orig(unit, ioActionFlags, inTimeStamp, inNumberFrames, ioData);
}
__attribute__((constructor))
static void initialize()
{
CTTelephonyCenterAddObserver(CTTelephonyCenterGetDefault(), NULL, CoreTelephonyNotificationCallback, NULL, NULL, CFNotificationSuspensionBehaviorHold);
MSHookFunction(AudioUnitProcess, AudioUnitProcess_hook, &AudioUnitProcess_orig);
}
</code></pre>
<p>A few words about what's going on. <code>AudioUnitProcess</code> function is used for processing audio streams in order to apply some effects, mix, convert etc. We are hooking <code>AudioUnitProcess</code> in order to access phone call's audio streams. While phone call is active these streams are being processed in various ways.</p>
<p>We are listening for CoreTelephony notifications in order to get phone call status changes. When we receive audio samples we need to determine where they come from - microphone or speaker. This is done using <code>componentSubType</code> field in <code>AudioComponentDescription</code> structure. Now, you might think, why don't we store <code>AudioUnit</code> objects so that we don't need to check <code>componentSubType</code> every time. I did that but it will break everything when you switch speaker on/off on iPhone 5 because <code>AudioUnit</code> objects will change, they are recreated. So, now we open audio files (one for microphone and one for speaker) and write samples in them, simple as that. When phone call ends we will receive appropriate CoreTelephony notification and close the files. We have two separate files with audio from microphone and speaker that we need to merge. This is what <code>void Convert()</code> is for. It's pretty simple if you know the API. I don't think I need to explain it, comments are enough.</p>
<p>About locks. There are many threads in <code>mediaserverd</code>. Audio processing and CoreTelephony notifications are on different threads so we need some kind synchronization. I chose spin locks because they are fast and because the chance of lock contention is small in our case. On iPhone 4S and even iPhone 5 all the work in <code>AudioUnitProcess</code> should be done as fast as possible otherwise you will hear hiccups from device speaker which obviously not good.</p> |
2,000,831 | Compare time part of DateTime data type in SQL Server 2005 | <p>How can I compare only the time portion of a DateTime data type in SQL Server 2005? For example, I want to get all records in which MyDateField is after a specific time. The following example is a very long and probably not fast way of doing this.
I want all dates where MyDateField is greater than 12:30:50.400</p>
<pre><code>SELECT *
FROM Table1
WHERE ((DATEPART(hour, MyDateField) = 12) AND (DATEPART(minute, MyDateField) = 30) AND (DATEPART(second, MyDateField) = 50) AND (DATEPART(millisecond, MyDateField) > 400))
OR ((DATEPART(hour, MyDateField) = 12) AND (DATEPART(minute, MyDateField) = 30) AND (DATEPART(second, MyDateField) > 50))
OR ((DATEPART(hour, MyDateField) = 12) AND (DATEPART(minute, MyDateField) > 30))
OR ((DATEPART(hour, MyDateField) > 12))
</code></pre> | 2,005,553 | 6 | 4 | null | 2010-01-04 17:14:01.933 UTC | 3 | 2020-08-18 07:23:14.017 UTC | 2014-09-03 10:25:11.057 UTC | null | 2,707,432 | null | 195,417 | null | 1 | 10 | sql-server|sql-server-2005 | 43,480 | <pre><code>SELECT *
FROM Table1
WHERE DATEADD(day, -DATEDIFF(day, 0, MyDateField), MyDateField) > '12:30:50.400'
</code></pre> |
1,936,864 | What is the difference between <strong> and <em> tags? | <p>Both of them emphasize text. The <code><em></code> tag shows text as italics, whereas <code><strong></code> makes it bold. Is this the only difference?</p> | 1,936,910 | 6 | 0 | null | 2009-12-20 20:14:47.667 UTC | 6 | 2021-09-08 14:45:06.793 UTC | 2021-09-04 14:02:35.197 UTC | null | 10,247,460 | null | 84,201 | null | 1 | 54 | html|xhtml|semantics | 28,718 | <p>Yeah, the definition of what ‘strong emphasis’ is compared to just ‘emphasis’ is pretty woolly. The only <strong>standard definition</strong> would be “it's <em>emphasised</em>, but <em>more</em>!!”.</p>
<p>Personally I use <code><em></code> for normal emphasis where you'd read the emphasised word in a different tone of voice, and <code><strong></code> for that thing where you take <strong>key words and phrases</strong> to pick them out of the text to help people skimming the text pick out the subjects.</p>
<p>This isn't a standard interpretation, but it makes some sense and rendered appropriately by the default italic/bold styles. Whatever you do, <strong>be consistent</strong>.</p> |
1,517,220 | How to style unordered lists in CSS as comma separated text | <p>I’m looking for a way to style an unordered list in XHTML with CSS such that it is rendered inline and the list items are separated by commas.</p>
<p>For example, the following list should be rendered as <code>apple, orange, banana</code> (note the missing comma at the end of the list).</p>
<pre class="lang-html prettyprint-override"><code><ul id="taglist">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
</code></pre>
<p>Currently, I’m using the following CSS for styling this list, which almost does what I want, but renders the list as <code>apple, orange, banana,</code> (note the trailing comma after banana).</p>
<pre class="lang-css prettyprint-override"><code>#taglist {
display: inline;
list-style: none;
}
#taglist li {
display: inline;
}
#taglist li:after {
content: ", ";
}
</code></pre>
<p>Is there a way to solve this problem with pure CSS?</p> | 1,517,228 | 6 | 2 | null | 2009-10-04 19:49:03.157 UTC | 10 | 2016-07-13 14:06:09.083 UTC | 2014-08-14 19:32:45.62 UTC | null | 578,288 | null | 33,019 | null | 1 | 76 | html|css|xhtml | 36,478 | <p>To remove the trailing comma, use the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child" rel="noreferrer"><code>:last-child</code></a> pseudo-class, like so:</p>
<pre class="lang-css prettyprint-override"><code>#taglist li:last-child:after {
content: "";
}
</code></pre> |
1,790,431 | How do you estimate a ROI for clearing technical debt? | <p>I'm currently working with a fairly old product that's been saddled with a lot of technical debt from poor programmers and poor development practices in the past. We are starting to get better and the creation of technical debt has slowed considerably.</p>
<p>I've identified the areas of the application that are in bad shape and I can estimate the cost of fixing those areas, but I'm having a hard time estimating the return on investment (ROI). </p>
<p>The code will be easier to maintain and will be easier to extend in the future but how can I go about putting a dollar figure on these? </p>
<p>A good place to start looks like going back into our bug tracking system and estimating costs based on bugs and features relating to these "bad" areas. But that seems time consuming and may not be the best predictor of value.</p>
<p>Has anyone performed such an analysis in the past and have any advice for me?</p> | 1,790,499 | 7 | 0 | null | 2009-11-24 14:29:23.087 UTC | 12 | 2009-11-24 22:32:12.87 UTC | 2009-11-24 14:33:46.077 UTC | null | 126,039 | null | 175,976 | null | 1 | 18 | technical-debt|roi | 2,085 | <p>Managers care about making $ through growth (first and foremost e.g. new features which attract new customers) and (second) through optimizing the process lifecycle.</p>
<p>Looking at your problem, your proposal falls in the second category: this will undoubtedly fall behind goal #1 (and thus get prioritized down <strong>even</strong> if this could save money... because saving money <strong>implies</strong> spending money (most of time at least ;-)).</p>
<p><strong>Now</strong>, putting a $ figure on the "bad technical debt" could be turned around into a more positive spin (assuming that the following applies in your case): " if we invest in reworking component X, we could introduce feature Y faster and thus get Z more customers ".</p>
<p>In other words, <strong>evaluate the cost of technical debt against cost of lost business opportunities</strong>. </p> |
1,999,891 | How to reliably submit an HTML form with JavaScript? | <p>Is there a way to submit an HTML form using <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> that is guaranteed to work in all situations?</p>
<p>I elaborate. The common approach seems to be:</p>
<pre><code>formElement.submit()
</code></pre>
<p>That is all good and well except for one thing. Fields of a form are available as attributes of <code>formElement</code>, so if there is a field with <strong>name</strong> or <strong>id</strong> "text1", it can be accessed as <code>formElement.text1</code>.</p>
<p>This means that if an elements is called "submit" (be it its <strong>name</strong> or its <strong>id</strong>), then <code>formElement.submit()</code> will not work. This is because <code>formElement.submit</code> won't be a method of the form, but the field with that name. Unfortunately, it's fairly common that submit buttons have a "submit" name or id.</p>
<p>Two examples to illustrate my point. First, the following will NOT work, because an element of the form has name "submit":</p>
<pre><code><form name="example" id="example" action="/">
<button type="button" name="submit" onclick="document.example.submit(); return false;">Submit</button>
</form>
</code></pre>
<p>The following will work though. The only difference is that I have removed the name "submit" from the form:</p>
<pre><code><form name="example" id="example" action="/">
<button type="button" onclick="document.example.submit(); return false;">Submit</button>
</form>
</code></pre>
<p>So, is there any other way to submit an HTML form using JavaScript?</p> | 2,000,021 | 7 | 5 | null | 2010-01-04 14:35:30.107 UTC | 9 | 2016-07-07 06:29:00.447 UTC | 2010-01-04 15:12:38.503 UTC | null | 63,550 | null | 43,273 | null | 1 | 18 | javascript|html|forms | 13,797 | <p>Create another form in JavaScript, and apply its <code>submit()</code> method on your original form:</p>
<pre><code><html>
<script>
function hack() {
var form = document.createElement("form");
var myForm = document.example;
form.submit.apply(myForm);
}
</script>
<form name="example" id="example" method="get" action="">
<input type="hidden" value="43" name="hid">
<button
type="button"
name="submit"
onclick="hack();return false;"
>Submit</button>
</form>
</html>
</code></pre>
<p><code>form.submit</code> is the reference to a fresh and clean submit method, and then you use <code>apply(myForm)</code> to execute it with the original form.</p> |
1,895,206 | How can I launch the 'Add Contact' activity in android | <p>Can you please tell me how to launch the Add Contact' activity in android?
Thank you.</p> | 1,895,302 | 8 | 0 | null | 2009-12-13 00:42:23.52 UTC | 16 | 2015-05-19 03:22:32.23 UTC | null | null | null | null | 128,983 | null | 1 | 37 | android | 37,383 | <p><a href="https://stackoverflow.com/questions/866769/how-to-call-android-contacts-list">This</a> post may help you out or at least point you in the right direction.</p>
<p>Hope this helps.</p>
<h2>Update 05/11/2015:</h2>
<p>Per the comments, check out <a href="https://stackoverflow.com/a/11663568/166712">vickey's answer below</a> for the appropriate solution.</p> |
2,013,937 | What is an OS kernel ? How does it differ from an operating system? | <p>I am not able to understand the difference between a kernel and an operating system. I do not see any difference between them. Is the kernel an operating system?</p> | 2,014,207 | 11 | 0 | null | 2010-01-06 15:22:54.3 UTC | 68 | 2018-03-24 11:45:29 UTC | 2010-01-06 15:36:09.747 UTC | null | 1,450 | null | 138,604 | null | 1 | 156 | kernel|operating-system | 206,563 | <p>The technical definition of an operating system is "a platform that consists of specific set of libraries and infrastructure for applications to be built upon and interact with each other". A kernel is an operating system in that sense.</p>
<p>The end-user definition is usually something around "a software package that provides a desktop, shortcuts to applications, a web browser and a media player". A kernel doesn't match that definition.</p>
<p>So for an end-user a Linux distribution (say Ubuntu) is an Operating System while for a programmer the Linux kernel itself is a perfectly valid OS depending on what you're trying to achieve. For instance embedded systems are mostly just kernel with very small number of specialized processes running on top of them. In that case the kernel itself becomes the OS itself.</p>
<p>I think you can draw the line at what the majority of the applications running on top of that OS do require. If most of them require only kernel, the kernel is the OS, if most of them require X Window System running, then your OS becomes X + kernel. </p> |
1,389,180 | Automatically initialize instance variables? | <p>I have a python class that looks like this:</p>
<pre><code>class Process:
def __init__(self, PID, PPID, cmd, FDs, reachable, user):
</code></pre>
<p>followed by:</p>
<pre><code> self.PID=PID
self.PPID=PPID
self.cmd=cmd
...
</code></pre>
<p>Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.</p> | 1,389,216 | 16 | 1 | null | 2009-09-07 12:28:28.807 UTC | 71 | 2020-09-28 15:26:56.39 UTC | 2018-01-06 15:00:39.46 UTC | null | 100,297 | null | 51,197 | null | 1 | 116 | python|class|initialization-list | 48,942 | <p>You can use a decorator:</p>
<pre><code>from functools import wraps
import inspect
def initializer(func):
"""
Automatically assigns the parameters.
>>> class process:
... @initializer
... def __init__(self, cmd, reachable=False, user='root'):
... pass
>>> p = process('halt', True)
>>> p.cmd, p.reachable, p.user
('halt', True, 'root')
"""
names, varargs, keywords, defaults = inspect.getargspec(func)
@wraps(func)
def wrapper(self, *args, **kargs):
for name, arg in list(zip(names[1:], args)) + list(kargs.items()):
setattr(self, name, arg)
for name, default in zip(reversed(names), reversed(defaults)):
if not hasattr(self, name):
setattr(self, name, default)
func(self, *args, **kargs)
return wrapper
</code></pre>
<p>Use it to decorate the <code>__init__</code> method:</p>
<pre><code>class process:
@initializer
def __init__(self, PID, PPID, cmd, FDs, reachable, user):
pass
</code></pre>
<p>Output:</p>
<pre><code>>>> c = process(1, 2, 3, 4, 5, 6)
>>> c.PID
1
>>> dir(c)
['FDs', 'PID', 'PPID', '__doc__', '__init__', '__module__', 'cmd', 'reachable', 'user'
</code></pre> |
1,528,298 | Get path of executable | <p>I know this question has been asked before but I still haven't seen a satisfactory answer, or a definitive "no, this cannot be done", so I'll ask again!</p>
<p>All I want to do is get the path to the currently running executable, either as an absolute path or relative to where the executable is invoked from, in a platform-independent fashion. I though boost::filesystem::initial_path was the answer to my troubles but that seems to only handle the 'platform-independent' part of the question - it still returns the path from which the application was invoked.</p>
<p>For a bit of background, this is a game using Ogre, which I'm trying to profile using Very Sleepy, which runs the target executable from its own directory, so of course on load the game finds no configuration files etc. and promptly crashes. I want to be able to pass it an absolute path to the configuration files, which I know will always live alongside the executable. The same goes for debugging in Visual Studio - I'd like to be able to run $(TargetPath) without having to set the working directory.</p> | 1,528,493 | 25 | 11 | null | 2009-10-06 21:52:56.847 UTC | 51 | 2022-05-21 20:29:05.033 UTC | null | null | null | null | 40,834 | null | 1 | 160 | c++|boost|executable | 249,875 | <p>There is no cross platform way that I know.</p>
<p>For Linux: pass <code>"/proc/self/exe"</code> to <a href="https://en.cppreference.com/w/cpp/filesystem/canonical" rel="noreferrer"><code>std::filesystem::canonical</code></a> or <a href="https://linux.die.net/man/2/readlink" rel="noreferrer"><code>readlink</code></a>.</p>
<p>Windows: pass NULL as the module handle to <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms683197(v=vs.85).aspx" rel="noreferrer"><code>GetModuleFileName</code></a>.</p> |
1,383,598 | Core Data: Quickest way to delete all instances of an entity | <p>I'm using Core Data to locally persist results from a Web Services call. The web service returns the full object model for, let's say, "Cars" - could be about 2000 of them (and I can't make the Web Service return anything less than 1 or ALL cars.</p>
<p>The next time I open my application, I want to refresh the Core Data persisted copy by calling the Web Service for all Cars again, however to prevent duplicates I would need to purge all data in the local cache first.</p>
<p>Is there a quicker way to purge ALL instances of a specific entity in the managed object context (e.g. all entities of type "CAR"), or do I need to query them call, then iterate through the results to delete each, then save?</p>
<p>Ideally I could just say delete all where entity is Blah.</p> | 1,383,645 | 29 | 1 | null | 2009-09-05 15:29:52.107 UTC | 164 | 2022-09-01 12:31:07.333 UTC | 2017-11-06 05:01:07.91 UTC | null | 2,303,865 | null | 163,924 | null | 1 | 428 | ios|objective-c|core-data | 186,984 | <h2>iOS 9 and later:</h2>
<p>iOS 9 added a new class called <code>NSBatchDeleteRequest</code> that allows you to easily delete objects matching a predicate without having to load them all in to memory. Here's how you'd use it:</p>
<h3>Swift 5</h3>
<pre><code>let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Car")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try myPersistentStoreCoordinator.execute(deleteRequest, with: myContext)
} catch let error as NSError {
// TODO: handle the error
}
</code></pre>
<h3>Objective-C</h3>
<pre><code>NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Car"];
NSBatchDeleteRequest *delete = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];
NSError *deleteError = nil;
[myPersistentStoreCoordinator executeRequest:delete withContext:myContext error:&deleteError];
</code></pre>
<p>More information about batch deletions can be found in the <a href="https://developer.apple.com/videos/wwdc/2015/?id=220" rel="noreferrer">"What's New in Core Data" session from WWDC 2015</a> (starting at ~14:10).</p>
<h2>iOS 8 and earlier:</h2>
<p>Fetch 'em all and delete 'em all:</p>
<pre><code>NSFetchRequest *allCars = [[NSFetchRequest alloc] init];
[allCars setEntity:[NSEntityDescription entityForName:@"Car" inManagedObjectContext:myContext]];
[allCars setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *cars = [myContext executeFetchRequest:allCars error:&error];
[allCars release];
//error handling goes here
for (NSManagedObject *car in cars) {
[myContext deleteObject:car];
}
NSError *saveError = nil;
[myContext save:&saveError];
//more error handling here
</code></pre> |
33,664,820 | Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle | <p>i have tried it many times but its giving me same error.how to set the proxy so that this error is solved</p> | 54,035,809 | 17 | 4 | null | 2015-11-12 05:08:38.013 UTC | 7 | 2022-03-11 19:02:55.38 UTC | 2019-04-10 13:52:54.597 UTC | null | 6,296,561 | null | 4,980,791 | null | 1 | 24 | android|gradle|android-gradle-plugin|build.gradle | 144,491 | <p>Update your project level build.gradle to latest version - it works for me</p>
<pre><code>classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:4.2.0'
</code></pre> |
8,630,146 | How to get text and a variable in a messagebox | <p>I just need to know how to have plain text and a variable in a messagebox.</p>
<p>For example:</p>
<p>I can do this: <code>MsgBox(variable)</code></p>
<p>And I can do this: <code>MsgBox("Variable = ")</code></p>
<p>But I can't do this: <code>MsgBox("Variable = " + variable)</code></p> | 8,630,256 | 5 | 2 | null | 2011-12-25 15:06:54.91 UTC | 4 | 2020-11-11 18:00:32.183 UTC | null | null | null | null | 952,248 | null | 1 | 13 | vb.net|messagebox | 169,285 | <p>As has been suggested, using the string.format method is nice and simple and very readable.</p>
<p>In vb.net the " + " is used for addition and the " & " is used for string concatenation.</p>
<p>In your example:</p>
<pre><code>MsgBox("Variable = " + variable)
</code></pre>
<p>becomes:</p>
<pre><code>MsgBox("Variable = " & variable)
</code></pre>
<p>I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source <a href="http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx</a></p>
<p>maybe call</p>
<pre><code>variable.ToString()
</code></pre>
<p>update:</p>
<p>Use string interpolation (vs2015 onwards I believe):</p>
<pre><code>MsgBox($"Variable = {variable}")
</code></pre> |
8,608,311 | How to add buttons dynamically to my form? | <p>I want to create 10 buttons on my form when I click on button1. No error with this code below but it doesnt work either.</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
List<Button> buttons = new List<Button>();
for (int i = 0; i < buttons.Capacity; i++)
{
this.Controls.Add(buttons[i]);
}
}
</code></pre> | 8,608,328 | 8 | 2 | null | 2011-12-22 18:33:39.287 UTC | 8 | 2020-10-12 09:49:20.29 UTC | 2011-12-23 11:16:17.343 UTC | null | 366,904 | null | 993,962 | null | 1 | 20 | c#|winforms|button|dynamic | 135,820 | <p>It doesn't work because the list is empty. Try this:</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
List<Button> buttons = new List<Button>();
for (int i = 0; i < 10; i++)
{
Button newButton = new Button();
buttons.Add(newButton);
this.Controls.Add(newButton);
}
}
</code></pre> |
8,981,845 | Android: Rotate image in imageview by an angle | <p>I am using the following code to rotate a image in ImageView by an angle. Is there any simpler and less complex method available.</p>
<pre><code>ImageView iv = (ImageView)findViewById(imageviewid);
TextView tv = (TextView)findViewById(txtViewsid);
Matrix mat = new Matrix();
Bitmap bMap = BitmapFactory.decodeResource(getResources(),imageid);
mat.postRotate(Integer.parseInt(degree));===>angle to be rotated
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0,bMap.getWidth(),bMap.getHeight(), mat, true);
iv.setImageBitmap(bMapRotate);
</code></pre> | 10,104,318 | 26 | 2 | null | 2012-01-24 04:00:00.14 UTC | 62 | 2022-03-25 10:41:13.79 UTC | 2016-07-03 08:51:58.86 UTC | null | 6,343,685 | null | 1,163,071 | null | 1 | 180 | android|bitmap|rotation|imageview | 362,978 | <p>Another simple way to rotate an <code>ImageView</code>:<br>
<strong>UPDATE:</strong><br>
Required imports: </p>
<pre><code>import android.graphics.Matrix;
import android.widget.ImageView;
</code></pre>
<p>Code: (Assuming <code>imageView</code>, <code>angle</code>, <code>pivotX</code> & <code>pivotY</code> are already defined)</p>
<pre><code>Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) angle, pivotX, pivotY);
imageView.setImageMatrix(matrix);
</code></pre>
<p>This method does not require creating a new bitmap each time. </p>
<blockquote>
<p>NOTE: To rotate an <code>ImageView</code> on <em>ontouch</em> at runtime you can
set <em>onTouchListener</em> on <code>ImageView</code> & rotate it by adding last two
lines(i.e. <em>postRotate</em> matrix & set it on <em>imageView</em>) in above code
section in your touch listener <em>ACTION_MOVE</em> part.</p>
</blockquote> |
18,083,061 | Make element unclickable (click things behind it) | <p>I have a fixed image that overlays a page when the user is in the act of scrolling a touch screen (mobile).</p>
<p>I want to make that image "unclickable" or "inactive" or whatever, so that if a user touches and drags from that image, the page behind it still scrolls as if the image weren't there "blocking" the interaction.</p>
<p>Is this possible? If need be, I could try to provide screen shots exemplifying what I mean.</p>
<p>Thanks!</p> | 18,083,136 | 4 | 0 | null | 2013-08-06 14:30:42.833 UTC | 24 | 2022-08-23 14:39:45.287 UTC | null | null | null | null | 432,321 | null | 1 | 118 | html|css|mobile|scroll|touch | 131,147 | <p>Setting CSS - <code>pointer-events: none</code> should remove any mouse interaction with the image. Supported pretty well in all but IE.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events#Values">Here's a full list</a> of values <code>pointer-events</code> can take.</p> |
17,853,541 | Java - how to convert a XML string into an XML file? | <p>I am wanting to convert a xml string to a xml file. I am getting a xml string as an out put and I have the following code so far:</p>
<pre><code>public static void stringToDom(String xmlSource)
throws SAXException, ParserConfigurationException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));
//return builder.parse(new InputSource(new StringReader(xmlSource)));
}
</code></pre>
<p>However Im not too sure where I go from here. I am not creating the file anywhere, so how do I incorporate that into it?</p>
<p>I am passing my xml string into xmlSource.</p> | 17,853,621 | 4 | 0 | null | 2013-07-25 09:04:13.557 UTC | 3 | 2013-07-25 09:15:57.207 UTC | null | null | null | null | 1,704,082 | null | 1 | 10 | java|xml | 64,940 | <p>If you just want to put the content of a String in a file, it doesn't really matter whether it is actually XML or not. You can skip the parsing (which is a relatively expensive operation) and just dump the <code>String</code> to file, like so:</p>
<pre><code>public static void stringToDom(String xmlSource)
throws IOException {
java.io.FileWriter fw = new java.io.FileWriter("my-file.xml");
fw.write(xmlSource);
fw.close();
}
</code></pre>
<p>If you want to be on the safe side and circumvent encoding issues, as pointed by Joachim, you would need parsing however. Since its good practice to never trust your inputs, this might be the preferable way. It would look like this:</p>
<pre><code>public static void stringToDom(String xmlSource)
throws SAXException, ParserConfigurationException, IOException {
// Parse the given input
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));
// Write the parsed document to an xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("my-file.xml"));
transformer.transform(source, result);
}
</code></pre> |
18,033,260 | set background color: Android | <p>How Do I set the background color of my android app. When I try:</p>
<pre><code>LinearLayout li=(LinearLayout)findViewById(R.id.myLayout);
li.setBackgroundColor(Color.parseColor("#rrggbb"));
</code></pre>
<p>My app always crashes. Could someone help me out. Thanks</p> | 18,033,320 | 5 | 2 | null | 2013-08-03 13:16:44.57 UTC | 6 | 2021-12-19 10:42:53.747 UTC | 2013-08-03 13:18:56.533 UTC | null | 2,225,682 | null | 1,952,565 | null | 1 | 41 | java|android|colors|background | 129,446 | <blockquote>
<pre><code>Color.parseColor("#rrggbb")
</code></pre>
</blockquote>
<p>instead of <code>#rrggbb</code> you should be using hex values 0 to F for rr, gg and bb:</p>
<p>e.g. <code>Color.parseColor("#000000")</code> or <code>Color.parseColor("#FFFFFF")</code></p>
<p><a href="http://www.w3schools.com/html/html_colors.asp" rel="noreferrer">Source</a></p>
<p>From documentation:</p>
<blockquote>
<p>public static int parseColor (String colorString):</p>
<p>Parse the color string, and return the corresponding color-int. If the
string cannot be parsed, throws an IllegalArgumentException exception.
Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green',
'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray',
'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuschia',
'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'</p>
</blockquote>
<p>So I believe that if you are using <code>#rrggbb</code> you are getting <strong>IllegalArgumentException</strong> in your logcat</p>
<p><a href="http://developer.android.com/reference/android/graphics/Color.html#parseColor%28java.lang.String%29" rel="noreferrer">Source</a></p>
<p>Alternative:</p>
<pre><code>Color mColor = new Color();
mColor.red(redvalue);
mColor.green(greenvalue);
mColor.blue(bluevalue);
li.setBackgroundColor(mColor);
</code></pre>
<p><a href="https://stackoverflow.com/questions/15717977/android-i-have-error-with-exception-color-parsecolor">Source</a> </p> |
18,077,264 | Convert csv to xls/xlsx using Apache poi? | <p>I need to convert csv to xls/xlsx in my project? How can i do that? Can anyone post me some examples? I want to do it with Apache poi. I also need to create a cell from java side.</p> | 18,083,196 | 6 | 0 | null | 2013-08-06 10:13:36.5 UTC | 12 | 2018-10-18 14:09:13.837 UTC | null | null | null | null | 2,526,714 | null | 1 | 10 | spring|spring-mvc|apache-poi|xssf|poi-hssf | 47,538 | <p>You can try following method to create xlsx file using apache-poi. </p>
<pre><code>public static void csvToXLSX() {
try {
String csvFileAddress = "test.csv"; //csv file address
String xlsxFileAddress = "test.xlsx"; //xlsx file address
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int RowNum=0;
BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
XSSFRow currentRow=sheet.createRow(RowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileAddress);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage()+"Exception in try");
}
}
</code></pre> |
17,769,429 | Get input type=text to look like type=password | <h3>tl;dr</h3>
<p>I have an input with <code>type=text</code> which I want to show stars like an input with <code>type=password</code> using only CSS.</p>
<hr />
<p>Basically I have a form with the following input:</p>
<pre><code><input type='text' value='hello' id='cake' />
</code></pre>
<p>I'm not generating the form, I don't have access to its HTML at all. I do however have access to CSS applied to the page.</p>
<p>What I'd like is for it to behave like <code>type=password</code> , that is - to show up stars for what the user typed rather than the actual text being typed. Basically, I'd want that aspect (the presentation of user input) to look like a <code>type=password</code> field.</p>
<p>Since this seems like a presentation only issue, I figured there has to be a way to do this with CSS since it's in its responsibility domain. However - I have not found such a way. I have to support IE8+ but I'd rather have a solution that works for modern browsers only over no solution at all. Extra points for preventing copy/paste functionality but I can live without that.</p>
<p><strong>Note:</strong> In case that was not clear I can not add HTML or JavaScript to the page - only CSS.</p>
<hr />
<p>(Only thing I've found is <a href="https://stackoverflow.com/q/17151252/1348195">this question</a> but it's dealing with a jQuery related issue and it has a JavaScript solution)</p> | 17,769,519 | 10 | 3 | null | 2013-07-21 05:36:41.55 UTC | 8 | 2021-11-24 16:17:17.143 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,348,195 | null | 1 | 37 | html|css | 61,428 | <p>Well as @ThiefMaster suggested </p>
<pre><code>input.pw {
-webkit-text-security: disc;
}
</code></pre>
<p>However, this will work in browsers that are webkit descendants.. Opera, Chrome and Safari, but not much support for the rest, another solution to this is using webfonts.</p>
<p>Use any font editing utility like <a href="http://fontforge.org/" rel="noreferrer">FontForge</a> to create a font with all the characters to be <code>*</code> ( or any symbol you want ). Then use CSS web fonts to use them as a custom font.</p> |
18,084,104 | Accept only numbers and a dot in Java TextField | <p>I've got one textField where I only accept numbers from the keyboard, but now I have to change it as it's a "price textField" and I would also need to accept a dot "." for any kind of prices.</p>
<p>How can I change this in order to get what I need?</p>
<pre><code>ptoMinimoField = new JTextField();
ptoMinimoField.setBounds(348, 177, 167, 20);
contentPanel.add(ptoMinimoField);
ptoMinimoField.setColumns(10);
ptoMinimoField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (((caracter < '0') || (caracter > '9'))
&& (caracter != '\b')) {
e.consume();
}
}
});
</code></pre> | 18,084,146 | 14 | 1 | null | 2013-08-06 15:14:24.35 UTC | 2 | 2019-04-15 05:37:26.843 UTC | 2013-08-06 15:49:58.28 UTC | null | 714,968 | null | 2,620,440 | null | 1 | 9 | java|swing|filter|numbers|textfield | 102,590 | <p>As suggested by Oracle ,<a href="http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html" rel="noreferrer">Use Formatted Text Fields</a> </p>
<blockquote>
<p>Formatted text fields provide a way for developers to specify the valid set of characters that can be typed in a text field. </p>
</blockquote>
<pre><code>amountFormat = NumberFormat.getNumberInstance();
...
amountField = new JFormattedTextField(amountFormat);
amountField.setValue(new Double(amount));
amountField.setColumns(10);
amountField.addPropertyChangeListener("value", this);
</code></pre> |
44,671,737 | Incorrect value returned by IdentityHashMap - Why? | <p>To my understanding, the following code should print <code>false</code> as it is doing <code>identity</code> based comparison.</p>
<p>However, when I run the following code it is printing <code>true</code>: </p>
<pre><code>public class Test1 {
public static void main(String[] args) {
IdentityHashMap m = new IdentityHashMap();
m.put("A", new String("B"));
System.out.println(m.remove("A", new String("B")));
}
}
</code></pre>
<p>Can some one help me understand why this behaving like this?</p> | 44,672,015 | 2 | 7 | null | 2017-06-21 09:14:54.473 UTC | 1 | 2021-05-03 07:58:26.093 UTC | 2019-12-30 09:50:35.363 UTC | null | 3,848,411 | null | 3,848,411 | null | 1 | 33 | java|hashmap | 1,539 | <p>You have actually hit a bug in JDK, see <a href="https://bugs.openjdk.java.net/browse/JDK-8178355" rel="noreferrer">JDK-8178355</a>. <code>IdentityHashMap</code> does not have custom implementation of the <code>remove(K,V)</code> method added to <code>Map</code> via default method, which is causing this issue.</p> |
6,583,389 | Dynamically define named classes in Ruby | <p>I am writing an internal DSL in Ruby. For this, I need to programmatically create named classes and nested classes. What is the best way to do so? I recon that there are two ways to do so:</p>
<ol>
<li>Use <code>Class.new</code> to create an anonymous class, then use <code>define_method</code> to add methods to it, and finally call <code>const_set</code> to add them as named constants to some namespace.</li>
<li>Use some sort of <code>eval</code></li>
</ol>
<p>I've tested the first way and it worked, but being new to Ruby, I am not sure that putting classes as constants is the right way.</p>
<p>Are there other, better ways? If not, which of the above is preferable?</p> | 6,583,845 | 3 | 1 | null | 2011-07-05 13:26:13.897 UTC | 4 | 2014-06-24 04:21:45.567 UTC | null | null | null | null | 308,193 | null | 1 | 30 | ruby|metaprogramming|dsl|metaclass | 13,348 | <p>If you want to create a class with a dynamic name, you'll have to do almost exactly what you said. However, you do not need to use <code>define_method</code>. You can just pass a block to <code>Class.new</code> in which you initialize the class. This is semantically identical to the contents of <code>class</code>/<code>end</code>. </p>
<p>Remember with <code>const_set</code>, to be conscientious of the receiver (<code>self</code>) in that scope. If you want the class defined globally you will need to call <code>const_set</code> on the TopLevel module (which varies in name and detail by Ruby). </p>
<pre><code>a_new_class = Class.new(Object) do
attr_accessor :x
def initialize(x)
print #{self.class} initialized with #{x}"
@x = x
end
end
SomeModule.const_set("ClassName", a_new_class)
c = ClassName.new(10)
...
</code></pre> |
6,367,812 | Sticky Sessions and Session Replication | <p>I am evaluating the case of using sticky sessions with Session replication in tomcat. From my initial evaluation, I thought that if we enable Session replication, then session started in one tomcat node will be copied to all other tomcat nodes and thus we do not need sticky session to continue sessions and the request can be picked up by any node.</p>
<p>But it seems that session replication is in general used with sticky sessions, otherwise the session id needs to be changed whenever the request goes to some other node. ref: <a href="http://tomcat.apache.org/tomcat-6.0-doc/cluster-howto.html#Bind_session_after_crash_to_failover_node" rel="noreferrer">http://tomcat.apache.org/tomcat-6.0-doc/cluster-howto.html#Bind_session_after_crash_to_failover_node</a></p>
<p>Can anyone explain what is the real use of session replication if you have to enable sticky session? Because then you would be unnecessarily copying the session on each node, when the request with a given session id is always going to the same node. It could be beneficial in case of a node crashing, but then that does not happen frequently and using session replication only for that seems like an overkill.</p> | 6,392,308 | 3 | 2 | null | 2011-06-16 06:14:28.653 UTC | 23 | 2019-05-13 08:51:50.427 UTC | null | null | null | null | 275,264 | null | 1 | 31 | session|tomcat|session-replication | 39,903 | <p>I think the only real benefit is to be able to shut down Tomcat instances without much thinking. Especially this applies today in cloud world (think Amazon AWS spot instances) when nodes can go on and off really often. Alternative to this would be to buy a decent load balancer which supports node draining. But decent load balancers are expensive, and draining takes time.</p>
<p>Another scenario I can think of is a (poor implementation of) shopping cart where items are kept in the <code>HttpSession</code> and shutting down would require the user to re-purchase them (which would likely lead to a lost sale).</p>
<p>But in most cases you're right - benefit of having both sticky sessions and session replication is very negligible.</p> |
6,742,663 | Where does Qt Creator save its settings? | <p>I would like to locate the folder where Qt Creator saves all its settings (text editor preferences, syntax highlighting, etc.) so that I can back them up. Does anybody know where they are?</p> | 6,743,019 | 3 | 0 | null | 2011-07-19 05:31:05.77 UTC | 8 | 2021-03-18 19:52:14.153 UTC | 2021-03-18 19:52:14.153 UTC | null | 865,175 | null | 561,309 | null | 1 | 56 | qt|qt-creator | 55,632 | <p>See <a href="http://doc.qt.io/qtcreator/creator-quick-tour.html#location-of-settings-files" rel="noreferrer">QtCreator Quick Tour</a>.</p>
<blockquote>
<p>Qt Creator creates the following files and directories:</p>
<pre><code>QtCreator.db
QtCreator.ini
qtversion.xml
toolChains.xml
qtcreator
qtc-debugging-helper
qtc-qmldump
</code></pre>
<p>The location depends on the platform. On Linux and other Unix
platforms, the files are located in <code>~/.config/QtProject</code> and
<code>~/.local/share/data/QtProject/qtcreator</code>.</p>
<p>On Mac OS, the files are located in <code>~/.config/QtProject</code> and
<code>~/Library/Application Support/QtProject/Qt Creator</code>.</p>
</blockquote>
<p>On Windows in general, the files are located in <code>%APPDATA%\QtProject</code> and <code>%LOCALAPPDATA%\QtProject</code>. Yes, you can use these paths in Explorer and in various command line shells. The environment variables (between the <code>%</code>-signs) are expanded automatically. If you need the concrete paths, see below.</p>
<blockquote>
<p>On Windows 10, 8, Vista and 7, the files are located in
<code><drive>:\Users\<username>\AppData\Roaming\QtProject</code> and
<code><drive>:\Users\<username>\AppData\Local\QtProject</code>.</p>
<p>On Windows XP, the files are located in <code><drive>:\Documents and Settings\<username>\Application Data\QtProject</code> and <code><drive>:\Documents and Settings\<username>\Local Settings\Application Data\QtProject</code>.</p>
</blockquote> |
6,587,729 | How to use IntelliJ IDEA to find all unused code? | <p>When I am in a .java file the unused code is usually grayed out or has a green underline saying this code will probably (probably because of some weird JNI/Reflection corner cases) be unused. But I have this project with thousands of Java files and I want to find ALL INSTANCES of such probable-unused codes. How can I do that in IntelliJ IDEA?</p> | 6,587,932 | 3 | 5 | null | 2011-07-05 19:18:23.467 UTC | 58 | 2022-03-29 06:29:36.797 UTC | 2018-02-01 17:26:21.703 UTC | null | 47,281 | null | 471,136 | null | 1 | 389 | java|refactoring|intellij-idea|code-metrics|code-inspection | 177,923 | <p>Just use <code>Analyze | Inspect Code</code> with appropriate inspection enabled (<strong>Unused declaration</strong> under <strong>Declaration redundancy</strong> group).</p>
<p>Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"</p> |
6,825,550 | String or binary data would be truncated SQL Error | <p>I have a SQL stored procedure that accepts a parameter of type VARCHAR(MAX).
As far as I know and according to all I read about, the max size for such strings is 2GB:
<a href="http://msdn.microsoft.com/en-us/library/ms176089.aspx">MSDN</a></p>
<p>For some reason when passing a string larger than 8KB I get:</p>
<blockquote>
<p>String or binary data would be truncated.</p>
</blockquote>
<p>Why do I get this error message, and how can I resolve it?</p> | 12,690,873 | 4 | 4 | null | 2011-07-26 05:15:14.1 UTC | 2 | 2014-05-09 15:18:27.323 UTC | 2011-07-26 05:18:07.137 UTC | null | 354,803 | null | 342,534 | null | 1 | 9 | sql|tsql|varchar | 68,701 | <p>According to BoL (the link you specified) there is a difference in interpretation.
The maximum amount you can use in a query (the n part) is 8000. For storage purposes the varchar(max) can handle 2GB on disk. </p>
<p>It is just interpretation of datatypes for querying and storage purposes. So bottom line, you can only use 8000 chars in a query....</p> |
23,651,751 | java.lang.String cannot be cast to [Ljava.lang.Object; | <p>I want to call course name in combobox and print course Id which selected coursename How can I solve this problem? </p>
<pre><code> public void coursename(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query= session.createQuery("select a.courseName,a.courseId from Semester e inner join e.course as a");
for (Iterator it = query.iterate(); it.hasNext();) {
Object row[] = (Object[]) it.next();
combocourse.addItem(row[0]);
}
session.close();
}
private void combocourseActionPerformed(java.awt.event.ActionEvent evt) {
JComboBox combocourse = (JComboBox)evt.getSource();
Object row[] = (Object[])combocourse.getSelectedItem();
System.out.println("id"+row[1] );
}
</code></pre> | 23,651,815 | 3 | 3 | null | 2014-05-14 10:15:10.467 UTC | 1 | 2018-02-19 15:44:43.857 UTC | null | null | null | null | 3,627,624 | null | 1 | 5 | java|object|combobox | 63,957 | <p>By not trying to cast a <code>String</code> to an <code>Object[]</code>. Look at the return value of the methods you're using, and use variables typed appropriately to store those return values. <a href="http://docs.oracle.com/javase/8/docs/api/javax/swing/JComboBox.html#getSelectedItem--" rel="nofollow noreferrer"><code>JComboBox#getSelectedItem</code></a> returns an <code>Object</code> (in this case apparently a <code>String</code>), not an <em>array</em> (of any kind). But in this line:</p>
<pre><code>Object row[] = (Object[])combocourse.getSelectedItem();
</code></pre>
<p>...you're trying to cast it to be an <code>Object[]</code> (array of <code>Object</code>) so you can store it in an <code>Object[]</code>. You can't do that.</p>
<p>It seems like <code>row</code> should just be <code>Object</code> or <code>String</code>, not <code>Object[]</code>, and that when you use it you should just use it directly, not as <code>row[1]</code>:</p>
<pre><code>Object row = combocourse.getSelectedItem();
System.out.println("id"+row );
</code></pre>
<p>Or</p>
<pre><code>String row = (String)combocourse.getSelectedItem();
System.out.println("id"+row );
</code></pre>
<hr>
<p>In a comment you asked:</p>
<blockquote>
<p>I called coursename in combobox but i should save course id in my database. How can I get courseId?</p>
</blockquote>
<p>I don't know <code>JComboBox</code>. Fundamentally, you need to store something that contains both values (the ID and name) and then use that something when you get the selected item. Unless <code>JComboBox</code> has some functionality for this built in, you might need a simple class for that that holds the values and implements <code>toString</code> by returning <code>courseName</code>. Something vaguely like:</p>
<pre><code>class CourseItem {
private String courseName;
private String courseId; // Or int or whatever
CourseItem(String courseName,String courseId) {
this.courseName = courseName;
this.courseId = courseId;
}
public String getCourseName() {
return this.courseName;
}
public String getCourseId() {
return this.courseId;
}
public String toString() { // For display
return this.courseName;
}
}
</code></pre>
<p>Then:</p>
<pre><code>public void coursename() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("select a.courseName,a.courseId from Semester e inner join e.course as a");
for (Iterator it = query.iterate(); it.hasNext();) {
Object row[] = (Object[]) it.next();
combocourse.addItem(new CourseItem((String)row[0], (String)row[1]));
}
session.close();
}
private void combocourseActionPerformed(java.awt.event.ActionEvent evt) {
JComboBox combocourse = (JComboBox) evt.getSource();
CourseItem item = (CourseItem)combocourse.getSelectedItem();
System.out.println("id" + item.getCourseId());
}
</code></pre> |
18,962,890 | 2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why? | <p>Good evening friends:</p>
<p>I have in mind 2 ways for clearing a content in a defined range of cells of a VBA project (in MS Excel):</p>
<ol>
<li><code>Worksheets("SheetName").Range("A1:B10").ClearContents</code></li>
<li><code>Worksheets("SheetName").Range(Cells(1, 1), Cells(10, 2)).ClearContents</code></li>
</ol>
<p>The problem is that the second way show me an error '<a href="https://db.tt/AZgDruIM" rel="noreferrer">1004</a>' when I'm not watching the current Worksheet "SheetName" (in other words, when I haven't "SheetName" as ActiveSheet).</p>
<p>The first way work flawlessly in any situation.</p>
<p>Why does this happen? How can I use the "Second way" without this bug?</p> | 18,962,945 | 3 | 3 | null | 2013-09-23 15:15:12.45 UTC | 4 | 2018-02-02 20:54:36.507 UTC | 2018-07-09 18:41:45.953 UTC | null | -1 | null | 2,807,748 | null | 1 | 12 | excel|vba | 147,796 | <p>It is because you haven't qualified <code>Cells(1, 1)</code> with a worksheet object, and the same holds true for <code>Cells(10, 2)</code>. For the code to work, it should look something like this:</p>
<pre><code>Dim ws As Worksheet
Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
</code></pre>
<p>Alternately:</p>
<pre><code>With Sheets("SheetName")
Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
</code></pre>
<p><em>EDIT</em>: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify <code>Range</code> also, like so:</p>
<pre><code>ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
</code></pre>
<p>or</p>
<pre><code>With Sheets("SheetName")
.Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
</code></pre> |
35,328,652 | Angular pass callback function to child component as @Input similar to AngularJS way | <p>AngularJS has the & parameters where you could pass a callback to a directive (e.g <a href="https://stackoverflow.com/questions/31440366/pass-callback-function-to-directive">AngularJS way of callbacks</a>. Is it possible to pass a callback as an <code>@Input</code> for an Angular Component (something like below)? If not what would be the closest thing to what AngularJS does?</p>
<pre><code>@Component({
selector: 'suggestion-menu',
providers: [SuggestService],
template: `
<div (mousedown)="suggestionWasClicked(suggestion)">
</div>`,
changeDetection: ChangeDetectionStrategy.Default
})
export class SuggestionMenuComponent {
@Input() callback: Function;
suggestionWasClicked(clickedEntry: SomeModel): void {
this.callback(clickedEntry, this.query);
}
}
<suggestion-menu callback="insertSuggestion">
</suggestion-menu>
</code></pre> | 39,620,352 | 11 | 9 | null | 2016-02-11 00:25:24.983 UTC | 54 | 2022-03-04 18:49:39.437 UTC | 2019-07-19 10:31:03.253 UTC | null | 2,285,240 | null | 986,160 | null | 1 | 305 | angularjs|angular|typescript | 314,217 | <p>I think that is a bad solution. If you want to pass a Function into component with <code>@Input()</code>, <code>@Output()</code> decorator is what you are looking for.</p>
<pre><code>export class SuggestionMenuComponent {
@Output() onSuggest: EventEmitter<any> = new EventEmitter();
suggestionWasClicked(clickedEntry: SomeModel): void {
this.onSuggest.emit([clickedEntry, this.query]);
}
}
<suggestion-menu (onSuggest)="insertSuggestion($event[0],$event[1])">
</suggestion-menu>
</code></pre> |
27,483,881 | Perform push segue after an unwind segue | <p>I am working on a camera app where the camera views are shown modally. After I am done with cropping. I perform an unwind segue to the <code>MainPageViewController</code>. (Please see the screenshot)</p>
<p><img src="https://i.stack.imgur.com/Lnyzt.png" alt="storyboard" /></p>
<p>My unwind function inside <code>MainPageViewController</code> is as follows;</p>
<pre><code>@IBAction func unwindToMainMenu(segue: UIStoryboardSegue) {
self.performSegueWithIdentifier("Categories", sender: self)
}
</code></pre>
<p>where "categories" is the push segue identifier from <code>MainPageViewController</code> to <code>CategoriesTableViewController</code>.</p>
<p>The program enters the <code>unwindToMainMenu</code> function but it does not perform the push segue. Any idea how to fix this?</p>
<p>Note: I found the same <a href="https://stackoverflow.com/questions/21503886/performing-programmatic-segue-after-unwind">question</a> but the answer suggests to change the storyboard structure.</p> | 37,602,422 | 7 | 3 | null | 2014-12-15 12:15:21.503 UTC | 10 | 2020-04-07 03:21:31.32 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 4,228,647 | null | 1 | 38 | ios|xcode|swift|unwind-segue | 6,657 | <p>A bit late to the party but I found a way to do this without using state flags</p>
<p>Note: this only works with iOS 9+, as only custom segues support class names prior to iOS9 and you cannot declare an exit segue as a custom segue in storyboards</p>
<h2>1. Subclass UIStoryboardSegue with UIStoryboardSegueWithCompletion</h2>
<pre><code>class UIStoryboardSegueWithCompletion: UIStoryboardSegue {
var completion: (() -> Void)?
override func perform() {
super.perform()
if let completion = completion {
completion()
}
}
}
</code></pre>
<h2>2. Set UIStoryBoardSegueWithCompletion as the class for your exit segue</h2>
<p>note: the action for this segue should be <code>unwindToMainMenu</code> to match the original question</p>
<p><a href="https://i.stack.imgur.com/NlIcp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NlIcp.png" alt="Select exit segue from storyboard"></a>
<a href="https://i.stack.imgur.com/5EOo0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5EOo0.png" alt="Add custom class"></a></p>
<h2>3. Update your unwind @IBAction to execute the code in the completion handler</h2>
<pre><code>@IBAction func unwindToMainMenu(segue: UIStoryboardSegue) {
if let segue = segue as? UIStoryboardSegueWithCompletion {
segue.completion = {
self.performSegueWithIdentifier("Categories", sender: self)
}
}
}
</code></pre>
<p>Your code will now execute after the exit segue completes its transition</p> |
5,249,920 | Mockito to test void methods | <p>I have following code I want to test:</p>
<pre><code>public class MessageService {
private MessageDAO dao;
public void acceptFromOffice(Message message) {
message.setStatus(0);
dao.makePersistent(message);
message.setStatus(1);
dao.makePersistent(message);
}
public void setDao (MessageDAO mD) { this.dao = mD; }
}
public class Message {
private int status;
public int getStatus () { return status; }
public void setStatus (int s) { this.status = s; }
public boolean equals (Object o) { return status == ((Message) o).status; }
public int hashCode () { return status; }
}
</code></pre>
<p>I need to verify, that method acceptFromOffice really sets status to 0, than persist message, then chage its status to 1, and then persist it again.</p>
<p>With Mockito, I have tried to do following:</p>
<pre><code>@Test
public void testAcceptFromOffice () throws Exception {
MessageDAO messageDAO = mock(MessageDAO.class);
MessageService messageService = new MessageService();
messageService.setDao(messageDAO);
final Message message = spy(new Message());
messageService.acceptFromOffice(message);
verify(messageDAO).makePersistent(argThat(new BaseMatcher<Message>() {
public boolean matches (Object item) {
return ((Message) item).getStatus() == 0;
}
public void describeTo (Description description) { }
}));
verify(messageDAO).makePersistent(argThat(new BaseMatcher<Message>() {
public boolean matches (Object item) {
return ((Message) item).getStatus() == 1;
}
public void describeTo (Description description) { }
}));
}
</code></pre>
<p>I actually expect here that verification will verify calling twice of makePersistent method with a different Message object's state. But it fails saying that </p>
<blockquote>
<p>Argument(s) are different!</p>
</blockquote>
<p>Any clues?</p> | 5,250,533 | 2 | 1 | null | 2011-03-09 17:44:00.107 UTC | 7 | 2011-03-09 20:44:19.953 UTC | null | null | null | null | 59,692 | null | 1 | 21 | java|unit-testing|mockito | 89,736 | <p>Testing your code is not trivial, though not impossible. My first idea was to use <a href="http://mockito.googlecode.com/svn/tags/1.8.5/javadoc/org/mockito/ArgumentCaptor.html" rel="noreferrer">ArgumentCaptor</a>, which is much easier both to use and comprehend compared to <a href="http://mockito.googlecode.com/svn/tags/1.8.5/javadoc/org/mockito/ArgumentMatcher.html" rel="noreferrer">ArgumentMatcher</a>. Unfortunately the test still fails - reasons are certainly beyond the scope of this answer, but I may help if that interests you. Still I find this test case interesting enough to be shown (<strong>not correct solution</strong>):</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class MessageServiceTest {
@Mock
private MessageDAO messageDAO = mock(MessageDAO.class);
private MessageService messageService = new MessageService();
@Before
public void setup() {
messageService.setDao(messageDAO);
}
@Test
public void testAcceptFromOffice() throws Exception {
//given
final Message message = new Message();
//when
messageService.acceptFromOffice(message);
//then
ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
verify(messageDAO, times(2)).makePersistent(captor.capture());
final List<Message> params = captor.getAllValues();
assertThat(params).containsExactly(message, message);
assertThat(params.get(0).getStatus()).isEqualTo(0);
assertThat(params.get(1).getStatus()).isEqualTo(1);
}
}
</code></pre>
<p>Unfortunately the working solution requires somewhat complicated use of <a href="http://mockito.googlecode.com/svn/tags/1.8.5/javadoc/org/mockito/stubbing/Answer.html" rel="noreferrer">Answer</a>. In a nutshell, instead of letting Mockito to record and verify each invocation, you are providing sort of callback method that is executed every time your test code executes given mock. In this callback method (<code>MakePersistentCallback</code> object in our example) you have access both to parameters and you can alter return value. This is a heavy cannon and you should use it with care:</p>
<pre><code> @Test
public void testAcceptFromOffice2() throws Exception {
//given
final Message message = new Message();
doAnswer(new MakePersistentCallback()).when(messageDAO).makePersistent(message);
//when
messageService.acceptFromOffice(message);
//then
verify(messageDAO, times(2)).makePersistent(message);
}
private static class MakePersistentCallback implements Answer {
private int[] expectedStatuses = {0, 1};
private int invocationNo;
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
final Message actual = (Message)invocation.getArguments()[0];
assertThat(actual.getStatus()).isEqualTo(expectedStatuses[invocationNo++]);
return null;
}
}
</code></pre>
<p>The example is not complete, but now the test succeeds and, more importantly, fails when you change almost anything in CUT. As you can see <code>MakePersistentCallback.answer</code> method is called every time mocked <code>messageService.acceptFromOffice(message)</code> is called. Inside <code>naswer</code> you can perform all the verifications you want.</p>
<p>NB: Use with caution, maintaining such tests can be troublesome to say the least.</p> |
5,253,348 | Very Long If Statement in Python | <p>I have a very long if statement in Python. What is the best way to break it up into several lines? By best I mean most readable/common. </p> | 5,253,378 | 2 | 1 | null | 2011-03-09 22:58:34.197 UTC | 24 | 2018-07-13 08:04:48.133 UTC | null | null | null | null | 433,417 | null | 1 | 148 | python | 170,787 | <p>According to <a href="http://www.python.org/dev/peps/pep-0008/#maximum-line-length" rel="noreferrer">PEP8</a>, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break <em>after</em> boolean operators.</p>
<p>Further to this, if you're using a code style check such as <a href="http://pycodestyle.pycqa.org/en/latest/intro.html#error-codes" rel="noreferrer">pycodestyle</a>, the next logical line needs to have different indentation to your code block.</p>
<p>For example:</p>
<pre><code>if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
here_is_another_long_identifier != and_finally_another_long_name):
# ... your code here ...
pass
</code></pre> |
338,056 | ResourceDictionary in a separate assembly | <p>I have resource dictionary files (MenuTemplate.xaml, ButtonTemplate.xaml, etc) that I want to use in multiple separate applications. I could add them to the applications' assemblies, but it's better if I compile these resources in one single assembly and have my applications reference it, right? </p>
<p>After the resource assembly is built, how can I reference it in the App.xaml of my applications? Currently I use ResourceDictionary.MergedDictionaries to merge the individual dictionary files. If I have them in an assembly, how can I reference them in xaml?</p> | 338,546 | 7 | 1 | null | 2008-12-03 17:44:54.457 UTC | 90 | 2022-01-27 15:43:34.243 UTC | 2015-07-04 01:17:19.693 UTC | null | 591,656 | Gustavo Cavalcanti | 28,029 | null | 1 | 264 | .net|wpf|xaml|controltemplate|resourcedictionary | 149,718 | <p>Check out the <a href="http://msdn.microsoft.com/en-us/library/aa970069(VS.85).aspx" rel="noreferrer">pack URI syntax</a>. You want something like this:</p>
<pre><code><ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>
</code></pre> |
596,072 | detect window width and compensate for scrollbars - Javascript | <p>How do I detect the width of a user's window with Javascript and account for their scrollbar? (I need the width of the screen INSIDE of the scrollbar). Here's what I have...it seems to work in multiple browsers...except that it doesn't account for the scrollbars..</p>
<pre><code> function browserWidth() {
var myWidth = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
} else if( document.documentElement && document.documentElement.clientWidth ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
} else if( document.body && document.body.clientWidth ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
}
return myWidth;
}
</code></pre>
<p>any ideas? i need it to work in all browsers;)</p> | 596,120 | 7 | 1 | null | 2009-02-27 18:47:23.237 UTC | 6 | 2013-01-18 19:05:55.95 UTC | 2009-02-27 18:53:27.683 UTC | johnnietheblack | 54,408 | johnnietheblack | 54,408 | null | 1 | 18 | javascript|screen|width | 39,519 | <p>You will find the big summary of what properties are supported on what browsers <a href="http://www.quirksmode.org/dom/w3c_cssom.html" rel="noreferrer">on this page on quirksmode.org</a>. </p>
<p>Your best bet is probably to grab an element in the page (using document.body where supported, or document.getElementById or whatever), walk its offsetParent chain to find the topmost element, then examine that element's clientWidth and clientHeight.</p> |
192,723 | Is there somewhere I can search for available webservices? | <p>I'm wondering if there is a website that collects (and hopefully updates) information on available web services. </p>
<p>Edit: Thanks for all the info; many good answers. I can only accept 1 as the "accepted answer" at this time, so I picked my favorite one.</p> | 192,788 | 7 | 0 | null | 2008-10-10 19:21:57.467 UTC | 16 | 2017-03-27 10:31:32.327 UTC | 2015-11-07 16:02:24.89 UTC | RoBorg | 4,370,109 | avgbody | 8,737 | null | 1 | 21 | web-services|api|mashup | 11,107 | <p>How about <a href="http://www.programmableweb.com/apis" rel="noreferrer">http://www.programmableweb.com/apis</a>? It has a fairly large list of popular Web Services and a quick info sheet on each, including how to access it.</p> |
295,156 | ASP.NET Security Best Practices | <p>What are others ASP.NET Security Best Practices?</p>
<p>So far identified are listed here:</p>
<ul>
<li><p>Always generate new encryption keys and admin passwords whenever you are moving an application to production.</p></li>
<li><p>Never store passwords directly or in encrypted form. Always stored one way hashed passwords.</p></li>
<li><p>Always store connection strings in tag of Web.config and encrypt it in configuration section by using protected configuration providers (RSA or DPAPI). See <a href="http://msdn.microsoft.com/en-us/library/ms998372.aspx#pagpractices0001_conhowtoencryptsensitivedatainmachineconfigandwebconfig" rel="noreferrer">example here</a></p></li>
<li><p>Use user ID with least-privilege to connect to SQL server or the database you are using. E.g if you are only executing stored procedures from a certain module of application then you must create a user ID which has permissions to execute only.</p></li>
<li><p>Use <a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.principalpermission.aspx" rel="noreferrer">PrincipalPermission</a> if you want to use role-base security on pages.</p>
<pre>[PrincipalPermission(SecurityAction.Demand, Role="Admin")]
public class AdminOnlyPage : BasePageClass
{
// ...
}</pre></li>
<li><p>Always use parameters to prevent <a href="http://en.wikipedia.org/wiki/SQL_Injection" rel="noreferrer">SQL Injection</a> in the SQL queries.</p>
<ol>
<li>Consider installing URLScan on your IIS servers to protect against SQL Injection.
Also, for protecting against XSS attacks. You can use MSFT's AntiXSS library instead of the built to encode output instead of the built in HtmlEncode found in HttpServerUtility. </li>
</ol></li>
<li><p>Always keep on customErrors in web config to make you errors/exceptions private </p>
<p><customErrors mode="On" defaultRedirect="MyErrorPage.htm" /></p></li>
<li><p>In web applications, always validate the user's inputs for html tags or any scripts.</p></li>
<li><p>Never store sensitive information, like passwords in cookies.</p></li>
<li>Don't display system error messages, stack traces etc, in case of exception.</li>
</ul> | 295,526 | 7 | 1 | null | 2008-11-17 09:14:18.41 UTC | 27 | 2020-04-27 17:18:57.507 UTC | 2015-05-26 12:30:27.767 UTC | Ramesh Soni | 4,287,738 | Ramesh Soni | 191 | null | 1 | 28 | asp.net|security | 15,525 | <p>I found Microsoft's <a href="https://download.microsoft.com/documents/uk/msdn/security/The%20Developer%20Highway%20Code.pdf" rel="nofollow noreferrer">Developer Highway Code</a> to be a useful security checklist.</p> |
610,245 | Where and why do I have to put the "template" and "typename" keywords? | <p>In templates, where and why do I have to put <code>typename</code> and <code>template</code> on dependent names?<br>
What exactly are dependent names anyway? </p>
<p>I have the following code:</p>
<pre><code>template <typename T, typename Tail> // Tail will be a UnionNode too.
struct UnionNode : public Tail {
// ...
template<typename U> struct inUnion {
// Q: where to add typename/template here?
typedef Tail::inUnion<U> dummy;
};
template< > struct inUnion<T> {
};
};
template <typename T> // For the last node Tn.
struct UnionNode<T, void> {
// ...
template<typename U> struct inUnion {
char fail[ -2 + (sizeof(U)%2) ]; // Cannot be instantiated for any U
};
template< > struct inUnion<T> {
};
};
</code></pre>
<p>The problem I have is in the <code>typedef Tail::inUnion<U> dummy</code> line. I'm fairly certain that <code>inUnion</code> is a dependent name, and VC++ is quite right in choking on it.<br>
I also know that I should be able to add <code>template</code> somewhere to tell the compiler that inUnion is a template-id. But where exactly? And should it then assume that inUnion is a class template, i.e. <code>inUnion<U></code> names a type and not a function?</p> | 613,132 | 8 | 10 | null | 2009-03-04 11:56:16.583 UTC | 915 | 2021-05-15 00:40:58.07 UTC | 2020-04-16 08:06:28.07 UTC | null | 806,202 | MSalters | 15,416 | null | 1 | 1,309 | c++|templates|typename|c++-faq|dependent-name | 232,218 | <p>(See <a href="https://stackoverflow.com/a/17579889/4561887">here also for my C++11 answer</a>)</p>
<p>In order to parse a C++ program, the compiler needs to know whether certain names are types or not. The following example demonstrates that:</p>
<pre><code>t * f;
</code></pre>
<p>How should this be parsed? For many languages a compiler doesn't need to know the meaning of a name in order to parse and basically know what action a line of code does. In C++, the above however can yield vastly different interpretations depending on what <code>t</code> means. If it's a type, then it will be a declaration of a pointer <code>f</code>. However if it's not a type, it will be a multiplication. So the C++ Standard says at paragraph (3/7):</p>
<blockquote>
<p>Some names denote types or templates. In general, whenever a name is encountered it is necessary to determine whether that name denotes one of these entities before continuing to parse the program that contains it. The process that determines this is called name lookup.</p>
</blockquote>
<p>How will the compiler find out what a name <code>t::x</code> refers to, if <code>t</code> refers to a template type parameter? <code>x</code> could be a static int data member that could be multiplied or could equally well be a nested class or typedef that could yield to a declaration. <strong>If a name has this property - that it can't be looked up until the actual template arguments are known - then it's called a <em>dependent name</em> (it "depends" on the template parameters).</strong> </p>
<p>You might recommend to just wait till the user instantiates the template: </p>
<blockquote>
<p><em>Let's wait until the user instantiates the template, and then later find out the real meaning of <code>t::x * f;</code>.</em> </p>
</blockquote>
<p>This will work and actually is allowed by the Standard as a possible implementation approach. These compilers basically copy the template's text into an internal buffer, and only when an instantiation is needed, they parse the template and possibly detect errors in the definition. But instead of bothering the template's users (poor colleagues!) with errors made by a template's author, other implementations choose to check templates early on and give errors in the definition as soon as possible, before an instantiation even takes place. </p>
<p>So there has to be a way to tell the compiler that certain names are types and that certain names aren't. </p>
<h2>The "typename" keyword</h2>
<p>The answer is: <em>We</em> decide how the compiler should parse this. If <code>t::x</code> is a dependent name, then we need to prefix it by <code>typename</code> to tell the compiler to parse it in a certain way. The Standard says at (14.6/2):</p>
<blockquote>
<p>A name used in a template declaration or definition and that is dependent on a template-parameter is
assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified
by the keyword typename. </p>
</blockquote>
<p>There are many names for which <code>typename</code> is not necessary, because the compiler can, with the applicable name lookup in the template definition, figure out how to parse a construct itself - for example with <code>T *f;</code>, when <code>T</code> is a type template parameter. But for <code>t::x * f;</code> to be a declaration, it must be written as <code>typename t::x *f;</code>. If you omit the keyword and the name is taken to be a non-type, but when instantiation finds it denotes a type, the usual error messages are emitted by the compiler. Sometimes, the error consequently is given at definition time:</p>
<pre><code>// t::x is taken as non-type, but as an expression the following misses an
// operator between the two names or a semicolon separating them.
t::x f;
</code></pre>
<p><em>The syntax allows <code>typename</code> only before qualified names</em> - it is therefor taken as granted that unqualified names are always known to refer to types if they do so.</p>
<p>A similar gotcha exists for names that denote templates, as hinted at by the introductory text.</p>
<h2>The "template" keyword</h2>
<p>Remember the initial quote above and how the Standard requires special handling for templates as well? Let's take the following innocent-looking example: </p>
<pre><code>boost::function< int() > f;
</code></pre>
<p>It might look obvious to a human reader. Not so for the compiler. Imagine the following arbitrary definition of <code>boost::function</code> and <code>f</code>:</p>
<pre><code>namespace boost { int function = 0; }
int main() {
int f = 0;
boost::function< int() > f;
}
</code></pre>
<p>That's actually a valid <em>expression</em>! It uses the less-than operator to compare <code>boost::function</code> against zero (<code>int()</code>), and then uses the greater-than operator to compare the resulting <code>bool</code> against <code>f</code>. However as you might well know, <code>boost::function</code> <a href="http://www.boost.org/doc/libs/1_54_0/doc/html/function.html" rel="noreferrer">in real life</a> is a template, so the compiler knows (14.2/3):</p>
<blockquote>
<p>After name lookup (3.4) finds that a name is a template-name, if this name is followed by a <, the < is
always taken as the beginning of a template-argument-list and never as a name followed by the less-than
operator.</p>
</blockquote>
<p>Now we are back to the same problem as with <code>typename</code>. What if we can't know yet whether the name is a template when parsing the code? We will need to insert <code>template</code> immediately before the template name, as specified by <code>14.2/4</code>. This looks like:</p>
<pre><code>t::template f<int>(); // call a function template
</code></pre>
<p>Template names can not only occur after a <code>::</code> but also after a <code>-></code> or <code>.</code> in a class member access. You need to insert the keyword there too:</p>
<pre><code>this->template f<int>(); // call a function template
</code></pre>
<hr>
<h2>Dependencies</h2>
<p>For the people that have thick Standardese books on their shelf and that want to know what exactly I was talking about, I'll talk a bit about how this is specified in the Standard.</p>
<p>In template declarations some constructs have different meanings depending on what template arguments you use to instantiate the template: Expressions may have different types or values, variables may have different types or function calls might end up calling different functions. Such constructs are generally said to <em>depend</em> on template parameters.</p>
<p>The Standard defines precisely the rules by whether a construct is dependent or not. It separates them into logically different groups: One catches types, another catches expressions. Expressions may depend by their value and/or their type. So we have, with typical examples appended:</p>
<ul>
<li>Dependent types (e.g: a type template parameter <code>T</code>)</li>
<li>Value-dependent expressions (e.g: a non-type template parameter <code>N</code>)</li>
<li>Type-dependent expressions (e.g: a cast to a type template parameter <code>(T)0</code>)</li>
</ul>
<p>Most of the rules are intuitive and are built up recursively: For example, a type constructed as <code>T[N]</code> is a dependent type if <code>N</code> is a value-dependent expression or <code>T</code> is a dependent type. The details of this can be read in section <code>(14.6.2/1</code>) for dependent types, <code>(14.6.2.2)</code> for type-dependent expressions and <code>(14.6.2.3)</code> for value-dependent expressions. </p>
<h3>Dependent names</h3>
<p>The Standard is a bit unclear about what <em>exactly</em> is a <em>dependent name</em>. On a simple read (you know, the principle of least surprise), all it defines as a <em>dependent name</em> is the special case for function names below. But since clearly <code>T::x</code> also needs to be looked up in the instantiation context, it also needs to be a dependent name (fortunately, as of mid C++14 the committee has started to look into how to fix this confusing definition). </p>
<p>To avoid this problem, I have resorted to a simple interpretation of the Standard text. Of all the constructs that denote dependent types or expressions, a subset of them represent names. Those names are therefore "dependent names". A name can take different forms - the Standard says:</p>
<blockquote>
<p>A name is a use of an identifier (2.11), operator-function-id (13.5), conversion-function-id (12.3.2), or template-id (14.2) that denotes an entity or label (6.6.4, 6.1)</p>
</blockquote>
<p>An identifier is just a plain sequence of characters / digits, while the next two are the <code>operator +</code> and <code>operator type</code> form. The last form is <code>template-name <argument list></code>. All these are names, and by conventional use in the Standard, a name can also include qualifiers that say what namespace or class a name should be looked up in.</p>
<p>A value dependent expression <code>1 + N</code> is not a name, but <code>N</code> is. The subset of all dependent constructs that are names is called <em>dependent name</em>. Function names, however, may have different meaning in different instantiations of a template, but unfortunately are not caught by this general rule. </p>
<h3>Dependent function names</h3>
<p>Not primarily a concern of this article, but still worth mentioning: Function names are an exception that are handled separately. An identifier function name is dependent not by itself, but by the type dependent argument expressions used in a call. In the example <code>f((T)0)</code>, <code>f</code> is a dependent name. In the Standard, this is specified at <code>(14.6.2/1)</code>.</p>
<h2>Additional notes and examples</h2>
<p>In enough cases we need both of <code>typename</code> and <code>template</code>. Your code should look like the following</p>
<pre><code>template <typename T, typename Tail>
struct UnionNode : public Tail {
// ...
template<typename U> struct inUnion {
typedef typename Tail::template inUnion<U> dummy;
};
// ...
};
</code></pre>
<p>The keyword <code>template</code> doesn't always have to appear in the last part of a name. It can appear in the middle before a class name that's used as a scope, like in the following example</p>
<pre><code>typename t::template iterator<int>::value_type v;
</code></pre>
<p>In some cases, the keywords are forbidden, as detailed below</p>
<ul>
<li><p>On the name of a dependent base class you are not allowed to write <code>typename</code>. It's assumed that the name given is a class type name. This is true for both names in the base-class list and the constructor initializer list:</p>
<pre><code> template <typename T>
struct derive_from_Has_type : /* typename */ SomeBase<T>::type
{ };
</code></pre></li>
<li><p>In using-declarations it's not possible to use <code>template</code> after the last <code>::</code>, and the C++ committee <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#109" rel="noreferrer">said</a> not to work on a solution. </p>
<pre><code> template <typename T>
struct derive_from_Has_type : SomeBase<T> {
using SomeBase<T>::template type; // error
using typename SomeBase<T>::type; // typename *is* allowed
};
</code></pre></li>
</ul> |
315,804 | How to display my application's errors in JSF? | <p>In my JSF/Facelets app, here's a simplified version of part of my form:</p>
<pre><code><h:form id="myform">
<h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
<h:message class="error" for="newPassword1" />
<h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
<h:message class="error" for="newPassword2" />
<h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>
</code></pre>
<p>I'd like to be able to assign an error to a specific h:message tag based on something happening in the continueButton() method. Different errors need to be displayed for newPassword and newPassword2. A validator won't really work, because the method that will deliver results (from the DB) is run in the continueButton() method, and is too expensive to run twice. </p>
<p>I can't use the h:messages tag because the page has multiple places that I need to display different error messages. When I tried this, the page displayed duplicates of every message.</p>
<p>I tried this as a best guess, but no luck:</p>
<pre><code>public Navigation continueButton() {
...
expensiveMethod();
if(...) {
FacesContext.getCurrentInstance().addMessage("newPassword", new FacesMessage("Error: Your password is NOT strong enough."));
}
}
</code></pre>
<p>What am I missing? Any help would be appreciated!</p> | 319,036 | 8 | 0 | null | 2008-11-24 23:02:10.887 UTC | 29 | 2018-05-21 16:53:04.603 UTC | null | null | null | Eric Noob | 27,515 | null | 1 | 42 | jsf|error-handling|facelets | 162,581 | <p>In case anyone was curious, I was able to figure this out based on all of your responses combined!</p>
<p>This is in the Facelet:</p>
<pre><code><h:form id="myform">
<h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
<h:message class="error" for="newPassword1" id="newPassword1Error" />
<h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
<h:message class="error" for="newPassword2" id="newPassword2Error" />
<h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>
</code></pre>
<p>This is in the continueButton() method:</p>
<pre><code>FacesContext.getCurrentInstance().addMessage("myForm:newPassword1", new FacesMessage(PASSWORDS_DONT_MATCH, PASSWORDS_DONT_MATCH));
</code></pre>
<p>And it works! Thanks for the help!</p> |
1,051,090 | How can I control IE6+jQuery+jQuery-ui memory leaks? | <p>Here's a <a href="http://jsbin.com/omoya" rel="nofollow noreferrer">sample page</a> with a couple datepickers. Here's the Drip result for that:</p>
<p><a href="http://www.picvault.info/images/537090308_omoya.png" rel="nofollow noreferrer">alt text http://www.picvault.info/images/537090308_omoya.png</a></p>
<p>This page leaks indefinitely in IE6sp1 when I click the Refresh button repeatedly (IE6sp3+, Opera 9, Chrome2, and FF3+ seem to be good). The memory goes up and never goes down until I actually close the browser completely.</p>
<p>I've also tried using the latest nightly of jquery (r6414) and the latest stable UI (1.7.2) but it didn't make any difference. I've tried various things with no success (<a href="http://www.mail-archive.com/[email protected]/msg03851.html" rel="nofollow noreferrer">CollectGarbage</a>, <a href="http://groups.google.com/group/jquery-ui/browse_thread/thread/d0093cf0199e26b4/acd3cecae3f5b055?hl=en&lnk=gst&q=dialog+memory+leak#acd3cecae3f5b055" rel="nofollow noreferrer">AntiLeak</a>, others).</p>
<p>I'm looking for a solution other than "use a different browser!!1" as I don't have any control over that. Any help will be greatly appreciated!</p>
<p><strong>Update 1:</strong> I added that button event to a loop and this is what happens (the sudden drop off is when I terminate IE):
<img src="https://i.stack.imgur.com/6pmp5.png" alt="alt text"></p>
<p><strong>Update 2:</strong> I filed a <a href="http://dev.jqueryui.com/ticket/4644" rel="nofollow noreferrer">bug report</a> (fingers crossed).</p>
<p><strong>Update 3:</strong> This is also on the <a href="http://groups.google.com/group/jquery-dev/browse_thread/thread/861282378f94a37e" rel="nofollow noreferrer">mailing list</a>.</p>
<p><strong>Update 4:</strong> This (as reported on the mailing list) doesn't work, and in fact makes things worse:</p>
<pre><code>$(window).bind("unload", function() {
$('.hasDatepicker').datepicker('destroy');
$(window).unbind();
});
</code></pre>
<p>It's not enough to just call destroy. I'm still stranded with this one and getting very close to ripping jquery out of the project. I love it (I really do!) but if it's broken, I can't use it.</p>
<p><strong>Update 5:</strong> Starting the bounty, another 550 points to one helpful individual!</p>
<p><strong>Update 6:</strong> Some more testing has shown that this leak exists in IE6 and IE6sp1, but has been fixed in IE6sp2+. Now, about the answers I have so far...</p>
<p>So far all answers have been any one of these:</p>
<ol>
<li>Abandon IE6sp0/sp1 users or ignore
them</li>
<li>Debug jquery and fix the problem myself</li>
<li>I can't repro the problem.</li>
</ol>
<p>I know beggars can't be choosers, but those simply are not answers to my problem.</p>
<p>I cannot abandon my users. They make up 25% of the userbase. This is a custom app written for a customer, designed to work on IE6. <em>It is not an option to abandon IE6sp0/sp1.</em> It's not an option to tell my customers to just deal with it. It leaks so fast that after five minutes, some of the weaker machines are unusable.</p>
<p>Further, while I'd love to become a JS ninja so I can hunt down obscure memory leaks in jquery code (granted this is MS's fault, not jquery's), I don't see that happening either. </p>
<p>Finally, multiple people have reproduced the problem here and on the mailing list. If you can't repro it, you might have IE6SP2+, or you might not be refreshing enough.</p>
<p>Obviously this issue is very important to me (hence the 6 revisions, bounty, etc.) so I'm open to new ideas, but please keep in mind that none of those three suggestions will work for me.</p>
<p>Thanks to all for your consideration and insights. Please keep them coming!</p>
<p><strong>Update 7:</strong> The bounty has ended and Keith's answer was auto-accepted by SO. I'm sorry that only half the points were awarded (since I didn't select the answer myself), but I'm still really stuck so I think half is fair. </p>
<p>I am hopeful that the jquery/jquery-ui team can fix this problem but I'm afraid that I'll have to write this off as "impossible (for now)" and stop using some or all of jquery. Thanks to everyone for your help and consideration. If someone comes along with a real solution to my problem, please post and I'll figure out some way to reward you.</p> | 1,136,776 | 9 | 9 | 2009-07-16 16:45:40.147 UTC | 2009-06-26 20:21:36.863 UTC | 16 | 2015-06-19 20:37:07.097 UTC | 2015-06-19 20:37:07.097 UTC | null | 1,159,643 | null | 29 | null | 1 | 28 | javascript|jquery|jquery-ui|memory-leaks|internet-explorer-6 | 5,019 | <p>I hate to say this, your approach is correct and professional, but I'd be tempted to just leave it.</p>
<p>The consequences of not fixing this is that IE6 users will notice their machine getting slower and slower and ultimately either crashing completely or more likely crashing IE6.</p>
<p>So what?</p>
<p>Really - <em>why is this your problem?</em></p>
<p>Yours definitely won't be the only site they visit with this leak, and they will see IE6 crash regularly regardless of what you do, because that's what it does. </p>
<p>It's unlikely that anyone still on IE6 could even point out your application as one that leaks. </p>
<p>Finally when IE6 does crash it reports IE6 as the culprit - you can legitimately point out that this is a bug in IE6 that Microsoft have fixed in a new release.</p>
<p>Your expensive time is better spent on improving the application for the users not trapped in legacy hell - your app should basically work for IE6 users, but this sort of issue can suck away all of your time and not fix their problem. IE6 is still going to be an unsupported, crash ridden, security hole of a browser.</p>
<p>I suspect the jQuery devs take a similar view to me. Also you have to do some really ugly stuff to get round this bug in IE6, including hacky DOM work that stops the leak but is actually much slower.</p>
<hr>
<p><strong>Update</strong></p>
<p>Ok, this isn't an easy problem to fix - MS describe the IE6 bug (and provide advice on how to fix it) here: <a href="http://msdn.microsoft.com/en-us/library/bb250448(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb250448(VS.85).aspx</a></p>
<p>Basically this isn't a problem with javascript or jQuery - the actual issue is with the IE6 DOM - when HTML elements are added to the page (by javascript, rather than being in the page when it loads) IE can't garbage collect them unless they are created in a very specific way.</p>
<p>This is back to front from how jQuery UI builds elements (see DOM insertion order bug in the link above) and so this isn't something that either the jQuery devs or you can easily fix.</p>
<p>So how do you fix the issue? Well, you can stick with the legacy pop-up calendar for IE6 or you can write your own one. </p>
<p>I would recommend the former, but if you really want to built the latter there are some basic rules to follow:</p>
<ol>
<li><p>Always add elements top-down - for instance if you want to built a table add the <code><table></code> element into the page's DOM, then add <code><tr></code> then <code><td></code> and so on. This is back to front as it's much quicker to build the entire table and then add it to the DOM - unfortunately that's where IE6 loses track of it.</p></li>
<li><p>Only use CSS and HTML 3.2 attributes - sounds dumb, but IE6 creates extra objects to store the extra attributes (or 'expando' properties) and these also leak.</p></li>
<li><p>Kinda related to (2), but as @gradbot mentions IE6 has problems garbage collecting javascript variables - if they reference a DOM element inside an event fired from that element you can get problems. This is also compounded by javascript references to DOM elements that have 'expando' properties.</p></li>
</ol>
<p>If you have a look around online there may already be a drop-down DHTML calendar that sticks to these rules - it won't be as pretty, quick or configurable as the jQuery UI one, but I'm sure I've seen it done without leaking in IE6.</p>
<p>I think the best bet is to keep as much static as possible - for instance you could load the calendar grid (week numbers and day column headings) with the page and then dynamically load in the numbers (and nothing else). Create the day numbers as links, with javascript in the href - not best practice normally but far less likely to leak in IE6.</p> |
789,073 | Indenting #defines | <p>I know that <code>#define</code>s, etc. are normally never indented. Why?</p>
<p>I'm working in some code at the moment which has a horrible mixture of <code>#define</code>s, <code>#ifdef</code>s, <code>#else</code>s, <code>#endif</code>s, etc. All these often mixed in with normal C code. The non-indenting of the <code>#define</code>s makes them hard to read. And the mixture of indented code with non-indented <code>#define</code>s is a nightmare.</p>
<p>Why are <code>#define</code>s typically not indented? Is there a reason one wouldn't indent (e.g. like this code below)?</p>
<pre><code>#ifdef SDCC
#if DEBUGGING == 1
#if defined (pic18f2480)
#define FLASH_MEMORY_END 0x3DC0
#elif defined (pic18f2580)
#define FLASH_MEMORY_END 0x7DC0
#else
#error "Can't set up flash memory end!"
#endif
#else
#if defined (pic18f2480)
#define FLASH_MEMORY_END 0x4000
#elif defined (pic18f2580)
#define FLASH_MEMORY_END 0x8000
#else
#error "Can't set up flash memory end!"
#endif
#endif
#else
#if DEBUGGING == 1
#define FLASH_MEMORY_END 0x7DC0
#else
#define FLASH_MEMORY_END 0x8000
#endif
#endif
</code></pre> | 789,156 | 9 | 0 | null | 2009-04-25 14:56:29.51 UTC | 16 | 2021-10-29 19:43:44.653 UTC | 2021-10-29 19:43:44.653 UTC | null | 2,756,409 | null | 55,934 | null | 1 | 116 | c|c-preprocessor|indentation|code-formatting | 28,799 | <p>Pre-ANSI C preprocessor did not allow for space between the start of a line and the "#" character; the leading "#" had to always be placed in the first column.</p>
<p>Pre-ANSI C compilers are non-existent these days. Use which ever style (space before "#" or space between "#" and the identifier) you prefer.</p>
<p><a href="http://www.delorie.com/gnu/docs/gcc/cpp_48.html" rel="noreferrer">http://www.delorie.com/gnu/docs/gcc/cpp_48.html</a></p> |
1,269,648 | How do I close a single buffer (out of many) in Vim? | <p>I open several files in Vim by, for example, running</p>
<pre><code>vim a/*.php
</code></pre>
<p>which opens 23 files.</p>
<p>I then make my edit and run the following twice</p>
<pre><code>:q
</code></pre>
<p>which closes all my buffers.</p>
<p><strong>How can you close only one buffer in Vim?</strong></p> | 1,381,652 | 10 | 3 | null | 2009-08-13 01:59:04.61 UTC | 136 | 2021-02-20 04:54:24.58 UTC | 2011-08-18 12:31:11.663 UTC | null | 26,819 | null | 54,964 | null | 1 | 533 | vim|buffer | 286,982 | <p><strong>A word of caution: “the <code>w</code> in <code>bw</code> does not stand for write but for wipeout!”</strong></p>
<p>More from manuals:</p>
<p><strong><code>:bd</code></strong></p>
<blockquote>
<p>Unload buffer [N] (default: current
buffer) and delete it from
the buffer list. If the buffer was changed, this fails,
unless when [!] is specified, in which case changes are
lost.
The file remains unaffected.</p>
</blockquote>
<p><strong>If you know what you’re doing, you can also use <code>:bw</code></strong></p>
<p><strong><code>:bw</code></strong></p>
<blockquote>
<p>Like |:bdelete|, but really delete the
buffer.</p>
</blockquote> |
995,906 | Not enough storage is available to process this command in VisualStudio 2008 | <p>When I try to compile an assembly in VS 2008, I got (occasionally, usually after 2-3 hours of work with the project) the following error</p>
<pre><code>Metadata file '[name].dll' could not be opened --
'Not enough storage is available to process this command.
</code></pre>
<p>Usually to get rid of that I need to restart Visual Studio</p>
<p>The assembly I need to use in my project is BIG enough (> 70 Mb) and probably this is the reason of that bug, I've never seen some thing like this in my previous projects. Ok, if this is the reason my question is why this happens and what I need to do to stop it.</p>
<p>I have enough of free memory on my drives and 2Gb RAM (only ~1.2 Gb are utilized when exception happens)</p>
<p>I googled for the answers to the questions like this.</p>
<p>Suggestions usually related to:</p>
<blockquote>
<ol>
<li>to the number of user handlers that is limited in WinXP...</li>
<li>to the physical limit of memory available per process</li>
</ol>
</blockquote>
<p>I don't think either could explain my case</p>
<p>For user handlers and other GUI resources - I don't think this could be a problem. The big 70Mb assembly is actually a GUI-less code that operates with sockets and implements parsers of a proprietary protocols. In my current project I have only 3 GUI forms, with total number of GUI controls < 100.</p>
<p>I suppose my case is closer to the fact that in Windows XP the process address space is limited with 2 GB memory (and, taking into account memory segmentation, it is possible that I don't have a free segment large enough to allocate a memory). </p>
<p>However, it is hard to believe that segmentation could be so big after just 2-3 hours of working with the project in Visual Studio. Task Manager shows that VS consumes about 400-500 Mb (OM + VM). During compilation, VS need to load only meta-data. </p>
<p>Well, there are a lot of classes and interfaces in that library, but still I would expect that 1-2 Mb is more then enough to allocate <strong>metadata</strong> that is used by compiler to find all public classes and interfaces (though it is only my suggestion, I don't know what exactly happens inside <code>CLR</code> when it loads assembly metadata).</p>
<p>In addition, I would say that entire assembly size is so big only because it is <code>C++ CLI</code> library that has other um-managed libraries statically linked into one <code>DLL</code>. I estimated (using Reflector) that .NET (managed) code is approx 5-10% of this assembly.</p>
<p>Any ideas how to define the real reason of that bug? Are there any restrictions or recommendations as to .NET assembly size? (<em>Yes I know that it worth thinking of refactoring and splitting a big assembly into several smaller pieces, but it is a 3rd party component, and I can't rebuilt it</em>)</p> | 1,701,123 | 10 | 4 | null | 2009-06-15 12:44:56.247 UTC | 14 | 2016-09-06 21:24:34.227 UTC | 2015-11-23 07:41:16.537 UTC | null | 2,263,683 | null | 123,070 | null | 1 | 37 | c#|visual-studio|visual-studio-2008|memory-leaks|metadata | 58,460 | <p>In my case the following fix helped:
<a href="https://web.archive.org/web/20130203074733/http://confluence.jetbrains.com/display/ReSharper/OutOfMemoryException+Fix" rel="nofollow noreferrer">http://confluence.jetbrains.net/display/ReSharper/OutOfMemoryException+Fix</a></p> |
717,012 | How can a developer learn about web design? | <p>Most of the time I worked as an application developer at backend side. I worked on enterprise web projects but never touched on user interface, design issues.
Good looking web sites and user interfaces always impress me. </p>
<p>And nowadays I am trying to develop public web site I know CSS, HTML but stuck with web design / user interface issues. I don't want to use a template or steal someone's web design. </p>
<p>How can a developer / programmer learn to design good web sites / user interfaces, What tools should I use and learn? or is desinging good web user interfaces a god's gift?</p> | 717,180 | 10 | 2 | null | 2009-04-04 12:50:04.773 UTC | 43 | 2018-02-14 09:35:54.63 UTC | null | null | null | mcaaltuntas | 36,474 | null | 1 | 41 | language-agnostic | 9,497 | <p>Looks like you hit on a hot topic. As a web/graphic designer myself, I think the best way to improve your ability in that regard is to look at a lot of good designs; meaning, actively seek them out.</p>
<p>As pixeline says, there's not a lot of objective knowledge to be learned (though there is <i>some</i>). It's more about improving your aesthetic eye. If you look at high quality designs all the time, then your tastes will become more refined and your web designs will naturally conform to your acclimated aesthetics.</p>
<p>For instance, I work at an indie metal label, so from time to time I'm called upon to work on band sites, album designs, magazine ads, sticker/clothing/merch designs, etc. So I'm always flipping through metal magazines and looking at ads designed by other people, or admiring the merch designs of other bands, or checking out the sites of other labels.</p>
<p>This not only serves as a source of inspiration when I'm stuck, helps me to gauge my own abilities and find areas for improvement, but it also helps me track the ever-changing trends and fashions in my particular sphere of design. As we all know, fashion is fickle, and people's tastes are always changing. A good designer knows how to stay just ahead of the curve all the time. This means that your designs don't deviate too drastically from accepted aesthetics (otherwise your designs will be rejected by audiences), but you also don't want to employ design elements that are overused and played out.</p>
<p>If you can ride the knife's edge and innovate enough to stand out, but not so much that the audience is unable to accept it, then you will have mastered the art of web design. A good designer can identify emerging trends and capitalize on them, while making it their own by adding their own twist to it.</p>
<p>If you're just starting to venture into web/graphic design, don't be afraid to emulate others and steal good ideas. Don't plagiarize, and give credit where credit is due, but just as making copies of famous drawings/paintings is an essential training technique in figure drawing & painting, so too is emulating quality designs an effective tool in learning graphic design.</p>
<p>Sites like <a href="http://bestwebgallery.com/" rel="noreferrer">Best Web Gallery</a> and <a href="http://www.screenalicious.com/" rel="noreferrer">Screenalicious</a> are excellent places to immerse oneself in quality designs and layouts. I would highly recommend scanning through these sites in your free time to flood your mind with examples of good aesthetics.</p>
<p>EDIT: I also want to emphasize that talent is not as much of a factor as most people would think. More often, <b>interest</b> is what people confuse as "talent." If you truly have an interest in something, you will be motivated to immerse yourself in it and practice it. This in turn leads to better ability, and if started at a young age builds confidence, which leads to an ability gap, which leads to more confidence and more interest, which in turn leads to more practice...</p>
<p>I consider myself a decent graphic designer (you can check out my portfolio via my profile link) and an alright artist. And people often comment on how talented I am, but they don't realize that I have literally spent thousands of hours honing my craft. While other kids were out playing with their friends, I was in my room drawing. That's the only reason I excelled in drawing. And when I first started building websites, they looked just as hideous as most teenagers' Myspace pages. So don't get discouraged when you see the work of "talented" designers. They all started from humble beginnings as well.</p> |
97,948 | What is std::pair? | <p>What is <code>std::pair</code> for, why would I use it, and what benefits does <code>boost::compressed_pair</code> bring?</p> | 98,022 | 10 | 0 | null | 2008-09-18 23:19:38.017 UTC | 18 | 2019-01-04 08:37:54.987 UTC | 2012-05-02 21:01:31.42 UTC | Ash | 298,479 | Anthony | 18,352 | null | 1 | 44 | c++|boost|stl|std-pair | 42,549 | <p><a href="http://en.cppreference.com/w/cpp/utility/pair" rel="nofollow noreferrer"><code>std::pair</code></a> is a data type for grouping two values together as a single object. <a href="http://en.cppreference.com/w/cpp/container/map" rel="nofollow noreferrer"><code>std::map</code></a> uses it for key, value pairs.</p>
<p>While you're learning <a href="http://en.cppreference.com/w/cpp/utility/pair" rel="nofollow noreferrer"><code>pair</code></a>, you might check out <a href="http://en.cppreference.com/w/cpp/utility/tuple" rel="nofollow noreferrer"><code>tuple</code></a>. It's like <code>pair</code> but for grouping an arbitrary number of values. <code>tuple</code> is part of TR1 and many compilers already include it with their Standard Library implementations.</p>
<p>Also, checkout Chapter 1, "Tuples," of the book <em>The C++ Standard Library Extensions: A Tutorial and Reference</em> by Pete Becker, ISBN-13: 9780321412997, for a thorough explanation.</p>
<p><img src="https://i.stack.imgur.com/M82nG.gif" alt="alt text"></p> |
498,371 | How to detect if my application is running in a virtual machine? | <p>How can I detect (.NET or Win32) if my application is running in a virtual machine?</p> | 498,394 | 11 | 3 | null | 2009-01-31 06:01:42.677 UTC | 22 | 2022-09-14 21:59:36.81 UTC | null | null | null | Jason | 16,794 | null | 1 | 45 | .net|winapi|virtualization | 58,616 | <p>According to <a href="http://blogs.msdn.com/virtual_pc_guy/" rel="noreferrer">Virtual PC Guy</a>'s blog post "<a href="http://blogs.msdn.com/virtual_pc_guy/archive/2005/10/27/484479.aspx" rel="noreferrer">Detecting Microsoft virtual machines</a>", you can use WMI to check the manufacturer of the motherboard. In PowerShell:</p>
<pre><code> (gwmi Win32_BaseBoard).Manufacturer -eq "Microsoft Corporation"
</code></pre> |
255,797 | uses for state machines | <p>In what areas of programming would I use state machines ? Why ? How could I implement one ?</p>
<p><strong>EDIT:</strong> please provide a practical example , if it's not too much to ask .</p> | 256,011 | 18 | 6 | null | 2008-11-01 17:27:00.003 UTC | 37 | 2012-12-05 01:27:08.467 UTC | 2012-12-05 01:27:08.467 UTC | Charade | 105,971 | Charade | 31,610 | null | 1 | 67 | state-machine | 30,874 | <h2>In what areas of programming would I use a state machine?</h2>
<p>Use a state machine to represent a (real or logical) object that can exist in a limited number of conditions ("<em>states</em>") and progresses from one state to the next according to a fixed set of rules.</p>
<h2>Why would I use a state machine?</h2>
<p>A state machine is often a <em>very</em> compact way to represent a set of complex rules and conditions, and to process various inputs. You'll see state machines in embedded devices that have limited memory. Implemented well, a state machine is self-documenting because each logical state represents a physical condition. A state machine can be embodied in a <em>tiny</em> amount of code in comparison to its procedural equivalent and runs extremely efficiently. Moreover, the rules that govern state changes can often be stored as data in a table, providing a compact representation that can be easily maintained.</p>
<h2>How can I implement one?</h2>
<p>Trivial example:</p>
<pre><code>enum states { // Define the states in the state machine.
NO_PIZZA, // Exit state machine.
COUNT_PEOPLE, // Ask user for # of people.
COUNT_SLICES, // Ask user for # slices.
SERVE_PIZZA, // Validate and serve.
EAT_PIZZA // Task is complete.
} STATE;
STATE state = COUNT_PEOPLE;
int nPeople, nSlices, nSlicesPerPerson;
// Serve slices of pizza to people, so that each person gets
/// the same number of slices.
while (state != NO_PIZZA) {
switch (state) {
case COUNT_PEOPLE:
if (promptForPeople(&nPeople)) // If input is valid..
state = COUNT_SLICES; // .. go to next state..
break; // .. else remain in this state.
case COUNT_SLICES:
if (promptForSlices(&nSlices))
state = SERVE_PIZZA;
break;
case SERVE_PIZZA:
if (nSlices % nPeople != 0) // Can't divide the pizza evenly.
{
getMorePizzaOrFriends(); // Do something about it.
state = COUNT_PEOPLE; // Start over.
}
else
{
nSlicesPerPerson = nSlices/nPeople;
state = EAT_PIZZA;
}
break;
case EAT_PIZZA:
// etc...
state = NO_PIZZA; // Exit the state machine.
break;
} // switch
} // while
</code></pre>
<p></p>
<p><strong>Notes:</strong></p>
<ul>
<li><p>The example uses a <code>switch()</code> with explicit <code>case</code>/<code>break</code> states for simplicity. In practice, a <code>case</code> will often "fall through" to the next state.</p></li>
<li><p>For ease of maintaining a large state machine, the work done in each <code>case</code> can be encapsulated in a "worker" function. Get any input at the top of the <code>while()</code>, pass it to the worker function, and check the return value of the worker to compute the next state.</p></li>
<li><p>For compactness, the entire <code>switch()</code> can be replaced with an array of function pointers. Each state is embodied by a function whose return value is a pointer to the next state. <em>Warning:</em> This can either simplify the state machine or render it totally unmaintainable, so consider the implementation carefully!</p></li>
<li><p>An embedded device may be implemented as a state machine that exits only on a catastrophic error, after which it performs a hard reset and re-enters the state machine.</p></li>
</ul> |
1,176,352 | PDO Prepared Inserts multiple rows in single query | <p>I am currently using this type of SQL on MySQL to insert multiple rows of values in one single query:</p>
<pre><code>INSERT INTO `tbl` (`key1`,`key2`) VALUES ('r1v1','r1v2'),('r2v1','r2v2'),...
</code></pre>
<p>On the readings on PDO, the use prepared statements should give me a better security than static queries.</p>
<p>I would therefore like to know whether it is possible to generate "inserting multiple rows of values by the use of one query" using prepared statements. </p>
<p>If yes, may I know how can I implement it?</p> | 2,098,689 | 21 | 1 | null | 2009-07-24 08:11:03.273 UTC | 85 | 2021-02-06 16:12:10.17 UTC | 2015-04-28 06:53:18.927 UTC | user1244033 | null | null | 142,514 | null | 1 | 166 | php|pdo|insert|prepared-statement | 194,949 | <p><strong>Multiple Values Insert with PDO Prepared Statements</strong></p>
<p>Inserting multiple values in one execute statement. Why because according to <a href="http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html" rel="noreferrer">this page</a> it is faster than regular inserts.</p>
<pre><code>$datafields = array('fielda', 'fieldb', ... );
$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);
$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);
</code></pre>
<p>more data values or you probably have a loop that populates data.</p>
<p>With prepared inserts you need to know the fields you're inserting to, and the number of fields to create the ? placeholders to bind your parameters.</p>
<pre><code>insert into table (fielda, fieldb, ... ) values (?,?...), (?,?...)....
</code></pre>
<p>That is basically how we want the insert statement to look like.</p>
<p>Now, the code:</p>
<pre><code>function placeholders($text, $count=0, $separator=","){
$result = array();
if($count > 0){
for($x=0; $x<$count; $x++){
$result[] = $text;
}
}
return implode($separator, $result);
}
$pdo->beginTransaction(); // also helps speed up your inserts.
$insert_values = array();
foreach($data as $d){
$question_marks[] = '(' . placeholders('?', sizeof($d)) . ')';
$insert_values = array_merge($insert_values, array_values($d));
}
$sql = "INSERT INTO table (" . implode(",", $datafields ) . ") VALUES " .
implode(',', $question_marks);
$stmt = $pdo->prepare ($sql);
$stmt->execute($insert_values);
$pdo->commit();
</code></pre>
<p>Although in my test, there was only a 1 sec difference when using multiple inserts and regular prepared inserts with single value.</p> |
720,807 | WCF, Service attribute value in the ServiceHost directive could not be found | <p>I'm trying to host my service with IIS 6 but I keep get this exception.</p>
<pre><code> Server Error in '/WebServices' Application.
--------------------------------------------------------------------------------
The type 'QS.DialogManager.Communication.IISHost.RecipientService', provided as the Service attribute value in the ServiceHost directive could not be found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The type 'QS.DialogManager.Communication.IISHost.RecipientService', provided as the Service attribute value in the ServiceHost directive could not be found.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The type 'QS.DialogManager.Communication.IISHost.RecipientService', provided as the Service attribute value in the ServiceHost directive could not be found.]
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +6714599
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath) +604
System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +46
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +654
[ServiceActivationException: The service '/WebServices/dm/RecipientService.svc' cannot be activated due to an exception during compilation. The exception message is: The type 'QS.DialogManager.Communication.IISHost.RecipientService', provided as the Service attribute value in the ServiceHost directive could not be found..]
System.ServiceModel.AsyncResult.End(IAsyncResult result) +15626880
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +15546921
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, Boolean flowContext) +265
System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +227
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082
</code></pre>
<p>I have absolutely no clue except that it seems like it can't find my assemblies. The code should be correctly compiled with public classes.</p>
<p>Here is my .svc file:</p>
<pre><code><%@ ServiceHost Language="C#" Debug="true" Service="QS.DialogManager.Communication.IISHost.RecipientService" CodeBehind="RecipientService.svc.cs" %>
</code></pre>
<p>I have tried to create a very very simple service that contains just nothin too see if this would work but still the same old error shows up.</p>
<pre><code>The type 'IISHost.Service1', provided as the Service attribute value in the ServiceHost directive could not be found.
</code></pre> | 720,829 | 22 | 6 | null | 2009-04-06 09:39:52.997 UTC | 14 | 2020-03-06 11:20:42.87 UTC | 2009-04-06 11:07:26.373 UTC | null | 79,792 | null | 79,792 | null | 1 | 77 | c#|wcf|iis | 196,738 | <p><strong>Option One</strong>:</p>
<p>This message is often due to an IIS 7 config problem. If you are used to creating a virtual directory pointing to the folder where your service resides, that no longer works. Now, you need to use the "Create Application..." option instead.</p>
<p><strong>Other Options</strong>:</p>
<ul>
<li><a href="http://www.thejoyofcode.com/WCF_The_type_provided_as_the_Service_attribute_could_not_be_found.aspx" rel="noreferrer">WCF: The type provided as the Service attribute could not be found</a> </li>
<li><a href="http://dennyonline.wordpress.com/2008/02/26/the-type-service-provided-as-the-service-attribute-value-in-the-servicehost-directive-could-not-be-found/" rel="noreferrer">The type , provided as the Service attribute value in the ServiceHost directive could not be found.</a></li>
</ul> |
6,893,165 | How to get Exception Error Code in C# | <pre><code>try
{
object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{
// Here I was hoping to get an error code.
}
</code></pre>
<p>When I invoke the above WMI method I am expected to get Access Denied. In my catch block I want to make sure that the exception raised was indeed for Access Denied. Is there a way I can get the error code for it ? Win32 error code for Acceess Denied is 5.
I dont want to search the error message for denied string or anything like that. </p>
<p>Thanks</p> | 6,893,197 | 5 | 4 | null | 2011-08-01 00:00:50.513 UTC | 7 | 2021-03-31 09:20:18.313 UTC | 2014-06-14 02:23:55.233 UTC | null | 832,390 | null | 258,956 | null | 1 | 33 | c#|exception | 181,882 | <p>You can use this to check the exception and the inner exception for a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.win32exception.aspx" rel="noreferrer">Win32Exception derived exception.</a></p>
<pre><code>catch (Exception e) {
var w32ex = e as Win32Exception;
if(w32ex == null) {
w32ex = e.InnerException as Win32Exception;
}
if(w32ex != null) {
int code = w32ex.ErrorCode;
// do stuff
}
// do other stuff
}
</code></pre>
<p>Starting with C# 6, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/when" rel="noreferrer">when</a> can be used in a catch statement to specify a condition that must be true for the handler for a specific exception to execute.</p>
<pre><code>catch (Win32Exception ex) when (ex.InnerException is Win32Exception) {
var w32ex = (Win32Exception)ex.InnerException;
var code = w32ex.ErrorCode;
}
</code></pre>
<p>As in the comments, you really need to see what exception is actually being thrown to understand what you can do, and in which case a specific catch is preferred over just catching Exception. Something like:</p>
<pre><code> catch (BlahBlahException ex) {
// do stuff
}
</code></pre>
<p>Also <a href="http://msdn.microsoft.com/en-us/library/system.exception.hresult.aspx" rel="noreferrer">System.Exception has a HRESULT</a></p>
<pre><code> catch (Exception ex) {
var code = ex.HResult;
}
</code></pre>
<p>However, it's only available from .NET 4.5 upwards.</p> |
6,819,314 | Why use data URI scheme? | <p>Basically the question is in the title.</p>
<p>Many people have had the question stackoverflow of how to create a data URI and problems therein.</p>
<p>My question is <em>why use data URI?</em></p>
<p>What are the advantages to doing:</p>
<pre><code><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
</code></pre>
<p>Over doing:</p>
<pre><code><img src="dot.png" alt="Red dot" />
</code></pre>
<p>I understand one has less overhead on the server side (maybe), but what are the <strong>real</strong> advantages/disadvantages to using <em>data URI</em>?</p> | 6,819,412 | 5 | 3 | null | 2011-07-25 16:29:28.487 UTC | 22 | 2020-02-15 22:24:19.077 UTC | 2011-07-25 16:35:03.48 UTC | null | 561,731 | null | 561,731 | null | 1 | 51 | html|browser|client|data-uri | 21,269 | <p>According to <a href="http://en.wikipedia.org/wiki/Data_URI_scheme#Advantages" rel="noreferrer">Wikipedia</a>:</p>
<p>Advantages:</p>
<ul>
<li><p>HTTP request and header traffic is not required for embedded data, so
data URIs consume less bandwidth whenever the overhead of encoding
the inline content as a data URI is smaller than the HTTP overhead.
For example, the required base64 encoding for an image 600 bytes long
would be 800 bytes, so if an HTTP request required more than 200
bytes of overhead, the data URI would be more efficient.</p></li>
<li><p>For transferring many small files (less than a few kilobytes each), this can be faster. TCP transfers tend to start slowly. If each file requires a new TCP connection, the transfer speed is limited by the round-trip time rather than the available bandwidth. Using HTTP keep-alive improves the situation, but may not entirely alleviate the bottleneck.</p></li>
<li><p>When browsing a secure HTTPS web site, web browsers commonly require that all elements of a web page be downloaded over secure connections, or the user will be notified of reduced security due to a mixture of secure and insecure elements. On badly configured servers, HTTPS requests have significant overhead over common HTTP requests, so embedding data in data URIs may improve speed in this case.</p></li>
<li><p>Web browsers are usually configured to make only a certain number
(often two) of concurrent HTTP connections to a domain, so inline
data frees up a download connection for other content.</p></li>
<li><p>Environments with limited or restricted access to external resources
may embed content when it is disallowed or impractical to reference
it externally. For example, an advanced HTML editing field could
accept a pasted or inserted image and convert it to a data URI to
hide the complexity of external resources from the user.
Alternatively, a browser can convert (encode) image based data from
the clipboard to a data URI and paste it in a HTML editing field.
Mozilla Firefox 4 supports this functionality.</p></li>
<li><p>It is possible to manage a multimedia page as a single file. Email
message templates can contain images (for backgrounds or signatures)
without the image appearing to be an "attachment".</p></li>
</ul>
<p>Disadvantages:</p>
<ul>
<li><p>Data URIs are not separately cached from their containing documents
(e.g. CSS or HTML files) so data is downloaded every time the
containing documents are redownloaded. Content must be re-encoded and
re-embedded every time a change is made.</p></li>
<li><p>Internet Explorer through version 7 (approximately 15% of the market as of January 2011), lacks support. However this can be overcome by serving browser specific content.
Internet Explorer 8 limits data URIs to a maximum length of 32 KB.</p></li>
<li><p>Data is included as a simple stream, and many processing environments (such as web browsers) may not support using containers (such as multipart/alternative or message/rfc822) to provide greater complexity such as metadata, data compression, or content negotiation.</p></li>
<li><p>Base64-encoded data URIs are 1/3 larger in size than their binary
equivalent. (However, this overhead is reduced to 2-3% if the HTTP
server compresses the response using gzip) Data URIs make it more
difficult for security software to filter content.</p></li>
</ul>
<p>According to <a href="http://www.mobify.com/blog/data-uris-are-slow-on-mobile/" rel="noreferrer">other sources</a>
- Data URLs are significantly slower on mobile browsers.</p> |
6,492,074 | Why does TextView in single line elipsized with "end" show boxes? | <p>I'm using a TextView in Android, what I want to show 1 line in TextView ending with ". " but this give [] type box at the end. I don't know why? I just want to remvoe this box and only to show text ending with "... "</p>
<p><img src="https://i.stack.imgur.com/yIS2u.png" alt="TextView shown box at end"></p>
<p>Update code for the list_row.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:orientation="horizontal"
android:gravity="center_vertical"
android:cacheColorHint="#4C7B8D"
android:background="#4C7B8D">
<ImageView
android:id="@+id/videoListImage"
android:src="@drawable/audio_thumbnail60x60"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:scaleType="fitXY"
android:layout_width="75dp"
android:padding="4dp"
android:background="@color/light_gray" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginRight="5dp"
android:layout_toLeftOf="@+id/next_arrow"
android:orientation="vertical"
android:gravity="center_vertical"
android:paddingLeft = "5dp">
<TextView
android:id="@+id/row_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="@color/app_background_color"
android:textSize="18sp"
android:ellipsize="end"
android:maxLines="1" />
<TextView
android:id="@+id/row_dis"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="@color/color_black"
android:layout_marginRight="2dp"
android:textSize="15sp"
android:ellipsize="end"
android:maxLines="1" />
<TextView
android:text="$7.50"
android:id="@+id/audio_price_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textColor="@color/color_white"
android:textStyle = "bold"
android:paddingLeft = "12dp"
android:paddingRight = "12dp"
android:background="@drawable/blue_round_cornor_background" />
</LinearLayout>
<ImageView
android:id="@+id/next_arrow"
android:src="@drawable/next_arrow"
android:layout_toLeftOf="@+id/saved_purchased"
android:scaleType="fitXY"
android:layout_height="25dp"
android:layout_width="18dp"
android:layout_centerVertical="true"
android:visibility = "gone"/>
<ImageView
android:id="@+id/saved_purchased"
android:layout_alignParentRight="true"
android:layout_alignParentTop ="true"
android:scaleType="fitXY"
android:layout_height="25dp"
android:layout_width="25dp"
android:layout_marginRight="2dp"/>
</RelativeLayout>
</code></pre>
<p></p>
<p>Here is the images of "next_arrow"
<img src="https://i.stack.imgur.com/Qc6KR.png" alt="enter image description here"></p>
<p>Here is the code I am using the getView() in adapter. </p>
<pre><code> String discription = listData.getDescription();
if (discription != null && discription.length() > 0) {
if (textViewDis != null) {
textViewDis.setTypeface(titleFont);
Log.e("data", ""+discription);
discription.replaceAll("\r\n", "");
textViewDis.setText(discription);
}
}
</code></pre>
<p>Here is the actual String of description to be display. </p>
<blockquote>
<p>Andrew and Stephanie Tidwell candidly share their success story in this business. This story will help everyone listening realize that no one is perfect, even in a second generation business. This is a streaming audio file. </p>
</blockquote>
<p>Still have some issue? I can update question more.</p> | 6,492,931 | 6 | 3 | null | 2011-06-27 11:22:06.353 UTC | 12 | 2013-08-30 15:03:24.33 UTC | 2012-02-21 07:09:01.013 UTC | null | 92,837 | null | 486,139 | null | 1 | 19 | android|android-layout|android-widget | 15,709 | <p>Quoting myself from <a href="http://commonsware.com/Android" rel="noreferrer">one of my books</a>:</p>
<blockquote>
<p>Android's TextView class has the built-in ability to "ellipsize" text,
truncating it and adding an ellipsis if the text is longer than the available
space. You can use this via the android:ellipsize attribute, for example.
This works fairly well, at least for single-line text.
The ellipsis that Android uses is not three periods. Rather it uses an actual
ellipsis character, where the three dots are contained in a single glyph.
Hence, any font that you use that you also use the "ellipsizing" feature will
need the ellipsis glyph.</p>
<p>Beyond that, though, Android pads out the string that gets rendered on-screen, such that the length (in characters) is the same before and after
"ellipsizing". To make this work, Android replaces one character with the
ellipsis, and replaces all other removed characters with the Unicode
character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF). This means the
"extra" characters after the ellipsis do not take up any visible space on
screen, yet they can be part of the string.</p>
<p>However, this means any custom fonts you use for TextView widgets that
you use with android:ellipsize must also support this special Unicode
character. Not all fonts do, and you will get artifacts in the on-screen
representation of your shortened strings if your font lacks this character
(e.g., rogue X's appear at the end of the line).</p>
</blockquote> |
6,896,504 | Java Inheritance - calling superclass method | <p>Lets suppose I have the following two classes</p>
<pre><code>public class alpha {
public alpha(){
//some logic
}
public void alphaMethod1(){
//some logic
}
}
public class beta extends alpha {
public beta(){
//some logic
}
public void alphaMethod1(){
//some logic
}
}
public class Test extends beta
{
public static void main(String[] args)
{
beta obj = new beta();
obj.alphaMethod1();// Here I want to call the method from class alpha.
}
}
</code></pre>
<p>If I initiate a new object of type beta, how can I execute the <code>alphamethod1</code> logic found in class alpha rather than beta? Can I just use <code>super().alphaMethod1()</code> <- I wonder if this is possible.</p>
<p>Autotype in Eclipse IDE is giving me the option to select <code>alphamethod1</code> either from class <code>alpha</code> or class <code>beta</code>.</p> | 6,896,597 | 7 | 3 | null | 2011-08-01 09:30:07.55 UTC | 11 | 2021-08-27 13:31:27.633 UTC | 2018-04-07 09:21:51.707 UTC | null | 4,697,339 | null | 869,403 | null | 1 | 72 | java|inheritance|methods|superclass | 185,258 | <p>You can do:</p>
<pre><code>super.alphaMethod1();
</code></pre>
<p>Note, that <code>super</code> is a reference to the parent class, but <code>super()</code> is its constructor.</p> |
6,480,723 | urllib.urlencode doesn't like unicode values: how about this workaround? | <p>If I have an object like:</p>
<pre><code>d = {'a':1, 'en': 'hello'}
</code></pre>
<p>...then I can pass it to <code>urllib.urlencode</code>, no problem:</p>
<pre><code>percent_escaped = urlencode(d)
print percent_escaped
</code></pre>
<p>But if I try to pass an object with a value of type <code>unicode</code>, game over:</p>
<pre><code>d2 = {'a':1, 'en': 'hello', 'pt': u'olá'}
percent_escaped = urlencode(d2)
print percent_escaped # This fails with a UnicodeEncodingError
</code></pre>
<p>So my question is about a reliable way to prepare an object to be passed to <code>urlencode</code>.</p>
<p>I came up with this function where I simply iterate through the object and encode values of type string or unicode:</p>
<pre><code>def encode_object(object):
for k,v in object.items():
if type(v) in (str, unicode):
object[k] = v.encode('utf-8')
return object
</code></pre>
<p>This seems to work:</p>
<pre><code>d2 = {'a':1, 'en': 'hello', 'pt': u'olá'}
percent_escaped = urlencode(encode_object(d2))
print percent_escaped
</code></pre>
<p>And that outputs <code>a=1&en=hello&pt=%C3%B3la</code>, ready for passing to a POST call or whatever.</p>
<p>But my <code>encode_object</code> function just looks really shaky to me. For one thing, it doesn't handle nested objects.</p>
<p>For another, I'm nervous about that if statement. Are there any other types that I should be taking into account? </p>
<p>And is comparing the <code>type()</code> of something to the native object like this good practice? </p>
<pre><code>type(v) in (str, unicode) # not so sure about this...
</code></pre>
<p>Thanks!</p> | 6,481,120 | 8 | 6 | null | 2011-06-25 21:43:33.913 UTC | 20 | 2017-12-01 05:22:23.443 UTC | 2011-06-25 21:56:32.613 UTC | user18015 | null | user18015 | null | null | 1 | 49 | python|unicode|urlencode | 41,768 | <p>You should indeed be nervous. The whole idea that you might have a mixture of bytes and text in some data structure is horrifying. It violates the fundamental principle of working with string data: decode at input time, work exclusively in unicode, encode at output time.</p>
<p>Update in response to comment:</p>
<p>You are about to output some sort of HTTP request. This needs to be prepared as a byte string. The fact that urllib.urlencode is not capable of properly preparing that byte string if there are unicode characters with ordinal >= 128 in your dict is indeed unfortunate. If you have a mixture of byte strings and unicode strings in your dict, you need to be careful. Let's examine just what urlencode() does:</p>
<pre><code>>>> import urllib
>>> tests = ['\x80', '\xe2\x82\xac', 1, '1', u'1', u'\x80', u'\u20ac']
>>> for test in tests:
... print repr(test), repr(urllib.urlencode({'a':test}))
...
'\x80' 'a=%80'
'\xe2\x82\xac' 'a=%E2%82%AC'
1 'a=1'
'1' 'a=1'
u'1' 'a=1'
u'\x80'
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\python27\lib\urllib.py", line 1282, in urlencode
v = quote_plus(str(v))
UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128)
</code></pre>
<p>The last two tests demonstrate the problem with urlencode(). Now let's look at the str tests.</p>
<p>If you insist on having a mixture, then you should at the very least ensure that the str objects are encoded in UTF-8.</p>
<p>'\x80' is suspicious -- it is not the result of any_valid_unicode_string.encode('utf8').<br>
'\xe2\x82\xac' is OK; it's the result of u'\u20ac'.encode('utf8').<br>
'1' is OK -- all ASCII characters are OK on input to urlencode(), which will percent-encode such as '%' if necessary.</p>
<p>Here's a suggested converter function. It doesn't mutate the input dict as well as returning it (as yours does); it returns a new dict. It forces an exception if a value is a str object but is not a valid UTF-8 string. By the way, your concern about it not handling nested objects is a little misdirected -- your code works only with dicts, and the concept of nested dicts doesn't really fly.</p>
<pre><code>def encoded_dict(in_dict):
out_dict = {}
for k, v in in_dict.iteritems():
if isinstance(v, unicode):
v = v.encode('utf8')
elif isinstance(v, str):
# Must be encoded in UTF-8
v.decode('utf8')
out_dict[k] = v
return out_dict
</code></pre>
<p>and here's the output, using the same tests in reverse order (because the nasty one is at the front this time):</p>
<pre><code>>>> for test in tests[::-1]:
... print repr(test), repr(urllib.urlencode(encoded_dict({'a':test})))
...
u'\u20ac' 'a=%E2%82%AC'
u'\x80' 'a=%C2%80'
u'1' 'a=1'
'1' 'a=1'
1 'a=1'
'\xe2\x82\xac' 'a=%E2%82%AC'
'\x80'
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 8, in encoded_dict
File "C:\python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte
>>>
</code></pre>
<p>Does that help?</p> |
6,910,641 | How do I get indices of N maximum values in a NumPy array? | <p>NumPy proposes a way to get the index of the maximum value of an array via <a href="https://numpy.org/doc/stable/reference/generated/numpy.argmax.html" rel="noreferrer"><code>np.argmax</code></a>.</p>
<p>I would like a similar thing, but returning the indexes of the <code>N</code> maximum values.</p>
<p>For instance, if I have an array, <code>[1, 3, 2, 4, 5]</code>, then <code>nargmax(array, n=3)</code> would return the indices <code>[4, 3, 1]</code> which correspond to the elements <code>[5, 4, 3]</code>.</p> | 23,734,295 | 20 | 4 | null | 2011-08-02 10:29:25.053 UTC | 184 | 2022-08-22 08:54:33.917 UTC | 2022-06-13 07:36:06.537 UTC | null | 365,102 | null | 147,077 | null | 1 | 737 | python|numpy|max|numpy-ndarray | 629,100 | <p>Newer NumPy versions (1.8 and up) have a function called <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html" rel="noreferrer"><code>argpartition</code></a> for this. To get the indices of the four largest elements, do</p>
<pre><code>>>> a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> a
array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> ind = np.argpartition(a, -4)[-4:]
>>> ind
array([1, 5, 8, 0])
>>> top4 = a[ind]
>>> top4
array([4, 9, 6, 9])
</code></pre>
<p>Unlike <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="noreferrer"><code>argsort</code></a>, this function runs in linear time in the worst case, but the returned indices are not sorted, as can be seen from the result of evaluating <code>a[ind]</code>. If you need that too, sort them afterwards:</p>
<pre><code>>>> ind[np.argsort(a[ind])]
array([1, 8, 5, 0])
</code></pre>
<p>To get the top-<em>k</em> elements in sorted order in this way takes O(<em>n</em> + <em>k</em> log <em>k</em>) time.</p> |
16,028,919 | catch all unhandled exceptions in ASP.NET Web Api | <p>How do I catch <em>all</em> unhandled exceptions that occur in ASP.NET Web Api so that I can log them?</p>
<p>So far I have tried:</p>
<ul>
<li>Create and register an <a href="http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx"><code>ExceptionHandlingAttribute</code></a></li>
<li>Implement an <code>Application_Error</code> method in <code>Global.asax.cs</code></li>
<li>Subscribe to <code>AppDomain.CurrentDomain.UnhandledException</code></li>
<li>Subscribe to <code>TaskScheduler.UnobservedTaskException</code></li>
</ul>
<p>The <code>ExceptionHandlingAttribute</code> successfully handles exceptions that are thrown within controller action methods and action filters, but other exceptions are not handled, for example:</p>
<ul>
<li>Exceptions thrown when an <code>IQueryable</code> returned by an action method fails to execute</li>
<li>Exceptions thrown by a message handler (i.e. <code>HttpConfiguration.MessageHandlers</code>)</li>
<li>Exceptions thrown when creating a controller instance</li>
</ul>
<p>Basically, if an exception is going to cause a 500 Internal Server Error to be returned to the client, I want it logged. Implementing <code>Application_Error</code> did this job well in Web Forms and MVC - what can I use in Web Api?</p> | 21,382,651 | 5 | 3 | null | 2013-04-16 04:41:11.737 UTC | 31 | 2020-05-11 11:44:18.49 UTC | 2016-02-08 00:51:21.083 UTC | null | 41,956 | null | 31,563 | null | 1 | 124 | c#|asp.net-web-api|unhandled-exception | 64,798 | <p>This is now possible with WebAPI 2.1 (see the <a href="http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21#global-error">What's New</a>):</p>
<p>Create one or more implementations of IExceptionLogger. For example:</p>
<pre><code>public class TraceExceptionLogger : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
Trace.TraceError(context.ExceptionContext.Exception.ToString());
}
}
</code></pre>
<p>Then register with your application's HttpConfiguration, inside a config callback like so:</p>
<pre><code>config.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());
</code></pre>
<p>or directly:</p>
<pre><code>GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());
</code></pre> |
10,841,239 | Enabling refreshing for specific html elements only | <p>I would like to know how I can only refresh a specific element in my website, instead of the whole web page? The element I'm talking about is a flash application that loads quite slow and may experience connection timeouts. I want to enable the user to only refresh that element/falsh app. How do i do that? Below I have an Ajax function that updates an HTML element but not sure how to apply it to my situation.</p>
<pre><code><head>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">
<h2>Let AJAX change this text</h2>
</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</code></pre> | 10,914,389 | 5 | 5 | null | 2012-05-31 21:04:09.92 UTC | 5 | 2022-06-25 14:04:36.743 UTC | 2012-05-31 21:08:01.293 UTC | null | 575,527 | null | 1,401,501 | null | 1 | 20 | javascript|html|ajax | 179,547 | <p>Try this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function reload(){
var container = document.getElementById("yourDiv");
var content = container.innerHTML;
container.innerHTML= content;
//this line is to watch the result in console , you can remove it later
console.log("Refreshed");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="javascript: reload()">Click to Reload</a>
<div id="yourDiv">The content that you want to refresh/reload</div></code></pre>
</div>
</div>
</p>
<p>Hope it works. Let me know</p> |
35,340,921 | AWS error from Python: No module named lambda_function | <p>I am creating a AWS Lambda python deployment package. I am using one external dependency requests. I installed the external dependency using the <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-package.html" rel="noreferrer">AWS documentation</a>. Below is my Python code.</p>
<pre><code>import requests
print('Loading function')
s3 = boto3.client('s3')
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
# Get the object from the event and show its content type
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
try:
response = s3.get_object(Bucket=bucket, Key=key)
s3.download_file(bucket,key, '/tmp/data.txt')
lines = [line.rstrip('\n') for line in open('/tmp/data.txt')]
for line in lines:
col=line.split(',')
print(col[5],col[6])
print("CONTENT TYPE: " + response['ContentType'])
return response['ContentType']
except Exception as e:
print(e)
print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
raise e
</code></pre>
<p>Created the Zip the content of the project-dir directory and uploaded to the lambda(Zip the directory content, not the directory). When I am execute the function I am getting the below mentioned error.</p>
<pre><code>START RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058 Version: $LATEST
**Unable to import module 'lambda_function': No module named lambda_function**
END RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058
REPORT RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058 Duration: 19.63 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 9 MB
</code></pre> | 35,355,800 | 31 | 9 | null | 2016-02-11 13:40:31.82 UTC | 24 | 2022-08-06 13:41:20.84 UTC | 2022-06-09 19:21:48.037 UTC | null | 1,145,388 | null | 1,112,259 | null | 1 | 147 | python|amazon-web-services|aws-lambda | 271,066 | <p>Error was due to file name of the lambda function. While creating the lambda function it will ask for Lambda function handler. You have to name it <code>Python_File_Name.Method_Name</code>. In this scenario, I named it <code>lambda.lambda_handler</code> (<code>lambda.py</code> is the file name).</p>
<p>Please find below the snapshot.
<a href="https://i.stack.imgur.com/Ribcl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ribcl.png" alt="enter image description here" /></a></p> |
39,932,969 | Angular2 lazy loading module error 'cannot find module' | <p>I was trying to find any solution for this error but nothing works for me. I have simple Angular2 App created with Angular-CLI. When I serve this app in browser I'm getting this error: <code>EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'.</code> I was trying using different path in loadChildren: </p>
<pre><code>'/app/test.module'
'./app/test.module'
'./test.module'
'/src/app/test.module'
</code></pre>
<p><strong>Folders</strong></p>
<pre><code>src/
app/
app-routing.module.ts
app.component.ts
app.module.ts
test.component.ts
test.module.ts
</code></pre>
<p><strong>app.module.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p><strong>app-routing.module.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{ path: '', loadChildren: '/app/test.module' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: []
})
export class RoutingModule { }
</code></pre>
<p><strong>test.module.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { TestComponent } from './test.component';
export const routes: Routes = [
{ path: '', component: TestComponent }
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(routes)
],
exports: [TestComponent],
declarations: [TestComponent]
})
export default class TestModule { }
</code></pre>
<p><strong>stack trace</strong></p>
<pre class="lang-js prettyprint-override"><code> error_handler.js:45EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'.ErrorHandler.handleError @ error_handler.js:45next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
2016-10-08 14:22:50.612 error_handler.js:50ORIGINAL STACKTRACE:ErrorHandler.handleError @ error_handler.js:50next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
2016-10-08 14:22:50.613 error_handler.js:51Error: Uncaught (in promise): Error: Cannot find module '/app/test.module'.
at resolvePromise (zone.js:429)
at zone.js:406
at ZoneDelegate.invoke (zone.js:203)
at Object.onInvoke (ng_zone_impl.js:43)
at ZoneDelegate.invoke (zone.js:202)
at Zone.run (zone.js:96)
at zone.js:462
at ZoneDelegate.invokeTask (zone.js:236)
at Object.onInvokeTask (ng_zone_impl.js:34)
at ZoneDelegate.invokeTask (zone.js:235)ErrorHandler.handleError @ error_handler.js:51next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
2016-10-08 14:22:50.614 zone.js:355Unhandled Promise rejection: Cannot find module '/app/test.module'. ; Zone: angular ; Task: Promise.then ; Value: Error: Cannot find module '/app/test.module'.(…) Error: Cannot find module '/app/test.module'.
at webpackEmptyContext (http://localhost:4200/main.bundle.js:49550:8)
at SystemJsNgModuleLoader.loadAndCompile (http://localhost:4200/main.bundle.js:57952:40)
at SystemJsNgModuleLoader.load (http://localhost:4200/main.bundle.js:57945:60)
at RouterConfigLoader.loadModuleFactory (http://localhost:4200/main.bundle.js:22354:128)
at RouterConfigLoader.load (http://localhost:4200/main.bundle.js:22346:81)
at MergeMapSubscriber.project (http://localhost:4200/main.bundle.js:61105:111)
at MergeMapSubscriber._tryNext (http://localhost:4200/main.bundle.js:32515:27)
at MergeMapSubscriber._next (http://localhost:4200/main.bundle.js:32505:18)
at MergeMapSubscriber.Subscriber.next (http://localhost:4200/main.bundle.js:7085:18)
at ScalarObservable._subscribe (http://localhost:4200/main.bundle.js:48555:24)consoleError @ zone.js:355_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386
2016-10-08 14:22:50.620 zone.js:357Error: Uncaught (in promise): Error: Cannot find module '/app/test.module'.(…)consoleError @ zone.js:357_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386
</code></pre> | 41,085,933 | 16 | 7 | null | 2016-10-08 13:31:02.973 UTC | 3 | 2021-10-15 09:32:54.39 UTC | 2020-04-05 17:48:35.24 UTC | null | 7,732,434 | null | 1,892,033 | null | 1 | 62 | angular|module|lazy-loading | 82,905 | <p>restarting <code>ng serve</code> worked for me</p> |
22,457,834 | What is the difference between node vs nodejs command in terminal? | <p>I have untarred node.js from the tar file given on nodejs.org, but when i try executing my js program through node command nothing happens, but on the other hand nodejs command runs executes the file.</p>
<p>So my question is what's the <strong>difference between node command and nodejs command</strong> as and will it effect my programs as i <strong>didn't build from the source code.</strong> And i of that is the reason of this discrepancy.</p> | 22,458,067 | 3 | 2 | null | 2014-03-17 15:04:25.013 UTC | 6 | 2017-05-19 17:48:07.583 UTC | 2015-11-23 05:45:27.347 UTC | null | 3,211,456 | null | 3,211,456 | null | 1 | 38 | javascript|node.js|terminal|installation | 38,559 | <p>This is highly dependent on many factors. Mainly, it depends on what <code>node</code> and <code>nodejs</code> in your shell actually are. You can check this using <code>type node</code> / <code>type nodejs</code> and/or <code>which node</code> / <code>which nodejs</code> (or perhaps <code>whereis</code>). This <em>also</em> depends on the OS and the shell.</p>
<p>My guess is that <code>which -a node</code> will yield <code>/usr/sbin/node</code> which is <em>not</em> the nodejs executable and thus why it does not execute your node code. On my system, it is:</p>
<pre><code>/usr/bin/node -> /etc/alternatives/node -> /usr/bin/nodejs
</code></pre>
<p>i.e. <code>node</code> is just a symbolic link to <code>nodejs</code>, which is the executable.</p>
<p>You can also create this alias yourself so that it overrides whatever <code>node</code> is for you.</p> |
13,373,935 | ModelState.IsValid is always returning false | <pre><code>[HttpPost]
public ActionResult Create(Users user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
</code></pre>
<p><code>ModelState.IsValid</code> is always false.<br>
so it just return view and new record is not getting added..</p>
<p><strong>Edit</strong></p>
<p>User:</p>
<pre><code>public class User
{
public int UserID { get; set; }
public string Name { get; set; }
[Display(Name = "Confirm Password")] [DataType(DataType.Password)]
public string ConfirmPassword { get; set; }
public string Designation { get; set; }
[Display(Name = "Date of Join")] [DataType(DataType.Date)] public DateTime DOJ { get; set; }
public string Email { get; set; }
[Display(Name = "Phone Number")] public System.Int64 PhoneNo { get; set; }
}
</code></pre> | 13,373,964 | 1 | 3 | null | 2012-11-14 06:16:27.943 UTC | 8 | 2018-05-30 05:54:38.76 UTC | 2018-05-30 05:54:38.76 UTC | null | 4,337,436 | null | 1,697,789 | null | 1 | 32 | asp.net-mvc|asp.net-mvc-3|modelstate | 55,568 | <p><code>ModelState.IsValid</code> will be false if the validation for the Model failed. </p>
<ol>
<li>You have <a href="http://msdn.microsoft.com/en-us/library/dd901590%28v=vs.95%29.aspx">DataAnnotation</a> which failed the incoming model.</li>
<li>You added custom validations.</li>
<li>Make sure there are no null entries in the model for non null properties</li>
</ol>
<p>Check the <code>ModelState.Errors</code> for what is the reason causing this. You can use this:</p>
<pre><code>var errors = ModelState.Values.SelectMany(v => v.Errors);
</code></pre> |
13,707,134 | Adding hover CSS attributes via jQuery/Javascript | <p>Some CSS styles need to be applied to an element on hover, and CSS styles have to be applied using javascript/jquery directly and not through stylesheets or <code>$(this).addClass('someStyle')</code> because I am injecting the DOM elements into another page.</p>
<p>We can apply the usual css styles using </p>
<pre><code>$('#some-content').css({
marginTop: '60px',
display: 'inline-block'
});
</code></pre>
<p>How should we add the CSS styles for <code>:hover</code> events?</p>
<hr>
<p>Do we have to resort to:</p>
<pre><code>$('#some-content').hover(
function(){ $(this).css('display', 'block') },
function(){ $(this).css('display', 'none') }
)
</code></pre> | 13,707,162 | 4 | 5 | null | 2012-12-04 16:14:16.17 UTC | 2 | 2014-03-20 14:11:10.807 UTC | 2014-03-20 14:11:10.807 UTC | null | 745,059 | null | 741,099 | null | 1 | 40 | javascript|jquery|html|css|hover | 77,454 | <p>I find using mouseenter and mouseleave to be better than hover. There's more control.</p>
<pre><code>$("#somecontent").mouseenter(function() {
$(this).css("background", "#F00").css("border-radius", "3px");
}).mouseleave(function() {
$(this).css("background", "00F").css("border-radius", "0px");
});
</code></pre> |
13,756,055 | Why can't I push this up-to-date Git subtree? | <p>I am using Git subtree with a couple of projects that I am working on, in order to share some base code between them. The base code gets updated often, and the upgrades can happen in anyone of the projects, with all of them getting updated, eventually.</p>
<p>I have ran into a problem where git reports that my subtree is up to date, but pushing gets rejected. For example:</p>
<pre><code>#! git subtree pull --prefix=public/shared project-shared master
From github.com:****
* branch master -> FETCH_HEAD
Already up-to-date.
</code></pre>
<p>If I push, I should get a message that there is nothing to push... Right? RIGHT? :(</p>
<pre><code>#! git subtree push --prefix=public/shared project-shared master
git push using: project-shared master
To [email protected]:***
! [rejected] 72a6157733c4e0bf22f72b443e4ad3be0bc555ce -> master (non-fast-forward)
error: failed to push some refs to '[email protected]:***'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code></pre>
<p>What could be the reason for this? Why is pushing failing?</p> | 15,623,469 | 12 | 4 | null | 2012-12-07 02:27:22.93 UTC | 56 | 2020-02-21 20:38:46.473 UTC | 2020-02-21 20:38:46.473 UTC | null | 3,619 | null | 1,086,672 | null | 1 | 97 | git|git-subtree | 25,234 | <p>I found the answer on this blog comment <a href="https://coderwall.com/p/ssxp5q">https://coderwall.com/p/ssxp5q</a></p>
<blockquote>
<p>If you come across the "Updates were rejected because the tip of your current branch is
behind. Merge the remote changes (e.g. 'git pull')" problem when you're pushing (due to
whatever reason, esp screwing about with git history) then you'll need to nest git
commands so that you can force a push to heroku. e.g, given the above example:</p>
</blockquote>
<pre><code>git push heroku `git subtree split --prefix pythonapp master`:master --force
</code></pre> |
13,364,243 | webSocketServer node.js how to differentiate clients | <p>I am trying to use sockets with node.js, I succeded but I don't know how to differentiate clients in my code.
The part concerning sockets is this:</p>
<pre><code>var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 8080});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
ws.send(message);
});
ws.send('something');
});
</code></pre>
<p>This code works fine with my client js.</p>
<p>But I would like to send a message to a particular user or all users having sockets open on my server.</p>
<p>In my case I send a message as a client and I receive a response but the others user show nothing.</p>
<p>I would like for example user1 sends a message to the server via webSocket and I send a notification to user2 who has his socket open.</p> | 17,223,609 | 12 | 5 | null | 2012-11-13 16:06:46.787 UTC | 37 | 2022-06-05 04:47:47.103 UTC | 2015-04-22 08:10:44.69 UTC | null | 620,140 | null | 1,820,957 | null | 1 | 105 | node.js|websocket | 109,804 | <p>You can simply assign users ID to an array CLIENTS[], this will contain all users. You can directly send message to all users as given below:</p>
<pre><code>var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 8080}),
CLIENTS=[];
wss.on('connection', function(ws) {
CLIENTS.push(ws);
ws.on('message', function(message) {
console.log('received: %s', message);
sendAll(message);
});
ws.send("NEW USER JOINED");
});
function sendAll (message) {
for (var i=0; i<CLIENTS.length; i++) {
CLIENTS[i].send("Message: " + message);
}
}
</code></pre> |
3,659,271 | Log4Net - Logging out the Exception stacktrace only for certain files | <p>I currently have multiple log files in my application using log4net.</p>
<p>I have a top level log file which contains every type of message. I also have an error log file which contains only error information. I am trying to configure it so the specific exception details and stack trace only appear in the error log file.</p>
<p>The call i am using is <code>Log.Error(myMessage, myException);</code> </p>
<p>My config can be seen below:</p>
<pre><code><configuration>
<log4net>
<root>
<level value="ALL"/>
<appender-ref ref="GeneralTextLog"/>
<appender-ref ref="ErrorTextLog"/>
</root>
<!-- The general appender rolls by date -->
<appender name="GeneralTextLog" type="log4net.Appender.RollingFileAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<level value="ALL"/>
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%type] %-5p %message%n"/>
</layout>
<rollingStyle value="Date"/>
<file value="C:/Logs/General_"/>
<datePattern value="yyyy_MM_dd'.log'" />
<appendToFile value="true"/>
<staticLogFileName value="false"/>
</appender>
<!-- The Error appender rolls by date -->
<appender name="ErrorTextLog" type="log4net.Appender.RollingFileAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="WARN"/>
<levelMax value="FATAL"/>
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%type] %-5p %message%newline%exception"/>
</layout>
<rollingStyle value="Date"/>
<file value="C:/Logs/Error_"/>
<datePattern value="yyyy_MM_dd'.log'" />
<appendToFile value="true"/>
<staticLogFileName value="false"/>
</appender>
<!-- Loggers -->
<logger name="DefaultLogger">
<appender-ref ref="GeneralTextLog"/>
<level value="ALL"/>
</logger>
<logger name="ErrorLogger">
<appender-ref ref="ErrorTextLog"/>
<levelMin value="WARN"/>
<levelMax value="FATAL"/>
</logger>
</code></pre>
<p></p>
<p></p>
<p>Despite the fact that i have only included %exception in the conversionPattern for the error log, the stacktrace appears in both logs. Does anyone know how i can stop this from happening?</p> | 3,660,529 | 2 | 0 | null | 2010-09-07 13:57:32.043 UTC | 11 | 2010-09-07 16:28:11.94 UTC | null | null | null | null | 432,094 | null | 1 | 23 | .net|log4net|log4net-configuration | 22,536 | <p>Configure the layout like this (GeneralTextLog Appender):</p>
<pre><code><layout type="log4net.Layout.PatternLayout">
<IgnoresException value="False" />
...
</code></pre>
<p>Setting <code>IgnoresException</code> to false tells the appender that the layout will take care of the exception. Thus you can choose not to print the stack trace. </p> |
16,564,789 | Changing the generated name of a foreign key in Hibernate | <pre><code>@OneToOne()
@JoinColumn(name="vehicle_id", referencedColumnName="vehicleId")
public Vehicle getVehicle() {
return vehicle;
}
</code></pre>
<p>My UserDetails class has a one-to-one mapping with the Entitity class Vehicle. <code>Hibernate</code> creates the 2 tables and assigns a generic Foreign Key, which maps the vehicle_id column (UserDetails table.) to the primary key vehicleId (Vehicle table).</p>
<pre><code>KEY FKB7C889CEAF42C7A1 (vehicle_id),
CONSTRAINT FKB7C889CEAF42C7A1 FOREIGN KEY (vehicle_id) REFERENCES vehicle (vehicleId)
</code></pre>
<p>My question is : how do we change this generated foreign key, into something meaningful, like Fk_userdetails_vehicle for example.</p> | 16,564,911 | 4 | 2 | null | 2013-05-15 12:16:49.253 UTC | 11 | 2017-11-23 05:20:43.517 UTC | null | null | null | null | 2,363,875 | null | 1 | 28 | java|mysql|hibernate | 28,843 | <p>Since JPA 2.1, you can use the <a href="https://docs.oracle.com/javaee/7/api/index.html?javax/persistence/ForeignKey.html" rel="noreferrer">@javax.persistence.ForeignKey</a> annotation:</p>
<pre><code>@OneToOne()
@JoinColumn(name="vehicle_id", referencedColumnName="vehicleId", foreignKey=@ForeignKey(name = "Fk_userdetails_vehicle"))
public Vehicle getVehicle() {
return vehicle;
}
</code></pre>
<p>Prior to JPA 2.1, you could use Hibernate’s <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/index.html?org/hibernate/annotations/ForeignKey.html" rel="noreferrer">@org.hibernate.annotations.ForeignKey</a> annotation, but this is now deprecated:</p>
<pre><code>@OneToOne()
@JoinColumn(name="vehicle_id", referencedColumnName="vehicleId")
@ForeignKey(name="Fk_userdetails_vehicle")
public Vehicle getVehicle() {
return vehicle;
}
</code></pre> |
16,302,554 | View all fields / properties of bean in JSP / JSTL | <p>I have a bean, <code>${product}</code>. I would like to view all of the available fields / properties of this bean. So for instance, <code>${product.price}</code>, <code>${product.name}</code>, <code>${product.attributes.colour}</code> etc. </p>
<p>Is it possible to dynamically print out all names and values of these properties in JSP, using JSTL/EL?</p>
<p>Something like:</p>
<pre><code><c:forEach items="${product}" var="p">
${p.key} - ${p.value}
</c:forEach>
</code></pre> | 24,576,688 | 4 | 0 | null | 2013-04-30 14:37:11.543 UTC | 17 | 2018-09-07 07:46:02.543 UTC | 2016-04-10 07:33:43.423 UTC | null | 157,882 | null | 1,230,910 | null | 1 | 32 | jsp|properties|jstl|javabeans | 38,325 | <p>Replace object with the bean to determine.</p>
<pre><code><c:set var="object" value="${product}" />
</code></pre>
<p>Display all declared fields and their values.</p>
<pre><code><c:if test="${not empty object['class'].declaredFields}">
<h2>Declared fields <em>&dollar;{object.name}</em></h2>
<ul>
<c:forEach var="field" items="${object['class'].declaredFields}">
<c:catch><li><span style="font-weight: bold">
${field.name}: </span>${object[field.name]}</li>
</c:catch>
</c:forEach>
</ul>
</c:if>
</code></pre>
<p>Display all declared methods.</p>
<pre><code><c:if test="${not empty object['class'].declaredMethods}">
<h2>Declared methods<em>&lt;% object.getName() %&gt;</em></h2>
<ul>
<c:forEach var="method" items="${object['class'].declaredMethods}">
<c:catch><li>${method.name}</li></c:catch>
</c:forEach>
</ul>
</c:if>
</code></pre> |
16,369,749 | How to disable pre-commit code analysis for Git-backed projects using IntelliJ IDEA | <p>I have a project in IntelliJ IDEA, and I'm using Git/GitHub as source control. Each time I try to commit changes, IntelliJ IDEA runs a lengthy code analysis and searches for TODOs. When it finds "problems," it prompts me whether or not I want to review or commit.</p>
<p>I don't want the pre-commit code analysis to run, and I don't want IntelliJ IDEA to ask me about the results. I can't seem to find any setting in the regular IntelliJ IDEA project/IDE settings to disable this. How can I disable this?</p> | 16,369,750 | 5 | 0 | null | 2013-05-04 01:39:03.823 UTC | 5 | 2022-09-09 18:51:30.96 UTC | 2017-11-29 22:31:02.9 UTC | null | 63,550 | null | 99,717 | null | 1 | 57 | git|github|intellij-idea|commit|code-analysis | 31,461 | <p><strong>This answer is outdated</strong>. Please see <a href="https://stackoverflow.com/a/65839277/99717">Interlated's answer</a> for a more current answer.</p>
<hr />
<p>Answer for IntelliJ IDEA 11.1.5:</p>
<p>There are persistent check-boxes in the "Commit Changes" dialog. The next time you go to commit a changelist, uncheck the "Perform code analysis" and "Check TODO" check-boxes.</p>
<p>If you want to just get it done now:</p>
<ul>
<li>Make a non-invasive, 'test change' to a file; for example, add a test comment to any file</li>
<li>Right click on the changelist and select "Commit Changes..."</li>
<li>In the "Commit Changes" dialog, uncheck the "Perform code analysis" and "Check TODO" check-boxes</li>
<li>Click "Commit" to persist the settings. You can then undo the test comment and commit that.</li>
</ul>
<p>I can't find anyway to disable these checkboxes by default for new projects.</p> |
17,463,171 | Using COUNT in GROUP_CONCAT | <p>This is my table:</p>
<pre><code> id | fk_company
-------------------
1 | 2
2 | 2
3 | 2
4 | 4
5 | 4
6 | 11
7 | 11
8 | 11
9 | 12
</code></pre>
<p>The result I want should be string "3, 2, 3, 1" (count of items that belong to each company), because this is just part of my complex query string.</p>
<p>I tried to use this query:</p>
<pre><code>SELECT GROUP_CONCAT(COUNT(id) SEPARATOR ", ")
FROM `table` GROUP BY fk_company;
</code></pre>
<p>But I got an error:</p>
<blockquote>
<p>Error Number: 1111<br />
Invalid use of group function</p>
</blockquote>
<p>I have a feeling <code>COUNT</code>, <code>MAX</code>, <code>MIN</code> or <code>SUM</code> can't be used in <code>GROUP_CONCAT</code>. If so, do you know another way to do this?</p> | 17,463,263 | 4 | 1 | null | 2013-07-04 06:21:26.323 UTC | 2 | 2021-01-06 23:32:19.563 UTC | 2021-01-06 23:32:19.563 UTC | null | 814,702 | null | 382,854 | null | 1 | 15 | mysql|sql|count|group-concat | 38,481 | <p>You need to <code>COUNT()</code> with <code>GROUP BY</code> in an inner <code>SELECT</code> clause first and then apply <code>GROUP_CONCAT()</code>;</p>
<pre><code>SELECT GROUP_CONCAT(cnt) cnt
FROM (
SELECT COUNT(*) cnt
FROM table1
GROUP BY fk_company
) q;
</code></pre>
<p>Output:</p>
<pre>
| CNT |
-----------
| 3,2,3,1 |
</pre>
<p>Here is <strong><a href="http://sqlfiddle.com/#!2/9c83f/3" rel="nofollow noreferrer">SQLFiddle</a></strong> demo.</p> |
21,935,149 | Sharing link on WhatsApp from mobile website (not application) for Android | <p>I have developed a website which is mainly used in mobile phones.<br>
I want to allow users to share information directly from the web page into WhatsApp.</p>
<p>Using UserAgent detection I can distinguish between Android and iOS.<br>
I was able to discover that in order to implement the above in iOS I can use the URL:</p>
<pre><code>href="whatsapp://send?text=http://www.example.com"
</code></pre>
<p>I'm still looking for the solution to be used when the OS is Android (as the above doesn't work).<br>
I guess it is somehow related to using "intent" in Android, but I couldn't figure out how to do it as parameter for href.</p> | 25,796,908 | 16 | 2 | null | 2014-02-21 12:58:17.95 UTC | 98 | 2021-11-17 16:19:07.19 UTC | 2019-12-14 22:35:32.06 UTC | null | 1,839,439 | null | 3,315,773 | null | 1 | 259 | android|html|mobile|share|whatsapp | 659,439 | <p>Just saw it on a website and seems to work on latest Android with latest chrome and whatsapp now too! Give the link a new shot!</p>
<pre><code><a href="whatsapp://send?text=The text to share!" data-action="share/whatsapp/share">Share via Whatsapp</a>
</code></pre>
<p>Rechecked it today (17<sup>th</sup> April 2015):<br>
Works for me on iOS 8 (iPhone 6, latest versions) Android 5 (Nexus 5, latest versions).</p>
<p>It also works on Windows Phone.</p> |
39,688,830 | Why use/develop Guice, when You have Spring and Dagger? | <p>To my knowledge, Dagger does generate code, while Guice and Spring rely on runtime processing, thus Dagger works faster, but requires more work on programmer side. Because of performance edge it's good for mobile (Android) development.</p>
<p>However, when we are left with Guice and Spring, the latter has lots of integrations. What's the point of developing/using Guice, if we can use Spring Framework (that does basically same thing, but offers ex. easier database access)?</p>
<p>Isn't Google trying to reinvent wheel by creating their own DI tool, instead of using (and possibly contributing to) Spring Framework?</p>
<p>I am looking for decision tree, that guides through choosing DI tool.</p> | 39,689,526 | 1 | 8 | null | 2016-09-25 15:52:14.933 UTC | 22 | 2022-06-20 18:27:38.64 UTC | null | null | null | null | 6,058,078 | null | 1 | 80 | java|spring|guice|dagger-2 | 39,742 | <p>It's important to acknowledge that Dagger was created after Guice, by one of Guice's creators (<a href="http://blog.crazybob.org/" rel="noreferrer">"Crazy Bob" Lee</a>) who had moved to Square:</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Rod_Johnson_(programmer)" rel="noreferrer">Rod Johnson</a> originally released <strong>Spring</strong> in <a href="https://en.wikipedia.org/wiki/Spring_Framework#Version_history" rel="noreferrer">October 2002</a> with his book <em>Expert One-on-One J2EE Design and Development</em>; Spring was then released publicly on the Apache license in June 2003 and as v1.0 in <a href="https://spring.io/blog/2004/03/24/spring-framework-1-0-final-released" rel="noreferrer">March 2004</a>.</li>
<li>Google originally released <strong>Guice</strong> publicly in <a href="https://github.com/google/guice/wiki/Guice10" rel="noreferrer">March 2007</a>.</li>
<li><a href="http://javax-inject.github.io/javax-inject/" rel="noreferrer"><strong>JSR-330</strong></a> formalized <code>javax.inject</code> annotations in <a href="https://jcp.org/en/jsr/detail?id=330" rel="noreferrer">October 2009</a>, as submitted by Google (Bob Lee) and SpringSource (Rod Johnson), with other industry collaborators on its Expert Group.</li>
<li>Square originally released <strong>Dagger 1</strong> publicly in <a href="https://github.com/square/dagger/blob/master/CHANGELOG.md" rel="noreferrer">May 2013</a>.</li>
<li>Google originally released <strong>Dagger 2</strong> publicly in <a href="https://github.com/google/dagger/releases/tag/dagger-2.0" rel="noreferrer">April 2015</a>.</li>
<li>Square marked Dagger 1 as deprecated 10 days before this question was asked, on <a href="https://github.com/square/dagger/commit/a0f269af6e9b0385c37ce7f89c9be6e1c75aa6a8" rel="noreferrer">September 15, 2016</a>.</li>
</ul>
<p>In that sense, the continued curation of Guice isn't "reinventing the wheel" so much as maintenance on a long-running and widely-consumed software package that thoroughly predates any version of Dagger. You might consider Dagger to be a spiritual successor to Guice, but one that only offers an <em>optimized subset</em> of Guice's functionality.</p>
<p>To list and amend to the differences you have above:</p>
<ul>
<li>Spring is a relatively-heavyweight framework with a lot of integrations, an XML configuration language, and runtime/reflective bindings. Applications already using Spring can use Spring's dependency injection framework with very little extra work.</li>
<li>Guice is a relatively-lightweight framework with fewer integrations, Java instance configuration, and runtime/reflective bindings. With the use of Java bindings, you get compile-time type checking and IDE autocomplete integration.</li>
<li>Dagger is a very lightweight framework with very few integrations, Java interface/annotation configuration, and compile-time code-generated bindings. The code generation aspect makes Dagger very performant overall and particularly in resource-limited and mobile environments. (Android's VMs differ from server JREs in ways that make reflection especially slow, so Dagger is especially useful here.)</li>
<li>All three of the above frameworks support JSR-330, so a well-crafted library or application can be mostly agnostic to the DI container used.</li>
</ul>
<p>Beyond that, keep an eye out for maintenance/deprecation patterns and policies among any framework you use. Based on your team's knowledge and experience, your need for reflection or runtime configuration, and your need for integrations and runtime performance, you'll probably see one of the above stand out. That said, there are also other frameworks out there, so keep an eye open for new options and forks of the above as well.</p> |
44,980,774 | AttributeError: 'Series' object has no attribute 'days' | <p>I have a column 'delta' in a dataframe dtype: timedelta64[ns], calculated by subcontracting one date from another. I am trying to return the number of days as a float by using this code:</p>
<pre><code>from datetime import datetime
from datetime import date
df['days'] = float(df['delta'].days)
</code></pre>
<p>but I receive this error:</p>
<pre><code>AttributeError: 'Series' object has no attribute 'days'
</code></pre>
<p>Any ideas why?</p> | 44,981,538 | 2 | 3 | null | 2017-07-07 22:56:47.523 UTC | 2 | 2019-09-26 20:19:48.443 UTC | null | null | null | null | 7,945,146 | null | 1 | 25 | python|attributeerror|timedelta | 65,071 | <p>While subtracting the dates you should use the following code.</p>
<pre><code>df = pd.DataFrame([ pd.Timestamp('20010101'), pd.Timestamp('20040605') ])
(df.loc[0]-df.loc[1]).astype('timedelta64[D]')
</code></pre>
<p>So basically use <code>.astype('timedelta64[D]')</code> on the subtracted column.</p> |
17,512,504 | change action bar direction to right-to-left | <p>I'm creating an android app for a right-to-left specific language. And I'm using ActionBarSherlock (a compatible android action bar library).<br/>
The thing I exactly want is how to change the direction of action bar to RTL even the user not sets the default Locale an RTL language.<br/>
If anyone has an idea even for standard android Action Bar it's valuable and may help please share it.<br/>
Thanks</p> | 17,683,045 | 6 | 2 | null | 2013-07-07 13:18:27.853 UTC | 12 | 2021-12-19 13:48:01.97 UTC | null | null | null | null | 1,362,571 | null | 1 | 19 | android|actionbarsherlock|android-actionbar | 24,118 | <p>From Android API Level 17+ it supports RTL natively. To force your entire layout to be RTL including the ActionBar do the following.</p>
<p>Edit your AndroidManifest.xml and add <code>android:supportsRtl="true"</code> to your <code><application></code> tag and then add the following line to the top of your Activities' onCreate() method <code>forceRTLIfSupported();</code> and then insert the follow function into your Activity.</p>
<pre><code>@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void forceRTLIfSupported()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
</code></pre>
<p>Of course that's only helpful for debugging. Use <code>View.LAYOUT_DIRECTION_LOCALE</code> for production builds so your layout is only changed when the user chosen system location/language aka locale supports RTL.</p>
<p>Hope that helps.</p> |
17,371,955 | Verifying signed git commits? | <p>With newer versions of <code>git</code> it's possible to sign individual commits (in addition to tags) with a PGP key:</p>
<pre><code>git commit -m "some message" -S
</code></pre>
<p>And you can show these signatures in the output of <code>git log</code> with the <code>--show-signature</code> option:</p>
<pre><code>$ git log --show-signature
commit 93bd0a7529ef347f8dbca7efde43f7e99ab89515
gpg: Signature made Fri 28 Jun 2013 02:28:41 PM EDT using RSA key ID AC1964A8
gpg: Good signature from "Lars Kellogg-Stedman <[email protected]>"
Author: Lars Kellogg-Stedman <[email protected]>
Date: Fri Jun 28 14:28:41 2013 -0400
this is a test
</code></pre>
<p>But is there a way to programatically verify the signature on a given commit other than by grepping the output of <code>git log</code>? I'm looking for the commit equivalent of <code>git tag -v</code> -- something that will provide an exit code indicating whether or not there was a valid signature on a given commit.</p> | 30,236,531 | 3 | 5 | null | 2013-06-28 19:09:08.953 UTC | 38 | 2022-01-13 22:54:01.997 UTC | 2013-08-02 13:30:48.813 UTC | null | 147,356 | null | 147,356 | null | 1 | 149 | git | 63,156 | <p>Just in case someone comes to this page through a search engine, like I did: New tools have been made available in the two years since the question was posted: There are now git commands for this task: <code>git verify-commit</code> and <code>git verify-tag</code> can be used to verify commits and tags, respectively.</p> |
18,235,654 | How to solve error: "Clock skew detected"? | <p>I am uploading my OpenCL and Cuda code to <a href="http://hgpu.org" rel="noreferrer" title="HGPU.org">hgpu.org</a> because I don't have a graphics card on my laptop. When I upload my code I get the following error:</p>
<pre><code>make: Warning: File `main.cu' has modification time 381 s in the future
make: warning: Clock skew detected. Your build may be incomplete.
</code></pre>
<p>I know that clock skew is due to difference in my machines clock time and the server's clock time, so I synchronized my time with the server's. The OpenCL and C++ code is running fine now but the Cuda code is still giving me this error.</p>
<p>So my question is:</p>
<p><strong>Is there any other reason for clock skew error besides the time synchronization? And if there is then how do I solve it?</strong></p>
<p>Cuda Code:</p>
<pre><code>__global__
void test()
{
}
int main()
{
dim3 gridblock(1,1,1);
dim3 threadblock(1,1,1);
test<<<gridblock,threadblock>>>();
return 0;
}
</code></pre>
<p>Note: I can provide the make file too.</p> | 27,720,764 | 4 | 0 | null | 2013-08-14 15:17:45.387 UTC | 5 | 2019-01-18 04:13:16.123 UTC | 2016-06-09 13:52:33.957 UTC | null | 5,550,456 | null | 2,286,337 | null | 1 | 20 | makefile|clock | 146,241 | <p>I am going to answer my own question.</p>
<p>I added the following lines of code to my Makefile and it fixed the "clock skew" problem:</p>
<pre><code>clean:
find . -type f | xargs touch
rm -rf $(OBJS)
</code></pre> |
9,462,356 | Can we say node.js is a web server? | <p>I found that I am confusing between web framework and web server.</p>
<p><code>Apache is a web server.</code></p>
<p><code>Tornado is a web server written in Python.</code></p>
<p><code>Nginx is a web server written in C</code></p>
<p><code>Zend is a web framework in php</code></p>
<p><code>Flask/Bottle is a web framework in Python</code></p>
<p><code>RoR is a web framework written in Ruby</code></p>
<p><code>Express is a web framework written in JS under Node.JS</code></p>
<p>Can we say node.js is a web server??? I am so confused between web server/ framework.</p>
<p>If somehow node.js is kind of webserver, not webframework (Express does), why do we need to put the whole node.js on top of Nginx server in useful practice??
<a href="https://stackoverflow.com/questions/9287747/why-do-we-need-apache-under-node-js-express-web-framework">Question on SO</a></p>
<p>Who can help???</p>
<p>Kit</p> | 9,484,970 | 10 | 3 | null | 2012-02-27 09:01:00.433 UTC | 52 | 2022-09-06 10:03:17.543 UTC | 2017-07-02 14:07:54.96 UTC | null | 2,327,544 | null | 514,316 | null | 1 | 116 | node.js|webserver|web-frameworks | 63,635 | <h2><a href="http://en.wikipedia.org/wiki/Web_server" rel="noreferrer">Web server</a></h2>
<blockquote>
<p>Web server can refer to either the hardware (the computer) or the
software (the computer application) that helps to deliver content that
can be accessed through the Internet.<a href="http://en.wikipedia.org/wiki/Web_server" rel="noreferrer">1</a></p>
<p>The primary function of a web server is to deliver web pages on the
request to clients. This means delivery of HTML documents and any
additional content that may be included by a document, such as images,
style sheets and scripts.</p>
</blockquote>
<p>A web server is the basic to delivering requests/pagess to the clients/user on the internet</p>
<h2><a href="http://en.wikipedia.org/wiki/Web_application_framework" rel="noreferrer">Web framework</a></h2>
<blockquote>
<p>A web application framework is a software framework that is designed
to support the development of dynamic websites, web applications and
web services. The framework aims to alleviate the overhead associated
with common activities performed in Web development. For example, many
frameworks provide libraries for database access, templating
frameworks and session management, and they often promote code reuse.</p>
</blockquote>
<p>A web framework uses a webserver to deliver the requests to client, but it is not the web server.</p>
<h2><a href="http://nodejs.org/" rel="noreferrer">Node.js</a></h2>
<blockquote>
<p>Node.js is a platform built on Chrome's JavaScript runtime for easily
building fast, scalable network applications. Node.js uses an
event-driven, non-blocking I/O model that makes it lightweight and
efficient, perfect for data-intensive real-time applications that run
across distributed devices.</p>
</blockquote>
<p>But then again you can also create CLI apps so I think you should see it more as a platform to write javascript programs to run on your server(computer) using <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">Javascript</a> <a href="http://en.wikipedia.org/wiki/Programming_language" rel="noreferrer">programming language</a> instead of just in the browser as in the beginning. I think you could see it as <code>Javascript++</code> ??</p>
<p>You can also write web server with node.js as you can see on the front page of node.js. In the beginning Ryan said you could put <a href="http://en.wikipedia.org/wiki/Nginx" rel="noreferrer">Nginx</a> in front of node.js because of the stabilty of the project. The project was and still is pretty young. Nginx is a proven web server that will keep on running while node.js can crash. Then again a lot of user just use node.js for that.</p> |
9,303,875 | fileExistsAtPath: returning NO for files that exist | <p>At a point in my code fileExistsAtPath: is returning NO for files that I have confirmed exist. I've been scratching my head at this and can't figure out why its not working, so changed it to this code as this directory absolutely exists but if it doesn't gets created anyway.</p>
<pre><code>NSError* err = nil;
NSURL *dir = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create: YES
error:&err];
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:[dir absoluteString]];
</code></pre>
<p>After running this code the application directory folder exists and err is 0, yet exists is NO.</p>
<p>How can this be?</p>
<p>TIA</p> | 9,314,386 | 3 | 4 | null | 2012-02-16 00:36:07.833 UTC | 3 | 2021-03-10 15:42:09.58 UTC | null | null | null | null | 1,082,219 | null | 1 | 68 | ios | 13,379 | <p>You should use <code>[dir path]</code>, not <code>[dir absoluteString]</code>.</p> |
9,522,591 | MPNowPlayingInfoCenter defaultCenter will not update or retrieve information | <p>I'm working to update the MPNowPlayingInfoCenter and having a bit of trouble. I've tried quite a bit to the point where I'm at a loss. The following is my code:</p>
<pre><code> self.audioPlayer.allowsAirPlay = NO;
Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
if (playingInfoCenter) {
NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"series_placeholder"]];
[songInfo setObject:thePodcast.title forKey:MPMediaItemPropertyTitle];
[songInfo setObject:thePodcast.author forKey:MPMediaItemPropertyArtist];
[songInfo setObject:@"NCC" forKey:MPMediaItemPropertyAlbumTitle];
[songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
}
</code></pre>
<p>This isn't working, I've also tried:</p>
<pre><code> [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:nil];
</code></pre>
<p>In an attempt to get it to remove the existing information from the iPod app (or whatever may have info there). In addition, just to see if I could find out the problem, I've tried retrieving the current information on app launch:</p>
<pre><code> NSDictionary *info = [[MPNowPlayingInfoCenter defaultCenter] nowPlayingInfo];
NSString *title = [info valueForKey:MPMediaItemPropertyTitle];
NSString *author = [info valueForKey:MPMediaItemPropertyArtist];
NSLog(@"Currently playing: %@ // %@", title, author);
</code></pre>
<p>and I get <code>Currently playing: (null) // (null)</code></p>
<p>I've researched this quite a bit and the following articles explain it pretty thoroughly, however, I am still unable to get this working properly. Am I missing something? Would there be anything interfering with this? Is this a service something my app needs to register to access (didn't see this in any docs)?</p>
<p><a href="https://developer.apple.com/library/ios/#documentation/MediaPlayer/Reference/MPNowPlayingInfoCenter_Class/Reference/Reference.html" rel="nofollow noreferrer">Apple's Docs</a></p>
<p><a href="https://stackoverflow.com/questions/6600592/change-lock-screen-background-audio-controls-text">Change lock screen background audio controls</a></p>
<p><a href="https://stackoverflow.com/questions/8808031/mpnowplayinginfocenter-nowplayinginfo-ignored-for-avplayer-audio-via-airplay">Now playing info ignored</a></p> | 9,537,112 | 2 | 5 | null | 2012-03-01 19:24:50.337 UTC | 9 | 2017-01-30 17:57:51.047 UTC | 2017-05-23 11:54:50.48 UTC | null | -1 | null | 535,632 | null | 1 | 28 | iphone|ios|mpmovieplayercontroller | 17,501 | <p>I finally figured out the problem, I was not prompting my app to receive remote control events, simply adding this line fixed the problem:</p>
<pre><code> [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
</code></pre> |
18,491,020 | What does "Throws" do and how is it helpful? | <p>I am new to Java and have just came across a tutorial which uses the"Throws" keyword in a method. I have done a little research into this but still do not really understand it.</p>
<p>From what I have seen so far, it is telling the compiler that a certain exception may be thrown in that particular method. Why do we need to tell the compiler this? I have made many programs using merely a try-catch statement in my methods and it has worked just fine - surely it is these try-catch statements which manage exceptions, right?</p> | 18,491,242 | 5 | 1 | null | 2013-08-28 14:38:19.377 UTC | 12 | 2016-12-21 17:00:14.813 UTC | null | null | null | null | 2,718,952 | null | 1 | 15 | java|exception|methods|exception-handling|keyword | 24,044 | <p>You can manage an exception <em>within</em> a method using <code>try</code> and <code>catch</code> as you say. In that case, you do not need to use <code>throws</code>. For example: </p>
<pre><code>public void myMethod()
{
try {
/* Code that might throw an exception */
}
catch (SpaceInvadersException exception) {
/* Complicated error handling code */
}
}
</code></pre>
<p>But suppose you had a thousand methods, all of which might throw a <code>SpaceInvadersException</code>. Then you would end up having to write all the complicated error handling code a thousand times. Of course, you could always create an <code>ErrorHandler</code> class with a <code>dealWithSpaceInvadersException()</code> method that you could call from them, but you'd still be stuck with a thousand <code>try</code>-<code>catch</code> blocks. </p>
<p>Instead, you tell the compiler that each of these thousand methods could throw a <code>SpaceInvadersException</code>. Then any method that calls one of these methods needs to deal with the error itself, either by using a <code>try</code>-<code>catch</code>, or by telling the compiler that <em>it</em> might throw a <code>SpaceInvadersException</code>. This is done using the <code>throws</code> keyword, like this: </p>
<pre><code>public void myMethod() throws SpaceInvadersException
{
/* Code that might throw an exception */
}
public void callingMethod()
{
try {
myMethod();
}
catch (SpaceInvadersException exception) {
/* Complicated error handling code */
}
}
</code></pre>
<p>In that case, you need to inform the compiler that <code>myMethod</code> could throw a <code>SpaceInvadersException</code>. This means that you can't call that method without dealing with the exception in some way (<code>try</code>-<code>catch</code> or using the <code>throws</code> keyword on the calling method). If <code>throws</code> weren't there, you could call the method without doing any exception handling, and get an exception that wasn't dealt with anywhere in the program (which would be bad). </p>
<p>Since it is always better to avoid code duplication, it is normally better to palm off your error handling to a <code>try</code>-<code>catch</code> in a much higher level function than it is to deal with it separately in all of the low level methods. That is why this mechanism exists. </p> |
20,254,084 | Plot normal, left and right skewed distribution in R | <p>I want to create 3 plots for illustration purposes:
- normal distribution
- right skewed distribution
- left skewed distribution</p>
<p>This should be an easy task, but I found only <a href="http://www.statmethods.net/advgraphs/probability.html" rel="noreferrer">this link</a>, which only shows a normal distribution. How do I do the rest?</p> | 20,269,784 | 3 | 2 | null | 2013-11-27 22:13:39.79 UTC | 13 | 2016-07-29 08:30:44.333 UTC | 2013-11-27 22:15:03.83 UTC | null | 1,315,767 | null | 1,419,344 | null | 1 | 36 | r|plot|statistics | 56,915 | <p>Finally I got it working, but with both of your help, but I was relying on <a href="http://zoonek2.free.fr/UNIX/48_R/07.html" rel="noreferrer">this site</a>.</p>
<pre><code> N <- 10000
x <- rnbinom(N, 10, .5)
hist(x,
xlim=c(min(x),max(x)), probability=T, nclass=max(x)-min(x)+1,
col='lightblue', xlab=' ', ylab=' ', axes=F,
main='Positive Skewed')
lines(density(x,bw=1), col='red', lwd=3)
</code></pre>
<p><img src="https://i.stack.imgur.com/aRwue.png" alt="enter image description here"></p>
<p>This is also a valid solution:</p>
<pre><code>curve(dbeta(x,8,4),xlim=c(0,1))
title(main="posterior distrobution of p")
</code></pre> |
19,994,874 | Unable to upload new APK file to Android Play store | <p>I'm getting below error while trying to upload new APK file.</p>
<blockquote>
<p>Upload failed</p>
<p>You uploaded a debuggable APK. For security reasons you need to
disable debugging before it can be published in Google Play.</p>
</blockquote> | 20,002,377 | 5 | 3 | null | 2013-11-15 06:30:39.71 UTC | 7 | 2020-01-22 11:50:03.133 UTC | 2013-11-15 14:10:45.337 UTC | null | 2,387,010 | null | 1,270,804 | null | 1 | 29 | android|google-play | 27,298 | <p>In my case I had to add android:debuggable="false" into manifest.. Worked even without few days ago.</p> |
27,580,077 | Does Meteor need either Gulp or Grunt? | <p>So I've been reading about <a href="http://gulpjs.com/" rel="nofollow noreferrer">Gulp</a> and <a href="http://gruntjs.com/" rel="nofollow noreferrer">Grunt</a>, and how they can minify code, compress files, combine files into one, livereload etc. However, <a href="https://www.meteor.com/" rel="nofollow noreferrer">Meteor</a> does all that already, with <a href="http://guide.meteor.com/build-tool.html" rel="nofollow noreferrer">Isobuild</a>.</p>
<p>The reason I'm asking is someone suggested using Gulp with Meteor, and I don't see a need for it. What are some possible reasons why I should run Gulp alongside Meteor? Or it is simply redundant?</p>
<p>If it is not redundant, what features does Gulp has that is not in Isobuild? And will the Meteor team plan to incorporate Gulp into its next versions?</p> | 27,589,753 | 1 | 6 | null | 2014-12-20 12:06:27.353 UTC | 10 | 2016-05-27 03:36:04.12 UTC | 2016-05-27 03:36:04.12 UTC | null | 2,317,532 | null | 2,317,532 | null | 1 | 19 | node.js|meteor|gruntjs|gulp|isobuild | 5,364 | <p>Need is probably not the right word. Whether you want it or not is a different story.</p>
<p>As the comments mentioned above, Meteor include a very clever build system of its own called isobuild, which builds your WHOLE application for you. But there are certainly instances where you may want your own tasks which would best be accomplished through grunt or gulp. (The range of tasks you can accomplish with these is staggering, so I'm only going to list a couple simple common examples.)</p>
<p>The most obvious is going to be for assets you want to put in your public folder. But this is far from an exhaustive list of tasks that you may want to automate on a larger project.</p>
<ul>
<li>Compile SASS files not using the libsass compiler (because it doesn't support all the features)</li>
<li>Compress and optimize images, svg files, favicons, etc.</li>
<li>Create multiple sizes / versions of images</li>
<li>Create Sprite Sheets</li>
<li>Concatenate and minify scripts in your own order / manner</li>
<li>Combine with Bower to manage front end packages that aren't available through atmosphere etc.</li>
</ul>
<p>The way I would approach it is by putting all of this into the private folder, so its avoided by the meteor isobuild build system.</p>
<p>I believe these are enough reasons to not consider Gulp or Grunt redundant, and the range of tasks possible with grunt or gulp are so varied they can't all be listed here. Needless to say IsoBuild is fantastic for what it does, but would not replace everything possible with these task runners, and to my knowledge there are no plans to incorporate Gulp into IsoBuild. IsoBuild is core to what Meteor is, gulp and grunt are very powerful automation tools with thousands of possible uses.</p>
<p>Heres a really great starter for gulp, its super simple to get started with: <a href="http://blog.nodejitsu.com/npmawesome-9-gulp-plugins">NodeJitsu Gulp tutorial</a></p>
<p>So, sure, you don't <strong>need</strong> grunt or gulp, but they could certainly have a productive place in your meteor project and they're definitely worthwhile tools to get to grips with to streamline your dev processes.</p>
<p>If you would like to use either grunt or gulp, this is how I approach structure my project:</p>
<pre><code>Project-folder
|__ webapp // my meteor app lives here
|__ assets // scss / images / svgs
|__ node_modules
| gruntfile.js
| .eslintrc
| package.json
</code></pre>
<p>I then build, minify, and process my assets, with my target directories in <code>webapp/public</code></p>
<p>Note that with full npm support coming in [email protected] this may change, though I'm unclear about whether we'll be able to mvoe this into the project yet.</p> |
15,375,986 | Magento - Module INSERT,UPDATE, DELETE, SELECT code | <p>I created a module and want to used core write and read function to insert,update,delete or select database value with condition, how can I do it without using SQL?
Example:
$customer_id=123
Model=(referral/referral)</p>
<p>SELECT</p>
<pre><code> $collection3 = Mage::getModel('referral/referral')->getCollection();
$collection3->addFieldToFilter('customer_id', array('eq' => $customer_id));
foreach($collection3 as $data1)
{
$ref_cust_id.= $data1->getData('referral_customer_id');
}
</code></pre>
<p>INSERT</p>
<pre><code>$collection1= Mage::getModel('referral/referral');
$collection1->setData('customer_id',$customer_id)->save();
</code></pre>
<p>DELETE,UPDATE(with condition)=???</p> | 15,382,220 | 5 | 0 | null | 2013-03-13 02:29:18.793 UTC | 12 | 2016-09-07 08:29:33.093 UTC | 2013-03-13 06:58:00.177 UTC | null | 727,208 | null | 2,156,564 | null | 1 | 13 | sql|magento|magento-1.7|crud | 47,710 | <p>Suppose, I have a module named <code>mynews</code>.
Here follows the code to <code>select, insert, update, and delete data</code> from the <code>news</code> table.</p>
<p><b><code>INSERT DATA</code></b></p>
<p><code>$data</code> contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.</p>
<pre><code>$data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);
$model = Mage::getModel('mynews/mynews')->setData($data);
try {
$insertId = $model->save()->getId();
echo "Data successfully inserted. Insert ID: ".$insertId;
} catch (Exception $e){
echo $e->getMessage();
}
</code></pre>
<p><b><code>SELECT DATA</code></b></p>
<pre><code>$item->getData() prints array of data from ‘news’ table.
$item->getTitle() prints the only the title field.
</code></pre>
<p>Similarly, to print content, we need to write <code>$item->getContent()</code>.</p>
<pre><code>$model = Mage::getModel('mynews/mynews');
$collection = $model->getCollection();
foreach($collection as $item){
print_r($item->getData());
print_r($item->getTitle());
}
</code></pre>
<p><b><code>UPDATE DATA</code></b></p>
<p><code>$id</code> is the database table row id to be updated.
<code>$data</code> contains array of data to be updated. The key of the array should be the database table’s field name and the value should be the value to be updated.</p>
<pre><code>// $id = $this->getRequest()->getParam('id');
$id = 2;
$data = array('title'=>'hello test','content'=>'test how are you?','status'=>0);
$model = Mage::getModel('mynews/mynews')->load($id)->addData($data);
try {
$model->setId($id)->save();
echo "Data updated successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
</code></pre>
<p><b><code>DELETE DATA</code></b></p>
<p><code>$id</code> is the database table row id to be deleted.</p>
<pre><code>// $id = $this->getRequest()->getParam('id');
$id = 3;
$model = Mage::getModel('mynews/mynews');
try {
$model->setId($id)->delete();
echo "Data deleted successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
</code></pre>
<p>In this way you can perform select, insert, update and delete in your custom module and in any <code>magento code</code>.</p>
<p><strong>Source: <a href="http://blog.chapagain.com.np/magento-how-to-select-insert-update-and-delete-data/" rel="nofollow">http://blog.chapagain.com.np/magento-how-to-select-insert-update-and-delete-data/</a></strong></p> |
15,191,649 | Are thread pools needed for pure Haskell code? | <p>In <a href="http://book.realworldhaskell.org/read/software-transactional-memory.html">Real World Haskell, Chapter 28, Software transactional memory</a>, a concurrent web link checker is developed. It fetches all the links in a webpage and hits every once of them with a HEAD request to figure out if the link is active. A concurrent approach is taken to build this program and the following statement is made:</p>
<blockquote>
<p>We can't simply create one thread per URL, because that may overburden either our CPU or our network connection if (as we expect) most of the links are live and responsive. Instead, we use a fixed number of worker threads, which fetch URLs to download from a queue.</p>
</blockquote>
<p>I do not fully understand why this pool of threads is needed instead of using <code>forkIO</code> for each link. AFAIK, the Haskell runtime maintains a pool of threads and schedules them appropriately so I do not see the CPU being overloaded. Furthermore, in <a href="http://www.haskell.org/pipermail/haskell/2011-April/022735.html">a discussion about concurrency on the Haskell mailing list</a>, I found the following statement going in the same direction:</p>
<blockquote>
<p>The one paradigm that makes no sense in Haskell is worker threads (since the RTS does that
for us); instead of fetching a worker, just forkIO instead.</p>
</blockquote>
<p><strong>Is the pool of threads only required for the network part or there is a CPU reason for it too?</strong></p> | 15,194,731 | 1 | 1 | null | 2013-03-03 22:25:11.613 UTC | 2 | 2013-03-04 04:47:53.163 UTC | null | null | null | null | 1,077,893 | null | 1 | 34 | multithreading|haskell | 1,378 | <p>The core issue, I imagine, is the network side. If you have 10,000 links and forkIO for each link, then you potentially have 10,000 sockets you're attempting to open at once, which, depending on how your OS is configured, probably won't even be possible, much less efficient.</p>
<p>However, the fact that we have green threads that get "virtually" scheduled across multiple os threads (which ideally are stuck to individual cores) doesn't mean that we can just distribute work randomly without regards to cpu usage either. The issue here isn't so much that the scheduling of the CPU itself won't be handled for us, but rather that context-switches (even green ones) cost cycles. Each thread, if its working on different data, will need to pull that data into the cpu. If there's enough data, that means pulling things in and out of the cpu cache. Even absent that, it means pulling things from the cache to registers, etc. </p>
<p>Even if a problem is trivially parallel, it is virtually <em>never</em> the right idea to just break it up as small as possible and attempt to do it "all at once".</p> |
15,356,641 | How to write XML declaration using xml.etree.ElementTree | <p>I am generating an XML document in Python using an <a href="https://docs.python.org/2/library/xml.etree.elementtree.html" rel="noreferrer"><code>ElementTree</code></a>, but the <code>tostring</code> function doesn't include an <a href="http://xmlwriter.net/xml_guide/xml_declaration.shtml" rel="noreferrer">XML declaration</a> when converting to plaintext.</p>
<pre class="lang-python prettyprint-override"><code>from xml.etree.ElementTree import Element, tostring
document = Element('outer')
node = SubElement(document, 'inner')
node.NewValue = 1
print tostring(document) # Outputs "<outer><inner /></outer>"
</code></pre>
<p>I need my string to include the following XML declaration:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
</code></pre>
<p>However, there does not seem to be any documented way of doing this.</p>
<p>Is there a proper method for rendering the XML declaration in an <code>ElementTree</code>?</p> | 15,357,667 | 11 | 0 | null | 2013-03-12 08:42:21.72 UTC | 10 | 2020-10-16 19:49:47.87 UTC | 2017-10-30 16:41:42.15 UTC | null | 3,357,935 | null | 2,002,323 | null | 1 | 90 | python|xml|elementtree | 97,718 | <p>I am surprised to find that there doesn't seem to be a way with <code>ElementTree.tostring()</code>. You can however use <code>ElementTree.ElementTree.write()</code> to write your XML document to a fake file:</p>
<pre><code>from io import BytesIO
from xml.etree import ElementTree as ET
document = ET.Element('outer')
node = ET.SubElement(document, 'inner')
et = ET.ElementTree(document)
f = BytesIO()
et.write(f, encoding='utf-8', xml_declaration=True)
print(f.getvalue()) # your XML file, encoded as UTF-8
</code></pre>
<p>See <a href="https://stackoverflow.com/questions/4997848/emitting-namespace-specifications-with-elementtree-in-python">this question</a>. Even then, I don't think you can get your 'standalone' attribute without writing prepending it yourself.</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.