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
23,767,765
Ansible doesn't pick up group_vars without loading it manually
<p>In my <code>local.yml</code> I'm able to run the playbook and reference variables within <code>group_vars/all</code> however I'm not able to access variables within <code>group_vars/phl-stage</code>. Let's assume the following.</p> <pre><code>ansible-playbook -i phl-stage site.yml </code></pre> <p>I have a variable, let's call it <em><code>deploy_path</code></em> that's different for each environment. I place the variable within <code>group_vars/&lt; environment name &gt;</code>. If I include the file <code>group_vars/phl-stage</code> within <code>vars_files</code> it works but I would've thought the group file would be automatically loaded?</p> <p>site.yml</p> <pre><code>- include: local.yml </code></pre> <p>local.yml</p> <pre><code>- hosts: 127.0.0.1 connection: local vars_files: - "group_vars/perlservers" - "group_vars/deploy_list" </code></pre> <p>group_vars/phl-stage</p> <pre><code>[webservers] phl-web1 phl-web2 [perlservers] phl-perl1 phl-perl2 [phl-stage:children] webservers perlservers </code></pre> <p>Directory structure:</p> <pre><code>group_vars all phl-stage phl-prod site.yml local.yml </code></pre>
23,784,771
1
0
null
2014-05-20 18:54:23.997 UTC
8
2014-05-22 04:12:12.677 UTC
2014-05-22 04:12:12.677 UTC
null
949,859
null
166,836
null
1
35
ansible
60,366
<p>You're confusing the structure a bit.</p> <ul> <li>The <code>group_vars</code> directory contains files <em>for each hostgroup</em> defined in your inventory file. The files define variables that member hosts can use.</li> <li>The inventory file doesn't reside in the <code>group_vars</code> dir, it should be outside.</li> <li><strong>Only</strong> hosts that are members of a group can use its variables, so unless you put 127.0.0.1 in a group, it won't be able to use any group_vars beside those defined in <code>group_vars/all</code>. </li> </ul> <p>What you want is this dir structure:</p> <pre><code>group_vars/ all perlservers phl-stage hosts site.yml local.yml </code></pre> <p>Your hosts file should look like this, assuming 127.0.0.1 is just a staging server and not perl or web server:</p> <pre><code>[webservers] phl-web1 phl-web2 [perlservers] phl-perl1 phl-perl2 [phl-stage] 127.0.0.1 [phl-stage:children] webservers perlservers </code></pre> <p>So you define which hosts belong to which group in the inventory, and then for each group you define variables in its group_vars file.</p>
45,538,993
Why don't memory allocators actively return freed memory to the OS?
<p>Yes, this might be the third time you see this code, because I asked two other questions about it (<a href="https://stackoverflow.com/q/45529430/8385554">this</a> and <a href="https://stackoverflow.com/q/45537965/8385554">this</a>).. The code is fairly simple:</p> <pre><code>#include &lt;vector&gt; int main() { std::vector&lt;int&gt; v; } </code></pre> <p>Then I build and run it with Valgrind on Linux:</p> <pre><code>g++ test.cc &amp;&amp; valgrind ./a.out ==8511== Memcheck, a memory error detector ... ==8511== HEAP SUMMARY: ==8511== in use at exit: 72,704 bytes in 1 blocks ==8511== total heap usage: 1 allocs, 0 frees, 72,704 bytes allocated ==8511== ==8511== LEAK SUMMARY: ==8511== definitely lost: 0 bytes in 0 blocks ==8511== indirectly lost: 0 bytes in 0 blocks ==8511== possibly lost: 0 bytes in 0 blocks ==8511== still reachable: 72,704 bytes in 1 blocks ==8511== suppressed: 0 bytes in 0 blocks ... ==8511== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) </code></pre> <p>Here, Valgrind reports there is no memory leak, even though there is 1 alloc and 0 free.</p> <p>The answer <a href="https://stackoverflow.com/a/45537999/8385554">here</a> points out the allocator used by C++ standard library don't necessarily return the memory back to the OS - it might keep them in an internal cache.</p> <p>Question is:</p> <p>1) Why keep them in an internal cache? If it is for speed, <em>how</em> is it faster? Yes, the OS needs to maintain a data structure to keep track of memory allocation, but this the maintainer of this cache also needs to do so.</p> <p>2) How is this implemented? Because my program <code>a.out</code> terminates already, there is no other process that is maintaining this memory cache - or, is there one? </p> <p>Edit: for question (2) - Some answers I've seen suggest "C++ runtime", what does it mean? If "C++ runtime" is the C++ library, but the library is just a bunch of machine code sitting on the disk, it is not a running process - the machine code is either linked to my <code>a.out</code> (static library, <code>.a</code>) or is invoked during runtime (shared objects, <code>.so</code>) in the process of <code>a.out</code>.</p>
45,539,066
1
1
null
2017-08-07 03:24:02.697 UTC
9
2017-08-07 05:29:43.29 UTC
2017-08-07 03:33:45.227 UTC
null
8,385,554
null
8,385,554
null
1
12
c++|memory-management|libstdc++
2,396
<h1>Clarification</h1> <p>First, some clarification. You asked: <em>... my program a.out terminates already, there is no other process that is maintaining this memory cache - or, is there one?</em> </p> <p>Everything we are talking about is within the lifetime of a single process: the process <em>always</em> returns all allocated memory when it exits. There is no cache that outlives the process<sup>1</sup>. The memory is returned even without any help from the runtime allocator: the OS simply "takes it back" when the process is terminated. So there is no system-wide leak possible from terminated applications with normal allocations.</p> <p>Now what Valgrind is reporting is memory that is in use <em>at the moment the process</em> terminated, but before the OS cleans everything up. It works at the <em>runtime library</em> level, and not at the OS level. So it's saying "Hey, when the program finished, there were 72,000 bytes that hadn't been returned to the runtime" but an unstated implication is that "these allocations will be cleaned up shortly by the OS".</p> <h1>The Underlying Questions</h1> <p>The code and Valgrind output shown doesn't really correlate well with the titular question, so let's break them apart. First we'll just try to answer the questions you asked about allocators: why they exist and why they don't generally don't immediately return freed memory to the OS, ignoring the example.</p> <p>You asked:</p> <blockquote> <p>1) Why keep them in an internal cache? If it is for speed, how is it faster? Yes, the OS needs to maintain a data structure to keep track of memory allocation, but this the maintainer of this cache also needs to do so.</p> </blockquote> <p>This is sort of two questions in one: one is why bother having a userland runtime allocator at all, and then the other one is (perhaps?) why don't these allocators immediately return memory to the OS when it is freed. They are related, but let's tackle them one at a time.</p> <h2>Why Runtime Allocators Exist</h2> <p>Why not just rely on the OS memory allocation routines?</p> <ul> <li><p>Many operating systems, including most Linux and other Unix-like operating systems, simply don't have an OS system call to allocate and free arbitrary blocks of memory. Unix-alikes offer <code>brk</code> which only grows or shrinks one contiguous block of memory - you have no way to "free" arbitrary earlier allocations. They also offer <code>mmap</code> which allows you to independently allocate and free chunks of memory, but these allocate on a <code>PAGE_SIZE</code> granularity, which on Linux is 4096 bytes. So if you want request 32 bytes, you'll have to waste <code>4096 - 32 == 4064</code> bytes if you don't have your own allocator. On these operating systems you practically <em>need</em> a separate memory allocation runtime which turns these coarse-grained tools into something capable of efficiently allocating small blocks.</p> <p>Windows is a bit different. It has the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa366597(v=vs.85).aspx" rel="noreferrer"><code>HeapAlloc</code></a> call, which is part of the "OS" and does offer <code>malloc</code>-like capabilities of allocating and freeing arbitrarily sized chunks of memory. With <em>some</em> compilers then, <code>malloc</code> is just implemented as a thin wrapper around <code>HeapAlloc</code> (the performance of this call has improved greatly in recent Windows versions, making this feasible). Still, while <code>HeapAlloc</code> is part of the <em>OS</em> it isn't implemented in the <em>kernel</em> - it is also mostly implemented in a user-mode library, managing a list of free and used blocks, with occasional kernel calls to get chunks of memory from the kernel. So it is mostly <code>malloc</code> in another disguise and any memory it is holding on to is also not available to any other processes.</p></li> <li>Performance! Even if there were appropriate kernel-level calls to allocate arbitrary blocks of memory, the simple overhead roundtrip to the kernel is usually hundreds of nanoseconds or more. A well-tuned <code>malloc</code> allocation or free, on other hand, is often only a dozen instructions and may complete in 10 ns or less. On top of that, system calls can't "trust their input" and so must carefully validate parameters passed from user-space. In the case of <code>free</code> this means that it much check that the user passed a pointer which is valid! Most runtime <code>free</code> implements simply crash or silently corrupt memory since there is no responsibility to protect a process from itself.</li> <li>Closer link to the rest of the language runtime. The functions you use to allocate memory in C++, namely <code>new</code>, <code>malloc</code> and friends, are part of an defined by the language. It is then entirely natural to implement them as part of the runtime that implements the rest of the language, rather than the OS which is for the most part language-agnostic. For example, the language may have specific alignment requirements for various objects, which can best be handled by language aware allocators. Changes to the language or compiler might also imply necessary changes to the allocation routines, and it would be a tough call to hope for the kernel to be updated to accommodate your language features!</li> </ul> <h2>Why Not Return Memory to the OS</h2> <p>Your example doesn't show it, but you asked and if you wrote a different test you would probably find that after allocating and then freeing a bunch of memory, your processes resident set size and/or virtual size as reported by the OS might not decrease after the free. That is, it seems like the process holds on to the memory even though you have freed it. This is in fact true of many <code>malloc</code> implementations. First, note that this is not a <em>leak</em> per se - the unreturned memory is still available to the process that allocated it, even if not to other processes.</p> <p>Why do they do that? Here are some reasons:</p> <ol> <li><p>The kernel API makes it hard. For the old-school <code>brk</code> and <code>sbrk</code> <a href="https://linux.die.net/man/2/sbrk" rel="noreferrer">system calls</a>, it simply isn't feasible to return freed memory unless it happens to be at the end of very last block allocated from <code>brk</code> or <code>sbrk</code>. That's because the abstraction offered by these calls is a single large contiguous region that you can only extend from one end. You can't hand back memory from the middle of it. Rather than trying to support the unusual case where all the freed memory happens to be at the end of <code>brk</code> region, most allocators don't even bother.</p> <p>The <code>mmap</code> call is more flexible (and this discussion generally applies also to Windows where <code>VirtualAlloc</code> is the <code>mmap</code> equivalent), allowing you to at least return memory at a page granularity - but even that is hard! You can't return a page until <em>all</em> allocations that are part of that page are freed. Depending on the size and allocation/free pattern of the application that may be common or uncommon. A case where it works well is for large allocations - greater than a page. Here you're guaranteed to be able to free most of the allocation if it was done via <code>mmap</code> and indeed some modern allocators satisfy large allocations directly from <code>mmap</code> and free them back to the OS with <code>munmap</code>. For <code>glibc</code> (and by extension the C++ allocation operators), you can even control <a href="http://man7.org/linux/man-pages/man3/mallopt.3.html" rel="noreferrer">this threshold</a>:</p> <pre><code>M_MMAP_THRESHOLD For allocations greater than or equal to the limit specified (in bytes) by M_MMAP_THRESHOLD that can't be satisfied from the free list, the memory-allocation functions employ mmap(2) instead of increasing the program break using sbrk(2). Allocating memory using mmap(2) has the significant advantage that the allocated memory blocks can always be independently released back to the system. (By contrast, the heap can be trimmed only if memory is freed at the top end.) On the other hand, there are some disadvantages to the use of mmap(2): deallocated space is not placed on the free list for reuse by later allocations; memory may be wasted because mmap(2) allocations must be page-aligned; and the kernel must perform the expensive task of zeroing out memory allocated via mmap(2). Balancing these factors leads to a default setting of 128*1024 for the M_MMAP_THRESHOLD parameter. </code></pre> <p>So by default allocations of 128K or more will be allocated by the runtime directly from the OS and freed back to the OS on free. So <em>sometimes</em> you will see the behavior you might have expected is always the case.</p></li> <li>Performance! Every kernel call is expensive, as described in the other list above. Memory that is freed by a process will be needed shortly later to satisfy another allocation. Rather than trying to return it to the OS, a relatively heavyweight operation, why not just keep it around on a <em>free list</em> to satisfy future allocations? As pointed out in the man page entry, this also avoids the overhead of zeroing out all the memory returned by the kernel. It also gives the best chance of good cache behavior since the process is continually re-using the same region of the address space. Finally, it avoids TLB flushes which would be imposed by <code>munmap</code> (and possibly by shrinking via <code>brk</code>).</li> <li>The "problem" of not returning memory is the worst for long-lived processes that allocate a bunch of memory at some point, free it and then never allocate that much again. I.e., processes whose allocation <em>high-water mark</em> is larger than their long term typical allocation amount. Most processes just don't follow that pattern, however. Processes often free a lot of memory, but allocate at a rate such that their overall memory use is constant or perhaps increasing. Applications that do have the "big then small" live size pattern could perhaps <a href="https://stackoverflow.com/questions/38644578/understanding-glibc-malloc-trimming">force the issue with <code>malloc_trim</code></a>. </li> <li><p>Virtual memory helps mitigate the issue. So far I've been throwing around terms like "allocated <em>memory</em>" without really defining what it means. If a program allocates and then frees 2 GB of <em>memory</em> and then sits around doing nothing, is it wasting 2 GB of actual DRAM plugged into your motherboard somewhere? Probably not. It is using 2 GB of virtual address space in your process, sure, but virtual address space is per-process, so that doesn't directly take anything away from other processes. If the process actually wrote to the memory at some point, it would be allocated physical memory (yes, DRAM) - after freeing it, you are - by definition - no longer using it. At this point the OS may reclaim those physical pages by use for someone else.</p> <p>Now this still requires you have swap to absorb the dirty not-used pages, but some allocators are smart: they can issue a <a href="http://man7.org/linux/man-pages/man2/madvise.2.html" rel="noreferrer"><code>madvise(..., MADV_DONTNEED)</code></a> call which tells the OS "this range doesn't have anything useful, you don't have to preserve its contents in swap". It still leaves the virtual address space mapped in the process and usable later (zero filled) and so it's more efficient than <code>munmap</code> and a subsequent <code>mmap</code>, but it avoid pointlessly swapping freed memory regions to swap.<sup>2</sup></p></li> </ol> <h1>The Demonstrated Code</h1> <p>As pointed out in <a href="https://stackoverflow.com/a/45537999/149138">this answer</a> your test with <code>vector&lt;int&gt;</code> isn't really testing <em>anything</em> because an empty, unused <code>std::vector&lt;int&gt; v</code> won't even <a href="https://godbolt.org/g/XQc2Qy" rel="noreferrer">create the vector object</a> as long as you are using some minimal level of optimization. Even without optimization, no allocation is likely to occur because most <code>vector</code> implementations allocate on first insertion, and not in the constructor. Finally, even if you are using some unusual compiler or library that does an allocation, it will be for a handful of bytes, not the ~72,000 bytes Valgrind is reporting.</p> <p>You should do something like this to actually see the impact of a vector allocation:</p> <pre><code>#include &lt;vector&gt; volatile vector&lt;int&gt; *sink; int main() { std::vector&lt;int&gt; v(12345678); sink = &amp;v; } </code></pre> <p>That results in <a href="https://godbolt.org/g/Givw4D" rel="noreferrer">actual allocation and de-allocation</a>. It isn't going to change the Valgrind output, however, since the vector allocation is correctly freed before the program exits, so there is no issue as far as Valgrind is concerned.</p> <p>At a high level, Valgrind basically categorizes things into "definite leaks" and "not freed at exit". The former occur when the program no longer has a reference to a pointer to memory that it allocated. It cannot free such memory and so has leaked it. Memory which hasn't been freed at exit may be a "leak" - i.e., objects that should have been freed, but it may also simply be memory that the developer knew would live the length of the program and so doesn't need to be explicitly freed (because of order-of-destruction issues for globals, especially when shared libraries are involved, it may be very hard to reliably free memory associated with global or static objects even if you wanted to).</p> <hr> <p><sup>1</sup> In some cases some deliberately <em>special</em> allocations may outlive the process, such as shared memory and memory mapped files, but that doesn't relate to plain C++ allocations and you can ignore it for the purposes of this discussion. </p> <p><sup>2</sup> Recent Linux kernels also have the Linux-specific <code>MADV_FREE</code> which seems to have similar semantics to <code>MADV_DONTNEED</code>.</p>
42,405,439
How to verify google auth token at server side in node js?
<p>My front end application is <em>authenticated</em> using gmail account. </p> <p>I retrieve <strong>id_token</strong> after the authentication is successful and send it as <strong>Authorization Header</strong> as <em>bearer token</em>. </p> <p>E.g. <a href="http://localhost:4000/api" rel="noreferrer">http://localhost:4000/api</a></p> <p>Authorization Bearer <em>token_id</em></p> <p>At <strong>nodejs</strong> server side, I call the following method to verify the token. </p> <pre><code>exports.verifyUser = function(req, res, next) { var GoogleAuth = require('google-auth-library'); var auth = new GoogleAuth(); var client = new auth.OAuth2(config.passport.google.clientID, config.passport.google.clientSecret, config.passport.google.callbackURL); // check header or url parameters or post parameters for token var token = ""; var tokenHeader = req.headers["authorization"]; var items = tokenHeader.split(/[ ]+/); if (items.length &gt; 1 &amp;&amp; items[0].trim().toLowerCase() == "bearer") { token = items[1]; } if (token) { var verifyToken = new Promise(function(resolve, reject) { client.verifyIdToken( token, config.passport.google.clientID, function(e, login) { console.log(e); if (login) { var payload = login.getPayload(); var googleId = payload['sub']; resolve(googleId); next(); } else { reject("invalid token"); } } ) }).then(function(googleId) { res.send(googleId); }).catch(function(err) { res.send(err); }) } else { res.send("Please pass token"); } } </code></pre> <p>When I call the above method, I always get <em>Invalid token</em> response with following error. </p> <pre><code>Error: No pem found for envelope: {"alg":"RS256","kid":"c1ab5857066442ea01a01601 850770676460a712"} at OAuth2Client.verifySignedJwtWithCerts (\node_modules\google-auth-libr ary\lib\auth\oauth2client.js:518:13) </code></pre> <ul> <li>Is this the right approach to verify token? </li> <li>Do I send the id_token as Authorization bearer? Or is it for authorization only?</li> <li>How do I send the id_token to the sever side? Thru url, header? </li> <li>What am I doing wrong? </li> </ul> <p>Any help is highly appreciated. </p>
42,405,866
3
0
null
2017-02-23 01:30:27.253 UTC
10
2022-08-12 13:19:48.577 UTC
2017-10-07 03:30:53.577 UTC
null
2,614,364
null
2,727,444
null
1
18
javascript|node.js|api|google-signin|google-authentication
18,335
<p><code>OAuth2Client.verifyIdToken</code> take an idToken in arguments, from the <a href="https://github.com/googleapis/google-auth-library-nodejs/blob/58c53b44113a7211884d49dac1683032a5ce681e/src/auth/oauth2client.ts#L1040-L1044" rel="nofollow noreferrer">library source</a> :</p> <pre><code>/** * Verify id token is token by checking the certs and audience * @param {string} idToken ID Token. * @param {(string|Array.&lt;string&gt;)} audience The audience to verify against the ID Token * @param {function=} callback Callback supplying GoogleLogin if successful */ OAuth2Client.prototype.verifyIdToken = function(idToken, audience, callback) </code></pre> <p>You have passed the whole header value <code>bearer eyJhbGciOiJSUzI1NiIsImtpZCI6ImMxYWI1OD U3MDY2NDQyZWEwMWEwMTYwMTg1MDc3MDY3NjQ2MGE3MTIifQ</code> so you will have to split the headers value as :</p> <pre><code>var authorization = req.headers[&quot;authorization&quot;]; var items = authorization.split(/[ ]+/); if (items.length &gt; 1 &amp;&amp; items[0].trim() == &quot;Bearer&quot;) { var token = items[1]; console.log(token); // verify token } </code></pre> <blockquote> <p>Is this the right approach to verify token ?</p> </blockquote> <p>Yes, this is the right way to verify token. For debugging, you can also verify token with the tokeninfo endpoint if you have any doubt or for quick testing :</p> <pre><code>https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123 </code></pre> <blockquote> <ul> <li>Do I send the id_token as Authorization bearer? Or is it for authorization only?</li> <li>How do I send the id_token to the sever side? Thru url, header?</li> </ul> </blockquote> <p>You can send JWT token in Authorization header but it could lead to usecase where you have <a href="https://stackoverflow.com/questions/29282578/multiple-http-authorization-headers">multiple Authorization headers</a>. It's best to URL encode or embed the token in the body. You can check Google example <a href="https://developers.google.com/identity/sign-in/web/backend-auth" rel="nofollow noreferrer">here</a></p> <p>Moreover, the following are required by Google :</p> <ul> <li>the token must be sent via HTTPS POST</li> <li>the token integrity must be verified</li> </ul> <p>To optimize your code, you could also move your Google <code>auth</code> object to your <code>app.js</code> at the root of your app instead of redefining it each time the token should be verified. In <code>app.js</code> :</p> <pre><code>var app = express(); var GoogleAuth = require('google-auth-library'); var auth = new GoogleAuth(); app.authClient = new auth.OAuth2(config.passport.google.clientID, config.passport.google.clientSecret, config.passport.google.callbackURL); </code></pre> <p>and in <code>verifyUser</code> call it from <code>req.app.authClient</code> :</p> <pre><code>req.app.authClient.verifyIdToken(...) </code></pre>
10,684,182
gnuplot with errorbars plotting
<p>The data in my "file.txt" file are as in the following (sample row shown)</p> <pre><code>31 1772911000 6789494.2537881 </code></pre> <p>Note that the second column is the mean and the third is the standard deviation of my input sample. So, for the error bar, I would need the bar at the x axis value 31, with the error bar start at (second column value)-(third column value), and end at (second column value)+(third column value). I tried the following:</p> <pre><code>plot "file.txt" using ($1-$2):1:($2+$1) with errorbars </code></pre> <p>but the result is inappropriate. Any help?</p>
10,684,516
2
0
null
2012-05-21 11:16:48.463 UTC
10
2018-09-21 19:00:35.067 UTC
null
null
null
null
506,901
null
1
16
plot|gnuplot
63,366
<p>You need x:y:err, so try</p> <pre><code>plot "file.txt" using 1:2:3 with yerrorbars </code></pre> <p><a href="https://i.stack.imgur.com/mgIxu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mgIxu.png" alt="yerrorbars"></a></p> <p>You may instead want candlesticks. These are generally a box with error bars extending out of the top and bottom, but setting the mins and maxes the same should give you boxes of the required size:</p> <pre><code>plot "file.txt" using 1:($2-$3):($2-$3):($2+$3):($2+$3) with candlesticks </code></pre> <p><a href="https://i.stack.imgur.com/DiH1m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DiH1m.png" alt="candlesticks"></a></p>
10,753,268
GitHub - error: failed to push some refs to '[email protected]:myrepo.git'
<p>I ran these commands below:</p> <pre><code>git add . </code></pre> <pre><code>git commit -m 't' </code></pre> <p>Then, when running the command below:</p> <pre><code>git push origin development </code></pre> <p>I got the error below:</p> <pre><code>To [email protected]:myrepo.git ! [rejected] development -&gt; development (non-fast-forward) error: failed to push some refs to '[email protected]:myrepo.git' To prevent you from losing history, non-fast-forward updates were rejected Merge the remote changes (e.g. 'git pull') before pushing again. See the 'Note about fast-forwards' section of 'git push --help' for details. </code></pre> <p>Are there any ways to solve the error above?</p>
10,753,360
15
0
null
2012-05-25 11:00:59.047 UTC
21
2022-06-07 15:24:06.55 UTC
2022-06-07 15:24:06.55 UTC
null
8,172,439
null
1,203,556
null
1
57
git|github|git-commit|git-push|git-add
205,603
<p>Your origin repository is ahead of your local repository. You'll need to pull down changes from the origin repository as follows before you can push. This can be executed between your commit and push.</p> <pre><code>git pull origin development </code></pre> <p><code>development</code> refers to the branch you want to pull from. If you want to pull from <code>master</code> branch then type this one.</p> <pre><code>git pull origin master </code></pre>
6,126,594
Http Live Streaming with the Apache web server
<p>Is it possible to do HLS with an Apache web server? Would it be enough to "put here the playlist with data chunks"? Is it that simple? Or is there some module, which can be used for that purpose?</p> <p>Thanks a lot for the reply</p>
6,324,864
2
1
null
2011-05-25 15:03:19.79 UTC
3
2016-06-30 09:28:04.03 UTC
2016-06-30 09:28:04.03 UTC
null
230,504
null
384,115
null
1
14
apache|live-streaming|http-live-streaming
43,453
<p>Yes, it's sufficient to merely have the m3u8 and segmented ts files available. The benefit of HLS is that it is bog simple HTTP.</p> <p>It's possible that you'll have to setup the mime types in Apache, but it's probably correct by default.</p>
23,272,839
How can I change font size in Eclipse for ALL text editors?
<p>I had to do a presentation yesterday, and as part of the presentation, I used Eclipse to show some code. Many of my coworkers in the room could not read the text and asked me to increase the size of the text for ALL files, not just Java files or XML files.</p> <p>But it wasn't immediately obvious from the available options how to do this. I went to menu <em>Window</em> → <em>Preferences and typed font</em> in the search input. This filtered the options to <em>General</em> → <em>Appearance</em> → <em>Colors and Fonts</em>. From here, I could see an option to change the font in Java files, but I didn't know how to change the font globally.</p> <p>I'm using Eclipse&nbsp;v4.3 Service Release 1 (Kepler) on Windows.</p> <p>This is similar to Stack&nbsp;Overflow question <em><a href="https://stackoverflow.com/questions/4922305">How can I change font size in Eclipse for Java text editors?</a></em>.</p>
23,272,840
8
0
null
2014-04-24 15:08:41.903 UTC
14
2018-06-06 20:31:06.29 UTC
2017-05-23 11:47:18 UTC
null
-1
null
1,930,619
null
1
59
eclipse
79,795
<p>This is what we figured out, and this is also found in <a href="https://apple.stackexchange.com/a/35588">this answer</a> and also <a href="https://stackoverflow.com/a/18097855/1930619">this answer</a> (I'll quote):</p> <blockquote> <p>Go to <em>Preferences</em> → <em>General</em> → <em>Appearance</em> → <em>Colors and Fonts</em>, expand the "Basic" folder and select "Text Font" and change that to whatever size you like.</p> </blockquote> <p>Pretty simple!</p> <p><img src="https://i.stack.imgur.com/NEEBr.png" alt="Here&#39;s what the dialog looks like -- click Edit"></p>
19,400,806
Which of the methods of turning on Data Protection on iOS are necessary?
<p>I'm interested in using data protection in my iOS app. There seem to be three places I can do this:</p> <ol> <li>In the App ID in the developer centre.</li> <li>In the entitlements plist</li> <li>By using <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/setAttributes%3aofItemAtPath%3aerror%3a"><code>[-NSFileManager setAttributesOfItemAtPath:error:]</code></a></li> </ol> <p>I've read the documentation that I can find, but none of it tells me which of these I need to do. If I do 1, does that turn it on for the whole app? Can I do 3 without doing 1? Do I need to do 2 at all?</p>
19,423,044
1
0
null
2013-10-16 10:17:53.417 UTC
9
2013-10-17 09:34:56.34 UTC
2013-10-16 10:33:19.697 UTC
null
15,371
null
15,371
null
1
11
ios|objective-c|nsfilemanager|data-protection
452
<p>I've had the following answers from Apple:</p> <blockquote> <p>If I do 1, does that turn it on for the whole app?</p> </blockquote> <p>Yes. It becomes the default data protection for all file system objects your app creates.</p> <blockquote> <p>Can I do 3 without doing 1?</p> </blockquote> <p>Yes. This is useful if you want protect just one file.</p> <p>You can also do 1 and 3, that is, use 1 to set the default and 3 to override that default for certain files.</p> <blockquote> <p>Do I need to do 2 at all?</p> </blockquote> <p>No. Once you do 1, the value ends up in your provisioning profile, which is then merged into your code signing entitlements at build time.</p>
47,235,256
How can I change Bootstrap carousel indicators into dots?
<p>I am using Bootstrap 4 Beta 2 version to do a carousel. The code looks like below: </p> <pre><code> &lt;ol class="carousel-indicators"&gt; &lt;li data-target="#mycarousel" data-slide-to="0" class="active"&gt;&lt;/li&gt; &lt;li data-target="#mycarousel" data-slide-to="1" &gt;&lt;/li&gt; &lt;li data-target="#mycarousel" data-slide-to="2" &gt;&lt;/li&gt; &lt;/ol&gt; </code></pre> <p>And the carousel indicator show as lines: <a href="https://i.stack.imgur.com/opi07.png" rel="noreferrer"><img src="https://i.stack.imgur.com/opi07.png" alt="enter image description here"></a></p> <p>Is there a way I can change the indicators into dots instead of lines? I would assume it is an bootstrap option but I didn't find that relevant document. Do I need to write custom css for that? </p>
47,235,368
6
0
null
2017-11-11 06:53:28.43 UTC
9
2022-05-09 08:33:30.177 UTC
2021-11-18 14:36:35.74 UTC
null
1,264,804
null
4,018,268
null
1
29
css|twitter-bootstrap
63,993
<p>Yes, I think you need to write custom CSS for doing lines into dots.<br> You just need to override two properties (<code>width</code> and <code>height</code>) and add a new one, <code>border-radius</code>, to <code>.carousel-indicators li</code>.<br> Make <code>width</code> and <code>height</code> values equal eg: <code>10px</code> each and give a <code>border-radius</code> of <code>100%</code>.</p> <pre><code>.carousel-indicators li { width: 10px; height: 10px; border-radius: 100%; } </code></pre>
21,065,242
EMV application development Questions
<p>I am new to EMV, currently I have an emergency EMV application development project, anybody could help me answer the below questions:</p> <ol> <li><p>what is EMV L2 application kernel? Is an API or just an executable EMV application?</p></li> <li><p>During an EMV payment transaction, what kind of data(message) information need to be captured from Chip&amp;Pin card so that it could submit to bank card issuer for authorization. Which ISO specification that the payment transaction data should apply for.</p></li> <li><p>what kind of connectivity between EMV terminal and acquirer? IP or Serial Port?</p></li> <li><p>Any testing tools for EMV application development? Such as acquirer host simulation.</p></li> </ol> <p>5.How much time it will take for an EMV application development?</p>
21,096,650
2
1
null
2014-01-11 17:07:40.127 UTC
11
2016-02-11 15:13:50.477 UTC
2016-02-11 15:13:50.477 UTC
null
949,297
null
2,297,408
null
1
13
emv
9,354
<p>1] <em>what is EMV L2 application kernel? Is an API or just an executable EMV application?</em></p> <p>It is more an API than an application. That's a piece of software that will use the underlying hardware to communicate with your EMV card, and will manage all of the EMV application level protocol (APDUs). If you're developing for a specific payment terminal, you'll have to contact the manufacturer to buy its kernel (ex : Ingenico, VeriFone). If you develop for a PC solution, you can buy some generic kernel (ex : <a href="http://www.level2kernel.com/emv_kernel.html">EmvX</a>). You probably don't want to write your own kernel, <a href="http://blog.abrantix.com/2013/08/07/paypass-paywave-and-expresspay-a-nightmare-for-developers/">this blog</a> estimates the cost of doing so :</p> <blockquote> <p><em>EMV recommends to take around 18 month time to develop and certify a contact kernel. [...] Something between 200’000 and 400’000 Euro is a normal value.</em></p> </blockquote> <p>2] <em>During an EMV payment transaction, what kind of data(message) information need to be captured from Chip&amp;Pin card so that it could submit to bank card issuer for authorization. Which ISO specification that the payment transaction data should apply for.</em></p> <p>The documentation for the EMV protocol is publicly available at <a href="http://www.emvco.com/specifications.aspx?id=223">EMVco.com</a>. An EMV card is a chip card, meaning you don't capture info from the card to later submit it to your bank (acquirer). In (very brief), your card will provide its characteristics to your application, and require a variable set of parameters (ex : amount, date, tip, etc.). Your application will reply with the required info and the card will then eventually decide if it accepts the transaction offline, accepts it online (after validation by the issuer), or rejects it.</p> <p>3] <em>what kind of connectivity between EMV terminal and acquirer? IP or Serial Port?</em></p> <p>Between terminal and acquirer, it's a dial-up connection most of time (60% of merchants in the U.S. in 2012), or IP connection.</p> <p>4] <em>Any testing tools for EMV application development? Such as acquirer host simulation.</em></p> <p>A bunch. You'll need a card issuer simulator (Visa, Mastercard, etc.), an acquirer (bank), simulator which will depend on the acquirer you're working with (in Canada, it could be Base24). You'll then need tools to troubleshoot communication problems between your application and EMV card (ex : <a href="http://www.fime.com/smartspy-contact.html">SmartSpy</a>), and eventually tools to prepare for certification (ex : from <a href="http://www.iccsolutions.com/offsite-2/page16/index.php">ICC Solutions</a>, or <a href="http://www.fime.com/acquirer-test-cards.html">Fime</a>)</p> <p>5] <em>How much time it will take for an EMV application development?</em></p> <p>A lot. Where I work, it just took a little bit more than 1 year to a 6 developers team with a strong experience in EMV transactions and payment applications to write a new payment application from scratch for an Ingenico terminal and to get it ready for certification. One of the most painful part is to succeed certification tests. Targeting a PC environment may make development easier (easier debugging, more online resources and documentation, etc), but not having in-house skills and experience will increase significantly the cost</p>
21,376,645
Store string into array in c
<p>As i know, i can create an array with item inside such as:</p> <pre><code>char *test1[3]= {"arrtest","ao", "123"}; </code></pre> <p>but how can i store my input into array like code above because i only can code it as </p> <pre><code>input[10]; scanf("%s",&amp;input) or gets(input); </code></pre> <p>and it store each char into each space.</p> <p>How can i store the input <strong>"HELLO"</strong> such that it stores into input[0] but now</p> <p>H to input[0],E to input[1], and so on.</p>
21,376,885
6
1
null
2014-01-27 09:01:51.767 UTC
5
2017-03-22 06:16:31.737 UTC
2014-01-27 09:17:12.07 UTC
null
1,309,352
null
3,122,881
null
1
9
c|arrays
91,822
<p>You need a 2 dimensional character array to have an array of strings:</p> <pre><code>#include &lt;stdio.h&gt; int main() { char strings[3][256]; scanf("%s %s %s", strings[0], strings[1], strings[2]); printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]); } </code></pre>
21,606,454
How to handle System.Data.Entity.Validation.DbEntityValidationException?
<p>My app gets the following error:</p> <blockquote> <p>An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code</p> <p>Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.</p> </blockquote> <p>I get this error when trying to register a new user. Error happens on 'db.SaveChanges()'</p> <p>Here is the code:</p> <pre><code>public ActionResult Registration(x.Models.User user) { if(ModelState.IsValid) { using(var db = new xDBEntities1()) { var crypto = new SimpleCrypto.PBKDF2(); var encrpPass = crypto.Compute(user.password); var sysUser = db.users.Create(); sysUser.email = user.email; sysUser.username = user.username; sysUser.password = encrpPass; sysUser.premium_credits = 0; sysUser.login_times = 0; sysUser.last_ip = Request.ServerVariables[&quot;REMOTE_ADDR&quot;]; sysUser.creation_ip = Request.ServerVariables[&quot;REMOTE_ADDR&quot;]; sysUser.banned = 0; sysUser.creation_date = DateTime.Now; sysUser.creation_time = DateTime.Now.TimeOfDay; db.users.Add(sysUser); db.SaveChanges(); } } return RedirectToAction(&quot;Index&quot;, &quot;Home&quot;); } </code></pre> <p>edit: User model class</p> <pre><code>public class User { [Required] [StringLength(50)] [Display(Name=&quot;Username: &quot;)] public String username { get; set; } [Required] [DataType(DataType.Password)] [StringLength(50,MinimumLength=6)] [Display(Name=&quot;Password: &quot;)] public string password { get; set; } [Required] [EmailAddress] [StringLength(50)] public string email { get; set; } public int phonenumber { get; set; } public int mobilephonenumber { get; set; } } } </code></pre> <p>How can I handle it ?</p>
21,606,785
7
0
null
2014-02-06 15:04:27.623 UTC
6
2020-11-17 12:16:05.41 UTC
2020-07-01 05:05:37.463 UTC
null
6,174,449
null
2,545,576
null
1
19
c#|asp.net-mvc|entity-framework|asp.net-mvc-4
85,475
<p>There is some sort of database validation happening preventing you from writing the data into it. </p> <p>The solution is already stated on this page:</p> <p><a href="https://stackoverflow.com/questions/7795300/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-propert">Validation failed for one or more entities. See &#39;EntityValidationErrors&#39; property for more details</a></p> <p>As an extra note to this as you are using .net mvc you should use System.Diagnostics.Debug.WriteLine() instead of Console.Writeline() and this will write to the debug output window when you are debugging. As you cannot write to the console when running a mvc project.</p>
35,578,404
Giving wrapped flexbox items vertical spacing
<p>I've recently been playing with Flexbox for the first time and, in general, it's absolutely amazing. I've encountered an issue recently however, where I cannot seem to give flex items that are wrapping any vertical spacing.</p> <p>I've tried using:</p> <pre><code>align-content: space-between; </code></pre> <p>but this doesn't seem to do anything. From the reading I've done, this would only seem to work if my flex container is taller than the elements contained within (is this right?) If so, then would I not have to set a height for my flex-container, which would seem to defeat the purpose of using flexbox?</p> <p>The only way I can think of to make this work would be to give bottom margin to the elements within, but again this seems to defeat the purpose.</p> <p>Hopefully I'm missing something fairly obvious - here's a link to a codepen: <a href="http://codepen.io/lordchancellor/pen/pgMEPz" rel="noreferrer">http://codepen.io/lordchancellor/pen/pgMEPz</a></p> <p>Also, here's my code:</p> <p>HTML:</p> <pre><code>&lt;div class="container"&gt; &lt;div class="col-sm-12"&gt; &lt;h1&gt;Flexbox Wrapping&lt;/h1&gt; &lt;div class="flexContainer"&gt; &lt;div class="flexLabel"&gt;This is a flex label&lt;/div&gt; &lt;a class="btn btn-primary"&gt;Button 1&lt;/a&gt; &lt;a class="btn btn-warning"&gt;Button 2&lt;/a&gt; &lt;a class="btn btn-success"&gt;Button 3&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.flexContainer { display: flex; flex-wrap: wrap; align-items: center; align-content: space-between; justify-content: center; } .flexContainer .flexLabel { flex-basis: 150px; flex-shrink: 0; } </code></pre> <p>EDIT - Just going to add a little more detail here, as I'm not sure I'm putting it across well enough.</p> <p>In my larger project, I have some block level elements that are arranged in a row using flexbox. However, there needs to be some responsiveness as the user may reduce the screen width. At this point, I want my elements to begin to stack (hence the wrap). However, as the elements begin to stack, they are all touching vertically, where I want there to be spacing.</p> <p>It's beginning to look like top and bottom margins may be the only way to resolve this - however I was wondering if there was a flexbox-centric way to achieve this.</p>
35,578,723
5
0
null
2016-02-23 13:05:32.41 UTC
8
2022-02-26 10:05:37.243 UTC
2016-02-23 14:02:14.547 UTC
null
3,456,730
null
3,456,730
null
1
82
html|css|flexbox
102,830
<p>If you force wrapping by applying a width you can then use margins as you normally would without setting a height.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.flexContainer { display: flex; align-items: center; flex-wrap: wrap; justify-content: center; background: pink; width: 150px; } .flexContainer &gt; * { margin: 1em 0; } .flexContainer .flexLabel { flex-basis: 150px; flex-shrink: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;div class="container"&gt; &lt;div class="col-sm-12"&gt; &lt;h1&gt;Flexbox Wrapping&lt;/h1&gt; &lt;div class="flexContainer"&gt; &lt;div class="flexLabel"&gt;This is a flex label&lt;/div&gt; &lt;a class="btn btn-primary"&gt;Button 1&lt;/a&gt; &lt;a class="btn btn-warning"&gt;Button 2&lt;/a&gt; &lt;a class="btn btn-success"&gt;Button 3&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
8,937,544
Xcode: Invalid parameter not satisfying
<p>I keep running into a pretty frustrating error in Xcode after implementing a date picker. The error in the debugger is: "Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: date"</p> <p>I've been going through my code for hours now, and can't find the issue. It may be because I'm not checking for nil, there is no date the first time the app installs and launches, so that may be causing the crash. If it is, how do I check for nil in this code? I'm still very new at programming, any help would be much appreciated. Here is the code:</p> <pre><code>#import "DatePickerViewController.h" @implementation DatePickerViewController @synthesize datePicker; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { // Initialization code } return self; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview // Release anything that's not essential, such as cached data } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UILocalNotification *localNotif = [[UILocalNotification alloc] init]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"mm'/'dd'/'yyyy"]; NSDate *eventDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"DatePickerViewController.selectedDate"]; localNotif.fireDate = [eventDate dateByAddingTimeInterval:-13*60*60]; localNotif.timeZone = [NSTimeZone defaultTimeZone]; localNotif.alertBody = @"Tomorrow!"; localNotif.alertAction = nil; localNotif.soundName = UILocalNotificationDefaultSoundName; localNotif.applicationIconBadgeNumber = 0; [[UIApplication sharedApplication]presentLocalNotificationNow:localNotif]; return YES; } - (void)viewDidLoad { NSDate *storedDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"DatePickerViewController.selectedDate"]; [self.datePicker setDate:storedDate animated:NO]; } - (IBAction)dateChanged:(id)sender { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSDate *selectedDate = [self.datePicker date]; [defaults setObject:selectedDate forKey:@"DatePickerViewController.selectedDate"]; } </code></pre>
8,937,724
2
0
null
2012-01-20 06:24:45.43 UTC
7
2019-09-02 07:40:11.623 UTC
2013-07-01 15:30:31.217 UTC
null
1,088,618
null
1,088,618
null
1
26
ios|xcode|parameters
60,676
<p>You don't check if date is null, before using it, in ex.</p> <pre><code>(void)viewDidLoad { NSDate *storedDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"DatePickerViewController.selectedDate"]; // add this check and set if (storedDate == nil) { storedDate = [NSDate date]; } // --- [self.datePicker setDate:storedDate animated:NO]; } </code></pre>
8,376,609
Prevent anti-aliasing for imshow in matplotlib
<p>When I use matplotlib's imshow() method to represent a small numpy matrix, it ends up doing some smoothing between pixels. Is there any way to disables this? It makes my figure's misleading in presentations.<img src="https://i.stack.imgur.com/fg5ay.png" alt="A 28x28 matrix plotted with imshow()"></p> <p>The figure above is a 28x28 image, so I should be seeing large squares of single colors representing each pixel (as matlab would display it when using imagesc()). But Instead, the pixels seem to be blurred with neighboring pixels. Is there a way to disable this behavior?</p>
8,376,685
2
0
null
2011-12-04 16:12:32.907 UTC
6
2012-03-06 14:01:23.307 UTC
null
null
null
null
518,386
null
1
50
python|numpy|matplotlib|scipy|blurry
15,379
<p>There is an interpolation option for <code>imshow</code> which controls how and if interpolation will be applied to the rendering of the matrix. If you try</p> <pre><code>imshow(array, interpolation="nearest") </code></pre> <p>you might get something more like you want. As an example</p> <pre><code>A=10*np.eye(10) + np.random.rand(100).reshape(10,10) imshow(A) </code></pre> <p><img src="https://i.stack.imgur.com/2C1RZ.png" alt="imshow(A)"></p> <p>compared with</p> <pre><code>A=10*np.eye(10) + np.random.rand(100).reshape(10,10) imshow(A, interpolation="nearest") </code></pre> <p><img src="https://i.stack.imgur.com/DG96d.png" alt="enter image description here"></p>
55,171,696
How to remove (base) from terminal prompt after updating conda
<p>After updating miniconda3, whenever I open a terminal it shows "(base)" in front of my username and host.</p> <p>In this answer post <a href="https://askubuntu.com/a/1113206/315699">https://askubuntu.com/a/1113206/315699</a> it was suggested to use</p> <pre><code>conda config --set changeps1 False </code></pre> <p>To remove it.</p> <p>But that would remove the indication for any conda environment. I would like to remove it only for the base one, so that I can maintain it always active and have access to its python and installed packages without having to always see this (base) taking up space.</p>
55,172,508
13
0
null
2019-03-14 20:46:15.52 UTC
40
2022-05-16 13:52:02.257 UTC
2019-03-14 21:37:58.957 UTC
null
1,273,751
null
1,273,751
null
1
103
bash|terminal|anaconda|conda|miniconda
103,149
<h1>Use the <code>base</code> env's activation hook</h1> <p>For each env, any scripts in the <code>etc/conda/activate.d</code> directory will be executed post-activation (likewise <code>etc/conda/deactivate.d</code> scripts for deactivation). If you add a script to remove the <code>(base)</code>, similar to <a href="https://stackoverflow.com/a/55801078/570918">@ewindes suggestion</a>, you'll get the behavior you desire.</p> <p>I had to create this directory for <strong>base</strong>, which is just the root of your Anaconda/Miniconda folder. E.g.,</p> <pre><code>mkdir -p miniconda3/etc/conda/activate.d </code></pre> <p>Then made a simple file in there (e.g., <code>remove_base_ps1.sh</code>) with one line:</p> <pre><code>PS1=&quot;$(echo &quot;$PS1&quot; | sed 's/(base) //') &quot; </code></pre> <p>If you are using zsh, use this instead.</p> <pre><code>PROMPT=$(echo $PROMPT | sed 's/(base) //') </code></pre> <p>Launching a new shell then does not show <code>(base)</code>, and deactivating out of nested envs also takes care of the PS1 change.</p> <p>Note: You must add quotes around $PS1 if you want to preserve ending spaces.</p>
26,958,592
Django, after upgrade: MySQL server has gone away
<p>I recently upgraded from Django 1.4 to Django 1.7 and since I keep getting the following error message for some scripts, sometimes:</p> <p><code>OperationalError: (2006, 'MySQL server has gone away')</code></p> <p>The scripts are very long or continuously running tasks that might involve phases of not communicating with the db for several minutes, so the connection times out. However, before I upgraded, that was no problem, as Django seemed to automatically re-establish a connection. Now it doesn't which means the tasks often stop and fail in the middle.</p> <p>Does anyone know what has changed and how I can fix it?</p> <p>Is it perhaps related to that ticket/fix: <a href="https://code.djangoproject.com/ticket/21463">https://code.djangoproject.com/ticket/21463</a></p> <p>Thanks a lot!</p>
27,190,534
9
1
null
2014-11-16 15:27:24 UTC
20
2021-03-27 22:44:09.06 UTC
null
null
null
null
789,656
null
1
33
mysql|django|timeout
30,276
<p>The reason of such behavior is persistent connect to database, which was introduced in Django 1.6.</p> <p>To prevent connection timeout error you should set <code>CONN_MAX_AGE</code> in <code>settings.py</code> to value which is less than <code>wait_timeout</code> in MySQL config (<code>my.cnf</code>). In that case Django detects that connection need to be reopen earlier than MySQL throws it. Default value for MySQL 5.7 is 28800 seconds.</p> <p><code>settings.py</code>:</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'CONN_MAX_AGE': 3600, &lt;other params here&gt; } } </code></pre> <p>Documentation: <a href="https://docs.djangoproject.com/en/1.7/ref/settings/#conn-max-age" rel="noreferrer">https://docs.djangoproject.com/en/1.7/ref/settings/#conn-max-age</a></p> <p><code>my.cnf</code>: </p> <pre><code>wait_timeout = 28800 </code></pre> <p>Documentation: <a href="https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_wait_timeout" rel="noreferrer">https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_wait_timeout</a></p>
27,417,398
How to change the checked mark color of a checkbox in HTML?
<p>I want to change the checked-mark (tick) color in the following checkbox (its name is "genres") as "blue". But it is displayed as "black".</p> <pre><code>&lt;input type="checkbox" name="genres" value="adventure" id="adventure_id"&gt; &lt;label for="adventure_id" style="font-family: 'SExtralight'; font-size:14px;"&gt;Adventure&lt;/label&gt; </code></pre>
27,417,602
2
2
null
2014-12-11 07:23:48.663 UTC
1
2021-09-13 14:48:20.813 UTC
null
null
null
null
4,376,902
null
1
18
html
115,493
<p>I think this is what you want (CSS only):</p> <p><strong><a href="http://jsfiddle.net/5g3w32ug/" rel="noreferrer">DEMO</a></strong></p> <p>You can check <a href="https://stackoverflow.com/questions/2639373/css-html-how-do-i-change-the-color-of-the-check-mark-within-the-checkbox-input">this</a> answer, the source from what I've got.</p> <p>CSS:</p> <pre><code> input[type="checkbox"]:checked + label::after { content: ''; position: absolute; width: 1.2ex; height: 0.4ex; background: rgba(0, 0, 0, 0); top: 0.9ex; left: 0.4ex; border: 3px solid blue; border-top: none; border-right: none; -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); -o-transform: rotate(-45deg); -ms-transform: rotate(-45deg); transform: rotate(-45deg); } input[type="checkbox"] { line-height: 2.1ex; } input[type="radio"], input[type="checkbox"] { position: absolute; left: -999em; } input[type="checkbox"] + label { position: relative; overflow: hidden; cursor: pointer; } input[type="checkbox"] + label::before { content: ""; display: inline-block; vertical-align: -25%; height: 2ex; width: 2ex; background-color: white; border: 1px solid rgb(166, 166, 166); border-radius: 4px; box-shadow: inset 0 2px 5px rgba(0,0,0,0.25); margin-right: 0.5em; } </code></pre>
112,603
What is 'JNI Global reference'
<p>I am using jProfiler to find memory leaks in a Java swing application. I have identified instances of a JFrame which keeps growing in count.</p> <p>This frame is opened, and then closed.</p> <p>Using jProfiler, and viewing the Paths to GC Root there is only one reference, 'JNI Global reference'.</p> <p>What does this mean? Why is it hanging on to each instance of the frame?</p>
112,705
3
0
null
2008-09-22 00:01:13.547 UTC
10
2015-05-22 08:53:41.247 UTC
null
null
null
waquin
18,445
null
1
32
java|swing|jprofiler
27,547
<p>Wikipedia has a good overview of <a href="http://en.wikipedia.org/wiki/Java_Native_Interface" rel="noreferrer">Java Native Interface</a>, essentially it allows communication between Java and native operating system libraries writen in other languages.</p> <p>JNI global references are prone to memory leaks, as they are not automatically garbage collected, and the programmer must explicitly free them. If you are not writing any JNI code yourself, it is possible that the library you are using has a memory leak.</p> <p><strong>edit</strong> <a href="http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/refs.html" rel="noreferrer">here</a> is a bit more info on local vs. global references, and why global references are used (and how they should be freed)</p>
385,262
How do I send a custom header with urllib2 in a HTTP Request?
<p>I want to send a custom "Accept" header in my request when using urllib2.urlopen(..). How do I do that?</p>
385,411
3
0
null
2008-12-22 00:39:53.047 UTC
13
2019-02-11 11:14:50.877 UTC
null
null
null
null
16,432
null
1
68
python|header|urllib2
83,353
<p>Not quite. Creating a <code>Request</code> object does not actually send the request, and Request objects have no <code>Read()</code> method. (Also: <code>read()</code> is lowercase.) All you need to do is pass the <code>Request</code> as the first argument to <code>urlopen()</code> and that will give you your response.</p> <pre><code>import urllib2 request = urllib2.Request("http://www.google.com", headers={"Accept" : "text/html"}) contents = urllib2.urlopen(request).read() </code></pre>
39,501,899
Mysql duplicate foreign key constraint
<p>When I try to import a database I get this error</p> <pre><code>SQL query: ALTER TABLE `bid` ADD CONSTRAINT `bid_ibfk_4` FOREIGN KEY (`auction_contact_id`) REFERENCES `auction_contact` (`auction_contact_id`), ADD CONSTRAINT `bid_ibfk_3` FOREIGN KEY (`car_id`) REFERENCES `car` (`car_id`) MySQL said: Documentation #1826 - Duplicate foreign key constraint name 'projekt_classics/bid_ibfk_3' </code></pre> <p>Looking at all the foreign keys I get this as a result</p> <pre><code>select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY' </code></pre> <p>result</p> <pre><code>def projekt_classics bid_ibfk_2 projekt_classics bid FOREIGN KEY def projekt_classics bid_ibfk_3 projekt_classics bid FOREIGN KEY def projekt_classics car_ibfk_1 projekt_classics car FOREIGN KEY def projekt_classics car_ibfk_3 projekt_classics car FOREIGN KEY def projekt_classics car_ibfk_4 projekt_classics car FOREIGN KEY def projekt_classics car_brand_ibfk_1 projekt_classics car_brand FOREIGN KEY </code></pre> <p>searching into the sql the <code>bid_ibfk_3</code> constraint shows only 1 time. All the data is in the imported database but I wonder how I can avoid this error.</p> <p><strong>EDIT:</strong> First dropping all the tables runs the query without problems. I export my database using PHPmyadmin. I guess the error was because of the foreign key constraint not yet deleted before trying to create it again.</p>
39,502,574
1
0
null
2016-09-15 01:23:39.57 UTC
2
2019-10-15 11:38:52.57 UTC
2019-10-15 11:38:52.57 UTC
null
8,701,527
null
3,118,044
null
1
8
mysql
38,025
<p>If you look at the result of your query, the foreign key <code>bid_ibfk_3</code> <strong>already exists</strong>. In fact it is in the second row of the result.</p> <pre><code>def projekt_classics bid_ibfk_2 projekt_classics bid FOREIGN KEY --the row below is the foreign key that you are trying to create def projekt_classics bid_ibfk_3 projekt_classics bid FOREIGN KEY def projekt_classics car_ibfk_1 projekt_classics car FOREIGN KEY def projekt_classics car_ibfk_3 projekt_classics car FOREIGN KEY def projekt_classics car_ibfk_4 projekt_classics car FOREIGN KEY def projekt_classics car_brand_ibfk_1 projekt_classics car_brand FOREIGN KEY </code></pre> <p>That's why you are getting the duplicate foreign key constraint name when you are trying to execute this:</p> <pre><code>ADD CONSTRAINT `bid_ibfk_3` FOREIGN KEY (`car_id`) REFERENCES `car` (`car_id`) </code></pre> <p>You can modify your query to check first if the foreign key that you are trying to create does not exist, before actually creating it.</p> <pre><code>IF NOT EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME = 'bid_ibfk_3') THEN ALTER TABLE `bid` ADD CONSTRAINT `bid_ibfk_3` FOREIGN KEY (`car_id`) REFERENCES `car` (`car_id`); END IF </code></pre>
22,378,742
Laravel - Video file validation
<p>Is this how to validate a video file in laravel ? </p> <pre><code>$validator = Validator::make(Input::all(), array( 'file' =&gt; 'mimes:mp4,mov,ogg | max:20000' ) ); </code></pre> <p>because even if the file uploaded is a mov type, it will return that the file should be one of the types listed in the rule above. </p> <p><hr/> <em>How I ended up solving it:</em> </p> <p>As prompted from the answer's below I ended up storing the mime type for the uploaded file to a <code>$mime</code> variable like so: </p> <pre><code>$file = Input::file('file'); $mime = $file-&gt;getMimeType(); </code></pre> <p>Then had to write an if statement to check for video mime types: </p> <pre><code>if ($mime == "video/x-flv" || $mime == "video/mp4" || $mime == "application/x-mpegURL" || $mime == "video/MP2T" || $mime == "video/3gpp" || $mime == "video/quicktime" || $mime == "video/x-msvideo" || $mime == "video/x-ms-wmv") { // process upload } </code></pre>
22,379,793
7
0
null
2014-03-13 12:31:20.93 UTC
7
2021-12-30 14:52:19.05 UTC
2018-03-16 16:50:39.143 UTC
null
1,410,918
null
1,410,918
null
1
31
php|laravel|validation
52,925
<p>That code is checking for the extension but not the MIME type. You should use the appropriate MIME type:</p> <pre><code> Video Type Extension MIME Type Flash .flv video/x-flv MPEG-4 .mp4 video/mp4 iPhone Index .m3u8 application/x-mpegURL iPhone Segment .ts video/MP2T 3GP Mobile .3gp video/3gpp QuickTime .mov video/quicktime A/V Interleave .avi video/x-msvideo Windows Media .wmv video/x-ms-wmv </code></pre> <p>If you are not sure the MIME type of the file you are testing you can try <code>$file-&gt;getMimeType()</code></p>
41,797,920
ImportError: No module named 'speech_recognition' in python IDLE
<p>I'm trying to use the speech recognition module with python 3.5.1 to make my jarvis AI voice activated! I have looked through stack overflow and found some questions similar to mine but they did not have the answer that i needed, i need an answer individualized for this. I have downloaded all the necessary packages and still no luck, i get this error:</p> <pre><code>ImportError: No module named 'speech_recognition' </code></pre> <p>If I run: </p> <pre><code>python -m speech_recognition </code></pre> <p>In terminal it runs only in terminal, i can talk to it and it isn't nearly spot on but it hears me and and can interpret some words. I have downloaded all the packages in terminal from this sites instructions.</p> <p><a href="https://pypi.python.org/pypi/SpeechRecognition/" rel="noreferrer">https://pypi.python.org/pypi/SpeechRecognition/</a></p> <p>When i run my code in IDLE my code gets the error shown above. I'm on a iMac running macOS Sierra 10.12.2, if anyone has the answer that would be helpful. Thank you!</p> <p>heres my code:</p> <pre><code>import speech_recognition import pyttsx speech_engine = pyttsx.init('sapi5') # see speech_engine.setProperty('rate', 150) def speak(text): speech_engine.say(text) speech_engine.runAndWait() recognizer = speech_recognition.Recognizer() def listen(): with speech_recognition.Microphone() as source: recognizer.adjust_for_ambient_noise(source) audio = recognizer.listen(source) try: return recognizer.recognize_sphinx(audio) # or: return recognizer.recognize_google(audio) except speech_recognition.UnknownValueError: print("Could not understand audio") except speech_recognition.RequestError as e: print("Recog Error; {0}".format(e)) return "" speak("Say something!") speak("I heard you say " + listen()) </code></pre>
41,798,051
10
2
null
2017-01-23 01:09:02.54 UTC
3
2022-08-14 20:38:28.557 UTC
2017-01-23 01:34:00.07 UTC
null
7,455,337
null
7,455,337
null
1
11
python|module|speech-recognition|speech-to-text
70,574
<p>OS X Sierra <a href="https://discussions.apple.com/thread/7740214?start=0&amp;tstart=0" rel="nofollow noreferrer">comes with Python 2.7.10</a>. Since you are using Python 3.5.1, you have presumably installed it yourself and you now have two versions of Python. IDLE is clearly running with the Python version for which you did <em>not</em> install the <code>speech_recognition</code> module. </p> <p>What to do depends on your set-up. I'd start by running <code>idle3</code> from the command line, instead of <code>idle</code>. If your module is installed for Python 3, that's all you need. If this doesn't work, check everything with an eye to the different versions and straighten them out the way you want them. </p>
20,372,128
iphone push notifications passphrase issue (pyAPns)
<p>I'm trying to implement push notifications for iphone based on PyAPNs</p> <p>When I run it on local but it blocks and prompts me to enter the passphrase manually and doesn't work until I do </p> <p>I don't know how to set it up so to work without prompt</p> <p>This is my code:</p> <pre><code>from apns import APNs, Payload import optparse import os certificate_file = here(".." + app.fichier_PEM.url ) token_hex = '0c99bb3d077eeacdc04667d38dd10ca1a' pass_phrase = app.mot_de_passe apns = APNs(use_sandbox=True, cert_file= certificate_file) payload = Payload(alert = message.decode('utf-8'), sound="default", badge=1) apns.gateway_server.send_notification(token_hex, payload) # Get feedback messages for (token_hex, fail_time) in apns.feedback_server.items(): print "fail: "+fail_time </code></pre>
20,375,745
2
0
null
2013-12-04 09:56:50.193 UTC
13
2014-07-22 04:18:08.28 UTC
2013-12-04 12:44:48.777 UTC
null
1,017,893
null
745,378
null
1
14
python|django|push-notification|apple-push-notifications|django-1.2
8,633
<p>When you create a .pem file without phrase specify <code>-nodes</code></p> <p><b>To Create .pem file without phrase</b></p> <pre><code>openssl pkcs12 -nocerts -out Pro_Key.pem -in App.p12 -nodes </code></pre> <p><b>To Create .pem file with phrase</b></p> <pre><code>openssl pkcs12 -nocerts -out Pro_Key.pem -in App.p12 </code></pre> <p>If you have a .pem file with password you can <b>get rid of its password for PyAPNs </b> using the following</p> <pre><code>openssl rsa -in haspassword.pem -out nopassword.pem </code></pre> <p>Refer </p> <ul> <li><a href="http://www.raywenderlich.com/3443/apple-push-notification-services-tutorial-part-12">Raywenderlich</a> </li> <li><a href="http://blog.serverdensity.com/2009/07/10/how-to-build-an-apple-push-notification-provider-server-tutorial/">Apple Push Notification Step By Step Guide</a></li> </ul> <p>for make certificates and other configurations.</p> <p>Some Python library for interacting with the Apple Push Notification service (APNs)</p> <ul> <li><strong><a href="https://github.com/djacobs/PyAPNs">djacobs->PyAPNs</a></strong></li> <li><strong><a href="https://github.com/samuraisam/pyapns">samuraisam->pyapns</a></strong></li> <li><strong><a href="https://bitbucket.org/sardarnl/apns-client/">apns-client</a></strong></li> </ul>
24,150,739
Code to read xlsx sheet into a table in a SQL Server database
<p>I am trying to read data from an Excel sheet (<code>.xlsx</code> file) into a table in SQL Server 2008. I want this to be run everyday as a batch job and hence want to write SQL code in a stored procedure to do so.</p> <p>Could someone help me? I have admin rights.</p> <p>~TIA</p>
24,173,062
6
0
null
2014-06-10 21:00:41.05 UTC
7
2017-08-10 11:31:45.46 UTC
2014-06-11 21:24:56.777 UTC
null
2,912,775
null
2,912,775
null
1
23
sql-server|tsql|xlsx
103,326
<p>This should do... </p> <pre><code>SELECT * FROM OPENROWSET( 'Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;HDR=NO;Database=T:\temp\Test.xlsx', 'select * from [sheet1$]') </code></pre> <p>But we aware, sometimes this just wont work. I had this working for local admins only. </p> <p>There is a way to do this using SSIS as well.</p>
24,042,949
Block retain cycles in Swift?
<p>Traditionally in Objc, we do weakSelf to prevent additional retain count for blocks.</p> <p>How does swift internally manage retain cycles that occur in blocks for Objc?</p>
24,045,189
3
0
null
2014-06-04 16:38:41.853 UTC
23
2016-05-12 10:00:21.54 UTC
null
null
null
null
1,213,166
null
1
50
swift
19,704
<p>To prevent a block from holding a strong reference to an object, you must define a capture list for the block.</p> <p>The closure expression syntax is defined as follows:</p> <pre><code>{ ( /*parameters*/ ) -&gt; /*return type*/ in // statements } </code></pre> <p>But this is extended later in the documentation to include a capture list. This effectively equates to the expression syntax being defined as follows:</p> <pre><code>{ [ /*reference type*/ /*object*/, ... ] ( /*parameters*/ ) -&gt; /*return type*/ in // statements } </code></pre> <p>...where <code>/*reference type*/</code> can be either <code>weak</code> or <code>unowned</code>.</p> <p>The capture list is the first thing to appear in the closure and it is optional. The syntax, as shown above is defined as one or more pairs of reference type followed by object; each pair is separated by a comma. For example:</p> <pre><code>[unowned self, weak otherObject] </code></pre> <p>Complete example:</p> <pre><code>var myClosure = { [unowned self] in print(self.description) } </code></pre> <p>Note that an <code>unowned</code> reference is non-optional, so you don't need to unwrap it.</p> <p>Hopefully that answers your question. You can read up more about ARC in Swift in the relevant section of the <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-XID_61">documentation</a>.</p> <p>You should pay particular attention to the difference between <code>weak</code> and <code>unowned</code>. It could be safer in your implementation to use <code>weak</code>, because using <code>unowned</code> assumes the object will never be nil. This may lead to your app crashing if the object has actually been deallocated before being used in your closure.</p> <p>Using <code>weak</code> as the reference type, you should unwrap with <code>?</code>, as follows:</p> <pre><code>var myClosure = { [weak self] in print(self?.description) } </code></pre>
36,031,590
Right way to update state in redux reducers
<p>I'm a newbie in redux and es6 syntax. I make my app with official redux tutorial, and with this <a href="http://redux.js.org/docs/advanced/ExampleRedditAPI.html" rel="noreferrer">example</a>. </p> <p>There is JS snippet below. My point - to define REQUEST_POST_BODY and RECEIVE_POST_BODY cases in posts reducer. Main difficult - to find and update right object in store.</p> <p>I try to use code from example:</p> <pre><code> return Object.assign({}, state, { [action.subreddit]: posts(state[action.subreddit], action) }) </code></pre> <p>But it used simple array of posts. It's not needed to find right post by id.</p> <p>Here my code:</p> <pre><code> const initialState = { items: [{id:3, title: '1984', isFetching:false}, {id:6, title: 'Mouse', isFetching:false}] } // Reducer for posts store export default function posts(state = initialState, action) { switch (action.type) { case REQUEST_POST_BODY: // here I need to set post.isFetching =&gt; true case RECEIVE_POST_BODY: // here I need to set post.isFetching =&gt; false and post.body =&gt; action.body default: return state; } } function requestPostBody(id) { return { type: REQUEST_POST_BODY, id }; } function receivePostBody(id, body_from_server) { return { type: RECEIVE_POST_BODY, id, body: body_from_server }; } dispatch(requestPostBody(3)); dispatch(receivePostBody(3, {id:3, body: 'blablabla'})); </code></pre>
36,031,765
3
1
null
2016-03-16 09:32:38.753 UTC
11
2019-08-07 23:31:06.033 UTC
null
null
null
null
2,807,660
null
1
28
javascript|reactjs|redux|flux
95,457
<h1>With Arrays</h1> <p>If you'd prefer to stick with arrays, then you can write a reducer that just tackles single <code>post</code> objects.</p> <pre><code>export default function reducePost(post, action) { if(post.id !== action.id) return post; switch(action.type) { case REQUEST_POST_BODY: return Object.assign({}, post, { isFetching: true }); case RECEIVE_POST_BODY: return Object.assign({}, post, { isFetching: false, body: action.body }); default: return post; } </code></pre> <p>Your root reducer would become:</p> <pre><code>export default function posts(state = initialState, action) { return state.map(post =&gt; reducePost(post, action); } </code></pre> <p>We're just running our new reducer over each post in the list, to return an updated array of posts. In this case, the unique id will ensure that only one item will be changed.</p> <h1>With Objects</h1> <p>If each item has a unique string/number id, then you can flip your array around and use an <code>object</code> instead.</p> <pre><code>const initialState = { items: { 3: {id:3, title: '1984', isFetching:false}, 6: {id:6, title: 'Mouse', isFetching:false} }; } </code></pre> <p>Then you can simplify your reducer.</p> <pre><code>switch (action.type) { case REQUEST_POST_BODY: let id = action.id; return Object.assign({}, state, { [id]: Object.assign({}, state[id], { isFetching: true }) }); case RECEIVE_POST_BODY: let id = action.id; return Object.assign({}, state, { [id]: Object.assign({}, state[id], { isFetching: false, body: action.body }) }); default: return state; } </code></pre> <p>If you're happy to experiment with some ES7 syntax too, you can enable the Object spread operator with Babel and rewrite the calls to <code>Object.assign</code>.</p> <pre><code>switch (action.type) { case REQUEST_POST_BODY: let id = action.id; return { ...state, [id]: {...state[id], isFetching: true } }; case RECEIVE_POST_BODY: let id = action.id; return { ...state, [id]: { ...state[id], isFetching: false, body: action.body } }; default: return state; } </code></pre> <p>If you're not so keen on using the spread syntax, then it's still possible to make <code>Object.assign</code> a bit more palatable.</p> <pre><code>function $set(...objects) { return Object.assign({}, ...objects); } case RECEIVE_POST_BODY: let id = action.id; return $set(state, { [id]: $set(state[id], { isFetching: false, body: action.body }) }); </code></pre>
19,944,334
Extract rows for the first occurrence of a variable in a data frame
<p>I have a data frame with two variables, Date and Taxa and want to get the date for the first time each taxa occurs. There are 9 different dates and 40 different taxa in the data frame consisting of 172 rows, but my answer should only have 40 rows. </p> <p>Taxa is a factor and Date is a date.</p> <p>For example, my data frame (called 'species') is set up like this:</p> <pre><code>Date Taxa 2013-07-12 A 2011-08-31 B 2012-09-06 C 2012-05-17 A 2013-07-12 C 2012-09-07 B </code></pre> <p>and I would be looking for an answer like this:</p> <pre><code>Date Taxa 2012-05-17 A 2011-08-31 B 2012-09-06 C </code></pre> <p>I tried using:</p> <pre><code>t.first &lt;- species[unique(species$Taxa),] </code></pre> <p>and it gave me the correct number of rows but there were Taxa repeated. If I just use unique(species$Taxa) it appears to give me the right answer, but then I don't know the date when it first occurred.</p> <p>Thanks for any help.</p>
19,944,458
6
0
null
2013-11-13 02:53:30.777 UTC
19
2022-04-29 10:23:44.817 UTC
null
null
null
null
2,614,883
null
1
55
r
69,065
<pre><code>t.first &lt;- species[match(unique(species$Taxa), species$Taxa),] </code></pre> <p>should give you what you're looking for. <code>match</code> returns indices of the first match in the compared vectors, which give you the rows you need.</p>
5,814,627
the value of type "..." cannot be added to a collection or dictionary of type 'uielementcollection'
<p>I am gettig following error when i am adding a custom control thru XAML. what can be the possible reason? <strong>the value of type "..." cannot be added to a collection or dictionary of type 'uielementcollection'</strong></p> <pre><code>&lt;Grid x:Name="QuantityDetail" DataContext="{StaticResource ViewModel}"&gt; &lt;GroupBox&gt; ..... &lt;Label Style="{StaticResource ResourceKey=LabelValue}"&gt;Min&lt;/Label&gt; &lt;!-- The following control --&gt; &lt;NumericUpDow&gt;&lt;NumericUpDown&gt; ..... &lt;/GroupBox&gt; &lt;/Grid&gt; </code></pre>
5,820,394
3
1
null
2011-04-28 06:38:34.397 UTC
1
2022-04-29 06:22:08.947 UTC
2011-04-28 08:12:32.293 UTC
null
582,994
null
582,994
null
1
27
c#|wpf|xaml
38,236
<p>Problem was that i was not referencing to one dll(which is referenced by numericupdown control) in my solution. Actually NumericUpDown control is not my control, its present in different dll. And this control was refereing System.Windows.Controls.Input.Toolkit.dll. Now I am refereing it in my solution. And things are working</p>
1,598,411
What names for standard website user roles?
<p>What are the standard user role names that a majority of sites could all use? Below is a list of the best roles that I could think of (in order of importance), but I am hoping to find at least ten role names for a user system I am working on.</p> <pre><code>admin: Manage everything manager: Manage most aspects of the site editor: Scheduling and managing content author: Write important content contributors: Authors with limited rights moderator: Moderate user content member: Special user access subscriber: Paying Average Joe user: Average Joe </code></pre> <p>Another thing that I'm interested in, is whether or not these names translate over correctly into other languages.</p>
1,647,745
2
2
null
2009-10-21 02:18:17.02 UTC
11
2016-03-11 16:32:01.533 UTC
2016-03-11 16:30:34.51 UTC
null
209,139
null
99,923
null
1
21
user-roles
13,654
<p>To get to the aspect of content production:</p> <pre><code>editors: Doing some stuff beyond writing: scheduling and managing content contributors: Authors with limited rights </code></pre>
1,992,629
Unit testing custom model binder in ASP.NET MVC 2
<p>I've wrote custom model binder in project, that uses ASP.NET MVC 2. This model binder bind just 2 fields of model:</p> <pre><code>public class TaskFormBinder : DefaultModelBinder { protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) { if (propertyDescriptor.Name == "Type") { var value = bindingContext.ValueProvider.GetValue("Type"); var typeId = value.ConvertTo(typeof(int)); TaskType foundedType; using (var nhSession = Domain.GetSession()) { foundedType = nhSession.Get&lt;TaskType&gt;(typeId); } if (foundedType != null) { SetProperty(controllerContext, bindingContext, propertyDescriptor, foundedType); } else { AddModelBindError(bindingContext, propertyDescriptor); } return; } if (propertyDescriptor.Name == "Priority") { /* Other field binding ... */ return; } base.BindProperty(controllerContext, bindingContext, propertyDescriptor); } } </code></pre> <p>How can i test this model binder using standart VS unit testing? Spent some hours googling, find couple examples (<a href="http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx" rel="nofollow noreferrer">http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx</a>), but this examples is for MVC1, and dont work when using MVC2.</p> <p>I appreciate your help.</p>
2,310,954
2
0
null
2010-01-02 19:50:17.9 UTC
9
2010-02-24 21:24:21.29 UTC
2010-02-24 21:24:21.29 UTC
null
54,182
null
241,565
null
1
21
asp.net-mvc|unit-testing|modelbinders
5,386
<p>I've modified <a href="http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx" rel="noreferrer">Hanselman's MVC 1 example</a> to test ASP.Net MVC 2 model binders...</p> <pre><code>[Test] public void Date_Can_Be_Pulled_Via_Provided_Month_Day_Year() { // Arrange var formCollection = new NameValueCollection { { "foo.month", "2" }, { "foo.day", "12" }, { "foo.year", "1964" } }; var valueProvider = new NameValueCollectionValueProvider(formCollection, null); var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(FwpUser)); var bindingContext = new ModelBindingContext { ModelName = "foo", ValueProvider = valueProvider, ModelMetadata = modelMetadata }; DateAndTimeModelBinder b = new DateAndTimeModelBinder { Month = "month", Day = "day", Year = "year" }; ControllerContext controllerContext = new ControllerContext(); // Act DateTime result = (DateTime)b.BindModel(controllerContext, bindingContext); // Assert Assert.AreEqual(DateTime.Parse("1964-02-12 12:00:00 am"), result); } </code></pre>
2,235,607
How does domain registration work?
<p>I searched on Google and Wikipedia a lot, but I could't find answers for these questions.</p> <p>1) What exactly registrar company do? They update an root DNS and set there IP of my DNS?</p> <p>2) How come the registrar can update records in the root DNS? How did they get this privilege? How could I get this privilege too?</p> <p>3) What exactly do we pay the registrar for? Just for sending one request to the root DNS?</p> <p>4) When I register a domain, am I the real (in the eye of the law) owner of the domain? How do companies (e.g. Google) protect their domain? Couldn't their registrar just say: <em>"sorry we sold the domain to someone else"</em>?</p> <p>I hope it's not kind of an offtopic question.</p> <p>Thanks in advance</p>
2,235,774
2
4
null
2010-02-10 09:18:54.97 UTC
8
2021-02-09 19:25:46.943 UTC
2017-03-16 11:34:11.65 UTC
null
1,818,089
null
190,438
null
1
53
dns|registration|registrar
13,330
<p>Registrars job is primarily to coordinate and make sure there are no duplicates in domain names. <a href="http://www.icann.org/" rel="nofollow noreferrer">ICANN</a> manages them. At a technical level registrars (and <a href="https://en.wikipedia.org/wiki/Domain_name_registry" rel="nofollow noreferrer">registries</a>) use the <a href="http://en.wikipedia.org/wiki/Extensible_Provisioning_Protocol" rel="nofollow noreferrer">Extensible Provisioning Protocol</a> to achieve this.</p> <p>They do update the DNS with nameserver information but not the <a href="http://www.root-servers.org/" rel="nofollow noreferrer">Root DNS servers</a> (which is an entirely different area) only the <a href="http://en.wikipedia.org/wiki/Top-level_domain" rel="nofollow noreferrer">TLD (Top Level Domain) servers</a>.</p> <p>Legally (I am not sure about this, so take it with a pinch of salt) you have a contractual relationship with your registrar and registry, and from there you can take it to courts and so on. They are governed by the country they reside. Registries also have pretty comprehensive dispute policies in case of disagreements of the ownership for example. However, starting with <a href="http://www.icann.org/" rel="nofollow noreferrer">ICANN</a>, all these organisations (another example is <a href="http://www.nominet.org.uk/" rel="nofollow noreferrer">Nominet</a> in the UK) have massively policy based working style, and they update them according to the feedback mainly from their members and customers (us).</p>
32,591,301
Babel error: JSX value should be either an expression or a quoted JSX text
<p>I'm getting an error from Babel when trying to compile my JSX code into JS. I'm new to react so apologies if this is an obvious issue, I wasn't able to find anything about it that seemed related. I'm attempting to use props in this chunk of code, and pass a pageTitle prop to my FieldContainer component. This is giving me an issue, though, that isn't letting the code compile to JS. I discovered in my searching that prop values should be passed between <code>{}</code>, but adding these did not help. Any ideas? Thanks!</p> <p><a href="https://i.stack.imgur.com/WkQhj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WkQhj.png" alt="Babel Error"></a></p>
32,591,444
3
2
null
2015-09-15 16:38:50.907 UTC
2
2021-07-04 09:08:14.057 UTC
2016-01-31 02:02:54.027 UTC
null
1,434,116
null
2,085,743
null
1
24
babeljs|reactjs
51,126
<p>It's hard to tell what you are trying to do here, but as the error says, the value of an attribute must be an expression <code>{foo}</code> or quoted text <code>"foo"</code>.</p> <p>In this case</p> <pre><code>Child={&lt;LoginForm /&gt;} </code></pre> <p>or</p> <pre><code>Child={LoginForm} </code></pre> <p>is probably what you want.</p>
5,698,477
Can an Interface contain a variable?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2115114/why-cant-c-interfaces-contain-fields">Why can&#39;t C# interfaces contain fields?</a> </p> </blockquote> <p>Hi all,</p> <p><a href="https://stackoverflow.com/questions/5691899/properties-or-variables-in-c/5691915#5691915">Jon Skeet has answered to a question that Using a property is backed by a variable.</a></p> <p>But properties in Interfaces are allowed in C#. Does that mean the interfaces in C# can contain a variable and how would the variable backed by the property will be handled? </p> <p>Thanks in advance. </p>
5,698,494
5
1
null
2011-04-18 04:19:37.387 UTC
9
2011-04-18 04:46:05.02 UTC
2017-05-23 12:02:23.357 UTC
null
-1
null
272,010
null
1
40
c#|.net|oop|interface|properties
100,985
<p>No. An interface cannot contain a field.</p> <p>An interface can declare a Property, but it doesn't provide any implementation of it, so there's no backing field. It's only when a class implements an interface that a backing field (or automatic property) is needed.</p>
6,182,488
Median of 5 sorted arrays
<p>I am trying to find the solution for median of 5 sorted arrays. This was an interview questions. </p> <p>The solution I could think of was merge the 5 arrays and then find the median [O(l+m+n+o+p)]. </p> <p>I know that for 2 sorted arrays of same size we can do it in log(2n). [by comparing the median of both arrays and then throwing out 1 half of each array and repeating the process]. .. Finding median can be constant time in sorted arrays .. so I think this is not log(n) ? .. what is the time complexity for this ?</p> <p>1] Is there a similar solution for 5 arrays . What if the arrays are of same size , is there a better solution then ? </p> <p>2] I assume since this was asked for 5, there would be some solution for N sorted arrays ?</p> <p>Thanks for any pointers. </p> <p>Some clarification/questions I asked back to the interviewer:<br> Are the arrays of same length<br> => No<br> I guess there would be an overlap in the values of arrays<br> => Yes</p> <p>As an exercise, I think the logic for 2 arrays doesnt extend . Here is a try:<br> Applying the above logic of 2 arrays to say 3 arrays: [3,7,9] [4,8,15] [2,3,9] ... medians 7,8,3<br> throw elements [3,7,9] [4,8] [3,9] .. medians 7,6,6<br> throw elements [3,7] [8] [9] ..medians 5,8,9 ...<br> throw elements [7] [8] [9] .. median = 8 ... This doesnt seem to be correct ?</p> <p>The merge of sorted elements => [2,3,4,7,8,9,15] => expected median = 7</p>
6,182,636
5
3
null
2011-05-31 02:41:12.107 UTC
37
2021-10-30 04:29:42.383 UTC
2011-05-31 04:20:59.53 UTC
null
250,304
null
250,304
null
1
45
arrays|algorithm|logic
20,089
<p>(This is a generalization of your idea for two arrays.)</p> <p>If you start by looking at the five medians of the five arrays, obviously the overall median must be between the smallest and the largest of the five medians.</p> <p>Proof goes something like this: If a is the min of the medians, and b is the max of the medians, then each array has less than half of its elements less than a and less than half of its elements greater than b. Result follows.</p> <p>So in the array containing a, throw away numbers less than a; in the array containing b, throw away numbers greater than b... But only throw away the same number of elements from both arrays.</p> <p>That is, if a is j elements from the start of its array, and b is k elements from the end of its array, you throw away the first min(j,k) elements from a's array and the last min(j,k) elements from b's array.</p> <p>Iterate until you are down to 1 or 2 elements total.</p> <p>Each of these operations (i.e., finding median of a sorted array and throwing away k elements from the start or end of an array) is constant time. So each iteration is constant time.</p> <p>Each iteration throws away (more than) half the elements from at least one array, and you can only do that log(n) times for each of the five arrays... So the overall algorithm is log(n).</p> <p>[Update]</p> <p>As Himadri Choudhury points out in the comments, my solution is incomplete; there are a lot of details and corner cases to worry about. So, to flesh things out a bit...</p> <p>For each of the five arrays R, define its "lower median" as R[n/2-1] and its "upper median" as R[n/2], where n is the number of elements in the array (and arrays are indexed from 0, and division by 2 rounds down).</p> <p>Let "a" be the smallest of the lower medians, and "b" be the largest of the upper medians. If there are multiple arrays with the smallest lower median and/or multiple arrays with the largest upper median, choose a and b from different arrays (this is one of those corner cases).</p> <p>Now, borrowing Himadri's suggestion: Erase all elements up to <em>and including</em> a from its array, and all elements down to <em>and including</em> b from its array, taking care to remove the same number of elements from both arrays. Note that a and b could be in the same array; but if so, they could not have the same value, because otherwise we would have been able to choose one of them from a different array. So it is OK if this step winds up throwing away elements from the start and end of the same array.</p> <p>Iterate as long as you have three or more arrays. But once you are down to just one or two arrays, you have to change your strategy to be exclusive instead of inclusive; you only erase up to <em>but not including</em> a and down to <em>but not including</em> b. Continue like this as long as both of the remaining one or two arrays has at least three elements (guaranteeing you make progress).</p> <p>Finally, you will reduce to a few cases, the trickiest of which is two arrays remaining, one of which has one or two elements. Now, if I asked you: "Given a sorted array plus one or two additional elements, find the median of all elements", I think you can do that in constant time. (Again, there are a bunch of details to hammer out, but the basic idea is that adding one or two elements to an array does not "push the median around" very much.)</p>
5,902,629
mmap, msync and linux process termination
<p>I want to use mmap to implement persistence of certain portions of program state in a C program running under Linux by associating a fixed-size struct with a well known file name using mmap() with the MAP_SHARED flag set. For performance reasons, I would prefer not to call msync() at all, and no other programs will be accessing this file. When my program terminates and is restarted, it will map the same file again and do some processing on it to recover the state that it was in before the termination. My question is this: if I never call msync() on the file descriptor, will the kernel guarantee that all updates to the memory will get written to disk and be subsequently recoverable even if my process is terminated with SIGKILL? Also, will there be general system overhead from the kernel periodically writing the pages to disk even if my program never calls msync()?</p> <p><strong>EDIT:</strong> I've settled the problem of whether the data is written, but I'm still not sure about whether this will cause some unexpected system loading over trying to handle this problem with open()/write()/fsync() and taking the risk that some data might be lost if the process gets hit by KILL/SEGV/ABRT/etc. Added a 'linux-kernel' tag in hopes that some knowledgeable person might chime in.</p>
5,953,213
6
0
null
2011-05-05 18:44:07.093 UTC
17
2020-03-04 14:17:23.253 UTC
2011-05-10 16:32:32.303 UTC
null
220,826
null
220,826
null
1
32
c|linux|linux-kernel
19,349
<p>I decided to be less lazy and answer the question of whether the data is written to disk definitively by writing some code. The answer is that it will be written.</p> <p>Here is a program that kills itself abruptly after writing some data to an mmap'd file:</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;errno.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/mman.h&gt; #include &lt;sys/stat.h&gt; #include &lt;fcntl.h&gt; typedef struct { char data[100]; uint16_t count; } state_data; const char *test_data = "test"; int main(int argc, const char *argv[]) { int fd = open("test.mm", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0700); if (fd &lt; 0) { perror("Unable to open file 'test.mm'"); exit(1); } size_t data_length = sizeof(state_data); if (ftruncate(fd, data_length) &lt; 0) { perror("Unable to truncate file 'test.mm'"); exit(1); } state_data *data = (state_data *)mmap(NULL, data_length, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_POPULATE, fd, 0); if (MAP_FAILED == data) { perror("Unable to mmap file 'test.mm'"); close(fd); exit(1); } memset(data, 0, data_length); for (data-&gt;count = 0; data-&gt;count &lt; 5; ++data-&gt;count) { data-&gt;data[data-&gt;count] = test_data[data-&gt;count]; } kill(getpid(), 9); } </code></pre> <p>Here is a program that validates the resulting file after the previous program is dead:</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;errno.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/mman.h&gt; #include &lt;sys/stat.h&gt; #include &lt;fcntl.h&gt; #include &lt;assert.h&gt; typedef struct { char data[100]; uint16_t count; } state_data; const char *test_data = "test"; int main(int argc, const char *argv[]) { int fd = open("test.mm", O_RDONLY); if (fd &lt; 0) { perror("Unable to open file 'test.mm'"); exit(1); } size_t data_length = sizeof(state_data); state_data *data = (state_data *)mmap(NULL, data_length, PROT_READ, MAP_SHARED|MAP_POPULATE, fd, 0); if (MAP_FAILED == data) { perror("Unable to mmap file 'test.mm'"); close(fd); exit(1); } assert(5 == data-&gt;count); unsigned index; for (index = 0; index &lt; 4; ++index) { assert(test_data[index] == data-&gt;data[index]); } printf("Validated\n"); } </code></pre>
46,553,682
Is there a way to use GeoFire with Firestore?
<p>GeoFire is tightly coupled to the Realtime Database, while geo-queries are a common functional dependency of many apps that are looking to migrate to Firestore. Is there any way to replicate the hashing/retrieval of locations in the Firestore environment?</p>
51,258,367
6
3
null
2017-10-03 21:25:21.813 UTC
24
2020-12-17 10:11:49.063 UTC
2018-06-02 14:14:09.893 UTC
null
209,103
null
4,380,236
null
1
60
firebase|firebase-realtime-database|google-cloud-firestore|geofire
21,025
<p>GREAT NEWS. There is now a library for both iOS and Android that replicates GeoFire for Firestore. The library is called <a href="https://github.com/imperiumlabs/GeoFirestore" rel="noreferrer">GeoFirestore</a>. It has full documentation and is well tested. I currently use it in my app and it works brilliantly. The code is very similar to that of GeoFire so it should only take a few minutes to learn.</p>
5,170,256
What makes a good autowarming query in Solr and how do they work?
<p>This question is a follow up to <a href="https://stackoverflow.com/questions/5154093/solr-requests-time-out-during-index-update-perhaps-replication-a-possible-soluti">this question</a> about infrequent, isolated read timeouts in a solr installation.</p> <p>As a possible problem missing / bad autowarming queries for new searchers were found.</p> <p>Now I am confused about how good autowarming queries should "look like".</p> <p>I read up but couldnt find any good documentation on this.</p> <p>Should they hit a lot of documents in the index? Or should they have matches in all distinct fields that exist in the index?</p> <p>Wouldnt just <code>*:*</code> be the best autowarming query or why not?</p> <p>The example solr config has theese sample queries in it:</p> <pre><code>&lt;lst&gt;&lt;str name="q"&gt;solr&lt;/str&gt; &lt;str name="start"&gt;0&lt;/str&gt; &lt;str name="rows"&gt;10&lt;/str&gt;&lt;/lst&gt; &lt;lst&gt;&lt;str name="q"&gt;rocks&lt;/str&gt; &lt;str name="start"&gt;0&lt;/str&gt; &lt;str name="rows"&gt;10&lt;/str&gt;&lt;/lst&gt; </code></pre> <p>I changed them to:</p> <pre><code>&lt;lst&gt;&lt;str name="q"&gt;george&lt;/str&gt; &lt;str name="start"&gt;0&lt;/str&gt; &lt;str name="rows"&gt;10&lt;/str&gt;&lt;/lst&gt; </code></pre> <p>Why? Because the index holds film entities with fields for titles and actors. Those are the most searched ones. And george appears in titles and actors.</p> <p>I don't really know whether this makes sense. So my question is:</p> <ul> <li>What would be good autowarming queries for my index and why?</li> <li>What makes a good autowarming query? </li> </ul> <p>This is an example document from the index. The index has about 70,000 documents and they all look like this (only different values of course): example document:</p> <pre><code> &lt;doc&gt; &lt;arr name="actor"&gt;&lt;str&gt;Tommy Lee Jones&lt;/str&gt;&lt;str&gt;Will Smith&lt;/str&gt;&lt;str&gt;Rip Torn&lt;/str&gt; &lt;str&gt;Lara Flynn Boyle&lt;/str&gt;&lt;str&gt;Johnny Knoxville&lt;/str&gt;&lt;str&gt;Rosario Dawson&lt;/str&gt;&lt;str&gt;Tony Shalhoub&lt;/str&gt; &lt;str&gt;Patrick Warburton&lt;/str&gt;&lt;str&gt;Jack Kehler&lt;/str&gt;&lt;str&gt;David Cross&lt;/str&gt;&lt;str&gt;Colombe Jacobsen-Derstine&lt;/str&gt; &lt;str&gt;Peter Spellos&lt;/str&gt;&lt;str&gt;Michael Rivkin&lt;/str&gt;&lt;str&gt;Michael Bailey Smith&lt;/str&gt;&lt;str&gt;Lenny Venito&lt;/str&gt; &lt;str&gt;Howard Spiegel&lt;/str&gt;&lt;str&gt;Alpheus Merchant&lt;/str&gt;&lt;str&gt;Jay Johnston&lt;/str&gt;&lt;str&gt;Joel McKinnon Miller&lt;/str&gt; &lt;str&gt;Derek Cecil&lt;/str&gt;&lt;/arr&gt; &lt;arr name="affiliate"&gt;&lt;str&gt;amazon&lt;/str&gt;&lt;/arr&gt; &lt;arr name="aka_title"&gt;&lt;str&gt;Men in Black II&lt;/str&gt;&lt;str&gt;MIB 2&lt;/str&gt;&lt;str&gt;MIIB&lt;/str&gt; &lt;str&gt;Men in Black 2&lt;/str&gt;&lt;str&gt;Men in black II (Hombres de negro II)&lt;/str&gt;&lt;str&gt;Hombres de negro II&lt;/str&gt;&lt;str&gt;Hommes en noir II&lt;/str&gt;&lt;/arr&gt; &lt;bool name="blockbuster"&gt;false&lt;/bool&gt; &lt;arr name="country"&gt;&lt;str&gt;US&lt;/str&gt;&lt;/arr&gt; &lt;str name="description"&gt;Agent J (Will Smith) muss die Erde wieder vor einigem Abschaum bewahren, denn in Gestalt des verführerischen Dessous-Models Serleena (Lara Flynn Boyle) will ein Alien den Planeten unterjochen. Dabei benötigt J die Hilfe seines alten Partners Agent K (Tommy Lee Jones). Der wurde aber bei seiner "Entlassung" geblitzdingst, und so muß J seine Erinnerung erst mal etwas auffrischen bevor es auf die Jagd gehen kann.&lt;/str&gt; &lt;arr name="director"&gt;&lt;str&gt;Barry Sonnenfeld&lt;/str&gt;&lt;/arr&gt; &lt;int name="film_id"&gt;120912&lt;/int&gt; &lt;arr name="genre"&gt;&lt;str&gt;Action&lt;/str&gt;&lt;str&gt;Komödie&lt;/str&gt;&lt;str&gt;Science Fiction&lt;/str&gt;&lt;/arr&gt; &lt;str name="id"&gt;120912&lt;/str&gt; &lt;str name="image_url"&gt;/media/search/filmcovers/105x/kf/false/F6Q1XW.jpg&lt;/str&gt; &lt;int name="imdb_id"&gt;120912&lt;/int&gt; &lt;date name="last_modified"&gt;2011-03-01T18:51:35.903Z&lt;/date&gt; &lt;str name="locale_title"&gt;Men in Black II&lt;/str&gt; &lt;int name="malus"&gt;3238&lt;/int&gt; &lt;int name="parent_id"&gt;0&lt;/int&gt; &lt;arr name="product_dvd"&gt;&lt;str&gt;amazon&lt;/str&gt;&lt;/arr&gt; &lt;arr name="product_type"&gt;&lt;str&gt;dvd&lt;/str&gt;&lt;/arr&gt; &lt;int name="rating"&gt;49&lt;/int&gt; &lt;str name="sort_title"&gt;meninblack&lt;/str&gt; &lt;int name="type"&gt;1&lt;/int&gt; &lt;str name="url"&gt;/film/Men-in-Black-II-Barry-Sonnenfeld-Tommy-Lee-Jones-F6Q1XW/&lt;/str&gt; &lt;int name="year"&gt;2002&lt;/int&gt; &lt;/doc&gt; </code></pre> <p>Most queries are exact match queries on actor fields with some filters in place.</p> <p>Example:</p> <blockquote> <p>INFO: [] webapp=/solr path=/select/ params={facet=true&amp;sort=score+asc,+malus+asc,+year+desc&amp;hl.simple.pre=<strong>starthl</strong>&amp;hl=true&amp;version=2.2&amp;fl=*,score&amp;facet.query=year:[1900+TO+1950]&amp;facet.query=year:[1951+TO+1980]&amp;facet.query=year:[1981+TO+1990]&amp;facet.query=year:[1991+TO+2000]&amp;facet.query=year:[2001+TO+2011]&amp;bf=div(sub(10000,malus),100)^10&amp;hl.simple.post=<strong>endhl</strong>&amp;facet.field=genre&amp;facet.field=country&amp;facet.field=blockbuster&amp;facet.field=affiliate&amp;facet.field=product_type&amp;qs=5&amp;qt=dismax&amp;hl.fragsize=200&amp;mm=2&amp;facet.mincount=1&amp;qf=actor^0.1&amp;f.blockbuster.facet.mincount=0&amp;f.genre.facet.limit=20&amp;hl.fl=actor&amp;wt=json&amp;f.affiliate.facet.mincount=1&amp;f.country.facet.limit=20&amp;rows=10&amp;pf=actor^5&amp;start=0&amp;q="Josi+Kleinpeter"&amp;ps=3} hits=1 status=0 QTime=4</p> </blockquote>
5,171,367
1
0
null
2011-03-02 16:15:06.887 UTC
9
2016-02-13 10:51:44.633 UTC
2017-05-23 12:33:44.917 UTC
null
-1
null
413,910
null
1
17
caching|search|lucene|solr
9,000
<p>There are 2 types of warming. Query cache warming and document cache warming (There's also filters, but those are similar to queries). Query cache warming can be done through a setting which will just re-run X number of recent queries before the index was reloaded. Document cache warming is different.</p> <p>The goal of document cache warming is to get a large quantity of your most frequently accessed documents into the document caches so they don't have to be read from disk. So, your queries should focus on this. You need to try and figure out what your most frequently searched documents are and load those. Preferably with a minimal number of queries. This has nothing to do with the actual content of the fields. EDIT: To clarify. When warming document caches your primary interest is the documents that turn up in search RESULTS most often, regardless of how they are queried.</p> <p>Personally, I'd run searches for things like:</p> <ul> <li>Loading by country, if most of your searches are for US films.</li> <li>Loading by year, if most of your searches are for more recent films.</li> <li>Loading by genre, if you have a short list of heavily searched genres.</li> </ul> <p>A last possibility is to load them all. Your documents look small. 70,000 of them is nothing in terms of server memory nowadays. If your document cache is large enough, and you have enough memory available, go for it. As a side note, some of your biggest benefit will be from your document cache. A query cache is only beneficial for repeated queries, which can be disappointingly low. You almost always benefit from a large document cache.</p>
5,501,118
Python - ElementTree- cannot use absolute path on element
<p>I'm getting this error in ElementTree when I try to run the code below:</p> <pre><code>SyntaxError: cannot use absolute path on element </code></pre> <p>My XML document looks like this:</p> <pre><code>&lt;Scripts&gt; &lt;Script&gt; &lt;StepList&gt; &lt;Step&gt; &lt;StepText&gt; &lt;/StepText&gt; &lt;StepText&gt; &lt;/StepText&gt; &lt;/Step&gt; &lt;/StepList&gt; &lt;/Script&gt; &lt;/Scripts&gt; </code></pre> <p>Code:</p> <pre><code>import xml.etree.ElementTree as ET def search(): root = ET.parse(INPUT_FILE_PATH) for target in root.findall("//Script"): print target.attrib['name'] print target.findall("//StepText") </code></pre> <p>I'm on Python 2.6 on Mac. Am I using Xpath syntax wrong?</p> <p>Basically I want to show every Script elements name attribute if it contains a StepText element with certain text.</p>
5,501,441
1
0
null
2011-03-31 14:02:43.453 UTC
7
2018-12-19 15:54:38.9 UTC
2017-02-23 23:22:27.367 UTC
user357812
442,945
null
13,009
null
1
38
python|xpath|elementtree
31,271
<p>Turns out I needed to say <code>target.findall(".//StepText")</code>. I guess anything without the '.' is considered an absolute path?</p> <p>Updated working code:</p> <pre><code>def search(): root = ET.parse(INPUT_FILE_PATH) for target in root.findall("//Script"): stepTexts = target.findall(".//StepText") for stepText in stepTexts: if FIND.lower() in stepText.text.lower(): print target.attrib['name'],' -- ',stepText.text </code></pre>
21,440,295
Uncaught ReferenceError: angular is not defined - AngularJS not working
<p>I'm attempting to learn angular and I am struggling with a simple button click.<br> I followed an example which has an identical code to the one below.</p> <p>The result I am looking for is for the button click to cause an alert. However, there is no response to the button click. Does anybody have any ideas? </p> <pre><code>&lt;html lang="en" ng-app="myApp" &gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;My AngularJS App&lt;/title&gt; &lt;link rel="stylesheet" href="css/app.css"/&gt; &lt;/head&gt; &lt;body&gt; &lt;div &gt; &lt;button my-directive&gt;Click Me!&lt;/button&gt; &lt;/div&gt; &lt;script&gt; var app = angular.module('myApp',[]); app.directive('myDirective',function(){ return function(scope, element,attrs) { element.bind('click',function() {alert('click')}); }; }); &lt;/script&gt; &lt;h1&gt;{{2+3}}&lt;/h1&gt; &lt;!-- In production use: &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"&gt;&lt;/script&gt; --&gt; &lt;script src="lib/angular/angular.js"&gt;&lt;/script&gt; &lt;script src="lib/angular/angular-route.js"&gt;&lt;/script&gt; &lt;script src="js/app.js"&gt;&lt;/script&gt; &lt;script src="js/services.js"&gt;&lt;/script&gt; &lt;script src="js/controllers.js"&gt;&lt;/script&gt; &lt;script src="js/filters.js"&gt;&lt;/script&gt; &lt;script src="js/directives.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
21,440,353
5
2
null
2014-01-29 19:06:42.96 UTC
9
2019-06-10 10:44:02.043 UTC
2018-02-26 01:02:46.127 UTC
null
2,427,596
null
1,544,223
null
1
52
javascript|angularjs|button|angularjs-directive
220,702
<p>You need to move your angular app code below the inclusion of the angular libraries. At the time your angular code runs, <code>angular</code> does not exist yet. This is an error (see your dev tools console).</p> <p>In this line:</p> <pre><code>var app = angular.module(` </code></pre> <p>you are attempting to access a variable called <code>angular</code>. Consider what causes that variable to exist. That is found in the angular.js script which must then be included first.</p> <pre><code> &lt;h1&gt;{{2+3}}&lt;/h1&gt; &lt;!-- In production use: &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"&gt;&lt;/script&gt; --&gt; &lt;script src="lib/angular/angular.js"&gt;&lt;/script&gt; &lt;script src="lib/angular/angular-route.js"&gt;&lt;/script&gt; &lt;script src="js/app.js"&gt;&lt;/script&gt; &lt;script src="js/services.js"&gt;&lt;/script&gt; &lt;script src="js/controllers.js"&gt;&lt;/script&gt; &lt;script src="js/filters.js"&gt;&lt;/script&gt; &lt;script src="js/directives.js"&gt;&lt;/script&gt; &lt;script&gt; var app = angular.module('myApp',[]); app.directive('myDirective',function(){ return function(scope, element,attrs) { element.bind('click',function() {alert('click')}); }; }); &lt;/script&gt; </code></pre> <p>For completeness, it is true that your directive is similar to the already existing directive <code>ng-click</code>, but I believe the point of this exercise is just to practice writing simple directives, so that makes sense.</p>
42,156,282
How to cluster Node.js app in multiple machines
<p>I am using <a href="http://expressjs.com/" rel="noreferrer">Express js</a> and <a href="https://nodejs.org/api/cluster.html" rel="noreferrer">Node-cluster</a> for taking the advantage of clustering I am also using <a href="https://github.com/Unitech/PM2/" rel="noreferrer">PM2</a> for process and memory management. For a single machine, it is working fine, but my machine having 2 cores and I want to make available more cores. So I decided to join 3 more machines and now all 4 machines are connected using LAN. I am able to access the other machines using IP address in web browser also. </p> <p>Now I want to connect all the machines and want to share their cores so that I will finally have 2 + 6 = 8 cores for my application. How can it possible? Is there any node module available to achieve this? Thanks.</p>
42,156,585
2
1
null
2017-02-10 09:53:20.77 UTC
13
2019-08-20 06:26:23.37 UTC
2019-08-20 06:26:23.37 UTC
null
5,369,031
null
5,369,031
null
1
16
node.js|express|cluster-computing
12,753
<p>Node-cluster is good for taking advantage of multi core processors, but when it comes to horizontal scaling(adding more machines), you'll need to use load balancers or reverse proxy. For reverse proxy you can use any web server like Apache or nginx. If you want to rely on node and npm, there is a module by <a href="https://www.nodejitsu.com/" rel="noreferrer">nodejitsu</a>: http-proxy. Here is an example for http proxy for 3 machines running your node app.</p> <ol> <li>create a new node project. </li> <li>Install http-proxy module.</li> </ol> <p>New version:</p> <blockquote> <p>npm install --save http-proxy</p> </blockquote> <p>If you prefer older version: </p> <blockquote> <p>npm install --save [email protected]</p> </blockquote> <ol start="3"> <li>Create a new js file (server.js or anything you like). </li> </ol> <p>For version 1.x.x (New)</p> <p>server.js</p> <pre><code>var http = require('http'), httpProxy = require('http-proxy'); var addresses = [ { host: "localhost", port: 8081 }, { host: "localhost", port: 8082 }, { host: "localhost", port: 8083 } ]; //Create a set of proxy servers var proxyServers = addresses.map(function (target) { return new httpProxy.createProxyServer({ target: target }); }); var server = http.createServer(function (req, res) { var proxy = proxyServers.shift(); proxy.web(req, res); proxyServers.push(proxy); }); server.listen(8080); </code></pre> <p>for version 0.x.x (Old)</p> <p>server.js</p> <pre><code>var proxyServer = require('http-proxy'); var servers = [ { host: "localhost", port: 8081 }, { host: "localhost", port: 8082 }, { host: "localhost", port: 8083 } ]; proxyServer.createServer(function (req, res, proxy) { var target = servers.shift(); proxy.proxyRequest(req, res, target); servers.push(target); }).listen(8080); </code></pre> <ol start="4"> <li>Now run this file.</li> <li>Request made to localhost:8080 will be routed to 8081, 8082 or 8083</li> <li>You can change the localhosts to IP addresses of your machines(and port numbers).</li> </ol> <p>Clients making request to 8080 port are unaware of existence of servers at 8081, 8082 and 8083. They make requests to 8080 as if it is the only server and get response from it.</p> <p>Now, one of the machines in your cluster will work as node balancer and application is hosted on other three machines. IP address of load balancer can be used as public IP.</p>
9,562,124
PHP MySQL set Connection Timeout
<p>There are certain posts on MySQL connection set time out from PHP using mysql.connect_timeout. I want to know if this set timeout from PHP just time out the initial connection to MySQL or valid for a particular query to database?</p> <p>My case here is that, I have a page with connection to MySQL on top and then I am executing say 3-4 queries to MySQL one after the another. 1st and 2nd query taken only 1-2 seconds to execute where as 3rd query takes 20 seconds. Now, in cases when 3rd query is taking more than 20 seconds, I want to call time out. So, the question here is that, setting this time out from PHP is applicable to initial connection to database or it is applicable to every subsequent query as well (independently). If later is the case, then how I can set it to timeout after 20 seconds for 3rd query?</p>
9,618,004
6
0
null
2012-03-05 05:41:26.157 UTC
2
2016-03-10 07:46:48.167 UTC
null
null
null
null
547,563
null
1
11
php|mysql|connection-timeout
81,469
<p>The connect_timeout parameter is only valid at connection time. It's useful to check if your DB server is reachable in 20 seconds or so. Once connected the specified timeout is no longer valid.</p> <p>I don't find any query timeout parameter on official mysql manual page: <a href="http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html</a> so I don't think this is possibile.</p>
52,268,320
Module parse failed: Unexpected token
<p>Hey Getting the error below I run the webpack command: $> webpack --mode "development"</p> <p><strong>stack trace:</strong></p> <pre><code>Version: webpack 4.17.2 Time: 1357ms Built at: 09/10/2018 8:13:26 PM Asset Size Chunks Chunk Names bundle.js 1.37 MiB main [emitted] main Entrypoint main = bundle.js [0] fs (ignored) 15 bytes {main} [built] [./node_modules/css-loader/index.js!./wwwroot/Source/Styles/app.css] ./node_modules/css-loader!./wwwroot/Source/Styles/app.css 165 bytes {main} [built] [./node_modules/css-loader/index.js!./wwwroot/Source/Styles/site.css] ./node_modules/css-loader!./wwwroot/Source/Styles/site.css 207 bytes {main} [built] [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 509 bytes {main} [built] [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 519 bytes {main} [built] [./wwwroot/Source/Script/app.ts] 221 bytes {main} [built] [./wwwroot/Source/Script/site.ts] 274 bytes {main} [built] [failed] [1 error] [./wwwroot/Source/Styles/app.css] 1.06 KiB {main} [built] [./wwwroot/Source/Styles/site.css] 1.07 KiB {main} [built] + 30 hidden modules ERROR in ./wwwroot/Source/Script/site.ts 25:8 Module parse failed: Unexpected token (25:8) You may need an appropriate loader to handle this file type. | | class Animal { &gt; name: string; | constructor(theName: string) { this.name = theName; } | move(distanceInMeters: number = 0) { @ ./wwwroot/Source/Script/app.ts 4:0-16 </code></pre> <p>It seems it does not recognize the properties in any of my classes when transpiling. </p> <p>** ts code **</p> <pre><code>class Animal { name: string; constructor(theName: string) { this.name = theName; } move(distanceInMeters: number = 0) { console.log(`${this.name} moved ${distanceInMeters}m.`); } } </code></pre> <p><strong>tsconfig</strong></p> <pre><code>{ "compilerOptions": { "outDir": "./app/", "noImplicitAny": true, "module": "es6", "target": "es5", "allowJs": true, "sourceMap": true } } </code></pre> <p><strong>package.json</strong></p> <pre><code> { "name": "ExposureAPI", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" &amp;&amp; exit 1", "wbp": "webpack" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.0.0", "@babel/preset-env": "^7.0.0", "@types/jquery": "^3.3.6", "@types/underscore": "^1.8.9", "babel-loader": "^8.0.2", "bootstrap": "^4.1.3", "css-loader": "^1.0.0", "gulp-babel": "^8.0.0", "jquery": "^3.3.1", "popper.js": "^1.14.4", "style-loader": "^0.22.1", "ts-loader": "^4.5.0", "typescript": "^3.0.1", "underscore": "^1.9.1", "webpack": "^4.17.2", "webpack-cli": "^3.1.0" }, "dependencies": { "@types/simplemde": "^1.11.7", "simplemde": "^1.11.2" } } </code></pre> <p><strong>webpack.config.js</strong></p> <pre><code> const path = require('path'); module.exports = { entry: './wwwroot/Source/Script/app.ts', module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, devtool: 'inline-source-map' } ] }, resolve: { extensions: [ '.tsx', '.ts', '.js' ] }, output: { path: path.resolve(__dirname, 'wwwroot/App'), filename: 'bundle.js' }, module: { rules: [ { test: /\.css$/, exclude: ['node_modules'], use: [ { loader: "style-loader" }, { loader: "css-loader" } ] }] } }; </code></pre> <p>Thanks</p>
52,303,131
1
2
null
2018-09-11 03:39:08.59 UTC
1
2018-09-12 20:38:01.15 UTC
2018-09-11 07:12:08.717 UTC
null
3,145,690
null
108,894
null
1
10
javascript|typescript|webpack
55,032
<p>Apparently it happened because you have two <code>module</code> properties in the webpack config object.</p> <p>Given JS objects can only hold one value per key - one value would be lost. And in this particular case the latter was overwriting the former, so webpack ended up configured without typescript loader config at all.</p>
31,180,816
MVC design pattern, service layer purpose?
<p>Let's say I have a following repo pattern :</p> <pre><code>interface IGenericRepo&lt;T&gt; where T : class { IEnumerable&lt;T&gt; GetAll(); T GetById(object id); void Insert(T obj); void Update(T obj); void Delete(T obj); void Save(); } interface ICustRepo : IGenericRepo&lt;Cust&gt; { IEnumerable&lt;Cust&gt; GetBadCust(); IEnumerable&lt;Cust&gt; GetGoodCust(); } public class CustRepo : ICustRepo&lt;Cust&gt; { //implement method here } </code></pre> <p>then in my controller :</p> <pre><code>public class CustController { private ICustRepo _custRepo; public CustController(ICustRepo custRepo) { _custRepo = custRepo; } public ActionResult Index() { var model = _custRepo.GetAll(); return View(model); } public ActionResult BadCust() { var model = _custRepo.GetBadCust(); return View(model); } } </code></pre> <p>Basically my pattern is something like</p> <p><code>View &lt;-&gt; Controller -&gt; Repo -&gt; EF -&gt; SQL Server</code></p> <p>but I saw a lot of people doing this</p> <p><code>View &lt;-&gt; Controller -&gt; Service -&gt; Repo -&gt; EF -&gt; SQL Server</code></p> <p>So my question is :</p> <ol> <li><p>Why and when do I need <code>service layer</code>? Isn't that just add another unnecessary layer because every non-generic method is already implemented in <code>ICustRepo</code>?</p></li> <li><p>Should the service layer return <code>DTO</code> or my <code>ViewModel</code>?</p></li> <li><p>Should the service layer map 1:1 with my repo?</p></li> </ol> <p>I've look around for few days but I haven't satisfied with the answers.</p> <p>Any help will be appreciated and apologize for bad english.</p> <p>Thank you.</p> <p>UPDATE :</p> <p><a href="https://stackoverflow.com/questions/5049363/difference-between-repository-and-service-layer">Difference between Repository and Service Layer?</a></p> <p>I've already read this. I already know the difference between those 2, but I wanna know why and the purpose. So that doesn't answer my question</p>
31,182,368
2
2
null
2015-07-02 09:30:53.907 UTC
13
2020-07-10 03:14:14.3 UTC
2017-05-23 12:32:05.06 UTC
null
-1
null
3,226,114
null
1
27
c#|asp.net-mvc|entity-framework|design-patterns|repository
27,719
<p><strong>TL;DR</strong></p> <ol> <li>See explanation below</li> <li>Layers above Service Layer should not be &quot;aware&quot; that more Layers exist below the Service Layer.</li> <li>Not necessarily, because you can have for example Data from 1 Type scattered across 2 tables and the &quot;Core&quot; only see's one, the Data Access Layer is responsible for &quot;Grouping&quot; and returning the Service Layer Type</li> </ol> <p><strong>Explanation</strong></p> <p>The typical 3-layer architecture is composed of Presentation Layer, Service/Domain Layer, Data Access Layer (DAL).</p> <p>Think of the Service layer as the &quot;Core&quot; of your Application. Typically, the Service Layer only has Repository Interfaces that will be implemented in the DAL.</p> <p>Therefore it allows you to &quot;easily&quot; switch the way you access data. The objects returned by the service layer should not be DAO's, because after all, the Presentation Layer doesn't even &quot;know&quot; the DAL exists.</p> <p>Scenario: You have a 3-tiered Solution. Currently doesn't make much sense in having all layers.</p> <pre><code> /-------------------\ | Web App | &lt;--- Presentation Layer |-------------------| | Service Library | &lt;--- Service Layer |-------------------| | Entity Framework | &lt;--- Data Access \-------------------/ </code></pre> <p>Now you want to have a REST API in ASP.NET MVC WebApi</p> <pre><code> /--------------------\ | Web App | REST API | &lt;--- Presentation Layer |--------------------| | Service Library | &lt;--- Service Layer |--------------------| | Entity Framework | &lt;--- Data Access \--------------------/ </code></pre> <p>Now, for example, you no longer want to use Entity Framework as your Data Access and want to use NHibernate.</p> <pre><code> /--------------------\ | Web App | REST API | &lt;--- Presentation Layer |--------------------| | Service Library | &lt;--- Service Layer |--------------------| | NHibernate | &lt;--- Data Access \--------------------/ </code></pre> <p>Notice that we added a new form of Presentation and switched the way we access Data, but the Service Layer never changed.</p> <p>Typically, the Service Layer exposes Interfaces to be implemented in the Data Access Layer so we get the &quot;abstraction&quot; we want.</p> <p>I implemented a project with this architecture in university. You can check out the code <a href="https://github.com/driverpt/PI-1112SV/tree/master/MVC3" rel="nofollow noreferrer">HERE</a></p> <p>I hope this helped. Sorry if I'm so boring @ explaining things :P</p>
10,744,645
Detect touchpad vs mouse in Javascript
<p>Is there any way to detect if the client is using a touchpad vs. a mouse with Javascript?</p> <p>Or at least to get some reasonable estimate of the number of users that use touchpads as opposed to mice?</p>
10,748,581
8
1
null
2012-05-24 20:14:25.42 UTC
15
2022-09-02 14:47:21.033 UTC
null
null
null
null
121,112
null
1
32
javascript|mouse|touchpad|trackpad
38,557
<p>In the general case, there is no way to do what you want. ActiveX <em>might</em> allow you to see and examine USB devices, but in the best case, even if that is somehow possible, that limits you to IE users. Beyond that, there is no way to know. </p> <p>You might be able to discern patterns in how (or how often) a touchpad user moves the cursor versus how a mouse user might move the cursor. Differentiating between physical input devices in this way is an absurdly difficult prospect, and may be wholly impossible, so I include here it for completeness only.</p>
31,381,762
swift ios 8 change font title of section in a tableview
<p>I would like to change the font type and font size of a section header in a table view controller.</p> <p>My code:</p> <pre><code>func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header = view as! UITableViewHeaderFooterView header.textLabel.textColor = UIColor.blackColor() header.textLabel.font = UIFont(name: "Futura", size: 38)! } </code></pre> <p>But this doesn't work. Any ideas?</p>
42,891,875
11
4
null
2015-07-13 11:08:12.05 UTC
12
2019-12-06 21:22:38.713 UTC
2015-07-15 12:38:47.277 UTC
null
2,572,285
null
5,068,746
null
1
35
ios|swift|uitableview|fonts
48,608
<p><strong>Swift 3</strong></p> <pre><code> override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -&gt; UIView? { let headerView = UIView() headerView.backgroundColor = UIColor.lightGray let headerLabel = UILabel(frame: CGRect(x: 30, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height)) headerLabel.font = UIFont(name: "Verdana", size: 20) headerLabel.textColor = UIColor.white headerLabel.text = self.tableView(self.tableView, titleForHeaderInSection: section) headerLabel.sizeToFit() headerView.addSubview(headerLabel) return headerView } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -&gt; CGFloat { return 40 } </code></pre>
37,636,373
How std::bind works with member functions
<p>I'm working with <code>std::bind</code> but I still don't get how it works when we use it with member class functions.</p> <p>If we have the following function:</p> <pre><code>double my_divide (double x, double y) {return x/y;} </code></pre> <p>I understand perfectly well the next lines of code:</p> <pre><code>auto fn_half = std::bind (my_divide,_1,2); // returns x/2 std::cout &lt;&lt; fn_half(10) &lt;&lt; '\n'; // 5 </code></pre> <p>But now, with the following code where we have a bind to member function I have some questions.</p> <pre><code>struct Foo { void print_sum(int n1, int n2) { std::cout &lt;&lt; n1+n2 &lt;&lt; '\n'; } int data = 10; }; Foo foo; auto f = std::bind(&amp;Foo::print_sum, &amp;foo, 95, _1); f(5); </code></pre> <ul> <li><p>Why is the first argument a reference? I'd like to get a theoretical explanation.</p></li> <li><p>The second argument is a reference to the object and it's for me the most complicated part to understand. I think it's because <code>std::bind</code> needs a context, am I right? Is always like this? Has <code>std::bind</code> some sort of implementation to require a reference when the first argument is a member function?</p></li> </ul>
37,636,624
2
2
null
2016-06-05 00:42:59.963 UTC
32
2019-08-21 15:26:58.573 UTC
2019-08-21 15:26:58.573 UTC
null
1,935,611
null
4,719,550
null
1
42
c++|c++11|std|stdbind
56,587
<p>When you say "the first argument is a reference" you surely meant to say "the first argument is a <em>pointer</em>": the <code>&amp;</code> operator takes the address of an object, yielding a pointer.</p> <p>Before answering this question, let's briefly step back and look at your first use of <code>std::bind()</code> when you use</p> <pre><code>std::bind(my_divide, 2, 2) </code></pre> <p>you provide a function. When a function is passed anywhere it decays into a pointer. The above expression is equivalent to this one, explicitly taking the address</p> <pre><code>std::bind(&amp;my_divide, 2, 2) </code></pre> <p>The first argument to <code>std::bind()</code> is an object identifying how to call a function. In the above case it is a pointer to function with type <code>double(*)(double, double)</code>. Any other callable object with a suitable function call operator would do, too.</p> <p>Since member functions are quite common, <code>std::bind()</code> provides support for dealing with pointer to member functions. When you use <code>&amp;print_sum</code> you just get a pointer to a member function, i.e., an entity of type <code>void (Foo::*)(int, int)</code>. While function names implicitly decay to pointers to functions, i.e., the <code>&amp;</code> can be omitted, the same is not true for member functions (or data members, for that matter): to get a pointer to a member function it is necessary to use the <code>&amp;</code>.</p> <p>Note that a pointer to member is specific to a <code>class</code> but it can be used with any object that class. That is, it is independent of any particular object. C++ doesn't have a direct way to get a member function directly bound to an object (I think in C# you can obtain functions directly bound to an object by using an object with an applied member name; however, it is 10+ years since I last programmed a bit of C#).</p> <p>Internally, <code>std::bind()</code> detects that a pointer to a member function is passed and most likely turns it into a callable objects, e.g., by use <code>std::mem_fn()</code> with its first argument. Since a non-<code>static</code> member function needs an object, the first argument to the resolution callable object is either a reference or a [smart] pointer to an object of the appropriate class.</p> <p>To use a pointer to member function an object is needed. When using a pointer to member with <code>std::bind()</code> the second argument to <code>std::bind()</code> correspondingly needs to specify when the object is coming from. In your example</p> <pre><code>std::bind(&amp;Foo::print_sum, &amp;foo, 95, _1) </code></pre> <p>the resulting callable object uses <code>&amp;foo</code>, i.e., a pointer to <code>foo</code> (of type <code>Foo*</code>) as the object. <code>std::bind()</code> is smart enough to use anything which looks like a pointer, anything convertible to a reference of the appropriate type (like <code>std::reference_wrapper&lt;Foo&gt;</code>), or a [copy] of an object as the object when the first argument is a pointer to member.</p> <p>I suspect, you have never seen a pointer to member - otherwise it would be quite clear. Here is a simple example:</p> <pre><code>#include &lt;iostream&gt; struct Foo { int value; void f() { std::cout &lt;&lt; "f(" &lt;&lt; this-&gt;value &lt;&lt; ")\n"; } void g() { std::cout &lt;&lt; "g(" &lt;&lt; this-&gt;value &lt;&lt; ")\n"; } }; void apply(Foo* foo1, Foo* foo2, void (Foo::*fun)()) { (foo1-&gt;*fun)(); // call fun on the object foo1 (foo2-&gt;*fun)(); // call fun on the object foo2 } int main() { Foo foo1{1}; Foo foo2{2}; apply(&amp;foo1, &amp;foo2, &amp;Foo::f); apply(&amp;foo1, &amp;foo2, &amp;Foo::g); } </code></pre> <p>The function <code>apply()</code> simply gets two pointers to <code>Foo</code> objects and a pointer to a member function. It calls the member function pointed to with each of the objects. This funny <code>-&gt;*</code> operator is applying a pointer to a member to a pointer to an object. There is also a <code>.*</code> operator which applies a pointer to a member to an object (or, as they behave just like objects, a reference to an object). Since a pointer to a member function needs an object, it is necessary to use this operator which asks for an object. Internally, <code>std::bind()</code> arranges the same to happen.</p> <p>When <code>apply()</code> is called with the two pointers and <code>&amp;Foo::f</code> it behaves exactly the same as if the member <code>f()</code> would be called on the respective objects. Likewise when calling <code>apply()</code> with the two pointers and <code>&amp;Foo::g</code> it behaves exactly the same as if the member <code>g()</code> would be called on the respective objects (the semantic behavior is the same but the compiler is likely to have a much harder time inlining functions and typically fails doing so when pointers to members are involved).</p>
36,808,434
label-encoder encoding missing values
<p>I am using the label encoder to convert categorical data into numeric values.</p> <p>How does LabelEncoder handle missing values?</p> <pre><code>from sklearn.preprocessing import LabelEncoder import pandas as pd import numpy as np a = pd.DataFrame(['A','B','C',np.nan,'D','A']) le = LabelEncoder() le.fit_transform(a) </code></pre> <p>Output:</p> <pre><code>array([1, 2, 3, 0, 4, 1]) </code></pre> <p>For the above example, label encoder changed NaN values to a category. How would I know which category represents missing values?</p>
36,814,364
15
1
null
2016-04-23 08:23:02.51 UTC
12
2021-09-03 09:53:44.19 UTC
2018-02-15 15:28:55.08 UTC
null
1,797,250
null
3,391,524
null
1
34
python|pandas|scikit-learn
46,752
<p>Don't use <code>LabelEncoder</code> with missing values. I don't know which version of <code>scikit-learn</code> you're using, but in 0.17.1 your code raises <code>TypeError: unorderable types: str() &gt; float()</code>.</p> <p>As you can see <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/preprocessing/label.py#L96" rel="noreferrer">in the source</a> it uses <code>numpy.unique</code> against the data to encode, which raises <code>TypeError</code> if missing values are found. If you want to encode missing values, first change its type to a string:</p> <pre><code>a[pd.isnull(a)] = 'NaN' </code></pre>
21,227,287
Make div scrollable
<p>I have a div that I am displaying many things in that are related to laptop for filtering data. The div increases it's size as the data size increases in it.</p> <p>I want the div to remain at a max size of 450px then if data increases scroll will come automatically. The div size should not be increased.</p> <p><a href="http://jsfiddle.net/kurbhatt/7w8TC/" rel="noreferrer">jsfiddle</a> for it.</p> <p>css :</p> <pre><code>.itemconfiguration { min-height:440px; width:215px; /* background-color:#CCC; */ float:left; position:relative; margin-left:-5px; } .left_contentlist { width:215px; float:left; padding:0 0 0 5px; position:relative; float:left; border-right: 1px #f8f7f3 solid; /* background-image:url(images/bubble.png); */ /* background-color: black; */ } </code></pre> <p>Can anyone help me achieve this?</p>
21,227,352
8
2
null
2014-01-20 06:10:05.96 UTC
12
2022-06-22 14:17:35.127 UTC
2014-01-20 06:14:58.497 UTC
null
3,081,206
null
3,145,373
null
1
82
css|html
191,670
<p>Use <code>overflow-y:auto</code> for displaying scroll automatically when the content exceeds the divs set height.</p> <h2><a href="http://jsfiddle.net/7w8TC/1/">See this demo</a></h2>
20,938,095
Difference between final and effectively final
<p>I'm playing with lambdas in Java 8 and I came across warning <code>local variables referenced from a lambda expression must be final or effectively final</code>. I know that when I use variables inside anonymous class they must be final in outer class, but still - what is the difference between <em>final</em> and <em>effectively final</em>?</p>
20,938,132
14
3
null
2014-01-05 19:30:31.647 UTC
86
2021-10-02 16:48:36.503 UTC
null
null
null
null
1,185,254
null
1
380
java|lambda|inner-classes|final|java-8
194,770
<blockquote> <p>... starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. <strong>A variable or parameter whose value is never changed after it is initialized is effectively final.</strong></p> </blockquote> <p>For example, suppose that the variable <code>numberLength</code> is not declared final, and you add the marked assignment statement in the <code>PhoneNumber</code> constructor:</p> <pre><code>public class OutterClass { int numberLength; // &lt;== not *final* class PhoneNumber { PhoneNumber(String phoneNumber) { numberLength = 7; // &lt;== assignment to numberLength String currentNumber = phoneNumber.replaceAll( regularExpression, ""); if (currentNumber.length() == numberLength) formattedPhoneNumber = currentNumber; else formattedPhoneNumber = null; } ... } ... } </code></pre> <p>Because of this assignment statement, the variable numberLength is not effectively final anymore. <strong>As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final"</strong> where the inner class PhoneNumber tries to access the numberLength variable:</p> <p><a href="http://codeinventions.blogspot.in/2014/07/difference-between-final-and.html" rel="noreferrer">http://codeinventions.blogspot.in/2014/07/difference-between-final-and.html</a></p> <p><a href="http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html</a></p>
28,331,397
Cocoapods OpenCV 2.4.10 Linker Error
<p>I'm trying to build a simple project using OpenCV 2.4.10 but I get a bunch of errors like this:</p> <pre> Undefined symbols for architecture x86_64: "_jpeg_free_large", referenced from: _free_pool in opencv2(jmemmgr.o) "_jpeg_free_small", referenced from: _free_pool in opencv2(jmemmgr.o) _self_destruct in opencv2(jmemmgr.o) </pre> <p>Here is ViewController.m</p> <pre class="lang-objective-c prettyprint-override"><code>#import "ViewController.h" #import &lt;opencv2/opencv.hpp&gt; @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; cv::Mat greyMat; } </code></pre> <p>Podfile</p> <pre><code>platform :ios, '8.1' pod 'OpenCV', '2.4.10' </code></pre> <p>Project builds just fine when I use version 2.4.9.1 or 2.4.9.<br> I was also able to build this project with framework file downloaded from URL which I found in podspec 2.4.10. </p>
33,926,672
6
1
null
2015-02-04 21:03:56.7 UTC
8
2018-01-23 08:55:18.287 UTC
null
null
null
null
1,970,912
null
1
25
ios|xcode|opencv|cocoapods
6,328
<p>I've added the new versions of OpenCV to CocoaPods (2.4.11, 2.4.12, 2.4.12.3, 3.0.0).</p> <p>2.4.11, 2.4.12, and 2.4.12.3 need libjpeg to be linked, so now the pod actually downloads the repo, compiles from source, and then links libjpeg in addition to the opencv2.framework file. This works out of the box now through CocoaPods, however it takes a while when doing <code>pod install</code> since it's compiling from source. Just make sure not to cancel it while it's doing that (there's a <a href="https://github.com/CocoaPods/CocoaPods/issues/4587" rel="nofollow">bug</a> in CocoaPods that causes issues if it's canceled).</p> <p>Under the hood, 3.0.0 works just like before with the prebuilt opencv2.framework file and can now be installed just fine through CocoaPods.</p> <p>Version 2.4.10 is still broken in CocoaPods, but since that version throws errors while compiling from source on my machine, there's not much I can do.</p> <p>(Note: I am not the original maintainer of the pod, I merely contributed these new versions.)</p>
28,242,593
Correct way to obtain confidence interval with scipy
<p>I have a 1-dimensional array of data:</p> <pre><code>a = np.array([1,2,3,4,4,4,5,5,5,5,4,4,4,6,7,8]) </code></pre> <p>for which I want to obtain the 68% confidence interval (ie: the <a href="https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule" rel="noreferrer">1 sigma</a>).</p> <p>The first comment in <a href="https://stackoverflow.com/a/15034101/1391441">this answer</a> states that this can be achieved using <code>scipy.stats.norm.interval</code> from the <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.norm.html#scipy.stats.norm" rel="noreferrer">scipy.stats.norm</a> function, via:</p> <pre><code>from scipy import stats import numpy as np mean, sigma = np.mean(a), np.std(a) conf_int = stats.norm.interval(0.68, loc=mean, scale=sigma) </code></pre> <p>But a comment in <a href="http://adventuresinpython.blogspot.com.ar/2012/12/confidence-intervals-in-python.html" rel="noreferrer">this post</a> states that the <em>actual</em> correct way of obtaining the confidence interval is:</p> <pre><code>conf_int = stats.norm.interval(0.68, loc=mean, scale=sigma / np.sqrt(len(a))) </code></pre> <p>that is, sigma is divided by the square-root of the sample size: <code>np.sqrt(len(a))</code>.</p> <p>The question is: which version is the correct one?</p>
28,243,282
3
1
null
2015-01-30 18:41:56.513 UTC
28
2018-11-24 10:07:12.72 UTC
2018-11-24 10:07:12.72 UTC
null
1,457,380
null
1,391,441
null
1
50
python|numpy|scipy|confidence-interval
103,408
<p>The 68% confidence interval for <strong>a single draw</strong> from a normal distribution with mean mu and std deviation sigma is</p> <pre><code>stats.norm.interval(0.68, loc=mu, scale=sigma) </code></pre> <p>The 68% confidence interval for <strong>the mean of N draws</strong> from a normal distribution with mean mu and std deviation sigma is</p> <pre><code>stats.norm.interval(0.68, loc=mu, scale=sigma/sqrt(N)) </code></pre> <p>Intuitively, these formulas make sense, since if you hold up a jar of jelly beans and ask a large number of people to guess the number of jelly beans, each individual may be off by a lot -- the same std deviation <code>sigma</code> -- but the average of the guesses will do a remarkably fine job of estimating the actual number and this is reflected by the standard deviation of the mean shrinking by a factor of <code>1/sqrt(N)</code>.</p> <hr> <p>If a single draw has variance <code>sigma**2</code>, then by the <a href="http://en.wikipedia.org/wiki/Variance#Sum_of_uncorrelated_variables_.28Bienaym.C3.A9_formula.29" rel="noreferrer">Bienaymé formula</a>, the sum of <code>N</code> <em>uncorrelated</em> draws has variance <code>N*sigma**2</code>. </p> <p>The mean is equal to the sum divided by N. When you multiply a random variable (like the sum) by a constant, the variance is multiplied by the constant squared. That is</p> <pre><code>Var(cX) = c**2 * Var(X) </code></pre> <p>So the variance of the mean equals</p> <pre><code>(variance of the sum)/N**2 = N * sigma**2 / N**2 = sigma**2 / N </code></pre> <p>and so the standard deviation of the mean (which is the square root of the variance) equals</p> <pre><code>sigma/sqrt(N). </code></pre> <p>This is the origin of the <code>sqrt(N)</code> in the denominator.</p> <hr> <p>Here is some example code, based on Tom's code, which demonstrates the claims made above:</p> <pre><code>import numpy as np from scipy import stats N = 10000 a = np.random.normal(0, 1, N) mean, sigma = a.mean(), a.std(ddof=1) conf_int_a = stats.norm.interval(0.68, loc=mean, scale=sigma) print('{:0.2%} of the single draws are in conf_int_a' .format(((a &gt;= conf_int_a[0]) &amp; (a &lt; conf_int_a[1])).sum() / float(N))) M = 1000 b = np.random.normal(0, 1, (N, M)).mean(axis=1) conf_int_b = stats.norm.interval(0.68, loc=0, scale=1 / np.sqrt(M)) print('{:0.2%} of the means are in conf_int_b' .format(((b &gt;= conf_int_b[0]) &amp; (b &lt; conf_int_b[1])).sum() / float(N))) </code></pre> <p>prints</p> <pre><code>68.03% of the single draws are in conf_int_a 67.78% of the means are in conf_int_b </code></pre> <p>Beware that if you define <code>conf_int_b</code> with the estimates for <code>mean</code> and <code>sigma</code> based on the sample <code>a</code>, the mean may not fall in <code>conf_int_b</code> with the desired frequency.</p> <hr> <p>If you take a <em>sample</em> from a distribution and compute the sample mean and std deviation,</p> <pre><code>mean, sigma = a.mean(), a.std() </code></pre> <p>be careful to note that there is no guarantee that these will equal the <em>population</em> mean and standard deviation and that we are <em>assuming</em> the population is normally distributed -- those are not automatic givens!</p> <p>If you take a sample and want to <em>estimate</em> the population mean and standard deviation, you should use</p> <pre><code>mean, sigma = a.mean(), a.std(ddof=1) </code></pre> <p>since this value for sigma is the <a href="http://en.wikipedia.org/wiki/Bias_of_an_estimator" rel="noreferrer">unbiased estimator</a> for the population standard deviation.</p>
9,009,333
How to check if the program is run from a console?
<p>I'm writing an application which dumps some diagnostics to the standard output.</p> <p>I'd like to have the application work this way:</p> <ul> <li>If it is run from a standalone command prompt (via <code>cmd.exe</code>) or has standard output redirected/piped to a file, exit cleanly as soon as it finished,</li> <li>Otherwise (if it is run from a window and the console window is spawned automagically), then additionally wait for a keypress before exiting (to let the user read the diagnostics) before the window disappears</li> </ul> <p>How do I make that distinction? <em>I suspect that examining the parent process could be a way but I'm not really into WinAPI, hence the question.</em></p> <p>I'm on MinGW GCC.</p>
9,009,783
5
1
null
2012-01-25 19:54:20.27 UTC
17
2020-04-03 21:49:25.85 UTC
2012-01-26 05:41:00.767 UTC
null
383,402
null
399,317
null
1
30
c++|c|winapi
13,280
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms683175%28v=vs.85%29.aspx" rel="noreferrer">GetConsoleWindow</a>, <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms633522%28v=vs.85%29.aspx" rel="noreferrer">GetWindowThreadProcessId</a> and <a href="http://msdn.microsoft.com/en-us/library/ms683180%28VS.85%29.aspx" rel="noreferrer">GetCurrentProcessId</a> methods.</p> <p>1) First you must retrieve the current handle of the console window using the <code>GetConsoleWindow</code> function.</p> <p>2) Then you get the process owner of the handle of the console window.</p> <p>3) Finally you compare the returned PID against the PID of your application.</p> <p>Check this sample (VS C++)</p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; using namespace std; #if _WIN32_WINNT &lt; 0x0500 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0500 #endif #include &lt;windows.h&gt; #include "Wincon.h" int _tmain(int argc, _TCHAR* argv[]) { HWND consoleWnd = GetConsoleWindow(); DWORD dwProcessId; GetWindowThreadProcessId(consoleWnd, &amp;dwProcessId); if (GetCurrentProcessId()==dwProcessId) { cout &lt;&lt; "I have my own console, press enter to exit" &lt;&lt; endl; cin.get(); } else { cout &lt;&lt; "This Console is not mine, good bye" &lt;&lt; endl; } return 0; } </code></pre>
8,884,230
jQuery move to anchor location on page load
<p>I have a simple page setup such as:</p> <pre><code>&lt;div id="aboutUs"&gt; About us content... &lt;/div&gt; &lt;div id="header"&gt; Header content... &lt;/div&gt; </code></pre> <p>When the page loads, I need the page to automatically scroll down (no animation needed) to <code>#header</code>, so the user cannot see the About Us div unless they scroll up.</p> <p><code>#aboutUs</code> has a fixed height, so there isn't any need for any variables to determine the height or anything... if that's even needed.</p> <p>I came across <a href="https://stackoverflow.com/questions/1708842/on-load-jump-to-anchor-within-a-div">this other question</a> and tried to modify some of the answers for my situation, but nothing seemed to work.</p> <p>Any help would be appreciated.</p>
8,884,286
3
1
null
2012-01-16 17:59:13.587 UTC
18
2015-12-08 18:59:24.29 UTC
2017-05-23 12:26:24.367 UTC
null
-1
null
984,008
null
1
72
jquery|scroll|anchor
145,884
<h3>Description</h3> <p>You can do this using jQuery's <code>.scrollTop()</code> and <code>.offset()</code> method</p> <p>Check out my sample and this <a href="http://jsfiddle.net/RbxVJ/2/" rel="noreferrer">jsFiddle Demonstration</a></p> <h3>Sample</h3> <pre><code>$(function() { $(document).scrollTop( $("#header").offset().top ); }); </code></pre> <h3>More Information</h3> <ul> <li><strong><a href="http://jsfiddle.net/RbxVJ/2/" rel="noreferrer">jsFiddle Demonstration</a></strong></li> <li><a href="http://api.jquery.com/scrollTop/" rel="noreferrer">jQuery.scrollTop()</a></li> <li><a href="http://api.jquery.com/offset/" rel="noreferrer">jQuery.offset()</a></li> </ul>
27,045,887
swift: Add multiple <key, value> objects to NSDictionary
<p>I'm trying to add multiple objects to NSDictionary, like</p> <pre><code>var myDict: NSDictionary = [["fname": "abc", "lname": "def"], ["fname": "ghi", "lname": "jkl"], ...] </code></pre> <p>Is it even possible to do this? If not, please suggest a better way. I actually need to convert this NSDictionary to JSON string and send that to the server, so I need multiple objects in NSDictionary.</p>
27,045,986
3
2
null
2014-11-20 17:32:22.463 UTC
6
2017-04-05 12:01:49.83 UTC
null
null
null
null
1,926,291
null
1
27
ios|json|swift|nsdictionary|key-value
82,388
<p>You can definitely make a dictionary of dictionaries. However, you need a different syntax for that:</p> <pre><code>var myDictOfDict:NSDictionary = [ "a" : ["fname": "abc", "lname": "def"] , "b" : ["fname": "ghi", "lname": "jkl"] , ... : ... ] </code></pre> <p>What you have looks like an <em>array</em> of dictionaries, though:</p> <pre><code>var myArrayOfDict: NSArray = [ ["fname": "abc", "lname": "def"] , ["fname": "ghi", "lname": "jkl"] , ... ] </code></pre> <p>To get JSON that looks like this</p> <pre><code>{"Data": [{"User": myDict1}, {"User": myDict1},...]} </code></pre> <p>you need to add the above array to a dictionary, like this:</p> <pre><code>var myDict:NSDictionary = ["Data" : myArrayOfDict] </code></pre>
27,230,293
How to draw an inline svg (in DOM) to a canvas?
<p>Well, I need some help about convert .svg file/image to .png file/image...</p> <p>I have a .svg image displayed on my page. It is saved on my server (as a .png file). I need to convert it to a .png file on demand (on click on a button) and save the .png file on the server (I will do this with an .ajax request).</p> <p>But the problem is the conversion.</p> <p>I read many things about the html5 Canvas, which can probably help doing what I need to do now, but I can't find any clear solution to my problem, and, tbh, I do not understand everything I found... So I need some clear advices/help about the way I have to do it.</p> <p>Here is the "html idea" template : </p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;svg id="mySvg" width="300px" height="300px"&gt; &lt;!-- my svg data --&gt; &lt;/svg&gt; &lt;label id="button"&gt;Click to convert&lt;/label&gt; &lt;canvas id="myCanvas"&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and some js : </p> <pre><code>&lt;script&gt; $("body").on("click","#button",function(){ var svgText = $("#myViewer").outerHTML; var myCanvas = document.getElementById("canvas"); var ctxt = myCanvas.getContext("2d"); }); &lt;/script&gt; </code></pre> <p>Then, I need to draw the svg into the Canvas, get back the base64 data, and save it in a .png file on my server... but... how? I read about so many different solutions that I'm actually... lost... I'm working on a jsfiddle, but I'm actually... nowhere... <a href="http://jsfiddle.net/xfh7nctk/6/" rel="noreferrer">http://jsfiddle.net/xfh7nctk/6/</a> ... Thanks for reading / help</p>
27,232,525
2
3
null
2014-12-01 14:15:46.773 UTC
29
2020-06-15 00:58:25.247 UTC
2019-08-14 23:34:42.223 UTC
null
3,702,797
null
3,774,191
null
1
31
javascript|html|canvas|svg|png
65,231
<p>For inline SVG you'll need to:</p> <ul> <li>Convert the SVG string to a <code>Blob</code></li> <li>Get an URL for the Blob</li> <li>Create an image element and set the URL as <code>src</code></li> <li>When loaded (<code>onload</code>) you can draw the SVG as an image on canvas</li> <li>Use <code>toDataURL()</code> to get the PNG file from canvas.</li> </ul> <p>For example:</p> <pre><code>function drawInlineSVG(ctx, rawSVG, callback) { var svg = new Blob([rawSVG], {type:"image/svg+xml;charset=utf-8"}), domURL = self.URL || self.webkitURL || self, url = domURL.createObjectURL(svg), img = new Image; img.onload = function () { ctx.drawImage(this, 0, 0); domURL.revokeObjectURL(url); callback(this); }; img.src = url; } // usage: drawInlineSVG(ctxt, svgText, function() { console.log(canvas.toDataURL()); // -&gt; PNG data-uri }); </code></pre> <p>Of course, console.log here is just for example. Store/transfer the string instead here. (I would also recommend adding an <code>onerror</code> handler inside the method).</p> <p>Also remember to set canvas size using either the <code>width</code> and <code>height</code> attributes, or from JavaScript using properties.</p>
19,561,269
AutoLayout with hidden UIViews?
<p>I feel like it's a fairly common paradigm to show/hide <code>UIViews</code>, most often <code>UILabels</code>, depending on business logic. My question is, what is the best way using AutoLayout to respond to hidden views as if their frame was 0x0. Here is an example of a dynamic list of 1-3 features.</p> <p><img src="https://i.stack.imgur.com/QGN4c.png" alt="Dynamic features list"></p> <p>Right now I have a 10px top space from the button to the last label, which obviously won't slide up when the the label is hidden. As of right now I created an outlet to this constraint and modifying the constant depending on how many labels I'm displaying. This is obviously a bit hacky since I'm using negative constant values to push the button up over the hidden frames. It's also bad because it's not being constrained to actual layout elements, just sneaky static calculations based on known heights/padding of other elements, and obviously fighting against what AutoLayout was built for. </p> <p>I could obviously just create new constraints depending on my dynamic labels, but that's a lot of micromanaging and a lot of verbosity for trying to just collapse some whitespace. Are there better approaches? Changing frame size 0,0 and letting AutoLayout do its thing with no manipulation of constraints? Removing views completely? </p> <p>Honestly though, just modifying the constant from context of the hidden view requires a single line of code with simple calculation. Recreating new constraints with <code>constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:</code> seems so heavy.</p> <p><strong>Edit Feb 2018</strong>: See Ben's answer with <code>UIStackView</code>s</p>
32,923,488
13
1
null
2013-10-24 08:52:19.973 UTC
60
2020-06-28 12:40:06.303 UTC
2018-02-13 05:59:16.947 UTC
null
775,762
null
775,762
null
1
168
ios|objective-c|autolayout
99,061
<p><a href="https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIStackView_Class_Reference/"><code>UIStackView</code></a> is probably the way to go for iOS 9+. Not only does it handle the hidden view, it will also remove additional spacing and margins if set up correctly.</p>
58,813,176
Webpack cant compile ts 3.7 (Optional Chaining, Nullish Coalescing)
<p>I try to use <code>typescript 3.7</code> features like Optional Chaining, Nullish Coalescing. But <code>webpack</code> gives me an error while transpaling. </p> <pre><code>app: Module parse failed: Unexpected token (50:40) app: File was processed with these loaders: app: * ../../../node_modules/ts-loader/index.js app: You may need an additional loader to handle the result of these loaders. app: | export const Layout = (props) =&gt; { app: | const regionsResults = useQuery(regionsQuery, { fetchPolicy: 'cache-first' }); app: &gt; const regions = regionsResults.data?.regions ?? []; app: | const userItem = useQuery(usersProfileQuery, { fetchPolicy: 'cache-first' }); app: | const handleOnClick = (selected) =&gt; props.history.push(selected.key); `` </code></pre>
58,836,714
3
1
null
2019-11-12 06:28:53.403 UTC
6
2021-07-06 04:59:15.817 UTC
2019-11-12 10:31:20.047 UTC
null
5,010,413
null
5,010,413
null
1
58
typescript|webpack|ts-loader
22,357
<p>I changed target: <code>esnext</code> to <code>es2018</code> in <code>tsconfig.json</code> file. Now it works.</p> <p>Webpack issue for reference : <a href="https://github.com/webpack/webpack/issues/10227" rel="noreferrer">https://github.com/webpack/webpack/issues/10227</a></p>
839,938
MySQL/SQL: Update with correlated subquery from the updated table itself
<p>I have a generic question that I will try to explain using an example.</p> <p>Say I have a table with the fields: "id", "name", "category", "appearances" and "ratio"</p> <p>The idea is that I have several items, each related to a single category and "appears" several times. The ratio field should include the percentage of each item's appearances out of the total number of appearances of items in the category.</p> <p>In pseudo-code what I need is the following: </p> <ul> <li><p><strong>For each category</strong><br> find the total sum of appearances for items related to it. For example it can be done with (<code>select sum("appearances") from table group by category</code>)</p></li> <li><p><strong>For each item</strong><br> set the ratio value as the item's appearances divided by the sum found for the category above</p></li> </ul> <p>Now I'm trying to achieve this with a single update query, but can't seem to do it. What I thought I should do is:</p> <pre><code>update Table T set T.ratio = T.appearances / ( select sum(S.appearances) from Table S where S.id = T.id ) </code></pre> <p>But MySQL does not accept the alias T in the update column, and I did not find other ways of achieving this. </p> <p>Any ideas?</p>
844,637
4
0
null
2009-05-08 14:04:28.05 UTC
12
2022-06-14 14:10:21.513 UTC
2018-07-02 15:59:27.113 UTC
null
9,070,959
null
103,532
null
1
24
mysql|sql|sql-update|correlated-subquery
45,178
<p>Following the two answers I received (none of which was complete so I wrote my own), what I eventually did is as follows:</p> <pre><code>UPDATE Table AS target INNER JOIN ( select category, appearances_sum from Table T inner join ( select category as cat, sum(appearances) as appearances_sum from Table group by cat ) as agg where T.category = agg.cat group by category ) as source ON target.category = source.category SET target.probability = target.appearances / source.appearances_sum </code></pre> <p>It works very quickly. I also tried with correlated subquery but it was much slower (orders of magnitude), so I'm sticking with the join.</p>
582,056
Getting list of parameter names inside python function
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/218616/getting-method-parameter-names-in-python">Getting method parameter names in python</a> </p> </blockquote> <p>Is there an easy way to be inside a python function and get a list of the parameter names?</p> <p>For example:</p> <pre><code>def func(a,b,c): print magic_that_does_what_I_want() &gt;&gt;&gt; func() ['a','b','c'] </code></pre> <p>Thanks</p>
4,051,447
4
0
null
2009-02-24 14:56:42.973 UTC
113
2022-07-03 14:19:13.96 UTC
2017-05-23 11:47:24.983 UTC
null
-1
R S
54,248
null
1
362
python|parameters
417,172
<p>Well we don't actually need <code>inspect</code> here.</p> <pre><code>&gt;&gt;&gt; func = lambda x, y: (x, y) &gt;&gt;&gt; &gt;&gt;&gt; func.__code__.co_argcount 2 &gt;&gt;&gt; func.__code__.co_varnames ('x', 'y') &gt;&gt;&gt; &gt;&gt;&gt; def func2(x,y=3): ... print(func2.__code__.co_varnames) ... pass # Other things ... &gt;&gt;&gt; func2(3,3) ('x', 'y') &gt;&gt;&gt; &gt;&gt;&gt; func2.__defaults__ (3,) </code></pre> <p>For Python 2.5 and older, use <code>func_code</code> instead of <code>__code__</code>, and <code>func_defaults</code> instead of <code>__defaults__</code>.</p>
602,717
Aligning UIToolBar items
<p>I have three <code>UIBarButtonItem</code> created as below. They align left and I'd like to align center so there isn't a gap on the right side. I don't see an align property on <code>UIToolBar</code>. Is there another way to accomplish this?</p> <pre><code>//create some buttons UIBarButtonItem *aboutButton = [[UIBarButtonItem alloc] initWithTitle:@"About" style:UIBarButtonItemStyleBordered target:self action:@selector(showAbout:)]; [toolbar setItems:[NSArray arrayWithObjects:settingsButton,deleteButton,aboutButton,nil]]; //Add the toolbar as a subview to the navigation controller. [self.navigationController.view addSubview:toolbar]; </code></pre>
602,795
4
0
null
2009-03-02 15:21:45.547 UTC
29
2020-12-31 20:37:22.103 UTC
2019-05-21 04:31:07.023 UTC
null
23,649
null
40,106
null
1
118
ios|cocoa-touch|uitoolbar
66,539
<p>Add two UIBarButtonSystemItemFlexibleSpace items to your toolbar, to the left and right of your items</p> <pre><code>UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; [toolbar setItems:[NSArray arrayWithObjects:flexibleSpace, settingsButton,deleteButton,aboutButton, flexibleSpace, nil]]; </code></pre> <p>Adding these as you would any other toolbar items will distribute space evenly between the two of them.</p>
23,373,376
Uncaught SyntaxError: Failed to execute 'postMessage' on 'Window': Invalid target origin 'my_page' in a call to 'postMessage'
<p>i have following script </p> <p><strong>Parent Page(pair_pixel_filter.php):</strong></p> <pre><code> window.addEventListener("message", function(e) { $('#log').append("Received message: " + (e.data)); }, false); $('.photo-upload-btn').click(function(event) { event.preventDefault(); window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes"); }); </code></pre> <p><strong>The Child Page</strong></p> <pre><code>$.ajax({ type: 'post', url: url, data: { base64data: dataURL }, success: function(data) { window.opener.postMessage(data, "pair_pixel_filter.php"); window.close(); } }); </code></pre> <p>Basically opening a Popup and then doing some ajax on pop up and returning result to parent. But from Child i am getting this error.</p> <blockquote> <p>Uncaught SyntaxError: Failed to execute 'postMessage' on 'Window': Invalid target origin 'pair_pixel_filter.php' in a call to 'postMessage'</p> </blockquote>
23,373,557
1
0
null
2014-04-29 19:15:46.537 UTC
3
2015-12-22 16:39:13.517 UTC
2014-04-29 19:21:22.727 UTC
null
1,045,808
null
1,045,808
null
1
22
javascript|jquery|cross-browser|postmessage
59,705
<p>The 2nd parameter to <code>postMessage</code> is the "target origin". This is the <em>domain</em> where the page is located, not the name of the (php) file.</p> <p>It needs to be something like:</p> <pre><code>window.opener.postMessage(data, "http://example.com"); </code></pre> <p>See: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage</a></p>
21,566,556
How to get a current Item's info from QtGui.QListWidget?
<p>Created a QtGui.QListWidget list widget:</p> <pre><code>myListWidget = QtGui.QListWidget() </code></pre> <p>Populated this ListWidget with QListWidgetItem list items:</p> <pre><code>for word in ['cat', 'dog', 'bird']: list_item = QtGui.QListWidgetItem(word, myListWidget) </code></pre> <p>Now connect a function on list_item's left click:</p> <pre><code>def print_info(): print myListWidget.currentItem().text() myListWidget.currentItemChanged.connect(print_info) </code></pre> <p>As you see from my code all I am getting on a left click is a list_item's label name. But aside from a label name I would like to get a list_item's index number (order number as it is displayed in ListWidget). I would like to get as much info on left-clicked list_item as possible. I looked at dir(my_list_item). But I can't anything useful there ( other than already used my_list_item.text() method which returns a list_item's label name). Thanks in advance!</p>
21,567,729
2
0
null
2014-02-05 00:45:48.793 UTC
3
2019-09-20 08:09:15.673 UTC
null
null
null
null
1,107,049
null
1
11
python|listview|pyqt|listviewitem
50,491
<p>Use <a href="https://doc.qt.io/qt-4.8/qlistwidget.html#currentRow-prop" rel="noreferrer">QListWidget.currentRow</a> to get the index of the current item:</p> <pre><code>def print_info(): print myListWidget.currentRow() print myListWidget.currentItem().text() </code></pre> <p>A <a href="https://doc.qt.io/qt-4.8/qlistwidgetitem.html" rel="noreferrer">QListWidgetItem</a> does not know its own index: it's up to the list-widget to manage that.</p> <p>You should also note that <a href="https://doc.qt.io/qt-4.8/qlistwidget.html#currentItemChanged" rel="noreferrer">currentItemChanged</a> sends the current and previous items as arguments, so you could simplify to:</p> <pre><code>def print_info(current, previous): print myListWidget.currentRow() print current.text() print current.isSelected() ... </code></pre>
58,172,688
Incorrect integrity when fetching from the cache
<p>When running <code>yarn add --dev jest</code>, I got <em>error Incorrect integrity when fetching from the cache</em>.</p> <h2>Full output:</h2> <pre class="lang-sh prettyprint-override"><code>tests (master)$ yarn add --dev jest yarn add v1.19.0 info No lockfile found. [1/4] Resolving packages... warning jest &gt; jest-cli &gt; jest-config &gt; jest-environment-jsdom &gt; jsdom &gt; [email protected]: use String.prototype.padStart() [2/4] Fetching packages... error Incorrect integrity when fetching from the cache info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command. </code></pre> <p>I tried removed <code>node_modules</code>, re-ran <code>yarn install</code> and <code>yarn add --dev jest</code> to no avail.</p> <p>How do I fix this?</p>
58,172,689
6
0
null
2019-09-30 17:36:39.577 UTC
8
2020-03-25 15:02:17.35 UTC
2019-10-22 15:26:34.03 UTC
null
12,143,080
null
196,964
null
1
62
yarnpkg
20,794
<h2><code>yarn cache clean</code></h2> <p>To fix this, run:</p> <pre class="lang-sh prettyprint-override"><code>yarn cache clean yarn add --dev jest </code></pre> <p>From the <a href="https://yarnpkg.com/lang/en/docs/cli/cache/" rel="noreferrer">yarn cache documentation</a>:</p> <blockquote> <h3><code>yarn cache clean [&lt;module_name...&gt;]</code></h3> <p>Running this command will clear the global cache. It will be populated again the next time yarn or yarn install is run. Additionally, you can specify one or more packages that you want to clean.</p> </blockquote> <p>You can also see where the cache is with <code>yarn cache dir</code>.</p> <blockquote> <h3><code>yarn cache dir</code></h3> <p>Running yarn cache dir will print out the path where yarn’s global cache is currently stored.</p> </blockquote>
37,052,899
What is the preferred method to echo a blank line in a shell script?
<p>I am currently writing some code for a shell script that needs a blank line between two parts of the script, as thus they can be separated when output is displayed to the user. </p> <p>My question is, I am not sure what the preferred practice is in a shell script for a blank line. </p> <p>Is it preferred practice to just write <code>echo</code> and nothing else or to write <code>echo " "</code> as in echo with quotes and blank between the quotes?</p>
37,053,001
6
0
null
2016-05-05 14:12:27.633 UTC
5
2021-12-19 21:03:00.687 UTC
2016-05-05 14:19:43.36 UTC
null
1,640,661
null
1,472,416
null
1
46
bash|shell
75,592
<p><code>echo</code> is preferred. <code>echo " "</code> outputs an unnecessary space character. <code>echo ""</code> would be better, but it's unnecessary.</p>
19,233,529
Run bash script as daemon
<p>I have a script, which runs my PHP script each X times:</p> <pre><code>#!/bin/bash while true; do /usr/bin/php -f ./my-script.php echo "Waiting..." sleep 3 done </code></pre> <p>How can I start it as daemon?</p>
19,235,243
5
0
null
2013-10-07 19:57:14.223 UTC
48
2019-01-31 11:23:16.797 UTC
2014-10-27 19:38:49.783 UTC
null
445,131
null
2,435,642
null
1
75
linux|centos|centos6|daemons
175,397
<p>To run it as a full daemon from a shell, you'll need to use <code>setsid</code> and redirect its output. You can redirect the output to a logfile, or to <code>/dev/null</code> to discard it. Assuming your script is called myscript.sh, use the following command:</p> <pre><code>setsid myscript.sh &gt;/dev/null 2&gt;&amp;1 &lt; /dev/null &amp; </code></pre> <p>This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first <code>/dev/null</code> with your /path/to/logfile.</p> <p>You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).</p>
24,428,520
Identity 2.0 with custom tables
<p>I'm new to ASP.NET identity and am still trying to get my head around how it all works. Unfortunately I've found many of the tutorials I've tried are for Identity 1.0, whereas I'm attempting to work with Identity 2.0.</p> <p>The biggest problem I am facing is something I thought would be simple, but has turned out not to be. What I'm trying to do is use an existing database with an existing user table. Currently all I can seem to do is get Identity to create it's own tables to store user data. I don't want to use Entity Framework, but I've had great difficulty separating Entity Framework from Identity 2.0.</p> <p>While my situation I'm using SQL Server, I thought I'd try and implement the custom provider for MySQL at this link: <a href="http://www.asp.net/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider">http://www.asp.net/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider</a> and <a href="https://github.com/raquelsa/AspNet.Identity.MySQL">https://github.com/raquelsa/AspNet.Identity.MySQL</a>. This appears to work under Identity 1 only. There does appear to be a newer one, however that uses Entity Framework. I've also tried <a href="https://github.com/ILMServices/RavenDB.AspNet.Identity">https://github.com/ILMServices/RavenDB.AspNet.Identity</a>.</p> <p>With everything I've tried, I get stuck with the following line:</p> <pre><code>var manager = new IdentityUserManager(new UserStore&lt;IdentityUser&gt;(context.Get&lt;ApplicationDbContext&gt;())); </code></pre> <p>The problem I'm facing is that I need to remove ApplicaitonDbContext class according to the instructions for RavenDB, however I don't know what to put in this line instead.</p> <p>The errors I get are:</p> <blockquote> <p>The non-generic type 'AspNet.Identity.MySQL.UserStore' cannot be used with type arguments</p> </blockquote> <p>and</p> <blockquote> <p>The type or namespace name 'ApplicationDbContext' could not be found (are you missing a using directive or an assembly reference?)</p> </blockquote> <p>The second error is to be expected, however I'm not sure what to use in this line of code instead. Has anyone had any experience with implementing a custom provider without using Entity Framework?</p> <p>Thanks.</p> <p><strong>Update 1:</strong></p> <p>I've attempted the following tutorial [ <a href="http://aspnetguru.com/customize-authentication-to-your-own-set-of-tables-in-asp-net-mvc-5/">http://aspnetguru.com/customize-authentication-to-your-own-set-of-tables-in-asp-net-mvc-5/</a> ] but it appears to be incomplete, with compile or runtime errors when following the tutorial exactly. A few problems I still have are...</p> <p>When replacing all instances of "ApplicationUser" with "User" have a problem with the following line in IdentityConfig.cs</p> <pre><code>var manager = new ApplicationUserManager(new UserStore&lt;ApplicationUser&gt;(context.Get&lt;MyDbContext&gt;())); </code></pre> <p>Changing ApplicationUser to User produces the following error</p> <blockquote> <p>The type 'WebApplicationTest2.Models.User' cannot be used as type parameter 'TUser' in the generic type or method 'Microsoft.AspNet.Identity.EntityFramework.UserStore'. There is no implicit reference conversion from 'WebApplicationTest2.Models.User' to 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser'.</p> </blockquote> <p>I'm also having difficulty working out how to use the user manager and many of the ASync methods. The following lines don't work:</p> <pre><code>AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager)); </code></pre> <p>In AccountController.cs with the following errors:</p> <blockquote> <p>The best overloaded method match for 'Microsoft.Owin.Security.IAuthenticationManager.SignIn(Microsoft.Owin.Security.AuthenticationProperties, params System.Security.Claims.ClaimsIdentity[])' has some invalid arguments.</p> <p>'WebApplicationTest2.Models.User' does not contain a definition for 'GenerateUserIdentityAsync' and no extension method 'GenerateUserIdentityAsync' accepting a first argument of type 'WebApplicationTest2.Models.User' could be found (are you missing a using directive or an assembly reference?)</p> </blockquote>
24,599,334
3
0
null
2014-06-26 10:51:22.523 UTC
17
2018-06-07 11:53:16.26 UTC
2016-03-28 05:32:10.56 UTC
null
209,259
null
391,299
null
1
29
c#|asp.net|asp.net-mvc-5|asp.net-identity-2
32,771
<p>In your examples, you seem to want to replace the <code>DbContext</code> with something else but I believe that actually, you need to focus your efforts one level higher.</p> <p>The framework has a class <code>UserManager</code> which has the responsibility for managing, but not storing, the users and their related information. When it wants to store the users (or their related information) the default is to use the provided <code>UserStore&lt;IdentityUser&gt;</code> which knows how to store <code>IdentityUser</code> instances in a database using a <code>DbContext</code>.</p> <p>In the 2.0 framework, the various bits of the identity storing were broken into several interfaces. The default implementation provided, <code>UserStore&lt;IdentityUser&gt;</code> implements several of these interfaces and stores the data for them all in the database using a <code>DBContext</code>. </p> <p>If you look at the defnition of the default provided entity framework based UserStore you can see that it implements many of these small interfaces:</p> <pre><code>public class UserStore&lt;TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim&gt; : IUserLoginStore&lt;TUser, TKey&gt;, IUserClaimStore&lt;TUser, TKey&gt;, IUserRoleStore&lt;TUser, TKey&gt;, IUserPasswordStore&lt;TUser, TKey&gt;, IUserSecurityStampStore&lt;TUser, TKey&gt;, IQueryableUserStore&lt;TUser, TKey&gt;, IUserEmailStore&lt;TUser, TKey&gt;, IUserPhoneNumberStore&lt;TUser, TKey&gt;, IUserTwoFactorStore&lt;TUser, TKey&gt;, IUserLockoutStore&lt;TUser, TKey&gt;, IUserStore&lt;TUser, TKey&gt;, IDisposable where TUser : IdentityUser&lt;TKey, TUserLogin, TUserRole, TUserClaim&gt; where TRole : IdentityRole&lt;TKey, TUserRole&gt; where TKey : Object, IEquatable&lt;TKey&gt; where TUserLogin : new(), IdentityUserLogin&lt;TKey&gt; where TUserRole : new(), IdentityUserRole&lt;TKey&gt; where TUserClaim : new(), IdentityUserClaim&lt;TKey&gt; </code></pre> <p>As you don't want to use Entity Framework at all, you need to provide your own implementations of some of these key interfaces which will store that data in the places you want the data to be stored. The main interface is <a href="http://msdn.microsoft.com/en-us/library/dn613278(v=vs.108).aspx" rel="nofollow noreferrer"><code>IUserStore&lt;Tuser,TKey&gt;</code></a>. this defines the contract for storing users which have a key of a particular type. If you only want to store users and no other information then you can implement this interface and then pass your implementation to the <code>UserManager</code> and you should be good to go.</p> <p>It's unlikely that this will be enough though as likely you will want passwords, roles, logins etc for your users. If so then you need to make your class which implements <code>IUserStore&lt;Tuser,TKey&gt;</code> also implement <code>IUserPasswordStore&lt;TUser, TKey&gt;</code>, <code>IRoleStore&lt;TRole, TKey&gt;</code> and <code>IUserClaimStore&lt;TUser, TKey&gt;</code>.</p> <p>You can find a list of all the interfaces <a href="http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity(v=vs.108).aspx" rel="nofollow noreferrer">on MSDN here</a></p> <p>Depending on the bits you want to use you need to implement those interfaces. </p> <p>You will probably also need to define your own versions of the <code>Identity*</code> classes which exist for the <a href="http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.entityframework(v=vs.108).aspx" rel="nofollow noreferrer">Entity framework already out of the box</a>. So you will need your own <code>IdentityUser</code> class which represents the users you want to store, and <code>IdentityUserClaim</code> for the users claims. I haven't done this myself so I'm not exactly sure, but my feeling is that you will have to do this.</p> <p>Scott Allen has a <a href="http://odetocode.com/blogs/scott/archive/2014/01/20/implementing-asp-net-identity.aspx" rel="nofollow noreferrer">good article</a> on the various bits of the model which might be useful.</p> <p>As for your issues with this line:</p> <pre><code>AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager)); </code></pre> <p>There is a method called <code>GenerateUserIdentityAsync</code> which is defined on <code>Applicationuser</code> which extends <code>IdentityUser</code>. It is defined in the template project I believe and looks something like this:</p> <pre><code>public class ApplicationUser : IdentityUser { public async Task&lt;ClaimsIdentity&gt; GenerateUserIdentityAsync( UserManager&lt;ApplicationUser&gt; manager) { // Note the authenticationType must match the one // defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } </code></pre> <p>As you are not using the entity framework <code>IdentityUser</code> any more then you either need to define a similar method or your own <code>User</code> class or implement the same functionality some other way (like just calling <code>await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie)</code> instead)</p>
36,209,068
Boto3: grabbing only selected objects from the S3 resource
<p>I can grab and read all the objects in my AWS S3 bucket via </p> <pre><code>s3 = boto3.resource('s3') bucket = s3.Bucket('my-bucket') all_objs = bucket.objects.all() for obj in all_objs: pass #filter only the objects I need </code></pre> <p>and then</p> <pre><code>obj.key </code></pre> <p>would give me the path within the bucket.</p> <p>Is there a way to filter beforehand for only those files respecting a certain starting path (a directory in the bucket) so that I'd avoid looping over all the objects and filtering later?</p>
36,209,136
3
0
null
2016-03-24 20:02:08.99 UTC
4
2021-08-26 04:01:53.3 UTC
null
null
null
null
2,352,319
null
1
24
python|amazon-web-services|amazon-s3|boto3
53,660
<p>Use the <code>filter</code><a href="http://boto3.readthedocs.org/en/latest/reference/core/collections.html#boto3.resources.collection.ResourceCollection.filter" rel="noreferrer">[1]</a>, <a href="http://boto3.readthedocs.org/en/latest/guide/collections.html#filtering" rel="noreferrer">[2]</a> method of collections like bucket.</p> <pre><code>s3 = boto3.resource('s3') bucket = s3.Bucket('my-bucket') objs = bucket.objects.filter(Prefix='myprefix') for obj in objs: pass </code></pre>
35,971,042
How to correctly use ES6 "export default" with CommonJS "require"?
<p>I've been working through <a href="http://blog.madewithlove.be/post/webpack-your-bags/">Webpack tutorial</a>. In one of the sections, it gives the code example that contains one line of essence to this question:</p> <pre class="lang-js prettyprint-override"><code>export default class Button { /* class code here */ } </code></pre> <p>In the next section of said tutorial, titled "Code splitting", the class defined above is loaded on demand, like this:</p> <pre class="lang-js prettyprint-override"><code>require.ensure([], () =&gt; { const Button = require("./Components/Button"); const button = new Button("google.com"); // ... }); </code></pre> <p>Unfortunately, this code throws an exception:</p> <pre><code>Uncaught TypeError: Button is not a function </code></pre> <p>Now, I know that the <em>right</em> way to include ES6 module would be to simply <code>import Button from './Components/Button';</code> at the top of the file, but using a construct like that anywhere else in the file makes babel a sad panda:</p> <pre><code>SyntaxError: index.js: 'import' and 'export' may only appear at the top level </code></pre> <p>After some fiddling with previous (<code>require.ensure()</code>) example above, I realized that ES6 <code>export default</code> syntax exports an object that has property named <code>default</code>, which contains my code (the <code>Button</code> function).</p> <p>I did fix the broken code example by appending <code>.default</code> after require call, like this:</p> <pre class="lang-js prettyprint-override"><code>const Button = require("./Components/Button").default; </code></pre> <p>...but I think it looks a bit clumsy and it is error-prone (I'd have to know which module uses ES6 syntax, and which uses good old <code>module.exports</code>).</p> <p>Which brings me to my question: <strong>what is the right way to import ES6 code from code that uses CommonJS syntax?</strong></p>
35,973,567
2
0
null
2016-03-13 13:49:13.933 UTC
12
2018-08-24 01:35:54.283 UTC
null
null
null
null
267,491
null
1
34
javascript|ecmascript-6|webpack|commonjs|es6-module-loader
15,299
<p>To use <code>export default</code> with Babel, you can do 1 of the following:</p> <ol> <li><code>require("myStuff").default</code></li> <li><code>npm install babel-plugin-add-module-exports --save-dev</code></li> </ol> <p>Or 3:</p> <pre><code>//myStuff.js var thingToExport = {}; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = thingToExport; </code></pre>
59,095,824
What is the difference between .pt, .pth and .pwf extentions in PyTorch?
<p>I have seen in some code examples, that people use .pwf as model file saving format. But in PyTorch documentation .pt and .pth are recommended. I used .pwf and worked fine for small 1->16->16 convolutional network.</p> <p>My question is what is the difference between these formats? Why is .pwf extension not even recommended in PyTorch documentation and why do people still use it?</p>
59,100,353
3
1
null
2019-11-28 20:33:37.55 UTC
6
2021-07-03 10:50:45.73 UTC
2020-07-26 14:45:59.597 UTC
null
4,317,729
null
4,317,729
null
1
36
python|serialization|deep-learning|pytorch|checkpointing
32,021
<p>There are no differences between the extensions that were listed: <code>.pt</code>, <code>.pth</code>, <code>.pwf</code>. One can use whatever extension (s)he wants. So, if you're using <code>torch.save()</code> for saving models, then it by default uses python pickle (<code>pickle_module=pickle</code>) to save the objects and some metadata. Thus, you have the liberty to choose the extension you want, as long as it doesn't cause collisions with any other standardized extensions.</p> <p>Having said that, it is however <a href="https://discuss.pytorch.org/t/what-does-pth-tar-extension-mean/36697/3" rel="noreferrer"><strong>not</strong> recommended to use <code>.pth</code> extension</a> when checkpointing models because it collides with <a href="https://docs.python.org/3.8/library/site.html" rel="noreferrer">Python path (<code>.pth</code>) configuration files</a>. Because of this, I myself use <code>.pth.tar</code> or <code>.pt</code> but not <code>.pth</code>, or any other extensions.</p> <hr /> <p>The standard way of checkpointing models in PyTorch is not finalized yet. Here is an open issue, as of this writing: <a href="https://github.com/pytorch/pytorch/issues/14864" rel="noreferrer">Recommend a different file extension for models (.PTH is a special extension for Python) - issues/14864 </a></p> <p>It's been <a href="https://github.com/pytorch/pytorch/issues/14864#issuecomment-477195843" rel="noreferrer">suggested by @soumith</a> to use:</p> <ul> <li><code>.pt</code> for checkpointing models in pickle format</li> <li><code>.ptc</code> for checkpointing models in pytorch compiled (for JIT)</li> </ul>
38,608,089
Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.ConnectException: Connection timed out: connect
<p>Here is the code of the application. I have been trying to run this using eclipse IDE. I also added all the required java mail jar files namely <code>dsn.jar,imap.jar,mailapi.jar,pop3.jar,smtp.jar,mail.jar</code>. But it gives the following error <code>Could not connect to SMTP host: smtp.gmail.com, port: 587</code>.</p> <p>There's no firewall blocking access because a reply is received on pinging smtp.gmail.com. I have even tried it this way :</p> <ul> <li>First sign into the Gmail account in a browser on the device where you are setting up/using your client</li> <li>Go here and enable access for "less secure" apps: <a href="https://www.google.com/settings/security/lesssecureapps" rel="noreferrer">https://www.google.com/settings/security/lesssecureapps</a></li> <li>Then go here: <a href="https://accounts.google.com/b/0/DisplayUnlockCaptcha" rel="noreferrer">https://accounts.google.com/b/0/DisplayUnlockCaptcha</a> and click Continue. </li> <li>Then straightaway go back to your client and try again.</li> </ul> <blockquote> <p>javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.ConnectException: Connection timed out: connect at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642) at javax.mail.Service.connect(Service.java:317) at javax.mail.Service.connect(Service.java:176) at javax.mail.Service.connect(Service.java:125) at javax.mail.Transport.send0(Transport.java:194) at javax.mail.Transport.send(Transport.java:124) at PlainTextEmailSender.sendPlainTextEmail(PlainTextEmailSender.java:50) at PlainTextEmailSender.main(PlainTextEmailSender.java:73) Caused by: java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:319) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)</p> </blockquote> <pre><code> package net.codejava.mail; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class PlainTextEmailSender { public void sendPlainTextEmail(String host, String port, final String userName, final String password, String toAddress, String subject, String message) throws AddressException, MessagingException { // sets SMTP server properties Properties properties = new Properties(); properties.put("mail.smtp.host", host); properties.put("mail.smtp.port", port); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); // creates a new session with an authenticator Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }; Session session = Session.getInstance(properties, auth); // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(userName)); InternetAddress[] toAddresses = { new InternetAddress(toAddress) }; msg.setRecipients(Message.RecipientType.TO, toAddresses); msg.setSubject(subject); msg.setSentDate(new Date()); // set plain text message msg.setText(message); // sends the e-mail Transport.send(msg); } /** * Test the send e-mail method * */ public static void main(String[] args) { // SMTP server information String host = "smtp.gmail.com"; String port = "587"; String mailFrom = "user_name"; String password = "password"; // outgoing message information String mailTo = "email_address"; String subject = "Hello my friend"; String message = "Hi guy, Hope you are doing well. Duke."; PlainTextEmailSender mailer = new PlainTextEmailSender(); try { mailer.sendPlainTextEmail(host, port, mailFrom, password, mailTo, subject, message); System.out.println("Email sent."); } catch (Exception ex) { System.out.println("Failed to sent email."); ex.printStackTrace(); } } } </code></pre>
38,629,240
4
3
null
2016-07-27 08:48:01.81 UTC
3
2019-05-05 09:54:24.853 UTC
2016-07-27 13:41:54.983 UTC
null
3,604,083
null
6,643,652
null
1
10
java|eclipse|email
71,874
<p>As I said, there's nothing wrong with your code. If anything, just to do some testing, try to drop the Authentication part to see if that works:</p> <pre><code> public void sendPlainTextEmail(String host, String port, final String userName, final String password, String toAddress, String subject, String message) throws AddressException, MessagingException { // sets SMTP server properties Properties properties = new Properties(); properties.put("mail.smtp.host", host); properties.put("mail.smtp.port", port); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); // *** BEGIN CHANGE properties.put("mail.smtp.user", userName); // creates a new session, no Authenticator (will connect() later) Session session = Session.getDefaultInstance(properties); // *** END CHANGE // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(userName)); InternetAddress[] toAddresses = { new InternetAddress(toAddress) }; msg.setRecipients(Message.RecipientType.TO, toAddresses); msg.setSubject(subject); msg.setSentDate(new Date()); // set plain text message msg.setText(message); // *** BEGIN CHANGE // sends the e-mail Transport t = session.getTransport("smtp"); t.connect(userName, password); t.sendMessage(msg, msg.getAllRecipients()); t.close(); // *** END CHANGE } </code></pre> <p>That's the code I'm using every day to send dozens of emails from my application, and it is 100% guaranteed to work -- as long as <code>smtp.gmail.com:587</code> is reachable, of course.</p>
34,862,375
How to save and restore Android Studio user interface settings?
<p>Android Studio allows the user to customize certain features, such as editor settings and coding styles. On Windows boxes, the default folder for these settings appears to be C:\Users\{username}\.AndroidStudio{version}\config. I'm looking for documentation for these files so that we can decide which files should be under version control.</p> <p>The goals are: 1) to have consistent UI settings for a group of developers; and 2) to have an easy way to configure a new Android Studio install.</p> <p>So far, the following files look interesting:</p> <pre> <code> ...\config\templates\user.xml User-defined code templates ...\config\options\editor.codeinsight.xml Editor settings & code insight ...\config\options\editor.xml Editor settings ...\config\options\cachedDictionary.xml User additions to spelling dictionary. ...\config\codestyles\Default_1_.xml Code formatting </code> </pre>
34,862,767
4
0
null
2016-01-18 19:17:49.917 UTC
6
2021-07-15 07:40:39.067 UTC
2017-04-24 12:28:40.023 UTC
null
2,225,646
null
2,225,646
null
1
52
android-studio|installation
25,801
<p>You can go <code>file &gt; Export settings</code> then you get to choose exactly the settings to export and you get a single <code>settings.jar</code> file. </p> <p>The reverse process is <code>file &gt; Import Settings &gt; choose settings.jar</code></p> <p><a href="https://i.stack.imgur.com/gmTUh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gmTUh.png" alt="enter image description here"></a></p>
53,798,660
pyinstaller command not found
<p>I am using Ubuntu on VirtualBox. How do I add <code>pyinstaller</code> to the <code>PATH</code>?</p> <p>The issue is when I say </p> <pre><code>pyinstaller file.py </code></pre> <p>it says pyinstaller command not found</p> <p>It says it installed correctly, and according to other posts, I think it has, but I just can't get it to work. I ran:</p> <pre><code>pip install pyinstaller </code></pre> <p>and </p> <pre><code>pyinstaller file.py </code></pre> <p>but it won't work. I think I need to add it to the shell path so Linux knows where to find it.</p> <p><code>pip show pyinstaller</code> works.</p>
59,564,377
5
4
null
2018-12-16 01:21:13.94 UTC
3
2021-12-04 03:16:12.5 UTC
2018-12-16 20:10:37.563 UTC
null
8,883,322
null
8,883,322
null
1
12
python|python-3.x|executable|pyinstaller
38,889
<p>You can use the following command if you do not want to create additional python file. </p> <pre><code>python -m PyInstaller myscript.py </code></pre>
51,870,736
How to define a const array in typescript
<p>My Code:</p> <pre><code>const WEEKDAYS_SHORT: string[] = ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'] </code></pre> <p>the error message comes from TypeScript (3.0) compiler:</p> <blockquote> <p>TS2322: Type 'string[]' is not assignable to type '[string, string, string, string, string, string, string]'. Property '0' is missing in type 'string[]'.</p> </blockquote> <p><a href="https://i.stack.imgur.com/rhZWw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rhZWw.png" alt="enter image description here"></a></p> <p>if I change the <code>string[]</code> to <code>ReadonlyArray&lt;string&gt;</code>, then the error message becomes:</p> <blockquote> <p>TS2322: Type 'ReadonlyArray' is not assignable to type '[string, string, string, string, string, string, string]'. Property '0' is missing in type 'ReadonlyArray'.</p> </blockquote> <p>my tsconfig.json:</p> <pre><code>{ "compilerOptions": { "declaration": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": ["es6", "dom"], "module": "es6", "moduleResolution": "node", "sourceMap": true, "target": "es5", "jsx": "react", "strict": true }, "exclude": [ "**/*.spec.ts", "node_modules", "vendor", "public" ], "compileOnSave": false } </code></pre> <p>how can I define a readonly array in TypeScript?</p>
51,871,676
5
2
null
2018-08-16 06:20:35.087 UTC
1
2021-11-27 00:17:18.683 UTC
2018-08-16 06:41:04.41 UTC
null
2,998,877
null
2,998,877
null
1
21
arrays|typescript
43,231
<p>As you point out the issue is cause because you try to assign the string array (<code>string[]</code>) to a 7-string-tuple. While your solution to use <code>any</code> will work it's not generally advisable to use <code>any</code>. Spelling out the supple is also not ideal since it's soo long.</p> <p>What we can do is create a helper function to create a tuple type. This function is reusable for anywhere you need tuple:</p> <pre><code>function tupleArray&lt;T extends any[]&gt;(...v: T) { return v; } const WEEKDAYS_SHORT_INFFERED = tupleArray('Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam') // INFFERED AS [string, string, string, string, string, string, string] const WEEKDAYS_SHORT: [string, string, string, string, string, string, string] = WEEKDAYS_SHORT_INFFERED </code></pre>
26,797,219
Echo off in Jenkins Console Output
<p>I'm following <a href="http://developer.android.com/sdk/installing/studio-build.html#configureSigning">guideline</a> how to sign Android apk with Jenkins. I have parametrized Jenkins job with KSTOREPWD and KEYPWD. A part of Jenkins' job configuration (Build->Execute shell) is to take those parameters and store them as environment variables:</p> <pre><code>export KSTOREPWD=${KSTOREPWD} export KEYPWD=${KEYPWD} ... ./gradlew assembleRelease </code></pre> <p>The problem is when the build is over anybody can access the build "Console Output" and see what passwords were entered; part of that output:</p> <pre><code>08:06:57 + export KSTOREPWD=secretStorePwd 08:06:57 + KSTOREPWD=secretStorePwd 08:06:57 + export KEYPWD=secretPwd 08:06:57 + KEYPWD=secretPwd </code></pre> <p>So I'd like to suppress echo before output from <code>export</code> commands and re-enable echo after <code>export</code> commands.</p>
26,803,326
3
1
null
2014-11-07 08:38:16.337 UTC
9
2019-10-21 15:28:41.12 UTC
2016-06-06 19:55:43.203 UTC
null
1,845,976
null
2,401,535
null
1
77
jenkins|android-gradle-plugin|echo|android-keystore
94,295
<p>By default, Jenkins launches <em>Execute Shell</em> script with <code>set -x</code>. This causes all commands to be echoed</p> <p>You can type <code>set +x</code> before any command to temporary override that behavior. Of course you will need <code>set -x</code> to start showing them again.</p> <p>You can override this behaviour for the whole script by putting the following at the top of the build step:<br> <code>#!/bin/bash +x</code></p>
26,510,930
Android Lollipop, add popup menu from title in toolbar
<p>I'm unable to see how adding a popup menu from the title is accomplished like is shown in many of the material design examples. Any help would be much appreciated.</p> <p><img src="https://i.stack.imgur.com/FlEaW.png" alt="Toolbar Popup From Title"></p>
26,511,653
2
1
null
2014-10-22 15:14:41.987 UTC
25
2018-04-18 16:31:35.81 UTC
null
null
null
null
274,817
null
1
47
android|android-5.0-lollipop|android-toolbar
34,433
<p>You're going to need to add a Spinner to the Toolbar:</p> <pre><code>&lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_height="?attr/actionBarSize" android:layout_width="match_parent" android:background="?attr/colorPrimary"&gt; &lt;Spinner android:id="@+id/spinner_nav" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/android.support.v7.widget.Toolbar&gt; </code></pre> <p>You will then need to disable the default title:</p> <pre><code>Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); </code></pre> <p>You can then retrieve and setup the Spinner as needed in your Activity/Fragment.</p>
6,901,764
Get Concrete Class name from Abstract Class
<p>In Java, inside an abstract class can I get the instance of the concrete class that extends it?</p>
6,901,774
2
0
null
2011-08-01 16:52:44.207 UTC
4
2021-10-22 13:37:31.38 UTC
2020-02-28 04:18:04.427 UTC
null
1,033,581
null
620,273
null
1
76
java|abstract-class
45,367
<p>Yes, you can do this by calling <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#getClass--" rel="noreferrer"><code>this.getClass()</code></a>. This will give you the <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html" rel="noreferrer"><code>Class</code></a> instance for the runtime type of <code>this</code>.</p> <p>If you just want the name of the class, you could use <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getName--" rel="noreferrer"><code>this.getClass().getName()</code></a>.</p> <p>Lastly, there are also <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getSimpleName--" rel="noreferrer"><code>this.getClass().getSimpleName()</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getCanonicalName--" rel="noreferrer"><code>this.getClass().getCanonicalName()</code></a>. I use the former all the time to print readable class names to log files and the like.</p>
7,551,132
How can I overwrite file contents with new content in PHP?
<p>I tried to use fopen, but I only managed to append content to end of file. Is it possible to overwrite all contents with new content in PHP?</p>
7,551,155
3
1
null
2011-09-26 06:00:10.853 UTC
8
2019-01-11 16:15:58.987 UTC
null
null
null
null
159,793
null
1
70
php|file
138,133
<p>Use <a href="http://php.net/file_put_contents" rel="noreferrer"><code>file_put_contents()</code></a></p> <pre><code>file_put_contents('file.txt', 'bar'); echo file_get_contents('file.txt'); // bar file_put_contents('file.txt', 'foo'); echo file_get_contents('file.txt'); // foo </code></pre> <p>Alternatively, if you're stuck with <a href="http://php.net/fopen" rel="noreferrer"><code>fopen()</code></a> you can use the <code>w</code> or <code>w+</code> modes:</p> <blockquote> <p><strong>'w'</strong> Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.</p> <p><strong>'w+'</strong> Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.</p> </blockquote>
7,552,551
no overload for matches delegate 'system.eventhandler'
<p>As I'm pretty new to C#, I struggle with the following piece of code. When I click to button 'knop', the method 'klik' has to be executed. The method has to draw the Bitmap 'b', generated by 'DrawMandel' on the form. But I constantly get the error 'no overload for matches delegate 'system.eventhandler'.</p> <pre><code>using System; using System.Windows.Forms; using System.Drawing; class Mandelbrot : Form { public Bitmap b; public Mandelbrot() { Button knop; knop = new Button(); knop.Location = new Point(370, 15); knop.Size = new Size(50, 30); knop.Text = "OK"; this.Text = "Mandelbrot 1.0"; this.ClientSize = new Size(800, 800); knop.Click += this.klik; this.Controls.Add(knop); } public void klik(PaintEventArgs pea, EventArgs e) { Bitmap c = this.DrawMandel(); Graphics gr = pea.Graphics; gr.DrawImage(b, 150, 200); } public Bitmap DrawMandel() { //function that creates the bitmap return b; } static void Main() { Application.Run(new Mandelbrot()); } } </code></pre>
7,552,578
4
3
null
2011-09-26 08:35:10.333 UTC
2
2016-11-02 16:41:06.05 UTC
null
null
null
null
964,657
null
1
36
c#
170,485
<p>You need to change <code>public void klik(PaintEventArgs pea, EventArgs e)</code> to <code>public void klik(object sender, System.EventArgs e)</code> because there is no <code>Click</code> event handler with parameters <code>PaintEventArgs pea, EventArgs e</code>.</p>
7,544,160
How to send parameters with jquery $.get()
<p>I'm trying to do a jquery GET and i want to send a parameter. </p> <p>here's my function: </p> <pre><code>$(function() { var availableProductNames; $.get("manageproducts.do?option=1", function(data){ availableProductNames = data.split(",");; alert(availableProductNames); $("#nameInput").autocomplete({ source: availableProductNames }); }); }); </code></pre> <p>This doesn't seem to work; i get a null in my servlet when i use <code>request.getParameter("option")</code>;</p> <p>If i type the link into the browser <a href="http://www.myite.com/manageproducts.do?option=1" rel="noreferrer">http://www.myite.com/manageproducts.do?option=1</a> it works perfectly.</p> <p>I also tried:</p> <pre><code>$.get( "manageproducts.do?", {option: "1"}, function(data){} </code></pre> <p>which doesn't work either.</p> <p>Can you please help me?</p> <p>EDIT:</p> <p>also tried</p> <pre><code> $.ajax({ type: "GET", url: "manageproducts.do", data: "option=1", success: function(msg){ availableProductNames = msg.split(","); alert(availableProductNames); $("#nameInput").autocomplete({ source: availableProductNames }); } }); </code></pre> <p>Still getting the same result.</p>
7,544,412
4
1
null
2011-09-25 07:13:24.473 UTC
10
2016-06-11 05:09:18.007 UTC
2011-09-25 07:50:16.747 UTC
null
716,092
null
716,092
null
1
47
ajax|jquery|get
114,408
<p>If you say that it works with accessing directly <code>manageproducts.do?option=1</code> in the browser then it should work with:</p> <pre><code>$.get('manageproducts.do', { option: '1' }, function(data) { ... }); </code></pre> <p>as it would send the same GET request.</p>
7,324,833
Concatenating Matrices in R
<p>How can I concatenate matrices of same columns but different number of rows? For example, I want to concatenate <code>a</code> (<code>dim(a) = 15 7000</code>) and <code>b</code> (<code>dim(b) = 16 7000</code>) and I want the result to be a matrix of <code>31</code> rows by <code>7000</code> columns.</p> <p>Can I also do this for matrices with a different number of rows <em>and</em> columns? Say I want to combine a matrix of 15 rows and 7000 columns with another of 16 rows and 7500 columns. Can I create one dataset with that?</p>
7,324,871
4
0
null
2011-09-06 19:06:07.393 UTC
1
2022-03-30 00:14:11.793 UTC
2022-02-11 18:12:05.423 UTC
null
2,828,287
null
633,426
null
1
50
r|matrix|concatenation
127,575
<p>Sounds like you're looking for <code>rbind</code>:</p> <pre><code>&gt; a&lt;-matrix(nrow=10,ncol=5) &gt; b&lt;-matrix(nrow=20,ncol=5) &gt; dim(rbind(a,b)) [1] 30 5 </code></pre> <p>Similarly, <code>cbind</code> stacks the matrices horizontally.</p> <p>I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")</p>
1,983,033
How do I dynamically generate columns in a WPF DataGrid?
<p>I am attempting to display the results of a query in a WPF datagrid. The ItemsSource type I am binding to is <code>IEnumerable&lt;dynamic&gt;</code>. As the fields returned are not determined until runtime I don't know the type of the data until the query is evaluated. Each "row" is returned as an <code>ExpandoObject</code> with dynamic properties representing the fields.</p> <p>It was my hope that <code>AutoGenerateColumns</code> (like below) would be able to generate columns from an <code>ExpandoObject</code> like it does with a static type but it does not appear to.</p> <pre><code>&lt;DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Results}"/&gt; </code></pre> <p>Is there anyway to do this declaratively or do I have to hook in imperatively with some C#?</p> <p><strong>EDIT</strong></p> <p>Ok this will get me the correct columns:</p> <pre><code>// ExpandoObject implements IDictionary&lt;string,object&gt; IEnumerable&lt;IDictionary&lt;string, object&gt;&gt; rows = dataGrid1.ItemsSource.OfType&lt;IDictionary&lt;string, object&gt;&gt;(); IEnumerable&lt;string&gt; columns = rows.SelectMany(d =&gt; d.Keys).Distinct(StringComparer.OrdinalIgnoreCase); foreach (string s in columns) dataGrid1.Columns.Add(new DataGridTextColumn { Header = s }); </code></pre> <p>So now just need to figure out how to bind the columns to the IDictionary values.</p>
1,990,632
4
0
null
2009-12-30 23:19:04.02 UTC
18
2017-10-01 23:16:29.767 UTC
2010-01-02 04:08:55.493 UTC
null
155,537
null
155,537
null
1
36
wpf|dynamic|datagrid|expandoobject
55,262
<p>Ultimately I needed to do two things:</p> <ol> <li>Generate the columns manually from the list of properties returned by the query </li> <li>Set up a DataBinding object</li> </ol> <p>After that the built-in data binding kicked in and worked fine and didn't seem to have any issue getting the property values out of the <code>ExpandoObject</code>.</p> <pre><code>&lt;DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Results}" /&gt; </code></pre> <p>and</p> <pre><code>// Since there is no guarantee that all the ExpandoObjects have the // same set of properties, get the complete list of distinct property names // - this represents the list of columns var rows = dataGrid1.ItemsSource.OfType&lt;IDictionary&lt;string, object&gt;&gt;(); var columns = rows.SelectMany(d =&gt; d.Keys).Distinct(StringComparer.OrdinalIgnoreCase); foreach (string text in columns) { // now set up a column and binding for each property var column = new DataGridTextColumn { Header = text, Binding = new Binding(text) }; dataGrid1.Columns.Add(column); } </code></pre>
1,487,978
Setting the target version of Java in ant javac
<p>I need to compile a jar file using ant (1.7.0) to run under a specific version of Java (1.5). I currently have Java 1.6 on my machine. I have tried setting:</p> <pre><code>&lt;target name="compile"&gt; &lt;javac compiler="javac1.5" target="1.5" srcdir=.../&gt; &lt;/target&gt; </code></pre> <p>I have also removed </p> <pre><code>&lt;property name="build.compiler" value="modern"/&gt; </code></pre> <p>and there is no properties file. I am running Java 1.6 on Linux/SUSE</p> <p>Also is there a simple way of determining which version of Java is expected in the jar file.</p>
1,488,014
4
0
null
2009-09-28 16:23:09.837 UTC
10
2013-05-24 19:28:49.59 UTC
null
null
null
null
130,964
null
1
72
ant|javac
146,581
<p>Use "target" attribute and remove the 'compiler' attribute. See <a href="http://ant.apache.org/manual/Tasks/javac.html" rel="noreferrer">here</a>. So it should go something like this:</p> <pre><code>&lt;target name="compile"&gt; &lt;javac target="1.5" srcdir=.../&gt; &lt;/target&gt; </code></pre> <p>Hope this helps</p>
2,018,512
reading tar file contents without untarring it, in python script
<p>I have a tar file which has number of files within it. I need to write a python script which will read the contents of the files and gives the count o total characters, including total number of letters, spaces, newline characters, everything, without untarring the tar file.</p>
2,018,576
4
2
null
2010-01-07 05:58:08.983 UTC
29
2021-01-30 21:48:58.427 UTC
2010-01-07 06:08:20.973 UTC
null
317,415
null
317,415
null
1
99
python|tar
89,193
<p>you can use <code>getmembers()</code></p> <pre><code>&gt;&gt;&gt; import tarfile &gt;&gt;&gt; tar = tarfile.open("test.tar") &gt;&gt;&gt; tar.getmembers() </code></pre> <p>After that, you can use <code>extractfile()</code> to extract the members as file object. Just an example</p> <pre><code>import tarfile,os import sys os.chdir("/tmp/foo") tar = tarfile.open("test.tar") for member in tar.getmembers(): f=tar.extractfile(member) content=f.read() print "%s has %d newlines" %(member, content.count("\n")) print "%s has %d spaces" % (member,content.count(" ")) print "%s has %d characters" % (member, len(content)) sys.exit() tar.close() </code></pre> <p>With the file object <code>f</code> in the above example, you can use <code>read()</code>, <code>readlines()</code> etc. </p>
1,677,880
How to get a DOM Element from a jQuery selector?
<p>I'm having an impossibly hard time finding out to get the actual <code>DOMElement</code> from a jQuery selector.</p> <p>Sample Code:</p> <pre><code>&lt;input type=&quot;checkbox&quot; id=&quot;bob&quot; /&gt; var checkbox = $(&quot;#bob&quot;).click(function() { //some code } ) </code></pre> <p>and in another piece of code I'm trying to determine the checked value of the checkbox.</p> <pre><code> if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked ) //do something. </code></pre> <p>And please, I do not want to do:</p> <pre><code> if ( checkbox.eq(0).is(&quot;:checked&quot;)) //do something </code></pre> <p>That gets me around the checkbox, but other times I've needed the real <code>DOMElement</code>.</p>
1,677,910
4
1
null
2009-11-05 02:00:19.92 UTC
39
2021-04-13 23:10:36.56 UTC
2021-04-13 23:10:36.56 UTC
null
814,702
null
59,114
null
1
191
javascript|jquery|dom
195,909
<p>You can access the raw DOM element with:</p> <pre><code>$("table").get(0); </code></pre> <p>or more simply:</p> <pre><code>$("table")[0]; </code></pre> <p>There isn't actually a lot you need this for however (in my experience). Take your checkbox example:</p> <pre><code>$(":checkbox").click(function() { if ($(this).is(":checked")) { // do stuff } }); </code></pre> <p>is more "jquery'ish" and (imho) more concise. What if you wanted to number them?</p> <pre><code>$(":checkbox").each(function(i, elem) { $(elem).data("index", i); }); $(":checkbox").click(function() { if ($(this).is(":checked") &amp;&amp; $(this).data("index") == 0) { // do stuff } }); </code></pre> <p>Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for <code>XmlHttpRequest</code>.</p>
25,973,581
How to format axis number format to thousands with a comma
<p>How can I change the format of the numbers in the x-axis to be like <code>10,000</code> instead of <code>10000</code>? Ideally, I would just like to do something like this:</p> <pre><code>x = format((10000.21, 22000.32, 10120.54), "#,###") </code></pre> <p>Here is the code:</p> <pre><code>import matplotlib.pyplot as plt # create figure instance fig1 = plt.figure(1) fig1.set_figheight(15) fig1.set_figwidth(20) ax = fig1.add_subplot(2,1,1) x = 10000.21, 22000.32, 10120.54 y = 1, 4, 15 ax.plot(x, y) ax2 = fig1.add_subplot(2,1,2) x2 = 10434, 24444, 31234 y2 = 1, 4, 9 ax2.plot(x2, y2) fig1.show() </code></pre>
25,973,637
9
1
null
2014-09-22 11:58:33.487 UTC
27
2022-08-18 14:24:23 UTC
2022-08-18 14:24:23 UTC
null
7,758,804
null
2,386,086
null
1
97
python|matplotlib
154,958
<p>Use <code>,</code> as <a href="https://docs.python.org/2/library/string.html#formatstrings" rel="noreferrer">format specifier</a>:</p> <pre><code>&gt;&gt;&gt; format(10000.21, ',') '10,000.21' </code></pre> <p>Alternatively you can also use <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="noreferrer"><code>str.format</code></a> instead of <a href="https://docs.python.org/2/library/functions.html#format" rel="noreferrer"><code>format</code></a>:</p> <pre><code>&gt;&gt;&gt; '{:,}'.format(10000.21) '10,000.21' </code></pre> <hr> <p>With <a href="http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FuncFormatter" rel="noreferrer"><code>matplotlib.ticker.FuncFormatter</code></a>:</p> <pre><code>... ax.get_xaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) ax2.get_xaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) fig1.show() </code></pre> <p><img src="https://i.stack.imgur.com/ysXP2.png" alt="enter image description here"></p>
36,265,026
Angular 2 - innerHTML styling
<p>I am getting chunks of HTML codes from HTTP calls. I put the HTML blocks in a variable and insert it on my page with [innerHTML] but I can not style the inserted HTML block. Does anyone have any suggestion how I might achieve this?</p> <pre class="lang-typescript prettyprint-override"><code>@Component({ selector: 'calendar', template: '&lt;div [innerHTML]=&quot;calendar&quot;&gt;&lt;/div&gt;', providers: [HomeService], styles: [`h3 { color: red; }`] }) </code></pre> <p>The HTML that I want to style is the block contained in the variable &quot;calendar&quot;.</p>
36,265,072
11
7
null
2016-03-28 15:04:23.29 UTC
67
2021-11-18 01:26:45.85 UTC
2021-08-27 22:03:10.593 UTC
null
13,618,646
null
4,725,175
null
1
208
angular|innerhtml
167,644
<p><strong>update 2 <code>::slotted</code></strong></p> <p><code>::slotted</code> is now supported by all new browsers and can be used with <code>ViewEncapsulation.ShadowDom</code></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted</a></p> <p><strong>update 1 ::ng-deep</strong></p> <p><code>/deep/</code> was deprecated and replaced by <code>::ng-deep</code>.</p> <p><code>::ng-deep</code> is also already marked deprecated, but there is no replacement available yet. </p> <p>When <code>ViewEncapsulation.Native</code> is properly supported by all browsers and supports styling accross shadow DOM boundaries, <code>::ng-deep</code> will probably be discontinued. </p> <p><strong>original</strong></p> <p>Angular adds all kinds of CSS classes to the HTML it adds to the DOM to emulate shadow DOM CSS encapsulation to prevent styles of bleeding in and out of components. Angular also rewrites the CSS you add to match these added classes. For HTML added using <code>[innerHTML]</code> these classes are not added and the rewritten CSS doesn't match.</p> <p>As a workaround try </p> <ul> <li>for CSS added to the component</li> </ul> <pre class="lang-css prettyprint-override"><code>/* :host /deep/ mySelector { */ :host ::ng-deep mySelector { background-color: blue; } </code></pre> <ul> <li>for CSS added to <code>index.html</code></li> </ul> <pre class="lang-css prettyprint-override"><code>/* body /deep/ mySelector { */ body ::ng-deep mySelector { background-color: green; } </code></pre> <p><code>&gt;&gt;&gt;</code> (and the equivalent<code>/deep/</code> but <code>/deep/</code> works better with SASS) and <code>::shadow</code> were added in 2.0.0-beta.10. They are similar to the shadow DOM CSS combinators (which are deprecated) and only work with <code>encapsulation: ViewEncapsulation.Emulated</code> which is the default in Angular2. They probably also work with <code>ViewEncapsulation.None</code> but are then only ignored because they are not necessary. These combinators are only an intermediate solution until more advanced features for cross-component styling is supported.</p> <p>Another approach is to use</p> <pre class="lang-css prettyprint-override"><code>@Component({ ... encapsulation: ViewEncapsulation.None, }) </code></pre> <p>for all components that block your CSS (depends on where you add the CSS and where the HTML is that you want to style - might be <strong>all</strong> components in your application)</p> <p><strong>Update</strong></p> <p><a href="https://plnkr.co/edit/ZHByFR?p=preview" rel="noreferrer">Example Plunker</a></p>
7,649,037
How to get rspec-2 to give the full trace associated with a test failure?
<p>Right now if I run my test suite using <code>rake spec</code> I get an error:</p> <pre> 1) SegmentsController GET 'index' should work Failure/Error: get 'index' undefined method `locale' for # # ./spec/controllers/segments_controller_spec.rb:14: in `block (3 levels) in ' </pre> <p>This is normal as I do have an error :)</p> <p>The problem is that the trace isn't very helpful. I know it broke in <code>segments_controller_spec.rb</code>, line 14, but this is just where I call the test:</p> <pre><code>### segments_controller_spec.rb:14 get 'index' </code></pre> <p>I would prefer to have the actual line breaking and the complete trace, not the part in the spec folder.</p> <p>Running with <code>--trace</code> doesn't help.</p>
7,653,286
6
1
null
2011-10-04 13:56:45.993 UTC
13
2017-01-05 05:56:29.317 UTC
2012-11-13 20:33:48.073 UTC
null
168,143
null
90,691
null
1
98
ruby|ruby-on-rails-3|testing|rspec|rspec2
22,692
<p>You must run rspec with <code>-b</code> option to see full backtraces</p>
7,604,636
Better to 'try' something and catch the exception or test if it's possible first to avoid an exception?
<p>Should I test <code>if</code> something is valid or just <code>try</code> to do it and catch the exception?</p> <ul> <li>Is there any solid documentation saying that one way is preferred?</li> <li>Is one way more <em>pythonic</em>?</li> </ul> <p>For example, should I:</p> <pre><code>if len(my_list) &gt;= 4: x = my_list[3] else: x = 'NO_ABC' </code></pre> <p>Or:</p> <pre><code>try: x = my_list[3] except IndexError: x = 'NO_ABC' </code></pre> <hr> <p>Some thoughts...<br> <a href="http://www.python.org/dev/peps/pep-0020/" rel="noreferrer">PEP 20</a> says:</p> <blockquote> <p>Errors should never pass silently.<br/> Unless explicitly silenced.</p> </blockquote> <p>Should using a <code>try</code> instead of an <code>if</code> be interpreted as an error passing silently? And if so, are you explicitly silencing it by using it in this way, therefore making it OK?</p> <hr> <p>I'm <strong><em>not</em></strong> referring to situations where you can only do things 1 way; for example:</p> <pre><code>try: import foo except ImportError: import baz </code></pre>
7,604,717
8
0
null
2011-09-29 23:55:29.787 UTC
49
2020-05-26 18:46:54.223 UTC
2018-04-09 14:17:14.54 UTC
null
1,033,581
null
836,407
null
1
149
python|exception-handling|if-statement|try-catch|pep
47,658
<p>You should prefer <code>try/except</code> over <code>if/else</code> if that results in</p> <ul> <li>speed-ups (for example by preventing extra lookups)</li> <li>cleaner code (fewer lines/easier to read)</li> </ul> <p>Often, these go hand-in-hand.</p> <hr> <p><b>speed-ups</b></p> <p>In the case of trying to find an element in a long list by:</p> <pre><code>try: x = my_list[index] except IndexError: x = 'NO_ABC' </code></pre> <p>the try, except is the best option when the <code>index</code> is probably in the list and the IndexError is usually not raised. This way you avoid the need for an extra lookup by <code>if index &lt; len(my_list)</code>.</p> <p><b>Python encourages the use of exceptions, <em>which you handle</em></b> is a phrase from <a href="http://www.diveintopython3.net/your-first-python-program.html#exceptions" rel="noreferrer">Dive Into Python</a>. Your example not only handles the exception (gracefully), rather than letting it <em>silently pass</em>, also the exception occurs only in the <em>exceptional</em> case of index not being found (hence the word <em>exception</em>!).</p> <hr> <p><b>cleaner code</b></p> <p>The official Python Documentation mentions <a href="https://docs.python.org/3/glossary.html?highlight=eafp#term-eafp" rel="noreferrer">EAFP</a>: <em>Easier to ask for forgiveness than permission</em> and <a href="http://bayes.colorado.edu/PythonIdioms.html" rel="noreferrer">Rob Knight</a> notes that <b>catching errors rather than avoiding them</b>, can result in cleaner, easier to read code. His example says it like this:</p> <p>Worse <em>(LBYL 'look before you leap')</em>:</p> <pre><code>#check whether int conversion will raise an error if not isinstance(s, str) or not s.isdigit(): return None elif len(s) &gt; 10: #too many digits for int conversion return None else: return int(s) </code></pre> <p>Better <em>(EAFP: Easier to ask for forgiveness than permission)</em>:</p> <pre><code>try: return int(s) except (TypeError, ValueError, OverflowError): #int conversion failed return None </code></pre>
7,414,983
How to use the ANSI Escape code for outputting colored text on Console
<p>I read about ANSI-C escape codes <a href="http://en.wikipedia.org/wiki/ANSI_escape_code#Colors" rel="noreferrer">here</a>. Tried to use it in C/C++ printf/cout to colorize the text outputted to consolde but without sucess.</p> <p>Code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdio&gt; int main() { int a=3, b=5; int &amp;ref = a; ref = b; //cout &lt;&lt; "\155\32\m" &lt;&lt; a &lt;&lt; b &lt;&lt;'\n'; //here it prints m→m 5, no colored text printf("\155\32\m %d",a); //here to it prints same - m→m 5, getchar(); } </code></pre> <p>How to use these escape codes to output colored text to console?</p> <p>Am i missing something?</p> <p><strong>EDIT:</strong> In some C++ code I saw a call to this function</p> <pre><code>textcolor(10); </code></pre> <p>But it gives compilation errors in g++ and in Visual Studio. Which compiler had this function available? Any details?</p>
7,415,204
9
0
null
2011-09-14 10:41:38.303 UTC
7
2022-03-08 16:38:48.06 UTC
2011-09-14 10:46:52.653 UTC
null
2,759,376
null
2,759,376
null
1
10
c++|c|colors
43,876
<p>I'm afraid you forgot the ESC character:</p> <pre><code>#include &lt;cstdio&gt; int main() { printf("%c[%dmHELLO!\n", 0x1B, 32); } </code></pre> <p>Unfortunately it will only work on consoles that support ANSI escape sequences (like a linux console using bash, or old Windows consoles that used ansi.sys)</p>
7,465,006
Differentiate between mouse and keyboard triggering onclick
<p>I need to find a way to determine if a link has been activated via a mouse click or a keypress.</p> <pre><code>&lt;a href="" onclick="submitData(event, '2011-07-04')"&gt;Save&lt;/a&gt; </code></pre> <p>The idea is that if they are using a mouse to hit the link then they can keep using the mouse to choose what they do next. But if they tabbing around the page and they tab to the Save link, then I'll open then next line for editing (the page is like a spreadsheet with each line becoming editable using ajax).</p> <p>I thought the event parameter could be queried for which mouse button is pressed, but when no button is pressed the answer is 0 and that's the same as the left mouse button. They I thought I could get the keyCode from the event but that is coming back as undefined so I'm assuming a mouse event doesn't include that info. </p> <pre><code>function submitData(event, id) { alert("key = "+event.keyCode + " mouse button = "+event.button); } </code></pre> <p>always returns "key = undefined mouse button = 0"</p> <p>Can you help?</p>
7,465,035
9
2
null
2011-09-18 22:52:55.897 UTC
4
2022-01-05 16:17:07.133 UTC
null
null
null
null
186,212
null
1
37
javascript|onclick|mouseevent|keypress
22,264
<p>You can create a condition with <code>event.type</code></p> <pre><code>function submitData(event, id) { if(event.type == 'mousedown') { // do something return; } if(event.type == 'keypress') { // do something else return; } } </code></pre> <p>Note: You'll need to attach an event which supports both event types. With JQuery it would look something like <code>$('a.save').bind('mousedown keypress', submitData(event, this));</code></p> <p>The inline <code>onClick=""</code> will not help you as it will always pass that click event since that's how it's trapped. </p> <p><strong>EDIT</strong>: <strong>Here's a working demo</strong> to prove my case with native JavaScript: <a href="http://jsfiddle.net/AlienWebguy/HPEjt/" rel="noreferrer">http://jsfiddle.net/AlienWebguy/HPEjt/</a></p> <p>I used a button so it'd be easier to see the node highlighted during a tab focus, but it will work the same with any node. </p>
7,063,276
How to load local html file into UIWebView
<p>I'm trying to load a html file into my UIWebView but it won't work. Here's the stage: I have a folder called html_files in my project. Then I created a webView in interface builder and assigned an outlet to it in the viewController. This is the code I'm using to append the html file:</p> <pre><code>-(void)viewDidLoad { NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"]; NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile]; [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]]; [super viewDidLoad]; } </code></pre> <p>That won't work and the UIWebView is blank. I'd appreciate some help.</p>
7,063,407
18
0
null
2011-08-15 09:08:05.71 UTC
53
2019-11-28 10:15:47.857 UTC
2019-05-15 16:30:38.893 UTC
null
2,272,431
null
526,924
null
1
170
ios|objective-c|iphone|cocoa-touch|uiwebview
199,766
<p>probably it is better to use NSString and load html document as follows:</p> <p><strong>Objective-C</strong></p> <pre><code>NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"]; NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil]; [webView loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]]; </code></pre> <p><strong>Swift</strong></p> <pre><code>let htmlFile = NSBundle.mainBundle().pathForResource("fileName", ofType: "html") let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding) webView.loadHTMLString(html!, baseURL: nil) </code></pre> <p><strong>Swift 3 has few changes:</strong></p> <pre><code>let htmlFile = Bundle.main.path(forResource: "intro", ofType: "html") let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8) webView.loadHTMLString(html!, baseURL: nil) </code></pre> <p>Did you try?</p> <p>Also check that the resource was found by <code>pathForResource:ofType:inDirectory</code> call.</p>
13,788,617
JAXB marshalling Java to output XML file
<p>problem is how do i generate XML file output instead of system.out?</p> <pre><code>package jaxbintroduction; import java.io.FileOutputStream; import java.io.OutputStream; public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here itemorder.Book quickXML = new itemorder.Book(); quickXML.setAuthor("Sillyme"); quickXML.setDescription("Dummie book"); quickXML.setISBN(123456789); quickXML.setPrice((float)12.6); quickXML.setPublisher("Progress"); quickXML.setTitle("Hello World JAVA"); try { javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(quickXML.getClass().getPackage().getName()); javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(quickXML, System.out); OutputStream os = new FileOutputStream( "nosferatu.xml" ); marshaller.marshal( quickXML, os ); } catch (javax.xml.bind.JAXBException ex) { // XXXTODO Handle exception java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N } } } </code></pre>
13,788,636
4
1
null
2012-12-09 15:07:32.253 UTC
null
2015-11-13 12:48:10.233 UTC
2012-12-09 15:25:43.663 UTC
null
1,145,285
null
1,798,864
null
1
17
java|xml|jaxb|marshalling
73,056
<p>You are already marshalling to <code>nosferatu.xml</code>. Just remove or comment the line:</p> <pre><code>marshaller.marshal(quickXML, System.out); </code></pre> <p>if you don't wish to display the output and close the <code>OutputStream</code>:</p> <pre><code>os.close(); </code></pre>
14,072,042
How to check if element has click handler?
<blockquote> <p><strong>Possible Duplicate:</strong><br /> <a href="https://stackoverflow.com/questions/1236067/test-if-event-handler-is-bound-to-an-element-in-jquery">test if event handler is bound to an element in jQuery</a></p> </blockquote> <p>Tried to do the following (link is jQuery object of 'a' tag):</p> <pre><code> link.data(&quot;events&quot;) //undefined even if link has event handlers jQuery.data(link, 'events') //undefined always also jQuery._data(link, 'events') //undefined always also </code></pre> <p>using jquery-1.8.3</p> <p>So, how to check if element has click handler?</p>
14,072,162
1
3
null
2012-12-28 15:47:48.123 UTC
6
2022-09-17 20:26:44.713 UTC
2022-09-17 20:26:44.713 UTC
null
4,370,109
null
1,491,537
null
1
21
javascript|jquery|jquery-events
53,057
<p>You can use <code>jQuery._data</code> to check for events. The first argument should be a reference to the HTML element, not the jQuery object.</p> <pre><code>var ev = $._data(element, 'events'); if(ev &amp;&amp; ev.click) alert('click bound'); </code></pre> <p>Sample below.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function(){ $('#test').click(function(){ // NOTE: this below is refering to the HTML element, NOT the jQuery element var ev = $._data(this, 'events'); if(ev &amp;&amp; ev.click) alert('click bound to this button'); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt; &lt;button id="test"&gt;Click me to check for click handlers&lt;/button&gt;</code></pre> </div> </div> </p> <p>Also note that this method for checking events will only work when the event is bound via jQuery. If the event is bound via <code>element.attachEventListener</code>, <code>element.onclick</code>, <code>&lt;a onclick="doStuff()"&gt;</code> or any other non jQuery way, this will not work. If you're fitting into this boat, check <a href="https://stackoverflow.com/a/22841712/1090190">this answer</a>.</p>
14,181,408
HttpContext.Current.Session is null in Ashx file
<p>I saw some questions (<a href="https://stackoverflow.com/questions/5868599/httpcontext-current-session-is-null">Here</a> and <a href="https://stackoverflow.com/questions/4710411/httpcontext-current-session-null-item">Here</a>) but they do not answer my question. I am trying to call Ajax using "ajax.ashx" file, and in function to access Session. For some reason, the value of the Session object itself is null.</p> <p>Use example:</p> <pre><code>Session = HttpContext.Current.Session // This is null </code></pre> <p>Or:</p> <pre><code>public virtual void ProcessRequest(HttpContext context) { System.Web.SessionState.HttpSessionState Session = context.Session; // This is null } </code></pre> <p>In the Web.config:</p> <pre class="lang-html prettyprint-override"><code>&lt;sessionState timeout="1800"&gt;&lt;/sessionState&gt; </code></pre>
14,181,556
1
1
null
2013-01-06 10:54:36.72 UTC
13
2016-05-29 05:14:48.043 UTC
2017-05-23 10:31:07.057 UTC
null
-1
null
863,110
null
1
44
c#|asp.net|.net|session|generic-handler
33,313
<p>You must add on your handler the <code>IRequiresSessionState</code> on the declaration of it as:</p> <pre><code>public class YourHandleName : IHttpHandler, IRequiresSessionState { ... </code></pre> <p>by default the handlers are not connected with the session to keep them minimum, by adding the <code>IRequiresSessionState</code> you attach them with the session.</p>
14,019,906
What is the difference between call hierarchy and find references eclipse?
<p>I got confused when using this two commands in <code>eclipse</code> <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>G</kbd> and <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>H</kbd> both are returning same results . </p> <p><strong>Scenario</strong>:</p> <p>Want to find where the method "<strong>findUsage</strong>" has been called.</p> <p><strong>Sample Class</strong></p> <p><img src="https://i.stack.imgur.com/Wz924.png" alt="enter image description here"></p> <p><strong>Call Hierarchy Output (<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>H</kbd>)</strong> .</p> <p><img src="https://i.stack.imgur.com/ODClf.png" alt="enter image description here"></p> <p><strong>Find References (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>G</kbd>) output</strong></p> <p><img src="https://i.stack.imgur.com/pMdiI.png" alt="enter image description here"></p> <p>Both are showing same results. Can anyone know what is the difference between these two commands?</p>
14,021,495
2
0
null
2012-12-24 10:11:57.867 UTC
17
2017-12-25 01:59:17.44 UTC
2015-07-18 00:40:53.843 UTC
null
2,901,002
null
1,449,101
null
1
50
eclipse|eclipse-plugin
28,375
<p>"Find references" shows you all <strong>direct callers</strong> of the selected method. "Call hierarchy" in contrast shows also the callers of those direct callers, and the callers of those, ... and so on.</p> <p>So the output is only identical, if direct callers of your selected method do not have any callers themselfes. Just try both commands on some larger code base and you will immmediately see the difference, like in this screenshot:</p> <p><img src="https://i.stack.imgur.com/OIj7s.jpg" alt="Call hierarchy"></p> <p>If you wonder why there are two such features, if "Find references" is basically just a subset of the "Call hierarchy": Find references works really fast, so you can use it all the time without any waiting for results. The call hierarchy on the other hand takes more computation time and therefore may interrupt your coding workflow.</p>
14,328,148
How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?
<p>The title says it all. I'm using a custom button to fetch the user's facebook information (for "sign up" purposes). Yet, I don't want the app to remember the last registered user, neither the currently logged in person via the Facebook native app. I want the Facebook login activity to pop up each time. That is why I want to log out any previous users programmatically.</p> <p>How can I do that? This is how I do the login:</p> <pre><code>private void signInWithFacebook() { SessionTracker sessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { } }, null, false); String applicationId = Utility.getMetadataApplicationId(getBaseContext()); mCurrentSession = sessionTracker.getSession(); if (mCurrentSession == null || mCurrentSession.getState().isClosed()) { sessionTracker.setSession(null); Session session = new Session.Builder(getBaseContext()).setApplicationId(applicationId).build(); Session.setActiveSession(session); mCurrentSession = session; } if (!mCurrentSession.isOpened()) { Session.OpenRequest openRequest = null; openRequest = new Session.OpenRequest(RegisterActivity.this); if (openRequest != null) { openRequest.setPermissions(null); openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK); mCurrentSession.openForRead(openRequest); } }else { Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() { @Override public void onCompleted(GraphUser user, Response response) { fillProfileWithFacebook( user ); } }); } } </code></pre> <p>Ideally, I would make a call at the beginning of this method to log out any previous users.</p>
14,328,450
9
0
null
2013-01-14 22:43:00.057 UTC
29
2017-02-07 15:02:01.123 UTC
2015-09-02 21:32:48.18 UTC
null
1,832,942
null
151,939
null
1
80
android|facebook|facebook-graph-api|facebook-android-sdk
114,150
<p><strong>Update for latest SDK:</strong></p> <p>Now @zeuter's answer is correct for Facebook SDK v4.7+:</p> <blockquote> <p><code>LoginManager.getInstance().logOut();</code></p> </blockquote> <p><strong>Original answer:</strong></p> <p>Please do not use SessionTracker. It is an internal (package private) class, and is not meant to be consumed as part of the public API. As such, its API may change at any time without any backwards compatibility guarantees. You should be able to get rid of all instances of SessionTracker in your code, and just use the active session instead.</p> <p>To answer your question, if you don't want to keep any session data, simply call <a href="https://developers.facebook.com/docs/reference/android/3.0/Session#closeAndClearTokenInformation%28%29" rel="noreferrer">closeAndClearTokenInformation</a> when your app closes.</p>
13,928,116
write a shell script to ssh to a remote machine and execute commands
<p>I have two questions:</p> <ol> <li>There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting? </li> <li>When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication. </li> </ol> <p>The remote machines are VMs created on the run and I just have their IPs. So, I cant place a script file beforehand in those machines and execute them from my machine.</p>
13,928,265
10
4
null
2012-12-18 07:15:55.123 UTC
46
2021-03-26 14:53:28.023 UTC
null
null
null
null
791,287
null
1
129
linux|shell|ssh
448,688
<blockquote> <p>There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?</p> </blockquote> <p>You can do this with ssh, for example:</p> <pre><code>#!/bin/bash USERNAME=someUser HOSTS="host1 host2 host3" SCRIPT="pwd; ls" for HOSTNAME in ${HOSTS} ; do ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}" done </code></pre> <blockquote> <p>When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.</p> </blockquote> <p>You can add the <code>StrictHostKeyChecking=no</code> option to ssh:</p> <pre><code>ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls" </code></pre> <p>This will <a href="http://linuxcommando.blogspot.co.uk/2008/10/how-to-disable-ssh-host-key-checking.html" rel="noreferrer">disable the host key check</a> and automatically add the host key to the list of known hosts. If you do not want to have the host added to the known hosts file, add the option <code>-o UserKnownHostsFile=/dev/null</code>.</p> <p>Note that this <strong>disables certain security checks</strong>, for example protection against man-in-the-middle attack. It should therefore not be applied in a security sensitive environment.</p>
9,208,951
iOS - Merging two images of different size
<p>I'm facing the following problem : I have to merge two images A and B to create a new image C as a result of the merging.<br> I already know how to merge two images but in this case my goal is a little bit different.<br> I would like that image A will be the background for Image B.<br> For instance if image A size is 500x500 and image B size is 460x460 I would like that image C (the image result of the merging) will be 500x500, with image B (460x460) centered in it.</p> <p>Thanks in advance for any help or suggestion</p>
9,209,044
7
1
null
2012-02-09 10:16:11.647 UTC
29
2017-03-30 06:00:43.75 UTC
2012-02-09 10:21:25.883 UTC
null
106,435
null
576,917
null
1
27
objective-c|ios|cocoa-touch|merge|uiimage
33,040
<p>This is what I've done in my app, but without using <code>UIImageView</code>:</p> <pre><code>UIImage *bottomImage = [UIImage imageNamed:@"bottom.png"]; //background image UIImage *image = [UIImage imageNamed:@"top.png"]; //foreground image CGSize newSize = CGSizeMake(width, height); UIGraphicsBeginImageContext( newSize ); // Use existing opacity as is [bottomImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; // Apply supplied opacity if applicable [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height) blendMode:kCGBlendModeNormal alpha:0.8]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); </code></pre> <p>If the image already has opacity, you do not need to set it (as in bottomImage) otherwise you can set it (as with image). </p> <p>After this <code>UIImage</code> is created then you can embed it in your <code>UIImageView</code></p> <p><strong>UPDATE</strong>: Thanks to Ahmet AkkoK - for Swift (2.2) users blend mode macro has changed. <code>CGBlendMode .kCGBlendModeNormal</code> is replaced with <code>CGBlendMode.Normal</code></p>
44,488,434
Inserting if statement inside ES6 template literal
<p>I have a simple ajax request returning some data and then inserting into a template literal. I was wondering if it it possible to insert an 'if' statement inside the template? </p> <p>Essentially to add a further line of code, if the json object has a 5th color.</p> <pre><code> $.ajax({ url: 'http://localhost:8888/ColourCatchr%202/app/search.php' }).done(function(results){ var res = jQuery.parseJSON(results); console.log(res); $.each(res,function(index,result){ $('.palettes').append(` &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h3 class="panel-title"&gt;${result.name}&lt;/h3&gt; &lt;/div&gt; &lt;div class="panel-body"&gt; &lt;div class="col-md-12 colors"&gt; &lt;div class="color" style=background-color:#${result['color 1']}&gt;&lt;h6&gt;${result['color 1']}&lt;/h6&gt;&lt;/div&gt; &lt;div class="color" style=background-color:#${result['color 2']}&gt;&lt;h6&gt;${result['color 2']}&lt;/h6&gt;&lt;/div&gt; &lt;div class="color" style=background-color:#${result['color 3']}&gt;&lt;h6&gt;${result['color 3']}&lt;/h6&gt;&lt;/div&gt; &lt;div class="color" style=background-color:#${result['color 4']}&gt;&lt;h6&gt;${result['color 4']}&lt;/h6&gt;&lt;/div&gt; ${if(result['color 5']){ &lt;div class="color" style=background-color:#${result['color 5']}&gt;&lt;h6&gt;${result['color 5']}&lt;/h6&gt;&lt;/div&gt; } } &lt;div class="color" style=background-color:#${result['color 5']}&gt;&lt;h6&gt;${result['color 5']}&lt;/h6&gt;&lt;/div&gt; &lt;p&gt;on hover change to translucent background and black text for ecah color&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="panel-footer"&gt; &lt;a class="btn btn-info btn-lg" href="update.html?id=${result.id}"&gt;Edit&lt;/a&gt; &lt;a class="btn btn-danger btn-lg"&gt;Delete&lt;/a&gt; &lt;/div&gt; &lt;/div&gt;` ) }) }) </code></pre>
44,488,488
6
3
null
2017-06-11 20:25:27.833 UTC
12
2021-11-16 17:01:30.707 UTC
null
null
null
null
5,210,565
null
1
42
javascript|jquery|ecmascript-6
56,787
<p>You'll need to move your logic into a function or use the ternary operator:</p> <pre><code>`${result['color 5'] ? 'color 5 exists!' : 'color 5 does not exist!'}` </code></pre> <p>Additional example based on comment:</p> <pre><code>`${result['color 5'] ? `&lt;div class="color" style=background-color:#${result['color 5']}&gt;&lt;h6&gt;${result['color 5']}&lt;/h6&gt;&lt;/div&gt;` : ''}` </code></pre>