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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31,025,967 | Code-first migration: How to set default value for new property? | <p>I am using EF6 for storing instances of the <code>report</code> class in my database. The database already contains data. Say I wanted to add a property to <code>report</code>, </p>
<pre><code>public class report {
// ... some previous properties
// ... new property:
public string newProperty{ get; set; }
}
</code></pre>
<p>Now if I go to the package-manager console and execute </p>
<pre><code>add-migration Report-added-newProperty
update-database
</code></pre>
<p>I will get a file in the '/Migrations' folder adding a <code>newProperty</code> column to the table. This works fine. However, on the older entries in the database, the value for the <code>newProperty</code> is now an empty string. But I want it to be, e.g., "old". </p>
<p>So my question is: How do I set default values for new properties (of any type) in the migration script (or elsewhere)?</p> | 31,026,023 | 5 | 1 | null | 2015-06-24 12:01:24.453 UTC | 9 | 2021-03-01 15:53:32.81 UTC | 2016-06-30 00:26:49.747 UTC | null | 1,698,987 | null | 1,514,973 | null | 1 | 65 | c#|.net|entity-framework|entity-framework-6|entity-framework-migrations | 66,160 | <p>If you see the generated migration code you will see <code>AddColumn</code></p>
<pre><code>AddColumn("dbo.report", "newProperty", c => c.String(nullable: false));
</code></pre>
<p>You can add <code>defaultValue</code></p>
<pre><code>AddColumn("dbo.report", "newProperty",
c => c.String(nullable: false, defaultValue: "old"));
</code></pre>
<p>Or add <code>defaultValueSql</code></p>
<pre><code>AddColumn("dbo.report", "newProperty",
c => c.String(nullable: false, defaultValueSql: "GETDATE()"));
</code></pre> |
34,321,128 | Render array of inputs in react | <p>I have an array of emails (as a part of a bigger model). These are displayed in seperate rows witha remove button for each (the address itself can be updated in the input box directly). Unfortunately I dont know how to do this in react when the inputs are renderd using a map function.
(I am converting a meteor blaze project to meteor react).</p>
<p><em>Everything renders but how do I attach to change event so I can update my array of emails? onChange + value need to be set somehow.</em></p>
<p>This is the map function</p>
<pre><code>return this.data.emailGroup.emails.map((email) => {
return (
<div key={email} className="input-group">
<input type="text" className="form-control" onChange={self.handleEmailListChange} value={email}/>
<div className="input-group-btn">
<button type="button"
className="btn btn-default remove-email"><span
className="glyphicon glyphicon-remove"></span></button>
</div>
</div>
);
});
</code></pre>
<p>The initial state(which is populated with data from the db:</p>
<pre><code> getInitialState() {
return {
name : '',
description: '',
emails : [],
newEmailAddress : ''
}
},
</code></pre>
<p>Upon request here is the render method(it requires a getContent method.The getcontent method is there because in meteor I need to wait for data so in the meantime I need a loading state.</p>
<pre><code> getContent() {
return (
<div className="box box-success">
<div className="box-header with-border">
<h3 className="box-title">List of emails</h3>
</div>
<form role="form" className="form-horizontal">
<div className="box-body">
<p>Below is a list of email addresses which are added to this email group. If
you
want
to add more
you can add them one by one by inputting in the box below or add a list into
the
same box (email
addresses have to be seperated by either a space or ;) then press Add to add
to
the
list. You can edit
the addresses directly as well as remove them.</p>
<div className="input-group">
<input type="text" className="form-control"
value={this.state.newEmailAddress}
onChange={this.handleAddNewEmail}
placeholder="Email addresses seperated by a space or a semicolon ; i.e. [email protected];[email protected]"/>
<span className="input-group-btn">
<button type="button" onClick={this.handleAddNewEmailButton} className="btn btn-info btn-flat add-email">Add</button>
</span>
</div>
<br/>
{this.renderEmail()}
</div>
</form>
</div>
)
},
render()
{
var contentStyle = {
minHeight : '946px'
};
return (
<div className="content-wrapper" style={contentStyle}>
<section className="content-header">
<h1>
{this.data.emailGroup? this.data.emailGroup.name : 'hello'}
</h1>
<small> Created by: Christian Klinton</small>
<br/>
<small> Last updated by: Christian Klinton - 2015-11-12 08:10:11</small>
<ol className="breadcrumb">
<li><a href="/emailGroups"><i className="fa fa-dashboard"></i> Home</a></li>
<li><a href="/emailGroups">Email groups</a></li>
<li className="active">{this.data.emailGroup? this.data.emailGroup.name : 'loading'}</li>
</ol>
</section>
<section className="content">
<div className="row">
<div className="col-md-6">
<div className="box box-primary">
<div className="box-header with-border">
<h3 className="box-title">Information</h3>
</div>
<form role="form">
<div className="box-body">
<div className="form-group">
<label htmlFor="inputName">Name</label>
<input type="email" className="form-control" id="name"
onChange={this.handleNameChange}
placeholder="Set the name of the email group" autoComplete="off"
value={this.state.name}/>
</div>
<div className="form-group">
<label>Description</label>
<textarea className="form-control" rows="3" id="description"
placeholder="Enter a description what and how the template is used..."
onChange={this.handleDesriptionChange}
value={this.state.description}
></textarea>
</div>
</div>
</form>
</div>
</div>
<div className="col-md-6">
{this.data.emailGroup? this.getContent() : <p>Loading</p> }
</div>
<div className="form-group">
<div className="col-sm-offset-8 col-sm-4">
<div className="pull-right">
<button className="btn btn-primary">Delete all</button>
<button className="btn btn-primary save">Save</button>
</div>
</div>
</div>
</div>
</section>
</div>
)
}
</code></pre> | 34,321,313 | 3 | 2 | null | 2015-12-16 20:07:33.967 UTC | 2 | 2018-05-08 20:21:49.557 UTC | 2015-12-16 20:17:15.243 UTC | null | 1,476,083 | null | 1,476,083 | null | 1 | 16 | javascript|meteor|reactjs | 45,888 | <p>React requires you to have something unique for every element in the rendered array, it's called a <code>key</code>, and it's an attribute.</p>
<p>If you don't know what to assign to the key, just assign it the array's indexes:</p>
<pre><code>this.props.doors.map((door, index) => (
<div key={index} className="door"></div>
));
</code></pre>
<p>Here's the same solution applied to your problem:</p>
<pre><code>return this.data.emailGroup.emails.map((email, index) => {
return (
<div key={index} className="input-group">
<input type="text"
className="form-control"
onChange={self.handleEmailListChange.bind(this, index)} value={email}/>
</div>
);
});
</code></pre>
<p>Notice how I bound <code>handleEmailListChange</code> to receive the index of the modified email. If <code>handleEmailListChange</code> accepts an index, it can update the modified email within the state:</p>
<pre><code>handleEmailListChange: function(index, event) {
var emails = this.state.emails.slice(); // Make a copy of the emails first.
emails[index] = event.target.value; // Update it with the modified email.
this.setState({emails: emails}); // Update the state.
}
</code></pre> |
10,311,189 | How does decompiling work? | <p>I have heard the term "decompiling" used a few times before, and I am starting to get very curious about how it works. </p>
<p>I have a very general idea of how it works; reverse engineering an application to see what functions it uses, but I don't know much beyond that. </p>
<p>I have also heard the term "<em>disassembler</em>", what is the difference between a disassembler and a decompiler?</p>
<p><strong>So to sum up my question(s):</strong> What exactly is involved in the process of decompiling something? How is it usually done? How complicated/easy of a processes is it? can it produce the exact code? And what is the difference between a decompiler, and a disassembler?</p> | 10,311,416 | 2 | 1 | null | 2012-04-25 07:28:29.02 UTC | 11 | 2018-05-07 08:38:11.123 UTC | 2012-04-26 17:22:49.54 UTC | null | 599,402 | null | 599,402 | null | 1 | 28 | decompiling | 15,757 | <p>Ilfak Guilfanov, the author of <a href="http://www.hex-rays.com/products/decompiler/compare_vs_disassembly.shtml" rel="noreferrer">Hex-Rays Decompiler</a>, gave a speech about the internal working of his decompiler at some con, and here is the <a href="http://www.hex-rays.com/products/ida/support/ppt/decompilers_and_beyond_white_paper.pdf" rel="noreferrer">white paper</a> and a <a href="http://www.hex-rays.com/products/ida/support/ppt/decompilers_and_beyond.ppt" rel="noreferrer">presentation</a>. This describes a nice overview in what are all the difficulties in building a decompiler and how to make it all work.</p>
<p>Apart from that, there are some quite old papers, e.g. the <a href="http://itee.uq.edu.au/~cristina/dcc.html#thesis" rel="noreferrer">classical PhD thesis of Cristina Cifuentes</a>.</p>
<p>As for the complexity, all the "decompiling" stuff depends on the language and runtime of the binary. For example decompiling .NET and Java is considered "done", as there are available free decompilers, that have a very high succeed ratio (they produce the original source). But that is caused by the very specific nature of the virtual machines that these runtimes use.</p>
<p>As for truly compiled languages, like C, C++, Obj-C, Delphi, Pascal, ... the task get much more complicated. Read the above papers for details.</p>
<blockquote>
<p>what is the difference between a disassembler and a decompiler?</p>
</blockquote>
<p>When you have a binary program (executable, DLL library, ...), it consists of processor instructions. The language of these instructions is called <em>assembly</em> (or assembler). In a binary, these instructions are binary encoded, so that the processor can directly execute them. A <em>disassembler</em> takes this binary code and translates it into a text representation. This translation is usually 1-to-1, meaning one instruction is shown as one line of text. This task is complex, but straightforward, the program just needs to know all the different instructions and how they are represented in a binary.</p>
<p>On the other hand, a <em>decompiler</em> does a much harder task. It takes either the binary code or the disassembler output (which is basically the same, because it's 1-to-1) and produces high-level code. Let me show you an example. Say we have this C function:</p>
<pre><code>int twotimes(int a) {
return a * 2;
}
</code></pre>
<p>When you compile it, the compiler first generates an <em>assembly file</em> for that function, it might look something like this:</p>
<pre><code>_twotimes:
SHL EAX, 1
RET
</code></pre>
<p>(the first line is just a label and not a real instruction, <code>SHL</code> does a shift-left operation, which does a quick multiply by two, <code>RET</code> means that the function is done). In the result binary, it looks like this:</p>
<pre><code>08 6A CF 45 37 1A
</code></pre>
<p>(I made that up, not real binary instructions). Now you know, that a <em>disassembler</em> takes you from the binary form to the assembly form. A <em>decompiler</em> takes you from the assembly form to the C code (or some other higher-level language).</p> |
10,441,717 | JavaScript scope in a try block | <p>Say I'm trying to execute this JavaScript snippet. Assume the undeclared vars and methods are declared elsewhere, above, and that <code>something</code> and <code>somethingElse</code> evaluate to boolean-true.</p>
<pre><code>try {
if(something) {
var magicVar = -1;
}
if(somethingElse) {
magicFunction(magicVar);
}
} catch(e) {
doSomethingWithError(e);
}
</code></pre>
<p>My question is: what is the scope of <code>magicVar</code> and is it okay to pass it into <code>magicFunction</code> as I've done?</p> | 10,441,739 | 6 | 1 | null | 2012-05-04 02:00:17.7 UTC | 7 | 2022-09-12 13:58:29.283 UTC | null | null | null | null | 177,541 | null | 1 | 39 | javascript|scope | 33,502 | <p>Javascript has function scope. That means that <code>magicvar</code> will exist from the beginning of the function it's declared in all the way to the end of that function, even if that statement doesn't ever execute. This is called <strong>variable hoisting</strong>. The same thing happens with functions declarations, which in turn is called <strong>function hoisting</strong>.</p>
<p>If the variable is declared in global scope, it will be visible to <em>everything</em>. This is part of the reason why global variables are considered evil in Javascript.</p>
<p>Your example will pass <code>undefined</code> into <code>magicFunction</code> if <code>something</code> is false, because <code>magicVar</code> hasn't been assigned to anything.</p>
<p>While this is technically valid Javascript, it's generally considered bad style and will not pass style checkers like jsLint. Extremely unintuitive Javascript like this will execute without any error</p>
<pre><code>alert(a); //alerts "undefined"
var a;
</code></pre>
<p><strong>POP QUIZ</strong>: What does the following code do?</p>
<pre><code>(function() {
x = 2;
var x;
alert(x);
})();
alert(x);
</code></pre> |
22,492,485 | Javascript error: Cannot read property 'parentNode' of null | <p>The javascript I am using: </p>
<pre><code>javascript: c = '{unit}, ({coords}) {player} |{distance}| {return}';
p = ['Scout', 'LC', 'HC', 'Axe', 'Sword', 'Ram', '***Noble***'];
function V() {
return 1;
}
window.onerror = V;
function Z() {
d = (window.frames.length > 0) ? window.main.document : document;
aid = d.getElementById('editInput').parentNode.innerHTML.match(/id\=(\d+)/)[1];
function J(e) {
vv = e.match(/\d+\|\d+/g);
return (vv ? vv[vv.length - 1].match(/((\d+)\|(\d+))/) : null);
}
function K(e) {
f = parseInt(e, 10);
return (f > 9 ? f : '0' + f);
}
function L(g, e) {
return g.getElementsByTagName(e);
}
function N(g) {
return g.innerHTML;
}
function M(g) {
return N(L(g, 'a')[0]);
}
function O() {
return k.insertRow(E++);
}
function W(f) {
return B.insertCell(f);
}
function P(g, e) {
g.innerHTML = e;
return g;
}
function X(e) {
C = B.appendChild(d.createElement('th'));
return P(C, e);
}
function Y(f) {
return K(f / U) + ':' + K(f % (U) / T) + ':' + K(f % T);
}
U = 3600;
T = 60;
R = 'table';
S = 'width';
s = L(document, R);
for (j = 0; j < s.length; j++) {
s[j].removeAttribute(S);
if (s[j].className == 'main') {
s = L(L(s[j], 'tbody')[0], R);
break;
}
}
D = 0;
for (j = 0; j < s.length; j++) {
s[j].removeAttribute(S);
if (s[j].className = 'vis') {
k = s[j];
if (t = k.rows) {
D = t.length;
break;
}
}
}
for (E = 0; E < D; E++) {
l = t[E];
m = (u = l.cells) ? u.length : 0;
if (m) {
u[m - 1].colSpan = 5 - m;
if (N(u[0]) == 'Arrival:') {
Q = new Date(N(u[1]).replace(/<.*/i, ''));
} else {
if (N(u[0]) == 'Arrival in:') {
v = N(u[1]).match(/\d+/ig);
}
}
if (E == 1) {
G = M(u[2]);
}
if (E == 2) {
w = J(M(u[1]));
}
if (E == 4) {
x = J(M(u[1]));
}
}
}
y = v[0] * U + v[1] * T + v[2] * 1;
n = w[2] - x[2];
o = w[3] - x[3];
F = Math.sqrt(n * n + o * o);
H = F.toFixed(2);
E = D - 2;
s = L(k, 'input');
i = s[1];
h = s[0];
h.size = T;
B = O();
P(W(0), 'Distance:').colSpan = 2;
P(W(1), H + ' Fields').colSpan = 2;
B = O();
X('Unit');
X('Sent');
X('Duration');
X('Name to');
c = c.replace(/\{coords\}/i, w[1]).replace(/\{distance\}/i, H).replace(/\{player\}/i, G);
for (j in p) {
z = Math.round([9.00000000, 10.00000000, 11.00000000, 18.0000000015, 22.00000000, 30.00000000, 35.0000000][j] * T * F);
A = z - y;
if (A > 0) {
I = Y(z);
B = O();
P(W(0), p[j]);
P(W(1), A < T && 'just now' || A < U && Math.floor(A / T) + ' mins ago' || Y(A) + ' ago');
P(W(2), I);
C = W(3);
q = C.appendChild(i.cloneNode(1));
r = C.appendChild(h.cloneNode(1));
r.id = 'I' + j;
r.value = c.replace(/\{duration\}/i, I).replace(/\{sent\}/i, new Date(Q.valueOf() - z * 1000).toLocaleString().replace(/.\d{4}/i, '').replace(/(\w{3})\w*/i, '$1')).replace(/\{return\}/i, new Date(Q.valueOf() + z * 1000).toString().replace(/\w+\s*/i, '').replace(/(\d*:\d*:\d*)(.*)/i, '$1')).replace(/\{unit\}/i, p[j]).replace(/\{attack_id\}/i, aid);
q.onmousedown = new Function('h.value=d.getElementById(\'I' + j + '\').value;');
}
}
}
Z();
</code></pre>
<p>The error I receive:</p>
<blockquote>
<p>Uncaught TypeError: Cannot read property 'parentNode' of null</p>
</blockquote>
<p>A URL looks like this:</p>
<p><code>game.php?village=2100&id=4348754&type=other&screen=info_command</code></p> | 22,492,596 | 3 | 1 | null | 2014-03-18 22:35:56.44 UTC | 2 | 2022-07-29 09:55:35.78 UTC | 2017-08-28 12:15:17.893 UTC | null | 4,720,935 | null | 3,230,127 | null | 1 | 20 | javascript | 119,805 | <p>There are two possibilities:</p>
<ol>
<li><code>editInput</code> is a typo, and the actual id of that element is different (ids are case-sensitive).</li>
<li>You are executing this code while the DOM is not ready. To prevent this, execute the code just before the <code></body></code> closing tag, or wrap it in an event handler for the <code>load</code> event of <code>window</code> or the <code>DOMContentLoaded</code> event of <code>document</code>.</li>
</ol>
<p><strong>EDITED</strong> How to wrap your code:</p>
<pre><code>window.onload = function() {
//your code here
};
</code></pre> |
7,159,644 | Does paramiko close ssh connection on a non-paramiko exception | <p>I'm debugging some code, which is going to result in me constantly logging in / out of some external sftp servers. Does anyone know if paramiko automatically closes a ssh / sftp session on the external server if a non-paramiko exception is raised in the code? I can't find it in the docs and as the connections have to be made fairly early in each iteration I don't want to end up with 20 open connections.</p> | 8,293,225 | 2 | 0 | null | 2011-08-23 10:31:21.123 UTC | 6 | 2017-02-17 13:21:42.023 UTC | 2014-02-04 13:56:19.7 UTC | null | 321,731 | null | 458,741 | null | 1 | 18 | python|ssh|paramiko | 44,462 | <p>No, paramiko will not automatically close the ssh / sftp session. It doesn't matter if the exception was generated by paramiko code or otherwise; there is nothing in the paramiko code that catches any exceptions and automatically closes them, so you have to do it yourself.</p>
<p>You can ensure that it gets closed by wrapping it in a try/finally block like so:</p>
<pre><code>client = None
try:
client = SSHClient()
client.load_system_host_keys()
client.connect('ssh.example.com')
stdin, stdout, stderr = client.exec_command('ls -l')
finally:
if client:
client.close()
</code></pre> |
7,465,590 | NameError: name 're' is not defined | <p>I am very new to python. Very new. I copied the following from a tutorial</p>
<pre><code>#!/usr/bin/python
from urllib import urlopen
from BeautifulSoup import BeautifulSoup
webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read
patFinderTitle = re.compile('<title>(.*)</title>')
patFinderLink = re.compile('<link rel.*href="(.*)"/>')
findPatTitle = re.findall(patFinderTitle,webpage)
findPatLink = re.findall(patFinderLink,webpage)
listIterator = []
listIterator[:] = range(2,16)
for i in listIterator:
print findPatTitle[i]
print findPatLink[i]
print "\n"
</code></pre>
<p>I get the error: </p>
<pre><code>Traceback (most recent call last):
File "test.py", line 8, in <module>
patFinderTitle = re.compile('<title>(.*)</title>')
NameError: name 're' is not defined
</code></pre>
<p>What am I doing wrong?</p> | 7,465,610 | 2 | 4 | null | 2011-09-19 01:17:00.49 UTC | 4 | 2018-09-21 12:37:24.543 UTC | 2018-09-21 12:32:46.28 UTC | null | 1,222,951 | null | 522,962 | null | 1 | 28 | python | 98,213 | <p>You need to import <a href="http://docs.python.org/library/re.html" rel="noreferrer">regular expression module</a> in your code</p>
<pre><code>import re
re.compile('<title>(.*)</title>')
</code></pre> |
32,076,823 | String Interpolation in Visual Studio 2015 and IFormatProvider (CA1305) | <p>The new string interpolation style in Visual Studio 2015 is this:</p>
<pre><code>Dim s = $"Hello {name}"
</code></pre>
<p>But if I use this the code analysis tells me I break <a href="https://msdn.microsoft.com/en-us/library/ms182190.aspx">CA1305: Specify IFormatProvider</a></p>
<p>In the old times I did it like this:</p>
<pre><code>Dim s = String.Format(Globalization.CultureInfo.InvariantCulture, "Hello {0}", name)
</code></pre>
<p>But how can it be done with the new style?</p>
<p>I have to mention that I'm looking for a solution for .Net 4.5.2 (for .Net 4.6 <a href="https://stackoverflow.com/a/32077060/254041">dcastro has the answer</a>)</p> | 56,011,872 | 4 | 2 | null | 2015-08-18 15:39:15.557 UTC | 8 | 2019-10-25 12:38:49.933 UTC | 2015-08-19 08:59:40.073 UTC | null | 254,041 | null | 254,041 | null | 1 | 32 | c#|.net|vb.net|visual-studio-2015|string.format | 8,487 | <p>Microsoft has made it easier to use <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated" rel="noreferrer">string interpolation</a> and comply with <a href="https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1305-specify-iformatprovider?view=vs-2019" rel="noreferrer">CA1305: Specify IFormatProvider</a>.</p>
<p>If you are using C# 6 or later, you have access to the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-static" rel="noreferrer"><code>using static</code></a> directive.</p>
<p>In addition, the static method <code>FormattableString.Invariant</code> is available for <a href="https://docs.microsoft.com/en-us/dotnet/api/system.formattablestring.invariant?view=netstandard-1.3" rel="noreferrer">.NET Standard 1.3</a>, <a href="https://docs.microsoft.com/en-us/dotnet/api/system.formattablestring.invariant?view=netcore-1.0" rel="noreferrer">.NET Core 1.0</a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.formattablestring.invariant?view=netframework-4.6" rel="noreferrer">.NET Framework 4.6</a> and later. Putting the two together allows you to do this:</p>
<pre><code>using static System.FormattableString;
string name = Invariant($"Hello {name}");
</code></pre>
<p>If, however, your goal is for the interpolation to be done via the current culture, then a companion static method <code>FormattableString.CurrentCulture</code> is proposed in <a href="https://docs.microsoft.com/en-us/dotnet/api/system.formattablestring.currentculture?view=netcore-3.0" rel="noreferrer">.NET Core 3.0</a> (currently, Preview 5):</p>
<pre><code>using static System.FormattableString;
string name = CurrentCulture($"Hello {name}");
</code></pre> |
3,903,079 | Does "default" serialization in C# serialize static fields? | <p>By "default" I mean just using the [Serializable] attribute on the class. I want to say that no, static fields would not be serialized, but I'm not exactly sure.</p> | 3,903,098 | 1 | 1 | null | 2010-10-11 01:55:44.013 UTC | 1 | 2010-10-11 02:00:36.52 UTC | null | null | null | null | 388,739 | null | 1 | 29 | c#|serialization|static | 7,190 | <p>No; static fields are not serialized.</p>
<p>.Net serialization serializes instances; static fields do not belong to an instance.</p> |
21,140,931 | generator-karma does not satisfy its siblings' peerDependencies requirements | <p>The same notorious error </p>
<pre>
npm ERR! peerinvalid The package generator-karma does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants generator-karma@~0.6.0
npm ERR! peerinvalid Peer [email protected] wants generator-karma@~0.5.0
npm ERR! System Darwin 12.5.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "generator-angular"
npm ERR! cwd /Users/dmitrizaitsev/Dropbox/Priv/APP/my-yo-project
npm ERR! node -v v0.10.24
npm ERR! npm -v 1.3.21
npm ERR! code EPEERINVALID
</pre>
<p>comes from installation various packages, e.g. for</p>
<pre><code>npm update -g yo
</code></pre>
<p>The only found advice to uninstall <code>generator-karma</code> does not help - it re-installs back.</p>
<p>Any better explanation of why it happens and working solution?</p> | 24,051,080 | 6 | 2 | null | 2014-01-15 15:06:12.317 UTC | 6 | 2016-04-09 06:00:03.073 UTC | null | null | null | null | 1,614,973 | null | 1 | 28 | node.js|angularjs|generator|yeoman|karma-runner | 15,867 | <p>You need to update all of your globally installed NPM packages. Run this command from your console:</p>
<pre><code>npm update -g
</code></pre>
<p>This command will update all the packages listed to the latest version (specified by the tag config).</p>
<p>It will also install missing packages.</p>
<p>When you specify the -g flag, this command will update globally installed packages. If no package name is specified, all packages in the specified location (global or local) will be updated.</p> |
28,089,215 | Two ways to check if a list is empty - differences? | <p>I have a short question.</p>
<p>Lets assume we have a <code>List</code> which is an <code>ArrayList</code> called <code>list</code>. We want to check if the list is empty.</p>
<p>What is the difference (if there is any) between:</p>
<pre><code>if (list == null) { do something }
</code></pre>
<p>and</p>
<pre><code>if (list.isEmpty()) { do something }
</code></pre>
<p>I'm working on an ancient code (written around 2007 by someone else) and it is using the <code>list == null</code> construction. But why use this construction when we have <code>list.isEmpty()</code> method...</p> | 28,089,242 | 4 | 2 | null | 2015-01-22 12:48:54.3 UTC | 6 | 2022-09-10 12:44:32.227 UTC | null | null | null | null | 4,012,392 | null | 1 | 23 | java|list | 87,903 | <p>The first tells you whether the <code>list</code> variable has been assigned a List instance or not.</p>
<p>The second tells you if the List referenced by the <code>list</code> variable is empty.
If <code>list</code> is null, the second line will throw a <code>NullPointerException</code>.</p>
<p>If you want to so something only when the list is empty, it is safer to write :</p>
<pre><code>if (list != null && list.isEmpty()) { do something }
</code></pre>
<p>If you want to do something if the list is either null or empty, you can write :</p>
<pre><code>if (list == null || list.isEmpty()) { do something }
</code></pre>
<p>If you want to do something if the list is not empty, you can write :</p>
<pre><code>if (list != null && !list.isEmpty()) { do something }
</code></pre> |
1,417,782 | How to run iPhone program with Zombies instrument? | <p>I'm running XCode 3.2 on Snow Leopard and I'm trying to run the Zombies instrument against my app but the selection is grayed out and I don't know why. I know about the NSZombieEnabled environment variable. I have that set to YES on my application. I'm not sure if this matters, but, the app is an app that I started developing on Leopard with the previous version of XCode. Here is a screenshot of what my menu looks like:</p>
<p><img src="https://i.stack.imgur.com/bl9HG.png" alt="ScreenShot"></p> | 3,091,433 | 3 | 4 | null | 2009-09-13 13:46:18.65 UTC | 23 | 2015-06-20 18:20:35.21 UTC | 2015-06-20 18:20:35.21 UTC | null | 1,159,643 | null | 148,208 | null | 1 | 29 | iphone|objective-c|xcode|instruments | 18,612 | <p><strong>You need to launch the Instruments application with the Zombies instrument from outside of XCode</strong></p>
<p>This is how you can do it:</p>
<p>The Instruments application is usually located inside <code>/Developer/Applications/</code>, but you can also use Spotlight to find it.</p>
<p>When Instruments starts you should be presented with a screen that asks you to choose a template for the new Trace Document.</p>
<p>Select: <code>iPhone Simulator > Memory > Zombies</code></p>
<p>Next you need to choose a target.</p>
<p>Go to: <code>Chose target > Chose target > Chose target...</code> </p>
<p>Now you need to select the application file:<br>
<code><Path to your iPhone project>/build/Debug-iphonesimulator/<Application name></code><br>
and press <code>Chose</code>.</p>
<p>Now you are all set.</p>
<p>To launch you application press the <code>Record</code> button.</p>
<p>A few <strong>Side Notes</strong>:</p>
<ul>
<li>I used XCode 3.2.3 on Mac OS X 10.6.3, but I believe it works the same on previous versions.</li>
<li>The Zombies instrument only works with the simulator.</li>
<li>The Zombies instrument cannot be used with the Leaks instrument because all the zombies would appear as leaks.</li>
<li>I would also like to know why the menu in XCode is grayed out.</li>
</ul> |
2,158,516 | Delay before 'O' opens a new line? | <p>I've noticed that, occasionally, when I use <kbd>O</kbd> (capital 'o') to create a new line and go into insert mode, there is a short delay before anything happens.</p>
<p>Is this common? Is there any way to change it?</p>
<p>Both <code>:map O</code> and <code>:imap O</code> show "No mapping found", so I don't think it's a strange mapping.</p> | 2,158,610 | 3 | 4 | null | 2010-01-28 22:33:26.76 UTC | 29 | 2013-06-10 11:36:33.54 UTC | 2013-06-10 11:36:33.54 UTC | anon | 1,076,493 | null | 71,522 | null | 1 | 89 | vim | 10,541 | <p>It's because the <code>'esckeys'</code> option is enabled (a consequence of <code>nocompatible</code> as I just discovered). When you press <kbd>^[</kbd><kbd>O</kbd>, there's a small delay as it figures out if you're using an arrow/function key or if you just meant those two keys in sequence.</p>
<p>One solution is to disable that option and give up on the arrow keys in insert mode.<br>
Another is to set <code>'timeoutlen'</code> to something less than 1000, maybe 100 (but be careful over slow connections).<br>
Another is to use <kbd>^C</kbd> instead of <kbd>^[</kbd> to leave insert mode.</p> |
8,933,634 | Must declare the scalar variable "@UserName" | <p>I keep getting an error that I don't understand.</p>
<blockquote>
<p>Must declare the scalar variable "@varname"</p>
</blockquote>
<p>My aim is to create a login page that uses 2 textboxes and a button, where it checks if the user exits based on the information stored in a SQL database.</p>
<p>This is where I think the problem is coming from:</p>
<pre><code>private bool DBConnection(string userName, string password)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
//string cmdString = ("SELECT UserName, Password FROM Users WHERE UserName ='" + userName +
// "'AND Password ='" + password + "'"); //REMOVED AS THIS IS PRONE TO SQL INJECTIONS
string cmdString = ("SELECT * FROM Users WHERE UserName = @uname AND Password = @pw");
SqlCommand cmd = new SqlCommand(cmdString, conn);
cmd.Parameters.Add("uname", SqlDbType.VarChar).Value = userName;
cmd.Parameters.Add("pw", SqlDbType.VarChar).Value = password;
DataSet loginCredentials = new DataSet();
SqlDataAdapter dataAdapter;
try
{
if (conn.State.Equals(ConnectionState.Closed))
{
conn.Open();
dataAdapter = new SqlDataAdapter(cmdString, conn);
dataAdapter.Fill(loginCredentials);
conn.Close();
if (loginCredentials != null)
{
if (loginCredentials.Tables[0].Rows.Count > 0)
{
return true;
}
else
{
lblMessage.Text = "Incorrect Username or Password";
lblMessage.Visible = true;
}
}
}
}
catch (Exception err)
{
lblMessage.Text = err.Message.ToString() + " Error connecting to the Database // " + cmd.Parameters.Count;
lblMessage.Visible = true;
return false;
}
return false;
}
</code></pre>
<p>specifically where <code>dataAdapter.Fill(loginCredentials);</code> is being executed.</p>
<p>The commented-out statement works successfully in logging in a user with the correct username and password, but as far as I know is not secure, as it's vulnerable to SQL injections and this is why I'm trying to parameterize the SQL statement.</p>
<p>error screenshot below:
<a href="https://i.stack.imgur.com/w0VG8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w0VG8.png" alt="Error screenshot" /></a></p> | 8,936,511 | 5 | 1 | null | 2012-01-19 21:35:52.543 UTC | null | 2021-02-01 23:18:13.487 UTC | 2021-02-01 23:16:50.923 UTC | null | 2,756,409 | null | 1,159,472 | null | 1 | 5 | c#|sql|asp.net|database|authentication | 56,977 | <p>You should pass the sqlcommand to the dataAdapter because in your case the sqlcommand (cmd) has more information than mere commandtext and connectionstring. Your code may look like the following:</p>
<pre><code>private bool DBConnection(string userName, string password)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
//string cmdString = ("SELECT UserName, Password FROM Users WHERE UserName ='" + userName +
// "'AND Password ='" + password + "'"); //REMOVED AS THIS IS PRONE TO SQL INJECTIONS
string cmdString = ("SELECT * FROM Users WHERE UserName = @uname AND Password = @pw");
SqlCommand cmd = new SqlCommand(cmdString, conn);
cmd.Parameters.Add("uname", SqlDbType.VarChar).Value = userName;
cmd.Parameters.Add("pw", SqlDbType.VarChar).Value = password;
DataSet loginCredentials = new DataSet();
SqlDataAdapter dataAdapter;
try
{
if (conn.State.Equals(ConnectionState.Closed))
{
conn.Open();
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(loginCredentials);
conn.Close();
if (loginCredentials != null)
{
if (loginCredentials.Tables[0].Rows.Count > 0)
{
return true;
}
else
{
lblMessage.Text = "Incorrect Username or Password";
lblMessage.Visible = true;
}
}
}
}
catch (Exception err)
{
lblMessage.Text = err.Message.ToString() + " Error connecting to the Database // " + cmd.Parameters.Count;
lblMessage.Visible = true;
return false;
}
return false;
}
</code></pre> |
8,810,036 | Complex data structures Redis | <p>Lets say I have a hash of a hash e.g.</p>
<pre><code>$data = {
'harry' : {
'age' : 25,
'weight' : 75,
},
'sally' : {
'age' : 25,
'weight' : 75,
}
}
</code></pre>
<ol>
<li>What would the 'usual' way to store such a data structure (or would you not?)</li>
<li>Would you be able to directly get a value (e.g. get harry : age ?</li>
<li>Once stored could you directly change the value of a sub key (e.g. sally : weight = 100)</li>
</ol> | 8,810,935 | 3 | 1 | null | 2012-01-10 20:26:20.753 UTC | 19 | 2016-06-27 06:47:43.717 UTC | 2016-06-27 06:47:43.717 UTC | null | 1,031,939 | null | 652,449 | null | 1 | 67 | redis | 48,801 | <blockquote>
<p>What would the 'usual' way to store such a data structure (or would
you not?)</p>
</blockquote>
<p>For example harry and sally would be stored each in separate <a href="http://redis.io/commands#hash" rel="noreferrer">hashes</a> where fields would represent their properties like age and weight. Then <a href="http://redis.io/commands#set" rel="noreferrer">set</a> structure would hold all the members (harry, sally, ...) which you have stored in redis.</p>
<blockquote>
<p>Would you be able to directly get a value (e.g. get harry : age ?)</p>
</blockquote>
<p>Yes, see <a href="http://redis.io/commands/hget" rel="noreferrer">HGET</a> or <a href="http://redis.io/commands/hmget" rel="noreferrer">HMGET</a> or <a href="http://redis.io/commands/hgetall" rel="noreferrer">HGETALL</a>.</p>
<blockquote>
<p>Once stored could you directly change the value of a sub key (e.g.
sally : weight = 100)</p>
</blockquote>
<p>Yes, see <a href="http://redis.io/commands/hset" rel="noreferrer">HSET</a>.</p> |
1,053,207 | How to implement TDD in ASP.NET WebForms | <p>I know that the reason that Microsoft came out with ASP.NET MVC was to make it simpler to do Test Driven Design (TDD) for ASP.NET. However, I have a rather large brown field (existing) application in ASP.NET WebForms that I would love to implement some TDD type functionality in. I'm assuming that there IS a way to do this, but what are some viable options?</p> | 1,053,304 | 4 | 2 | null | 2009-06-27 17:03:10.32 UTC | 17 | 2011-01-06 16:33:52.3 UTC | null | null | null | null | 116,620 | null | 1 | 31 | asp.net|webforms|tdd | 8,317 | <p>Microsoft introduced ASP.NET MVC because they thought they could make money from an untapped market - those who feel that Web Forms are too "heavyweight", and who are programming using a lighter-weight framework. This includes those who are accustomed to the MVC paradigm.</p>
<p>It also includes those who couldn't figure out how to do unit tests in web forms, and who want to use unit tests and TDD.</p>
<p>The way to do it with web forms, as with anything else, is to separate everything but the UI code into separate classes in a class library. Use TDD to develop those classes.</p>
<p>The next layer of controversy is whether it's necessary to use TDD to develop the remainder of the code: the markup, client-side code, user interactions, etc. My answer is that if you've got the rest isolated and tested, that it's not worth the trouble to use TDD for this.</p>
<p>Consider: your pages need to have a particular appearance. Are you going to write a failing unit test to prove that you are using CSS correctly? To prove that you're using the correct CSS styles? I don't think so.</p>
<hr>
<p>To clarify: In TDD, we start with a failing unit test. We then make the simplest possible changes that will make the test succeed.</p>
<p>Imagine using TDD for a web page. What failing tests will you produce?</p>
<ol>
<li>Test that page is well-formed HTML</li>
<li>Test that page includes the correct title</li>
<li>Test that page includes
<ol>
<li>"Enter ID" label</li>
<li>An id textbox</li>
<li>A data grid</li>
<li>A "Go" button</li>
</ol></li>
<li>Test that data grid is empty after a GET</li>
<li>Test that grid loads with data from customer 1 when "1" is entered into the text box and "Go" is clicked.</li>
</ol>
<p>And none of the above tests for the appearance of the page. None of it tests the client-side behavior of any JavaScript on the page.</p>
<p>I think that's silly. Instead, test your DAL method that retrieves data based on the ID. Make sure it returns the correct ID for id 1. Then, how long will it take to manually test the page to make sure it looks correct, you can enter the "1" and click "Go", and that the data that appears in the grid is the correct data for customer 1?</p>
<p>Test-Driven Development and automated unit tests are meant to test behavior. The UI of a web form is mostly declarative. There's a large "impedance mismatch" here.</p> |
525,855 | Moving focus from JTextArea using tab key | <p>As stated, I want to change the default TAB behaviour within a <code>JTextArea</code> (so that it acts like a <code>JTextField</code> or similar component)</p>
<p>Here's the event action</p>
<pre><code>private void diagInputKeyPressed(java.awt.event.KeyEvent evt) {
if(evt.KEY_PRESSED == java.awt.event.KeyEvent.VK_TAB) {
actionInput.transferFocus();
}
}
</code></pre>
<p>And here's the listener</p>
<pre><code>diagInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
diagInputKeyPressed(evt);
}
});
</code></pre>
<p>I've tried evt.KEY_TYPED as well with no joy.</p>
<p>Any ideas?</p>
<p>quick edit: I've also tried <code>requestFocus()</code> in place of <code>transferFocus()</code></p> | 525,867 | 1 | 1 | null | 2009-02-08 14:50:19.733 UTC | 10 | 2014-06-20 04:55:47.54 UTC | 2012-05-12 14:05:46.433 UTC | null | 613,495 | tag | null | null | 1 | 32 | java|swing|netbeans | 17,947 | <p>According to <a href="http://www.koders.com/java/fidEFE6DD3BBD50DC8AAAE60012E847110CBE3EF7A8.aspx?s=mdef%3Ainsert" rel="noreferrer">this class</a>:</p>
<pre><code>/**
* Some components treat tabulator (TAB key) in their own way.
* Sometimes the tabulator is supposed to simply transfer the focus
* to the next focusable component.
* <br/>
* Here s how to use this class to override the "component's default"
* behavior:
* <pre>
* JTextArea area = new JTextArea(..);
* <b>TransferFocus.patch( area );</b>
* </pre>
* This should do the trick.
* This time the KeyStrokes are used.
* More elegant solution than TabTransfersFocus().
*
* @author kaimu
* @since 2006-05-14
* @version 1.0
*/
public class TransferFocus {
/**
* Patch the behaviour of a component.
* TAB transfers focus to the next focusable component,
* SHIFT+TAB transfers focus to the previous focusable component.
*
* @param c The component to be patched.
*/
public static void patch(Component c) {
Set<KeyStroke>
strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB")));
c.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes);
strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB")));
c.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes);
}
}
</code></pre>
<p>Note that <code>patch()</code> can be even shorter, according to <a href="https://stackoverflow.com/users/411282/joshua-goldberg">Joshua Goldberg</a> in <a href="https://stackoverflow.com/questions/525855/moving-focus-from-jtextarea-using-tab-key/525867#comment37587468_525867">the comments</a>, since the goal is to get back default behaviors overridden by <code>JTextArea</code>:</p>
<pre><code>component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
component.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
</code></pre>
<p>This is used in question "<a href="https://stackoverflow.com/a/5043957/6309">How can I modify the behavior of the tab key in a <code>JTextArea</code>?</a>"</p>
<hr>
<p>The <a href="http://www.koders.com/java/fid0F02F3C453624EDF1564C356CC30EFC1561774E9.aspx?s=mdef%3ainsert" rel="noreferrer">previous implementation</a> involved indeed a <code>Listener</code>, and the a <code>transferFocus()</code>:</p>
<pre><code> /**
* Override the behaviour so that TAB key transfers the focus
* to the next focusable component.
*/
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_TAB) {
System.out.println(e.getModifiers());
if(e.getModifiers() > 0) a.transferFocusBackward();
else a.transferFocus();
e.consume();
}
}
</code></pre>
<p><code>e.consume();</code> might have been what you missed to make it work in your case.</p> |
55,788,714 | Deploying to Cloud Run with a custom service account failed with iam.serviceaccounts.actAs error | <p>I have created a custom service account <code>travisci-deployer@PROJECT_ID.iam.gserviceaccount.com</code> on my project and gave it the <strong>Cloud Run Admin</strong> role:</p>
<pre class="lang-sh prettyprint-override"><code>gcloud projects add-iam-policy-binding "${PROJECT_ID}" \
--member="serviceAccount:${SERVICE_ACCOUNT_EMAIL}" \
--role="roles/run.admin"
</code></pre>
<p>Then I set this service account as the identity for my gcloud commands:</p>
<pre class="lang-sh prettyprint-override"><code>gcloud auth activate-service-account --key-file=google-key.json
</code></pre>
<p>But when I ran <code>gcloud beta run deploy</code> command, I got an error about the "Compute Engine default service account" not having <code>iam.serviceAccounts.actAs</code> permission:</p>
<pre class="lang-sh prettyprint-override"><code>gcloud beta run deploy -q "${SERVICE_NAME}" \
--image="${CONTAINER_IMAGE}" \
--allow-unauthenticated
</code></pre>
<pre><code>Deploying container to Cloud Run service [$APP_NAME] in project [$PROJECT_ID] region [us-central1]
Deploying...
Deployment failed
ERROR: (gcloud.beta.run.deploy) PERMISSION_DENIED: Permission 'iam.serviceaccounts.actAs'
denied on service account [email protected]
</code></pre>
<p>This seems weird to me (because I'm not using the GCE default service account identity, although it's used by Cloud Run app once the app is deployed).</p>
<p>So the <code>[email protected]</code> account is being used for the API call, and not my <code>travisci-deployer@PROJECT_ID.iam.gserviceacount</code> service account configured on <code>gcloud</code>?</p>
<p>How can I address this?</p> | 55,788,899 | 5 | 0 | null | 2019-04-22 03:12:40.033 UTC | 5 | 2022-09-22 15:02:45.357 UTC | 2022-01-21 10:40:47.577 UTC | null | 8,172,439 | null | 54,929 | null | 1 | 31 | docker|google-cloud-platform|gcloud|google-cloud-run|google-iam | 13,445 | <p><strong>TLDR: Add <em>Cloud Run Admin</em> and <em>Service Account User</em> roles to your service account</strong>.</p>
<p>If we read the docs in detail for the IAM Reference page for Cloud Run which is found <a href="https://cloud.google.com/run/docs/reference/iam/roles#additional-configuration" rel="noreferrer">here</a>, we find the following text:</p>
<blockquote>
<p>A user needs the following permissions to deploy new Cloud Run
services or revisions:</p>
<ul>
<li><code>run.services.create</code> and <code>run.services.update</code> on the project level.
Typically assigned through the <code>roles/run.admin</code> role. It can be changed
in the project permissions admin page.</li>
<li><code>iam.serviceAccounts.actAs</code> for
the Cloud Run runtime service account. By default, this is
<code>[email protected]</code>. The permission
is typically assigned through the <code>roles/iam.serviceAccountUser</code> role.</li>
</ul>
</blockquote>
<p>I think these extra steps explain the story as you see it.</p> |
19,472,747 | Convert Linear scale to Logarithmic | <p>I have a linear scale that ranges form 0.1 to 10 with increments of change at 0.1:<br />
|----------[]----------|<br>
0.1 5.0 10</p>
<p>However, the output really needs to be:<br />
|----------[]----------|<br>
0.1 1.0 10 (logarithmic scale)</p>
<p>I'm trying to figure out the formula needed to convert the 5 (for example) to 1.0.
Consequently, if the dial was shifted halfway between 1.0 and 10 (real value on linear scale being 7.5), what would the resulting logarithmic value be? Been thinking about this for hours, but I have not worked with this type of math in quite a few years, so I am really lost. I understand the basic concept of log<sub>10</sub>X = 10<sup>y</sup>, but that's pretty much it.</p>
<p>The psuedo-value of 5.0 would become 10 (or 10<sup>1</sup>) while the psuedo-value of 10 would be 10<sup>10</sup>. So how to figure the pseudo-value <em>and</em> resulting logarithmic value of, let's say, the 7.5?</p>
<p>Let me know if addition information is needed.</p>
<p>Thanks for any help provided; this has beaten me.</p> | 19,472,811 | 2 | 0 | null | 2013-10-20 00:50:15.993 UTC | 25 | 2022-01-12 16:56:07.24 UTC | 2013-10-21 11:43:16.457 UTC | null | 1,513,458 | null | 1,513,458 | null | 1 | 51 | math|logarithm | 76,839 | <h2>Notation</h2>
<p>As is the convention both in mathematics and programming, the "log" function is taken to be base-e. The "exp" function is the exponential function. Remember that these functions are inverses we take the functions as:</p>
<blockquote>
<p>exp : ℝ → ℝ<sup>+</sup>, and</p>
<p>log : ℝ<sup>+</sup> → ℝ.</p>
</blockquote>
<h2>Solution</h2>
<p>You're just solving a simple equation here:</p>
<blockquote>
<p>y = a exp bx</p>
</blockquote>
<p>Solve for <em>a</em> and <em>b</em> passing through the points x=0.1, y=0.1 and x=10, y=10.</p>
<p>Observe that the ratio y<sub>1</sub>/y<sub>2</sub> is given by:</p>
<blockquote>
<p>y<sub>1</sub>/y<sub>2</sub> = (a exp bx<sub>1</sub>) / (a exp bx<sub>2</sub>) = exp b(x<sub>1</sub>-x<sub>2</sub>)</p>
</blockquote>
<p>Which allows you to solve for <em>b</em></p>
<blockquote>
<p>b = log (y<sub>1</sub>/y<sub>2</sub>) / (x<sub>1</sub>-x<sub>2</sub>)</p>
</blockquote>
<p>The rest is easy.</p>
<blockquote>
<p>b = log (10 / 0.1) / (10 - 0.1) = 20/99 log 10 ≈ 0.46516870565536284</p>
<p>a = y<sub>1</sub> / exp bx<sub>1</sub> ≈ 0.09545484566618341</p>
</blockquote>
<h2>More About Notation</h2>
<p>In your career you will find people who use the convention that the log function uses base e, base 10, and even base 2. <strong>This does not mean that anybody is right or wrong.</strong> It is simply a <em>notational convention</em> and everybody is free to use the notational convention that they prefer.</p>
<p>The convention in both mathematics and computer programming is to use base e logarithm, and using base e simplifies notation in this case, which is why I chose it. It is not the same as the convention used by calculators such as the one provided by Google and your TI-84, but then again, calculators are for engineers, and engineers use different notation than mathematicians and programmers.</p>
<p>The following programming languages include a base-e log function in the standard library.</p>
<ul>
<li><p>C <a href="http://www.cplusplus.com/reference/cmath/log/" rel="noreferrer"><code>log()</code></a> (and C++, by inclusion)</p>
</li>
<li><p>Java <a href="http://docs.oracle.com/javase/6/docs/api/" rel="noreferrer"><code>Math.log()</code></a></p>
</li>
<li><p>JavaScript <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/log" rel="noreferrer"><code>Math.log()</code></a></p>
</li>
<li><p>Python <a href="http://docs.python.org/3/library/math.html#math.log" rel="noreferrer"><code>math.log()</code></a> (including Numpy)</p>
</li>
<li><p>Fortran <a href="http://www.personal.psu.edu/jhm/f90/lectures/7.html" rel="noreferrer"><code>log()</code></a></p>
</li>
<li><p>C#, <a href="http://msdn.microsoft.com/en-us/library/x80ywz41.aspx" rel="noreferrer"><code>Math.Log()</code></a></p>
</li>
<li><p>R</p>
</li>
<li><p>Maxima (strictly speaking a CAS, not a language)</p>
</li>
<li><p>Scheme's <code>log</code></p>
</li>
<li><p>Lisp's <code>log</code></p>
</li>
</ul>
<p>In fact, I cannot think of a <em>single</em> programming language where <code>log()</code> is anything other than the base-e logarithm. I'm sure such a programming language exists.</p> |
39,522,113 | How to stop annoying documentation popups in IntelliJ IDEA | <p>Using IntelliJ IDEA 15, I get these constant and annoying documentation popups whenever my mouse is anywhere in the code window for a decompiled class (from a 3rd party jar). It will popup docs for whatever variable/method/class/anything happens to be near my mouse. If my mouse is not near any lines of code, it will popup for the current classfile, so basically I can't browse code unless I move my mouse to another window. </p>
<p>It only happens with decompiled classes, not my normal code. How do I stop these?</p> | 39,523,944 | 5 | 0 | null | 2016-09-16 00:15:47.503 UTC | 4 | 2021-07-12 22:05:12.4 UTC | 2016-09-16 00:24:13.88 UTC | null | 849,141 | null | 849,141 | null | 1 | 73 | intellij-idea | 9,515 | <p>Go to File>Settings>Editor>General - in the section 'Other', uncheck 'Show quick documentation on mouse move'.</p>
<p>In later versions of IntelliJ, the path is File>Settings>Editor>Code Editing, and it is under the "Quick Documentation" section.</p> |
47,211,319 | How To Pull Data From the Adwords API and put into a Pandas Dataframe | <p>I'm using Python to pull data from Googles adwords API. I'd like to put that data into a Pandas DataFrame so I can perform analysis on the data. I'm using examples provided by Google <a href="https://github.com/googleads/googleads-python-lib/blob/master/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py" rel="noreferrer">here.</a></p>
<p>Below is my attempt to try to get the output to be read as a pandas dataframe:</p>
<pre><code>from googleads import adwords
import pandas as pd
import numpy as np
# Initialize appropriate service.
adwords_client = adwords.AdWordsClient.LoadFromStorage()
report_downloader = adwords_client.GetReportDownloader(version='v201710')
# Create report query.
report_query = ('''
select Date, Clicks
from ACCOUNT_PERFORMANCE_REPORT
during LAST_7_DAYS''')
df = pd.read_csv(report_downloader.DownloadReportWithAwql(
report_query,
'CSV',
client_customer_id='xxx-xxx-xxxx', # denotes which adw account to pull from
skip_report_header=True,
skip_column_header=False,
skip_report_summary=True,
include_zero_impressions=True))
</code></pre>
<p>The output is the data in what looks like csv format and an error.</p>
<pre><code>Day,Clicks
2017-11-05,42061
2017-11-07,45792
2017-11-03,36874
2017-11-02,39790
2017-11-06,44934
2017-11-08,45631
2017-11-04,36031
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-cc25e32c9f3a> in <module>()
25 skip_column_header=False,
26 skip_report_summary=True,
---> 27 include_zero_impressions=True))
/anaconda/lib/python3.6/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
653 skip_blank_lines=skip_blank_lines)
654
--> 655 return _read(filepath_or_buffer, kwds)
656
657 parser_f.__name__ = name
/anaconda/lib/python3.6/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
390 compression = _infer_compression(filepath_or_buffer, compression)
391 filepath_or_buffer, _, compression = get_filepath_or_buffer(
--> 392 filepath_or_buffer, encoding, compression)
393 kwds['compression'] = compression
394
/anaconda/lib/python3.6/site-packages/pandas/io/common.py in get_filepath_or_buffer(filepath_or_buffer, encoding, compression)
208 if not is_file_like(filepath_or_buffer):
209 msg = "Invalid file path or buffer object type: {_type}"
--> 210 raise ValueError(msg.format(_type=type(filepath_or_buffer)))
211
212 return filepath_or_buffer, None, compression
ValueError: Invalid file path or buffer object type: <class 'NoneType'>
</code></pre>
<p>I know I am missing something fundamental and I do not fully understand how to get data into a pandas dataframe. Any help would be greatly appreciated.</p> | 47,270,853 | 2 | 0 | null | 2017-11-09 20:52:15.487 UTC | 8 | 2021-04-28 08:45:07.163 UTC | 2017-11-09 22:24:23.507 UTC | null | 7,556,913 | null | 7,556,913 | null | 1 | 7 | python-3.x|pandas|jupyter-notebook|google-ads-api | 5,385 | <p>So I was able to find out the answer to my own question if anybody is curious or had the same problem I did. I had to <code>import io</code> and wrote the output from the adwords query to a string that I named <code>output</code>. I then used the <code>seek()</code> method to start from the beginning and read that using pandas <code>read_csv</code>.</p>
<pre><code>from googleads import adwords
import pandas as pd
import numpy as np
import io
# Define output as a string
output = io.StringIO()
# Initialize appropriate service.
adwords_client = adwords.AdWordsClient.LoadFromStorage()
report_downloader = adwords_client.GetReportDownloader(version='v201710')
# Create report query.
report_query = ('''
select Date, HourOfDay, Clicks
from ACCOUNT_PERFORMANCE_REPORT
during LAST_7_DAYS''')
# Write query result to output file
report_downloader.DownloadReportWithAwql(
report_query,
'CSV',
output,
client_customer_id='xxx-xxx-xxx', # denotes which adw account to pull from
skip_report_header=True,
skip_column_header=False,
skip_report_summary=True,
include_zero_impressions=False)
output.seek(0)
df = pd.read_csv(output)
df.head()
</code></pre> |
20,288,793 | Does SASS support adding !important to all properties in a mixin? | <p>I am currently using the <a href="http://compass-style.org" rel="noreferrer">compass framework</a> and all it's helpful CSS3 mixins. I would like to use the <code>border-radius(5px)</code> mixin and have all properties that come from it marked with <code>!important</code></p>
<p>In <a href="http://lesscss.org" rel="noreferrer">LESS</a> it is possible to apply <code>!important</code> to all properties in a mixin by simply specifying it after call</p>
<pre><code>.myMixin(@x) {
border-radius: @x;
-moz-border-radius: @x;
}
.myClass {
.myMixin(5px) !important;
}
</code></pre>
<p>compiles to</p>
<pre><code>.myClass {
border-radius: 5px !important;
-moz-border-radius: 5px !important;
}
</code></pre>
<p>Is this possible in <a href="http://sass-lang.com/" rel="noreferrer">SASS</a>, or will I have to rewrite the mixins with an important parameter?</p>
<pre><code>@mixin my-border-radius($value, $important: false) {
border-radius: @value if($important, !important, null);
....
}
</code></pre> | 20,289,137 | 3 | 0 | null | 2013-11-29 15:15:40.94 UTC | null | 2016-09-29 13:28:54.18 UTC | null | null | null | null | 680,210 | null | 1 | 25 | sass|compass-sass | 41,475 | <p>The answer is almost too obvious...</p>
<p><code>!important</code> can simply be specified as part of the property value</p>
<pre><code>border-radius(5px !important);
</code></pre> |
21,470,409 | Spring-Boot: How do I reference application.properties in an @ImportResource | <p>I have an applicationContext.xml file in my Spring Boot application. In this file, it has a property placeholder - ${profile.services.url} - that's used to configure the "address" property of a <jaxws:client> bean.</p>
<p>In my Application.java class, I import this file.</p>
<pre><code>@ImportResource("classpath:applicationContext.xml")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</code></pre>
<p>I have "profile.services.url" defined in application.properties. However, it's not recognized when building the bean in my XML file. I've tried adding the following, but it doesn't seem to work.</p>
<pre><code><context:property-placeholder location="classpath:application.properties"/>
</code></pre>
<p>Any suggestions on how to get @ImportResource to recognize Spring Boot's property support?</p> | 21,472,453 | 2 | 0 | null | 2014-01-31 00:29:22.16 UTC | 2 | 2014-02-03 17:06:15.717 UTC | 2014-01-31 00:32:07.617 UTC | null | 2,310,289 | null | 65,681 | null | 1 | 12 | java|spring|spring-boot | 48,388 | <p>I've got the following code: </p>
<pre><code>package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import java.util.Collection;
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
Collection<Foo> shouldBeConfigured = applicationContext.getBeansOfType(Foo.class).values();
System.out.println(shouldBeConfigured.toString());
}
}
@Configuration
@ImportResource("/another.xml")
class XmlImportingConfiguration {
}
class Foo {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Foo{" +
"name='" + name + '\'' +
'}';
}
}
</code></pre>
<p>I have a Spring XML configuration file, <code>another.xml</code>: </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="another.properties" />
<!-- this property value is defined in another.properties, which we install in this XML file
-->
<bean class="demo.Foo" >
<property name="name" value="${name.property}"/>
</bean>
<!-- this property value is defined in application.properties, which Spring Boot automatically installs for us.
-->
<bean class="demo.Foo" >
<property name="name" value="${some.property}"/>
</bean>
</beans>
</code></pre>
<p>I have the following <code>pom.xml</code>:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.demo</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.0.RC1</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<start-class>demo.Application</start-class>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>http://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
</code></pre>
<p>Finally, I have two <code>.properties</code> files, <code>another.properties</code>, and <code>application.properties</code>:</p>
<pre><code># application.properties
some.property=Test
</code></pre>
<p>and.. </p>
<pre><code># another.properties
name.property=Another
</code></pre>
<p>When I run this, the output is:</p>
<blockquote>
<p>[Foo{name='Another'}, Foo{name='Test'}]</p>
</blockquote>
<p>Which would seem to work.</p>
<p>I'm not quite sure I am understanding the error. Can you elaborate, or confirm this seems satisfactory behavior for you, too please?</p> |
29,995,249 | 'verbose' argument in scikit-learn | <p>Many scikit-learn functions have a <code>verbose</code> argument that, according to their documentation, "[c]ontrols the verbosity: the higher, the more messages" (e.g., <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html" rel="noreferrer">GridSearchCV</a>).</p>
<p>Unfortunately, no guidance is provided on which integers are allowed (e.g., can a user set verbosity to 100?) and what level of verbosity corresponds to which integers. I cannot find this information anywhere in the documentation.</p>
<p><strong>My question is, which integers map to which levels of verbosity?</strong></p> | 30,020,197 | 2 | 0 | null | 2015-05-01 21:14:16.303 UTC | 4 | 2020-06-24 09:16:35.817 UTC | 2020-06-24 09:16:35.817 UTC | null | 4,194,079 | null | 2,932,774 | null | 1 | 40 | python|arguments|scikit-learn|verbosity|verbose | 38,100 | <p>Higher integers map to higher verbosity as the docstring says. You can set verbosity=100 but I'm pretty sure it will be the same as verbosity=10. If you are looking for a list of what exactly is printed for each estimator for each integer, you have to look into the source.
I think most estimators only have two or three levels of verbosity, I think 3 or above will be the most verbose you can get.</p> |
36,895,711 | Can I define System Properties within Spring Boot configuration files? | <p>I have a single <code>application.yml</code> configuration file for my Spring Boot app that defines two profiles (as described in the <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html#howto-change-configuration-depending-on-the-environment" rel="noreferrer">documentation</a>). </p>
<p>When the production profile is enabled, I would like to set the <a href="http://docs.oracle.com/javase/8/docs/api/java/net/doc-files/net-properties.html#MiscHTTP" rel="noreferrer"><code>http.maxConnections</code></a> system property to a custom value, e.g.</p>
<pre><code>spring:
profiles:
active: dev
---
spring:
profiles: dev
---
spring:
profiles: production
http:
maxConnections: 15
</code></pre>
<p>But this doesn't actually set the system level property; it appears to just create an application-level property. I've verified this through both <a href="http://locahost:8080/env" rel="noreferrer">http://locahost:8080/env</a> and a JMX Console when comparing launching by </p>
<pre><code>java -jar -Dspring.profiles.active=production myapp.jar
</code></pre>
<p>versus </p>
<pre><code>java -Dhttp.maxConnections=15 myapp.jar
</code></pre>
<p>I suppose I could create a bean that's <code>@Conditional</code> on the "production" profile that programmatically calls<code>System.setProperty</code> based on my <code>application.yml</code>-defined property, but is there a simpler way through configuration files alone?</p> | 36,896,400 | 4 | 0 | null | 2016-04-27 16:30:59.743 UTC | 11 | 2020-01-17 17:13:51.863 UTC | null | null | null | null | 417,302 | null | 1 | 45 | java|spring-boot|system-properties | 69,209 | <blockquote>
<p>I suppose I could create a bean that's @Conditional on the "production" profile that programmatically callsSystem.setProperty based on my application.yml-defined property, but is there a simpler way through configuration files alone?</p>
</blockquote>
<p>I think that's your best bet here. Spring Boot does that itself in its <code>LoggingSystem</code> where various <code>logging.*</code> properties are mapped to System properties.</p>
<p>Note that you'll probably want to set the system properties as early as possible, probably as soon as the <code>Environment</code> is prepared. To do so, you can use an <code>ApplicationListener</code> that listens for the <code>ApplicationEnvironmentPreparedEvent</code>. Your <code>ApplicationListener</code> implementation should be registered via an entry in <code>spring.factories</code>.</p> |
20,508,788 | Do I need Content-Type: application/octet-stream for file download? | <p>The <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html">HTTP standard</a> says:</p>
<blockquote>
<p>If this header [Content-Disposition: attachment] is used in a response
with the application/octet-stream content-type, the implied
suggestion is that the user agent should not display the response, but
directly enter a `save response as...' dialog.</p>
</blockquote>
<p>I read that as</p>
<pre><code>Content-Type: application/octet-stream
Content-Disposition: attachment
</code></pre>
<p>But I would have thought that <code>Content-Type</code> would be <code>application/pdf</code>, <code>image/png</code>, etc.</p>
<p>Should I have <code>Content-Type: application/octet-stream</code> if I want browsers to download the file?</p> | 20,509,354 | 1 | 0 | null | 2013-12-11 01:24:18.76 UTC | 262 | 2019-09-18 13:48:12.957 UTC | 2014-03-05 16:33:48.483 UTC | null | 1,212,596 | null | 1,212,596 | null | 1 | 550 | http|browser|http-headers|download | 794,953 | <p>No.</p>
<p>The content-type should be whatever it is known to be, if you know it. <code>application/octet-stream</code> is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.</p>
<p>You can combine the use of <code>Content-Disposition</code> with other content-types, such as <code>image/png</code> or even <code>text/html</code> to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of <code>text/html</code> but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).</p>
<p>RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise <code>inline</code> to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the <code>filename</code> part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.</p>
<p>Hence:</p>
<pre><code>Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
</code></pre>
<p>Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".</p>
<pre><code>Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
</code></pre>
<p>Means "This is a PNG image. Please save it as a file, preferably named picture.png".</p>
<pre><code>Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
</code></pre>
<p>Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".</p>
<p>Of those browsers that recognise <code>inline</code> some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).</p> |
53,395,147 | Use React hook to implement a self-increment counter | <p>The code is here: <a href="https://codesandbox.io/s/nw4jym4n0" rel="noreferrer">https://codesandbox.io/s/nw4jym4n0</a></p>
<pre><code>export default ({ name }: Props) => {
const [counter, setCounter] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCounter(counter + 1);
}, 1000);
return () => {
clearInterval(interval);
};
});
return <h1>{counter}</h1>;
};
</code></pre>
<p>The problem is each <code>setCounter</code> trigger re-rendering so the interval got reset and re-created. This might looks fine since the state(counter) keeps incrementing, however it could freeze when combining with other hooks.</p>
<p>What's the correct way to do this? In class component it's simple with a instance variable holding the interval.</p> | 53,395,342 | 3 | 0 | null | 2018-11-20 14:25:34.43 UTC | 17 | 2021-05-17 19:01:44.743 UTC | 2018-11-20 16:35:10.78 UTC | null | 1,751,946 | null | 8,310,382 | null | 1 | 47 | javascript|reactjs|react-hooks | 85,132 | <p>You could give an empty array as second argument to <code>useEffect</code> so that the function is only run once after the initial render. Because of how closures work, this will make the <code>counter</code> variable always reference the initial value. You could then use the function version of <code>setCounter</code> instead to always get the correct value.</p>
<p><strong>Example</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { useState, useEffect } = React;
function App() {
const [counter, setCounter] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCounter(counter => counter + 1);
}, 1000);
return () => {
clearInterval(interval);
};
}, []);
return <h1>{counter}</h1>;
};
ReactDOM.render(
<App />,
document.getElementById('root')
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
<p>A more versatile approach would be to create a new custom hook that stores the function in a <a href="https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables" rel="noreferrer"><code>ref</code></a> and only creates a new interval if the <code>delay</code> should change, <a href="https://overreacted.io/making-setinterval-declarative-with-react-hooks/#just-show-me-the-code" rel="noreferrer">like Dan Abramov does in his great blog post <strong>"Making setInterval Declarative with React Hooks"</strong></a>.</p>
<p><strong>Example</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { useState, useEffect, useRef } = React;
function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
let id = setInterval(() => {
savedCallback.current();
}, delay);
return () => clearInterval(id);
}, [delay]);
}
function App() {
const [counter, setCounter] = useState(0);
useInterval(() => {
setCounter(counter + 1);
}, 1000);
return <h1>{counter}</h1>;
};
ReactDOM.render(
<App />,
document.getElementById('root')
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p> |
36,196,284 | In Typescript how to fix Cannot set property 'first' of undefined | <p>I'm trying to set a the sub property <code>first</code> that is defined in the <code>Name</code> interface but when do so I always get an error for example:</p>
<pre><code>interface Name{
first: string,
last:string,
}
class Person{
private name:Name
public setName(firstName, lastName){
this.name.first = firstName;
this.name.last = lastName;
}
}
var person1 = new Person();
person1.setName('Tracy','Herrera');
</code></pre>
<p>When running it i get the error: <code>Cannot set property 'first' of undefined</code></p>
<p>Any one have an idea to work this out?</p> | 36,196,502 | 4 | 0 | null | 2016-03-24 08:54:51.633 UTC | 1 | 2020-08-21 06:36:57.12 UTC | null | null | null | null | 5,751,341 | null | 1 | 22 | interface|typescript | 38,306 | <p>Class properties are not automatically initialized on instantiation. You need to initialize them with the corresponding objects manually -- in this case, with an object containing the properties defined by its interface:</p>
<pre><code>class Person {
private name: Name;
public setName(firstName, lastName) {
this.name = {
first: firstName,
last: lastName
};
}
}
</code></pre>
<hr>
<p>Another approach -- for example, in case there are multiple methods setting properties on the same object -- is to first initialize the property to an empty object, preferably in the constructor:</p>
<pre><code>class Person {
private name: Name;
constructor() {
this.name = {};
}
public setName(firstName, lastName) {
this.name.first = firstName;
this.name.last = lastName;
}
public setFirstName(firstName) {
this.name.first = firstName;
}
}
</code></pre>
<p>However, with the current setup this will yield a compile error when assigning <code>{}</code> to <code>this.name</code>, because the <code>Name</code> interface <em>requires</em> the presence of a <code>first</code> and a <code>last</code> property on the object. To overcome this error, one might resort to defining <em>optional</em> properties on an interface:</p>
<pre><code>interface Name {
first?: string;
last?: string;
}
</code></pre> |
36,051,146 | CodeIgniter3: Why would $_SERVER['CI_ENV'] ever be set in the first place? | <p>I see that in their default installation, their index.php has this: </p>
<pre><code>define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
</code></pre>
<p>Why would <code>CI_ENV</code> ever <em>already</em> be set within the <code>$_SERVER</code> array?</p> | 36,159,541 | 3 | 0 | null | 2016-03-17 03:27:42.247 UTC | 8 | 2019-11-03 11:56:27.76 UTC | 2017-09-23 18:11:08.07 UTC | null | 6,592,263 | null | 689,152 | null | 1 | 29 | php|codeigniter-3 | 19,701 | <p>As Oliver described; it's a special-use case for multiple environments. Splitting out the development, testing & production by means of <code>.htaccess</code> before it even gets to the code. To configure this:</p>
<h3>Development (Localhost)</h3>
<pre><code><IfModule mod_env.c>
SetEnv CI_ENV development
</IfModule>
</code></pre>
<h3>Testing (Your Local Server)</h3>
<pre><code><IfModule mod_env.c>
SetEnv CI_ENV testing
</IfModule>
</code></pre>
<h3>Production (Remote Server)</h3>
<pre><code><IfModule mod_env.c>
SetEnv CI_ENV production
</IfModule>
</code></pre>
<p>You're right in thinking it won't ever change unless there's some manual intervention. There's not much documentation in regards to this:</p>
<blockquote>
<p>"This server variable can be set in your .htaccess file, or Apache config using SetEnv. Alternative methods are available for nginx and other servers, or you can remove this logic entirely and set the constant based on the server’s IP address."</p>
</blockquote>
<p>Source: <a href="https://www.codeigniter.com/user_guide/general/environments.html#the-environment-constant" rel="noreferrer"><strong>Using the Environment Constant</strong></a></p> |
27,784,836 | Bean property is not readable or has an invalid getter method | <p>So, I have a task to write a simple web-application for registry routes. Using Spring MVC. So I have class "Route", where I want to keep start point, finish point and list of intermediate points. But I don't understand, how to put values to list from jsp (e.g. using jstl). So I decide to parse a string. </p>
<pre><code>public class Route {
private String start;
private String finish;
private String form;
private List<String> list;
public Route() {
}
public Route(String start, String finish, String route) {
this.start = start;
this.finish = finish;
this.form = route;
this.toList();
}
public Route(String start, String finish) {
this.start = start;
this.finish = finish;
this.list = new ArrayList<>();
}
public void addTown(String town){
list.add(town);
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getFinish() {
return finish;
}
public void setFinish(String finish) {
this.finish = finish;
}
public List<String> getRoute() {
return list;
}
public void setFormRoute(String route) {
this.form = route;
this.toList();
}
private void toList()
{
String[] temp = form.split(",");
for(String temp1 : temp) {
list.add(temp1);
}
}
}
</code></pre>
<p>and follow JSP:</p>
<pre><code><h2><a href="find.htm">Найти существующий маршрут</a><br/><br/>
Добавить маршрут</h2>
<h3>
<spring:nestedPath path="route">
<form modelAttribute="routeAttribute" method="POST" action="${add}">
Пункт отправления:
<spring:bind path="start">
<input type="text" name="${status.expression}" value="${status.value}">
</spring:bind><br/><br/>
Пункт прибытия:
<spring:bind path="finish">
<input type="text" name="${status.expression}" value="${status.value}">
</spring:bind><br/><br/>
Промежуточные пункты (через запятую):
<spring:bind path="form">
<input type="text" name="${status.expression}" value="${status.value}">
</spring:bind><br/><br/>
<input type="submit" value="Сохранить">
</form>
</spring:nestedPath>
</code></pre>
<p>If it's nessesary I can post Controller code.
And I have an error:</p>
<pre><code>Bean property 'form' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
</code></pre>
<p>Can anyone, please, to explain what I do principaly wrong? </p> | 27,784,881 | 2 | 0 | null | 2015-01-05 17:38:18.437 UTC | 2 | 2015-01-05 18:08:20.947 UTC | null | null | null | null | 4,122,043 | null | 1 | 6 | java|spring|spring-mvc|model-view-controller | 48,555 | <p>Add the form's getter method to the bean as indicated by the error message</p>
<pre><code>public String getForm() {
return form;
}
</code></pre>
<p><code>setForm</code> should have a corresponding method</p>
<pre><code>public void setForm(String form) {
this.form = form;
}
</code></pre> |
43,708,017 | AWS lambda api gateway error "Malformed Lambda proxy response" | <p>I am trying to set up a hello world example with AWS lambda and serving it through api gateway. I clicked the "Create a Lambda Function", which set up the api gatway and selected the Blank Function option. I added the lambda function found on <a href="http://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started.html#getting-started-new-lambda" rel="noreferrer">AWS gateway getting started guide</a>: </p>
<pre><code>exports.handler = function(event, context, callback) {
callback(null, {"Hello":"World"}); // SUCCESS with message
};
</code></pre>
<p>The issue is that when I make a GET request to it, it's returning back a 502 response <code>{ "message": "Internal server error" }</code>. And the logs say "Execution failed due to configuration error: Malformed Lambda proxy response".</p> | 43,709,502 | 19 | 0 | null | 2017-04-30 15:23:59.57 UTC | 10 | 2022-04-29 11:04:13.68 UTC | null | null | null | null | 3,107,798 | null | 1 | 121 | node.js|amazon-web-services|aws-lambda|aws-api-gateway | 71,757 | <p>Usually, when you see <code>Malformed Lambda proxy response</code>, it means your response from your Lambda function doesn't match the format API Gateway is expecting, like this</p>
<pre><code>{
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "..."
}
</code></pre>
<p>If you are not using Lambda proxy integration, you can login to API Gateway console and uncheck the Lambda proxy integration checkbox.</p>
<p>Also, if you are seeing intermittent <code>Malformed Lambda proxy response</code>, it might mean the request to your Lambda function has been throttled by Lambda, and you need to request a concurrent execution limit increase on the Lambda function.</p> |
34,866,510 | Building a JavaScript library, why use an IIFE this way? | <p>I have noticed a lot of libraries use this style below to define their library. I also notice that the first self invoking function has something to do with Require.js or AMD systems, they always have factory as an argument, I will look more into Require.js, always been into Browserify.</p>
<p>Why is the main code passed into the end of the first self invoking function inside parentheses, is this is a closure, or just considered an anonymous function, I will dig deeper into both. What are the benefits to this? It looks like inside the closure the author passes a <code>string</code>, <code>this</code>, and a <code>callback</code>. </p>
<p>Will this give my library a clean safe way to globalize the main object in this example below <code>Please</code>?</p>
<pre><code>(function( globalName, root, factory ) {
if ( typeof define === 'function' && define.amd ) {
define( [], factory );
}
else if ( typeof exports === 'object' ) {
module.exports = factory();
}
else{
root[globalName] = factory();
}
}('Please', this, function(){
</code></pre>
<p>I am trying to dig really deep into JavaScript and create my own small MVC architecture, I don't want to hear I am silly or its been done before, I want to challenge myself and learn. </p>
<p>If there are any great resources for creating a JavaScript library or even better an MVC library I would love to know.</p> | 34,866,603 | 2 | 0 | null | 2016-01-19 00:24:01.57 UTC | 10 | 2021-06-22 07:25:24.687 UTC | 2021-06-22 07:25:24.687 UTC | null | 13,604,898 | null | 1,971,279 | null | 1 | 17 | javascript|amd|umd|module-export | 1,977 | <p>This code pattern is called <a href="https://github.com/umdjs/umd" rel="noreferrer">Universal Module Definition</a> (UMD). It allows you to make your JavaScript library usable in different environments. It provides three ways of defining modules:</p>
<ol>
<li><p><a href="https://en.wikipedia.org/wiki/Asynchronous_module_definition" rel="noreferrer">Asynchronous Module Definition</a> (AMD), implemented by <a href="http://requirejs.org/" rel="noreferrer">RequireJS</a> and <a href="https://dojotoolkit.org/" rel="noreferrer">Dojo Toolkit</a>.</p>
<p><code>define( [], factory );</code></p>
</li>
<li><p><a href="https://en.wikipedia.org/wiki/CommonJS" rel="noreferrer">CommonJS</a> — NodeJS modules.</p>
<p><code>module.exports = factory();</code></p>
</li>
<li><p>Assigning module to the global object, for example <code>window</code> in browsers.</p>
<p><code>root[globalName] = factory();</code></p>
</li>
</ol>
<p>The IIFE has three parameters: <code>globalName</code>, <code>root</code> and <code>factory</code>.</p>
<ul>
<li><code>globalName</code> is the name of your module. It applies only to the third way of defining a module, i.e. assigning your module object to the global variable. For example, if you set this parameter to <code>"myAwesomeModule"</code> and use the code in browser (without AMD), you can access your module using <code>myAwesomeModule</code> variable.</li>
<li><code>root</code> is the name of global object. Obviously, it also applies only to the third way of defining a module. Usually <code>this</code> is passed as this parameter, because <code>this</code> is a reference to <code>window</code> in browser. However, this <a href="https://stackoverflow.com/questions/32012589/umd-javascript-module-which-also-works-in-strict-mode">doesn't work in strict mode</a>. If you want your code to work in strict mode, you can replace <code>this</code> with <code>typeof window !== "undefined" ? window : undefined</code>.</li>
<li>Finally, <code>factory</code> is an anonymous function, which should return your module as object.</li>
</ul>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript">What is the (function() { } )() construct in JavaScript?</a></li>
<li><a href="http://davidbcalhoun.com/2014/what-is-amd-commonjs-and-umd/" rel="noreferrer">What Is AMD, CommonJS, and UMD?</a></li>
</ul> |
47,721,635 | in operator, float("NaN") and np.nan | <p>I used to believe that <code>in</code> operator in Python checks the presence of element in some collection using equality checking <code>==</code>, so <code>element in some_list</code> is roughly equivalent to <code>any(x == element for x in some_list)</code>. For example:</p>
<pre><code>True in [1, 2, 3]
# True because True == 1
</code></pre>
<p>or</p>
<pre><code>1 in [1., 2., 3.]
# also True because 1 == 1.
</code></pre>
<p>However, it is well-known that <code>NaN</code> is not equal to itself. So I expected that <code>float("NaN") in [float("NaN")]</code> is <code>False</code>. And it is <code>False</code> indeed.</p>
<p>However, if we use <code>numpy.nan</code> instead of <code>float("NaN")</code>, the situation is quite different:</p>
<pre><code>import numpy as np
np.nan in [np.nan, 1, 2]
# True
</code></pre>
<p>But <code>np.nan == np.nan</code> still gives <code>False</code>!</p>
<p>How is it possible? What's the difference between <code>np.nan</code> and <code>float("NaN")</code>? How does <code>in</code> deal with <code>np.nan</code>?</p> | 47,721,759 | 2 | 0 | null | 2017-12-08 20:22:54.247 UTC | 1 | 2018-01-12 20:49:54.677 UTC | 2018-01-12 20:49:54.677 UTC | null | 3,923,281 | null | 3,025,981 | null | 1 | 36 | python|numpy|containers|nan | 8,110 | <p>To check if the item is in the list, Python tests for object identity <em>first</em>, and then tests for equality only if the objects are different.<sup>1</sup></p>
<p><code>float("NaN") in [float("NaN")]</code> is False because two <em>different</em> <code>NaN</code> objects are involved in the comparison. The test for identity therefore returns False, and then the test for equality also returns False since <code>NaN != NaN</code>.</p>
<p><code>np.nan in [np.nan, 1, 2]</code> however is True because the <em>same</em> <code>NaN</code> object is involved in the comparison. The test for object identity returns True and so Python immediately recognises the item as being in the list.</p>
<p>The <code>__contains__</code> method (invoked using <code>in</code>) for many of Python's other builtin Container types, such as tuples and sets, is implemented using the same check. </p>
<hr>
<p><sup>1</sup> At least this is true in CPython. Object identity here means that the objects are found at the same memory address: the <a href="https://github.com/python/cpython/blob/master/Objects/listobject.c#L397-L407" rel="noreferrer">contains method for lists</a> is performed using <a href="https://github.com/python/cpython/blob/master/Objects/object.c#L710-L736" rel="noreferrer"><code>PyObject_RichCompareBool</code></a> which quickly compares object pointers before a potentially more complicated object comparison. Other Python implementations may differ.</p> |
39,059,032 | Randomly insert NA's values in a pandas dataframe | <p>How can I randomly insert <code>np.nan</code>'s in a DataFrame ?
Let's say I want 10% null values inside my DataFrame. </p>
<p>My data looks like this : </p>
<pre><code>df = pd.DataFrame(np.random.randn(5, 3),
index=['a', 'b', 'c', 'd', 'e'],
columns=['one', 'two', 'three'])
one two three
a 0.695132 1.044791 -1.059536
b -1.075105 0.825776 1.899795
c -0.678980 0.051959 -0.691405
d -0.182928 1.455268 -1.032353
e 0.205094 0.714192 -0.938242
</code></pre>
<p>Is there an easy way to insert the null values?</p> | 39,059,033 | 3 | 0 | null | 2016-08-20 14:48:09.917 UTC | 4 | 2021-11-19 11:16:26.28 UTC | 2017-11-03 18:50:02.147 UTC | null | 4,686,625 | mitsi | 4,745,336 | null | 1 | 29 | python|pandas|numpy|missing-data | 18,316 | <p>Here's a way to clear exactly 10% of cells (or rather, as close to 10% as can be achieved with the existing data frame's size).</p>
<pre class="lang-python prettyprint-override"><code>import random
ix = [(row, col) for row in range(df.shape[0]) for col in range(df.shape[1])]
for row, col in random.sample(ix, int(round(.1*len(ix)))):
df.iat[row, col] = np.nan
</code></pre>
<p>Here's a way to clear cells independently with a per-cell probability of 10%.</p>
<pre class="lang-python prettyprint-override"><code>df = df.mask(np.random.random(df.shape) < .1)
</code></pre> |
50,448,326 | Uncaught TypeError: angular.lowercase is not a function | <blockquote>
<p>Uncaught TypeError: angular.lowercase is not a function</p>
</blockquote>
<p>this error in my angularjs application, and entire application is not running. This is its showing in <code>textAngular-sanitize.js:413</code>.</p>
<p>Not able to debug, i tried using same version as of angular.js, but no success. Please provide me solution for this. I dont have anything to share apart from this error message in console.</p>
<pre><code>textAngular-sanitize.js:413 Uncaught TypeError: angular.lowercase is not a function
at parseEndTag (textAngular-sanitize.js:413)
at htmlParser (textAngular-sanitize.js:378)
at textAngular-sanitize.js:147
at textAngularSetup.js:443
at Object.invoke (angular.js:5093)
at angular.js:4892
at forEach (angular.js:374)
at createInjector (angular.js:4892)
at doBootstrap (angular.js:1923)
at bootstrap (angular.js:1944)
</code></pre> | 50,448,475 | 8 | 0 | null | 2018-05-21 11:54:28.863 UTC | 7 | 2020-02-24 12:51:47.723 UTC | 2018-05-21 12:30:57.92 UTC | null | 5,379,496 | null | 3,628,929 | null | 1 | 32 | javascript|angularjs|bower|angular-sanitizer | 30,894 | <p>As you can see <a href="https://github.com/angular/angular.js/commit/1daa4f2231a89ee88345689f001805ffffa9e7de#diff-1d54c5f722aebc473dbe96f836ddf974" rel="noreferrer">here</a>, angular deprecated their <code>lowercase</code> util method. </p>
<p>The library you use has not updated yet and is therefore only compatible with an angular version before 1.6.7. But since you get this error, the angular version you use is probably higher.</p>
<p>You can either </p>
<p><strong>(A) Downgrade angular to 1.6.7, in your bower.json:</strong></p>
<pre><code>"dependencies": {
"angular": "1.6.7",
...
}
"resolutions": {
"angular": "1.6.7"
}
</code></pre>
<p><strong>(B) Create a simple workaround by adding these methods back as such:</strong></p>
<pre><code>angular.lowercase = text => text.toLowerCase();
</code></pre>
<p>Make sure this is done after angular is loaded but before your app starts.</p> |
27,916,062 | Gulp uglify output min.js | <p>The js file being compressed is output with the same filename.</p>
<pre><code>gulp.task('compressjs', function () {
gulp.src('app/**/*.js')
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
</code></pre>
<p>How can I have it output the file with <code>min.js</code> at the back?</p> | 27,917,915 | 1 | 0 | null | 2015-01-13 06:23:31.793 UTC | 17 | 2016-08-19 08:42:44.597 UTC | 2015-10-07 07:38:07.137 UTC | null | 2,054,072 | null | 1,995,781 | null | 1 | 64 | gulp|gulp-uglify | 27,524 | <p>You can use the <code>suffix</code> or <code>extname</code> parameters of <a href="https://github.com/hparra/gulp-rename">gulp-rename</a> like: </p>
<pre><code>gulp.task('compressjs', function () {
gulp.src('app/**/*.js')
.pipe(uglify())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('dist'))
})
</code></pre> |
54,573,420 | How do I use concepts in if-constexpr? | <p>How does one use concepts in <code>if constexpr</code>?</p>
<p>Given the example below, what would one give to <code>if constexpr</code> to return 1 in case <code>T</code> meets the requirements of <code>integral</code> and else 0?</p>
<pre><code>template<typename T>
concept integral = std::is_integral_v<T>;
struct X{};
template<typename T>
constexpr auto a () {
if constexpr (/* T is integral */) {
return 1;
}
else {
return 0;
}
}
int main () {
return a<X>();
}
</code></pre> | 54,573,498 | 2 | 1 | null | 2019-02-07 12:32:06.783 UTC | 2 | 2019-02-26 17:09:01.64 UTC | 2019-02-11 13:37:22.25 UTC | null | 63,550 | null | 7,014,926 | null | 1 | 35 | c++|c++-concepts|c++20|if-constexpr | 2,987 | <p>It is sufficient to do:</p>
<pre><code>if constexpr ( integral<T> )
</code></pre>
<p>since <code>integral<T></code> is already testable as <code>bool</code></p> |
22,249,702 | Delete rows containing specific strings in R | <p>I would like to exclude lines containing a string "REVERSE", but my lines do not match exactly with the word, just contain it.</p>
<p>My input data frame:</p>
<pre><code> Value Name
55 REVERSE223
22 GENJJS
33 REVERSE456
44 GENJKI
</code></pre>
<p>My expected output:</p>
<pre><code> Value Name
22 GENJJS
44 GENJKI
</code></pre> | 22,249,839 | 7 | 1 | null | 2014-03-07 12:08:23.687 UTC | 43 | 2022-06-22 09:25:31.267 UTC | 2015-09-05 16:53:15.493 UTC | null | 1,743,880 | null | 3,091,668 | null | 1 | 74 | r|string|match|rows | 204,826 | <p>This should do the trick:</p>
<pre><code>df[- grep("REVERSE", df$Name),]
</code></pre>
<p>Or a safer version would be:</p>
<pre><code>df[!grepl("REVERSE", df$Name),]
</code></pre> |
22,159,044 | How to append a string at end of a specific line in a file in bash | <p>I want to append an alias to the end of a certain line of my hosts file. For example</p>
<p>I have</p>
<pre><code>192.168.1.1 www.address1.com
192.168.1.2 www.address2.com
192.168.1.3 www.address3.com
</code></pre>
<p>I want to it to look like</p>
<pre><code>192.168.1.1 www.address1.com
192.168.1.2 www.address2.com myalias
192.168.1.3 www.address3.com
</code></pre>
<p>I want to find the line that contains 19.2.68.1.2 and append myalias at the end of it. The line is not necessarily the second line in the file like I've shown here. It could be anywhere.</p> | 22,159,086 | 4 | 1 | null | 2014-03-03 22:36:49.85 UTC | 5 | 2014-03-04 06:05:51.777 UTC | null | null | null | null | 1,401,560 | null | 1 | 23 | bash|sed|awk | 74,969 | <p>Using <code>sed</code> and the pattern described:</p>
<pre><code>sed '/192.168.1.2/s/$/ myalias/' file
</code></pre>
<hr>
<p>Using <code>sed</code> and a specific line number:</p>
<pre><code>sed '2s/$/ myalias/' file
</code></pre> |
30,394,419 | Thymeleaf + Spring : How to keep line break? | <p>I'm using Thymeleaf template engine with spring and I'd like to display text stored throught a multiline textarea.</p>
<p>In my database multiline string are store with "\n" like this : "Test1\nTest2\n...."</p>
<p>With th:text i've got : "Test1 Test2" with no line break.</p>
<p>How I can display line break using Thymeleaf and avoid manually "\n" replacing with < br/> and then avoid using th:utext (this open form to xss injection) ?</p>
<p>Thanks !</p> | 30,602,103 | 8 | 1 | null | 2015-05-22 10:32:36.207 UTC | 5 | 2022-02-15 12:40:28.413 UTC | 2015-05-22 15:09:35.993 UTC | null | 4,300,661 | null | 4,300,661 | null | 1 | 30 | spring|thymeleaf|spring-el | 35,195 | <p>Two of your options: </p>
<ol>
<li>Use th:utext - easy setup option, but harder to read and remember</li>
<li>Create a custom processor and dialect - more involved setup, but easier, more readable future use.</li>
</ol>
<p><strong>Option 1:</strong></p>
<p>You can use th:utext if you escape the text using the expression utility method <code>#strings.escapeXml( text )</code> to prevent XSS injection and unwanted formatting - <a href="http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#strings" rel="noreferrer">http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#strings</a></p>
<p>To make this platform independent, you can use <code>T(java.lang.System).getProperty('line.separator')</code> to grab the line separator. </p>
<p>Using the existing Thymeleaf expression utilities, this works:</p>
<pre><code><p th:utext="${#strings.replace( #strings.escapeXml( text ),T(java.lang.System).getProperty('line.separator'),'&lt;br /&gt;')}" ></p>
</code></pre>
<p><strong>Option 2:</strong></p>
<p><strong>The API for this is now different in 3 (I wrote this tutorial for 2.1)</strong>
Hopefully you can combine the below logic with their official tutorial. One day maybe I'll have a minute to update this completely. But for now:
<a href="https://www.thymeleaf.org/doc/tutorials/3.0/extendingthymeleaf.html#creating-our-own-dialect" rel="noreferrer">Here's the official Thymeleaf tutorial for creating your own dialect.</a> </p>
<p>Once setup is complete, all you will need to do to accomplish escaped textline output with preserved line breaks:</p>
<pre><code><p fd:lstext="${ text }"></p>
</code></pre>
<p>The main piece doing the work is the processor. The following code will do the trick:</p>
<pre><code>package com.foo.bar.thymeleaf.processors
import java.util.Collections;
import java.util.List;
import org.thymeleaf.Arguments;
import org.thymeleaf.Configuration;
import org.thymeleaf.dom.Element;
import org.thymeleaf.dom.Node;
import org.thymeleaf.dom.Text;
import org.thymeleaf.processor.attr.AbstractChildrenModifierAttrProcessor;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.unbescape.html.HtmlEscape;
public class HtmlEscapedWithLineSeparatorsProcessor extends
AbstractChildrenModifierAttrProcessor{
public HtmlEscapedWithLineSeparatorsProcessor(){
//only executes this processor for the attribute 'lstext'
super("lstext");
}
protected String getText( final Arguments arguments, final Element element,
final String attributeName) {
final Configuration configuration = arguments.getConfiguration();
final IStandardExpressionParser parser =
StandardExpressions.getExpressionParser(configuration);
final String attributeValue = element.getAttributeValue(attributeName);
final IStandardExpression expression =
parser.parseExpression(configuration, arguments, attributeValue);
final String value = (String) expression.execute(configuration, arguments);
//return the escaped text with the line separator replaced with <br />
return HtmlEscape.escapeHtml4Xml( value ).replace( System.getProperty("line.separator"), "<br />" );
}
@Override
protected final List<Node> getModifiedChildren(
final Arguments arguments, final Element element, final String attributeName) {
final String text = getText(arguments, element, attributeName);
//Create new text node signifying that content is already escaped.
final Text newNode = new Text(text == null? "" : text, null, null, true);
// Setting this allows avoiding text inliners processing already generated text,
// which in turn avoids code injection.
newNode.setProcessable( false );
return Collections.singletonList((Node)newNode);
}
@Override
public int getPrecedence() {
// A value of 10000 is higher than any attribute in the SpringStandard dialect. So this attribute will execute after all other attributes from that dialect, if in the same tag.
return 11400;
}
}
</code></pre>
<p>Now that you have the processor, you need a custom dialect to add the processor to.</p>
<pre><code>package com.foo.bar.thymeleaf.dialects;
import java.util.HashSet;
import java.util.Set;
import org.thymeleaf.dialect.AbstractDialect;
import org.thymeleaf.processor.IProcessor;
import com.foo.bar.thymeleaf.processors.HtmlEscapedWithLineSeparatorsProcessor;
public class FooDialect extends AbstractDialect{
public FooDialect(){
super();
}
//This is what all the dialect's attributes/tags will start with. So like.. fd:lstext="Hi David!<br />This is so much easier..."
public String getPrefix(){
return "fd";
}
//The processors.
@Override
public Set<IProcessor> getProcessors(){
final Set<IProcessor> processors = new HashSet<IProcessor>();
processors.add( new HtmlEscapedWithLineSeparatorsProcessor() );
return processors;
}
}
</code></pre>
<p>Now you need to add it to your xml or java configuration:</p>
<p>If you are writing a Spring MVC application, you just have to set it at the additionalDialects property of the Template Engine bean, so that it is added to the default SpringStandard dialect:</p>
<pre><code> <bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="additionalDialects">
<set>
<bean class="com.foo.bar.thymeleaf.dialects.FooDialect"/>
</set>
</property>
</bean>
</code></pre>
<p>Or if you are using Spring and would rather use JavaConfig you can create a class annotated with @Configuration in your base package that contains the dialect as a managed bean:</p>
<pre><code>package com.foo.bar;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.foo.bar.thymeleaf.dialects.FooDialect;
@Configuration
public class TemplatingConfig {
@Bean
public FooDialect fooDialect(){
return new FooDialect();
}
}
</code></pre>
<p>Here are some further references on creating custom processors and dialects: <a href="http://www.thymeleaf.org/doc/articles/sayhelloextendingthymeleaf5minutes.html" rel="noreferrer">http://www.thymeleaf.org/doc/articles/sayhelloextendingthymeleaf5minutes.html</a> , <a href="http://www.thymeleaf.org/doc/articles/sayhelloagainextendingthymeleafevenmore5minutes.html" rel="noreferrer">http://www.thymeleaf.org/doc/articles/sayhelloagainextendingthymeleafevenmore5minutes.html</a> and <a href="http://www.thymeleaf.org/doc/tutorials/2.1/extendingthymeleaf.html" rel="noreferrer">http://www.thymeleaf.org/doc/tutorials/2.1/extendingthymeleaf.html</a></p> |
30,730,300 | Optimize website to show reader view in Firefox | <p>Firefox 38.0.5 added a "Reader View" to the address bar:</p>
<p><img src="https://i.stack.imgur.com/L6tY7.png" alt="enter image description here"></p>
<p>But not all sites get this icon, It only appears when readable content page is detected. So how do I <strong>enable</strong> this for my site?</p>
<p>I tried media print and an extra stylesheet for print-view, but that has no effect: </p>
<pre><code><html>
<head>
<style>
@media print { /* no effect: */
.no-print { display:none; }
}
</style>
<!-- no effect either:
<link rel="stylesheet" href="print.css" media="print"><!-- -->
</head><body>
<h1>Some Title</h1>
<img class="no-print" src="http://dummyimage.com/1024x100/000/ffffff&text=This+banner+should+vanish+in+print+view">
<br><br><br>This is the only text
</body></html>
</code></pre>
<hr>
<p>What code snippets do I have to add into my website sourcecode so this <strong>book icon</strong> will become visible to the visitors of my site?</p> | 30,750,212 | 2 | 1 | null | 2015-06-09 11:07:29.243 UTC | 14 | 2020-12-25 13:04:33.08 UTC | 2015-06-10 07:48:06.4 UTC | null | 1,069,083 | null | 1,069,083 | null | 1 | 32 | firefox|firefox-reader-view | 20,207 | <p>You have to add <code><div></code> or <code><p></code> tags to achieve a page to iniciate the ReaderView.</p>
<p>I created a simple html that works:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Reader View shows only the browser in reader view</title>
</head>
<body>
Everything outside the main div tag vanishes in Reader View<br>
<img class="no-print" src="http://dummyimage.com/1024x100/000/ffffff&text=This+banner+should+vanish+in+print+view">
<div>
<h1>H1 tags outside ot a p tag are hidden in reader view</h1>
<img class="no-print" src="http://dummyimage.com/1024x100/000/ffffff&text=This+banner+is resized+in+print+view">
<p>
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
123456789 123456
</p>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>This is the minimum needed to activate it. This is a somewhat multi-faceted process where scores are added for text chunks.</p>
<p>You can for example activate the reader view in forum's software if you add a <code><p></code>-tag around each message block in the view-posts template.</p>
<p><a href="https://stackoverflow.com/a/30688312/1069083">Here are some more details about the mechanism</a></p> |
30,317,070 | Java returns error "Cannot instantiate the type" | <p>I got this error message when I try to init a new object.</p>
<pre><code>Cannot instantiate the type Car
</code></pre>
<p>My code</p>
<p>Main.java</p>
<pre><code>public class Main {
public static void main(String args[]){
Car car = new Car(4,4,COUNTRY.MALAYSIA, Locale.ENGLISH, "150.00"); //error here
}
}
</code></pre>
<p>Car.java</p>
<pre><code>public abstract class Car implements Automobile {
public int wheel;
public int door;
public COUNTRY country;
public Locale locale;
public String price;
public Car(int w, int d, COUNTRY c, Locale l, String p){
this.wheel = w;
this.door = d;
this.country = c;
this.locale = l;
this.price = p;
}
}
</code></pre> | 30,317,092 | 3 | 2 | null | 2015-05-19 04:58:00.013 UTC | null | 2019-04-03 19:00:43.3 UTC | 2019-04-03 19:00:43.3 UTC | null | 472,495 | null | 1,922,589 | null | 1 | 3 | java | 93,201 | <p>Car is an Abstract class you cannot create an instance of it.</p>
<pre><code>public abstract class Car implements Automobile
</code></pre>
<p>you can potentially do something like </p>
<pre><code>public class FordFocus extends Car
</code></pre>
<p>keep in mind that you will need to call the super constructor, but then you will be able to create an instance of the FordFocus car type </p> |
4,458,812 | What's the difference and compatibility of CGLayer and CALayer? | <p>I'm confusing <code>CGLayer</code> and <code>CALayer</code>. They look similar, so why are there separate implementations? What's the difference between, and compatibility of, <code>CGLayer</code> and <code>CALayer</code>?</p> | 4,594,394 | 1 | 0 | null | 2010-12-16 08:39:36.027 UTC | 28 | 2021-11-28 10:27:41.937 UTC | 2013-12-17 10:08:01.607 UTC | null | 246,776 | null | 246,776 | null | 1 | 55 | cocoa|core-graphics|calayer|cglayer | 9,820 | <p>They are completely different, and not compatible.</p>
<p>To be absolutely clear:</p>
<p>it is <strong>strictly a coincidence</strong> that the word "layer" is used in both <strong>names</strong>; they are <strong>completely unrelated</strong>.</p>
<p>CGLayers are a "special" "high performance" thingy.</p>
<p>You could consider them "like bitmaps, but better."</p>
<p>Apple sat down and said "We're sick of people using bitmaps, let's make something better!" :-)</p>
<p>Indeed, you only work with CGLayers <em><strong>offscreen</strong></em>.</p>
<p>To repeat, CGLayers are entirely used offscreen.</p>
<p>Once they are ready, you can then blast them on to your actual screen (that is to say: blast them on to one of your views).</p>
<p>(<strong>However</strong>: note that: CGLayers are often used "alone." When I say they are used "alone," I mean they are used for: image processing or mathematical calculations. In that case, CGLayers are never seen onscreen, and they have utterly no connection to the onscreen world.)</p>
<p>In contrast ... <em><strong>CALayers are simply the things "in" views. CALayers are just how views work.</strong></em></p>
<p>So the two concepts are totally different.</p>
<p>CALayers are just the things "in" views. <em><strong>In contrast CGLayers are Apple's cool "offscreen, high performance, calculation machinery."</strong></em></p>
<p>To be clear, CGLayers have utterly no connection to views, and no association with views. (Sure, you could paste a CGLayer in to a view, but then, you can paste say "typography" or "an image" in to a view. Typography and images are not views, and CGLayers are not views.)</p>
<p>The typical example is this:</p>
<p>you want to draw something complicated once, and then draw that thing many times on-screen. The answer to that problem is exactly CGLayers. Your "work area" would be a CGLayer; you could then blit it on to a printer, on to the screen, or whatever.</p>
<p><strong>To be clear, in my opinion Apple should have chosen a different name</strong> ...</p>
<p>a good name would be "CGCalculationSpace."</p>
<p>The fact that the name contains the word "layer," makes you think of NSLayers.</p>
<p>To repeat: there is absolutely no relationship, whatsoever, in any way. CGLayers are not even vaguely related to layers.</p>
<p>There is no connection, at all. It is really confusing that the letters "l a y e r" are used in the name - it's a shame!!</p>
<p>CGLayers should be called perhaps "workspaces" or "calculation paradigms" or something like that.</p> |
48,472,977 | How to catch and deal with "WebSocket is already in CLOSING or CLOSED state" in Node | <p>I've been searching for a solution to the issue "WebSocket is already in CLOSING or CLOSED state" and found this:</p>
<ol>
<li><a href="https://stackoverflow.com/questions/40259972/meteor-websocket-is-already-in-closing-or-closed-state-error">Meteor WebSocket is already in CLOSING or CLOSED state error</a></li>
<li><a href="https://stackoverflow.com/questions/25266009/websocket-is-already-in-closing-or-closed-state">WebSocket is already in CLOSING or CLOSED state.</a></li>
</ol>
<p>Answer #1 is for strictly related to Meteor and #2 has no answers... I have a Node server app with a socket:</p>
<pre><code>const WebSocket = require('ws');
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(socket) {
socket.on('message', function incoming(data) {
console.log('Incoming data ', data);
});
});
</code></pre>
<p>And clients connect like this:</p>
<pre><code>const socket = new WebSocket('ws://localhost:3090'); //Create WebSocket connection
//Connection opened
socket.addEventListener('open', function(event) {
console.log("Connected to server");
});
//Listen to messages
socket.addEventListener('message', function(event) {
console.log('Message from server ', event);
});
</code></pre>
<p>However after a few minutes, clients randomly disconnect and the function</p>
<pre><code>socket.send(JSON.stringify(data));
</code></pre>
<p>Will then throw a "WebSocket is already in CLOSING or CLOSED state.".</p>
<p>I am looking for a way to detect and deal these disconnections and immediately attempt to connect again.</p>
<p><strong>What is the most correct and efficient way to do this?</strong></p> | 54,061,045 | 3 | 5 | null | 2018-01-27 05:41:59.933 UTC | 7 | 2022-08-29 10:05:54.367 UTC | null | null | null | null | 1,996,066 | null | 1 | 43 | javascript|node.js|sockets|websocket | 59,590 | <p>The easiest way is to check if the socket is open or not before sending.</p>
<p>For example - write a simple function:</p>
<pre><code>function isOpen(ws) { return ws.readyState === ws.OPEN }
</code></pre>
<p>Then - before any <code>socket.send</code> make sure it is open:</p>
<pre><code>if (!isOpen(socket)) return;
socket.send(JSON.stringify(data));
</code></pre>
<p>You can also rewrite the <code>send</code> function like <a href="https://stackoverflow.com/a/47898118/3107689">this answer</a> but in my way you can log this situations.</p>
<p>And, for your second request</p>
<blockquote>
<p>immediately attempt to connect again</p>
</blockquote>
<p>There is no way you can do it from the server.</p>
<p>The client code should monitor the WebSocket state and apply reconnect method based on your needs.</p>
<p>For example - check <a href="https://www.npmjs.com/package/vue-native-websocket" rel="noreferrer">this</a> VueJS library that do it nicely. Look at <em>Enable ws reconnect automatically</em> section</p> |
20,061,057 | Error 1920 service failed to start. Verify that you have sufficient privileges to start system services | <p>We have created a custom windows service. The deployment package is done in InstallShield and the installation prompts for the user name and password for the service Log On account.</p>
<p>We have had no issues at all installing on various Windows 7 (Professional) and Windows 8 machines, but we get the 1920 error when trying to deploy to a Windows 7 Ultimate machine. We have not yet confirmed whether the issue is to do with the OS or the specific machine that we are trying to install this on.</p>
<p>The installer is always run by right-clicking and "Run as Administrator", and the users (both, the user running the installer and the Logon User for which the credentials are supplied) are administrators on the machine. Usually the logged in user installing the service, and the Logon user running the service are the same.</p>
<p>Here are the things we have tried.</p>
<ol>
<li>Verified the Logon user is a member of Administrators.</li>
<li>Verified the user account settings are exactly the same as another machine where it works.</li>
<li>Verified from Control Panel - Administrative tools - Local Security Policy - Local Policies - Security Options = that these again match machine where it works.</li>
<li>Ensured that all windows updates have been applied.</li>
<li>Verified that the Windows Management Instrumentation Service is running. Restarted it.</li>
<li>Rebooted the machine, then tried again.</li>
<li>Added "generatePublisherEvidence" element in the service configuration file. (<a href="https://stackoverflow.com/questions/4406595/service-failed-to-start-error-1920">Service failed to start error 1920</a>)</li>
</ol>
<p>But none of the above work.</p>
<p>Hope that someone else has come across a similar issue and has a fix..</p>
<p>UPDATE:</p>
<p>I have also tried the following:</p>
<ul>
<li>Open SecPol.msc</li>
<li>Navigate to Local Policies/User Rights Assigment</li>
<li>Find "Log on as a service" policy and add the service account</li>
</ul> | 20,061,097 | 10 | 1 | null | 2013-11-19 00:50:22.667 UTC | 2 | 2021-07-21 15:09:43.82 UTC | 2020-09-04 10:35:26.417 UTC | null | 3,241,243 | null | 2,188,809 | null | 1 | 14 | windows|installation|service|windows-installer | 303,538 | <p>1920 is a generic error code that means the service didn't start. My hunch is this:</p>
<p><a href="http://blog.iswix.com/2008/09/different-year-same-problem.html">http://blog.iswix.com/2008/09/different-year-same-problem.html</a></p>
<p>To confirm, with the installer on the abort, retry, ignore, cancel dialog up... go into services.msc and set the username and password manually. If you get a message saying the user was granted logon as service right, try hitting retry on the MSI dialog and see if it starts.</p>
<p>It could also be missing dependencies or exceptions being thrown in your code.</p> |
7,379,263 | Disposing of view and model objects in Backbone.js | <p>Which is the most efficient way to dispose model/view instances when not needed?</p>
<p>Usually, I put all the logic in the controller/router. It is the one that decides, what views should be created, and what models should be supplied to them. Usually, there are a few handler functions, corresponding to different user actions or routes, where I create new view instances every time when a handler gets executed. Of course, that should eliminate whatever I've previously stored in the view instance. However, there are some situations when some views keep DOM event handlers themselves, and they don't get unbinded properly, which results in those instances being kept alive. I wish if there were a proper way to destroy view instances, when for example their el (DOM representation) gets detached, or thrown out of the DOM</p> | 7,383,008 | 3 | 1 | null | 2011-09-11 15:30:31.797 UTC | 43 | 2014-05-27 14:32:51.847 UTC | null | null | null | null | 802,232 | null | 1 | 64 | javascript|backbone.js | 35,973 | <p>you're on the right path. you should have an object that controls the lifecycle of your views. i don't like to put this in my view. i like to create a separate object for this.</p>
<p>the thing you need to do, is unbind the events when necessary. to do this, it's a good idea to create a "close" method on all of your views, and use the object that controls the lifecycle of everything to always call the close method.</p>
<p>for example:</p>
<pre><code>
function AppController(){
this.showView = function (view){
if (this.currentView){
this.currentView.close();
}
this.currentView = view;
this.currentView.render();
$("#someElement").html(this.currentView.el);
}
}
</code></pre>
<p>at this point, you would set up your code to only have one instance of the AppController, and you would always call <code>appController.showView(...)</code> from your router or any other code that needs to show a view in the <code>#someElement</code> portion of your screen.</p>
<p>(i have another example of a very simple backbone app that uses an "AppView" (a backbone view that runs the main portion of the app), here: <a href="http://jsfiddle.net/derickbailey/dHrXv/9/">http://jsfiddle.net/derickbailey/dHrXv/9/</a> )</p>
<p>the <code>close</code> method does not exist on views by default, so you need to create one yourself, for each of your views. There are two things that should always be in the close method: <code>this.unbind()</code> and <code>this.remove()</code>. in addition to these, if you are binding your view to any model or collection events, you should unbind them in the close method. </p>
<p>for example:</p>
<pre><code>
MyView = Backbone.View.extend({
initialize: function(){
this.model.bind("change", this.modelChanged, this);
},
modelChanged: function(){
// ... do stuff here
},
close: function(){
this.remove();
this.unbind();
this.model.unbind("change", this.modelChanged);
}
});
</code></pre>
<p>this will properly clean up all of the events from the DOM (via <code>this.remove()</code>), all of the events that the view itself may raise (via <code>this.unbind()</code>) and the event that the view bound from the model (via <code>this.model.unbind(...)</code>).</p> |
7,388,361 | TextView with different textSize | <p>Is this possible to set different textSize in one TextView? I know that I can change text style using:</p>
<pre><code>TextView textView = (TextView) findViewById(R.id.textView);
Spannable span = new SpannableString(textView.getText());
span.setSpan(arg0, 1, 10, arg3);
textView.setText(span)
</code></pre>
<p>I know the range start...end of text I want to change size. But what can I use as <code>arg0</code> and <code>arg3</code>?</p> | 7,388,398 | 3 | 0 | null | 2011-09-12 13:08:29.19 UTC | 16 | 2018-12-11 11:31:38.683 UTC | 2018-12-11 11:31:38.683 UTC | null | 7,666,442 | null | 845,220 | null | 1 | 90 | android|textview|spannable | 71,138 | <p>Try </p>
<pre><code>span.setSpan(new RelativeSizeSpan(0.8f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</code></pre> |
10,729,034 | Can I map a hostname *and* a port with /etc/hosts? | <p>Can I map an IP address like <code>127.0.0.1</code> to a domain name <em>and</em> a port?</p>
<p>For example, I would like to map <code>127.0.0.1</code> to <code>api.example.com:8000</code></p> | 10,729,058 | 2 | 2 | null | 2012-05-23 23:00:30.387 UTC | 29 | 2022-01-12 03:01:28.99 UTC | 2019-10-24 13:48:48.153 UTC | null | 5,446,749 | null | 200,619 | null | 1 | 215 | linux|dns|port|hostname | 176,354 | <p>No, that's not possible. The port is not part of the hostname, so it has no meaning in the <code>hosts</code>-file.</p> |
28,844,535 | Python Pandas GroupBy get list of groups | <p>I have a line of code: </p>
<pre><code>g = x.groupby('Color')
</code></pre>
<p>The colors are Red, Blue, Green, Yellow, Purple, Orange, and Black. How do I return this list? For similar attributes, I use x.Attribute and it works fine, but x.Color doesn't behave the same way.</p> | 40,721,256 | 6 | 3 | null | 2015-03-04 00:18:59.777 UTC | 15 | 2022-08-05 18:36:31.867 UTC | null | null | null | null | 3,745,115 | null | 1 | 52 | python|pandas | 133,803 | <p>There is much easier way of doing it:</p>
<pre><code>g = x.groupby('Color')
g.groups.keys()
</code></pre>
<p>By doing <code>groupby()</code> pandas returns you a dict of grouped DFs.
You can easily get the key list of this dict by python built in function <code>keys()</code>.</p> |
26,143,571 | Using SqlQuery to get IQueryable | <p>Is there something that can return <code>IQueryable</code>for a dynamic sql query in Entity Framework 6?</p>
<p>This is what I am using now but it is pulling all the records (as expected). </p>
<pre><code>DbContext.Database.SqlQuery<T>("SELECT * FROM dbo.SomeDynamicView")
</code></pre>
<p>Problem is that <code>SqlQuery</code> returns <a href="http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbrawsqlquery(v=vs.113).aspx"><code>DbRawSqlQuery</code></a> which is <code>IEnumerable</code>.</p>
<p><code>dbo.SomeDynamicView</code> is a database view created at runtime.</p> | 26,143,932 | 2 | 2 | null | 2014-10-01 14:19:38.42 UTC | 2 | 2019-10-04 16:51:22.557 UTC | 2014-10-01 15:29:39.083 UTC | null | 13,302 | null | 1,576,573 | null | 1 | 28 | entity-framework|entity-framework-6 | 20,774 | <p>No, you can't get a <code>IQueryable</code> from <code>SqlQuery</code><sup>*</sup>, this is because what <code>IQueryable</code> is doing is building a SQL string dynamically based on what select and where filters you put in. Because in <code>SqlQuery</code> you are providing the string Entity Framework can not generate that dynamic string.</p>
<p>Your options are either dynamically build the string your self to pass in to <code>SqlQuery</code> and use it as a <code>IEnumerable</code> instead of a <code>IQueryable</code> or use a <code>DbSet</code> in your <code>DbContext</code> and do the more "normal" way of letting entity framework build the query for you.</p>
<hr>
<p><sup>* You technically can by calling <a href="http://msdn.microsoft.com/en-us/library/vstudio/bb353734(v=vs.100).aspx" rel="noreferrer">AsQueryable()</a> on the result, but that is just a IEnumerable pretending to be a IQueryable, it does not give you any of the benefits of using a "Real" IQueryable like only retrieving the needed rows from the server.</sup></p> |
7,027,129 | MySQL MONTHNAME() from numbers | <p>Is there anyway to get the <code>MONTHNAME()</code> from just the number of the month (1-12)? For example if I have <code>6,7,8</code> is there any native way in MySQL to transform those into <code>June,July,August</code>?</p> | 7,027,175 | 5 | 0 | null | 2011-08-11 13:54:37.403 UTC | 7 | 2018-10-16 13:53:48.403 UTC | 2014-12-23 16:00:00.577 UTC | null | 541,091 | null | 702,638 | null | 1 | 38 | mysql | 64,984 | <p>You can use <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_str-to-date" rel="noreferrer"><code>STR_TO_DATE()</code></a> to convert the number to a date, and then back with <code>MONTHNAME()</code></p>
<pre><code>SELECT MONTHNAME(STR_TO_DATE(6, '%m'));
+---------------------------------+
| MONTHNAME(STR_TO_DATE(6, '%m')) |
+---------------------------------+
| June |
+---------------------------------+
</code></pre>
<p>Warning: This could be slow if done over a lot of rows.</p> |
7,273,316 | What is the javascript filename naming convention? | <p>Should files be named something-with-hyphens.js, camelCased.js, or something else?</p>
<p>I didn't find the answer to this question <a href="https://stackoverflow.com/questions/921133/javascript-naming-conventions">here</a>.</p> | 7,273,431 | 5 | 3 | null | 2011-09-01 16:24:17.21 UTC | 79 | 2022-02-17 09:24:28.843 UTC | 2017-05-23 11:54:53.897 UTC | null | -1 | null | 11,236 | null | 1 | 341 | javascript|naming-conventions | 232,773 | <p>One possible naming convention is to use something similar to the naming scheme jQuery uses. It's not universally adopted but it is pretty common.</p>
<pre><code>product-name.plugin-ver.sion.filetype.js
</code></pre>
<p>where the <code>product-name</code> + <code>plugin</code> pair can also represent a <a href="http://www.yuiblog.com/blog/2007/06/12/module-pattern/" rel="noreferrer"><em>namespace</em> and a <em>module</em></a>. The <code>version</code> and <code>filetype</code> are usually optional.</p>
<p><code>filetype</code> can be something relative to how the content of the file is. Often seen are:</p>
<ul>
<li><code>min</code> for minified files</li>
<li><code>custom</code> for custom built or modified files</li>
</ul>
<p>Examples: </p>
<ul>
<li><code>jquery-1.4.2.min.js</code></li>
<li><code>jquery.plugin-0.1.js</code></li>
<li><code>myapp.invoice.js</code></li>
</ul> |
7,306,316 | B-Tree vs Hash Table | <p>In MySQL, an index type is a b-tree, and access an element in a b-tree is in logarithmic amortized time <code>O(log(n))</code>.</p>
<p>On the other hand, accessing an element in a hash table is in <code>O(1)</code>.</p>
<p>Why is a hash table not used instead of a b-tree in order to access data inside a database?</p> | 7,306,456 | 8 | 2 | null | 2011-09-05 09:43:17.933 UTC | 52 | 2021-10-26 17:11:39.127 UTC | 2020-07-28 21:39:24.207 UTC | null | 3,197,387 | null | 324,853 | null | 1 | 151 | mysql|data-structures|computer-science|complexity-theory|b-tree | 97,214 | <p>You can only access elements by their primary key in a hashtable.
This is faster than with a tree algorithm (<em><code>O(1)</code> instead of <code>log(n)</code></em>), but you cannot select ranges (<em>everything in between <code>x</code> and <code>y</code></em>).
Tree algorithms support this in <code>Log(n)</code> whereas hash indexes can result in a full table scan <code>O(n)</code>.
Also the constant overhead of hash indexes is usually bigger (<em>which is no factor in theta notation, but it still exists</em>).
Also tree algorithms are usually easier to maintain, grow with data, scale, etc.</p>
<p>Hash indexes work with pre-defined hash sizes, so you end up with some "buckets" where the objects are stored in. These objects are looped over again to really find the right one inside this partition.</p>
<p>So if you have small sizes you have a lot of overhead for small elements, big sizes result in further scanning.</p>
<p>Todays hash tables algorithms usually scale, but scaling can be inefficient.</p>
<blockquote>
<p>There are indeed scalable hashing algorithms. Don't ask me how that works - its a mystery to me too. AFAIK they evolved from scalable replication where re-hashing is not easy.</p>
<p>Its called <strong>RUSH</strong> - <strong>R</strong>eplication <strong>U</strong>nder <strong>S</strong>calable <strong>H</strong>ashing, and those algorithms are thus called RUSH algorithms.</p>
</blockquote>
<p>However there may be a point where your index exceeds a tolerable size compared to your hash sizes and your entire index needs to be re-built. Usually this is not a problem, but for huge-huge-huge databases, this can take days.</p>
<p>The trade off for tree algorithms is small and they are suitable for almost every use case and thus are default.</p>
<p>However if you have a very precise use case and you know exactly what and only what is going to be needed, you can take advantage of hashing indexes.</p> |
7,206,801 | Is there any way to git checkout previous branch? | <p>I sort of want the equivalent of <code>cd -</code> for git. If I am in branch <code>master</code> and I checkout <code>foo</code>, I would love to be able to type something like <code>git checkout -</code> to go back to <code>master</code>, and be able to type it again to return to <code>foo</code>.</p>
<p>Does anything like this exist? Would it be hard to implement?</p> | 7,207,542 | 9 | 7 | null | 2011-08-26 15:09:11.523 UTC | 145 | 2022-08-23 16:24:39.81 UTC | 2018-12-07 13:32:16.76 UTC | null | 1,429,387 | null | 10,771 | null | 1 | 898 | git|git-checkout | 111,179 | <p>From the <a href="https://github.com/git/git/blob/master/Documentation/RelNotes/1.6.2.txt" rel="noreferrer">release notes for 1.6.2</a></p>
<blockquote>
<p><code>@{-1}</code> is a way to refer to the last branch you were on. This is<br>
accepted not only where an object name is expected, but anywhere a
branch name is expected and acts as if you typed the branch name.<br>
E.g. <code>git branch --track mybranch @{-1}</code>, <code>git merge @{-1}</code>, and<br>
<code>git rev-parse --symbolic-full-name @{-1}</code> would work as expected.</p>
</blockquote>
<p>and</p>
<blockquote>
<p><code>git checkout -</code> is a shorthand for <code>git checkout @{-1}</code>.</p>
</blockquote> |
7,170,688 | SQL Server - boolean literal? | <p>How to write literal boolean value in SQL Server? See sample use:</p>
<pre><code>select * from SomeTable where PSEUDO_TRUE
</code></pre>
<p>another sample:</p>
<pre><code>if PSEUDO_TRUE
begin
select 'Hello, SQL!'
end
</code></pre>
<p>Note: The query above has nothing to do with how I'm going to use it. It is just to test the literal boolean.</p> | 7,171,264 | 13 | 2 | null | 2011-08-24 05:07:28.077 UTC | 11 | 2020-06-03 00:44:49.043 UTC | 2018-12-19 18:14:37.45 UTC | null | 759,866 | null | 724,689 | null | 1 | 89 | sql|sql-server|boolean|literals | 242,619 | <p>SQL Server doesn't have a boolean <a href="http://msdn.microsoft.com/en-us/library/ms187752.aspx">data type</a>. As @Mikael has indicated, the closest approximation is the bit. But that is a numeric type, not a boolean type. In addition, it only supports 2 values - <code>0</code> or <code>1</code> (and one non-value, <code>NULL</code>).</p>
<p>SQL (standard SQL, as well as T-SQL dialect) describes a <a href="http://en.wikipedia.org/wiki/Three-valued_logic">Three valued logic</a>. The boolean type for SQL should support 3 values - <code>TRUE</code>, <code>FALSE</code> and <code>UNKNOWN</code> (and also, the non-value <code>NULL</code>). So <code>bit</code> isn't actually a good match here.</p>
<p>Given that SQL Server has no support for the <em>data type</em>, we should not expect to be able to write literals of that "type".</p> |
13,959,624 | make a div grow and shrink based on the browser window size | <p>I am making a very simple html page and would like to know how to do the following two things for my page:</p>
<ol>
<li>I have a container div and would like to put the container div in the center of the page.</li>
<li>The container div will grow and shrink when I resize the windows size.</li>
</ol>
<p>I wrote the attached code but the container is always sticked on the left and it won't change the size when I resize the window.</p>
<pre><code><title>Demo</title>
<head>This is a demo</head>
<style>
#nav
{
background-color: red;
float: left;
width: 200px;
position:relative;
}
#detail
{
background-color: green;
float : right;
width: 800px;
position:relative;
}
div.testDetail
{
margin-top:10px;
margin-left:20px;
margin-right:20px;
margin-bottom:10px;
}
#container
{
width:1000px;
position:relative;
}
</style>
<hr>
<body>
<div id="container">
<div id="nav">
<ul>Tests</ul>
</div>
<div id="detail">
<div class="testDetail">
<image style="float:right;margin:5px;" src="test1.jpg" width="50px" height="50px"/>
<image style="float:right;margin:5px;" src="test2.jpg" width="50px" height="50px"/>
<image style="float:right;margin:5px;" src="test3.jpg" width="50px" height="50px"/>
<image style="float:right;margin:5px;" src="test4.jpg" width="50px" height="50px"/>
<h3>Title</h3>
<p>Testing</p>
</div>
<hr>
</div>
</div>
<body>
</code></pre>
<p>Did I miss something here? Any help will be appreciate!</p>
<p>Thanks.</p> | 13,959,690 | 3 | 2 | null | 2012-12-19 19:23:39.937 UTC | 3 | 2017-01-24 18:11:13.44 UTC | 2012-12-19 19:27:44.357 UTC | null | 854,246 | null | 1,701,504 | null | 1 | 11 | html|css | 88,133 | <pre><code><div id="my-div">
...content goes here
</div>
</code></pre>
<p>CSS</p>
<pre><code>#my-div{
//For center align
margin: 0 auto;
// For grow & shrink as per screen size change values as per your requirements
width: 80%;
height: 50%;
}
</code></pre> |
14,193,131 | Give 777 permission to dynamically created file in php | <p>Hi i have a script which <strong>dynamically</strong> created a file on my local directory
Please tell me how can i give 777 permission to that file right now it is unaccessible in the browser</p>
<pre><code><?php
//Get the file
$content = 'http://xxx.xxx.com.mx/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/r/bridal-shoes1.jpg ';
$content1 = explode('/', $content);
$end = end($content1);
echo $end;
//print_r($content1[12]);
//Store in the filesystem.
$my_file = $end;
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file
$path = '/var/www/'.$end;
copy($content, $path);
?>
</code></pre> | 14,193,173 | 7 | 3 | null | 2013-01-07 09:30:23.793 UTC | 6 | 2019-04-04 12:35:45.403 UTC | 2019-04-04 12:35:45.403 UTC | null | 1,847,459 | null | 1,847,459 | null | 1 | 20 | php|apache|save | 52,141 | <p>Use the function chmod<br>
<a href="http://it2.php.net/function.chmod">chmod</a></p>
<pre><code>$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
chmod($file, 0777);
</code></pre> |
14,148,276 | Toolbar with "Previous" and "Next" for Keyboard inputAccessoryView | <p>I've been trying to implement this toolbar, where only the 'Next' button is enabled when the top textField is the firstResponder and only the 'Previous' button is enabled when the bottom textField is the firstResponder. </p>
<p>It kind of works, but what keeps happening is I need to tap the 'Previous'/'Next' buttons twice each time to enable/disable the opposing button.</p>
<p>Am I missing something in the responder chain that's making this happen?</p>
<p>Here's my code:</p>
<pre><code>- (void)viewDidLoad
{
[super viewDidLoad];
[self.topText becomeFirstResponder];
}
- (UIToolbar *)keyboardToolBar {
UIToolbar *toolbar = [[UIToolbar alloc] init];
[toolbar setBarStyle:UIBarStyleBlackTranslucent];
[toolbar sizeToFit];
UISegmentedControl *segControl = [[UISegmentedControl alloc] initWithItems:@[@"Previous", @"Next"]];
[segControl setSegmentedControlStyle:UISegmentedControlStyleBar];
segControl.momentary = YES;
segControl.highlighted = YES;
[segControl addTarget:self action:@selector(changeRow:) forControlEvents:(UIControlEventValueChanged)];
[segControl setEnabled:NO forSegmentAtIndex:0];
UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithCustomView:segControl];
NSArray *itemsArray = @[nextButton];
[toolbar setItems:itemsArray];
return toolbar;
}
- (void)changeRow:(id)sender {
int idx = [sender selectedSegmentIndex];
if (idx == 1) {
[sender setEnabled:NO forSegmentAtIndex:1];
[sender setEnabled:YES forSegmentAtIndex:0];
self.topText.text = @"Top one";
[self.bottomText becomeFirstResponder];
}
else {
[sender setEnabled:NO forSegmentAtIndex:0];
[sender setEnabled:YES forSegmentAtIndex:1];
self.bottomText.text =@"Bottom one";
[self.topText becomeFirstResponder];
}
}
-(void)textFieldDidBeginEditing:(UITextField *)textField {
if (!textField.inputAccessoryView) {
textField.inputAccessoryView = [self keyboardToolBar];
}
}
</code></pre> | 14,158,530 | 7 | 2 | null | 2013-01-03 22:28:26.923 UTC | 11 | 2018-05-11 12:02:28.86 UTC | null | null | null | null | 405,095 | null | 1 | 22 | ios|keyboard|uitextfield|uisegmentedcontrol|accessory | 28,160 | <p>Okay, after looking at the brilliant <a href="https://github.com/SimonBS/BSKeyboardControls">BSKeyboardControls</a>, I tried implementing the enabling and disabling of the segmented control in <code>textFieldDidBeginEditing</code>, instead of where my <code>@selector</code> was. I also introduced a variable for the segmented control.
It works now.
Here's the amended code snippet:</p>
<pre><code>- (void)viewDidLoad
{
[super viewDidLoad];
[self.topText becomeFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (UIToolbar *)keyboardToolBar {
UIToolbar *toolbar = [[UIToolbar alloc] init];
[toolbar setBarStyle:UIBarStyleBlackTranslucent];
[toolbar sizeToFit];
self.segControl = [[UISegmentedControl alloc] initWithItems:@[@"Previous", @"Next"]];
[self.segControl setSegmentedControlStyle:UISegmentedControlStyleBar];
self.segControl.momentary = YES;
[self.segControl addTarget:self action:@selector(changeRow:) forControlEvents:(UIControlEventValueChanged)];
[self.segControl setEnabled:NO forSegmentAtIndex:0];
UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithCustomView:self.segControl];
NSArray *itemsArray = @[nextButton];
[toolbar setItems:itemsArray];
return toolbar;
}
- (void)changeRow:(id)sender {
int idx = [sender selectedSegmentIndex];
if (idx) {
self.topText.text = @"Top one";
[self.bottomText becomeFirstResponder];
}
else {
self.bottomText.text =@"Bottom one";
[self.topText becomeFirstResponder];
}
}
-(void)textFieldDidBeginEditing:(UITextField *)textField {
if (!textField.inputAccessoryView) {
textField.inputAccessoryView = [self keyboardToolBar];
}
if (textField.tag) {
[self.segControl setEnabled:NO forSegmentAtIndex:1];
[self.segControl setEnabled:YES forSegmentAtIndex:0];
}
}
</code></pre> |
13,973,927 | Check if Object is empty with JavaScript/jQuery | <p>I have an object like this:</p>
<pre><code>ricHistory = {
name1: [{
test1: value1,
test2: value2,
test3: value3
}],
name2: [{
test1: value1,
test2: value2,
test3: value3
}]
};
</code></pre>
<p>Now I want to check if e.g. name2 is empty with Javascript/jQuery. I know the method <code>hasOwnProperty</code>. It work for <code>data.hasOwnProperty('name2')</code> only if the name exists or not, but I have to check if its empty.</p> | 13,973,979 | 7 | 3 | null | 2012-12-20 14:07:03.153 UTC | 6 | 2018-09-10 16:05:18.653 UTC | 2015-06-25 12:31:31.53 UTC | null | 1,106,382 | null | 1,697,528 | null | 1 | 29 | javascript|jquery|json | 82,650 | <p>Try this:</p>
<pre><code>if (ricHistory.name2 &&
ricHistory.name2 instanceof Array &&
!ricHistory.name2.length) {
console.log('name2 is empty array');
} else {
console.log('name2 does not exists or is not an empty array.');
}
</code></pre>
<p>The solution above will show you whether richHistory.name2 exists, is an array and it's not empty.</p> |
13,949,840 | Why does the Java increment operator allow narrowing operations without explicit cast? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/8710619/java-operator">Java += operator</a> </p>
</blockquote>
<p>In Java, this is not valid (doesn't compile), as expected:</p>
<pre><code>long lng = 0xffffffffffffL;
int i;
i = 5 + lng; //"error: possible loss of magnitude"
</code></pre>
<p>But this is perfectly fine (?!)</p>
<pre><code>long lng = 0xffffffffffffL;
int i = 5;
i += lng; //compiles just fine
</code></pre>
<p>This is obviously a narrowing operation, that can possibly exceed the <code>int</code> range. So why doesn't the compiler complain?</p> | 13,949,854 | 3 | 1 | null | 2012-12-19 10:04:42.09 UTC | 2 | 2012-12-19 17:13:11.003 UTC | 2017-05-23 12:17:05.72 UTC | null | -1 | null | 11,545 | null | 1 | 29 | java|compiler-errors|precision | 1,003 | <p><code>i += lng;</code> compound assignment operator cast's implicitly.</p>
<pre><code>i+=lng;
is same as
i = int(i+lng);
</code></pre>
<p>FROM <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2" rel="noreferrer">JLS</a>:</p>
<blockquote>
<p>A compound assignment expression of the form E1 op= E2 is equivalent
to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1
is evaluated only once.</p>
</blockquote> |
14,046,679 | In Moment.js, how do you get the current financial Quarter? | <p>Is there a simple/built in way of figuring out the current financial quarter? </p>
<p>ex:</p>
<ul>
<li>Jan-Mar: 1st </li>
<li>Apr-Jul: 2nd </li>
<li>Jul-Sept: 3rd </li>
<li>Oct-Dec: 4th</li>
</ul> | 23,414,575 | 9 | 0 | null | 2012-12-26 21:49:48.677 UTC | 8 | 2020-07-21 07:59:15.97 UTC | 2013-02-08 20:25:43.857 UTC | null | 275,491 | null | 1,769,217 | null | 1 | 33 | javascript|date|momentjs | 44,966 | <p>This is now supported in moment:</p>
<pre><code>moment('2014-12-01').utc().quarter() //outputs 4
moment().quarter(); //outputs current quarter ie. 2
</code></pre>
<p><a href="https://momentjs.com/docs/#/get-set/quarter/" rel="noreferrer">Documentation</a></p> |
14,337,071 | convert array of bytes to bitmapimage | <p>I'm going to convert array of bytes to <code>System.Windows.Media.Imaging.BitmapImage</code> and show the <code>BitmapImage</code> in an image control. </p>
<p>When I'm using the first code, noting happens! no error and no image is displayed. But when I'm using the second one it works fine! can anyone say what is going on?</p>
<p>first code is here:</p>
<pre><code>public BitmapImage ToImage(byte[] array)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(array))
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = ms;
image.EndInit();
return image;
}
}
</code></pre>
<p>second code is here:</p>
<pre><code>public BitmapImage ToImage(byte[] array)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = new System.IO.MemoryStream(array);
image.EndInit();
return image;
}
</code></pre> | 14,337,202 | 2 | 0 | null | 2013-01-15 11:50:00.957 UTC | 8 | 2016-04-20 14:16:32.447 UTC | 2013-01-15 11:50:39.193 UTC | null | 447,156 | null | 1,468,295 | null | 1 | 35 | c#|wpf|bytearray|bitmapimage | 53,610 | <p>In the first code example the stream is closed (by leaving the <code>using</code> block) before the image is actually loaded. You must also set <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapcacheoption.aspx" rel="noreferrer">BitmapCacheOptions.OnLoad</a> to achieve that the image is loaded immediately, otherwise the stream needs to be kept open, as in your second example.</p>
<pre><code>public BitmapImage ToImage(byte[] array)
{
using (var ms = new System.IO.MemoryStream(array))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad; // here
image.StreamSource = ms;
image.EndInit();
return image;
}
}
</code></pre>
<p>From the Remarks section in <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.streamsource.aspx" rel="noreferrer">BitmapImage.StreamSource</a>:</p>
<blockquote>
<p>Set the CacheOption property to BitmapCacheOption.OnLoad if you wish
to close the stream after the BitmapImage is created.</p>
</blockquote>
<hr>
<p>Besides that, you can also use built-in type conversion to convert from type <code>byte[]</code> to type <code>ImageSource</code> (or the derived <code>BitmapSource</code>):</p>
<pre><code>var bitmap = (BitmapSource)new ImageSourceConverter().ConvertFrom(array);
</code></pre>
<p>ImageSourceConverter is called implicitly when you bind a property of type <code>ImageSource</code> (e.g. the Image control's <code>Source</code> property) to a source property of type <code>string</code>, <code>Uri</code> or <code>byte[]</code>.</p> |
14,188,397 | Why are "echo" short tags permanently enabled as of PHP 5.4? | <p>Even the official documentation used to tell us that <a href="https://stackoverflow.com/questions/200640/are-php-short-tags-acceptable-to-use">PHP "short tags" (<code><? /*...*/ ?></code>) are "bad"</a>. However, <a href="http://php.net/manual/en/language.basic-syntax.phpmode.php" rel="nofollow noreferrer">since PHP 5.4, the <code>echo</code> variety <code><?= /*...*/ ?></code> is permanently enabled regardless of the <code>short_open_tag</code> setting</a>.</p>
<p><em>What's changed?</em></p>
<p>Even if they were previously discouraged solely due to the unpredictable nature of whether <code>short_open_tag</code> is enabled on a shared hosting platform, surely that argument doesn't go away just because some subset of hosts will be running PHP 5.4?</p>
<p>Arguably this change to the language doesn't inherently signify a change in the recommendation that we should nonetheless avoid "short tags", but if they've gone to the trouble it would certainly seem like the PHP devs no longer "hate" them so much. Right?</p>
<p><em>The only logical conclusion I can draw at this time is that there must be some objective rationale for the introduction of this change in PHP 5.4.</em></p>
<p><em>What is it?</em></p> | 14,188,438 | 4 | 9 | null | 2013-01-07 00:40:30.397 UTC | 6 | 2013-11-12 13:25:39.483 UTC | 2017-05-23 11:54:12.947 UTC | null | -1 | null | 560,648 | null | 1 | 38 | php|coding-style|php-shorttags | 19,690 | <p><strong>Short open tags</strong> are not always enabled since PHP 5.4. The documentation talks about the <strong>short echo tags</strong>. Which is a different thing. (short open tags are <code><?</code> style tags, short echo tags are <code><?=</code> style tags, for echo-ing).</p>
<p>Then why are they enabled by default now? Well, there are a lot of scripts out there, where it benefits to use <code><?= $somevar ?></code> instead of <code><?php echo $somevar ?></code>. And <a href="https://wiki.php.net/rfc/shortags" rel="noreferrer">because the short echo tags aren't as bad as the short open tags, they chose to always enable the short echo tags</a>. Because now developers (of frameworks and CMS-es) can count on them (or rather, when PHP 5.4 becomes mainstream).</p>
<p>However, the short <strong>open</strong> tags are still influenced by the <code>short_open_tag</code> setting in your php.ini.</p> |
14,225,010 | Fastest technique to pass messages between processes on Linux? | <p>What is the fastest technology to send messages between C++ application processes, on Linux? I am vaguely aware that the following techniques are on the table:</p>
<ul>
<li>TCP</li>
<li>UDP</li>
<li>Sockets</li>
<li>Pipes</li>
<li>Named pipes</li>
<li>Memory-mapped files</li>
</ul>
<p>are there any more ways and what is the fastest? </p> | 14,225,091 | 7 | 2 | null | 2013-01-08 22:19:01.307 UTC | 28 | 2015-11-06 14:56:02.007 UTC | null | null | null | null | 997,112 | null | 1 | 45 | c++|linux|performance|ipc|latency | 56,949 | <p>I would suggest looking at this also: <a href="https://stackoverflow.com/q/5656530/1175253">How to use shared memory with Linux in C</a>.</p>
<p>Basically, I'd drop network protocols such as TCP and UDP when doing IPC on a single machine. These have packeting overhead and are bound to even more resources (e.g. ports, loopback interface).</p> |
14,231,688 | How to remove element from ArrayList by checking its value? | <p>I have ArrayList, from which I want to remove an element which has particular value...</p>
<p>for eg. </p>
<pre><code>ArrayList<String> a=new ArrayList<String>();
a.add("abcd");
a.add("acbd");
a.add("dbca");
</code></pre>
<p>I know we can iterate over arraylist, and .remove() method to remove element but I dont know how to do it while iterating.
How can I remove element which has value "acbd", that is second element?</p> | 14,231,796 | 11 | 5 | null | 2013-01-09 09:11:14.44 UTC | 16 | 2021-08-09 08:51:27.37 UTC | 2013-01-09 09:17:09.783 UTC | null | 1,673,616 | null | 1,673,616 | null | 1 | 60 | java|collections|arraylist | 221,473 | <p>In your case, there's no need to iterate through the list, because you know which object to delete. You have several options. First you can remove the object by index (so if you know, that the object is the second list element):</p>
<pre><code> a.remove(1); // indexes are zero-based
</code></pre>
<p>Or, you can remove the <em>first</em> occurence of your string:</p>
<pre><code> a.remove("acbd"); // removes the first String object that is equal to the
// String represented by this literal
</code></pre>
<p>Or, remove all strings with a certain value:</p>
<pre><code> while(a.remove("acbd")) {}
</code></pre>
<p>It's a bit more complicated, if you have more complex objects in your collection and want to remove instances, that have a certain property. So that you can't remove them by using <code>remove</code> with an object that is equal to the one you want to delete.</p>
<p>In those case, I usually use a second list to collect all instances that I want to delete and remove them in a second pass:</p>
<pre><code> List<MyBean> deleteCandidates = new ArrayList<>();
List<MyBean> myBeans = getThemFromSomewhere();
// Pass 1 - collect delete candidates
for (MyBean myBean : myBeans) {
if (shallBeDeleted(myBean)) {
deleteCandidates.add(myBean);
}
}
// Pass 2 - delete
for (MyBean deleteCandidate : deleteCandidates) {
myBeans.remove(deleteCandidate);
}
</code></pre> |
14,027,417 | What does Pylint's "Too few public methods" message mean? | <p>I'm running Pylint on some code, and receiving the error "Too few public methods (0/2)". What does this message mean?</p>
<p>The <a href="http://docs.pylint.org/features.html#id22" rel="noreferrer">Pylint documentation</a> is not helpful:</p>
<blockquote>
<p>Used when a class has too few public methods, so be sure it's really worth it.</p>
</blockquote> | 14,027,686 | 4 | 5 | null | 2012-12-25 03:22:03.213 UTC | 11 | 2022-01-13 17:53:43.227 UTC | 2021-01-21 14:20:16.873 UTC | null | 63,550 | null | 107,250 | null | 1 | 144 | python|pylint | 95,188 | <p>The error basically says that classes aren't meant to <em>just</em> store data, as you're basically treating the class as a dictionary. Classes should have at least a few methods to operate on the data that they hold.</p>
<p>If your class looks like this:</p>
<pre><code>class MyClass(object):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
</code></pre>
<p>Consider using a dictionary or a <code>namedtuple</code> instead. Although if a class seems like the best choice, use it. Pylint doesn't always know what's best.</p>
<p>Do note that <code>namedtuple</code> is immutable and the values assigned on instantiation cannot be modified later.</p> |
43,487,413 | password and confirm password field validation angular2 reactive forms | <p>I need to check whether password and confirm password fields have same value using reactive form angular2. I did see a lot of answers on the same here,<a href="https://stackoverflow.com/questions/35474991/angular-2-form-validating-for-repeat-password">Angular 2 form validating for repeat password</a> ,<a href="https://stackoverflow.com/questions/33768655/comparing-fields-in-validator-with-angular2">Comparing fields in validator with angular2</a>, but none seemed to work for me.Can someone please help."this" is undefined in my validate function :( .
Sharing my code,</p>
<pre><code>this.addEditUserForm = this.builder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
title: ['', Validators.required],
email: ['', Validators.required],
password: ['', Validators.required],
confirmPass: ['', [Validators.required, this.validatePasswordConfirmation]]
});
validatePasswordConfirmation(group: FormGroup): any{
let valid = true;
// if (this.addEditUserForm.controls.password != this.addEditUserForm.controls.confirmPass) {
// valid = false;
// this.addEditUserForm.controls.confirmPass.setErrors({validatePasswordConfirmation: true});
// }
return valid;
}
</code></pre> | 44,667,121 | 11 | 2 | null | 2017-04-19 05:49:17.407 UTC | 8 | 2021-12-22 14:44:55.94 UTC | 2017-05-23 12:34:14.767 UTC | null | -1 | null | 7,428,625 | null | 1 | 30 | angular|angular2-forms | 50,740 | <p>This is what eventually worked for me -</p>
<pre><code>this.addEditUserForm = this.builder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
title: ['', Validators.required],
email: ['', Validators.required],
password: ['', Validators.required],
confirmPass: ['', Validators.required]
},{validator: this.checkIfMatchingPasswords('password', 'confirmPass')});
checkIfMatchingPasswords(passwordKey: string, passwordConfirmationKey: string) {
return (group: FormGroup) => {
let passwordInput = group.controls[passwordKey],
passwordConfirmationInput = group.controls[passwordConfirmationKey];
if (passwordInput.value !== passwordConfirmationInput.value) {
return passwordConfirmationInput.setErrors({notEquivalent: true})
}
else {
return passwordConfirmationInput.setErrors(null);
}
}
}
</code></pre> |
9,442,381 | Formatting binary values in Scala | <p>Does Scala have a built in formatter for binary data?</p>
<p>For example to print out: 00000011 for the Int value 3.</p>
<p>Writing one won't be difficult - just curious if it exists.</p> | 9,442,418 | 8 | 1 | null | 2012-02-25 08:00:23.48 UTC | 7 | 2021-03-09 18:45:55.853 UTC | 2012-02-25 08:18:46.163 UTC | null | 41,283 | null | 828,757 | null | 1 | 35 | scala|string-formatting | 30,196 | <pre><code>scala> 3.toBinaryString
res0: String = 11
</code></pre>
<p>Scala has an implicit conversion from Int to RichInt which has a method toBinaryString. This function does not print the leading zeroes though.</p> |
9,110,310 | Update git commit author date when amending | <p>I found myself amending my commits quite often. I don't <code>stash</code> so much because I tend to forget I did so, especially when I want to save what I did before I leave or before a weekend, so I do a "draft" commit. Only thing is, when I amend the commit, it is still set to the original author date. Is there a (simple) way to update it when amending?</p> | 9,110,424 | 5 | 1 | null | 2012-02-02 09:59:27.983 UTC | 117 | 2021-09-27 16:49:38.74 UTC | 2016-04-20 09:43:40.38 UTC | null | 321,731 | null | 669,020 | null | 1 | 384 | git | 122,481 | <p>You can change the author date with the <code>--date</code> parameter to <code>git commit</code>. So, if you want to amend the last commit, and update its author date to the current date and time, you can do:</p>
<pre><code>git commit --amend --date="$(date -R)"
</code></pre>
<p>(The <code>-R</code> parameter to <code>date</code> tells it to output the date in RFC 2822 format. This is one of the <a href="https://git-scm.com/docs/git-commit#_date_formats" rel="noreferrer">date formats understood by <code>git commit</code></a>.)</p> |
58,866,796 | Understanding the React Hooks 'exhaustive-deps' lint rule | <p>I'm having a hard time understanding the 'exhaustive-deps' lint rule.</p>
<p>I already read <a href="https://stackoverflow.com/questions/58549846/react-useeffect-hook-with-warning-react-hooks-exhaustive-deps">this post</a> and <a href="https://stackoverflow.com/questions/57983717/designing-react-hooks-prevent-react-hooks-exhaustive-deps-warning">this post</a> but I could not find an answer.</p>
<p>Here is a simple React component with the lint issue:</p>
<pre><code>const MyCustomComponent = ({onChange}) => {
const [value, setValue] = useState('');
useEffect(() => {
onChange(value);
}, [value]);
return (
<input
value={value}
type='text'
onChange={(event) => setValue(event.target.value)}>
</input>
)
}
</code></pre>
<p>It requires me to add <code>onChange</code> to the <code>useEffect</code> dependencies array. But in my understanding <code>onChange</code> will never change, so it should not be there.</p>
<p>Usually I manage it like this:</p>
<pre><code>const MyCustomComponent = ({onChange}) => {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
onChange(event.target.value)
}
return (
<input
value={value}
type='text'
onChange={handleChange}>
</input>
)
}
</code></pre>
<p>Why the lint? Any clear explanation about the lint rule for the first example?</p>
<p><em>Or should I not be using <code>useEffect</code> here? (I'm a noob with hooks)</em></p> | 58,959,298 | 2 | 6 | null | 2019-11-14 21:28:53.757 UTC | 25 | 2021-04-01 23:02:02.203 UTC | 2021-04-01 23:02:02.203 UTC | null | 117,714 | null | 7,745,173 | null | 1 | 127 | reactjs|react-hooks|eslint | 117,582 | <p>The reason the linter rule wants <code>onChange</code> to go into the <code>useEffect</code> hook is because it's possible for <code>onChange</code> to change between renders, and the lint rule is intended to prevent that sort of "stale data" reference.</p>
<p>For example:</p>
<pre><code>const MyParentComponent = () => {
const onChange = (value) => { console.log(value); }
return <MyCustomComponent onChange={onChange} />
}
</code></pre>
<p>Every single render of <code>MyParentComponent</code> will pass a different <code>onChange</code> function to <code>MyCustomComponent</code>. </p>
<p>In your specific case, you probably don't care: you only want to call <code>onChange</code> when the value changes, not when the <code>onChange</code> function changes. However, that's not clear from how you're using <code>useEffect</code>. </p>
<hr>
<p>The root here is that your <code>useEffect</code> is somewhat unidiomatic. </p>
<p><code>useEffect</code> is best used for side-effects, but here you're using it as a sort of "subscription" concept, like: "do X when Y changes". That does sort of work functionally, due to the mechanics of the <code>deps</code> array, (though in this case you're also calling <code>onChange</code> on initial render, which is probably unwanted), but it's not the intended purpose.</p>
<p>Calling <code>onChange</code> really isn't a side-effect here, it's just an effect of triggering the <code>onChange</code> event for <code><input></code>. So I do think your second version that calls both <code>onChange</code> and <code>setValue</code> together is more idiomatic. </p>
<p>If there were other ways of setting the value (e.g. a clear button), constantly having to remember to call <code>onChange</code> might be tedious, so I might write this as:</p>
<pre class="lang-js prettyprint-override"><code>const MyCustomComponent = ({onChange}) => {
const [value, _setValue] = useState('');
// Always call onChange when we set the new value
const setValue = (newVal) => {
onChange(newVal);
_setValue(newVal);
}
return (
<input value={value} type='text' onChange={e => setValue(e.target.value)}></input>
<button onClick={() => setValue("")}>Clear</button>
)
}
</code></pre>
<p>But at this point this is hair-splitting.</p> |
44,403,930 | Error: Network error: Error writing result to store for query (Apollo Client) | <p>I am using Apollo Client to make an application to query my server using Graphql. I have a python server on which I execute my graphql queries which fetches data from the database and then returns it back to the client. </p>
<p>I have created a custom NetworkInterface for the client that helps me to make make customized server request (by default ApolloClient makes a POST call to the URL we specify). The network interface only has to have a query() method wherein we return the promise for the result of form <code>Promise<ExecutionResult></code>. </p>
<p>I am able to make the server call and fetch the requested data but still getting the following error.</p>
<pre><code>Error: Network error: Error writing result to store for query
{
query something{
row{
data
}
}
}
Cannot read property 'row' of undefined
at new ApolloError (ApolloError.js:32)
at ObservableQuery.currentResult (ObservableQuery.js:76)
at GraphQL.dataForChild (react-apollo.browser.umd.js:410)
at GraphQL.render (react-apollo.browser.umd.js:448)
at ReactCompositeComponent.js:796
at measureLifeCyclePerf (ReactCompositeComponent.js:75)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:746)
at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724)
at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645)
at ReactCompositeComponentWrapper.performUpdateIfNecessary (ReactCompositeComponent.js:561)
at Object.performUpdateIfNecessary (ReactReconciler.js:157)
at runBatchedUpdates (ReactUpdates.js:150)
at ReactReconcileTransaction.perform (Transaction.js:140)
at ReactUpdatesFlushTransaction.perform (Transaction.js:140)
at ReactUpdatesFlushTransaction.perform (ReactUpdates.js:89)
at Object.flushBatchedUpdates (ReactUpdates.js:172)
at ReactDefaultBatchingStrategyTransaction.closeAll (Transaction.js:206)
at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:153)
at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)
at Object.enqueueUpdate (ReactUpdates.js:200)
</code></pre>
<p>I want to know the possible cause of the error and solution if possible.</p> | 55,756,468 | 6 | 3 | null | 2017-06-07 05:05:41.93 UTC | 8 | 2022-03-15 11:30:04.033 UTC | null | null | null | null | 5,956,492 | null | 1 | 56 | javascript|graphql|react-apollo|apollo-client | 23,618 | <p>I had a similar error.
I worked it out by adding id to query.
for example, my current query was</p>
<pre><code>query {
service:me {
productServices {
id
title
}
}
}
</code></pre>
<p>my new query was</p>
<pre><code>query {
service:me {
id // <-------
productServices {
id
title
}
}
}
</code></pre> |
19,652,662 | What is a "runtime context"? | <p>(Edited for even more clarity)</p>
<p>I'm reading the Python book (<em>Python Essential Reference by Beazley</em>) and he says:</p>
<blockquote>
<p>The <code>with</code> statement allows a series of statements to execute inside a
<em>runtime context</em> that is controlled by an object that serves as a context manager.</p>
<p>Here is an example:</p>
<pre><code>with open("debuglog","a") as f:
f.write("Debugging\n")
statements
f.write("Done\n")
</code></pre>
</blockquote>
<p>He goes on to say:</p>
<blockquote>
<p>The with obj statement accepts an optional as var specifier. If given, the value
returned by obj._ <em>enter</em> _() is placed into var. It is important to emphasize
that obj is not necessarily the value assigned to var.</p>
</blockquote>
<p>I understand the mechanics of what a <strong>'with'</strong> keyword does: a file-object is returned by <strong>open</strong> and that object is accessible via <strong>f</strong> within the body of the block. I also understand that <em><strong>enter</strong>()</em> and eventually <em><strong>exit</strong>()</em> will be called.</p>
<p>But what exactly is a run-time context? A few low level details would be nice - or, an example in C. Could someone clarify what exactly a "context" is and how it might relate to other languages (C, C++). My understanding of a context was the environment eg: a <em>Bash</em> shell executes <em>ls</em> in the context of all the (<em>env</em> displayed) shell variables.
With the <em>with</em> keyword - yes <em>f</em> is accessible to the body of the block but isn't that just scoping? <strong>eg: for x in y:</strong> here <em>x</em> is not scoped within the block and retains it's value outside the block - is this what Beazley means when he talks about 'runtime context', that <strong>f</strong> is scoped only within the block and looses all significance outside the with-block?? Why does he say that the statements "execute <strong>inside</strong> a runtime context"??? Is this like an "eval"??</p>
<p>I understand that <code>open</code> returns an object that is <strong>"not ... assigned to var"??</strong>
Why isn't it assigned to var? What does Beazley mean by making a statement like that?</p> | 19,652,828 | 2 | 2 | null | 2013-10-29 07:59:56.693 UTC | 10 | 2020-01-17 21:04:45.437 UTC | 2020-01-17 21:04:45.437 UTC | null | 166,949 | user621819 | null | null | 1 | 12 | python | 4,280 | <p>The <code>with</code> statement was introduced in PEP 343. This PEP also introduced a new term, "context manager", and defined what that term means.</p>
<p>Briefly, a "context manager" is an object that has special method functions <code>.__enter__()</code> and <code>.__exit__()</code>. The <code>with</code> statement guarantees that the <code>.__enter__()</code> method will be called to set up the block of code indented under the <code>with</code> statement, and also guarantees that the <code>.__exit__()</code> method function will be called at the time of exit from the block of code (no matter how the block is exited; for example, if the code raises an exception, <code>.__exit__()</code> will still be called).</p>
<p><a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow noreferrer">http://www.python.org/dev/peps/pep-0343/</a></p>
<p><a href="http://docs.python.org/2/reference/datamodel.html?highlight=context%20manager#with-statement-context-managers" rel="nofollow noreferrer">http://docs.python.org/2/reference/datamodel.html?highlight=context%20manager#with-statement-context-managers</a></p>
<p>The <code>with</code> statement is now the preferred way to handle any task that has a well-defined setup and teardown. Working with a file, for example:</p>
<pre><code>with open(file_name) as f:
# do something with file
</code></pre>
<p>You know the file will be properly closed when you are done.</p>
<p>Another great example is a resource lock:</p>
<pre><code>with acquire_lock(my_lock):
# do something
</code></pre>
<p>You know the code won't run until you get the lock, and as soon as the code is done the lock will be released. I don't often do multithreaded coding in Python, but when I did, this statement made sure that the lock was always released, even in the face of an exception.</p>
<p>P.S. I did a Google search online for examples of context managers and I found this nifty one: a context manager that executes a Python block in a specific directory.</p>
<p><a href="http://ralsina.me/weblog/posts/BB963.html" rel="nofollow noreferrer">http://ralsina.me/weblog/posts/BB963.html</a></p>
<p>EDIT:</p>
<p>The runtime context is the environment that is set up by the call to <code>.__enter__()</code> and torn down by the call to <code>.__exit__()</code>. In my example of acquiring a lock, the block of code runs in the context of having a lock available. In the example of reading a file, the block of code runs in the context of the file being open.</p>
<p>There isn't any secret magic inside Python for this. There is no special scoping, no internal stack, and nothing special in the parser. You simply write two method functions, <code>.__enter__()</code> and <code>.__exit__()</code> and Python calls them at specific points for your <code>with</code> statement.</p>
<p>Look again at this section from the PEP:</p>
<p><em>Remember, PEP 310 proposes roughly this syntax (the "VAR =" part is optional):</em></p>
<pre><code> with VAR = EXPR:
BLOCK
</code></pre>
<p><em>which roughly translates into this:</em></p>
<pre><code> VAR = EXPR
VAR.__enter__()
try:
BLOCK
finally:
VAR.__exit__()
</code></pre>
<p>In both examples, <code>BLOCK</code> is a block of code that runs in a specific runtime context that is set up by the call to <code>VAR.__enter__()</code> and torn down by <code>VAR.__exit__()</code>.</p>
<p>There are two main benefits to the <code>with</code> statement and the way it is all set up.</p>
<p>The more concrete benefit is that it's "syntactic sugar". I would much rather write a two-line <code>with</code> statement than a six-line sequence of statements; it's easier two write the shorter one, it looks nicer and is easier to understand, and it is easier to get right. Six lines versus two means more chances to screw things up. (And before the <code>with</code> statement, I was usually sloppy about wrapping file I/O in a <code>try</code> block; I only did it sometimes. Now I always use <code>with</code> and always get the exception handling.)</p>
<p>The more abstract benefit is that this gives us a new way to think about designing our programs. Raymond Hettinger, in a talk at PyCon 2013, put it this way: when we are writing programs we look for common parts that we can factor out into functions. If we have code like this:</p>
<pre><code>A
B
C
D
E
F
B
C
D
G
</code></pre>
<p>we can easily make a function:</p>
<pre><code>def BCD():
B
C
D
A
BCD()
E
F
BCD()
G
</code></pre>
<p>But we have never had a really clean way to do this with setup/teardown. When we have a lot of code like this:</p>
<pre><code>A
BCD()
E
A
XYZ()
E
A
PDQ()
E
</code></pre>
<p>Now we can define a context manager and rewrite the above:</p>
<pre><code>with contextA:
BCD()
with contextA:
XYZ()
with contextA:
PDQ()
</code></pre>
<p>So now we can think about our programs and look for setup/teardown that can be abstracted into a "context manager". Raymond Hettinger showed several new "context manager" recipes he had invented (and I'm racking my brain trying to remember an example or two for you).</p>
<p>EDIT: Okay, I just remembered one. Raymond Hettinger showed a recipe, that will be built in to Python 3.4, for using a <code>with</code> statement to ignore an exception within a block. See it here: <a href="https://stackoverflow.com/a/15566001/166949">https://stackoverflow.com/a/15566001/166949</a></p>
<p>P.S. I've done my best to give the sense of what he was saying... if I have made any mistake or misstated anything, it's on me and not on him. (And he posts on StackOverflow sometimes so he might just see this and correct me if I've messed anything up.)</p>
<p>EDIT: You've updated the question with more text. I'll answer it specifically as well.</p>
<p><em>is this what Beazley means when he talks about 'runtime context', that f is scoped only within the block and looses all significance outside the with-block?? Why does he say that the statements "execute inside a runtime context"??? Is this like an "eval"??</em></p>
<p>Actually, <code>f</code> is not scoped only within the block. When you bind a name using the <code>as</code> keyword in a <code>with</code> statement, the name remains bound after the block.</p>
<p>The "runtime context" is an informal concept and it means "the state set up by the <code>.__enter__()</code> method function call and torn down by the <code>.__exit__()</code> method function call." Again, I think the best example is the one about getting a lock before the code runs. The block of code runs in the "context" of having the lock.</p>
<p><em>I understand that open returns an object that is "not ... assigned to var"?? Why isn't it assigned to var? What does Beazley mean by making a statement like that?</em></p>
<p>Okay, suppose we have an object, let's call it <code>k</code>. <code>k</code> implements a "context manager", which means that it has method functions <code>k.__enter__()</code> and <code>k.__exit__()</code>. Now we do this:</p>
<pre><code>with k as x:
# do something
</code></pre>
<p>What David Beazley wants you to know is that <code>x</code> will not necessarily be bound to <code>k</code>. <code>x</code> will be bound to whatever <code>k.__enter__()</code> returns. <code>k.__enter__()</code> is free to return a reference to <code>k</code> itself, but is also free to return something else. In this case:</p>
<pre><code>with open(some_file) as f:
# do something
</code></pre>
<p>The call to <code>open()</code> returns an open file object, which works as a context manager, and its <code>.__enter__()</code> method function really does just return a reference to itself.</p>
<p>I think most context managers return a reference to self. Since it's an object it can have any number of member variables, so it can return any number of values in a convenient way. But it isn't required.</p>
<p>For example, there could be a context manager that starts a daemon running in the <code>.__enter__()</code> function, and returns the process ID number of the daemon from the <code>.__enter__()</code> function. Then the <code>.__exit__()</code> function would shut down the daemon. Usage:</p>
<pre><code>with start_daemon("parrot") as pid:
print("Parrot daemon running as PID {}".format(pid))
daemon = lookup_daemon_by_pid(pid)
daemon.send_message("test")
</code></pre>
<p>But you could just as well return the context manager object itself with any values you need tucked inside:</p>
<pre><code>with start_daemon("parrot") as daemon:
print("Parrot daemon running as PID {}".format(daemon.pid))
daemon.send_message("test")
</code></pre>
<p>If we need the PID of the daemon, we can just put it in a <code>.pid</code> member of the object. And later if we need something else we can just tuck that in there as well.</p> |
35,144,130 | In `knitr` how can I test for if the output will be PDF or word? | <p>I would like to include specific content based on which format is being created. In this specific example, my tables look terrible in <code>MS word</code> output, but great in <code>HTML</code>. I would like to add in some test to leave out the table depending on the output.</p>
<p>Here's some pseudocode:</p>
<pre><code>output.format <- opts_chunk$get("output")
if(output.format != "MS word"){
print(table1)
}
</code></pre>
<p>I'm sure this is not the correct way to use <code>opts_chunk</code>, but this is the limit of my understanding of how <code>knitr</code> works under the hood. What would be the correct way to test for this?</p> | 35,149,103 | 5 | 3 | null | 2016-02-02 02:42:58.187 UTC | 11 | 2021-06-20 22:39:49.29 UTC | 2016-02-02 07:28:23.313 UTC | null | 378,085 | null | 378,085 | null | 1 | 40 | r|knitr | 5,366 | <h2>Short Answer</h2>
<p>In most cases, <code>opts_knit$get("rmarkdown.pandoc.to")</code> delivers the required information.</p>
<p>Otherwise, query <code>rmarkdown::all_output_formats(knitr::current_input())</code> and check if the return value contains <code>word_document</code>:</p>
<pre><code>if ("word_document" %in% rmarkdown::all_output_formats(knitr::current_input()) {
# Word output
}
</code></pre>
<h2>Long answer</h2>
<p>I assume that the source document is RMD because this is the usual/most common input format for knitting to different output formats such as MS Word, PDF and HTML.</p>
<p>In this case, <code>knitr</code> options cannot be used to determine the final output format because it doesn't matter from the perspective of <code>knitr</code>: For all output formats, <code>knitr</code>'s job is to knit the input RMD file to a MD file. The conversion of the MD file to the output format specified in the YAML header is done in the next stage, by <code>pandoc</code>. </p>
<p>Therefore, we cannot use the <a href="http://yihui.name/knitr/options/#package_options" rel="noreferrer">package option</a> <code>knitr::opts_knit$get("out.format")</code> to learn about the final output format but we need to parse the YAML header instead. </p>
<p><strong>So far in theory.</strong> Reality is a little bit different. RStudio's "Knit PDF"/"Knit HTML" button calls <code>rmarkdown::render</code> which in turn calls <code>knit</code>. Before this happens, <a href="https://github.com/rstudio/rmarkdown/blob/314eff98ecc080a7996fe1ad5461a50bdd162a9c/R/render.R#L246" rel="noreferrer"><code>render</code> sets</a> a <a href="http://yihui.name/knitr/options/#package_options" rel="noreferrer">(undocumented?) package option</a> <code>rmarkdown.pandoc.to</code> to the actual output format. The value will be <code>html</code>, <code>latex</code> or <code>docx</code> respectively, depending on the output format.</p>
<p>Therefore, if (and only if) RStudio's "Knit PDF"/"Knit HTML" button is used, <code>knitr::opts_knit$get("rmarkdown.pandoc.to")</code> can be used to determine the output format. This is also described in <a href="https://stackoverflow.com/questions/25528067/ifelse-action-depending-on-document-type-in-rmarkdown">this answer</a> and <a href="http://www.r-bloggers.com/rmarkdown-alter-action-depending-on-document/" rel="noreferrer">that blog post</a>.</p>
<p>The problem remains unsolved for the case of calling <code>knit</code> directly because then <code>rmarkdown.pandoc.to</code> is not set. In this case we can exploit the (unexported) function <code>parse_yaml_front_matter</code> from the <code>rmarkdown</code> package to parse the YAML header.</p>
<p>[<strong>Update</strong>: As of <code>rmarkdown</code> 0.9.6, the function <code>all_output_formats</code> has been added (thanks to <a href="https://stackoverflow.com/questions/35144130/in-knitr-how-can-i-test-for-if-the-output-will-be-pdf-or-word/35149103?noredirect=1#comment64054064_35149103">Bill Denney</a> for pointing this out). It makes the custom function developed below obsolete – for production, use <code>rmarkdown::all_output_formats</code>! I leave the remainder of this answer as originally written for educational purposes.]</p>
<pre><code>---
output: html_document
---
```{r}
knitr::opts_knit$get("out.format") # Not informative.
knitr::opts_knit$get("rmarkdown.pandoc.to") # Works only if knit() is called via render(), i.e. when using the button in RStudio.
rmarkdown:::parse_yaml_front_matter(
readLines(knitr::current_input())
)$output
```
</code></pre>
<p>The example above demonstrates the use(lesness) of <code>opts_knit$get("rmarkdown.pandoc.to")</code> (<code>opts_knit$get("out.format")</code>), while the line employing <code>parse_yaml_front_matter</code> returns the format specified in the "output" field of the YAML header.</p>
<p>The input of <code>parse_yaml_front_matter</code> is the source file as character vector, as returned by <code>readLines</code>. To determine the name of the file currently being knitted, <code>current_input()</code> as suggested in <a href="https://stackoverflow.com/a/25294943/2706569">this answer</a> is used.</p>
<p>Before <code>parse_yaml_front_matter</code> can be used in a simple <code>if</code> statement to implement behavior that is conditional on the output format, a small refinement is required: The statement shown above may return a list if there are additional YAML parameters for the output like in this example:</p>
<pre><code>---
output:
html_document:
keep_md: yes
---
</code></pre>
<p>The following helper function should resolve this issue:</p>
<pre><code>getOutputFormat <- function() {
output <- rmarkdown:::parse_yaml_front_matter(
readLines(knitr::current_input())
)$output
if (is.list(output)){
return(names(output)[1])
} else {
return(output[1])
}
}
</code></pre>
<p>It can be used in constructs such as</p>
<pre><code>if(getOutputFormat() == 'html_document') {
# do something
}
</code></pre>
<p>Note that <code>getOutputFormat</code> uses only the first output format specified, so with the following header only <code>html_document</code> is returned:</p>
<pre><code>---
output:
html_document: default
pdf_document:
keep_tex: yes
---
</code></pre>
<p>However, this is not very restrictive. When RStudio's "Knit HTML"/"Knit PDF" button is used (along with the dropdown menu next to it to select the output type), RStudio rearranges the YAML header such that the selected output format <em>will</em> be the first format in the list. Multiple output formats are (AFAIK) only relevant when using <code>rmarkdown::render</code> with <code>output_format = "all"</code>. And: In both of these cases <code>rmarkdown.pandoc.to</code> can be used, which is easier anyways. </p> |
976,015 | Why do I need to close fds when reading and writing to the pipe? | <p>Here is an <a href="http://tldp.org/LDP/lpg/node11.html" rel="noreferrer">example</a> to illustrate what I mean:</p>
<pre><code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
</code></pre>
<p>}</p>
<p>However, what if one of my processes needs to continuously write to the pipe while the other pipe needs to read?</p>
<p>The example above seems to work only for one write and one read.</p> | 976,087 | 5 | 6 | null | 2009-06-10 14:42:18.777 UTC | 10 | 2018-11-20 19:57:27.44 UTC | 2009-06-10 15:07:15.467 UTC | null | 5,640 | Sasha | null | null | 1 | 11 | c++|c|multithreading|pipe|unix | 11,654 | <p>Your pipe is a unidirectional stream - with a file descriptor for each end. It is not necessary to close() either end of the pipe to allow data to pass along it.</p>
<p><strong>if your pipe spans processes</strong> (i.e. is created before a fork() and then the parent and child use it to communicate) you can have one write and and one read end. Then it is good practice to close the unwanted ends of the pipe. This will</p>
<ul>
<li>make sure that when the writing end closes the pipe it is seen by the read end. As an example, say the child is the write side, and it dies. If the parent write side has not been closed, then the parent will not get "eof" (zero length read()) from the pipe - because the pipe has a open write-end.</li>
<li>make it clear which process is doing the writing and which process is doing the reading on the pipe.</li>
</ul>
<p><strong>if your pipe spans threads</strong> (within the same process), then do not close the unwanted ends of the pipe. This is because the file descriptor is held by the process, and closing it for one thread will close it for all threads, and therefore the pipe will become unusable.</p>
<p>There is nothing stopping you having one process writing continuously to the pipe and the other process reading. If this is a problem you are having then give us more details to help you out.</p> |
571,327 | Excel VBA object constructor and destructor | <p>I need to make some custom objects in VBA that will need to reference each other and I have a some issues.</p>
<p>First - how do object constructors work in VBA? Are there constructors?</p>
<p>Second - are there destructors? How does VBA handle the end of the object lifecycle? If I have an object that references others (and this is their only reference), then can I set it to Nothing and be done with it or could that produce memory leaks?</p>
<p>This quasi-OO stuff is just a little bit irritating.</p> | 571,352 | 5 | 1 | null | 2009-02-20 21:37:37.223 UTC | 3 | 2018-07-10 17:12:30.54 UTC | 2018-07-10 17:12:30.54 UTC | divo | 8,112,776 | notnot | 65,184 | null | 1 | 26 | vba|object|memory-leaks|constructor|destructor | 47,316 | <p>VBA supports Class Modules. They have a Class_Initialize event that is the constructor and a Class_Terminate that is the destructor. You can define properties and methods.
I believe VBA uses reference counting for object lifecycle. Which is why you see a lot of Set whatever = Nothing in that type of code. In your example case I think it will not leak any memory. But you need to be careful of circular references.</p> |
920,910 | Sending Multipart html emails which contain embedded images | <p>I've been playing around with the email module in python but I want to be able to know how to embed images which are included in the html.</p>
<p>So for example if the body is something like</p>
<pre><code><img src="../path/image.png"></img>
</code></pre>
<p>I would like to embed <em>image.png</em> into the email, and the <code>src</code> attribute should be replaced with <code>content-id</code>. Does anybody know how to do this?</p> | 49,098,251 | 5 | 0 | null | 2009-05-28 13:45:57.843 UTC | 67 | 2022-09-07 17:09:06.443 UTC | 2015-09-28 08:37:35.3 UTC | null | 2,642,204 | null | 100,758 | null | 1 | 95 | python|email|mime|attachment|multipart | 135,338 | <p><strong>For Python versions 3.4 and above.</strong></p>
<p>The accepted answer is excellent, but only suitable for older Python versions (2.x and 3.3). I think it needs an update.</p>
<p>Here's how you can do it in newer Python versions (3.4 and above):</p>
<pre><code>from email.message import EmailMessage
from email.utils import make_msgid
import mimetypes
msg = EmailMessage()
# generic email headers
msg['Subject'] = 'Hello there'
msg['From'] = 'ABCD <[email protected]>'
msg['To'] = 'PQRS <[email protected]>'
# set the plain text body
msg.set_content('This is a plain text body.')
# now create a Content-ID for the image
image_cid = make_msgid(domain='xyz.com')
# if `domain` argument isn't provided, it will
# use your computer's name
# set an alternative html body
msg.add_alternative("""\
<html>
<body>
<p>This is an HTML body.<br>
It also has an image.
</p>
<img src="cid:{image_cid}">
</body>
</html>
""".format(image_cid=image_cid[1:-1]), subtype='html')
# image_cid looks like <[email protected]>
# to use it as the img src, we don't need `<` or `>`
# so we use [1:-1] to strip them off
# now open the image and attach it to the email
with open('path/to/image.jpg', 'rb') as img:
# know the Content-Type of the image
maintype, subtype = mimetypes.guess_type(img.name)[0].split('/')
# attach it
msg.get_payload()[1].add_related(img.read(),
maintype=maintype,
subtype=subtype,
cid=image_cid)
# the message is ready now
# you can write it to a file
# or send it using smtplib
</code></pre> |
1,185,712 | How to use AJAX to populate state list depending on Country list? | <p>I have the code below that will change a state dropdown list when you change the country list.<br>
How can I make it change the state list ONLY when country ID number 234 and 224 are selected?<br>
If another country is selected it should be change into this text input box</p>
<pre><code><input type="text" name="othstate" value="" class="textBox">
</code></pre>
<p><strong>The form</strong></p>
<pre><code><form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
</code></pre>
<p><strong>The javascript</strong></p>
<pre><code><script>
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
</code></pre> | 1,185,725 | 6 | 0 | null | 2009-07-26 22:18:14.513 UTC | 3 | 2019-03-13 11:16:11.967 UTC | 2014-09-03 09:47:10.773 UTC | null | 3,748,572 | null | 143,030 | null | 1 | 4 | ajax|drop-down-menu | 49,473 | <p>Just check the countryId value before you do the AJAX request and only perform the request if the countryId is in the allowable range. In the case where the countryId doesn't match, I would hide the select (probably clear it's value, too) and show an already existing input that was previously hidden. The reverse should be done if an allowable country is chosen.</p>
<p>jQuery example below:</p>
<pre><code><form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" value="" class="textBox" style="display: none;">
</form>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
</code></pre> |
932,339 | .NET Assembly Plugin Security | <p>I have used the following code in a number of applications to load .DLL assemblies that expose plugins.</p>
<p>However, I previously was always concerned with functionality, rather than security.</p>
<p>I am now planning to use this method on a web application that could be used by groups other than me, and I would like to make sure that the security of the function is up-to-snuff.</p>
<pre><code>private void LoadPlugins(string pluginsDirectory)
{
List<IPluginFactory> factories = new List<IPluginFactory>();
foreach (string path in Directory.GetFiles(pluginsDirectory, "*.dll"))
{
Assembly assembly = Assembly.LoadFile(path);
foreach (Type type in assembly.GetTypes())
{
IPluginEnumerator instance = null;
if (type.GetInterface("IPluginEnumerator") != null)
instance = (IPluginEnumerator)Activator.CreateInstance(type);
if (instance != null)
{
factories.AddRange(instance.EnumerateFactories());
}
}
}
// Here, I would usually collate the plugins into List<ISpecificPlugin>, etc.
}
</code></pre>
<p>The first few concerns I have:</p>
<ol>
<li>This function reads the entire directory and doesn't care about what assemblies it loads, and instead just loads all of them. Is there a way to detect whether an assembly is a valid, functional .NET assembly before loading it with Assembly.LoadFile()?</li>
<li>What kind of exception handling should be added to the function to prevent initialization of the assembly from halting my code?</li>
<li>If I want to deny the assembly the right to do the following: Read/Write files, Read/Wite the registry, etc, how would I do that?</li>
</ol>
<p>Are there any other security concerns I should be worried about?</p>
<p><strong>EDIT: Keep in mind that I want anybody to be able to write a plug-in, but I still want to be secure.</strong></p> | 1,350,012 | 6 | 0 | null | 2009-05-31 16:04:03.9 UTC | 9 | 2012-07-21 16:54:30.737 UTC | 2009-08-29 15:41:59.273 UTC | null | 57,986 | null | 57,986 | null | 1 | 11 | c#|security|reflection|plugins | 4,818 | <p>1) strong name the assembly with a certain key.</p>
<ul>
<li>you do <strong>not</strong> have to put it in the GAC</li>
<li>you can re-use a key to sign more than one assembly</li>
<li>when you re-use the key, you get the same "public key" on each signed assembly</li>
</ul>
<p>2) on load, check that the assembly has been strong named with the key you're expecting</p>
<ul>
<li>You can store the public key as a binary file, an embedded resource,
or use the existing public key of the executing assembly </li>
<li>this last way may not be the best way as you may want to differentiate assemblies
signed with the "plugin" key from those signed with a regular key)</li>
</ul>
<p>Example:</p>
<pre><code>public static StrongName GetStrongName(Assembly assembly)
{
if(assembly == null)
throw new ArgumentNullException("assembly");
AssemblyName assemblyName = assembly.GetName();
// get the public key blob
byte[] publicKey = assemblyName.GetPublicKey();
if(publicKey == null || publicKey.Length == 0)
throw new InvalidOperationException( String.Format("{0} is not strongly named", assembly));
StrongNamePublicKeyBlob keyBlob = new StrongNamePublicKeyBlob(publicKey);
// create the StrongName
return new StrongName(keyBlob, assemblyName.Name, assemblyName.Version);
}
// load the assembly:
Assembly asm = Assembly.LoadFile(path);
StrongName sn = GetStrongName(asm);
// at this point
// A: assembly is loaded
// B: assembly is signed
// C: we're reasonably certain the assembly has not been tampered with
// (the mechanism for this check, and it's weaknesses, are documented elsewhere)
// all that remains is to compare the assembly's public key with
// a copy you've stored for this purpose, let's use the executing assembly's strong name
StrongName mySn = GetStrongName(Assembly.GetExecutingAssembly());
// if the sn does not match, put this loaded assembly in jail
if (mySn.PublicKey!=sn.PublicKey)
return false;
</code></pre>
<p>note: code has not been tested or compiled, may contain syntax errors.</p> |
1,199,470 | combine javascript files at deployment in python | <p>I'm trying to reduce the number of scripts included in our website and we use buildout to handle deployments. Has anybody successfully implemented a method of combining and compressing scripts with buildout?</p> | 1,199,481 | 6 | 0 | null | 2009-07-29 11:06:42.253 UTC | 18 | 2018-08-04 23:13:32.747 UTC | 2009-08-05 02:53:58.44 UTC | null | 10,293 | null | 65,556 | null | 1 | 13 | javascript|python|deployment|buildout|jscompress | 6,469 | <p>Here's a Python script I made that I use with all my heavy JavaScript projects. I'm using YUICompressor, but you can change the code to use another compressor.</p>
<pre><code>import os, os.path, shutil
YUI_COMPRESSOR = 'yuicompressor-2.4.2.jar'
def compress(in_files, out_file, in_type='js', verbose=False,
temp_file='.temp'):
temp = open(temp_file, 'w')
for f in in_files:
fh = open(f)
data = fh.read() + '\n'
fh.close()
temp.write(data)
print ' + %s' % f
temp.close()
options = ['-o "%s"' % out_file,
'--type %s' % in_type]
if verbose:
options.append('-v')
os.system('java -jar "%s" %s "%s"' % (YUI_COMPRESSOR,
' '.join(options),
temp_file))
org_size = os.path.getsize(temp_file)
new_size = os.path.getsize(out_file)
print '=> %s' % out_file
print 'Original: %.2f kB' % (org_size / 1024.0)
print 'Compressed: %.2f kB' % (new_size / 1024.0)
print 'Reduction: %.1f%%' % (float(org_size - new_size) / org_size * 100)
print ''
#os.remove(temp_file)
</code></pre>
<p>I use it like this (the below is just a code snippet, and assumes that the <code>compress</code> function exists in the current namespace):</p>
<pre><code>SCRIPTS = [
'app/js/libs/EventSource.js',
'app/js/libs/Hash.js',
'app/js/libs/JSON.js',
'app/js/libs/ServiceClient.js',
'app/js/libs/jquery.hash.js',
'app/js/libs/Application.js',
'app/js/intro.js',
'app/js/jquery-extras.js',
'app/js/settings.js',
'app/js/api.js',
'app/js/game.js',
'app/js/user.js',
'app/js/pages.intro.js',
'app/js/pages.home.js',
'app/js/pages.log-in.js',
'app/js/pages.log-out.js',
'app/js/pages.new-command.js',
'app/js/pages.new-frame.js',
'app/js/pages.not-found.js',
'app/js/pages.register.js',
'app/js/pages.outro.js',
'app/js/outro.js',
]
SCRIPTS_OUT_DEBUG = 'app/js/multifarce.js'
SCRIPTS_OUT = 'app/js/multifarce.min.js'
STYLESHEETS = [
'app/media/style.css',
]
STYLESHEETS_OUT = 'app/media/style.min.css'
def main():
print 'Compressing JavaScript...'
compress(SCRIPTS, SCRIPTS_OUT, 'js', False, SCRIPTS_OUT_DEBUG)
print 'Compressing CSS...'
compress(STYLESHEETS, STYLESHEETS_OUT, 'css')
if __name__ == '__main__':
main()
</code></pre> |
760,978 | Long-running ssh commands in python paramiko module (and how to end them) | <p>I want to run a <code>tail -f logfile</code> command on a remote machine using python's paramiko module. I've been attempting it so far in the following fashion:</p>
<pre><code>interface = paramiko.SSHClient()
#snip the connection setup portion
stdin, stdout, stderr = interface.exec_command("tail -f logfile")
#snip into threaded loop
print stdout.readline()
</code></pre>
<p>I'd like the command to run as long as necessary, but I have 2 problems:</p>
<ol>
<li>How do I stop this cleanly? I thought of making a Channel and then using the <code>shutdown()</code> command on the channel when I'm through with it- but that seems messy. Is it possible to do something like sent <code>Ctrl-C</code> to the channel's stdin?</li>
<li><code>readline()</code> blocks, and I could avoid threads if I had a non-blocking method of getting output- any thoughts?</li>
</ol> | 836,069 | 6 | 1 | null | 2009-04-17 15:51:20.05 UTC | 13 | 2020-03-26 03:20:26.317 UTC | null | null | null | null | 17,925 | null | 1 | 25 | python|ssh|paramiko | 48,886 | <p>1) You can just close the client if you wish. The server on the other end will kill the tail process. </p>
<p>2) If you need to do this in a non-blocking way, you will have to use the channel object directly. You can then watch for both stdout and stderr with channel.recv_ready() and channel.recv_stderr_ready(), or use select.select.</p> |
1,282,726 | Get subdomain and load it to url with greasemonkey | <p>I am having the URL <a href="http://somesubdomain.domain.com" rel="noreferrer">http://somesubdomain.domain.com</a> (subdomains may vary, domain is always the same). Need to take subdomain and reload the page with something like domain.com/some/path/here/somesubdomain using greasemonkey (or open a new window with URL domain.com/some/path/here/somesubdomain, whatever).</p> | 1,282,760 | 6 | 0 | null | 2009-08-15 20:07:48.63 UTC | 9 | 2021-08-05 07:12:27.007 UTC | null | null | null | user157011 | null | null | 1 | 37 | javascript|url|greasemonkey | 48,702 | <pre><code>var full = window.location.host
//window.location.host is subdomain.domain.com
var parts = full.split('.')
var sub = parts[0]
var domain = parts[1]
var type = parts[2]
//sub is 'subdomain', 'domain', type is 'com'
var newUrl = 'http://' + domain + '.' + type + '/your/other/path/' + subDomain
window.open(newUrl);
</code></pre> |
648,814 | Direct array initialization with a constant value | <p>Whenever you allocate a new array in C# with </p>
<pre><code>new T[length]
</code></pre>
<p>the array entries are set to the default of T. That is <code>null</code> for the case that <code>T</code> is a reference type or the result of the default constructor of <code>T</code>, if <code>T</code> is a value type.</p>
<p>In my case i want to initialize an <code>Int32</code> array with the value -1:</p>
<pre><code>var myArray = new int[100];
for (int i=0; i<myArray.Length; i++) { myArray[i] = -1; }
</code></pre>
<p>So after the memory is reserved for the array, the CLR loops over the newly allocated memory and sets all entries to default(int) = 0. After that, my code sets all entries to -1. </p>
<p>That makes the initialization redundant. Does the JIT detect this and neglects the initialization to 0 and if not, is there a way to directly initialize a portion of memory with a custom value?</p>
<p>Referring to <a href="https://stackoverflow.com/questions/136836/c-array-initialization-with-non-default-value">C# Array initialization - with non-default value </a>, using <code>Enumerable.Repeat(value, length).ToArray()</code> is no option, because <code>Enumerable.ToArray</code> allocates a new array and copies the values to it afterwards.</p> | 648,818 | 6 | 1 | null | 2009-03-15 23:37:29.127 UTC | 4 | 2021-03-04 19:41:59.467 UTC | 2017-05-23 12:10:10.513 UTC | null | -1 | Rauhotz | 48,722 | null | 1 | 51 | c#|arrays|initialization|constants | 57,422 | <p>It's not redundant.</p>
<p>Suppose an exception is thrown during your initialization loop. If the CLR hasn't cleared the memory first, you might be able to "see" the original uninitialized memory, which is a very bad idea, particularly from a security standpoint. That's why the CLR guarantees that any newly allocated memory is wiped to a 0 bit pattern.</p>
<p>The same argument holds for fields in an object, by the way.</p>
<p>I suppose in both cases the CLR could check that you're not going to make the array visible elsewhere before finishing initialization, but it's a complicated check to avoid a pretty simple "wipe this area of memory".</p> |
1,104,457 | Auto-initializing C# lists | <p>I am creating a new C# List (<code>List<double></code>). Is there a way, other than to do a loop over the list, to initialize all the starting values to 0?</p> | 1,104,527 | 6 | 1 | null | 2009-07-09 15:02:31.12 UTC | 10 | 2015-09-16 00:05:07.66 UTC | 2012-09-24 14:12:58.587 UTC | null | 63,550 | null | 132,528 | null | 1 | 68 | c#|.net|list|collections | 117,792 | <p>In addition to the functional solutions provided (using the static methods on the <code>Enumerable</code> class), you can pass an array of <code>double</code>s in the constructor.</p>
<pre><code>var tenDoubles = new List<double>(new double[10]);
</code></pre>
<p>This works because the default value of an <code>double</code> is already 0, and probably performs slightly better.</p> |
44,004,451 | Navigator operation requested with a context that does not include a Navigator | <p>I'm trying to start a new screen within an onTap but I get the following error:</p>
<blockquote>
<p>Navigator operation requested with a context that does not include a
Navigator.</p>
</blockquote>
<p>The code I am using to navigate is:</p>
<pre><code>onTap: () { Navigator.of(context).pushNamed('/settings'); },
</code></pre>
<p>I have set up a route in my app as follows:</p>
<pre><code>routes: <String, WidgetBuilder>{
'/settings': (BuildContext context) => new SettingsPage(),
},
</code></pre>
<p>I've tried to copy the code using the stocks sample application. I've looked at the Navigator and Route documentation and can't figure out how the context can be made to include a Navigator. The <code>context</code> being used in the onTap is referenced from the parameter passed into the build method:</p>
<pre><code>class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
</code></pre>
<p>SettingsPage is a class as follows:</p>
<pre><code>class SettingsPage extends Navigator {
Widget buildAppBar(BuildContext context) {
return new AppBar(
title: const Text('Settings')
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: buildAppBar(context),
);
}
}
</code></pre> | 51,292,613 | 16 | 1 | null | 2017-05-16 14:35:51.813 UTC | 30 | 2022-06-21 16:58:00.067 UTC | null | null | null | null | 411,539 | null | 1 | 147 | flutter | 124,336 | <p><em>TLDR</em>: Wrap the widget which needs to access to <code>Navigator</code> into a <code>Builder</code> or extract that sub-tree into a class. And use the new <code>BuildContext</code> to access <code>Navigator</code>.</p>
<hr />
<p>This error is unrelated to the destination. It happens because you used a <code>context</code> that doesn't contain a <code>Navigator</code> instance as parent.</p>
<p><strong>How do I create a Navigator instance then ?</strong></p>
<p>This is usually done by inserting in your widget tree a <code>MaterialApp</code> or <code>WidgetsApp</code>. Although you can do it manually by using <code>Navigator</code> directly but less recommended. Then, all children of such widget can access <code>NavigatorState</code> using <code>Navigator.of(context)</code>.</p>
<p><strong>Wait, I already have a <code>MaterialApp</code>/<code>WidgetsApp</code> !</strong></p>
<p>That's most likely the case. But this error can still happens when you use a <code>context</code> that is a parent of <code>MaterialApp</code>/<code>WidgetsApp</code>.</p>
<p>This happens because when you do <code>Navigator.of(context)</code>, it will start from the widget associated to the <code>context</code> used. And then go upward in the widget tree until it either find a <code>Navigator</code> or there's no more widget.</p>
<p>In the first case, everything is fine. In the second, it throws a</p>
<blockquote>
<p>Navigator operation requested with a context that does not include a Navigator.</p>
</blockquote>
<p><strong>So, how do I fix it ?</strong></p>
<p>First, let's reproduce this error :</p>
<pre><code>import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Center(
child: RaisedButton(
child: Text("Foo"),
onPressed: () => Navigator.pushNamed(context, "/"),
),
),
);
}
}
</code></pre>
<p>This example creates a button that attempts to go to '/' on click but will instead throw an exception.</p>
<p>Notice here that in the</p>
<pre><code> onPressed: () => Navigator.pushNamed(context, "/"),
</code></pre>
<p>we used <code>context</code> passed by to <code>build</code> of <code>MyApp</code>.</p>
<p>The problem is, <code>MyApp</code> is actually a parent of <code>MaterialApp</code>. As it's the widget who instantiate <code>MaterialApp</code>! Therefore <code>MyApp</code>'s <code>BuildContext</code> doesn't have a <code>MaterialApp</code> as parent!</p>
<p>To solve this problem, we need to use a different <code>context</code>.</p>
<p>In this situation, the easiest solution is to introduce a new widget as child of <code>MaterialApp</code>. And then use that widget's context to do the <code>Navigator</code> call.</p>
<p>There are a few ways to achieve this. You can extract <code>home</code> into a custom class :</p>
<pre><code>import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHome()
);
}
}
class MyHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
child: Text("Foo"),
onPressed: () => Navigator.pushNamed(context, "/"),
),
);
}
}
</code></pre>
<p>Or you can use <code>Builder</code> :</p>
<pre><code>import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Builder(
builder: (context) => Center(
child: RaisedButton(
child: Text("Foo"),
onPressed: () => Navigator.pushNamed(context, "/"),
),
),
),
);
}
}
</code></pre> |
17,977,869 | How to filter my data? (ng-grid) | <p>I think this is most likely very simple but I cannot find any clear documentation on how to add a filter outside of the 'filterText' that is shown on their website. What I am trying to do is something as simple as this: </p>
<pre><code>$scope.filterOptions = {
filter: $scope.myFilter, // <- How to do something like this?
useExternalFilter: true
}
$scope.gridOptions = {
data: 'entries',
enableColumnResize: false,
multiSelect: false,
enableSorting: false,
selectedItems: $scope.selectedEntries,
filterOptions: $scope.filterOptions
}
$scope.lowerLimit = 50;
// My Filter
$scope.myFilter = function(entry) {
if (entry < $scope.lowerLimit) {
return false;
}
return true;
}
</code></pre>
<p>Edit: Or maybe if I could filter the datasource somehow? I tried this: </p>
<pre><code>$scope.gridOptions = {
data: 'entries | filter: myFilter',
enableColumnResize: false,
multiSelect: false,
enableSorting: false,
selectedItems: $scope.selectedEntries,
}
</code></pre>
<p>But it is throwing quite a few errors. </p> | 17,979,710 | 3 | 8 | null | 2013-07-31 18:14:07.39 UTC | 14 | 2014-11-12 22:23:50.04 UTC | 2013-07-31 19:13:59.883 UTC | null | 1,146,259 | null | 1,146,259 | null | 1 | 26 | javascript|angularjs|filtering|ng-grid | 45,063 | <p>I have found a way that updates instantly. Basically I hold a hidden set of all my data, and upon receiving new data or changing my filter - I apply this filter to the full data set and hand the grid the filtered version. </p>
<p>This lets me use <strong><em>comparators</em></strong> (i.e. age >= 50) in my filter, which is the purpose of this question. </p>
<pre><code>// Full unfiltered data set
$scope.entries = []; // Updated and pushed to
$scope.gridOptions = {
// The grids already filtered data set
data: 'filteredEntries',
enableColumnResize: false,
multiSelect: false,
enableSorting: false,
selectedItems: $scope.selectedEntries,
}
$scope.$on("updateEntries", function(data) {
// My table is filled by socket pushes, this is where it is updated.
$scope.updateFilters();
}
$scope.$on("newFilter", function(newFilter) {
// This is where I update my filter
$scope.updateFilters();
}
$scope.updateFilters = function() {
// Filters the full set and hands the result to the grid.
$scope.filteredEntries = $filter('filter')($scope.entries, $scope.myFilter);
$scope.$digest();
}
// A modifiable limit, modify through newFilter so data is refiltered
$scope.lowerLimit = 50;
// My Filter
$scope.myFilter = function(entry) {
if (entry < $scope.lowerLimit) {
return false;
}
return true;
}
</code></pre> |
33,232,849 | Increase HTTP Post maxPostSize in Spring Boot | <p>I've got a fairly simple Spring Boot web application, I have a single HTML page with a form with <code>enctype="multipart/form-data"</code>. I'm getting this error:</p>
<blockquote>
<p>The multi-part request contained parameter data (excluding uploaded files) that exceeded the limit for maxPostSize set on the associated connector.</p>
</blockquote>
<p>I'm using Spring Boot's default embedded tomcat server. Apparently the default <code>maxPostSize</code> value is 2 megabytes. Is there any way to edit this value? Doing so via <code>application.properties</code> would be best, rather than having to create customized beans or mess with xml files.</p> | 33,726,892 | 17 | 3 | null | 2015-10-20 09:26:08.383 UTC | 15 | 2022-09-10 07:20:53.83 UTC | 2015-10-20 09:46:52.063 UTC | null | 4,960,623 | null | 4,665,781 | null | 1 | 66 | java|spring|spring-mvc|tomcat | 128,225 | <p>Found a solution. Add this code to the same class running SpringApplication.run.</p>
<pre><code>// Set maxPostSize of embedded tomcat server to 10 megabytes (default is 2 MB, not large enough to support file uploads > 1.5 MB)
@Bean
EmbeddedServletContainerCustomizer containerCustomizer() throws Exception {
return (ConfigurableEmbeddedServletContainer container) -> {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
tomcat.addConnectorCustomizers(
(connector) -> {
connector.setMaxPostSize(10000000); // 10 MB
}
);
}
};
}
</code></pre>
<p>Edit: Apparently adding this to your application.properties file will also increase the maxPostSize, but I haven't tried it myself so I can't confirm.</p>
<pre><code>multipart.maxFileSize=10Mb # Max file size.
multipart.maxRequestSize=10Mb # Max request size.
</code></pre> |
23,016,057 | Web API Best Approach for returning HttpResponseMessage | <p>I have a Web API project and right my methods always returns <strong>HttpResponseMessage</strong>.</p>
<p>So, if it works or fails I return:</p>
<p><strong>No errors:</strong></p>
<pre><code>return Request.CreateResponse(HttpStatusCode.OK,"File was processed.");
</code></pre>
<p><strong>Any error or fail</strong></p>
<pre><code>return Request.CreateResponse(HttpStatusCode.NoContent, "The file has no content or rows to process.");
</code></pre>
<p>When I return an object then I use:</p>
<pre><code>return Request.CreateResponse(HttpStatusCode.OK, user);
</code></pre>
<p>I would like to know how can I return to my HTML5 client a better encapsulated respose, so I can return more information about the transaction, etc.</p>
<p>I was thinking on creating a custom class that can encapsulate the HttpResponseMessage but also have more data.</p>
<p>Does anyone have implemented something similar?</p> | 23,016,387 | 3 | 2 | null | 2014-04-11 14:56:57.22 UTC | 6 | 2015-07-14 21:18:36.38 UTC | null | null | null | null | 1,253,667 | null | 1 | 31 | c#|asp.net-mvc|json|asp.net-web-api|httpresponse | 100,529 | <p>Although this is not directly answering the question, I wanted to provide some information I found usefull.
<a href="http://weblogs.asp.net/dwahlin/archive/2013/11/11/new-features-in-asp-net-web-api-2-part-i.aspx">http://weblogs.asp.net/dwahlin/archive/2013/11/11/new-features-in-asp-net-web-api-2-part-i.aspx</a></p>
<p>The HttpResponseMessage has been more or less replaced with IHttpActionResult. It is much cleaner an easier to use.</p>
<pre><code>public IHttpActionResult Get()
{
Object obj = new Object();
if (obj == null)
return NotFound();
return Ok(obj);
}
</code></pre>
<p>Then you can encapsulate to create custom ones.
<a href="https://stackoverflow.com/questions/21440307/how-to-set-custom-headers-when-using-ihttpactionresult">How to set custom headers when using IHttpActionResult?</a></p>
<p>I haven't found a need yet for implementing a custom result yet but when I do, I will be going this route.</p>
<p>Its probably very similar to do using the old one as well.</p>
<p>To expand further on this and provide a bit more info. You can also include messages with some of the requests. For instance.</p>
<pre><code>return BadRequest("Custom Message Here");
</code></pre>
<p>You can't do this with many of the other ones but helps for common messages you want to send back. </p> |
2,260,220 | C# FindAll VS Where Speed | <p>Anyone know any speed differences between Where and FindAll on List. I know Where is part of IEnumerable and FindAll is part of List, I'm just curious what's faster.</p> | 2,260,227 | 5 | 1 | null | 2010-02-14 05:23:58.057 UTC | 4 | 2021-06-22 23:28:12.07 UTC | null | null | null | null | 11,137 | null | 1 | 43 | c#|performance|where|findall | 28,848 | <p>The FindAll method of the List<T> class actually constructs a new list object, and adds results to it. The Where extension method for IEnumerable<T> will simply iterate over an existing list and yield an enumeration of the matching results without creating or adding anything (other than the enumerator itself.)</p>
<p>Given a small set, the two would likely perform comparably. However, given a larger set, Where should outperform FindAll, as the new List created to contain the results will have to dynamically grow to contain additional results. Memory usage of FindAll will also start to grow exponentially as the number of matching results increases, where as Where should have constant minimal memory usage (in and of itself...excluding whatever you do with the results.) </p> |
2,185,549 | Css attribute selector for input type="button" not working on IE7 | <p>I am working on a big form and it contains a lot of buttons all over the form, therefore I am trying to get working input[type="button"] in my main css file so it would catch all buttons with out having to add a class to every single one, for some reason this is not working on IE7, after checking on the web it says that IE7 should be supporting this.</p>
<p>Also it has to be type="button" and not type="submit" as not all buttons will submit the form.</p>
<p>Could anybody give a hint what am I doing wrong?</p>
<pre><code>input[type="button"] {
text-align:center;
}
</code></pre>
<p>I have also tried <code>input[type=button]</code></p> | 3,386,459 | 8 | 2 | null | 2010-02-02 16:10:41.23 UTC | 5 | 2012-07-09 05:23:58.267 UTC | 2012-04-30 04:44:46.25 UTC | null | 106,224 | null | 207,847 | null | 1 | 15 | html|css|internet-explorer-7|css-selectors | 68,155 | <p>I was struggling getting <code>input[type=button]</code> selectors working in IE7 or IE8. The problem turned out to be that the HTML Pages were missing a "!DOCTYPE" declaration. Once I added </p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
</code></pre>
<p>Then everything worked fine. You can obviously use a different "!DOCTYPE" declaration to suit your requirements.</p> |
1,602,578 | C#: What is the fastest way to generate a unique filename? | <p>I've seen several suggestions on naming files randomly, including using </p>
<pre><code>System.IO.Path.GetRandomFileName()
</code></pre>
<p>or using a </p>
<pre><code>System.Guid
</code></pre>
<p>and appending a file extension. </p>
<p>My question is: <strong>What is the fastest way to generate a unique filename?</strong></p> | 1,602,591 | 8 | 7 | null | 2009-10-21 18:12:26.49 UTC | 12 | 2018-12-23 22:37:06.38 UTC | 2009-10-21 19:07:34.937 UTC | null | 67 | null | 19,020 | null | 1 | 32 | c#|.net|windows|performance|filesystems | 51,825 | <p>A GUID would be extremely fast, <strike>since it's implementation guarantees Windows can generate at least 16,384 GUIDS in a 100-nanosecond timespan</strike>. (As others pointed out, the spec doesn't guarantee, only allows for. However, GUID generation is really, really fast. Really.) The likelihood of collision on any filesystem anywhere on any network is very low. It's safe enough that although it'd be best practice to always check to see if that filename is available anyway, in reality you would never even need to do that.</p>
<p>So you're looking at no I/O operations except the save itself, and <0.2 milliseconds (on a test machine) to generate the name itself. Pretty fast.</p> |
2,046,012 | 'CompanyName.Foo' is a 'namespace' but is used like a 'type' | <p><strong>Restatement of the question</strong></p>
<p>I'm resurrecting this question because I just ran into this error again today, and I'm still utterly confused why the C# compiler bothers to check for collisions between namespaces and types in contexts where it makes no sense for a namespace to exist.</p>
<p>If I have...</p>
<pre><code>public Foo MyFoo { get; set; }
</code></pre>
<p>...why would the compiler care that <code>Foo</code> is both a namespace and a type? Can you declare a property as a namespace instead of a type?</p>
<p>What is the logic behind the "namespace used like type" compiler error? What problem is this saving me from?</p>
<p>[And how do I tag Eric Lippert? :)]</p>
<hr>
<p><strong>Original Question</strong></p>
<hr>
<p><strong>The problem</strong></p>
<p>I have a project "Foo" with default namespace <code>CompanyName.Foo</code>. I have a database that's also called "Foo".</p>
<p>And when I run SqlMetal.exe on the database, it generates a class <code>CompanyName.Foo.Models.Foo</code>.</p>
<p>Then, when I attempt to create a property with this class as the type, like this...</p>
<pre><code>using CompanyName.Foo.Models;
...
public Foo DataContext { get; set; }
</code></pre>
<p>...I get the error: </p>
<blockquote>
<p>'CompanyName.Foo' is a 'namespace' but is used like a 'type'.</p>
</blockquote>
<p>I am forced to do...</p>
<pre><code>public CompanyName.Foo.Models.Foo Foo { get; set; } // :-(
</code></pre>
<p><strong>Questions:</strong></p>
<ol>
<li><p>Why does this error occur? My property declaration doesn't contain <code>CompanyName</code>, so why is this a problem? Simply put: <code>Foo != CompanyName.Foo</code>. Also, just to be sure, I did a search of my entire solution for <code>namespace Foo</code> and came up with zero hits (if I had actually used a namespace <code>Foo</code>, I could understand getting an error).</p></li>
<li><p><em>[answered]</em> Is there any way around fully qualifying <code>Foo</code> every time I want to use it?</p></li>
<li><p><em>[answered]</em> Is there any way to get SqlMetal to name the class anything other than <code>Foo</code> (w/o changing the name of my database)? I can change the namespace using a switch, but I don't know of a way to change the actual class name.</p></li>
</ol>
<p><strong>Update</strong></p>
<p>Still seeking an answer to (1).</p>
<p>O.K.W. nailed (2) & (3).</p>
<p><strong>Usings</strong></p>
<p>A request was made for all my <code>using</code> statements:</p>
<pre><code>using System;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using MyCompany.Foo.Models;
</code></pre> | 2,330,632 | 8 | 1 | null | 2010-01-12 00:58:34.423 UTC | 19 | 2022-07-16 17:38:11.467 UTC | 2010-02-19 19:03:44.577 UTC | null | 129,164 | null | 129,164 | null | 1 | 47 | c#|linq-to-sql|compiler-construction|code-generation|namespaces | 57,826 | <blockquote>
<p>how do I tag Eric Lippert?</p>
</blockquote>
<p>If you have something you want brought to my attention you can use the "contact" link on my blog.</p>
<blockquote>
<p>I'm still utterly confused why the C# compiler bothers to check for collisions between namespaces and types in contexts where it makes no sense for a namespace to exist.</p>
</blockquote>
<p>Indeed, the rules here are tricky. Coincidentally, two weeks ago I wrote and posted a series of blog articles about some of these issues closely related to this very issue; they'll actually go live in early March. Watch the blog for details.</p>
<p>UPDATE: The articles mentioned above are here:</p>
<p><a href="https://web.archive.org/web/20150922170157/http://blogs.msdn.com/b/ericlippert/archive/tags/namespaces/" rel="nofollow noreferrer">Link</a></p>
<blockquote>
<p>Why does this error occur?</p>
</blockquote>
<p>Let me rephrase the question into several questions.</p>
<blockquote>
<p>What sections of the specification justify the production of this error?</p>
</blockquote>
<p>I think that's already been covered satisfactorily in other answers. The type resolution algorithm is extremely well-specified. But just to sum up: being <em>inside</em> something of the right name "binds more tightly" than <em>using</em> something of the right name from the <em>outside</em>. When you say:</p>
<pre><code>using XYZ;
namespace ABC.DEF
{
class GHI : DEF { }
}
</code></pre>
<p>that is the same as</p>
<pre><code>using XYZ;
namespace ABC
{
namespace DEF
{
class GHI : DEF { }
}
}
</code></pre>
<p>So now we must determine the meaning of DEF. We go from inside to outside. Is there a type parameter of GHI called DEF? No. Look at the container. Is there a member of DEF called DEF? No. Look at the container. Is there a member of ABC called DEF? <strong>YES</strong>. We're done; we have determined the meaning of DEF, it is a namespace. We discover the meaning of DEF <em>before</em> we ask "does XYZ have a member DEF?"</p>
<blockquote>
<p>What design principles influence this design?</p>
</blockquote>
<p>One design principle is "names mean the same thing no matter how you use them". The language does not 100% obey this principle; there are situations in which the same name can be used to refer to two different things in the same code. But in general, we strive for a situation where when you see "Foo" two times in the same context, it means the same thing. (See my article on <a href="https://web.archive.org/web/20100226210505/http://blogs.msdn.com:80/ericlippert/archive/2009/07/06/color-color.aspx" rel="nofollow noreferrer">The Color Color Problem</a> for some details on this, as well as my articles on <a href="http://blogs.msdn.com/ericlippert/archive/tags/Simple+Names/default.aspx" rel="nofollow noreferrer">identifying violations of the "simple name" rules</a>.)</p>
<p>One design principle is "no backtracking". We do not ever say in C# "I see that you used a name to refer to something that is not legal to refer to in this context. Let me abandon the result of name binding and start over, looking for something that might work."</p>
<p>A larger principle that underlies the "no backtracking" principle is that C# is not a "guess what the user meant" language. You wrote a program where the best possible binding of an identifier identified a namespace when a type was expected. There are two possibilities. Possibility one: you've made an error that you want to be told about so that <em>you</em> can take action to correct it. Possibility two: you meant for a less-good binding to be the one we choose, and so we should <em>guess</em> from amongst all the possible less-good bindings to figure out which one you probably meant.</p>
<p>That's a good design principle in languages like JScript -- JScript is all about muddling on through when the developer does something crazy. C# is not that kind of language; the feedback we get loud and clear from our developers is <em>tell me when something is broken so I can fix it</em>.</p>
<p>The thing about "no backtracking" is that it makes the language much easier to understand. Suppose you have something like this mess:</p>
<pre><code>namespace XYZ.DEF
{
public class GHI {}
}
namespace QRS.DEF.GHI
{
public class JKL { }
}
...
using QRS;
namespace TUV
{
using XYZ;
namespace ABC
{
namespace DEF
{
class GHI { }
class MNO : DEF.GHI.JKL { }
}
}
}
</code></pre>
<p>Work out the base type of MNO. With no backtracking we say "DEF is ABC.DEF". Therefore GHI is ABC.DEF.GHI. Therefore JKL is ABC.DEF.GHI.JKL, which does not exist, error. You must fix the error by giving a type name that lets the compiler identify which DEF you meant.</p>
<p>If we had backtracking, what would we have to do? We get that error, and then we backtrack. Does XYZ contain a DEF? Yes. Does it contain a GHI? Yes. Does it contain a JKL? No. Backtrack again. Does QRS contain an DEF.GHI.JKL? Yes.</p>
<p>That <em>works</em>, but can we logically conclude from the fact that it works that it is the one the user <em>meant</em>?</p>
<p>Who the heck knows in this crazy siutation? We got all kinds of good bindings in there that then went bad very late in the game. The idea that we stumbled upon the desired answer after going down many blind alleys seems highly suspect.</p>
<p>The correct thing to do here is not to backtrack multiple times and try out all kinds of worse bindings for every stage of the lookup. The correct thing to do is to say "buddy, the best possible match for this lookup gives nonsensical results; give me something less ambiguous to work with here please."</p>
<p>An unfortunate fact about writing a language where the compiler <em>by design</em> complains loudly if the best match is something that doesn't work, is that developers frequently say "well, sure, in <em>general</em> I want the compiler to point out all my mistakes -- or, rather, all my coworker's mistakes. But for this <em>specific</em> case, I know what I am doing, so please, compiler, <strong>do what I mean, not what I say</strong>."</p>
<p>Trouble is, you can't have it both ways. You can't have both a compiler that both enforces rigid rules that make it highly likely that suspicious code will be aggressively identified as erroneous <em>and</em> allow crazy code via compiler heuristics that figure out "what I really meant" when you write something that the compiler quite rightly sees as ambiguous or wrong.</p>
<p>For an object lesson in how lots of pro devs vehemently dislike the effects of a language design that aggressively identifies errors rather than guessing that the developer meant for the worse result to be chosen, see <a href="https://web.archive.org/web/20100125145510/http://blogs.msdn.com:80/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx" rel="nofollow noreferrer">the 116 comments to this article on a minor and rather unimportant aspect of overload resolution</a>:</p>
<p>(Note that I am no longer responding to comments on this issue; I've explained my position over ten times. If all those explanations are not convincing, that's because I'm not a very good convincer.)</p>
<p>And finally, if you really want to test your understanding of how the name resolution rules work in C#, <a href="https://ericlippert.com/2007/07/27/an-inheritance-puzzle-part-one/" rel="nofollow noreferrer">try out this little puzzle</a>. Almost everyone gets it wrong, or gets it right for the wrong reasons. The answer is <a href="https://ericlippert.com/2007/07/30/an-inheritance-puzzle-part-two/" rel="nofollow noreferrer">here</a>.</p> |
1,576,753 | Parse DateTime string in JavaScript | <p>Does anyone know how to parse date string in required format <code>dd.mm.yyyy</code>?</p> | 1,576,772 | 9 | 1 | null | 2009-10-16 08:14:00.877 UTC | 15 | 2017-09-21 06:35:58.137 UTC | 2012-05-18 17:50:13.173 UTC | null | 41,956 | null | 188,862 | null | 1 | 95 | javascript|datetime-format|datetime-parsing | 225,437 | <p>See:</p>
<ul>
<li><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date" rel="noreferrer">Mozilla Core JavaScript Reference: Date object</a></li>
<li><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/split" rel="noreferrer">Mozilla Core JavaScript Reference: String.Split</a></li>
</ul>
<p>Code:</p>
<pre><code>var strDate = "03.09.1979";
var dateParts = strDate.split(".");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
</code></pre> |
2,086,529 | What is the relative performance difference of if/else versus switch statement in Java? | <p>Worrying about my web application's performances, I am wondering which of "if/else" or switch statement is better regarding performance?</p> | 2,086,546 | 9 | 11 | null | 2010-01-18 14:09:30.207 UTC | 42 | 2021-01-04 02:31:57.36 UTC | 2010-03-29 15:08:51.457 UTC | null | 157,882 | null | 253,236 | null | 1 | 142 | java|performance|switch-statement|if-statement | 131,087 | <p>That's micro optimization and premature optimization, which are evil. Rather worry about readabililty and maintainability of the code in question. If there are more than two <code>if/else</code> blocks glued together or its size is unpredictable, then you may highly consider a <code>switch</code> statement.</p>
<p>Alternatively, you can also grab <em>Polymorphism</em>. First create some interface:</p>
<pre><code>public interface Action {
void execute(String input);
}
</code></pre>
<p>And get hold of all implementations in some <code>Map</code>. You can do this either statically or dynamically:</p>
<pre><code>Map<String, Action> actions = new HashMap<String, Action>();
</code></pre>
<p>Finally replace the <code>if/else</code> or <code>switch</code> by something like this (leaving trivial checks like nullpointers aside):</p>
<pre><code>actions.get(name).execute(input);
</code></pre>
<p>It <em>might</em> be microslower than <code>if/else</code> or <code>switch</code>, but the code is at least far better maintainable. </p>
<p>As you're talking about webapplications, you can make use of <a href="http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequest.html#getPathInfo%28%29" rel="noreferrer"><code>HttpServletRequest#getPathInfo()</code></a> as action key (eventually write some more code to split the last part of pathinfo away in a loop until an action is found). You can find here similar answers: </p>
<ul>
<li><a href="https://stackoverflow.com/questions/1798232/using-a-custom-servlet-oriented-framework-too-many-servlets-is-this-an-issue/1798461#1798461">Using a custom Servlet oriented framework, too many servlets, is this an issue</a></li>
<li><a href="https://stackoverflow.com/questions/2060128/java-front-controller/2060842#2060842">Java Front Controller</a></li>
</ul>
<p>If you're worrying about Java EE webapplication performance in general, then you may find <a href="http://balusc.blogspot.com/2009/09/webapplication-performance-tips-and.html" rel="noreferrer">this article</a> useful as well. There are other areas which gives a <strong>much more</strong> performance gain than only (micro)optimizing the raw Java code.</p> |
1,404,210 | Java Date vs Calendar | <p>Could someone please advise the current "best practice" around <code>Date</code> and <code>Calendar</code> types.</p>
<p>When writing new code, is it best to always favour <code>Calendar</code> over <code>Date</code>, or are there circumstances where <code>Date</code> is the more appropriate datatype?</p> | 1,404,216 | 13 | 3 | null | 2009-09-10 09:09:59.6 UTC | 86 | 2019-12-14 20:45:20.38 UTC | 2014-10-15 12:16:34.8 UTC | null | 1,331,488 | null | 59,015 | null | 1 | 385 | java|date|calendar | 192,072 | <p>Date is a simpler class and is mainly there for backward compatibility reasons. If you need to set particular dates or do date arithmetic, use a Calendar. Calendars also handle localization. The previous date manipulation functions of Date have since been deprecated.</p>
<p>Personally I tend to use either time in milliseconds as a long (or Long, as appropriate) or Calendar when there is a choice.</p>
<p>Both Date and Calendar are mutable, which tends to present issues when using either in an API.</p> |
8,539,079 | How to start and stop/pause setInterval? | <p>I'm trying to pause and then play a <code>setInterval</code> loop.</p>
<p>After I have stopped the loop, the "start" button in <a href="http://jsfiddle.net/Daniel_Hug/gEdKM/" rel="noreferrer">my attempt</a> doesn't seem to work :</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>input = document.getElementById("input");
function start() {
add = setInterval("input.value++", 1000);
}
start();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" /></code></pre>
</div>
</div>
</p>
<p>Is there a working way to do this?</p> | 8,539,139 | 8 | 2 | null | 2011-12-16 19:19:20.39 UTC | 11 | 2022-05-10 21:00:25.343 UTC | 2019-08-04 12:34:51.71 UTC | null | 10,607,772 | null | 552,067 | null | 1 | 30 | javascript|jquery|loops|setinterval | 131,973 | <h3>The reason you're seeing this specific problem:</h3>
<p>JSFiddle wraps your code in a function, so <strong><code>start()</code> is not defined in the global scope</strong>.</p>
<p><img src="https://i.stack.imgur.com/SUrUQ.png" alt="enter image description here" /></p>
<hr />
<p>Moral of the story: don't use inline event bindings. Use <a href="https://developer.mozilla.org/en/DOM/element.addEventListener" rel="noreferrer"><code>addEventListener</code></a>/<code>attachEvent</code>.</p>
<hr />
<h3>Other notes:</h3>
<p><strong>Please</strong> don't pass strings to <code>setTimeout</code> and <code>setInterval</code>. It's <code>eval</code> in disguise.</p>
<p>Use a function instead, and get cozy with <code>var</code> and white space:</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>var input = document.getElementById("input"),
add;
function start() {
add = setInterval(function() {
input.value++;
}, 1000);
}
start();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" /></code></pre>
</div>
</div>
</p> |
46,585,044 | Xcode 9 Storyboard: an internal error occurred. editing functionality may be limited | <p>When I am opening my project in Xcode 9, getting above error for Storyboard and Launchscreen. </p>
<p>Note: Cleaning derived data didn't help me.</p>
<p>Please have a look at the screenshot.</p>
<p><a href="https://i.stack.imgur.com/pTxyt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pTxyt.png" alt="enter image description here"></a></p> | 46,663,902 | 27 | 5 | null | 2017-10-05 11:58:12.563 UTC | 4 | 2021-05-05 15:26:03.603 UTC | 2018-04-03 11:00:15.893 UTC | null | 2,227,743 | null | 4,883,533 | null | 1 | 34 | ios|storyboard|xcode9 | 23,079 | <p>I fixed this issue by-</p>
<ol>
<li>updating my Mac to MacOS High Siera</li>
<li>deleted Xcode</li>
<li>installed new Xcode from AppStore</li>
</ol> |
18,009,909 | clearing or set null to objects in java | <p>I was recently looking into freeing up memory occupied by Java objects. While doing that I got confused about how objects are copied (shallow/deep) in Java and how to avoid accidently clearing/nullifying objects while they are still in use.</p>
<p>Consider following scenarios:</p>
<ol>
<li>passing a <code>ArrayList<Object></code> as an argument to a method.</li>
<li>passing a <code>ArrayList<Object></code> to a runnable class to be processed by a thread.</li>
<li>putting a <code>ArrayList<Object></code> into a <code>HashMap</code>.</li>
</ol>
<p>Now in these case, if I call <code>list = null;</code> or <code>list.clear();</code>, what happens to the objects? In which case the objects are lost and in which cases only the reference is set to null?</p>
<p>I guess it has to do with shallow and deep copying of objects, but in which cases does shallow copying happens and in which case does deep copy happens in Java?</p> | 18,010,019 | 7 | 1 | null | 2013-08-02 06:12:33.87 UTC | 5 | 2015-08-21 17:56:43.867 UTC | 2015-08-21 17:56:43.867 UTC | null | 1,743,880 | null | 1,189,063 | null | 1 | 24 | java|memory-management|null|deep-copy|shallow-copy | 91,260 | <p>Firstly, you never set an <em>object</em> to null. That concept has no meaning. You can assign a value of <code>null</code> to a <em>variable</em>, but you need to distinguish between the concepts of "variable" and "object" very carefully. Once you do, your question will sort of answer itself :)</p>
<p>Now in terms of "shallow copy" vs "deep copy" - it's probably worth avoiding the term "shallow copy" here, as usually a shallow copy involves creating a new object, but just copying the fields of an existing object directly. A deep copy would take a copy of the objects referred to by those fields as well (for reference type fields). A simple assignment like this:</p>
<pre><code>ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = list1;
</code></pre>
<p>... doesn't do <em>either</em> a shallow copy or a deep copy in that sense. It just copies the reference. After the code above, <code>list1</code> and <code>list2</code> are independent variables - they just happen to have the same values (references) at the moment. We could change the value of one of them, and it wouldn't affect the other:</p>
<pre><code>list1 = null;
System.out.println(list2.size()); // Just prints 0
</code></pre>
<p>Now if instead of changing the <em>variables</em>, we make a change to the object that the variables' values refer to, that change will be visible via the other variable too:</p>
<pre><code>list2.add("Foo");
System.out.println(list1.get(0)); // Prints Foo
</code></pre>
<p>So back to your original question - you never store <em>actual objects</em> in a map, list, array etc. You only ever store <em>references</em>. An object can only be garbage collected when there are no ways of "live" code reaching that object any more. So in this case:</p>
<pre><code>List<String> list = new ArrayList<String>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("Foo", list);
list = null;
</code></pre>
<p>... the <code>ArrayList</code> object still can't be garbage collected, because the <code>Map</code> has an entry which refers to it.</p> |
6,751,564 | How to pass a boolean between intents | <p>I need to pass a boolean value to and intent and back again when the back button is pressed. The goal is to set the boolean and use a conditional to prevent multiple launches of a new intent when an onShake event is detected. I would use SharedPreferences, but it seems it does not play nice with my onClick code and I'm not sure how to fix that. Any suggestions would be appreciated!</p>
<pre><code>public class MyApp extends Activity {
private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSensorListener = new ShakeEventListener();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
public void onShake() {
// This code is launched multiple times on a vigorous
// shake of the device. I need to prevent this.
Intent myIntent = new Intent(MyApp.this, NextActivity.class);
MyApp.this.startActivity(myIntent);
}
});
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener,mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onStop() {
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}}
</code></pre> | 6,751,747 | 3 | 0 | null | 2011-07-19 17:41:46.31 UTC | 4 | 2020-09-21 09:56:54.65 UTC | 2018-02-22 05:33:34.367 UTC | null | 1,761,003 | null | 818,263 | null | 1 | 20 | android|android-intent|shake | 54,910 | <p>have a private member variable in your activity called wasShaken.</p>
<pre><code>private boolean wasShaken = false;
</code></pre>
<p>modify your onResume to set this to false.</p>
<pre><code>public void onResume() { wasShaken = false; }
</code></pre>
<p>in your onShake listener, check if it's true. if it is, return early. Then set it to true.</p>
<pre><code> public void onShake() {
if(wasShaken) return;
wasShaken = true;
// This code is launched multiple times on a vigorous
// shake of the device. I need to prevent this.
Intent myIntent = new Intent(MyApp.this, NextActivity.class);
MyApp.this.startActivity(myIntent);
}
});
</code></pre> |
15,658,858 | how to make div slide from right to left | <p>got a code here from someone....</p>
<p>what I like is to make the sliding div from right slide to left, i mean it hides the div to the right and slowly slides to the left for 300px width.</p>
<p>HTML</p>
<pre><code><a id="loginPanel">quote</a>
<div id="userNav">User Area</div>
</code></pre>
<p>CSS</p>
<pre><code>#loginPanel {
color: #000;
cursor:pointer;
}
#userNav {
width: 200px;
height: 200px;
display: none;
background: #ff0000;
}
</code></pre>
<p>Jquery</p>
<pre><code>// Open / Close Panel According to Cookie //
if ($.cookie('panel') == 'open'){
$('#userNav').slideDown('fast');
} else {
$('#userNav').slideUp('fast');
}
// Toggle Panel and Set Cookie //
$('#loginPanel').click(function(){
$('#userNav').slideToggle('fast', function(){
if ($(this).is(':hidden')) {
$.cookie('panel', 'closed');
} else {
$.cookie('panel', 'open');
}
});
});
</code></pre>
<p>Please need help on this one. just to make the div slide right to left</p>
<p>here is the fiddle <a href="http://jsfiddle.net/7m7uK/195/" rel="noreferrer">http://jsfiddle.net/7m7uK/195/</a></p> | 15,659,115 | 5 | 4 | null | 2013-03-27 12:31:39.22 UTC | 3 | 2016-09-30 07:11:48.5 UTC | null | null | null | null | 1,749,212 | null | 1 | 8 | javascript|jquery|css | 93,124 | <p>You can use jQueryUI and additional effects <em>Slide</em></p>
<p><a href="http://docs.jquery.com/UI/Effects/Slide" rel="noreferrer">http://docs.jquery.com/UI/Effects/Slide</a></p>
<p>Example:</p>
<pre><code>$('#userNav').hide("slide", {direction: "left" }, 1000);
$('#userNav').show("slide", { direction: "right" }, 1000);
</code></pre>
<p>You can't use .slideToggle() to slide from left to right or vice versa, from <a href="http://api.jquery.com/slideToggle/" rel="noreferrer">http://api.jquery.com/slideToggle/</a>: </p>
<blockquote>
<p>The .slideToggle() method animates the height of the matched elements.
This causes lower parts of the page to slide up or down, appearing to
reveal or conceal the items. If the element is initially displayed, it
will be hidden; if hidden, it will be shown.</p>
</blockquote>
<p>You should try and change your code to implement this code, but I think it's maybe better if you try with <a href="https://stackoverflow.com/a/15659017/1081079">@s15199d</a> answer, than you don't need to use jQueryUI</p>
<p>Ok, I created jsfiddle, you must include jQueryUI in order to work, you have different combinations of slide directions:</p>
<p><a href="http://jsfiddle.net/7m7uK/197/" rel="noreferrer">http://jsfiddle.net/7m7uK/197/</a></p>
<p>Ok, created another fiddle with cookies</p>
<p><a href="http://jsfiddle.net/7m7uK/198/" rel="noreferrer">http://jsfiddle.net/7m7uK/198/</a></p> |
60,967,561 | Jest coverage: How can I get a total percentage of coverage? | <p>In my gitlab pipeline I want to send the total percentage value to a server. But jest --coverage only gives me these large reporting files in /coverage. I can't seem to parse the total value out of it. Am I missing a parameter?</p> | 60,968,723 | 3 | 1 | null | 2020-04-01 09:22:55.673 UTC | 4 | 2022-03-17 13:24:28.377 UTC | 2021-12-03 06:08:25.83 UTC | null | 6,340 | null | 5,330,421 | null | 1 | 33 | jestjs|code-coverage | 26,690 | <p>Thank's to Teneff's answer, I go with the coverageReporter="json-summary".</p>
<pre><code> jest --coverage --coverageReporters="json-summary"
</code></pre>
<p>This generates a coverage-summary.json file which can easily be parsed. I get the total values directly from the json:</p>
<pre><code> "total": {
"lines": { "total": 21777, "covered": 65, "skipped": 0, "pct": 0.3 },
"statements": { "total": 24163, "covered": 72, "skipped": 0, "pct": 0.3 },
"functions": { "total": 5451, "covered": 16, "skipped": 0, "pct": 0.29 },
"branches": { "total": 6178, "covered": 10, "skipped": 0, "pct": 0.16 }
}
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.