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
6,192,268
Elegant clean way to include HTML in JavaScript files?
<p>I'm building a small app with a few modal dialog windows. The windows require a tiny bit of HTML. I've hard coded the window HTML in the javascript library but am not thrilled with this solution. Is there a more elegant way to do this? It seems that JavaScript doesn't have multi line strings/heredoc syntax. </p> <pre><code>var html = "&lt;div id='email_window'&gt;&lt;h2&gt;Email Share&lt;/h2&gt;&lt;div&gt;"; html = html + "&lt;form action='javascript:emailDone();' method='post'&gt;"; html = html + "&lt;div&gt;&lt;label for='to'&gt;To&lt;/label&gt;&lt;input id='to' type='text'&gt;&lt;/div&gt;"; html = html + "&lt;div&gt;&lt;label for='from'&gt;From&lt;/label&gt;&lt;input id='from' type='text' value='" + email + "'&gt;&lt;/div&gt;"; html = html + "&lt;div&gt;&lt;label for='subject'&gt;Subject&lt;/label&gt;&lt;input id='subject' type='text' disabled='disabled' value='" + subject + "'&gt;&lt;/div&gt;"; html = html + "&lt;div&gt;&lt;label for='body'&gt;Body&lt;/label&gt;&lt;input id='body' type='text' disabled='disabled' value='" + body + "'&gt;&lt;/div&gt;"; html = html + "&lt;div&gt;&lt;input type='submit' value='Send'&gt;&lt;input type='button' value='Cancel' onClick='javascript:$.fancybox.close();'&gt;&lt;/div&gt;"; html = html + "&lt;/form&gt;&lt;/div&gt;"; $("#data").html(html); </code></pre> <p><strong>Added to clarify the original message-</strong></p> <p>Any solution can't use Ajax/XHR to pull in the template file because the javascript library will be on a different domain that the html file it's included in It's a little like ShareThis. The library will be included on a number of different sites and attached to the onClick event of any anchor tag inside divs with attribute sharetool="true".</p> <p>For example:</p> <pre><code>http://www.bar.com - index.html &lt;html&gt; ... &lt;script type="text/javascript" src="http://www.foo.com/sharetool.js"&gt;&lt;/script&gt; ... &lt;body&gt; &lt;div sharetool="true"&gt; &lt;/div&gt; ... &lt;/html&gt; </code></pre>
6,192,330
7
0
null
2011-05-31 19:05:29.643 UTC
16
2014-04-13 17:55:24.53 UTC
2012-10-15 20:12:31.26 UTC
null
541,091
null
107,380
null
1
29
javascript|jquery
39,631
<p>Templates. Pick your poison</p> <ul> <li><a href="https://github.com/visionmedia/ejs" rel="noreferrer">EJS</a></li> <li><a href="http://api.jquery.com/jquery.tmpl/" rel="noreferrer">jQuery templates</a> (nb: <a href="http://www.borismoore.com/2011/10/jquery-templates-and-jsviews-roadmap.html" rel="noreferrer">development discontinued</a>)</li> <li><a href="http://documentcloud.github.com/underscore/#template" rel="noreferrer">underscore templates</a></li> <li><a href="http://mustache.github.com/" rel="noreferrer">mustache</a></li> <li><a href="http://ejohn.org/blog/javascript-micro-templating/" rel="noreferrer">jResig micro templates</a></li> </ul> <p>Either inline them as script blocks or load them using ajax as external resources. </p> <p>I personally use EJS as external template files and just get EJS to load them and inject them into a container with json data bound to the template.</p> <pre><code>new EJS({ url: "url/to/view" }).update('html_container_name', { "foobar": "Suprise" }); </code></pre> <p>And then view files use generic view logic.</p> <pre><code>// url/to/view &lt;p&gt; &lt;%=foobar %&gt;&lt;/p&gt; </code></pre>
5,776,529
int *array = new int[n]; what is this function actually doing?
<p>I am confused about how to create a dynamic defined array:</p> <pre><code> int *array = new int[n]; </code></pre> <p>I have no idea what this is doing. I can tell it's creating a pointer named array that's pointing to a new object/array int? Would someone care to explain?</p>
5,776,541
8
1
null
2011-04-25 08:16:02.86 UTC
10
2021-11-06 15:26:10.223 UTC
2013-07-07 19:21:11.777 UTC
null
445,131
null
707,485
null
1
30
c++|arrays|pointers|new-operator
138,035
<p><em>new</em> allocates an amount of memory needed to store the object/array that you request. In this case n numbers of int.</p> <p>The pointer will then store the address to this block of memory.</p> <p>But be careful, this allocated block of memory will not be freed until you tell it so by writing</p> <pre><code>delete [] array; </code></pre>
6,293,421
How to print a string multiple times?
<p>How can I repeat a string multiple times, multiple times? I know I can use a for loop, but I would like to repeat a string <code>x</code> times per row, over <code>n</code> rows.</p> <p>For example, if the user enters <code>2</code>, the output would be:</p> <pre><code>@@ @@ @@ @@ </code></pre> <p>Where <code>x</code> equals 2, and <code>n</code> equals 4.</p>
6,293,448
10
5
null
2011-06-09 13:20:56.88 UTC
3
2021-06-26 04:22:20.793 UTC
2020-10-22 04:29:42.85 UTC
null
2,745,495
null
718,531
null
1
12
python
212,011
<pre><code>for i in range(3): print "Your text here" </code></pre> <p>Or</p> <pre><code>for i in range(3): print("Your text here") </code></pre>
5,725,278
How do I use pdfminer as a library
<p>I am trying to get text data from a pdf using <a href="http://www.unixuser.org/~euske/python/pdfminer/index.html" rel="noreferrer">pdfminer</a>. I am able to extract this data to a .txt file successfully with the pdfminer command line tool pdf2txt.py. I currently do this and then use a python script to clean up the .txt file. I would like to incorporate the pdf extract process into the script and save myself a step. </p> <p><a href="https://stackoverflow.com/questions/25665/python-module-for-converting-pdf-to-text">I thought I was on to something when I found this link</a>, but I didn't have success with any of the solutions. Perhaps the function listed there needs to be updated again because I am using a newer version of pdfminer. </p> <p><a href="http://www.herblainchbury.com/2010/05/opendatabc-extracting-data-from-a4ca.html" rel="noreferrer">I also tried the function shown here, but it also did not work.</a> </p> <p>Another approach I tried was to call the script within a script using <code>os.system</code>. This was also unsuccessful.</p> <p>I am using Python version 2.7.1 and pdfminer version 20110227.</p>
8,325,135
15
3
null
2011-04-20 03:50:00.03 UTC
54
2022-03-21 15:41:13.297 UTC
2017-05-23 11:47:11.08 UTC
null
-1
null
716,364
null
1
74
python|pdf|pdfminer
86,871
<p>Here is a cleaned up version I finally produced that worked for me. The following just simply returns the string in a PDF, given its filename. I hope this saves someone time.</p> <pre><code>from pdfminer.pdfinterp import PDFResourceManager, process_pdf from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from cStringIO import StringIO def convert_pdf(path): rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) fp = file(path, 'rb') process_pdf(rsrcmgr, device, fp) fp.close() device.close() str = retstr.getvalue() retstr.close() return str </code></pre> <p>This solution was valid until <a href="https://github.com/euske/pdfminer/#api-changes" rel="noreferrer">API changes in November 2013</a>.</p>
39,053,451
Using spread with duplicate identifiers for rows
<p>I have a long form dataframe that have multiple entries for same date and person. </p> <pre><code>jj &lt;- data.frame(month=rep(1:3,4), student=rep(c("Amy", "Bob"), each=6), A=c(9, 7, 6, 8, 6, 9, 3, 2, 1, 5, 6, 5), B=c(6, 7, 8, 5, 6, 7, 5, 4, 6, 3, 1, 5)) </code></pre> <p>I want to convert it to wide form and make it like this:</p> <pre><code>month Amy.A Bob.A Amy.B Bob.B 1 2 3 1 2 3 1 2 3 1 2 3 </code></pre> <p>My question is very similar to <a href="https://stackoverflow.com/questions/30592094/r-spreading-multiple-columns-with-tidyr">this</a>. I have used the given code in the answer :</p> <pre><code>kk &lt;- jj %&gt;% gather(variable, value, -(month:student)) %&gt;% unite(temp, student, variable) %&gt;% spread(temp, value) </code></pre> <p>but it gives following error:</p> <blockquote> <p>Error: Duplicate identifiers for rows (1, 4), (2, 5), (3, 6), (13, 16), (14, 17), (15, 18), (7, 10), (8, 11), (9, 12), (19, 22), (20, 23), (21, 24)</p> </blockquote> <p>Thanks in advance. Note: I don't want to delete multiple entries.</p>
39,053,597
4
1
null
2016-08-20 11:11:45.117 UTC
7
2019-09-14 22:49:35.18 UTC
2017-05-23 12:02:21.55 UTC
null
-1
null
5,868,054
null
1
30
r|dplyr|tidyr
44,677
<p>The issue is the two columns for both <code>A</code> and <code>B</code>. If we can make that one value column, we can spread the data as you would like. Take a look at the output for <code>jj_melt</code> when you use the code below.</p> <pre><code>library(reshape2) jj_melt &lt;- melt(jj, id=c("month", "student")) jj_spread &lt;- dcast(jj_melt, month ~ student + variable, value.var="value", fun=sum) # month Amy_A Amy_B Bob_A Bob_B # 1 1 17 11 8 8 # 2 2 13 13 8 5 # 3 3 15 15 6 11 </code></pre> <p>I won't mark this as a duplicate since the other question did not summarize by <code>sum</code>, but the <code>data.table</code> answer could help with one additional argument, <code>fun=sum</code>:</p> <pre><code>library(data.table) dcast(setDT(jj), month ~ student, value.var=c("A", "B"), fun=sum) # month A_sum_Amy A_sum_Bob B_sum_Amy B_sum_Bob # 1: 1 17 8 11 8 # 2: 2 13 8 13 5 # 3: 3 15 6 15 11 </code></pre> <p>If you would like to use the <code>tidyr</code> solution, combine it with <code>dcast</code> to summarize by <code>sum</code>.</p> <pre><code>as.data.frame(jj) library(tidyr) jj %&gt;% gather(variable, value, -(month:student)) %&gt;% unite(temp, student, variable) %&gt;% dcast(month ~ temp, fun=sum) # month Amy_A Amy_B Bob_A Bob_B # 1 1 17 11 8 8 # 2 2 13 13 8 5 # 3 3 15 15 6 11 </code></pre> <p><strong>Edit</strong></p> <p>Based on your new requirements, I have added an activity column.</p> <pre><code>library(dplyr) jj %&gt;% group_by(month, student) %&gt;% mutate(id=1:n()) %&gt;% melt(id=c("month", "id", "student")) %&gt;% dcast(... ~ student + variable, value.var="value") # month id Amy_A Amy_B Bob_A Bob_B # 1 1 1 9 6 3 5 # 2 1 2 8 5 5 3 # 3 2 1 7 7 2 4 # 4 2 2 6 6 6 1 # 5 3 1 6 8 1 6 # 6 3 2 9 7 5 5 </code></pre> <p>The other solutions can also be used. Here I added an optional expression to arrange the final output by activity number:</p> <pre><code>library(tidyr) jj %&gt;% gather(variable, value, -(month:student)) %&gt;% unite(temp, student, variable) %&gt;% group_by(temp) %&gt;% mutate(id=1:n()) %&gt;% dcast(... ~ temp) %&gt;% arrange(id) # month id Amy_A Amy_B Bob_A Bob_B # 1 1 1 9 6 3 5 # 2 2 2 7 7 2 4 # 3 3 3 6 8 1 6 # 4 1 4 8 5 5 3 # 5 2 5 6 6 6 1 # 6 3 6 9 7 5 5 </code></pre> <p>The <code>data.table</code> syntax is compact because it allows for multiple <code>value.var</code> columns and will take care of the spread for us. We can then skip the <code>melt -&gt; cast</code> process.</p> <pre><code>library(data.table) setDT(jj)[, activityID := rowid(student)] dcast(jj, ... ~ student, value.var=c("A", "B")) # month activityID A_Amy A_Bob B_Amy B_Bob # 1: 1 1 9 3 6 5 # 2: 1 4 8 5 5 3 # 3: 2 2 7 2 7 4 # 4: 2 5 6 6 6 1 # 5: 3 3 6 1 8 6 # 6: 3 6 9 5 7 5 </code></pre>
25,008,472
Pagination in Spring Data JPA (limit and offset)
<p>I want the user to be able to specify the limit (the size of the amount returned) and offset (the first record returned / index returned) in my query method. </p> <p>Here are my classes without any paging capabilities. My entity:</p> <pre><code>@Entity public Employee { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column(name="NAME") private String name; //getters and setters } </code></pre> <p>My repository:</p> <pre><code>public interface EmployeeRepository extends JpaRepository&lt;Employee, Integer&gt; { @Query("SELECT e FROM Employee e WHERE e.name LIKE :name ORDER BY e.id") public List&lt;Employee&gt; findByName(@Param("name") String name); } </code></pre> <p>My service interface:</p> <pre><code>public interface EmployeeService { public List&lt;Employee&gt; findByName(String name); } </code></pre> <p>My service implementation:</p> <pre><code>public class EmployeeServiceImpl { @Resource EmployeeRepository repository; @Override public List&lt;Employee&gt; findByName(String name) { return repository.findByName(name); } } </code></pre> <p>Now here is my attempt at providing paging capabilities that support offset and limit. My entity class remains the same.</p> <p>My "new" repository takes in a pageable parameter:</p> <pre><code>public interface EmployeeRepository extends JpaRepository&lt;Employee, Integer&gt; { @Query("SELECT e FROM Employee e WHERE e.name LIKE :name ORDER BY e.id") public List&lt;Employee&gt; findByName(@Param("name") String name, Pageable pageable); } </code></pre> <p>My "new" service interface takes in two additional parameters:</p> <pre><code>public interface EmployeeService { public List&lt;Employee&gt; findByName(String name, int offset, int limit); } </code></pre> <p>My "new" service implementation:</p> <pre><code>public class EmployeeServiceImpl { @Resource EmployeeRepository repository; @Override public List&lt;Employee&gt; findByName(String name, int offset, int limit) { return repository.findByName(name, new PageRequest(offset, limit); } } </code></pre> <p>This however isn't what i want. PageRequest specifies the page and size (page # and the size of the page). Now specifying the size is exactly what I want, however, I don't want to specify the starting page #, I want the user to be able to specify the starting record / index. I want something similar to</p> <pre><code>public List&lt;Employee&gt; findByName(String name, int offset, int limit) { TypedQuery&lt;Employee&gt; query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.name LIKE :name ORDER BY e.id", Employee.class); query.setFirstResult(offset); query.setMaxResults(limit); return query.getResultList(); } </code></pre> <p>Specifically the setFirstResult() and setMaxResult() methods. But I can't use this method because I want to use the Employee repository interface. (Or is it actually better to define queries through the entityManager?) Anyways, is there a way to specify the offset without using the entityManager? Thanks in advance! </p>
36,365,522
8
1
null
2014-07-29 04:56:39.037 UTC
31
2022-07-08 08:01:27.737 UTC
2015-03-19 11:48:46.597 UTC
null
142,983
null
3,814,650
null
1
65
spring|jpa|pagination|spring-data|paging
131,598
<p>Below code should do it. I am using in my own project and tested for most cases.</p> <p>usage:</p> <pre><code> Pageable pageable = new OffsetBasedPageRequest(offset, limit); return this.dataServices.findAllInclusive(pageable); </code></pre> <p>and the source code:</p> <pre><code>import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.springframework.data.domain.AbstractPageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import java.io.Serializable; /** * Created by Ergin **/ public class OffsetBasedPageRequest implements Pageable, Serializable { private static final long serialVersionUID = -25822477129613575L; private int limit; private int offset; private final Sort sort; /** * Creates a new {@link OffsetBasedPageRequest} with sort parameters applied. * * @param offset zero-based offset. * @param limit the size of the elements to be returned. * @param sort can be {@literal null}. */ public OffsetBasedPageRequest(int offset, int limit, Sort sort) { if (offset &lt; 0) { throw new IllegalArgumentException(&quot;Offset index must not be less than zero!&quot;); } if (limit &lt; 1) { throw new IllegalArgumentException(&quot;Limit must not be less than one!&quot;); } this.limit = limit; this.offset = offset; this.sort = sort; } /** * Creates a new {@link OffsetBasedPageRequest} with sort parameters applied. * * @param offset zero-based offset. * @param limit the size of the elements to be returned. * @param direction the direction of the {@link Sort} to be specified, can be {@literal null}. * @param properties the properties to sort by, must not be {@literal null} or empty. */ public OffsetBasedPageRequest(int offset, int limit, Sort.Direction direction, String... properties) { this(offset, limit, new Sort(direction, properties)); } /** * Creates a new {@link OffsetBasedPageRequest} with sort parameters applied. * * @param offset zero-based offset. * @param limit the size of the elements to be returned. */ public OffsetBasedPageRequest(int offset, int limit) { this(offset, limit, Sort.unsorted()); } @Override public int getPageNumber() { return offset / limit; } @Override public int getPageSize() { return limit; } @Override public int getOffset() { return offset; } @Override public Sort getSort() { return sort; } @Override public Pageable next() { return new OffsetBasedPageRequest(getOffset() + getPageSize(), getPageSize(), getSort()); } public OffsetBasedPageRequest previous() { return hasPrevious() ? new OffsetBasedPageRequest(getOffset() - getPageSize(), getPageSize(), getSort()) : this; } @Override public Pageable previousOrFirst() { return hasPrevious() ? previous() : first(); } @Override public Pageable first() { return new OffsetBasedPageRequest(0, getPageSize(), getSort()); } @Override public boolean hasPrevious() { return offset &gt; limit; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OffsetBasedPageRequest)) return false; OffsetBasedPageRequest that = (OffsetBasedPageRequest) o; return new EqualsBuilder() .append(limit, that.limit) .append(offset, that.offset) .append(sort, that.sort) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(limit) .append(offset) .append(sort) .toHashCode(); } @Override public String toString() { return new ToStringBuilder(this) .append(&quot;limit&quot;, limit) .append(&quot;offset&quot;, offset) .append(&quot;sort&quot;, sort) .toString(); } } </code></pre>
27,529,486
Do Immutable.js or Lazy.js perform short-cut fusion?
<p>First, let me define what is <a href="https://www.haskell.org/haskellwiki/Short_cut_fusion" rel="noreferrer">short-cut fusion</a> for those of you who don't know. Consider the following array transformation in JavaScript:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var a = [1,2,3,4,5].map(square).map(increment); console.log(a); function square(x) { return x * x; } function increment(x) { return x + 1; }</code></pre> </div> </div> </p> <p>Here we have an array, <code>[1,2,3,4,5]</code>, whose elements are first squared, <code>[1,4,9,16,25]</code>, and then incremented <code>[2,5,10,17,26]</code>. Hence, although we don't need the intermediate array <code>[1,4,9,16,25]</code>, we still create it.</p> <p>Short-cut fusion is an optimization technique which can get rid of intermediate data structures by merging some functions calls into one. For example, short-cut fusion can be applied to the above code to produce:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var a = [1,2,3,4,5].map(compose(square, increment)); console.log(a); function square(x) { return x * x; } function increment(x) { return x + 1; } function compose(g, f) { return function (x) { return f(g(x)); }; }</code></pre> </div> </div> </p> <p>As you can see, the two separate <code>map</code> calls have been fused into a single <code>map</code> call by composing the <code>square</code> and <code>increment</code> functions. Hence the intermediate array is not created.</p> <hr /> <p>Now, I understand that libraries like <a href="https://github.com/facebook/immutable-js" rel="noreferrer">Immutable.js</a> and <a href="http://philosopherdeveloper.com/posts/introducing-lazy-js.html" rel="noreferrer">Lazy.js</a> emulate lazy evaluation in JavaScript. Lazy evaluation means that results are only computed when required.</p> <p>For example, consider the above code. Although we <code>square</code> and <code>increment</code> each element of the array, yet we may not need all the results.</p> <p>Suppose we only want the first 3 results. Using Immutable.js or Lazy.js we can get the first 3 results, <code>[2,5,10]</code>, without calculating the last 2 results, <code>[17,26]</code>, because they are not needed.</p> <p>However, lazy evaluation just delays the calculation of results until required. It does not remove intermediate data structures by fusing functions.</p> <p>To make this point clear, consider the following code which emulates lazy evaluation:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var List = defclass({ constructor: function (head, tail) { if (typeof head !== "function" || head.length &gt; 0) Object.defineProperty(this, "head", { value: head }); else Object.defineProperty(this, "head", { get: head }); if (typeof tail !== "function" || tail.length &gt; 0) Object.defineProperty(this, "tail", { value: tail }); else Object.defineProperty(this, "tail", { get: tail }); }, map: function (f) { var l = this; if (l === nil) return nil; return cons(function () { return f(l.head); }, function () { return l.tail.map(f); }); }, take: function (n) { var l = this; if (l === nil || n === 0) return nil; return cons(function () { return l.head; }, function () { return l.tail.take(n - 1); }); }, mapSeq: function (f) { var l = this; if (l === nil) return nil; return cons(f(l.head), l.tail.mapSeq(f)); } }); var nil = Object.create(List.prototype); list([1,2,3,4,5]) .map(trace(square)) .map(trace(increment)) .take(3) .mapSeq(log); function cons(head, tail) { return new List(head, tail); } function list(a) { return toList(a, a.length, 0); } function toList(a, length, i) { if (i &gt;= length) return nil; return cons(a[i], function () { return toList(a, length, i + 1); }); } function square(x) { return x * x; } function increment(x) { return x + 1; } function log(a) { console.log(a); } function trace(f) { return function () { var result = f.apply(this, arguments); console.log(f.name, JSON.stringify([...arguments]), result); return result; }; } function defclass(prototype) { var constructor = prototype.constructor; constructor.prototype = prototype; return constructor; }</code></pre> </div> </div> </p> <p>As you can see, the function calls are interleaved and only the first three elements of the array are processed, proving that the results are indeed computed lazily:</p> <pre><code>square [1] 1 increment [1] 2 2 square [2] 4 increment [4] 5 5 square [3] 9 increment [9] 10 10 </code></pre> <p>If lazy evaluation is not used then the result would be:</p> <pre><code>square [1] 1 square [2] 4 square [3] 9 square [4] 16 square [5] 25 increment [1] 2 increment [4] 5 increment [9] 10 increment [16] 17 increment [25] 26 2 5 10 </code></pre> <p>However, if you see the source code then each function <code>list</code>, <code>map</code>, <code>take</code> and <code>mapSeq</code> returns an intermediate <code>List</code> data structure. No short-cut fusion is performed.</p> <hr /> <p>This brings me to my main question: do libraries like Immutable.js and Lazy.js perform short-cut fusion?</p> <p>The reason I ask is because according to the documentation, they “apparently” do. However, I am skeptical. I have my doubts whether they actually perform short-cut fusion.</p> <p>For example, this is taken from the <a href="https://github.com/facebook/immutable-js/blob/master/README.md" rel="noreferrer">README.md</a> file of Immutable.js:</p> <blockquote> <p><code>Immutable</code> also provides a lazy <code>Seq</code>, allowing efficient chaining of collection methods like <code>map</code> and <code>filter</code> without creating intermediate representations. Create some <code>Seq</code> with <code>Range</code> and <code>Repeat</code>.</p> </blockquote> <p>So the developers of Immutable.js claim that their <code>Seq</code> data structure allows efficient chaining of collection methods like <code>map</code> and <code>filter</code> <strong>without creating intermediate representations</strong> (i.e. they perform short-cut fusion).</p> <p>However, I don't see them doing so in their <a href="https://github.com/facebook/immutable-js/blob/master/src/Seq.js" rel="noreferrer">code</a> anywhere. Perhaps I can't find it because they are using ES6 and my eyes aren't all too familiar with ES6 syntax.</p> <p>Furthermore, in their documentation for <a href="https://github.com/facebook/immutable-js/blob/master/README.md#lazy-seq" rel="noreferrer">Lazy Seq</a> they mention:</p> <blockquote> <p><code>Seq</code> describes a lazy operation, allowing them to efficiently chain use of all the Iterable methods (such as <code>map</code> and <code>filter</code>).</p> <p><strong>Seq is immutable</strong> — Once a Seq is created, it cannot be changed, appended to, rearranged or otherwise modified. Instead, any mutative method called on a Seq will return a new Seq.</p> <p><strong>Seq is lazy</strong> — Seq does as little work as necessary to respond to any method call.</p> </blockquote> <p>So it is established that <code>Seq</code> is indeed lazy. However, there are no examples to show that <em>intermediate representations are indeed not created</em> (which they claim to be doing).</p> <hr /> <p>Moving on to Lazy.js we have the same situation. Thankfully, Daniel Tao wrote a <a href="http://philosopherdeveloper.com/posts/introducing-lazy-js.html" rel="noreferrer">blog post</a> on how Lazy.js works, in which he mentions that at its heart Lazy.js simply does function composition. He gives the following example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>Lazy.range(1, 1000) .map(square) .filter(multipleOf3) .take(10) .each(log); function square(x) { return x * x; } function multipleOf3(x) { return x % 3 === 0; } function log(a) { console.log(a); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://rawgit.com/dtao/lazy.js/master/lazy.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>Here the <code>map</code>, <code>filter</code> and <code>take</code> functions produce intermediate <code>MappedSequence</code>, <code>FilteredSequence</code> and <code>TakeSequence</code> objects. These <code>Sequence</code> objects are essentially iterators, which eliminate the need of intermediate arrays.</p> <p>However, from what I understand, there is still no short-cut fusion taking place. The intermediate array structures are simply replaced with intermediate <code>Sequence</code> structures which are not fused.</p> <p>I could be wrong, but I believe that expressions like <code>Lazy(array).map(f).map(g)</code> produce two separate <code>MappedSequence</code> objects in which the first <code>MappedSequence</code> object feeds its values to the second one, instead of the second one replacing the first one by doing the job of both (via function composition).</p> <p><strong>TLDR:</strong> Do Immutable.js and Lazy.js indeed perform short-cut fusion? As far as I know they get rid of intermediate arrays by emulating lazy evaluation via sequence objects (i.e. iterators). However, I believe that these iterators are chained: one iterator feeding its values lazily to the next. They are not merged into a single iterator. Hence they do not “eliminate intermediate representations“. They only transform arrays into constant space sequence objects.</p>
27,532,894
1
2
null
2014-12-17 15:49:26.053 UTC
17
2017-10-15 20:31:30.313 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
783,743
null
1
34
javascript|lazy-evaluation|immutable.js|lazy.js
3,160
<p>I'm the author of Immutable.js (and a fan of Lazy.js).</p> <p>Does Lazy.js and Immutable.js's Seq use short-cut fusion? No, not exactly. But they do remove intermediate representation of operation results.</p> <p>Short-cut fusion is a code compilation/transpilation technique. Your example is a good one:</p> <pre><code>var a = [1,2,3,4,5].map(square).map(increment); </code></pre> <p>Transpiled:</p> <pre><code>var a = [1,2,3,4,5].map(compose(square, increment)); </code></pre> <p>Lazy.js and Immutable.js are not transpilers and will not re-write code. They are runtime libraries. So instead of short-cut fusion (a compiler technique) they use iterable composition (a runtime technique).</p> <p>You answer this in your TLDR:</p> <blockquote> <p>As far as I know they get rid of intermediate arrays by emulating lazy evaluation via sequence objects (i.e. iterators). However, I believe that these iterators are chained: one iterator feeding its values lazily to the next. They are not merged into a single iterator. Hence they do not "eliminate intermediate representations". They only transform arrays into constant space sequence objects.</p> </blockquote> <p>That is exactly right.</p> <p>Let's unpack:</p> <p>Arrays store intermediate results when chaining:</p> <pre><code>var a = [1,2,3,4,5]; var b = a.map(square); // b: [1,4,6,8,10] created in O(n) var c = b.map(increment); // c: [2,5,7,9,11] created in O(n) </code></pre> <p>Short-cut fusion transpilation creates intermediate functions:</p> <pre><code>var a = [1,2,3,4,5]; var f = compose(square, increment); // f: Function created in O(1) var c = a.map(f); // c: [2,5,7,9,11] created in O(n) </code></pre> <p>Iterable composition creates intermediate iterables:</p> <pre><code>var a = [1,2,3,4,5]; var i = lazyMap(a, square); // i: Iterable created in O(1) var j = lazyMap(i, increment); // j: Iterable created in O(1) var c = Array.from(j); // c: [2,5,7,9,11] created in O(n) </code></pre> <p>Note that using iterable composition, we have not created a store of intermediate results. When these libraries say they do not create intermediate representations - what they mean is exactly what is described in this example. No data structure is created holding the values <code>[1,4,6,8,10]</code>.</p> <p>However, of course <strong>some</strong> intermediate representation is made. Each "lazy" operation must return something. They return an iterable. Creating these is extremely cheap and not related to the size of the data being operated on. Note that in short-cut fusion transpilation, an intermediate representation is also made. The result of <code>compose</code> is a new function. Functional composition (hand-written or the result of a short-cut fusion compiler) is very related to Iterable composition.</p> <p>The goal of removing intermediate representations is performance, especially regarding memory. Iterable composition is a powerful way to implement this and does not require the overhead that parsing and rewriting code of an optimizing compiler which would be out of place in a runtime library.</p> <hr> <p>Appx:</p> <p>This is what a simple implementation of <code>lazyMap</code> might look like:</p> <pre><code>function lazyMap(iterable, mapper) { return { "@@iterator": function() { var iterator = iterable["@@iterator"](); return { next: function() { var step = iterator.next(); return step.done ? step : { done: false, value: mapper(step.value) } } }; } }; } </code></pre>
42,187,188
Can you migrate AWS Cognito users between user pools?
<p>I am using AWS Cognito. I have a pretty common scenario: users can register in different roles. Depending on the role different user attributes are required, so I need to use different user pools.</p> <p>Now a user wants to upgrade from role A to role B - thus I would have to move his account from one pool to another. Is this possible with AWS? The response in <a href="https://stackoverflow.com/questions/40059151/can-you-export-migrate-users-out-of-aws-cognito-does-it-cause-vendor-lock-in">Can you export/migrate users out of AWS cognito, does it cause vendor lock-in?</a> seems to indicate the opposite.</p> <p>If not possible this way, what would be a viable solution to achieve requiring different user attributes depending on different user roles with AWS Cognito. (NOTE: requiring / verifying them only on the front end is <em>not</em> a viable solution)</p>
49,546,395
1
2
null
2017-02-12 11:47:42.28 UTC
8
2019-09-27 12:01:36.41 UTC
2017-05-23 12:08:55.76 UTC
null
-1
null
1,977,182
null
1
16
amazon-web-services|authentication|amazon-cognito
16,025
<p>I know this question is a bit dated, but it is possible that this scenario is best solved by using Groups instead of a separate user pool for each role. See <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html" rel="noreferrer">here</a></p> <p>If you reach this link to find out how to transfer users to a new pool (for instance, you needed to create a new user pool in order to change how your users log in), then there isn't a built in way to do this. However, there are solutions that you could build in order to migrate users, which is referenced <a href="https://aws.amazon.com/blogs/mobile/migrating-users-to-amazon-cognito-user-pools/" rel="noreferrer">here</a>:</p> <ol> <li>Create your new user pool.</li> <li><p>Modify your client to do the following:</p> <ul> <li>On failed sign in with new user pool, attempt sign in with old user pool.</li> <li>If existing user pool sign in is successful, use the username and password that was submitted to the existing sign in to create a user on the new user pool.</li> <li>Possibly do something to remove the user from the old user pool or mark as migrated.</li> </ul></li> </ol> <p><a href="https://i.stack.imgur.com/FiASl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FiASl.png" alt="enter image description here"></a></p> <p>You can export users and import them to a new user pool with a CSV file, but <strong>your users will have to change their password.</strong></p>
34,009,992
Python ElementTree default namespace?
<p>Is there a way to define the default/unprefixed namespace in python ElementTree? This doesn't seem to work...</p> <pre><code>ns = {"":"http://maven.apache.org/POM/4.0.0"} pom = xml.etree.ElementTree.parse("pom.xml") print(pom.findall("version", ns)) </code></pre> <p>Nor does this:</p> <pre><code>ns = {None:"http://maven.apache.org/POM/4.0.0"} pom = xml.etree.ElementTree.parse("pom.xml") print(pom.findall("version", ns)) </code></pre> <p>This does, but then I have to prefix every element:</p> <pre><code>ns = {"mvn":"http://maven.apache.org/POM/4.0.0"} pom = xml.etree.ElementTree.parse("pom.xml") print(pom.findall("mvn:version", ns)) </code></pre> <p>Using Python 3.5 on OSX.</p> <p>EDIT: if the answer is "no", you can still get the bounty :-). I just want a definitive "no" from someone who's spent a lot of time using it.</p>
35,165,997
3
1
null
2015-11-30 23:33:53.53 UTC
9
2021-12-11 10:39:35.333 UTC
2018-03-05 14:56:38.69 UTC
null
3,357,935
null
125,601
null
1
25
python|xml|python-3.x|namespaces|elementtree
16,608
<p>NOTE: for Python 3.8+ please see <a href="https://stackoverflow.com/a/62398604/771848">this answer</a>.</p> <hr /> <p>There is no straight-forward way to handle the default namespaces transparently. Assigning the empty namespace a non-empty name is a common solution, as you've already mentioned:</p> <pre><code>ns = {&quot;mvn&quot;:&quot;http://maven.apache.org/POM/4.0.0&quot;} pom = xml.etree.ElementTree.parse(&quot;pom.xml&quot;) print(pom.findall(&quot;mvn:version&quot;, ns)) </code></pre> <p>Note that <code>lxml.etree</code> does not allow the use of empty namespaces explicitly. You would get:</p> <blockquote> <p><code>ValueError</code>: empty namespace prefix is not supported in ElementPath</p> </blockquote> <hr /> <p>You can though, make things simpler, by <a href="http://auxmem.com/2014/07/07/suppressing-the-default-namespace-in-elementtree/" rel="nofollow noreferrer">removing the default namespace definition</a> while loading the XML input data:</p> <pre><code>import xml.etree.ElementTree as ET import re with open(&quot;pom.xml&quot;) as f: xmlstring = f.read() # Remove the default namespace definition (xmlns=&quot;http://some/namespace&quot;) xmlstring = re.sub(r'\sxmlns=&quot;[^&quot;]+&quot;', '', xmlstring, count=1) pom = ET.fromstring(xmlstring) print(pom.findall(&quot;version&quot;)) </code></pre>
47,216,731
How can I use `def` in Jenkins Pipeline?
<p>I am learning <a href="https://www.jenkins.io/doc/book/pipeline/" rel="nofollow noreferrer">Jenkins Pipeline</a>, and I tried to follow this Pipeline <a href="https://github.com/azure-devops/movie-db-java-on-azure/blob/master/Jenkinsfile-data-app#L19" rel="nofollow noreferrer">code</a>. But my Jenkins always complains that <code>def</code> is not legal.</p> <p>I am wondering did I miss any plugins? I already installed <code>groovy</code>, <code>job-dsl</code>, but it doesn't work.</p>
47,218,620
3
2
null
2017-11-10 06:19:12.32 UTC
9
2021-11-16 08:51:31.987 UTC
2021-11-16 08:51:31.987 UTC
null
814,702
null
1,241,464
null
1
21
jenkins|jenkins-plugins|jenkins-pipeline
38,420
<p>As @Rob said, There are 2 types of pipelines: <code>scripted</code> and <code>declarative</code>. It is like <code>imperative</code> vs <code>declarative</code>. <code>def</code> is only allowed in <code>scripted</code> pipeline or wrapped in <code>script {}</code>.</p> <h2>Scripted pipeline (Imperative)</h2> <p>Start with <code>node</code>, and <code>def</code> or <code>if</code> is allowed, like below. It is traditional way.</p> <pre><code>node { stage('Example') { if (env.BRANCH_NAME == 'master') { echo 'I only execute on the master branch' } else { echo 'I execute elsewhere' } } } </code></pre> <h2>Declarative pipeline (Preferred)</h2> <p>Start with <code>pipeline</code>, and <code>def</code> or <code>if</code> is NOT allowed, unless it is wrapped in <code>script {...}</code>. Declarative pipeline make a lot things easy to write and read.</p> <h3>time trigger</h3> <pre><code>pipeline { agent any triggers { cron('H 4/* 0 0 1-5') } stages { stage('Example') { steps { echo 'Hello World' } } } } </code></pre> <h3>when</h3> <pre><code>pipeline { agent any stages { stage('Example Build') { steps { echo 'Hello World' } } stage('Example Deploy') { when { branch 'production' } steps { echo 'Deploying' } } } } </code></pre> <h3>Parallel</h3> <pre><code>pipeline { agent any stages { stage('Non-Parallel Stage') { steps { echo 'This stage will be executed first.' } } stage('Parallel Stage') { when { branch 'master' } failFast true parallel { stage('Branch A') { agent { label &quot;for-branch-a&quot; } steps { echo &quot;On Branch A&quot; } } stage('Branch B') { agent { label &quot;for-branch-b&quot; } steps { echo &quot;On Branch B&quot; } } } } } } </code></pre> <h3>embedded with scripted code</h3> <pre><code>pipeline { agent any stages { stage('Example') { steps { echo 'Hello World' script { def browsers = ['chrome', 'firefox'] for (int i = 0; i &lt; browsers.size(); ++i) { echo &quot;Testing the ${browsers[i]} browser&quot; } } } } } } </code></pre> <p>To read more declarative pipeline grammar, please refer the official doc <a href="https://jenkins.io/doc/book/pipeline/syntax/" rel="noreferrer">here</a></p>
47,095,019
How to use Array.prototype.filter with async?
<h2>Background</h2> <p>I am trying to filter an array of objects. Before I filter, I need to convert them to some format, and this operation is asynchronous. </p> <pre><code> const convert = () =&gt; new Promise( resolve =&gt; { setTimeout( resolve, 1000 ); }); </code></pre> <p>So, my first try was to do something like the following using async/await:</p> <pre><code>const objs = [ { id: 1, data: "hello" }, { id: 2, data: "world"} ]; objs.filter( async ( obj ) =&gt; { await convert(); return obj.data === "hello"; }); </code></pre> <p>Now, as some of you may know, <code>Array.protoype.filter</code> is a function which callback <strong>must return either true or false</strong>. <code>filter</code> is synchronous. In the previous example, I am returning none of them, I return a Promise ( all async functions are Promises ). </p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter</a></p> <p>So as one can assume, the code before doesn't really work... That assumption is correct.</p> <h2>Problem</h2> <p>To make filter work with an async function, I checked stackoverflow and found this topic:</p> <p><a href="https://stackoverflow.com/questions/33355528/filtering-an-array-with-a-function-that-returns-a-promise">Filtering an array with a function that returns a promise</a></p> <p>Unfortunately, the chosen answer is overly complex and uses classes. This won't do for me. I am instead looking for a more simple solution, using simple functions with a functional approach. </p> <p>There is one solution at the very end, using a map with a callback to simulate a filter:</p> <p><a href="https://stackoverflow.com/a/46842181/1337392">https://stackoverflow.com/a/46842181/1337392</a></p> <p>But I was hoping to fix my filter function, not to replace it.</p> <h2>Questions</h2> <ul> <li>Is there a way to have an async function inside a filter?</li> <li>If not, what is the simplest replacement I can do?</li> </ul>
47,095,184
7
2
null
2017-11-03 11:45:31.68 UTC
8
2022-09-01 23:43:13.637 UTC
null
null
null
null
1,337,392
null
1
66
javascript|arrays|filter|async-await
42,332
<p>There is no way to use filter with an async function (at least that I know of). The simplest way that you have to use filter with a collection of promises is to use <code>Promise.all</code> and then apply the function to your collection of results. It would look something like this:</p> <pre><code>const results = await Promise.all(your_promises) const filtered_results = results.filter(res =&gt; //do your filtering here) </code></pre> <p>Hope it helps.</p>
10,571,170
How many comparisons will binary search make in the worst case using this algorithm?
<p>Hi there below is the pseudo code for my binary search implementation:</p> <pre><code>Input: (A[0...n-1], K) begin l ← 0; r ← n-1 while l ≤ r do m ← floor((l+r)/2) if K &gt; A[m] then l ← m+1 else if K &lt; A[m] then r ← m-1 else return m end if end while return -1 // key not found end </code></pre> <p>I was just wondering how to calculate the number of comparisons this implementation would make in the worst case for a sorted array of size n?</p> <p>Would the number of comparisons = lg n + 1? or something different?</p>
10,571,300
3
1
null
2012-05-13 10:57:43.313 UTC
6
2015-09-07 14:56:36.203 UTC
2012-05-13 11:58:08.183 UTC
null
1,391,566
null
1,391,566
null
1
20
arrays|algorithm|complexity-theory|binary-search
58,851
<p>The worst-case in this case is, if the element K is not present in A and smaller than all elements in A. Then we have two comparisons in each step: <code>K &gt; A[m]</code> and <code>K &lt; A[m]</code>.</p> <p>For in each step the array is being cut into two parts, each of the size <code>(n-1)/2</code>, we have a maximum of <code>log_2(n-1)</code> steps.</p> <p>This leads to a total of <code>2*log_2(n-1)</code> comparisons, which asymptotically indeed equals to <code>O(log(n))</code>.</p>
10,436,454
Replacing a substring of a string with Python
<p>I'd like to get a few opinions on the best way to replace a substring of a string with some other text. Here's an example:</p> <p>I have a string, a, which could be something like "Hello my name is $name". I also have another string, b, which I want to insert into string a in the place of its substring '$name'.</p> <p>I assume it would be easiest if the replaceable variable is indicated some way. I used a dollar sign, but it could be a string between curly braces or whatever you feel would work best.</p> <p><strong>Solution:</strong> Here's how I decided to do it:</p> <pre><code>from string import Template message = 'You replied to $percentageReplied of your message. ' + 'You earned $moneyMade.' template = Template(message) print template.safe_substitute( percentageReplied = '15%', moneyMade = '$20') </code></pre>
10,436,832
6
1
null
2012-05-03 17:30:00.33 UTC
10
2016-03-29 20:27:48.407 UTC
2016-03-29 20:27:48.407 UTC
null
42,223
null
492,348
null
1
23
python|string|substring|string-interpolation
24,606
<p>Here are the most common ways to do it:</p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; t = string.Template("Hello my name is $name") &gt;&gt;&gt; print t.substitute(name='Guido') Hello my name is Guido &gt;&gt;&gt; t = "Hello my name is %(name)s" &gt;&gt;&gt; print t % dict(name='Tim') Hello my name is Tim &gt;&gt;&gt; t = "Hello my name is {name}" &gt;&gt;&gt; print t.format(name='Barry') Hello my name is Barry </code></pre> <p>The approach using <a href="http://docs.python.org/library/string.html#template-strings" rel="noreferrer">string.Template</a> is easy to learn and should be familiar to bash users. It is suitable for exposing to end-users. This style became available in Python 2.4.</p> <p>The <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" rel="noreferrer">percent-style</a> will be familiar to many people coming from other programming languages. Some people find this style to be error-prone because of the trailing "s" in <code>%(name)s</code>, because the %-operator has the same precedence as multiplication, and because the behavior of the applied arguments depends on their data type (tuples and dicts get special handling). This style has been supported in Python since the beginning.</p> <p>The <a href="http://docs.python.org/library/string.html#format-string-syntax" rel="noreferrer">curly-bracket style</a> is only supported in Python 2.6 or later. It is the most flexible style (providing a rich set of control characters and allowing objects to implement custom formatters).</p>
19,185,596
Spock - Testing Exceptions with Data Tables
<p>How can exceptions be tested in a nice way (e.g. data tables) with Spock?</p> <p>Example: Having a method <code>validateUser</code> that can throw exceptions with different messages or no exception if the user is valid.</p> <p>The specification class itself:</p> <pre><code>class User { String userName } class SomeSpec extends spock.lang.Specification { ...tests go here... private validateUser(User user) { if (!user) throw new Exception ('no user') if (!user.userName) throw new Exception ('no userName') } } </code></pre> <p><strong>Variant 1</strong></p> <p>This one is working but the real intention is cluttered by all the <em>when</em> / <em>then</em> labels and the repeated calls of <code>validateUser(user)</code>.</p> <pre><code> def 'validate user - the long way - working but not nice'() { when: def user = new User(userName: 'tester') validateUser(user) then: noExceptionThrown() when: user = new User(userName: null) validateUser(user) then: def ex = thrown(Exception) ex.message == 'no userName' when: user = null validateUser(user) then: ex = thrown(Exception) ex.message == 'no user' } </code></pre> <p><strong>Variant 2</strong></p> <p>This one is not working because of this error raised by Spock at compile time:</p> <p><em>Exception conditions are only allowed in 'then' blocks</em></p> <pre><code> def 'validate user - data table 1 - not working'() { when: validateUser(user) then: check() where: user || check new User(userName: 'tester') || { noExceptionThrown() } new User(userName: null) || { Exception ex = thrown(); ex.message == 'no userName' } null || { Exception ex = thrown(); ex.message == 'no user' } } </code></pre> <p><strong>Variant 3</strong></p> <p>This one is not working because of this error raised by Spock at compile time:</p> <p><em>Exception conditions are only allowed as top-level statements</em></p> <pre><code> def 'validate user - data table 2 - not working'() { when: validateUser(user) then: if (expectedException) { def ex = thrown(expectedException) ex.message == expectedMessage } else { noExceptionThrown() } where: user || expectedException | expectedMessage new User(userName: 'tester') || null | null new User(userName: null) || Exception | 'no userName' null || Exception | 'no user' } </code></pre>
19,187,445
7
1
null
2013-10-04 15:54:37.07 UTC
22
2019-11-14 12:14:03.963 UTC
null
null
null
null
2,847,174
null
1
68
exception|testing|groovy|spock
35,925
<p>The recommended solution is to have two methods: one that tests the good cases, and another that tests the bad cases. Then both methods can make use of data tables.</p> <p>Example:</p> <pre><code>class SomeSpec extends Specification { class User { String userName } def 'validate valid user'() { when: validateUser(user) then: noExceptionThrown() where: user &lt;&lt; [ new User(userName: 'tester'), new User(userName: 'joe')] } def 'validate invalid user'() { when: validateUser(user) then: def error = thrown(expectedException) error.message == expectedMessage where: user || expectedException | expectedMessage new User(userName: null) || Exception | 'no userName' new User(userName: '') || Exception | 'no userName' null || Exception | 'no user' } private validateUser(User user) { if (!user) throw new Exception('no user') if (!user.userName) throw new Exception('no userName') } } </code></pre>
28,057,430
What is the Access Token vs. Access Token Secret and Consumer Key vs. Consumer Secret
<p>I have been using Oauth for a while but have never been completely sure of the difference between these four terms (and the functionality of each). I frequently see (for instance in the Twitter Public API)</p> <p><code>Consumer key:</code></p> <p><code>Consumer secret:</code></p> <p><code>Access token:</code></p> <p>and</p> <p><code>Access token secret:</code></p> <p>field but I have never known exactly what they do. I know that Oauth has the ability to authorize apps (let them act on a user's behalf) but I do not understand the relationship between these four authorization terms and would love an explanation. </p> <p>Basically, I am not sure how the access token or token secret are generated, where they are stored, and what relation they have to each other or to the consumer key and secret.</p> <p>Thank you</p>
28,057,700
2
1
null
2015-01-21 00:02:43.213 UTC
31
2020-03-08 14:33:27.57 UTC
null
null
null
null
3,291,506
null
1
83
oauth
61,854
<p><strong>Consumer key</strong> is the API key that a service provider (Twitter, Facebook, etc.) issues to a consumer (a service that wants to access a user's resources on the service provider). This key is what identifies the consumer.</p> <p><strong>Consumer secret</strong> is the consumer &quot;password&quot; that is used, along with the consumer key, to request access (i.e. authorization) to a user's resources from a service provider.</p> <p><strong>Access token</strong> is what is issued to the consumer by the service provider once the consumer completes authorization. This token defines the access privileges of the consumer over a particular user's resources. Each time the consumer wants to access the user's data from that service provider, the consumer includes the access token in the API request to the service provider.</p> <p>Hope that clears it up. I would recommend skimming through the beginning of the <a href="https://www.rfc-editor.org/rfc/rfc6749" rel="nofollow noreferrer">oAuth 2.0 spec</a>. It's really informative.</p>
2,332,349
Best practices for cross platform git config?
<h2>Context</h2> <p>A number of my application user configuration files are kept in a git repository for easy sharing across multiple machines and multiple platforms. Amongst these configuration files is <code>.gitconfig</code> which contains the following settings for handling the carriage return linefeed characters</p> <pre><code>[core] autocrlf = true safecrlf = false </code></pre> <h2>Problem</h2> <p>These settings also gets applied on a GNU/Linux platform which causes obscure errors. </p> <h2>Question</h2> <p>What are some best practices for handling these platform specific differences in configuration files? </p> <h2>Proposed solution</h2> <p>I realize this problem could be solved by having a branch for each platform and keeping the common stuff in master and merging with the platform branch when master moves forward. I'm wondering if there are any <em>easier</em> solutions to this problem?</p>
2,361,309
3
1
2010-02-25 07:26:02.683 UTC
2010-02-25 07:26:02.683 UTC
37
2016-11-26 19:06:31.113 UTC
2010-04-04 09:15:01.683 UTC
null
164,901
null
74,198
null
1
57
git|git-config
36,485
<p>I have reviewed that kind of config setting (<code>crlf</code>) extensively in the question:<br> <strong><a href="https://stackoverflow.com/questions/2333424/distributing-git-configuration-with-the-code/2354278#2354278">distributing git configuration with the code</a></strong>.</p> <p>The conclusion was:</p> <ul> <li><strong><a href="https://stackoverflow.com/questions/1206406/dealing-with-files-that-git-refuses-to-reset/1206441#1206441">checkout/checking .gitattributes</a></strong> files</li> <li>list all types which explicitly need that kind of conversion.<br> For instance:</li> </ul> <pre> *.java +crlf *.txt +crlf ... </pre> <ul> <li>avoid doing any kind of conversion of type of files which don't need it, because of the various side-effect of such a conversion on merges, <code>git status</code>, shell environment and <code>svn import</code> (see "<a href="https://stackoverflow.com/questions/2333424/distributing-git-configuration-with-the-code/2354278#2354278">distributing git configuration with the code</a>" for links and references).</li> <li>avoid any <code>crlf</code> conversion altogether if you can.</li> </ul> <hr> <p>Now, regarding the specific issue of <strong>per-platform settings</strong>, branch is not always the right tool, especially for non-program related data (i.e; those settings are not related to what you are developing, only to the VCS storing the history of your development)</p> <p>As stated in the question <a href="https://stackoverflow.com/questions/431201/git-how-to-maintain-two-branches-of-a-project-and-merge-only-shared-data">Git: How to maintain two branches of a project and merge only shared data?</a>:</p> <blockquote> <p>your life will be vastly simpler if you put the system-dependent code in different directories and deal with the cross-platform dependencies in the build system (Makefiles or whatever you use).</p> </blockquote> <p>In this case, while branches could be use for system-dependent code, I would recommend directory for support tools system-dependent settings, with a script able to build the appropriate <code>.gitattributes</code> file to apply the right setting depending on the repo deployment platform.</p>
2,049,330
C# variable scoping: 'x' cannot be declared in this scope because it would give a different meaning to 'x'
<pre><code>if(true) { string var = "VAR"; } string var = "New VAR!"; </code></pre> <p>This will result in:</p> <blockquote> <p>Error 1 A local variable named 'var' cannot be declared in this scope because it would give a different meaning to 'var', which is already used in a 'child' scope to denote something else.</p> </blockquote> <p>Nothing earth shattering really, but isn't this just plain wrong? A fellow developer and I were wondering if the first declaration should be in a different scope, thus the second declaration cannot interfere with the first declaration. </p> <p>Why is C# unable to differentiate between the two scopes? Should the first IF scope not be completely separate from the rest of the method?</p> <p>I cannot call var from outside the if, so the error message is wrong, because the first var has no relevance in the second scope.</p>
2,049,377
3
9
null
2010-01-12 13:51:15.13 UTC
13
2017-02-17 11:50:06.777 UTC
2017-02-17 11:50:06.777 UTC
null
226,958
user1144
null
null
1
66
c#|scope
19,573
<p>The issue here is largely one of good practice and preventing against inadvertent mistakes. Admittedly, the C# compiler <em>could theoretically</em> be designed such that there is no conflict between scopes here. This would however be much effort for little gain, as I see it.</p> <p>Consider that if the declaration of <code>var</code> in the parent scope were <em>before</em> the if statement, there would be an unresolvable naming conflict. The compiler simply does not differentiate between the following two cases. Analysis is done <em>purely based on scope</em>, and not order of declaration/use, as you seem to be expecting.</p> <p>The theoretically acceptable (but still invalid as far as C# is concerned):</p> <pre><code>if(true) { string var = "VAR"; } string var = "New VAR!"; </code></pre> <p>and the unacceptable (since it would be hiding the parent variable):</p> <pre><code>string var = "New VAR!"; if(true) { string var = "VAR"; } </code></pre> <p>are both treated precisely the same in terms of variables and scopes.</p> <p>Now, is there any actual reason in this secenario why you can't just give one of the variables a different name? I assume (hope) your actual variables aren't called <code>var</code>, so I don't really see this being a problem. If you're still intent on reusing the same variable name, just put them in sibling scopes:</p> <pre><code>if(true) { string var = "VAR"; } { string var = "New VAR!"; } </code></pre> <p>This however, while valid to the compiler, can lead to some amount of confusion when reading the code, so I recommend against it in almost any case.</p>
1,745,165
Looping Over Result Sets in MySQL
<p>I am trying to write a stored procedure in MySQL which will perform a somewhat simple select query, and then loop over the results in order to decide whether to perform additional queries, data transformations, or discard the data altogether. Effectively, I want to implement this:</p> <pre><code>$result = mysql_query("SELECT something FROM somewhere WHERE some stuff"); while ($row = mysql_fetch_assoc($result)) { // check values of certain fields, decide to perform more queries, or not // tack it all into the returning result set } </code></pre> <p>Only, I want it only in MySQL, so it can be called as a procedure. I know that for triggers, there is the <code>FOR EACH ROW ...</code> syntax, but I can't find mention of anything like this for use outside of the <code>CREATE TRIGGER ...</code> syntax. I have read through some of the looping mechanisms in MySQL, but so far all I can imagine is that I would be implementing something like this:</p> <pre><code>SET @S = 1; LOOP SELECT * FROM somewhere WHERE some_conditions LIMIT @S, 1 -- IF NO RESULTS THEN LEAVE -- DO SOMETHING SET @S = @S + 1; END LOOP </code></pre> <p>Although even this is somewhat hazy in my mind. </p> <p>For reference, though I don't think it's necessarily relevant, the initial query will be joining four tables together to form a model of hierarchal permissions, and then based on how high up the chain a specific permission is, it will retrieve additional information about the children to which that permission should be inherited.</p>
1,745,292
3
2
null
2009-11-16 22:09:19.107 UTC
26
2022-05-22 19:29:59.673 UTC
2021-12-22 19:35:12.63 UTC
null
4,294,399
null
173,925
null
1
76
mysql|loops|stored-procedures|database-cursor
180,081
<p>Something like this should do the trick (However, read after the snippet for more info)</p> <pre><code>CREATE PROCEDURE GetFilteredData() BEGIN DECLARE bDone INT; DECLARE var1 CHAR(16); -- or approriate type DECLARE var2 INT; DECLARE var3 VARCHAR(50); DECLARE curs CURSOR FOR SELECT something FROM somewhere WHERE some stuff; DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1; DROP TEMPORARY TABLE IF EXISTS tblResults; CREATE TEMPORARY TABLE IF NOT EXISTS tblResults ( --Fld1 type, --Fld2 type, --... ); OPEN curs; SET bDone = 0; REPEAT FETCH curs INTO var1, var2, var3; IF whatever_filtering_desired -- here for whatever_transformation_may_be_desired INSERT INTO tblResults VALUES (var1, var2, var3); END IF; UNTIL bDone END REPEAT; CLOSE curs; SELECT * FROM tblResults; END </code></pre> <p><strong>A few things to consider...</strong></p> <p>Concerning the snippet above:</p> <ul> <li>may want to pass part of the query to the Stored Procedure, maybe particularly the search criteria, to make it more generic.</li> <li>If this method is to be called by multiple sessions etc. may want to pass a Session ID of sort to create a unique temporary table name (actually unnecessary concern since different sessions do not share the same temporary file namespace; see comment by Gruber, below)</li> <li>A few parts such as the variable declarations, the SELECT query etc. need to be properly specified</li> </ul> <p>More generally: <strong>trying to avoid needing a cursor</strong>.</p> <p>I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.</p> <p>Maybe you can look into expressing the transformation and filtering desired in the context of a &quot;plain&quot; (declarative) SQL query.</p>
8,992,840
Getting correct call stacks in VS Concurrency profiler
<p>I'm using the VS Concurrency profiler to profile a WPF application, but I can't get symbols for NGen'ned images like PresentationCore et al, so my call stacks all look like:</p> <p><img src="https://i.stack.imgur.com/SvpUz.png" alt=""></p> <p>Is there a way to make VS do the right thing here? <strong>Edit:</strong> I have correctly configured my symbol paths, that's not the issue.</p>
8,993,588
1
1
null
2012-01-24 19:28:39.187 UTC
13
2012-06-08 15:32:40.153 UTC
2012-06-08 15:32:40.153 UTC
null
1,569
null
5,728
null
1
14
wpf|visual-studio|profiler
1,645
<p>Figured this one out - if you follow the steps <a href="http://blogs.msdn.com/b/sburke/archive/2008/01/29/how-to-disable-optimizations-when-debugging-reference-source.aspx" rel="noreferrer">here</a>, it works out pretty well. Here's the short version:</p> <ol> <li>Start an elevated CMD prompt</li> <li><code>set COMPLUS_ZapDisable=1</code></li> <li><code>"%ProgramFiles(x86)%\Microsoft Visual Studio 10.0\Common7\ide\devenv.exe"</code></li> <li>Go into your csproj settings, Debug Tab, and Disable the VS Hosting Process</li> <li>Kick off the profiler - your app will be a fair bit slower because you're not using the NGen DLLs but it'll still be proportionally accurate in the profile result.</li> </ol>
19,380,738
Mongoose nested query on Model by field of its referenced model
<p>It seems like there is a lot of Q/A's on this topic on stackoverflow, but I can't seem to find an exact answer anywhere. </p> <p><strong>What I have:</strong></p> <p>I have Company and Person models:</p> <pre><code>var mongoose = require('mongoose'); var PersonSchema = new mongoose.Schema{ name: String, lastname: String}; // company has a reference to Person var CompanySchema = new mongoose.Schema{ name: String, founder: {type:Schema.ObjectId, ref:Person}}; </code></pre> <p><strong>What I need:</strong></p> <p>Find all companies that people with lastname "Robertson" have founded</p> <p><strong>What I tried:</strong></p> <pre><code>Company.find({'founder.id': 'Robertson'}, function(err, companies){ console.log(companies); // getting an empty array }); </code></pre> <p>Then I figured that Person is not embedded but referenced, so I used populate to populate founder-Person and then tried to use find with 'Robertson' lastname</p> <pre><code>// 1. retrieve all companies // 2. populate their founders // 3. find 'Robertson' lastname in populated Companies Company.find({}).populate('founder') .find({'founder.lastname': 'Robertson'}) .exec(function(err, companies) { console.log(companies); // getting an empty array again }); </code></pre> <p>I still can query companies with Person's id as a String. But it's not exactly what I want as you can understand</p> <pre><code>Company.find({'founder': '525cf76f919dc8010f00000d'}, function(err, companies){ console.log(companies); // this works }); </code></pre>
19,381,833
3
0
null
2013-10-15 12:03:30.693 UTC
19
2021-02-04 13:26:06.773 UTC
null
null
null
null
1,874,278
null
1
31
node.js|mongodb|mongoose|populate
33,782
<p>You can't do this in a single query because MongoDB doesn't support joins. Instead, you have to break it into a couple steps:</p> <pre class="lang-js prettyprint-override"><code>// Get the _ids of people with the last name of Robertson. Person.find({lastname: 'Robertson'}, {_id: 1}, function(err, docs) { // Map the docs into an array of just the _ids var ids = docs.map(function(doc) { return doc._id; }); // Get the companies whose founders are in that set. Company.find({founder: {$in: ids}}, function(err, docs) { // docs contains your answer }); }); </code></pre>
19,788,661
Change JavaFx Tab default Look
<p>I am trying to change the default look of JavaFx tabs using css.</p> <p>I managed to achieve following.</p> <p><img src="https://i.stack.imgur.com/6H0BB.png" alt="enter image description here"></p> <p>What I am looking for is there should not be left gap on first tab.</p> <p>Can somebody please point me in right direction on how to achieve it.</p> <p>Below is the output I am trying to achieve.</p> <p><img src="https://i.stack.imgur.com/zueag.png" alt="enter image description here"></p> <p>I have used following CSS</p> <pre><code>.tab-pane .tab-header-area .tab-header-background { -fx-opacity: 0; } .tab-pane { -fx-tab-min-width:90px; } .tab{ -fx-background-insets: 0 1 0 1,0,0; } .tab-pane .tab { -fx-background-color: #e6e6e6; } .tab-pane .tab:selected { -fx-background-color: #3c3c3c; } .tab .tab-label { -fx-alignment: CENTER; -fx-text-fill: #828282; -fx-font-size: 12px; -fx-font-weight: bold; } .tab:selected .tab-label { -fx-alignment: CENTER; -fx-text-fill: #96b946; } </code></pre>
19,792,996
1
1
null
2013-11-05 12:09:06.91 UTC
13
2017-04-04 11:11:12.113 UTC
null
null
null
null
758,104
null
1
31
tabs|javafx
45,944
<p>You should also override the CSS:</p> <pre><code>.tab-pane:top *.tab-header-area { -fx-background-insets: 0, 0 0 1 0; /* -fx-padding: 0.416667em 0.166667em 0.0em 0.833em; /* 5 2 0 10 */ -fx-padding: 0.416667em 0.166667em 0.0em 0.0em; /* overridden as 5 2 0 0 */ } </code></pre> <p>Here the left padding value of the tab-header-area changed from 10 to 0. In addition you need to override other CSS selectors: <code>.tab-pane:bottom</code>, <code>.tab-pane:left</code> and <code>.tab-pane:right</code> in the same manner for different <code>javafx.geometry.Side</code>s of the TabPane.</p>
19,751,420
MongooseJS - How to find the element with the maximum value?
<p>I am using MongoDB , MongooseJS and Nodejs.</p> <p>I have a Collection ( called Member ) with the following Fields - </p> <p>Country_id , Member_id , Name, Score </p> <p>I want to write a query which returns the Member with the max Score where Country id = 10 </p> <p>I couldnt find suitable documentation for this in MongooseJS.</p> <p>I found this at StackOVerflow ( this is MongoDB code )</p> <pre><code>Model.findOne({ field1 : 1 }).sort(last_mod, 1).run( function(err, doc) { var max = doc.last_mod; }); </code></pre> <p>But how do I translate the same to MongooseJS ?</p>
19,751,733
5
1
null
2013-11-03 09:16:56.18 UTC
3
2019-05-21 17:48:08.07 UTC
2017-09-22 17:57:57.377 UTC
null
-1
null
609,235
null
1
29
node.js|mongodb|mongoose|max|database
33,789
<pre><code>Member .findOne({ country_id: 10 }) .sort('-score') // give me the max .exec(function (err, member) { // your callback code }); </code></pre> <p>Check <a href="http://mongoosejs.com/docs/queries.html" rel="noreferrer">the mongoose docs for querying</a>, they are pretty good.</p> <p>If you dont't want to write the same code again you could also add a static method to your Member model like this:</p> <pre><code>memberSchema.statics.findMax = function (callback) { this.findOne({ country_id: 10 }) // 'this' now refers to the Member class .sort('-score') .exec(callback); } </code></pre> <p>And call it later via <code>Member.findMax(callback)</code></p>
889,431
What should a "beginning developer" know about architectures and planning
<p>I've been working with C and C# for ages, I consider myself a "pretty good" programmer, but as has been pointed out many times, programming is only a small facet of software engineering and development. I'm the sole coder for my department but it looks like that is going to begin to change, what I would like to know from the Stackoverflow community is the following.</p> <ul> <li><strong>What does it take to move from coder to developer</strong> - I've read Code Complete so I think i'm ready to take that plunge. To some degree I already am.</li> <li><strong>What tools should I use when doing models of my software</strong> - assume C#</li> <li><strong>How deeply should I model my architecture before setting down hard and fast code?</strong> - I realize how subjective this question is, and I'd like rules of thumb more than "well it depends." Assume i'm writing in house tools that are intended to "last 5-10 years"</li> <li><strong>What advice would you be willing to give to someone making the move from codeing to engineering?</strong></li> </ul> <p>Thank you all in advance! Have a great Memorial day!</p>
889,718
4
2
null
2009-05-20 18:17:46.983 UTC
13
2009-07-21 14:46:35.977 UTC
2009-05-20 19:55:19.297 UTC
null
72,871
null
72,871
null
1
8
architecture
1,509
<p>Firstly the generic answers:</p> <ul> <li>Understand that <em>any</em> given tool is not a silver bullet to fix all your problems. So when you're reading about MVC or Functional Programming or someone is spewing that LISP will solve all your problems, they won't. They may solve a whole bunch of problems you have, but they won't solve them all. In many cases in addition to solving some problems, they'll introduce a whole bunch of others.</li> <li>Understand the limitations and advantages of different components/technologies/tools at your fingertips for providing solutions to any given problem. Make your decisions based upon evalauation of all the advantages and drawbacks - don't make your decisions blindly.</li> <li>Pick the right tools for the job, including language, development, integration techniques.</li> <li>Who will be maintaining the code? Code to the expected audience. If that's you, don't expect that six months from now when you're expected to provide a fix that you'll remember what your thought process was today... write code that reads simply and document your thought process. Not the "how" - the code does that, but the "why". No matter how easy to read your code is, it cannot tell you <em>why</em> you did it that way. Code comments are for the why, not the how.</li> <li>Understand your users, how they work, their mentality towards their tools, what their jobs are, what their attitude towards the learning curve for your software is.</li> <li>Understand the mentality of the person/team that will be supporting your application - this means installation too.</li> <li>Understand the need for source control and use it.</li> <li>Backups, always assume and prepare for the worst, if you don't you'll wish you did.</li> <li>Learn how to write software specifications, technical specifications, test documentation, user documentation.</li> <li>FAT/SAT/UAT testing and signoff procedures.</li> <li>Set lower expectations than you're capable of delivering, don't promise the client a Lambourghini and deliver a Volkswagon Beetle [Bug]. Much better to promise the Beetle [Bug] and deliver a Mercedes.</li> <li>Don't overcomplicate <em>anything</em> - that includes architecturally, programmatically or anything else. Documentation should be simple to read, the interface should be simple to use.</li> </ul> <p>Now the specifics:</p> <ul> <li>Understand that you must research the problem and understand the problem domain before you can provide <em>any</em> kind of solution, architectural or otherwise.</li> <li>Understand what the users expect will be delivered, how it will be delivered and how they will interact with it.</li> <li>Find the least technically adept person that will be using your solution, if they can understand it, everyone else will too.</li> <li>Design your software for your <em>users</em> as well as your financiers. If those you deliver it to can't/won't use it, you're never going to hear the end of it - even if your financiers are initially satisfied, they will very quickly recant.</li> </ul> <p><strong>Failure to plan is to plan for failure</strong></p> <p>Your environment, software needs, target audience, network support staff, budget and any number of other factors will greatly affect the solutions you provide. For instance, in the type of environment I code for, I tend to draw on a finite set of tools for delivery of products, and they will likely vary for your environment:</p> <ul> <li>Web browsers - IE/Firefox/Opera/Safari</li> <li>Application/File servers - Windows Server, Linux, Unix</li> <li>Web servers - IIS/Apache</li> <li>Web application development - ASP.NET/C#/VB.NET/ASP/PHP/JavaScript/AJAX/MVC</li> <li>Console application development - BAT/C#/VB.NET [Don't write a full blown C# app if a BAT file will do the job much more simply].</li> <li>Windows application development - C#/VB.NET</li> <li>Data maintenance - C#/VB.NET/Excel/VBA</li> <li>Database servers - SQL Server, MySQL, Oracle</li> <li>Network/Data/File integration services - MSMQ, BizTalk, SonicMQ, FTP</li> </ul> <p>I may use one or more of these technologies for my solution dependent entirely upon what is being asked of me. The key is to understanding which is relevant for a given situation and only using those necessary. For instance don't write a full blown web application if a command line utility can easily be used by a single user, don't write a Windows application if many users need access to an application that can't easily be installed on their machines due to user restrictions and limited systems support personnel. Don't write a command line utility for users that can barely navigate around windows with their mouse and don't expect a Microsoft expert to support your *nix based system.</p> <p>Provide diagrams and documentation that make it simple to diagnose issues so that when problems <em>are</em> found [and they <em>will</em> be], users/deskside support can easily narrow down the problem to a particular component in the system. This will make your life easier because they'll either be able to fix it themselves or provide you with enough information to fix the problem quickly and simply.</p> <p><strong>Edit</strong>: in response to your comment regarding UML which is great for the purpose, but once again you have to be aware of your target audience. If you're a lone programmer that's developing systems for a small client whose personnel don't understand UML, you'd be just as well providing a regular flow-chart decorated with simple English. If your target audience is a software consultancy whose business is software development, then by all means, UML is a great tool - especially as with some UML tools, you can have it automatically generate your stub classes/methods for you to automate some of the process. I tend to work in small teams for small companies so I don't use UML as much as I'd like, and probably don't understand it as well as I should, but that's not to say that if I was required I wouldn't brush up on it. It's a great tool to have in your toolbox but don't use it just for the sake of it. Everything you use in the design/architecture/development of your solution should be used for an objective reason - don't just use/learn it blindly because someone says "you should use this because it's great".</p> <p>The key to good architecture is this:</p> <ul> <li>Understand the tools you're using</li> <li>Understand the reasons you should and shouldn't use the tools you have for any given purpose</li> <li>Make informed decisions objectively, don't base them on hearsay or emotion.</li> </ul> <p>And most of all:</p> <ul> <li>Use your common sense!! If something doesn't sound or feel right, figure out why that is, worst case is that you'll find out you were wrong and you've corrected a misunderstanding/misconception, best case you saved a lot of time pursuing an incorrect and potentially expensive option based on that misconception - either way you're better off than you were.</li> </ul>
127,936
Deleting Custom Event Log Source Without Using Code
<p>I have an application that has created a number of custom event log sources to help filter its output. How can I delete the custom sources from the machine WITHOUT writing any code as running a quick program using System.Diagnostics.EventLog.Delete is not possible.</p> <p>I've tried using RegEdit to remove the custom sources from [HKEY_LOCAL_MACHINE\SYSTEM\ControlSetXXX\Services\Eventlog] however the application acts as if the logs still exist behind the scenes.</p> <p>What else am I missing?</p>
128,704
4
0
null
2008-09-24 15:38:26.477 UTC
14
2016-12-08 08:39:02.443 UTC
null
null
null
Wolfwyrd
15,570
null
1
46
c#|windows|event-log
46,217
<p>I also think you're in the right place... it's stored in the registry, under the name of the event log. I have a custom event log, under which are multiple event sources.</p> <blockquote> <p>HKLM\System\CurrentControlSet\Services\Eventlog\LOGNAME\LOGSOURCE1 HKLM\System\CurrentControlSet\Services\Eventlog\LOGNAME\LOGSOURCE2</p> </blockquote> <p>Those sources have an <em>EventMessageFile</em> key, which is <em>REG_EXPAND_SZ</em> and points to: </p> <blockquote> <p>C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll</p> </blockquote> <p>I think if you delete the Key that is the log source, LOGSOURCE1 in my example, that should be all that's needed.</p> <p>For what it's worth, I tried it through .NET and that's what it did. However, it does look like each custom event log also has a source of the same name. If you have a custom log, that could affect your ability to clear it. You'd have to delete the log outright, perhaps. Further, if your app has an installer, I can see that the application name also may be registered as a source in the application event log. One more place to clear.</p>
1,095,718
Diff two tabs in Vim
<p>Scenario: I have opened Vim and pasted some text. I open a second tab with <code>:tabe</code> and paste some other text in there.</p> <p>Goal: I would like a third tab with a output equivalent to writing both texts to files and opening them with <code>vimdiff</code>.</p> <p>The closest I can find is "diff the current buffer against a file", but not <code>diff</code>ing two open but unsaved buffers.</p>
1,098,521
4
3
null
2009-07-08 01:34:57.333 UTC
59
2018-03-01 11:01:20.977 UTC
2012-06-05 00:11:33.723 UTC
null
21,115
null
21,115
null
1
123
vim|diff|tabs|vimdiff|buffer
38,833
<p>I suggest opening the second file in the same tab instead of a new one.</p> <p>Here's what I usually do:</p> <pre><code>:edit file1 :diffthis :vnew :edit file2 :diffthis </code></pre> <p>The <a href="http://vimdoc.sourceforge.net/htmldoc/windows.html#:vnew" rel="noreferrer"><code>:vnew</code></a> command splits the current view vertically so you can open the second file there. The <a href="http://vimdoc.sourceforge.net/htmldoc/diff.html#:diffthis" rel="noreferrer"><code>:diffthis</code></a> (or short: <code>:difft</code>) command is then applied to each view.</p>
128,263
How do you determine a valid SoapAction?
<p>I'm calling a <code>webservice</code> using the <code>NuSoap PHP library</code>. The <code>webservice</code> appears to use <code>.NET</code>; every time I call it I get an error about using an invalid <code>SoapAction header</code>. The header being sent is an empty string. How can I find the <code>SoapAction</code> that the server is expecting?</p>
128,457
1
0
null
2008-09-24 16:39:51.397 UTC
4
2015-06-05 21:48:47.137 UTC
2015-06-05 21:48:47.137 UTC
null
4,248,328
richardg
null
null
1
17
php|web-services|soap
59,694
<p>You can see the SoapAction that the service operation you're calling expects by looking at the WSDL for the service. For .NET services, you can access the WSDL by opening a web browser to the url of the service and appending ?wsdl on the end.</p> <p>Inside the WSDL document, you can see the SoapActions defined under the 'Operation' nodes (under 'Bindings'). For example:</p> <pre><code>&lt;wsdl:operation name="Execute"&gt; &lt;soap:operation soapAction="http://tempuri.org/Execute" style="document" /&gt; </code></pre> <p>Find the operation node for the operation you're trying to invoke, and you'll find the Soap Action it expects there.</p>
42,257,354
Concat a video with itself, but in reverse, using ffmpeg
<p>I was able to reverse with:</p> <pre><code>ffmpeg -i input.mp4 -vf reverse output_reversed.mp4 </code></pre> <p>And I can concat with:</p> <pre><code>ffmpeg -i input.mp4 -i input.mp4 -filter_complex "[0:0] [0:1] [1:0] [1:1] concat=n=2:v=1:a=1 [v] [a]" -map "[v]" -map "[a]" output.mp4 </code></pre> <p>But can I concat with a reverse version of the video, with a single command?</p> <p>What I am trying to achieve is a ping pong effect, where the video plays once, then plays backwards right after.</p> <p>Thanks!</p>
42,257,863
1
0
null
2017-02-15 18:28:48.83 UTC
10
2018-11-11 14:09:07.457 UTC
null
null
null
null
7,396,678
null
1
23
video|ffmpeg|reverse
9,296
<p>Technically, you can do it using</p> <pre><code>ffmpeg -i input.mp4 -filter_complex "[0:v]reverse,fifo[r];[0:v][0:a][r] [0:a]concat=n=2:v=1:a=1 [v] [a]" -map "[v]" -map "[a]" output.mp4 </code></pre> <p>But the reverse filter will use a lot of memory for large videos. I've added a <code>fifo</code> filter to avoid frame drops. But test and see. (I haven't reversed the audio)</p> <p>If your clip has no audio, the above command will throw an error – instead, use:</p> <pre><code>ffmpeg -i input.mp4 -filter_complex "[0:v]reverse,fifo[r];[0:v][r] concat=n=2:v=1 [v]" -map "[v]" output.mp4 </code></pre>
39,573,571
.NET Core console application, how to configure appSettings per environment?
<p>I have a .NET Core 1.0.0 console application and two environments. I need to be able to use <code>appSettings.dev.json</code> and <code>appSettings.test.json</code> based on environment variables I set at run time. This seems to be quite straight forward for ASP.NET Core web applications, via dependency injection and IHostingEnvironment and the EnvironmentName env. variable, however how should I wire things up for the console application (besides writing my own custom code that uses <code>Microsoft.Framework.Configuration.EnvironmentVariables</code>)? </p> <p>Thank you. </p>
40,620,561
10
0
null
2016-09-19 12:46:43.523 UTC
22
2022-08-11 06:22:05.23 UTC
null
null
null
null
2,916,547
null
1
98
c#|console-application|.net-core
110,683
<p>This is how we do it in our <code>.netcore</code> console app. The key here is to include the right <strong>dependencies</strong> on your project namely (<em>may be not all, check based on your needs</em>) and <strong>copy to output</strong> the appSetting.json as part of your <strong>buildoptions</strong></p> <pre class="lang-json prettyprint-override"><code> { &quot;buildOptions&quot;: { &quot;emitEntryPoint&quot;: true, &quot;copyToOutput&quot;: { &quot;include&quot;: [ &quot;appsettings*.json&quot;, &quot;App*.config&quot; ] } }, </code></pre> <pre class="lang-cs prettyprint-override"><code>using Microsoft.Extensions.Configuration; namespace MyApp { public static void Main(string[] args) { var environmentName = Environment.GetEnvironmentVariable(&quot;ASPNETCORE_ENVIRONMENT&quot;); var builder = new ConfigurationBuilder() .AddJsonFile($&quot;appsettings.json&quot;, true, true) .AddJsonFile($&quot;appsettings.{environmentName}.json&quot;, true, true) .AddEnvironmentVariables(); var configuration = builder.Build(); var myConnString= configuration.GetConnectionString(&quot;SQLConn&quot;); } } </code></pre>
21,905,377
How to open chrome in Selenium webdriver?
<p>I'm trying to launch chrome with <code>Selenium Webdriver</code> and used the following code: </p> <pre><code>System.setProperty("webdriver.chrome.driver", "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"); WebDriver driver=new ChromeDriver(); driver.get("http://www.yahoo.com"); </code></pre> <p>Chrome browser opens but is not proceeding further. What could be the reason for the following error:</p> <pre><code>Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure. </code></pre>
21,905,509
5
0
null
2014-02-20 10:46:08.94 UTC
null
2021-06-01 05:30:06.953 UTC
2017-09-19 11:14:30.56 UTC
null
7,755,936
null
2,814,359
null
1
0
google-chrome|selenium-webdriver
76,803
<p>Use the latest versions of ChromeDriver.</p> <p><strong>Source|</strong></p> <pre><code>http://chromedriver.storage.googleapis.com/index.html </code></pre>
21,556,961
Intercept JAX-RS Request: Register a ContainerRequestFilter with tomcat
<p>I am trying to intercept a request to my JAX-RS webservice by a ContainerRequestFilter. I want to use it with a custom annotation, so I can decorate certain methods of the webservice. This should enable me to handle requests to this methods based on the information whether they are made on a secure channel or not, before the actual method is executed.</p> <p>I tried different approaches, searched several posts and then implemented mostly based on the answer by Alden in this <a href="https://stackoverflow.com/questions/19785001/custom-method-annotation-using-jerseys-abstracthttpcontextinjectable-not-workin/20611842#20611842">post</a>. But I can't get it working.</p> <p>I have a method test in my webservice decorated with my custom annotation Ssl.</p> <pre><code>@POST @Path("/test") @Ssl public static Response test(){ System.out.println("TEST ..."); } </code></pre> <p>The annotation looks like this:</p> <pre><code>@NameBinding @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface Ssl {} </code></pre> <p>Then I setup a filter implementation</p> <pre><code>import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.ext.Provider; @Ssl @Provider public class SslInterceptor implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { System.out.println("Filter executed."); } } </code></pre> <p>But the filter is never executed nor there occur any error messages or warnings. The test method runs fine anyway. </p> <p>To resolve it, I tried to register the filter in the web.xml as described <a href="https://stackoverflow.com/questions/17300218/jersey-containerrequestfilter-not-triggered">here</a>.</p> <pre><code>&lt;servlet&gt; &lt;servlet-name&gt;Jersey Web Application&lt;/servlet-name&gt; &lt;servlet-class&gt;com.sun.jersey.spi.container.servlet.ServletContainer&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.config.property.resourceConfigClass&lt;/param-name&gt; &lt;param-value&gt;com.sun.jersey.api.core.PackagesResourceConfig&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.config.property.packages&lt;/param-name&gt; &lt;param-value&gt;com.my.packagewithfilter&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.spi.container.ContainerRequestFilters&lt;/param-name&gt; &lt;param-value&gt;com.my.packagewithfilter.SslInterceptor&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;jersey.config.server.provider.packages&lt;/param-name&gt; &lt;param-value&gt;com.my.packagewithfilter&lt;/param-value&gt; &lt;/init-param&gt; &lt;/servlet&gt; </code></pre> <p>But that also doesn't work. What am I missing? Any ideas how to make that filter work? Any help is really appreciated!</p>
21,578,954
3
0
null
2014-02-04 15:48:19.96 UTC
4
2017-07-24 16:06:25.38 UTC
2017-05-23 10:31:37.83 UTC
null
-1
null
3,271,380
null
1
10
java|web-services|rest|tomcat|jax-rs
52,033
<p>You're using JAX-RS 2.0 APIs (request filters, name binding, ...) in your classes but Jersey 1 proprietary init params in your <code>web.xml</code> (package starting with <code>com.sun.jersey</code>, Jersey 2 uses <code>org.glassfish.jersey</code>). Take a look at this <a href="https://stackoverflow.com/questions/18086218/java-lang-classnotfoundexception-com-sun-jersey-spi-container-servlet-servletco/18099938#18099938">answer</a> and at these articles:</p> <ul> <li><a href="http://blog.dejavu.sk/2013/11/19/registering-resources-and-providers-in-jersey-2/" rel="nofollow noreferrer">Registering Resources and Providers in Jersey 2</a></li> <li><a href="http://blog.dejavu.sk/2014/01/08/binding-jax-rs-providers-to-resource-methods/" rel="nofollow noreferrer">Binding JAX-RS Providers to Resource Methods</a></li> </ul>
19,071,179
Capistrano - How to put files in the shared folder?
<p>I am new to <code>Capistrano</code>and I saw there is shared folder and also option <code>:linked_files</code>. I think shared folder is used to keep files between releases. But my question is, how do files end up being in the shared folder?</p> <p>Also, if I want to symlink another directory to the current directory e.g. static folder at some path, how do I put it at the <code>linked_dirs</code> ?</p> <p>Lastly how to set <code>chmod 755</code> to linked_files and linked_dirs.</p> <p>Thank you.</p>
19,306,181
6
0
null
2013-09-28 20:09:11.42 UTC
16
2019-07-29 11:35:05.377 UTC
2017-02-19 00:34:30.583 UTC
null
1,533,054
null
273,183
null
1
50
capistrano|config|web-deployment
48,754
<p>Folders inside your app are symlinks to folders in the shared directory. If your app writes to <code>log/production.log</code>, it will actually write to <code>../shared/log/production.log</code>. That's how the files end up being in the shared folder.</p> <p>You can see how this works by looking at the <a href="https://github.com/capistrano/capistrano/search?q=linked_dirs&amp;ref=cmdform">feature specs or tests in Capistrano</a>.</p> <p>If you want to chmod these shared files, you can just do it once directly over ssh since they won't ever be modified by Capistrano after they've been created.</p> <p>To add a linked directory, in your <code>deploy.rb</code>: </p> <pre><code>set :linked_dirs, %w{bin log tmp/backup tmp/pids tmp/cache tmp/sockets vendor/bundle} </code></pre> <p>or </p> <pre><code>set :linked_dirs, fetch(:linked_dirs) + %w{public/system} </code></pre>
17,922,748
What is the correct method for calculating the Content-length header in node.js
<p>I'm not at all sure whether my current method of calculating the content-length is correct. What are the implications of using string.length() to calculate the content-length. Does setting the charset to utf-8 even mean anything when using node.js?</p> <pre><code>payload = JSON.stringify( payload ); response.header( 'content-type', application/json; charset=utf-8 ); response.header( 'content-length', payload.length ); response.end( payload ); </code></pre>
17,922,999
1
1
null
2013-07-29 11:23:30.193 UTC
8
2013-07-29 11:37:31.403 UTC
null
null
null
null
560,383
null
1
38
javascript|node.js|utf-8|express
19,754
<p>Content-Length header must be the count of octets in the response body. <code>payload.length</code> refers to string length in characters. Some UTF-8 characters contain multiple bytes. The better way would be to use <code>Buffer.byteLength(string, [encoding])</code> from <a href="http://nodejs.org/api/buffer.html" rel="noreferrer">http://nodejs.org/api/buffer.html</a>. It's a class method so you do not have to create any Buffer instance.</p>
24,054,590
ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'user' from content with media type 'multipart/form-data in "postman"
<p>I am creating the Login Service using Web API. When I am checking with <code>fiddler</code> it's working fine but when I am checking with <code>postman</code> of <code>chrome</code> it's showing error:</p> <pre><code>{ "Message": "An error has occurred.", "ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'user' from content with media type 'multipart/form-data'.", "ExceptionType": "System.InvalidOperationException", "StackTrace": " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)\r\n at System.Web.Http.Controllers.HttpActionBinding.&lt;&gt;c__DisplayClass1.&lt;ExecuteBindingAsync&gt;b__0(HttpParameterBinding parameterBinder)\r\n at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()\r\n at System.Threading.Tasks.TaskHelpers.IterateImpl(IEnumerator`1 enumerator, CancellationToken cancellationToken)" } </code></pre> <p></p> <pre><code>public class user { //public user(string userId, string password) //{ // UserId = userId; // Password = password; //} public string UserId { get; set; } public string Password { get; set; } } </code></pre> <p>I am checking in <code>postman</code> if this service is able to access in mobile application. Also, to check this in mac system.</p>
24,058,025
2
0
null
2014-06-05 07:52:13.563 UTC
1
2017-06-19 12:07:12.707 UTC
2017-06-19 12:07:12.707 UTC
null
3,714,940
null
2,107,297
null
1
7
asp.net-web-api|fiddler|postman
41,543
<p>Click on the Header button type this both header and value</p> <pre><code>Content-Type: application/json </code></pre> <p>check below link for fiddle and postman both use same content-types <a href="https://stackoverflow.com/questions/22384354/error-sending-json-in-post-to-web-api-service">Error sending json in POST to web API service</a></p>
34,500,020
ReferenceError: Can't find variable: __fbBatchedBridge
<p>Using just the default code from <code>react-native init AwesomeProject</code>, when I run the app I get the 'ReferenceError: Can't find variable: __fbBatchedBridge (line 1 in the generated bundle)'.</p> <p>And, when I 'Reload JS', the app just has the white background rather than any 'hello world' views. I haven't touched any of the code from the init.</p> <p>Any ideas how to resolve the error?</p> <p>Screenshot (click to view full size):<br> <a href="https://i.stack.imgur.com/bNYBH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bNYBHm.png" alt="enter image description here"></a></p> <p>Using:</p> <ul> <li>Ubuntu 15.10, 64-bit</li> <li>Node.js v5.3.0</li> <li>reactive-native v0.1.7</li> <li>Nexus 5X, API 6.0.1</li> </ul>
34,500,080
8
0
null
2015-12-28 20:08:50.403 UTC
5
2016-05-16 06:44:35.623 UTC
2016-02-10 16:51:26.977 UTC
null
1,043,380
null
887,894
null
1
40
node.js|react-native
15,294
<p>I generally see this when the packager hasn't started. Ensure that is running by running react-native start</p>
26,108,672
RSA: encrypt in iOS, decrypt in Java
<p>I have a public key that's sent from a Java server. The base64 encoded strings match before I decode and strip out the ASN.1 headers. I store the public key in the keychain with <code>SecItemAdd</code>.</p> <p>So I'm trying to encrypt the data using the public key and decrypt it with the private key in Java. I'm using <code>SecKeyEncrypt</code> on the iOS side and <code>Cipher</code> on the Java side.</p> <p>What I'm encrypting is the symmetric AES key that encrypts my actual data, so the key length is 16 bytes. When simply base64 encoding the key, everything works, so I know something is wrong with this RSA encryption.</p> <p>Here's an example of my iOS call:</p> <pre><code>OSStatus sanityCheck = SecKeyEncrypt(publicKey, kSecPaddingPKCS1, (const uint8_t *) [incomingData bytes], keyBufferSize, cipherBuffer, &amp;cipherBufferSize ); </code></pre> <p>Here's an example of my Java call:</p> <pre><code>public static byte[] decryptMessage (byte[] message, PrivateKey privateKey, String algorithm) { if (message == null || privateKey == null) { return null; } Cipher cipher = createCipher(Cipher.DECRYPT_MODE, privateKey, algorithm, false); if (cipher == null) { return null; } try { return cipher.doFinal(message); } catch (IllegalBlockSizeException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. return null; } catch (BadPaddingException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. return null; } } private static Cipher createCipher (int mode, Key encryptionKey, String algorithm, boolean useBouncyCastle) { Cipher cipher; try { if (useBouncyCastle) { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); cipher = Cipher.getInstance(algorithm, "BC"); } else { cipher = Cipher.getInstance(algorithm); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. return null; } catch (NoSuchPaddingException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. return null; } catch (NoSuchProviderException e) { e.printStackTrace(); return null; } try { cipher.init(mode, encryptionKey); } catch (InvalidKeyException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. return null; } return cipher; } </code></pre> <p>I've tried so many combinations and nothing has worked.</p> <ul> <li>iOS: PKCS1, Java: RSA/ECB/PKCS1Padding</li> <li>iOS: PKCS1, Java: RSA</li> <li>iOS: PKCS1, Java: RSA/None/PKCS1Padding (throws <code>org.bouncycastle.crypto.DataLengthException: input too large for RSA cipher.</code>)</li> <li>iOS: OAEP, Java: RSA/ECB/OAEPWithSHA-1AndMGF1Padding</li> <li>iOS: OAEP, Java: RSA/ECB/OAEPWithSHA-256AndMGF1Padding</li> </ul> <p>I've also tried using the internal Java provider as well as the BouncyCastle provider. The <code>javax.crypto.BadPaddingException</code> gets thrown every time, but the message is different for each combination. Some show <code>Data must start with zero</code>, while others are <code>Message is larger than modulus</code>.</p> <p>The <code>iOS: PKCS1, Java: RSA</code> doesn't throw an exception, but the resulting decrypted <code>byte[]</code> array should be length 16, but it's length 256, which means the padding isn't correctly stripped out.</p> <p>Can someone help?</p> <p>*** <strong>EDIT</strong> ***</p> <p>As I'm doing more testing, I came across this page (<a href="http://javadoc.iaik.tugraz.at/iaik_jce/current/iaik/pkcs/pkcs1/RSACipher.html" rel="noreferrer">http://javadoc.iaik.tugraz.at/iaik_jce/current/iaik/pkcs/pkcs1/RSACipher.html</a>), which essentially tells me that <code>RSA == RSA/None/PKCS1Padding</code>. The decryption works in the sense that there are no exceptions, but I'm still getting a decrypted key whose byte[] is length 256 instead of length 16.</p> <p>Another point of interest. It seems that if the Java server has the public key generated from the iOS device and encrypted using <code>Cipher.getInstance("RSA")</code>, the phone is able to decode the message correctly with RSA/PKCS1.</p> <p>*** <strong>EDIT 2</strong> ***</p> <p>I have looked at these tutorials and looked through my code again on the iOS side:</p> <ul> <li><a href="http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios/" rel="noreferrer">http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios/</a></li> <li><a href="http://blog.wingsofhermes.org/?p=42" rel="noreferrer">http://blog.wingsofhermes.org/?p=42</a></li> <li><a href="http://blog.wingsofhermes.org/?p=75" rel="noreferrer">http://blog.wingsofhermes.org/?p=75</a></li> </ul> <p>As far as I can tell, my code is doing everything correctly. One significant difference was in how I was saving the key, so I tried saving it the other way:</p> <pre><code> OSStatus error = noErr; CFTypeRef persistPeer = NULL; NSMutableDictionary * keyAttr = [[NSMutableDictionary alloc] init]; keyAttr[(__bridge id) kSecClass] = (__bridge id) kSecClassKey; keyAttr[(__bridge id) kSecAttrKeyType] = (__bridge id) kSecAttrKeyTypeRSA; keyAttr[(__bridge id) kSecAttrApplicationTag] = [secKeyWrapper getKeyTag:serverPublicKeyTag]; keyAttr[(__bridge id) kSecValueData] = strippedServerPublicKey; keyAttr[(__bridge id) kSecReturnPersistentRef] = @YES; error = SecItemAdd((__bridge CFDictionaryRef) keyAttr, (CFTypeRef *)&amp;persistPeer); if (persistPeer == nil || ( error != noErr &amp;&amp; error != errSecDuplicateItem)) { NSLog(@"Problem adding public key to keychain"); return; } CFRelease(persistPeer); </code></pre> <p>That save was successful, but the end result was the same: the decrypted AES key was still 256 bytes long instead of 16 bytes.</p>
27,446,066
2
0
null
2014-09-29 20:51:56.907 UTC
15
2014-12-12 14:45:06.47 UTC
2014-09-29 23:44:01.86 UTC
null
1,733,644
null
1,733,644
null
1
20
java|ios7|rsa
10,134
<p>I had same problem. Does work with <code>kSecPaddingNone</code>, but <strong>doesn't</strong> work with <code>kSecPaddingPKCS1</code> with any <code>PKCS1</code> combination in Java code.</p> <p>But, it's not good idea to use it without padding.</p> <p>So, on iOS, replace <code>kSecPaddingNone</code> with <code>kSecPaddingOAEP</code> and use <code>RSA/NONE/OAEPWithSHA1AndMGF1Padding</code> in your Java code. This does work for me.</p>
46,407,009
How to hide .env passwords in Laravel whoops output?
<p>How can I hide my passwords and other sensitive environment variables on-screen in Laravel's whoops output?</p> <p>Sometimes other people are looking at my development work. I don't want them to see these secrets if an exception is thrown, but I also don't want to have to keep toggling debug on and off, or spin up a dedicated site just for a quick preview.</p> <p><a href="https://i.stack.imgur.com/A9vD6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/A9vD6.png" alt="whoops output screenshot with passwords shown"></a></p>
46,407,010
12
0
null
2017-09-25 13:57:51.503 UTC
31
2021-10-19 23:02:42.63 UTC
null
null
null
null
4,233,593
null
1
74
php|laravel|environment-variables|secret-key|whoops
33,186
<p>As of <a href="https://github.com/laravel/framework/pull/21336" rel="noreferrer">Laravel 5.5.13</a>, you can censor variables by listing them under the key <code>debug_blacklist</code> in <code>config/app.php</code>. When an exception is thrown, whoops will mask these values with asterisks <code>*</code> for each character.</p> <p>For example, given this <code>config/app.php</code></p> <pre><code>return [ // ... 'debug_blacklist' =&gt; [ '_ENV' =&gt; [ 'APP_KEY', 'DB_PASSWORD', 'REDIS_PASSWORD', 'MAIL_PASSWORD', 'PUSHER_APP_KEY', 'PUSHER_APP_SECRET', ], '_SERVER' =&gt; [ 'APP_KEY', 'DB_PASSWORD', 'REDIS_PASSWORD', 'MAIL_PASSWORD', 'PUSHER_APP_KEY', 'PUSHER_APP_SECRET', ], '_POST' =&gt; [ 'password', ], ], ]; </code></pre> <p>Results in this output:</p> <p><a href="https://i.stack.imgur.com/R71SE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/R71SE.png" alt="whoops exception page" /></a></p>
40,465,047
How can I mock an ES6 module import using Jest?
<p>I want to test that one of my <a href="https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_%E2%80%93_ECMAScript_2015" rel="noreferrer">ES6</a> modules calls another ES6 module in a particular way. With <a href="https://en.wikipedia.org/wiki/Jasmine_(JavaScript_testing_framework)" rel="noreferrer">Jasmine</a> this is super easy --</p> <p>The application code:</p> <pre><code>// myModule.js import dependency from './dependency'; export default (x) =&gt; { dependency.doSomething(x * 2); } </code></pre> <p>And the test code:</p> <pre><code>//myModule-test.js import myModule from '../myModule'; import dependency from '../dependency'; describe('myModule', () =&gt; { it('calls the dependency with double the input', () =&gt; { spyOn(dependency, 'doSomething'); myModule(2); expect(dependency.doSomething).toHaveBeenCalledWith(4); }); }); </code></pre> <p>What's the equivalent with Jest? I feel like this is such a simple thing to want to do, but I've been tearing my hair out trying to figure it out.</p> <p>The closest I've come is by replacing the <code>import</code>s with <code>require</code>s, and moving them inside the tests/functions. Neither of which are things I want to do.</p> <pre><code>// myModule.js export default (x) =&gt; { const dependency = require('./dependency'); // Yuck dependency.doSomething(x * 2); } //myModule-test.js describe('myModule', () =&gt; { it('calls the dependency with double the input', () =&gt; { jest.mock('../dependency'); myModule(2); const dependency = require('../dependency'); // Also yuck expect(dependency.doSomething).toBeCalledWith(4); }); }); </code></pre> <p>For bonus points, I'd love to make the whole thing work when the function inside <code>dependency.js</code> is a default export. However, I know that spying on default exports doesn't work in Jasmine (or at least I could never get it to work), so I'm not holding out hope that it's possible in Jest either.</p>
60,669,731
9
3
null
2016-11-07 12:19:32.183 UTC
102
2022-06-28 16:08:05.45 UTC
2020-09-24 21:19:18.267 UTC
null
63,550
null
665,488
null
1
437
javascript|node.js|mocking|ecmascript-6|jestjs
373,675
<p>Fast forwarding to 2020, I found this blog post to be the solution: <em><a href="https://remarkablemark.org/blog/2018/06/28/jest-mock-default-named-export/" rel="noreferrer">Jest mock default and named export</a></em></p> <p>Using only ES6 module syntax:</p> <pre><code>// esModule.js export default 'defaultExport'; export const namedExport = () =&gt; {}; // esModule.test.js jest.mock('./esModule', () =&gt; ({ __esModule: true, // this property makes it work default: 'mockedDefaultExport', namedExport: jest.fn(), })); import defaultExport, { namedExport } from './esModule'; defaultExport; // 'mockedDefaultExport' namedExport; // mock function </code></pre> <p>Also one thing you need to know (which took me a while to figure out) is that you can't call jest.mock() inside the test; you must call it at the top level of the module. However, you can call mockImplementation() inside individual tests if you want to set up different mocks for different tests.</p>
40,081,332
What does the `is` keyword do in typescript?
<p>I came across some code that looks like this:</p> <pre><code>export function foo(arg: string): arg is MyType { return ... } </code></pre> <p>I haven't been able to search for <code>is</code> in either the docs or google, it's a pretty common word and shows up on basically every page.</p> <p>What does the keyword do in that context?</p>
45,748,366
2
1
null
2016-10-17 08:06:49.98 UTC
58
2022-06-23 14:59:31.88 UTC
2022-06-23 14:59:31.88 UTC
null
527,702
null
595,605
null
1
261
typescript|keyword
90,782
<p>See the reference for <a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates" rel="noreferrer">user-defined type guard functions</a> for more information.</p> <pre class="lang-js prettyprint-override"><code>function isString(test: any): test is string{ return typeof test === &quot;string&quot;; } function example(foo: any){ if(isString(foo)){ console.log(&quot;it is a string&quot; + foo); console.log(foo.length); // string function } } example(&quot;hello world&quot;); </code></pre> <p>Using the type predicate <code>test is string</code> in the above format (instead of just using <code>boolean</code> for the return type), after <code>isString()</code> is called, if the function returns <code>true</code>, <strong>TypeScript will narrow the type to <code>string</code> in any block guarded by a call to the function.</strong> The compiler will think that <code>foo</code> is <code>string</code> in the below-guarded block (and ONLY in the below-guarded block)</p> <pre class="lang-js prettyprint-override"><code>{ console.log(&quot;it is a string&quot; + foo); console.log(foo.length); // string function } </code></pre> <p>A type predicate is just used in compile time. The resulting <code>.js</code> file (runtime) will have no difference because it does not consider the TYPE.</p> <p>I will illustrate the differences in below four examples.</p> <p>E.g 1: the above example code will not have a compile error nor a runtime error.</p> <p>E.g 2: the below example code will have a compile error (as well as a runtime error) because TypeScript has narrowed the type to <code>string</code> and checked that <code>toExponential</code> does not belong to <code>string</code> method.</p> <pre class="lang-js prettyprint-override"><code>function example(foo: any){ if(isString(foo)){ console.log(&quot;it is a string&quot; + foo); console.log(foo.length); console.log(foo.toExponential(2)); } } </code></pre> <p>E.g. 3: the below example code does not have a compile error but will have a runtime error because TypeScript will ONLY narrow the type to <code>string</code> in the block guarded but not after, therefore <code>foo.toExponential</code> will not create compile error (TypeScript does not think it is a <code>string</code> type). However, in runtime, <code>string</code> does not have the <code>toExponential</code> method, so it will have runtime error.</p> <pre class="lang-js prettyprint-override"><code>function example(foo: any){ if(isString(foo)){ console.log(&quot;it is a string&quot; + foo); console.log(foo.length); } console.log(foo.toExponential(2)); } </code></pre> <p>E.g. 4: if we don’t use <code>test is string</code> (type predicate), TypeScript will not narrow the type in the block guarded and the below example code will not have compile error but it will have runtime error.</p> <pre class="lang-js prettyprint-override"><code>function isString(test: any): boolean{ return typeof test === &quot;string&quot;; } function example(foo: any){ if(isString(foo)){ console.log(&quot;it is a string&quot; + foo); console.log(foo.length); console.log(foo.toExponential(2)); } } </code></pre> <p>The conclusion is that <code>test is string</code> (type predicate) is used in compile-time to tell the developers the code will have a chance to have a runtime error. For javascript, the developers will not KNOW the error in compile time. This is the advantage of using TypeScript.</p>
22,079,587
AngularJS : transcluding multiple sub elements in a single Angular directive
<p>I was reading about <code>ng-transclude</code> in the AngularJS docs on <a href="https://docs.angularjs.org/guide/directive#creating-a-directive-that-wraps-other-elements" rel="nofollow noreferrer">Creating a Directive that Wraps Other Elements</a> and I think I understand properly what it does.</p> <p>If you have a directive that applies to an element that has content inside it such as the following:</p> <pre><code>&lt;my-directive&gt;directive content&lt;/my-directive&gt; </code></pre> <p>it will allow you to tag an element within the directive's template with <code>ng-transclude</code> and the content included in the element would be rendered inside the tagged element.</p> <p>So if the template for <code>myDirective</code> is</p> <pre><code>&lt;div&gt;before&lt;/div&gt; &lt;div ng-transclude&gt;&lt;/div&gt; &lt;div&gt;after&lt;/div&gt; </code></pre> <p>it would render as</p> <pre><code>&lt;div&gt;before&lt;/div&gt; &lt;div ng-transclude&gt;directive content&lt;/div&gt; &lt;div&gt;after&lt;/div&gt; </code></pre> <hr /> <p>My question is if it is possible to somehow pass more then a single block of html into my directive?</p> <p>For example, suppose the directive usage would look like this:</p> <pre><code>&lt;my-multipart-directive&gt; &lt;part1&gt;content1&lt;/part1&gt; &lt;part2&gt;content2&lt;/part2&gt; &lt;/my-multipart-directive&gt; </code></pre> <p>and have a template like:</p> <pre><code>&lt;div&gt; this: &lt;div ng-transclude=&quot;part2&quot;&gt;&lt;/div&gt; was after that: &lt;div ng-transclude=&quot;part1&quot;&gt;&lt;/div&gt; but now they are switched &lt;div&gt; </code></pre> <p>I want it to render as follows:</p> <pre><code>&lt;div&gt; this: &lt;div ng-transclude=&quot;part2&quot;&gt;content2&lt;/div&gt; was after that: &lt;div ng-transclude=&quot;part1&quot;&gt;content1&lt;/div&gt; but now they are switched &lt;div&gt; </code></pre> <p>Perhaps I could somehow bind the HTML value of a node to the model so that I will be able to use it in such a way without calling it &quot;transclude&quot;?</p>
34,063,645
3
1
null
2014-02-27 20:26:45.96 UTC
8
2021-02-18 16:38:46.097 UTC
2021-02-18 16:38:46.097 UTC
null
1,028,230
null
25,412
null
1
40
angularjs|angularjs-directive|angularjs-scope
22,468
<p>Starting Angular 1.5, it's now possible to create multiple slots. Instead of <strong>transclude:true</strong>, you provide an <strong>object</strong> with the mappings of each slot:</p> <p><a href="https://docs.angularjs.org/api/ng/directive/ngTransclude">https://docs.angularjs.org/api/ng/directive/ngTransclude</a></p> <pre><code>angular.module('multiSlotTranscludeExample', []) .directive('pane', function(){ return { restrict: 'E', transclude: { 'title': '?pane-title', 'body': 'pane-body', 'footer': '?pane-footer' }, template: '&lt;div style="border: 1px solid black;"&gt;' + '&lt;div class="title" ng-transclude="title"&gt;Fallback Title&lt;/div&gt;' + '&lt;div ng-transclude="body"&gt;&lt;/div&gt;' + '&lt;div class="footer" ng-transclude="footer"&gt;Fallback Footer&lt;/div&gt;' + '&lt;/div&gt;' }; }) </code></pre>
60,453,261
How to default Python3.8 on my Mac using Homebrew?
<p>I have updated my python 3 to the latest version 3.8:</p> <pre><code>brew search python ==&gt; Formulae app-engine-python gst-python python ✔ [email protected] ✔ boost-python ipython python-markdown wxpython boost-python3 micropython python-yq ==&gt; Casks awips-python kk7ds-python-runtime mysql-connector-python </code></pre> <p>But when I check the python3 version on my mac it still shows 3.7:</p> <pre><code>python3 --version Python 3.7.6 </code></pre> <p>how can I default python3 to the latest 3.8 version using Homebrew ?</p> <p>Edit: When I tried to use <code>brew switch</code>, it tells me I only installed python 3.7.6, but with last <code>brew upgrade</code> I'm pretty sure that <code>python3.8.1</code> is installed with Homebrew</p> <pre><code>brew switch python 3.8.1 python does not have a version "3.8.1" in the Cellar. python's installed versions: 3.7.6_1 </code></pre>
60,453,764
4
1
null
2020-02-28 13:59:27.567 UTC
12
2021-03-31 16:35:13.61 UTC
null
null
null
null
11,104,367
null
1
31
python-3.x|linux|macos|homebrew
51,810
<p>Ok, thanks to @gromgit from Homebrew community discussion (<a href="https://discourse.brew.sh/t/how-to-default-python-3-8-on-my-mac-using-homebrew/7050" rel="noreferrer">https://discourse.brew.sh/t/how-to-default-python-3-8-on-my-mac-using-homebrew/7050</a>)</p> <p>Here is the solution:</p> <pre><code>$ brew info [email protected] [email protected]: stable 3.8.1 (bottled) [keg-only] ... ==&gt; Caveats Python has been installed as /usr/local/opt/[email protected]/bin/python3 ... [email protected] is keg-only, which means it was not symlinked into /usr/local, because this is an alternate version of another formula. If you need to have [email protected] first in your PATH run: echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' &gt;&gt; ~/.bash_profile For compilers to find [email protected] you may need to set: export LDFLAGS="-L/usr/local/opt/[email protected]/lib" For pkg-config to find [email protected] you may need to set: export PKG_CONFIG_PATH="/usr/local/opt/[email protected]/lib/pkgconfig" </code></pre> <p>I will stick to <code>python</code> (v3.7.6) at this time and wait for seamless upgrade of v3.8.1 in the future releases.</p>
30,540,632
CoordinatorLayout using the ViewPager's RecyclerView
<p>I am using the view <code>CoordinatorLayout</code> from <code>android.support.design</code>. I want to attach the <code>app:layout_behavior</code> to the fragment's <code>RecyclerView</code>?</p> <p>In the example given by Google, they only attach it in the <code>RecyclerView</code> of the same XML file where the <code>CoordinatorLayout</code> was attached.</p> <p>Is there a way to attach <code>CoordinatorLayout</code> to the fragment's <code>RecyclerView</code> within the <code>ViewPager</code>?</p> <p>The sample is in <a href="http://android-developers.blogspot.ca/2015/05/android-design-support-library.html">this blog post</a> at Android Developers blog.</p>
30,543,783
6
1
null
2015-05-29 23:38:11.493 UTC
15
2017-02-04 03:51:36.54 UTC
2016-01-10 11:47:31.943 UTC
null
1,276,636
null
3,444,777
null
1
53
android|android-appcompat|android-recyclerview|android-design-library|android-coordinatorlayout
51,804
<p>Chris Banes has posted a sample on Github which shows exactly what you want to do. </p> <p>Here is the xml file that defines how one can indirectly attach a coordinator layout to the viewpager's fragments.</p> <pre><code>&lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:layout_scrollFlags="scroll|enterAlways" /&gt; &lt;android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /&gt; &lt;android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="@dimen/fab_margin" android:src="@drawable/ic_done" /&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <p>The idea is to let the viewpager have the layout_behavior attribute.</p>
53,769,401
Angular 6 - NullInjectorError: No provider for HttpClient in unit tests
<p>I am importing and using <code>HttpClient</code> in a service as follows:</p> <pre class="lang-js prettyprint-override"><code>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root', }) export class MyService { constructor(private http: HttpClient) { } getData() { return this.http.get(&quot;url...&quot;); } } </code></pre> <p>However, when I run <code>ng test</code> for my <strong>unit tests</strong>, and when those tests use the service, I am getting the error:</p> <pre><code>Error: StaticInjectorError(DynamicTestModule)[HttpClient]: StaticInjectorError(Platform: core)[HttpClient]: NullInjectorError: No provider for HttpClient! </code></pre> <p>The <a href="https://v6.angular.io/tutorial/toh-pt6#heroes-and-http" rel="noreferrer">Angular 6 documentation on HTTP</a> just says to do what I did above.</p>
53,769,491
3
5
null
2018-12-13 20:13:03.027 UTC
9
2022-01-07 14:59:23.073 UTC
2022-01-07 14:58:36.993 UTC
null
6,831,341
null
5,100,278
null
1
61
angular|karma-jasmine|angular-test
110,248
<pre class="lang-js prettyprint-override"><code>import { TestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import {HttpClientModule} from '@angular/common/http'; import { myService } from './myservice'; describe('myService', () =&gt; { beforeEach(() =&gt; TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [myService] })); it('should be created', () =&gt; { const service: myService = TestBed.get(myService); expect(service).toBeTruthy(); }); it('should have getData function', () =&gt; { const service: myService = TestBed.get(myService); expect(service.getData).toBeTruthy(); }); }); </code></pre>
29,360,395
Display images in Django
<p>I have a django app which allows users to submit an image with it. Right now my model looks like </p> <pre><code>class Posting(models.Model): title = models.CharField(max_length=150) images = models.ForeignKey(Image, null=True) class Image(models.Model): img = models.ImageField(upload_to="photos/",null=True, blank=True) </code></pre> <p>and I am trying to display the images in my template however I cannot seem to get it to work. I have gone though countless stack overflow posts and haven't had any luck. In my template I have </p> <pre><code>{ for post in postings } &lt;img src"{{ post.image.url }} #and many variations of this </code></pre> <p>however other seems to display the url. The url seems to always be blank. Any help would be greatly appreciated! </p>
29,397,661
5
2
null
2015-03-31 04:02:33.573 UTC
2
2019-07-03 14:40:44.937 UTC
null
null
null
null
3,443,176
null
1
8
django|image|imagefield
40,241
<p>This is how i got it working.</p> <p><strong>settings.py</strong></p> <pre><code>import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) MEDIA_ROOT = ( BASE_DIR ) MEDIA_URL = '/media/' </code></pre> <p><strong>models.py</strong> ...</p> <pre><code>image = models.ImageField(upload_to='img') </code></pre> <p><strong>urls.py</strong>(project's)</p> <pre><code>if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre> <p><strong>template</strong> (.html)</p> <pre><code>&lt;img src="{{ post.image.url }}" alt="img"&gt; </code></pre>
32,231,489
smtp exception “failure sending mail”
<p>I created console application for sending Email</p> <pre><code> public static void sendEmail(string email, string body) { if (String.IsNullOrEmpty(email)) return; try { MailMessage mail = new MailMessage(); mail.To.Add(email); mail.From = new MailAddress("[email protected]"); mail.Subject = "sub"; mail.Body = body; mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "admin@1234"); // ***use valid credentials*** smtp.Port = 587; //Or your Smtp Email ID and Password smtp.EnableSsl = true; smtp.Send(mail); } catch (Exception ex) { } } </code></pre> <p>I am using correct credential of my gmail account.</p> <p>Is there any <strong>settings</strong> I need to do for <strong>GMail Account</strong>?</p>
32,231,849
2
3
null
2015-08-26 16:04:42.067 UTC
1
2018-08-26 08:53:12.67 UTC
null
null
null
user5264652
null
null
1
10
c#|email|console-application
69,648
<p>It's likely that you're actually getting this error, it's just suppressed in some way by you being in a console app.</p> <blockquote> <p>The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.</p> </blockquote> <p>Change this piece of code and add one extra line. It's important that it goes before the credentials.</p> <pre><code>smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address // ** HERE! ** smtp.UseDefaultCredentials = false; // *********** smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "admin@1234"); // ***use valid credentials*** smtp.Port = 587; </code></pre> <p>You'll also need to go here and enable less secure apps.</p> <p><a href="https://www.google.com/settings/security/lesssecureapps" rel="noreferrer">https://www.google.com/settings/security/lesssecureapps</a></p> <p>Or if you have two step authentication on your account you'll need to set an app specific password, then use that password in your code instead of your main account password.</p> <p>I've just tested and verified this works on my two step account. Hell, here's my entire method copied right out of LINQPad in case it helps (with removed details of course).</p> <pre><code>var fromAddress = new MailAddress("[email protected]", "My Name"); var toAddress = new MailAddress("[email protected]", "Mr Test"); const string fromPassword = "tbhagpfpcxwhkczd"; const string subject = "test"; const string body = "HEY, LISTEN!"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword), Timeout = 20000 }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); } </code></pre> <p><strong>Edit:</strong></p> <p>Using attachments:</p> <pre><code>using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { Attachment attachment = new Attachment(filePath); message.Attachments.Add(attachment); smtp.Send(message); } </code></pre>
4,495,511
How to pass custom component parameters in java and xml
<p>When creating a custom component in android it is often asked how to create and pass through the attrs property to the constructor.</p> <p>It is often suggested that when creating a component in java that you simply use the default constructor, i.e. </p> <pre><code>new MyComponent(context); </code></pre> <p>rather than attempting to create an attrs object to pass through to the overloaded constructor often seen in xml based custom components. I've tried to create an attrs object and it doesn't seem either easy or at all possible (without an exceedingly complicated process), and by all accounts isn't really required. </p> <p>My question is then: What is the most efficient way of construction a custom component in java that passes or sets properties that would have otherwise been set by the attrs object when inflating a component using xml?</p>
4,495,745
1
0
null
2010-12-21 01:07:03.887 UTC
24
2018-12-06 02:04:06.29 UTC
2011-01-08 23:58:44.55 UTC
null
244,296
null
468,195
null
1
52
android|components|custom-attributes|uicomponents
41,139
<p>(Full disclosure: This question is an offshoot of <a href="https://stackoverflow.com/questions/4418700">Creating custom view</a>)</p> <p>You can create constructors beyond the three standard ones inherited from <code>View</code> that add the attributes you want...</p> <pre><code>MyComponent(Context context, String foo) { super(context); // Do something with foo } </code></pre> <p>...but I don't recommend it. It's better to follow the same convention as other components. This will make your component as flexible as possible and will prevent developers using your component from tearing their hair out because yours is inconsistent with everything else:</p> <p><strong>1. Provide getters and setters for each of the attributes:</strong></p> <pre><code>public void setFoo(String new_foo) { ... } public String getFoo() { ... } </code></pre> <p><strong>2. Define the attributes in <code>res/values/attrs.xml</code> so they can be used in XML.</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;declare-styleable name="MyComponent"&gt; &lt;attr name="foo" format="string" /&gt; &lt;/declare-styleable&gt; &lt;/resources&gt; </code></pre> <p><strong>3. Provide the three standard constructors from <code>View</code>.</strong></p> <p>If you need to pick anything out of the attributes in one of the constructors that takes an <code>AttributeSet</code>, you can do...</p> <pre><code>TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MyComponent); CharSequence foo_cs = arr.getString(R.styleable.MyComponent_foo); if (foo_cs != null) { // Do something with foo_cs.toString() } arr.recycle(); // Do this when done. </code></pre> <p>With all that done, you can instantiate <code>MyCompnent</code> programmatically...</p> <pre><code>MyComponent c = new MyComponent(context); c.setFoo("Bar"); </code></pre> <p>...or via XML:</p> <pre><code>&lt;!-- res/layout/MyActivity.xml --&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:blrfl="http://schemas.android.com/apk/res-auto" ...etc... &gt; &lt;com.blrfl.MyComponent android:id="@+id/customid" android:layout_weight="1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" blrfl:foo="bar" blrfl:quux="bletch" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>Additional Resource - <a href="https://developer.android.com/training/custom-views/create-view" rel="noreferrer">https://developer.android.com/training/custom-views/create-view</a></p>
25,028,873
How do I reload a module in an active Julia session after an edit?
<p><strong>2018 Update:</strong> Be sure to check all the responses, as the answer to this question has changed multiple times over the years. At the time of this update, the <code>Revise.jl</code> answer is probably the best solution.</p> <p>I have a file "/SomeAbsolutePath/ctbTestModule.jl", the contents of which are:</p> <pre><code>module ctbTestModule export f1 f1(x) = x + 1 end </code></pre> <p>I fire up Julia in a terminal, which runs "~/.juliarc.jl". The startup code includes the line:</p> <pre><code>push!(LOAD_PATH, "/SomeAbsolutePath/") </code></pre> <p>Hence I can immediately type into the Julia console:</p> <pre><code>using ctbTestModule </code></pre> <p>to load my module. As expected <code>f1(1)</code> returns <code>2</code>. Now I suddenly decide I want to edit <code>f1</code>. I open up "/SomeAbsolutePath/ctbTestModule.jl" in an editor, and change the contents to:</p> <pre><code>module ctbTestModule export f1 f1(x) = x + 2 end </code></pre> <p>I now try to reload the module in my active Julia session. I try </p> <pre><code>using ctbTestModule </code></pre> <p>but <code>f1(1)</code> still returns <code>2</code>. Next I try: </p> <pre><code>reload("ctbTestModule") </code></pre> <p>as suggested <a href="https://github.com/JuliaLang/julia/issues/4008" rel="noreferrer">here</a>, but <code>f1(1)</code> still returns <code>2</code>. Finally, I try:</p> <pre><code>include("/SomeAbsolutePath/ctbTestModule.jl") </code></pre> <p>as suggested <a href="http://julia.readthedocs.org/en/latest/manual/faq/" rel="noreferrer">here</a>, which is <em>not</em> ideal since I have to type out the full absolute path since the current directory might not be "/SomeAbsolutePath". I get the warning message <code>Warning: replacing module ctbTestModule</code> which sounds promising, but <code>f1(1)</code> still returns <code>2</code>.</p> <p>If I close the current Julia session, start a new one, and type in <code>using ctbTestModule</code>, I now get the desired behaviour, i.e. <code>f1(1)</code> returns <code>3</code>. But obviously I want to do this <em>without</em> re-starting Julia.</p> <p>So, what am I doing wrong?</p> <p>Other details: Julia v0.2 on Ubuntu 14.04.</p>
25,077,725
5
2
null
2014-07-30 04:39:54.37 UTC
17
2021-05-27 08:22:32.367 UTC
2018-06-12 23:09:32.927 UTC
null
1,667,895
null
1,667,895
null
1
68
module|julia
19,187
<p>The basis of this problem is the confluence of reloading a module, but not being able to redefine a thing in the module <strong><em>Main</em></strong> (<a href="http://julia.readthedocs.org/en/latest/manual/faq/">see the documentation here</a>) -- that is <a href="https://github.com/JuliaLang/julia/pull/7487">at least until the new function workspace() was made available</a> on July 13 2014. Recent versions of the 0.3 pre-release should have it.</p> <h2>Before workspace()</h2> <p>Consider the following simplistic module</p> <pre><code>module TstMod export f function f() return 1 end end </code></pre> <p>Then use it....</p> <pre><code>julia&gt; using TstMod julia&gt; f() 1 </code></pre> <p>If the function <strong>f</strong>() is changed to <em>return 2</em> and the module is reloaded, <strong>f</strong> is in fact updated. But not redefined in module <strong>Main</strong>.</p> <pre><code>julia&gt; reload("TstMod") Warning: replacing module TstMod julia&gt; TstMod.f() 2 julia&gt; f() 1 </code></pre> <p>The following warnings make the problem clear</p> <pre><code>julia&gt; using TstMod Warning: using TstMod.f in module Main conflicts with an existing identifier. julia&gt; using TstMod.f Warning: ignoring conflicting import of TstMod.f into Main </code></pre> <h2>Using workspace()</h2> <p>However, the new function <strong>workspace</strong>() clears <strong><em>Main</em></strong> preparing it for reloading <strong><em>TstMod</em></strong></p> <pre><code>julia&gt; workspace() julia&gt; reload("TstMod") julia&gt; using TstMod julia&gt; f() 2 </code></pre> <p>Also, the previous <strong><em>Main</em></strong> is stored as <strong><em>LastMain</em></strong></p> <pre><code>julia&gt; whos() Base Module Core Module LastMain Module Main Module TstMod Module ans Nothing julia&gt; LastMain.f() 1 </code></pre>
24,961,797
Android resize bitmap keeping aspect ratio
<p>I have a custom view (1066 x 738), and I am passing a bitmap image (720x343). I want to scale the bitmap to fit in the custom view without exceeding the bound of the parent.</p> <p><img src="https://i.stack.imgur.com/OLaY2.jpg" alt="enter image description here"></p> <p>I want to achieve something like this:</p> <p><img src="https://i.stack.imgur.com/7HVgj.jpg" alt="enter image description here"></p> <p>How should I calculate the bitmap size?</p> <p>How I calculate the new width/height:</p> <pre><code> public static Bitmap getScaledBitmap(Bitmap b, int reqWidth, int reqHeight) { int bWidth = b.getWidth(); int bHeight = b.getHeight(); int nWidth = reqWidth; int nHeight = reqHeight; float parentRatio = (float) reqHeight / reqWidth; nHeight = bHeight; nWidth = (int) (reqWidth * parentRatio); return Bitmap.createScaledBitmap(b, nWidth, nHeight, true); } </code></pre> <p>But all I am achieving is this:</p> <p><img src="https://i.stack.imgur.com/76dZg.jpg" alt="enter image description here"></p>
24,962,139
1
3
null
2014-07-25 17:56:34 UTC
4
2014-12-09 12:39:20.503 UTC
null
null
null
null
1,950,209
null
1
16
android|bitmap|scale
41,525
<p>You should try using a transformation matrix built for <code>ScaleToFit.CENTER</code>. For example:</p> <pre><code>Matrix m = new Matrix(); m.setRectToRect(new RectF(0, 0, b.getWidth(), b.getHeight()), new RectF(0, 0, reqWidth, reqHeight), Matrix.ScaleToFit.CENTER); return Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true); </code></pre>
39,076,988
Add extra User Information with firebase
<p>I have integrated firebase auth with my android app. Lets say a user has a mail <code>[email protected]</code>. I want to add some extra information to the user like the name of the user, occupation and address. How can i connect the user auth table with my android app to do that? </p> <p>Do i need to write any APIs for that? </p>
39,077,132
3
5
null
2016-08-22 10:19:50.26 UTC
13
2018-02-28 20:44:35.177 UTC
null
null
null
null
5,408,958
null
1
50
android|firebase|firebase-realtime-database|firebase-authentication
62,114
<p>First, create a <code>users</code> directory in db. Then, using user's unique id you get from authn process, store the user info under <code>users/{userid}</code>.</p> <p>To achieve this, you need to get into the details of Firebase database. See here: <a href="https://firebase.google.com/docs/database/android/save-data" rel="noreferrer">https://firebase.google.com/docs/database/android/save-data</a></p>
20,147,964
What does if [[ $? -ne 0 ]]; mean in .ksh
<p>I have a following piece of code that says if everything is executed mail a person if it fails mail the person with a error message. </p> <pre><code>if [[ $? -ne 0 ]]; then mailx -s" could not PreProcess files" [email protected] else mailx -s" PreProcessed files" [email protected] fi done </code></pre> <p>I am new to linux coding I want to understand what <code>if [[ $? -ne 0 ]];</code> means </p>
20,148,053
4
0
null
2013-11-22 15:02:34.433 UTC
3
2019-01-24 01:11:00.003 UTC
2015-07-06 13:10:40.4 UTC
null
1,480,391
null
2,957,106
null
1
14
linux|bash|unix|ksh
42,223
<p>Breaking it down, simple terms:</p> <pre><code>[[ and ]] </code></pre> <p>... signifies a test is being made for truthiness.</p> <pre><code>$? </code></pre> <p>... is a variable holding the exit code of the last run command.</p> <pre><code>-ne 0 </code></pre> <p>... checks that the thing on the left (<code>$?</code>) is "not equal" to "zero". In UNIX, a command that exits with zero succeeded, while an exit with any other value (1, 2, 3... up to 255) is a failure.</p>
7,193,787
Keyboard Scroll on Active Text Field - Scrolling to Out of View?
<p>I have an application with a view that has text fields from the top of the view to the bottom of the view. I needed it to scroll when editing the bottom fields so that the fields would be visible, but it's not seeming to work correctly.</p> <p>Following the <a href="http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html" rel="noreferrer">Apple docs</a>, I placed all of that code into my program (Listings 4-1, 4-2), and added the <code>scrollView</code> and <code>activeField</code> outlets to my header file and linked them to IB. </p> <p>The problem is as soon as I click into a text field, ALL of the text fields go out of view until I dismiss the keyboard. They scroll down very far (again, far enough to where none of the fields are visible). </p> <p>Does anyone know what that problem could be caused by?</p> <p>I'm placing the code in here from the Apple Docs so you can see exactly what code I'm using without having to click away. </p> <pre><code>//my .h IBOutlet UIScrollView *scrollView; IBOutlet UITextField *activeField; //.m // Call this method somewhere in your view controller setup code. - (void)registerForKeyboardNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; } // Called when the UIKeyboardDidShowNotification is sent. - (void)keyboardWasShown:(NSNotification*)aNotification { NSDictionary* info = [aNotification userInfo]; CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0); scrollView.contentInset = contentInsets; scrollView.scrollIndicatorInsets = contentInsets; // If active text field is hidden by keyboard, scroll it so it's visible // Your application might not need or want this behavior. CGRect aRect = self.view.frame; aRect.size.height -= kbSize.height; if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) { CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height); [scrollView setContentOffset:scrollPoint animated:YES]; } } // Called when the UIKeyboardWillHideNotification is sent - (void)keyboardWillBeHidden:(NSNotification*)aNotification { UIEdgeInsets contentInsets = UIEdgeInsetsZero; scrollView.contentInset = contentInsets; scrollView.scrollIndicatorInsets = contentInsets; } - (void)textFieldDidBeginEditing:(UITextField *)textField { activeField = textField; } - (void)textFieldDidEndEditing:(UITextField *)textField { activeField = nil; } </code></pre>
7,195,882
4
4
null
2011-08-25 16:16:36.977 UTC
10
2016-09-09 09:00:56.907 UTC
2011-08-25 18:34:55.447 UTC
null
801,858
null
801,858
null
1
7
iphone|objective-c|xcode|uiscrollview
25,150
<p><strong>UPDATE:</strong> Below answer is outdated. For now you can use "<a href="https://github.com/michaeltyson/TPKeyboardAvoiding" rel="nofollow">TPkeyboardavoiding</a>" library for handle all kind of text field operation in UIScrollView, UITableView &amp; many more. Try it and let me know if any one have a problem in integration.</p> <p><strong>Old Answer</strong></p> <p>There is no need to register for the keyboard notifications for this functionality. In order to center the active textField the screen above the keyboard, you only have to set the contentOffset of the UIscrollView two methods as shown here:</p> <pre><code>// called when textField start editting. - (void)textFieldDidBeginEditing:(UITextField *)textField { activeField = textField; [scrollView setContentOffset:CGPointMake(0,textField.center.y-60) animated:YES]; } // called when click on the retun button. - (BOOL)textFieldShouldReturn:(UITextField *)textField { NSInteger nextTag = textField.tag + 1; // Try to find next responder UIResponder *nextResponder = [textField.superview viewWithTag:nextTag]; if (nextResponder) { [scrollview setContentOffset:CGPointMake(0,textField.center.y-60) animated:YES]; // Found next responder, so set it. [nextResponder becomeFirstResponder]; } else { [scrollview setContentOffset:CGPointMake(0,0) animated:YES]; [textField resignFirstResponder]; return YES; } return NO; } </code></pre> <p><strong>Note: All TextField should have incremental tags Like 1,2,3 and so no. And set delegates to self.</strong></p> <p>Thanks,</p>
7,044,365
How to replace " with \" in javascript
<p>I have a textbox that posts info to the server and it's in JSON format. Lets say I want to enter two quotes for the value, and the JSON struct would look like:</p> <pre><code>{ "test": """" } </code></pre> <p>I need it to look like: </p> <pre><code>{ "test": "\"\"" } </code></pre> <p>so it will follow JSON standards and can be parsable/stringifyable.</p> <p>I tried using</p> <pre><code> var val = myVal.replace('"', "\\\""); </code></pre> <p>but this didn't work. <code>val</code> ends up with only one escaped quote like so <code>\""</code>Any help is much appreciated!</p>
7,044,544
4
5
null
2011-08-12 18:01:57.24 UTC
2
2015-11-26 06:05:10.587 UTC
2011-08-12 19:09:21.123 UTC
null
277,140
null
277,140
null
1
10
javascript|replace
45,197
<p>My answer makes some assumptions, as I've had to fill in the rather sizeable gaps in your question:</p> <ul> <li>The user will enter a text string into a textbox;</li> <li>Your script will read the textbox contents, and use those contents as the <em>value</em> of one of the items in a JSON string that it's building;</li> <li>The script sends this resulting JSON string to the server somehow.</li> </ul> <p>If I've got that right, let's proceed...</p> <hr> <h2>Baseline code</h2> <p>So, with some placeholders, you're doing:</p> <pre><code>function get_contents_of_textbox() { // Dummy data for example return 'My mum pushed and I said "Hello World"!'; } function send_to_server(json_str) { // Dummy action: display JSON string console.log(json_str); } var myVal = get_contents_of_textbox(); var JSON = '{ "test": "' + myVal + '" }'; send_to_server(JSON); </code></pre> <h3><a href="http://jsfiddle.net/EgKzs/" rel="noreferrer">Live demo</a>, showing the malformed JSON.</h3> <hr> <h2>Initial attempt</h2> <p>To ensure that <code>JSON</code> is valid, <em>escape</em> any quotes and backslashes that it may contain. You already gave it a go:</p> <pre><code>myVal = myVal.replace('"', "\\\""); </code></pre> <p>and <a href="http://jsfiddle.net/xqyCp/" rel="noreferrer">the result of your attempt</a> is:</p> <pre><code>{ "test": "My mum pushed and I said \"Hello World"!" } </code></pre> <p>Only the first quote has been escaped. This is because only one instance of the search string is replaced by default.</p> <p>The Mozilla documentation <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace" rel="noreferrer">says</a>:</p> <blockquote> <p>To perform a global search and replace, either include the g flag in the regular expression or if the first parameter is a string, include g in the flags parameter.</p> </blockquote> <hr> <h2>Working attempt</h2> <p>Unfortunately, the <code>flags</code> parameter is non-standard, so let's switch to the regex version of <code>replace</code>, and use the <code>/g</code> switch in it:</p> <pre><code>myVal = myVal.replace(/"/g, '\\"'); </code></pre> <p><sup>(You'll notice that I also condensed the replacement string, for brevity.)</sup></p> <p>Result:</p> <pre><code>{ "test": "My mum pushed and I said \"Hello World\"!" } </code></pre> <h3><a href="http://jsfiddle.net/NY9jy/" rel="noreferrer">Live demo.</a> Hurrah!</h3> <hr> <h2>Complete solution</h2> <p>Let's also add logic to escape backslashes, and we end up with this:</p> <pre><code>function get_contents_of_textbox() { // Dummy data for example return 'My mum pushed [a back\\slash] and I said "Hello World"!'; } function send_to_server(json_str) { // Dummy action: display JSON string console.log(json_str); } var myVal = get_contents_of_textbox(); myVal = myVal.replace(/\\/g, '\\\\'); // escape backslashes myVal = myVal.replace(/"/g, '\\"'); // escape quotes var JSON = '{ "test": "' + myVal + '" }'; send_to_server(JSON); </code></pre> <p>Result:</p> <pre><code>{ "test": "My mum pushed [a back\\slash] and I said \"Hello World\"!" } </code></pre> <h3><a href="http://jsfiddle.net/czs4S/" rel="noreferrer">Live demo.</a></h3>
24,124,417
Swift init Array with capacity
<p>How do I initialize an Array in swift with a specific capacity?</p> <p>I've tried:</p> <pre><code>var grid = Array &lt;Square&gt; () grid.reserveCapacity(16) </code></pre> <p>but get the error</p> <pre><code>expected declaration </code></pre>
43,233,766
5
1
null
2014-06-09 16:18:44.263 UTC
7
2022-06-03 10:56:40.193 UTC
null
null
null
null
1,370,927
null
1
42
arrays|swift
36,391
<p><strong>Swift 3 / Swift 4 / Swift 5</strong></p> <pre><code>var grid : [Square] = [] grid.reserveCapacity(16) </code></pre> <p>I believe it can be achieved in one line as well.</p>
8,236,701
Modeling Favorites
<p>I'm looking to add a <code>Favorite</code> model to my <code>User</code> and <code>Link</code> models. </p> <p><strong>Business Logic</strong></p> <ul> <li>Users can have multiple links (that is, they can add multiple links) </li> <li>Users can favorite multiple links (of their own or other users) </li> <li>A Link can be favorited by multiple users but have one owner</li> </ul> <p>I'm confused as to how to model this association and how would a user favorite be created once the models are in place? </p> <pre><code>class User &lt; ActiveRecord::Base has_many :links has_many :favorites end class Link &lt; ActiveRecord::Base belongs_to :user #can be favorited by multiple users end class Favorite &lt; ActiveRecord::Base belongs_to :user belongs_to :link end </code></pre>
8,236,769
1
0
null
2011-11-23 02:40:23.613 UTC
8
2011-11-23 03:22:42.083 UTC
null
null
null
null
830,554
null
1
5
ruby-on-rails|ruby|database|ruby-on-rails-3
911
<p>How about the following data model:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :links has_many :favorites, :dependent =&gt; :destroy has_many :favorite_links, :through =&gt; :favorites, :source =&gt; :link end class Link &lt; ActiveRecord::Base belongs_to :user has_many :favorites, :dependent =&gt; :destroy has_many :favorited, :through =&gt; :favorites, :source =&gt; :user end class Favorite &lt; ActiveRecord::Base belongs_to :user belongs_to :link end </code></pre> <p>Since <code>User</code> already has an association called <code>links</code>, and <code>Link</code> already has one called <code>users</code>, we cannot use the same name for the <code>has_many :through</code> association (e.g. <code>User has_many :links, :through =&gt; :favorites</code> would not work). So, we invent a new association name, and help Rails know what association to load from the intermediary association via the <code>source</code> attribute.</p> <p>Here's some pseudocode for using this association:</p> <pre><code># Some users user1 = User.create :name =&gt; "User1" user2 = User.create :name =&gt; "User2" # They create some links link1_1 = user1.links.create :url =&gt; "http://link1_1" link1_2 = user1.links.create :url =&gt; "http://link1_2" link2_1 = user2.links.create :url =&gt; "http://link2_1" link2_2 = user2.links.create :url =&gt; "http://link2_2" # User1 favorites User2's first link user1.favorites.create :link =&gt; link2_1 # User2 favorites both of User1's links user2.favorites.create :link =&gt; link1_1 user2.favorites.create :link =&gt; link1_2 user1.links =&gt; [link1_1, link1_2] user1.favorite_links =&gt; [link2_1] user2.links =&gt; [link2_1, link2_2] user2.favorite_links =&gt; [link1_1, link1_2] link1_1.favorited =&gt; [user2] link2_1.destroy user1.favorite_links =&gt; [] user2.links =&gt; [link2_2] </code></pre>
21,565,991
How to serve a file using iron router or meteor itself?
<p>I'm trying to serve a zip file on my Meteor app but I'm stuck. After a lot of Googling it seems the best way to go is with Iron Router but I don't know how:</p> <pre><code>Router.map -&gt; @route "data", where: 'server' path: '/data/:id' action: -&gt; data = getBase64ZipData(this.params.id) this.response.writeHead 200, { 'Content-Type': 'application/zip;base64' } ??? </code></pre>
21,566,476
1
2
null
2014-02-04 23:50:43.88 UTC
10
2014-12-12 00:42:41.11 UTC
null
null
null
null
335,911
null
1
15
meteor|iron-router
6,985
<h3>On the server:</h3> <pre class="lang-js prettyprint-override"><code>var fs = Npm.require('fs'); var fail = function(response) { response.statusCode = 404; response.end(); }; var dataFile = function() { // TODO write a function to translate the id into a file path var file = fileFromId(this.params.id); // Attempt to read the file size var stat = null; try { stat = fs.statSync(file); } catch (_error) { return fail(this.response); } // The hard-coded attachment filename var attachmentFilename = 'filename-for-user.zip'; // Set the headers this.response.writeHead(200, { 'Content-Type': 'application/zip', 'Content-Disposition': 'attachment; filename=' + attachmentFilename 'Content-Length': stat.size }); // Pipe the file contents to the response fs.createReadStream(file).pipe(this.response); }; Router.route('/data/:id', dataFile, {where: 'server'}); </code></pre> <h3>On the client:</h3> <pre class="lang-html prettyprint-override"><code>&lt;a href='/data/123'&gt;download zip&lt;/a&gt; </code></pre> <p>The nice part about this is that it will download the file as an attachment, and you can customize the filename that the user sees. The trick is writing the <code>fileFromId</code> function. I find it's easiest to store all of my dynamically generated files under <code>/tmp</code>.</p> <p>This answer assumes that the files are being generated dynamically. If you want to serve static content, you can just put your files under the <code>public</code> directory. See <a href="https://stackoverflow.com/questions/21341291/how-to-serve-static-content-images-fonts-etc-using-iron-router">this</a> question for more details.</p>
1,371,953
VBScript how to set the connection string
<p>I am not sure whether it has been disscussed before or not but I have the following code (I changed from example for an Access database.) </p> <p>I don't know what to put inside the <strong><em>'Provider'</em></strong> and the <strong><em>'Data Source'</em></strong>. I'm using <strong>MS SQL Server 2005</strong> and how to find this information in my machine? Please, even I try to follow from here <em><a href="http://www.connectionstrings.com/" rel="nofollow noreferrer">http://www.connectionstrings.com/</a></em>, yet I still don't know how to do it.</p> <p><pre><code> Dim conn, sql sql = "SELECT * FROM tblOutbox" Set conn = CreateObject("ADODB.Connection") With conn .Provider = "myProvider" .Mode = adModeReadWrite .ConnectionString = "Data Source=mysource;" &amp; _ "database=myDbase.mdf; " .Open End With If conn.State = adStateOpen Then WScript.Echo "Connection was established." End If conn.Close Set conn = Nothing </pre></code></p> <p>here is using access database: <pre><code> Dim conn Dim sql sql = "SELECT * FROM tblOutbox" Set conn = CreateObject("ADODB.Connection") With conn .Provider = "Microsoft.Jet.OLEDB.4.0" .Mode = adModeReadWrite .ConnectionString = "Data Source= f:/Status.mdb" .Open End With WScript.Echo "Connection was opened." conn.Close Set conn = Nothing WScript.Echo "Connection was closed." </pre></code></p>
1,392,061
4
0
null
2009-09-03 07:41:53.67 UTC
3
2010-03-23 22:26:27.533 UTC
2010-03-23 22:25:04.773 UTC
null
63,550
null
147,685
null
1
2
sql-server-2005|vbscript|connection-string|database-connection|wsh
55,210
<p>I finally found the solution thanks to your help. Under the Administrative Tools, Data Source (ODBS), driver tabs, I use provider: SQLNCLI, my Server: Data Source, and I add Recordset rs to the code. It seems that, without this one, the connection is not established. I don't know what happened.</p> <p><pre><code>Dim conn , rs, sql, ConnString sql = "SELECT * FROM tblOutbox" Set rs = CreateObject("ADODB.Recordset") Set conn = CreateObject("ADODB.Connection") With conn .Provider = "SQLNCLI" .Mode = adModeReadWrite .ConnectionString = "SERVER=.\SQLExpress;AttachDbFilename=F:\Test2.mdf;Database=Test2.mdf; Trusted_Connection=Yes;" .Open WScript.Echo "Connection was established." End With rs.Open sql,conn If conn.State = adStateOpen Then WScript.Echo "Connection was established." Else WScript.Echo "No Connection ." End If rs.Close Set rs = Nothing conn.Close Set conn = Nothing </pre></code></p>
2,010,166
connection url for sql server
<p>I downloaded microsfot's jdbc driver, and I am not sure what the connection.url should be?</p> <pre><code> &lt;property name="connection.driver_class"&gt;org.microsoft.sqlserver.jdbc&lt;/property&gt; &lt;property name="connection.url"&gt;jdbc:&lt;/property&gt; .. &lt;property name="dialect"&gt;org.hibernate.dialect.SQLServerDialect&lt;/property&gt; </code></pre> <p>i configured sqlexpress to work via tcpip and a static port already.</p>
2,010,180
4
0
null
2010-01-06 00:23:50.503 UTC
2
2022-01-25 17:11:13.58 UTC
null
null
null
null
68,183
null
1
8
java|hibernate
47,676
<p>Here you go:</p> <pre><code> &lt;property name = "hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/&gt; &lt;property name = "hibernate.connection.driver_class" value = "com.microsoft.sqlserver.jdbc.SQLServerDriver"/&gt; &lt;property name = "hibernate.connection.url" value = "jdbc:sqlserver://localhost;databaseName=cust;instanceName=SQLEXPRESS;"/&gt; &lt;property name = "hibernate.connection.username" value = "sa"/&gt; &lt;property name = "hibernate.connection.password" value = ""/&gt; &lt;property name = "hibernate.show_sql" value="true"/&gt; </code></pre>
2,129,519
Align text only on first separator in VIM
<p>Suppose I have this code:</p> <pre><code>width: 215px; height: 22px; margin-top: 3px; background-color: white; border: 1px solid #999999; </code></pre> <p>I want to align it this way:</p> <pre><code>width: 215px; height: 22px; margin-top: 3px; background-color: white; border: 1px solid #999999; </code></pre> <p>using Align.vim I can do <code>:Align \s</code> to use whitespace as separator, but that has 2 problems</p> <ol> <li>the initial indent is doubled</li> <li><strong>all</strong> whitespaces are considered separators, so the last line is messed up</li> </ol> <p>I've read through the many options Align.vim offers, but I haven't found a way to do this.</p>
2,129,690
4
1
null
2010-01-25 00:19:43.56 UTC
10
2017-10-18 09:24:37.563 UTC
null
null
null
null
148,968
null
1
15
vim|alignment
5,554
<p>If you use <a href="http://github.com/godlygeek/tabular" rel="noreferrer">Tabular</a>, then you can just do <code>:Tabularize /:\zs/</code>.</p> <p>Looking at Align's description on vim.org, a similar invocation should work for it. You could try <code>:Align :\zs</code>. I don't use Align, so I'm not positive.</p>
2,055,557
What is the use of the "-O" flag for running Python?
<p>Python can run scripts in optimized mode (<a href="https://docs.python.org/3/using/cmdline.html?highlight=pythonoptimize#cmdoption-O" rel="nofollow noreferrer"><code>python -O</code></a>) which turns off debugs, removes <a href="https://docs.python.org/3/reference/simple_stmts.html#assert" rel="nofollow noreferrer"><code>assert</code></a> statements, and IIRC it also removes docstrings.</p> <p>However, I have not seen it used. Is <code>python -O</code> actually used? If so, what for?</p>
2,083,834
4
0
null
2010-01-13 09:21:00.193 UTC
17
2022-08-25 23:58:15.253 UTC
2022-08-25 23:58:15.253 UTC
null
523,612
null
206,855
null
1
36
python|assert|assertion
14,102
<p>It saves a small amount of memory, and a small amount of disk space if you distribute any archive form containing only the <code>.pyo</code> files. (If you use <code>assert</code> a lot, and perhaps with complicated conditions, the savings can be not trivial and can extend to running time too).</p> <p>So, it's definitely not <em>useless</em> -- and of course it's being used (if you deploy a Python-coded server program to a huge number N of server machines, why <em>ever</em> would you want to waste N * X bytes to keep docstrings which nobody, ever, would anyway be able to access?!). Of course it would be better if it saved even more, but, hey -- waste not, want not!-)</p> <p>So it's pretty much a no-brainer to keep this functionality (which is in any case trivially simple to provide, you know;-) in Python 3 -- why add even "epsilon" to the latter's adoption difficulties?-)</p>
1,704,533
Intercept page exit event
<p>When editing a page within my system, a user might decide to navigate to another website and in doing so could lose all the edits they have not saved.</p> <p>I would like to intercept any attempt to go to another page and prompt the user to be sure they want this to happen since they could potentially lose their current work.</p> <p>Gmail does this in a very similar way. For example, compose a new email, start typing into the message body and enter a new location in the address bar (say twitter.com or something). It will prompt asking &quot;Are you sure?&quot;</p> <p>Ideas how to replicate this? I'm targeting IE8, but would like to be compatible with Firefox and Chrome also.</p>
1,704,783
4
2
null
2009-11-09 22:56:53.18 UTC
24
2021-07-09 08:46:13.89 UTC
2021-07-09 08:46:13.89 UTC
null
4,370,109
null
1,551
null
1
123
javascript|internet-explorer|dom-events
159,792
<p>Similar to Ghommey's answer, but this also supports old versions of IE and Firefox.</p> <pre><code>window.onbeforeunload = function (e) { var message = "Your confirmation message goes here.", e = e || window.event; // For IE and Firefox if (e) { e.returnValue = message; } // For Safari return message; }; </code></pre>
49,654,143
Spring Security 5 : There is no PasswordEncoder mapped for the id "null"
<p>I am migrating from Spring Boot 1.4.9 to Spring Boot 2.0 and also to Spring Security 5 and I am trying to do authenticate via OAuth 2. But I am getting this error: </p> <blockquote> <p>java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null </p> </blockquote> <p>From the documentation of <a href="https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-encoding" rel="noreferrer">Spring Security 5</a>, I get to know that storage format for password is changed.</p> <p>In my current code I have created my password encoder bean as:</p> <pre class="lang-java prettyprint-override"><code>@Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } </code></pre> <p>However it was giving me below error: </p> <blockquote> <p><strong>Encoded password does not look like BCrypt</strong></p> </blockquote> <p>So I update the encoder as per the <a href="https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-encoding" rel="noreferrer">Spring Security 5</a> document to:</p> <pre class="lang-java prettyprint-override"><code>@Bean public PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } </code></pre> <p>Now if I can see password in database it is storing as </p> <pre><code>{bcrypt}$2a$10$LoV/3z36G86x6Gn101aekuz3q9d7yfBp3jFn7dzNN/AL5630FyUQ </code></pre> <p>With that 1st error gone and now when I am trying to do authentication I am getting below error:</p> <blockquote> <p>java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null</p> </blockquote> <p>To solve this issue I tried all the below questions from Stackoverflow:</p> <ul> <li><p><a href="https://stackoverflow.com/questions/46999940/spring-boot-passwordencoder-error?noredirect=1&amp;lq=1">Spring Boot PasswordEncoder Error</a></p></li> <li><p><a href="https://stackoverflow.com/questions/26013251/spring-oauth2-password-encoder-is-not-set-in-daoauthenticationprovider">Spring Oauth2. Password encoder is not set in DaoAuthenticationProvider</a> </p></li> </ul> <p>Here is a question similar to mine but not answerd:</p> <ul> <li><a href="https://stackoverflow.com/questions/49236707/spring-security-5-password-migration">Spring Security 5 - Password Migration</a></li> </ul> <p>NOTE: I am already storing encrypted password in database so no need to encode again in <code>UserDetailsService</code>.</p> <p>In the <a href="https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-encoding" rel="noreferrer">Spring security 5</a> documentation they suggested you can handle this exception using:</p> <blockquote> <p>DelegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(PasswordEncoder)</p> </blockquote> <p>If this is the fix then where should I put it? I have tried to put it in <code>PasswordEncoder</code> bean like below but it wasn't working: </p> <pre><code>DelegatingPasswordEncoder def = new DelegatingPasswordEncoder(idForEncode, encoders); def.setDefaultPasswordEncoderForMatches(passwordEncoder); </code></pre> <p><strong>MyWebSecurity class</strong></p> <pre class="lang-java prettyprint-override"><code>@Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override public void configure(WebSecurity web) throws Exception { web .ignoring() .antMatchers(HttpMethod.OPTIONS) .antMatchers("/api/user/add"); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } </code></pre> <p><strong>MyOauth2 Configuration</strong></p> <pre class="lang-java prettyprint-override"><code>@Configuration @EnableAuthorizationServer protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Bean public TokenStore tokenStore() { return new InMemoryTokenStore(); } @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Bean public TokenEnhancer tokenEnhancer() { return new CustomTokenEnhancer(); } @Bean public DefaultAccessTokenConverter accessTokenConverter() { return new DefaultAccessTokenConverter(); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .tokenStore(tokenStore()) .tokenEnhancer(tokenEnhancer()) .accessTokenConverter(accessTokenConverter()) .authenticationManager(authenticationManager); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients .inMemory() .withClient("test") .scopes("read", "write") .authorities(Roles.ADMIN.name(), Roles.USER.name()) .authorizedGrantTypes("password", "refresh_token") .secret("secret") .accessTokenValiditySeconds(1800); } } </code></pre> <p>Please guide me with this issue. I have spend hours to fix this but not able to fix.</p>
49,683,417
11
3
null
2018-04-04 14:51:52.86 UTC
11
2022-09-01 19:25:44.263 UTC
2018-04-05 09:07:36.457 UTC
null
5,277,820
null
3,855,773
null
1
98
java|spring|spring-boot|spring-security|spring-security-oauth2
134,856
<p>When you are configuring the <code>ClientDetailsServiceConfigurer</code>, you have to also apply the new <a href="https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-format" rel="noreferrer">password storage format</a> to the client secret.</p> <pre class="lang-java prettyprint-override"><code>.secret("{noop}secret") </code></pre>
49,436,161
MAX() OVER PARTITION BY in Oracle SQL
<p>I am trying to utilize the MAX() OVER PARTITION BY function to evaluate the most recent receipt for a specific part that my company has bought. Below is an example table of the information for a few parts from the last year:</p> <pre class="lang-none prettyprint-override"><code>| VEND_NUM | VEND_NAME | RECEIPT_NUM | RECEIPT_ITEM | RECEIPT_DATE | |----------|--------------|-------------|----------|--------------| | 100 | SmallTech | 2001 | 5844HAJ | 11/22/2017 | | 100 | SmallTech | 3188 | 5521LRO | 12/31/2017 | | 200 | RealSolution | 5109 | 8715JUI | 05/01/2017 | | 100 | SmallTech | 3232 | 8715JUI | 11/01/2017 | | 200 | RealSolution | 2101 | 4715TEN | 01/01/2017 | </code></pre> <p>As you can see, the third and fourth row show two different vendors for the SAME part number.</p> <p>Here is my current query:</p> <pre><code>WITH -- various other subqueries above... AllData AS ( SELECT VEND_NUM, VEND_NAME, RECEIPT_NUM, RECEIPT_ITEM, RECEIPT_DATE FROM tblVend INNER JOIN tblReceipt ON VEND_NUM = RECEIPT_VEND_NUM WHERE VEND_NUM = '100' OR VEND_NUM = '200' AND RECEIPT_DATE &gt;= '01-Jan-2017' ), SELECT MAX(RECEIPT_DATE) OVER PARTITION BY(RECEIPT_ITEM) AS "Recent Date", RECEIPT_ITEM FROM AllData </code></pre> <p>My return set looks like:</p> <pre class="lang-none prettyprint-override"><code>| Recent Date | RECEIPT_ITEM | |-------------|--------------| | 11/22/2017 | 5844HAJ | | 12/31/2017 | 5521LRO | | 11/01/2017 | 8715JUI | | 11/01/2017 | 8715JUI | | 01/01/2017 | 4715TEN | </code></pre> <p>However, it should look like this:</p> <pre class="lang-none prettyprint-override"><code>| Recent Date | RECEIPT_ITEM | |-------------|--------------| | 11/22/2017 | 5844HAJ | | 12/31/2017 | 5521LRO | | 11/01/2017 | 8715JUI | | 01/01/2017 | 4715TEN | </code></pre> <p>Can anybody please offer advice as to what I'm doing wrong? It looks like it is simply replacing the most recent date, not giving me just the row I want that is most recent.</p> <p>Ultimately, I would like for my table to look like this. However, I don't know how to use the MAX() or MAX() OVER PARTITION BY() functions properly to allow for this:</p> <pre class="lang-none prettyprint-override"><code>| VEND_NUM | VEND_NAME | RECEIPT_NUM | RECEIPT_ITEM | RECEIPT_DATE | |----------|--------------|-------------|----------|--------------| | 100 | SmallTech | 2001 | 5844HAJ | 11/22/2017 | | 100 | SmallTech | 3188 | 5521LRO | 12/31/2017 | | 100 | SmallTech | 3232 | 8715JUI | 11/01/2017 | | 200 | RealSolution | 2101 | 4715TEN | 01/01/2017 | </code></pre>
49,436,307
4
4
null
2018-03-22 18:39:41.407 UTC
2
2020-04-13 18:05:44.433 UTC
2018-03-26 07:38:06.24 UTC
null
330,315
null
4,876,561
null
1
5
sql|oracle|window-functions
71,536
<p>Use window function <code>ROW_NUMBER() OVER (PARTITION BY receipt_item ORDER BY receipt_date DESC)</code> to assign a sequence number to each row. The row with the most recent <code>receipt_date</code> for a <code>receipt_item</code> will be numbered as 1.</p> <pre><code>WITH -- various other subqueries above... AllData AS ( SELECT VEND_NUM, VEND_NAME, RECEIPT_NUM, RECEIPT_ITEM, RECEIPT_DATE, ROW_NUMBER() OVER (PARTITION BY RECEIPT_ITEM ORDER BY RECEIPT_DATE DESC ) AS RN FROM tblVend INNER JOIN tblReceipt ON VEND_NUM = RECEIPT_VEND_NUM WHERE VEND_NUM IN ( '100','200') AND RECEIPT_DATE &gt;= '01-Jan-2017' ) SELECT VEND_NUM, VEND_NAME, RECEIPT_NUM, RECEIPT_ITEM, RECEIPT_DATE FROM AllData WHERE RN = 1 </code></pre>
26,178,441
How to toggle a highlighted selected item in a group list
<p>I have this in using Bootstrap:</p> <pre><code> &lt;ul class="list-group"&gt; &lt;li class="list-group-item active"&gt;Cras justo odio&lt;/li&gt; &lt;li class="list-group-item"&gt;Dapibus ac facilisis in&lt;/li&gt; &lt;li class="list-group-item"&gt;Morbi leo risus&lt;/li&gt; &lt;li class="list-group-item"&gt;Porta ac consectetur ac&lt;/li&gt; &lt;li class="list-group-item"&gt;Vestibulum at eros&lt;/li&gt; &lt;li class="list-group-item"&gt;Cras justo odio&lt;/li&gt; &lt;li class="list-group-item"&gt;Dapibus ac facilisis in&lt;/li&gt; &lt;li class="list-group-item"&gt;Morbi leo risus&lt;/li&gt; &lt;li class="list-group-item"&gt;Porta ac consectetur ac&lt;/li&gt; &lt;li class="list-group-item"&gt;Vestibulum at eros&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>The top row is selected.</p> <p>I only ever want to show to the User 1 selected row.</p> <p>I can raise an event when the User clicks on a row by adding a function to a Click-Event using Javascript.</p> <p>I can then set that Row to be Active. but what happens is that the previous selected Row needs to be deselected.</p> <p>What is the accepted way to do this?</p> <p>How do I enumerate and access each row to change its Class settings?</p> <p>Is there a better CSS way to do this?</p> <p>ADDITIONAL All these methods work (thanks everyone) but if I have more than 1 option group on my page how can I explicitly remove the active highlighted row on the one I am using?</p>
26,178,517
10
1
null
2014-10-03 11:51:04.837 UTC
4
2021-06-09 14:55:22.657 UTC
2014-10-14 23:10:48.497 UTC
null
515,189
null
846,281
null
1
20
javascript|html|twitter-bootstrap
41,476
<p>Here we go buddy. I have made a JSfiddle for ya</p> <p><a href="http://jsfiddle.net/mgjk3xk2/" rel="noreferrer">demo</a></p> <pre><code>$(function(){ console.log('ready'); $('.list-group li').click(function(e) { e.preventDefault() $that = $(this); $that.parent().find('li').removeClass('active'); $that.addClass('active'); }); }) </code></pre> <p>JSFiddle updated to have more than one Group</p> <p><a href="http://jsfiddle.net/mgjk3xk2/1/" rel="noreferrer">http://jsfiddle.net/mgjk3xk2/1/</a></p>
49,075,027
Angular - Dynamically add/remove validators
<p>I have a <code>FormGroup</code> defined like below:</p> <pre><code>this.businessFormGroup: this.fb.group({ 'businessType': ['', Validators.required], 'description': ['', Validators.compose([Validators.required, Validators.maxLength(200)])], 'income': [''] }) </code></pre> <p>Now when <code>businessType</code> is <code>Other</code> , I want to remove <code>Validators.required</code> validator from <code>description</code>. And if <code>businessType</code> is not <code>Other</code>, I want to add back the <code>Validators.required</code>.</p> <p>I am using the below code to dynamically add/remove the <code>Validators.required</code>. However, it clears the existing <code>Validators.maxLength</code> validator.</p> <pre><code>if(this.businessFormGroup.get('businessType').value !== 'Other'){ this.businessFormGroup.get('description').validator = &lt;any&gt;Validators.compose([Validators.required]); } else { this.businessFormGroup.get('description').clearValidators(); } this.businessFormGroup.get('description').updateValueAndValidity(); </code></pre> <p>My question is, how can I retain the existing validators when adding/removing the <code>required</code> validator. </p>
49,076,116
8
4
null
2018-03-02 18:13:42.32 UTC
14
2021-08-31 14:58:06.367 UTC
null
null
null
null
641,103
null
1
75
angular|angular-forms|angular-validation
98,503
<p>If you are using Angular 12.2 or higher, you can use the <code>AbstractControl</code> methods <code>addValidators</code>, <code>removeValidators</code>, and <code>hasValidator</code>, <a href="https://angular.io/api/forms/AbstractControl#addvalidators" rel="noreferrer">as per the docs</a>:</p> <pre><code>if(this.businessFormGroup.get('businessType').value !== 'Other'){ this.businessFormGroup.get('description').addValidators(Validators.required); } else { this.businessFormGroup.get('description').clearValidators(); } </code></pre> <p>For older versions, Angular forms have a built in function <a href="https://angular.io/api/forms/AbstractControl#setValidators" rel="noreferrer">setValidators()</a> that enables programmatic assignment of Validators. However, this will overwrite your validators.</p> <p>For your example you can do:</p> <pre><code>if(this.businessFormGroup.get('businessType').value !== 'Other'){ this.businessFormGroup.controls['description'].setValidators([Validators.required, Validators.maxLength(200)]); } else { this.businessFormGroup.controls['description'].setValidators([Validators.maxLength(200)]); } this.businessFormGroup.controls['description'].updateValueAndValidity(); </code></pre> <p>It is important to keep in mind that <strong>by using this method you will overwrite your existing validators</strong> so you will need to include all the validators you need/want for the control that you are resetting.</p>
7,149,923
Android how to wait for code to finish before continuing
<p>I have a method called <code>hostPhoto()</code>; it basically uploads an image to a site and retrieves a link. I then have an other method to post the link to a website.</p> <p>Now the way Im' using this method is like this:</p> <pre><code>String link = hostPhoto(); //returns a link in string format post(text+" "+link); // posts the text + a link. </code></pre> <p>My problem is... that the <code>hostPhoto()</code> takes a few seconds to upload and retrieve the link, my program seems to not wait and continue posting, therefore im left with the link as null,</p> <p>Is there anyway i could make it get the link first... and then post? like some sort of onComplete? or something like that.. i thought my method above would work but by doing Log.i's it seems the link is returned to the string after a second or so.</p> <p>UPDATE: This is the updates progress on my problem, im using a AsyncTask as informed, but the Log.i's error out showing the urlLink as a null... this means that the link requested from hostphoto never came back intime for the Logs..</p> <p>UPDATE 2: FINALLY WORKS! The problem was the Thread within the hostPhoto(), could someone provide me an explination why that thread would have caused this? Thanks to all who replied.</p> <pre><code>private class myAsyncTask extends AsyncTask&lt;Void, Void, Void&gt; { String urlLink; String text; public myAsyncTask(String txt){ text=txt; } @Override protected Void doInBackground(Void... params) { urlLink=hostPhoto(); //Log.i("Linked", urlLink); return null; } @Override protected void onPostExecute(Void result) { try { Log.i("Adding to status", urlLink); mLin.updateStatus(text+" "+urlLink); Log.i("Status:", urlLink); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre> <p>hostPhoto() does this:</p> <pre><code> String link; new Thread(){ @Override public void run(){ HostPhoto photo = new HostPhoto(); //create the host class link= photo.post(filepath); // upload the photo and return the link Log.i("link:",link); } }.start(); </code></pre>
7,150,042
5
5
null
2011-08-22 15:37:59.883 UTC
1
2016-11-22 10:34:23.33 UTC
2011-08-23 10:51:03.613 UTC
null
704,513
null
901,132
null
1
10
java|android|hyperlink|android-asynctask
43,211
<p>You can use AsyncTask here,</p> <p><a href="http://developer.android.com/reference/android/os/AsyncTask.html" rel="noreferrer">AsyncTask</a></p> <p>By Using that you can execute the code of </p> <p><code>hostPhoto()</code> </p> <p>in doInBackground() and then execute the code of </p> <p><code>post(text+" "+link);</code> </p> <p>in the onPostExecute() Method, that will the best solution for you.</p> <p>You can write the code in this pattern</p> <pre><code>private class MyAsyncTask extends AsyncTask&lt;Void, Void, Void&gt; { @Override protected Void doInBackground(Void... params) { hostPhoto(); return null; } @Override protected void onPostExecute(Void result) { post(text+" "+link); } } </code></pre> <p>and the can execute it using </p> <pre><code> new MyAsyncTask().execute(); </code></pre>
7,574,857
Group array by subarray values
<p>I have an array of subarrays in the following format:</p> <pre><code>array ( a =&gt; array ( id = 20, name = chimpanzee ) b =&gt; array ( id = 40, name = meeting ) c =&gt; array ( id = 20, name = dynasty ) d =&gt; array ( id = 50, name = chocolate ) e =&gt; array ( id = 10, name = bananas ) f =&gt; array ( id = 50, name = fantasy ) g =&gt; array ( id = 50, name = football ) ) </code></pre> <p>And I would like to group it into a new array based on the id field in each subarray.</p> <pre><code>array ( 10 =&gt; array ( e =&gt; array ( id = 10, name = bananas ) ) 20 =&gt; array ( a =&gt; array ( id = 20, name = chimpanzee ) c =&gt; array ( id = 20, name = dynasty ) ) 40 =&gt; array ( b =&gt; array ( id = 40, name = meeting ) ) 50 =&gt; array ( d =&gt; array ( id = 50, name = chocolate ) f =&gt; array ( id = 50, name = fantasy ) g =&gt; array ( id = 50, name = football ) ) ) </code></pre>
7,574,916
5
0
null
2011-09-27 19:49:39.02 UTC
16
2020-07-27 17:41:12.493 UTC
2020-07-17 12:56:43.757 UTC
null
1,378,646
null
476,426
null
1
64
php|arrays|algorithm|sorting
122,552
<pre><code>$arr = array(); foreach ($old_arr as $key =&gt; $item) { $arr[$item['id']][$key] = $item; } ksort($arr, SORT_NUMERIC); </code></pre>
14,080,758
Reversing a linkedlist recursively in c
<p>The following code works fine when head is sent as a parameter to it. As I am new to C, I couldn't understand how it works. Help me out please.</p> <pre><code>struct node *recursiveReverseLL(struct node *list) { struct node *revHead; if (list == NULL || list-&gt;link == NULL) { return list; } revHead = recursiveReverseLL(list-&gt;link); list-&gt;link-&gt;link = list; list-&gt;link = NULL; return revHead; } </code></pre> <p>I dont know how the links are provided using those recursive calls. ie) if the links are as,</p> <pre><code>1 -&gt; 2 -&gt; 3 -&gt; 4 </code></pre> <p>then hw is it changed as,</p> <pre><code>4 -&gt; 3 -&gt; 2 -&gt; 1 </code></pre>
14,080,830
9
3
null
2012-12-29 10:25:34.877 UTC
14
2020-05-07 07:01:54.673 UTC
2012-12-29 18:42:09.34 UTC
null
227,665
null
1,397,864
null
1
20
c|recursion|linked-list|singly-linked-list
78,065
<p>The general recursive algorithm for this is:</p> <ol> <li><code>Divide</code> the list in <code>2</code> parts - first node and rest of the list.</li> <li>Recursively call reverse for the <code>rest</code> of the linked list.</li> <li>Link <code>rest</code> to <code>first</code>.</li> <li>Fix <code>head</code> pointer</li> </ol> <p>Here is the code with inline comments:</p> <pre><code>struct node* recursiveReverseLL(struct node* first){ if(first == NULL) return NULL; // list does not exist. if(first-&gt;link == NULL) return first; // list with only one node. struct node* rest = recursiveReverseLL(first-&gt;link); // recursive call on rest. first-&gt;link-&gt;link = first; // make first; link to the last node in the reversed rest. first-&gt;link = NULL; // since first is the new last, make its link NULL. return rest; // rest now points to the head of the reversed list. } </code></pre> <p>I hope this picture will make things clearer:</p> <p><a href="https://i.stack.imgur.com/prOq0.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/prOq0.gif" alt="image"></a><br> <sub>(source: <a href="http://geeksforgeeks.org/wp-content/uploads/2009/07/Linked-List-Rverse.gif" rel="noreferrer">geeksforgeeks.org</a>)</sub><br> .</p>
14,006,150
Android SearchView Icon
<p>I want to disable the Mag icon displayed inside the search view component. Any idea how to reference it and remove it or replace it with another drawable ?</p> <p><img src="https://i.stack.imgur.com/0IqyN.png" alt="enter image description here"></p>
14,006,295
10
4
null
2012-12-22 20:03:07.393 UTC
4
2017-10-30 17:24:19.763 UTC
null
null
null
null
155,196
null
1
29
android|android-actionbar|actionbarsherlock|searchview
25,408
<p>In your theme:</p> <pre><code>&lt;style name="Theme" parent="Your parent theme"&gt; &lt;item name="android:searchViewSearchIcon"&gt;@android:drawable/ic_search&lt;/item&gt; &lt;/style&gt; </code></pre> <p><strong>Edit:</strong><br> <code>searchViewSearchIcon</code> is a private attribute. This answer therefore does not work (on the native ActionBar).</p>
14,134,712
Epplus not reading excel file
<p>Below is my code to read excel file.</p> <p>Code.</p> <pre><code>FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeExceptionReport.xls"); ExcelPackage pck = new ExcelPackage(newFile); var ws = pck.Workbook.Worksheets.Add("Content"); ws.View.ShowGridLines = false; ws.Cells["J12"].Value = "Test Write"; pck.Save(); System.Diagnostics.Process.Start("C:\\Excel\\SampleStockTakeExceptionReport.xls"); </code></pre> <p>When i run the code it throw a runtime error.</p> <p>Error</p> <pre><code>System.Exception: Can not open the package. Package is an OLE compound document. If this is an encrypted package, please supply the password ---&gt; System.IO.FileFormatException: File contains corrupted data. at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.FindPosition(Stream archiveStream) at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.SeekableLoad(ZipIOBlockManager blockManager) at MS.Internal.IO.Zip.ZipArchive..ctor(Stream archiveStream, FileMode mode, FileAccess access, Boolean streaming, Boolean ownStream) at MS.Internal.IO.Zip.ZipArchive.OpenOnStream(Stream stream, FileMode mode, FileAccess access, Boolean streaming) at System.IO.Packaging.ZipPackage..ctor(Stream s, FileMode mode, FileAccess access, Boolean streaming) at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming) at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess) at OfficeOpenXml.ExcelPackage.ConstructNewFile(Stream stream, String password) --- End of inner exception stack trace --- at OfficeOpenXml.ExcelPackage.ConstructNewFile(Stream stream, String password) at OfficeOpenXml.ExcelPackage..ctor(FileInfo newFile) at Report.Form1.ExportToExcel1(DataTable Tbl, String ExcelFilePath) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 39 </code></pre> <p>Appreciated if anyone could advice/help on this. Thanks.</p>
14,134,762
3
0
null
2013-01-03 07:27:47.277 UTC
4
2019-02-23 08:00:10.99 UTC
null
null
null
null
1,225,432
null
1
29
c#|visual-studio-2010|epplus
41,362
<p>Epplus does not handle .xls (BIFF8 format) files as far as i know.</p> <p>It handles the newer .xlsx (Open Office Xml) format.</p> <p>You can use <a href="http://code.google.com/p/excellibrary/" rel="noreferrer">excellibrary</a> though as it works for xls files.</p>
13,990,465
3d Numpy array to 2d
<p>I have a 3d matrix like this</p> <pre><code>arange(16).reshape((4,2,2)) array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]], [[12, 13], [14, 15]]]) </code></pre> <p>and would like to stack them in grid format, ending up with</p> <pre><code>array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]]) </code></pre> <p>Is there a way of doing without explicitly hstacking (and/or vstacking) them or adding an extra dimension and reshaping (not sure this would work)?</p> <p>Thanks, </p>
13,990,648
1
0
null
2012-12-21 12:44:53.413 UTC
13
2013-09-16 12:09:43.977 UTC
null
null
null
null
1,470,604
null
1
30
python|numpy|multidimensional-array
38,127
<pre><code>In [27]: x = np.arange(16).reshape((4,2,2)) In [28]: x.reshape(2,2,2,2).swapaxes(1,2).reshape(4,-1) Out[28]: array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 12, 13], [10, 11, 14, 15]]) </code></pre> <hr> <p>I've posted more general functions for <a href="https://stackoverflow.com/a/16873755/190597">reshaping/unshaping arrays into blocks, here</a>.</p>
13,916,726
Using $index with the AngularJS 'ng-options' directive?
<p>Say that I bind an array to a <code>select</code> tag using the following:</p> <pre><code>&lt;select ng-model="selData" ng-options="$index as d.name for d in data"&gt; </code></pre> <p>In this case, the associated <code>option</code> tags are assigned a sequence of index values: (0, 1, 2, ...). However, when I select something from the drop-down, the value of <code>selData</code> is getting bound to <code>undefined</code>. Should the binding actually work?</p> <p>On the other hand, say that I instead do the following:</p> <pre><code>&lt;select ng-model="selData" ng-options="d as d.name for d in data"&gt; </code></pre> <p>Here, the <code>option</code> tags get the same index, but the entire object is bound on change. Is it working this way by design, or this behavior simply a nice bug or side-effect of AngularJS?</p>
13,917,351
5
0
null
2012-12-17 15:11:45.2 UTC
16
2018-12-03 13:03:54.607 UTC
2018-12-03 12:59:30.91 UTC
null
1,497,596
null
1,910,294
null
1
61
angularjs|html-select
77,664
<p>$index is defined for ng-repeat, not select. I think this explains the <code>undefined</code>. (So, no, this shouldn't work.)</p> <p>Angular supports binding on the entire object. The documentation could be worded better to indicate this, but it does hint at it: "ngOptions ... should be used instead of ngRepeat when you want the select model to be bound to a non-string value."</p>
28,882,878
How to get last 24 hours from current time-stamp?
<p>I am trying to pull all data for the last 24 hours but starting from the current time. If the current date-time is 5/3 and the time is 11:30 then i want to pull the last 24 hours from 11:30. The data type for date field is <code>datetime</code> and it has only the date and time values without the seconds. Here is my current query</p> <pre><code>select Name, Location, myDate from myTable where myDate&gt;= getdate()-24 </code></pre> <p>the query above is giving me everything but i only want from the current time. this is how myDate look like in the table</p> <pre><code> 2015-03-05 10:30:00.000 2015-03-05 11:00:00.000 2015-03-05 11:30:00.000 2015-03-05 12:00:00.000 2015-03-05 12:30:00.000 2015-03-05 13:00:00.000 2015-03-05 13:30:00.000 2015-03-05 14:00:00.000 2015-03-05 14:30:00.000 </code></pre>
28,883,038
3
3
null
2015-03-05 16:32:31.523 UTC
2
2015-03-07 14:56:13.253 UTC
2015-03-07 14:48:03.77 UTC
null
1,080,354
null
1,669,621
null
1
2
sql|sql-server|tsql
39,485
<p>To be more explicit with your intentions, you may want to write your query like so:</p> <pre><code> select Name, Location, myDate from myTable where myDate&gt;= DATEADD(hh, -24, GETDATE()) </code></pre> <p><a href="https://msdn.microsoft.com/en-us/library/ms186819.aspx" rel="noreferrer">SQL Server DATEADD</a></p>
9,290,994
SQL Conditional column data return in a select statement
<p>Here is a simplication of the problem: I have a select that looks like this:</p> <pre><code>Select ID, Assignee, WorkStream from assignees; </code></pre> <p>And a snap shot of the data returned looked like this</p> <pre><code>1|Joe Soap|Internal 2|Mrs Balls|External </code></pre> <p>What I would like to do is have the select not display the Assignee name if the worksteam is internal. Instead to display the Workstream. </p> <p>So for example the outcome I want to achieve would be this:</p> <pre><code>1|Internal|Internal 2|Mrs Balls|External </code></pre> <p>I hope this makes sense? Basically a conditional select that can detect if a certain column contains a certain value, then replace another columns value with [whatever]. </p> <p>Thanks in advance!</p> <p>EDIT I want to achieve something like this:</p> <pre><code>Select ID, if (workstream='internal' select Workstream as Assignee - else - select Assignee as Assigneee), WorkStream from assignees; </code></pre>
9,291,033
2
1
null
2012-02-15 09:42:41.403 UTC
5
2012-02-15 09:50:22.393 UTC
null
null
null
null
41,543
null
1
45
sql
99,259
<p>You didn't mention your DBMS but a searched <code>CASE</code> statement works in all major DBMS's I know off.</p> <pre><code>SELECT ID , CASE WHEN WorkStream = 'Internal' THEN WorkStream ELSE Assignee END AS Assignee , Workstream FROM assignees </code></pre> <hr> <p>Reference: <a href="http://msdn.microsoft.com/en-us/library/ms181765.aspx">MSDN</a></p> <blockquote> <p><strong>CASE</strong></p> <p>Evaluates a list of conditions and returns one of multiple possible result expressions.</p> </blockquote>
19,645,655
Disable Skrollr for mobile device ( <767px )
<p>Firstly would like to thanks @prinzhorn for such an amazing and powerful library. My question: I have implemented a Skrollr parallax background to the header of my website but I would like to disable this feature when viewed on a mobile device, particularly iphones, etc. eg. (max-width: 767px).I was wondering what would be the best way to do this? And if the destroy() function was able to do this or I should be using another technique? Also, if destroy() is the answer, how could I implement this correctly? Many thanks and examples or demo's greatly appreciated.</p>
27,006,015
6
2
null
2013-10-28 21:44:58.747 UTC
8
2017-09-20 08:38:13.79 UTC
null
null
null
null
2,929,823
null
1
10
jquery|html|parallax|skrollr
18,499
<p>Skrollr has its own mobile check function</p> <pre><code>var s = skrollr.init(); if (s.isMobile()) { s.destroy(); } </code></pre>
19,669,001
Using len for text but discarding spaces in the count
<p>So, I am trying to create a program which counts the number of characters in a string which the user inputs, but I want to discard any spaces that the user enters.</p> <pre><code>def main(): full_name = str(input("Please enter in a full name: ")).split(" ") for x in full_name: print(len(x)) main() </code></pre> <p>Using this, I can get the number of the characters in each word, without spaces, but I don't know how to add each number together and print the total.</p>
19,669,051
8
2
null
2013-10-29 20:59:18.13 UTC
3
2021-03-07 10:10:58.043 UTC
2019-05-20 09:42:49.837 UTC
null
6,395,052
null
2,933,784
null
1
8
python|python-3.x
45,301
<p>Count the length and subtract the number of spaces:</p> <pre><code>&gt;&gt;&gt; full_name = input("Please enter in a full name: ") Please enter in a full name: john smith &gt;&gt;&gt; len(full_name) - full_name.count(' ') 9 &gt;&gt;&gt; len(full_name) </code></pre>
903,228
Why use precompiled headers (C/C++)?
<p>Why use precompiled headers?</p> <hr/> <p>Reading the responses, I suspect what I've been doing with them is kind of stupid:</p> <pre><code>#pragma once // Defines used for production versions #ifndef PRODUCTION #define eMsg(x) (x) // Show error messages #define eAsciiMsg(x) (x) #else #define eMsg(x) (L"") // Don't show error messages #define eAsciiMsg(x) ("") #endif // PRODUCTION #include "targetver.h" #include "version.h" // Enable "unsafe", but much faster string functions #define _CRT_SECURE_NO_WARNINGS #define _SCL_SECURE_NO_WARNINGS // Standard includes #include &lt;stdio.h&gt; #include &lt;tchar.h&gt; #include &lt;iostream&gt; #include &lt;direct.h&gt; #include &lt;cstring&gt; #ifdef _DEBUG #include &lt;cstdlib&gt; #endif // Standard Template Library #include &lt;bitset&gt; #include &lt;vector&gt; #include &lt;list&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; #include &lt;string&gt; #include &lt;numeric&gt; // Boost libraries #include &lt;boost/algorithm/string.hpp&gt; #include &lt;boost/lexical_cast.hpp&gt; #include &lt;boost/scoped_array.hpp&gt; //Windows includes #define WIN32_LEAN_AND_MEAN #include &lt;windows.h&gt; #include "FILETIME_Comparisons.h" #include &lt;shlwapi.h&gt; #include &lt;Shellapi.h&gt; #include &lt;psapi.h&gt; #include &lt;imagehlp.h&gt; #include &lt;mscat.h&gt; #include &lt;Softpub.h&gt; #include &lt;sfc.h&gt; #pragma comment(lib, "wintrust.lib") #pragma comment(lib,"kernel32.lib") #pragma comment(lib,"Psapi.lib") #pragma comment(lib,"shlwapi.lib") #pragma comment(lib,"imagehlp.lib") #pragma comment(lib,"Advapi32.lib") #pragma comment(lib,"Shell32.lib") #pragma comment(lib,"Sfc.lib") #pragma comment(lib,"Version.lib") // Crypto ++ libraries #ifdef _DEBUG #pragma comment(lib,"cryptlibd.lib") #else #pragma comment(lib,"cryptlib.lib") #endif #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 #include &lt;md5.h&gt; #include &lt;sha.h&gt; // String libraries #include "stringUnicodeConversions.h" #include "expandEnvStrings.h" #include "randomString.h" #include "getShortPathName.h" // Regular Expression Libraries #include "fpattern.h" // File Result Record #include "unixTimeToFileTime.h" #include "fileData.h" // Writer #include "writeFileData.h" // Criteria Structure System #include "priorities.h" #include "criterion.H" #include "OPSTRUCT.H" #include "regexClass.H" #include "FILTER.h" // Sub Programs Root Class #include "subProgramClass.h" // Global data #include "globalOptions.h" // Logger #include "logger.h" // Console parser #include "consoleParser.h" // Timeout handler #include "timeoutThread.h" // Zip library #include "zip.h" #include "unzip.h" #include "zipIt.h" // Scanner #include "mainScanner.h" #include "filesScanner.h" // Sub Programs #include "volumeEnumerate.h" #include "clsidCompressor.h" #include "times.h" #include "exec.h" #include "uZip.h" // 64 bit support #include "disable64.h" </code></pre>
903,234
5
2
null
2009-05-24 06:35:24.347 UTC
18
2021-11-28 15:47:45.193 UTC
2019-06-29 18:05:12.46 UTC
null
63,550
null
82,320
null
1
52
c++|precompiled-headers
45,366
<p>It compiles a <em>lot</em> quicker. C++ compilation takes years without them. Try comparing some time in a large project!</p>
1,032,376
guid to base64, for URL
<p>Question: is there a better way to do that?</p> <p>VB.Net</p> <pre><code>Function GuidToBase64(ByVal guid As Guid) As String Return Convert.ToBase64String(guid.ToByteArray).Replace("/", "-").Replace("+", "_").Replace("=", "") End Function Function Base64ToGuid(ByVal base64 As String) As Guid Dim guid As Guid base64 = base64.Replace("-", "/").Replace("_", "+") &amp; "==" Try guid = New Guid(Convert.FromBase64String(base64)) Catch ex As Exception Throw New Exception("Bad Base64 conversion to GUID", ex) End Try Return guid End Function </code></pre> <p>C#</p> <pre><code>public string GuidToBase64(Guid guid) { return Convert.ToBase64String(guid.ToByteArray()).Replace("/", "-").Replace("+", "_").Replace("=", ""); } public Guid Base64ToGuid(string base64) { Guid guid = default(Guid); base64 = base64.Replace("-", "/").Replace("_", "+") + "=="; try { guid = new Guid(Convert.FromBase64String(base64)); } catch (Exception ex) { throw new Exception("Bad Base64 conversion to GUID", ex); } return guid; } </code></pre>
1,032,451
5
12
null
2009-06-23 12:51:09.987 UTC
13
2022-09-14 08:12:04.343 UTC
2015-12-21 18:48:55.297 UTC
null
156,604
null
40,868
null
1
57
c#|.net|vb.net|guid|base64
46,675
<p>I understand that the reason you are clipping == in the end is that because you can be certain that for GUID (of 16 bytes), encoded string will <em>always</em> end with ==. So 2 characters can be saved in every conversion.</p> <p>Beside the point @Skurmedal already mentioned (should throw an exception in case of invalid string as input), I think the code you posted is just good enough.</p>
435,964
How do I find duplicate entries in a database table?
<p>The following query will display all Dewey Decimal numbers that have been duplicated in the "book" table:</p> <pre><code>SELECT dewey_number, COUNT(dewey_number) AS NumOccurrences FROM book GROUP BY dewey_number HAVING ( COUNT(dewey_number) &gt; 1 ) </code></pre> <p>However, what I'd like to do is have my query display the name of the authors associated with the duplicated entry (the "book" table and "author" table are connected by "author_id"). In other words, the query above would yield the following:</p> <pre><code>dewey_number | NumOccurrences ------------------------------ 5000 | 2 9090 | 3 </code></pre> <p>What I'd like the results to display is something similar to the following:</p> <pre><code>author_last_name | dewey_number | NumOccurrences ------------------------------------------------- Smith | 5000 | 2 Jones | 5000 | 2 Jackson | 9090 | 3 Johnson | 9090 | 3 Jeffers | 9090 | 3 </code></pre> <p>Any help you can provide is greatly appreciated. And, in case it comes into play, I'm using a Postgresql DB.</p> <p><strong>UPDATE</strong>: Please note that "author_last_name" is not in the "book" table.</p>
435,991
6
3
null
2009-01-12 16:23:54.843 UTC
10
2019-02-08 06:47:57.903 UTC
2009-01-12 16:29:12.43 UTC
Huuuze
10,040
Huuuze
10,040
null
1
25
sql|postgresql
98,621
<p>A nested query can do the job.</p> <pre><code>SELECT author_last_name, dewey_number, NumOccurrences FROM author INNER JOIN ( SELECT author_id, dewey_number, COUNT(dewey_number) AS NumOccurrences FROM book GROUP BY author_id, dewey_number HAVING ( COUNT(dewey_number) &gt; 1 ) ) AS duplicates ON author.id = duplicates.author_id </code></pre> <p>(I don't know if this is the fastest way to achieve what you want.)</p> <p>Update: Here is my data</p> <pre><code>SELECT * FROM author; id | author_last_name ----+------------------ 1 | Fowler 2 | Knuth 3 | Lang SELECT * FROM book; id | author_id | dewey_number | title ----+-----------+--------------+------------------------ 1 | 1 | 600 | Refactoring 2 | 1 | 600 | Refactoring 3 | 1 | 600 | Analysis Patterns 4 | 2 | 600 | TAOCP vol. 1 5 | 2 | 600 | TAOCP vol. 1 6 | 2 | 600 | TAOCP vol. 2 7 | 3 | 500 | Algebra 8 | 3 | 500 | Undergraduate Analysis 9 | 1 | 600 | Refactoring 10 | 2 | 500 | Concrete Mathematics 11 | 2 | 500 | Concrete Mathematics 12 | 2 | 500 | Concrete Mathematics </code></pre> <p>And here is the result of the above query:</p> <pre><code> author_last_name | dewey_number | numoccurrences ------------------+--------------+---------------- Fowler | 600 | 4 Knuth | 600 | 3 Knuth | 500 | 3 Lang | 500 | 2 </code></pre>
1,202,839
get request data in Django form
<p>Is it possible to get request.user data in a form class? I want to clean an email address to make sure that it's unique, but if it's the current users email address then it should pass.</p> <p>This is what I currently have which works great for creating new users, but if I want to edit a user I run into the problem of their email not validating, because it comes up as being taken already. If I could check that it's their email using request.user.email then I would be able to solve my problem, but I'm not sure how to do that. </p> <pre><code>class editUserForm(forms.Form): email_address = forms.EmailField(widget=forms.TextInput(attrs={'class':'required'})) def clean_email_address(self): this_email = self.cleaned_data['email_address'] test = UserProfiles.objects.filter(email = this_email) if len(test)&gt;0: raise ValidationError("A user with that email already exists.") else: return this_email </code></pre>
1,204,136
6
0
null
2009-07-29 20:29:51.23 UTC
24
2021-12-13 11:56:13.877 UTC
2016-11-14 21:30:03.22 UTC
null
1,022,923
null
74,474
null
1
57
python|django
71,759
<p>As ars and Diarmuid have pointed out, you can pass <code>request.user</code> into your form, and use it in validating the email. Diarmuid's code, however, is wrong. The code should actually read:</p> <pre><code>from django import forms class UserForm(forms.Form): email_address = forms.EmailField( widget=forms.TextInput( attrs={ 'class': 'required' } ) ) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(UserForm, self).__init__(*args, **kwargs) def clean_email_address(self): email = self.cleaned_data.get('email_address') if self.user and self.user.email == email: return email if UserProfile.objects.filter(email=email).count(): raise forms.ValidationError( u'That email address already exists.' ) return email </code></pre> <p>Then, in your view, you can use it like so:</p> <pre><code>def someview(request): if request.method == 'POST': form = UserForm(request.POST, user=request.user) if form.is_valid(): # Do something with the data pass else: form = UserForm(user=request.user) # Rest of your view follows </code></pre> <p><s>Note that you should pass request.POST as a keyword argument, since your constructor expects 'user' as the first positional argument.</s></p> <p>Doing it this way, you need to pass <code>user</code> as a keyword argument. You can either pass <code>request.POST</code> as a positional argument, or a keyword argument (via <code>data=request.POST</code>).</p>
391,130
What is an HttpHandler in ASP.NET
<p>What is an HttpHandler in ASP.NET? Why and how is it used?</p>
391,211
6
1
null
2008-12-24 09:52:09.797 UTC
30
2019-03-13 09:57:18.497 UTC
2013-07-09 20:29:18.033 UTC
null
1,066,291
Nikola Stjelja
32,582
null
1
68
asp.net|httphandler|ihttphandler|ihttpasynchandler
106,522
<p>In the simplest terms, an ASP.NET HttpHandler is a class that implements the <code>System.Web.IHttpHandler</code> interface. </p> <p>ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web application server. They run as processes in response to a request made to the ASP.NET Site. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. </p> <p>ASP.NET offers a few <strong>default HTTP handlers</strong>:</p> <ul> <li>Page Handler (.aspx): handles Web pages</li> <li>User Control Handler (.ascx): handles Web user control pages</li> <li>Web Service Handler (.asmx): handles Web service pages</li> <li>Trace Handler (trace.axd): handles trace functionality</li> </ul> <p>You can create your own <strong>custom HTTP handlers</strong> that render custom output to the browser. Typical scenarios for HTTP Handlers in ASP.NET are for example</p> <ul> <li>delivery of dynamically created images (charts for example) or resized pictures.</li> <li>RSS feeds which emit RSS-formated XML</li> </ul> <p>You <strong>implement</strong> the <code>IHttpHandler</code> interface to create a synchronous handler and the <code>IHttpAsyncHandler</code> interface to create an asynchronous handler. The interfaces require you to implement the <code>ProcessRequest</code> method and the <code>IsReusable</code> property.</p> <p>The <code>ProcessRequest</code> method handles the actual processing for requests made, while the Boolean <code>IsReusable</code> property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.</p>
95,800
How do I add FTP support to Eclipse?
<p>I'm using Eclipse PHP Development Tools. What would be the easiest way to access a file or maybe create a remote project trough FTP and maybe SSH and SFTP?.</p>
6,944,100
6
2
null
2008-09-18 19:07:11.15 UTC
37
2015-04-11 09:26:12.787 UTC
2011-10-15 11:31:35.69 UTC
null
1,288
levhita
7,946
null
1
93
eclipse|ftp|eclipse-pdt
149,378
<p>Eclipse natively supports FTP and SSH. Aptana is not necessary.</p> <p>Native FTP and SSH support in Eclipse is in the "Remote System Explorer End-User Runtime" Plugin.</p> <p>Install it through Eclipse itself. These instructions may vary slightly with your version of Eclipse:</p> <ol> <li>Go to 'Help' -> 'Install New Software' (in older Eclipses, this is called something a bit different)</li> <li>In the 'Work with:' drop-down, select your version's plugin release site. Example: for Kepler, this is <br/> <em>Kepler - <a href="http://download.eclipse.org/releases/kepler" rel="noreferrer">http://download.eclipse.org/releases/kepler</a></em> </li> <li>In the filter field, type 'remote'.</li> <li>Check the box next to 'Remote System Explorer End-User Runtime'</li> <li>Click 'Next', and accept the terms. It should now download and install.</li> <li>After install, Eclipse may want to restart.</li> </ol> <p>Using it, in Eclipse:</p> <ol> <li>Window -> Open Perspective -> (perhaps select 'Other') -> Remote System Explorer</li> <li>File -> New -> Other -> Remote System Explorer (folder) -> Connection (or type Connection into the filter field)</li> <li>Choose FTP from the 'Select Remote System Type' panel.</li> <li>Fill in your FTP host info in the next panel (username and password come later).</li> <li>In the Remote Systems panel, right-click the hostname and click 'connect'.</li> <li>Enter username + password and you're good!</li> <li>Well, not exactly 'good'. The RSE system is fairly unusual, but you're connected.</li> <li>And you're one smart cookie! You'll figure out the rest.</li> </ol> <p><strong>Edit:</strong> To change the default port, follow the instructions on this page: <a href="http://ikool.wordpress.com/2008/07/25/tips-to-access-ftpssh-on-different-ports-using-eclipse-rse/" rel="noreferrer">http://ikool.wordpress.com/2008/07/25/tips-to-access-ftpssh-on-different-ports-using-eclipse-rse/</a></p>
31,103,813
Executing non-database actions in a transaction in Slick 3
<p>I'm having trouble understanding the new Slick <code>DBIOAction</code> API, which does not seem to have a lot of examples in the docs. I am using Slick 3.0.0, and I need to execute some DB actions and also some calculations with the data received from the database, but all of those actions have to be done inside a single transaction. I'm trying to do the following:</p> <ol> <li>Execute a query to database (the <code>types</code> table).</li> <li>Do some aggregations and filtering of the query results (this calculation can't be done on the database).</li> <li>Execute another query, based on the calculations from step 2 (the <code>messages</code> table — due to some limitations, this query has to be in raw SQL).</li> <li>Join data from step 2 and 3 in memory.</li> </ol> <p>I want the queries from step 1 and 3 to be executed inside a transaction, as the data from their result sets has to be consistent.</p> <p>I've tried to do this in a monadic join style. Here's an overly simplified version of my code, but I can't even get it to compile:</p> <pre><code> val compositeAction = (for { rawTypes &lt;- TableQuery[DBType].result (projectId, types) &lt;- rawTypes.groupBy(_.projectId).toSeq.map(group =&gt; (group._1, group._2.slice(0, 10))) counts &lt;- DBIO.sequence(types.map(aType =&gt; sql"""select count(*) from messages where type_id = ${aType.id}""".as[Int])) } yield (projectId, types.zip(counts))).transactionally </code></pre> <ol> <li>The first row of <code>for</code> comprehension selects the data from the <code>types</code> table.</li> <li>The second row of <code>for</code> comprehension is supposed to do some grouping and slicing of the results, resulting in a <code>Seq[(Option[String], Seq[String])]</code></li> <li>The third row of <code>for</code> comprehension has to execute a set of queries for every element from the previous step, in particular, it has to execute a single SQL query for each of the values inside <code>Seq[String]</code>. So in the third row I build a sequence of <code>DBIOAction</code>s.</li> <li>The <code>yield</code> clause <code>zip</code>s <code>types</code> from the second step and <code>counts</code> from the third step.</li> </ol> <p>This construction, however, does not work and gives two compile time errors:</p> <pre><code>Error:(129, 16) type mismatch; found : slick.dbio.DBIOAction[(Option[String], Seq[(com.centreit.proto.repiso.storage.db.models.DBType#TableElementType, Vector[Int])]),slick.dbio.NoStream,slick.dbio.Effect] (which expands to) slick.dbio.DBIOAction[(Option[String], Seq[(com.centreit.proto.repiso.storage.db.models.TypeModel, Vector[Int])]),slick.dbio.NoStream,slick.dbio.Effect] required: scala.collection.GenTraversableOnce[?] counts &lt;- DBIO.sequence(types.map(aType =&gt; sql"""select count(*) from messages where type_id = ${aType.id}""".as[Int])) ^ Error:(128, 28) type mismatch; found : Seq[Nothing] required: slick.dbio.DBIOAction[?,?,?] (projectId, types) &lt;- rawTypes.groupBy(_.projectId).toSeq.map(group =&gt; (group._1, group._2.slice(0, 10))) ^ </code></pre> <p>I've tried to wrap the second line in a <code>DBIOAction</code> by using <code>DBIO.successful</code>, which is supposed to lift a constant value into the <code>DBIOAction</code> monad:</p> <pre><code>(projectId, types) &lt;- DBIO.successful(rawTypes.groupBy(_.projectId).toSeq.map(group =&gt; (group._1, group._2.slice(0, 10)))) </code></pre> <p>But in this code the <code>types</code> variable is inferred to be <code>Any</code>, and the code does not compile because of that.</p>
31,194,089
1
2
null
2015-06-28 19:20:47.137 UTC
10
2015-07-12 12:54:49.533 UTC
2015-07-12 12:54:49.533 UTC
null
930,450
null
1,336,841
null
1
26
database|scala|slick|slick-3.0
4,055
<p>Try it this way :</p> <pre><code>val compositeAction = (for { rawTypes &lt;- TableQuery[DBType].result pair &lt;- DBIO.sequence(rawTypes.groupBy(_.projectId).toSeq.map(group =&gt; DBIO.successful(group))) counts &lt;- DBIO.sequence(pair.head._2.map(aType =&gt; sql"""select count(*) from messages where type_id = ${aType.id}""".as[Int])) } yield (pair.head._1, pair.head._2.zip(counts))).transactionally </code></pre>
21,309,366
AngularJS ui-router $state.go('^') only changing URL in address bar, but not loading controller
<p>I am trying to create a "Todo App" with angularjs <code>ui-router</code>. It has 2 columns:</p> <ul> <li>Column 1: list of Todos</li> <li>Column 2: Todo details or Todo edit form</li> </ul> <p>In the Edit and Create controller after saving the Todo I would like to reload the list to show the appropriate changes. The problem: after calling <code>$state.go('^')</code> when the Todo is created or updated, the URL in the browser changes back to <code>/api/todo</code>, but the ListCtrl is not executed, i.e. <code>$scope.search</code> is not called, hence the Todo list (with the changed items) is not retrieved, nor are the details of the first Todo displayed in Column 2 (instead, it goes blank).</p> <p>I have even tried <code>$state.go('^', $stateParams, { reload: true, inherit: false, notify: false });</code>, no luck.</p> <p><strong>How can I do a state transition so the controller eventually gets executed?</strong></p> <p>Source:</p> <pre><code>var TodoApp = angular.module('TodoApp', ['ngResource', 'ui.router']) .config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/api/todo'); $stateProvider .state('todo', { url: '/api/todo', controller: 'ListCtrl', templateUrl: '/_todo_list.html' }) .state('todo.details', { url: '/{id:[0-9]*}', views: { 'detailsColumn': { controller: 'DetailsCtrl', templateUrl: '/_todo_details.html' } } }) .state('todo.edit', { url: '/edit/:id', views: { 'detailsColumn': { controller: 'EditCtrl', templateUrl: '/_todo_edit.html' } } }) .state('todo.new', { url: '/new', views: { 'detailsColumn': { controller: 'CreateCtrl', templateUrl: '/_todo_edit.html' } } }) ; }) ; TodoApp.factory('Todos', function ($resource) { return $resource('/api/todo/:id', { id: '@id' }, { update: { method: 'PUT' } }); }); var ListCtrl = function ($scope, $state, Todos) { $scope.todos = []; $scope.search = function () { Todos.query(function (data) { $scope.todos = $scope.todos.concat(data); $state.go('todo.details', { id: $scope.todos[0].Id }); }); }; $scope.search(); }; var DetailsCtrl = function ($scope, $stateParams, Todos) { $scope.todo = Todos.get({ id: $stateParams.id }); }; var EditCtrl = function ($scope, $stateParams, $state, Todos) { $scope.action = 'Edit'; var id = $stateParams.id; $scope.todo = Todos.get({ id: id }); $scope.save = function () { Todos.update({ id: id }, $scope.todo, function () { $state.go('^', $stateParams, { reload: true, inherit: false, notify: false }); }); }; }; var CreateCtrl = function ($scope, $stateParams, $state, Todos) { $scope.action = 'Create'; $scope.save = function () { Todos.save($scope.todo, function () { $state.go('^'); }); }; }; </code></pre>
21,349,764
3
6
null
2014-01-23 13:19:38.727 UTC
8
2016-09-25 18:11:22.697 UTC
2016-09-25 18:11:22.697 UTC
null
4,373,584
null
2,270,404
null
1
11
javascript|angularjs|angular-ui-router
58,041
<p>Huge thanks for Radim Köhler for pointing out that <code>$scope</code> is inherited. With 2 small changes I managed to solve this. See below code, I commented where I added the extra lines. Now it works like a charm.</p> <pre><code>var TodoApp = angular.module('TodoApp', ['ngResource', 'ui.router']) .config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/api/todo'); $stateProvider .state('todo', { url: '/api/todo', controller: 'ListCtrl', templateUrl: '/_todo_list.html' }) .state('todo.details', { url: '/{id:[0-9]*}', views: { 'detailsColumn': { controller: 'DetailsCtrl', templateUrl: '/_todo_details.html' } } }) .state('todo.edit', { url: '/edit/:id', views: { 'detailsColumn': { controller: 'EditCtrl', templateUrl: '/_todo_edit.html' } } }) .state('todo.new', { url: '/new', views: { 'detailsColumn': { controller: 'CreateCtrl', templateUrl: '/_todo_edit.html' } } }) ; }) ; TodoApp.factory('Todos', function ($resource) { return $resource('/api/todo/:id', { id: '@id' }, { update: { method: 'PUT' } }); }); var ListCtrl = function ($scope, $state, Todos) { $scope.todos = []; $scope.search = function () { Todos.query(function (data) { $scope.todos = $scope.todos(data); // No concat, just overwrite if (0 &lt; $scope.todos.length) { // Added this as well to avoid overindexing if no Todo is present $state.go('todo.details', { id: $scope.todos[0].Id }); } }); }; $scope.search(); }; var DetailsCtrl = function ($scope, $stateParams, Todos) { $scope.todo = Todos.get({ id: $stateParams.id }); }; var EditCtrl = function ($scope, $stateParams, $state, Todos) { $scope.action = 'Edit'; var id = $stateParams.id; $scope.todo = Todos.get({ id: id }); $scope.save = function () { Todos.update({ id: id }, $scope.todo, function () { $scope.search(); // Added this line //$state.go('^'); // As $scope.search() changes the state, this is not even needed. }); }; }; var CreateCtrl = function ($scope, $stateParams, $state, Todos) { $scope.action = 'Create'; $scope.save = function () { Todos.save($scope.todo, function () { $scope.search(); // Added this line //$state.go('^'); // As $scope.search() changes the state, this is not even needed. }); }; }; </code></pre>
21,122,303
How to list all Linux environment variables including LD_LIBRARY_PATH
<p>How to list all the environment variables in Linux?</p> <p>When I type the command <code>env</code> or <code>printenv</code> it gives me lots of variables, but some variables like <code>LD_LIBRARY_PATH</code> and <code>PKG_CONFIG</code> don't show up in this list.</p> <p>I want to type a command that list all the environment variables including this variables (<code>LD_LIBRARY_PATH</code> and <code>PKG_CONFIG</code>)</p>
21,125,235
3
7
null
2014-01-14 19:30:51.317 UTC
9
2015-09-29 20:58:13.423 UTC
null
null
null
null
1,004,172
null
1
18
linux|ubuntu|centos
62,944
<p><code>env</code> does list all environment variables. </p> <p>If <code>LD_LIBRARY_PATH</code> is not there, then that variable was not declared; or was declared but not <code>export</code>ed, so that child processes do not inherit it.</p> <p>If you are setting <code>LD_LIBRARY_PATH</code> in your shell start-up files, like <code>.bash_profile</code> or <code>.bashrc</code> make sure it is exported:</p> <pre><code>export LD_LIBRARY_PATH </code></pre>
69,437,526
What is this odd sorting algorithm?
<p>Some <a href="https://stackoverflow.com/a/69435932/16759116">answer</a> originally had this sorting algorithm:</p> <pre class="lang-none prettyprint-override"><code>for i from 0 to n-1: for j from 0 to n-1: if A[j] &gt; A[i]: swap A[i] and A[j] </code></pre> <p>Note that both <code>i</code> and <code>j</code> go the full range and thus <code>j</code> can be both larger and smaller than <code>i</code>, so it can make pairs both correct and wrong order (and it actually <em>does</em> do both!). I thought that's a mistake (and the author later called it that) and that this would jumble the array, but it does appear to sort correctly. It's not obvious why, though. But the <em>code</em> simplicity (going full ranges, and no <code>+1</code> as in bubble sort) makes it interesting.</p> <p><strong>Is it correct? If so, why does it work? And does it have a name?</strong></p> <p>Python implementation with testing:</p> <pre><code>from random import shuffle for _ in range(3): n = 20 A = list(range(n)) shuffle(A) print('before:', A) for i in range(n): for j in range(n): if A[j] &gt; A[i]: A[i], A[j] = A[j], A[i] print('after: ', A, '\n') </code></pre> <p>Sample output (<a href="https://tio.run/##bU5BCsIwELznFXtLAjmIvUihQt@hRSomdku7CWk8@PqYpBUV3Mvsziwz455hsFQdnI/ReDuD7@mWAGdnfYBleBgzacaM9XABpKzftahkzSANQQP7XVnbtE64BLF@kJSF3hxEu57OIwXBrzoZ6porSHwRcgB@AmgLeEvjfykPGmhPYwfHBNj9aqVYYtX60hRQhWLffXoTtK8h91HAz8RljC8" rel="noreferrer" title="Python 3.8 (pre-release) – Try It Online">Try it online!</a>):</p> <pre><code>before: [9, 14, 8, 12, 16, 19, 2, 1, 10, 11, 18, 4, 15, 3, 6, 17, 7, 0, 5, 13] after: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] before: [5, 1, 18, 10, 19, 14, 17, 7, 12, 16, 2, 0, 6, 8, 9, 11, 4, 3, 15, 13] after: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] before: [11, 15, 7, 14, 0, 2, 9, 4, 13, 17, 8, 10, 1, 12, 6, 16, 18, 3, 5, 19] after: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] </code></pre> <p>Edit: Someone pointed out a very nice brand new <a href="https://arxiv.org/abs/2110.01111" rel="noreferrer">paper</a> about this algorithm. Just to clarify: We're unrelated, it's a coincidence. As far as I can tell it was <em>submitted</em> to arXiv <a href="https://i.stack.imgur.com/0rF9E.png" rel="noreferrer"><em>before</em></a> that answer that sparked my question and <a href="https://web.archive.org/web/20211006015855/https://arxiv.org/list/cs.DS/recent" rel="noreferrer"><em>published</em></a> by arXiv <a href="https://i.stack.imgur.com/IC6lF.png" rel="noreferrer"><em>after</em></a> my question.</p>
69,438,471
5
27
null
2021-10-04 14:14:22.687 UTC
17
2021-10-24 16:59:30.557 UTC
2021-10-10 23:43:29.963 UTC
null
13,990,016
null
16,759,116
null
1
103
python|algorithm|sorting
10,078
<p>To prove that it's correct, you have to find some sort of invariant. Something that's true during every pass of the loop.</p> <p>Looking at it, after the very first pass of the inner loop, the <em>largest</em> element of the list will actually be in the <em>first</em> position.</p> <p>Now in the second pass of the inner loop, <code>i = 1</code>, and the very first comparison is between <code>i = 1</code> and <code>j = 0</code>. So, the largest element was in position 0, and after this comparison, it will be swapped to position 1.</p> <p>In general, then it's not hard to see that after each step of the outer loop, the largest element will have moved one to the right. So after the full steps, we know at least the largest element will be in the correct position.</p> <p>What about all the rest? Let's say the second-largest element sits at position <code>i</code> of the current loop. We know that the <em>largest</em> element sits at position <code>i-1</code> as per the previous discussion. Counter <code>j</code> starts at 0. So now we're looking for the first <code>A[j]</code> such that it's <code>A[j] &gt; A[i]</code>. Well, the <code>A[i]</code> is the second largest element, so the first time that happens is when <code>j = i-1</code>, at the first largest element. Thus, they're adjacent and get swapped, and are now in the &quot;right&quot; order. Now <code>A[i]</code> again points to the largest element, and hence for the rest of the inner loop no more swaps are performed.</p> <p>So we can say: Once the outer loop index has moved past the location of the second largest element, the second and first largest elements will be in the right order. They will now slide up together, in every iteration of the outer loop, so we know that at the end of the algorithm both the first and second-largest elements will be in the right position.</p> <p>What about the third-largest element? Well, we can use the same logic again: Once the outer loop counter <code>i</code> is at the position of the third-largest element, it'll be swapped such that it'll be just below the second largest element (if we have found that one already!) or otherwise just below the first largest element.</p> <p>Ah. And here we now have our invariant: After <code>k</code> iterations of the outer loop, the k-length sequence of elements, ending at position <code>k-1</code>, will be in sorted order:</p> <p>After the 1st iteration, the 1-length sequence, at position 0, will be in the correct order. That's trivial.</p> <p>After the 2nd iteration, we know the largest element is at position 1, so obviously the sequence <code>A[0]</code>, <code>A[1]</code> is in the correct order.</p> <p>Now let's assume we're at step <code>k</code>, so all the elements up to position <code>k-1</code> will be in order. Now <code>i = k</code> and we iterate over <code>j</code>. What this does is basically find the position at which the new element needs to be slotted into the existing sorted sequence so that it'll be properly sorted. Once that happens, the rest of the elements &quot;bubble one up&quot; until now the largest element sits at position <code>i = k</code> and no further swaps happen.</p> <p>Thus finally at the end of step <code>N</code>, all the elements up to position <code>N-1</code> are in the correct order, QED.</p>
16,599,691
Basic Syntax for passing a Scanner object as a Parameter in a Function
<p>Here is what I wrote which is pretty basic :</p> <pre><code>import java.util.Scanner; public class Projet { /** * @param args * @param Scanner */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Enter a digit"); Scanner in = new Scanner(System.in); getChoice(Scanner); in.close(); } public static int getChoice(Scanner n){ n = in.nextInt(); return n; } } </code></pre> <p>What seems to be wrong here ? I had it working earlier, I had to pass the <strong>Scanner type</strong> and <strong>argument name</strong> as a parameter to the function... and simply call that function in the main using <strong>Scanner type and argument</strong> as an argument to the function ?</p> <p><strong>-----EDIT-----</strong></p> <p>New Code below for below that will need it :</p> <pre><code>import java.util.Scanner; public class Projet { /** * @param args * @param Scanner */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Enter a digit"); Scanner in = new Scanner(System.in); System.out.println(getChoice(in)); in.close(); } public static int getChoice(Scanner in){ return in.nextInt(); } } </code></pre> <p>@rgettman Thanks !</p>
16,599,700
1
0
null
2013-05-17 00:42:12.013 UTC
4
2015-07-22 15:02:32.87 UTC
2013-05-17 01:23:09.437 UTC
null
1,791,497
null
1,791,497
null
1
2
java|function|parameters|arguments|java.util.scanner
65,797
<p>You need to pass the actual variable name <code>in</code> when you call the method, not the class name <code>Scanner</code>.</p> <pre><code>getChoice(in); </code></pre> <p>instead of</p> <pre><code>getChoice(Scanner); </code></pre> <p>Incidentally, your <code>getChoice</code> method won't compile as shown. Just return what the scanner returns, which is an <code>int</code>, as you declared <code>getChoice</code> to return an <code>int</code>:</p> <pre><code>public static int getChoice(Scanner n){ return n.nextInt(); } </code></pre>
1,625,455
itext positioning text absolutely
<p>In itext I have a chunk/phrase/paragraph (I dont mind which) and I want to position some where else on the page e.g. at 300 x 200. How would I do this?</p>
1,631,956
5
0
null
2009-10-26 15:23:04.123 UTC
3
2018-09-17 06:58:52.373 UTC
2009-10-27 08:59:54.143 UTC
null
147,683
null
147,683
null
1
24
java|.net|itextsharp|itext
39,708
<p>In the end I wrote my own method to do it.</p> <pre><code>private void PlaceChunck(String text, int x, int y) { PdfContentByte cb = writer.DirectContent; BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.SaveState(); cb.BeginText(); cb.MoveText(x, y); cb.SetFontAndSize(bf, 12); cb.ShowText(text); cb.EndText(); cb.RestoreState(); } </code></pre>
2,035,959
How to convert a float to an Int by rounding to the nearest whole integer
<p>Is there a way to convert a <code>float</code> to an <code>Int</code> by rounding to the nearest possible whole integer? </p>
2,036,049
5
1
null
2010-01-10 03:15:37.717 UTC
6
2020-02-12 01:58:14.08 UTC
2014-05-12 16:56:14.857 UTC
null
1,580,941
null
231,964
null
1
25
type-conversion
51,357
<p>Actually Paul Beckingham's answer isn't quite correct. If you try a negative number like -1.51, you get -1 instead of -2. </p> <p>The functions round(), roundf(), lround(), and lroundf() from math.h work for negative numbers too. </p>
1,366,179
How to display XML in a HTML page as a collapsible and expandable tree using Javascript?
<p>How to display a XML document in a HTML page as a collapsible and expandable tree?</p> <p>I'd like to display a XML document inside a HTML page as a nicely pretty printed tree structure. I'd like to be able to expand and collapse tree branches. For example Firefox browser does this when you load a plain XML file. I am looking how to do this in client-side with JavaScript.</p>
1,366,270
5
0
null
2009-09-02 06:56:02.647 UTC
10
2017-05-16 15:55:07.803 UTC
2013-07-19 18:28:58.543 UTC
null
1,431
null
1,431
null
1
33
javascript|html|xml|tree
79,962
<p><a href="http://www.codeproject.com/KB/scripting/Exsead2.aspx" rel="noreferrer">Creating An XML Viewer With JScript - Exsead XML Power Scripting</a></p> <p><a href="http://www.levmuchnik.net/Content/ProgrammingTips/WEB/XMLDisplay/DisplayXMLFileWithJavascript.html" rel="noreferrer">Display XML Files with Javascript</a></p> <h2>Update:</h2> <p>There seems to be a better and easier-to-use alternative than what I listed above many years ago:</p> <p><a href="https://www.jstree.com/" rel="noreferrer">https://www.jstree.com/</a></p> <p>Hope they help.</p>
2,322,366
How do I serve up an Unauthorized page when a user is not in the Authorized Roles?
<p>I am using the <code>Authorize</code> attribute like this:</p> <pre><code>[Authorize (Roles="Admin, User")] Public ActionResult Index(int id) { // blah } </code></pre> <p>When a user is not in the specified roles, I get an error page (resource not found). So I put the <code>HandleError</code> attribute in also.</p> <pre><code>[Authorize (Roles="Admin, User"), HandleError] Public ActionResult Index(int id) { // blah } </code></pre> <p>Now it goes to the <em>Login</em> page, if the user is not in the specified roles.</p> <p>How do I get it to go to an <em>Unauthorized</em> page instead of the login page, when a user does not meet one of the required roles? And if a different error occurs, how do I distinguish that error from an Unauthorized error and handle it differently?</p>
2,322,403
5
2
null
2010-02-23 22:50:10.7 UTC
16
2017-09-29 09:08:37.817 UTC
null
null
null
null
102,937
null
1
41
c#|asp.net-mvc|security|roles
28,398
<p>Add something like this to your web.config:</p> <pre><code>&lt;customErrors mode="On" defaultRedirect="~/Login"&gt; &lt;error statusCode="401" redirect="~/Unauthorized" /&gt; &lt;error statusCode="404" redirect="~/PageNotFound" /&gt; &lt;/customErrors&gt; </code></pre> <p>You should obviously create the <code>/PageNotFound</code> and <code>/Unauthorized</code> routes, actions and views.</p> <p><strong>EDIT</strong>: I'm sorry, I apparently didn't understand the problem thoroughly. </p> <p>The problem is that when the <code>AuthorizeAttribute</code> filter is executed, it decides that the user does not fit the requirements (he/she may be logged in, but is not in a correct role). It therefore sets the response status code to 401. This is intercepted by the <code>FormsAuthentication</code> module which will then perform the redirect.</p> <p>I see two alternatives: </p> <ol> <li><p>Disable the defaultRedirect.</p></li> <li><p>Create your own <code>IAuthorizationFilter</code>. Derive from <code>AuthorizeAttribute</code> and override HandleUnauthorizedRequest. In this method, if the user is authenticated do a <em>redirect</em> to /Unauthorized</p></li> </ol> <p>I don't like either: the defaultRedirect functionality is nice and not something you want to implement yourself. The second approach results in the user being served a visually correct "You are not authorized"-page, but the HTTP status codes will not be the desired 401.</p> <p>I don't know enough about HttpModules to say whether this can be circumvented with a a tolerable hack.</p> <p><strong>EDIT 2</strong>: How about implementing your own IAuthorizationFilter in the following way: download the MVC2 code from CodePlex and "borrow" the code for AuthorizeAttribute. Change the OnAuthorization method to look like</p> <pre><code> public virtual void OnAuthorization(AuthorizationContext filterContext) { if (AuthorizeCore(filterContext.HttpContext)) { HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; cachePolicy.SetProxyMaxAge(new TimeSpan(0)); cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */); } // Is user logged in? else if(filterContext.HttpContext.User.Identity.IsAuthenticated) { // Redirect to custom Unauthorized page filterContext.Result = new RedirectResult(unauthorizedUrl); } else { // Handle in the usual way HandleUnauthorizedRequest(filterContext); } } </code></pre> <p>where <code>unauthorizedUrl</code> is either a property on the filter or read from Web.config.</p> <p>You could also inherit from AuthorizeAttribute and override <code>OnAuthorization</code>, but you would end up writing a couple of private methods which are already in AuthorizeAttribute.</p>
1,766,067
What is the most useable VI/Vim plugin for Eclipse?
<p>I used to be a huge fan of Intelli-J and there is a fantastic VI plugin for Idea. Now I'm shifting to the Spring Source Tool Suite for my primary IDE and need to find a VI plugin that will allow me to work just as effectively.</p> <p>What plugin are people using?</p>
1,766,207
5
1
null
2009-11-19 19:52:02.36 UTC
13
2014-08-06 18:20:53.023 UTC
2012-11-10 00:11:51.39 UTC
null
834,176
null
1,129,162
null
1
46
eclipse|vim|vi
30,656
<p>I rate <a href="http://www.viplugin.com/" rel="noreferrer">viPlugin</a> highly enough to pay the small fee for the licensed edition (not licensing it means you get popups every so often, IIRC).</p> <p>In my opinion it works better than the equivalent Intellij plugin.</p>
1,639,291
How do I add a newline to command output in PowerShell?
<p>I run the following code using PowerShell to get a list of add/remove programs from the registry:</p> <pre><code>Get-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object -Process { Write-Output $_.GetValue("DisplayName") } ` | Out-File addrem.txt </code></pre> <p>I want the list to be separated by newlines per each program. I've tried:</p> <pre><code>Get-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object -Process { Write-Output $_.GetValue("DisplayName") `n } ` | out-file test.txt Get-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object {$_.GetValue("DisplayName") } ` | Write-Host -Separator `n Get-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object -Process { $_.GetValue("DisplayName") } ` | foreach($_) { echo $_ `n } </code></pre> <p>But all result in weird formatting when output to the console, and with three square characters after each line when output to a file. I tried <code>Format-List</code>, <code>Format-Table</code>, and <code>Format-Wide</code> with no luck. Originally, I thought something like this would work:</p> <pre><code>Get-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object -Process { "$_.GetValue("DisplayName") `n" } </code></pre> <p>But that just gave me an error.</p>
1,641,787
5
1
null
2009-10-28 18:45:04.363 UTC
10
2018-12-10 10:31:29.95 UTC
2014-12-27 14:37:45.7 UTC
null
63,550
null
198,358
null
1
80
powershell|newline
424,331
<p>Or, just set the <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-6#ofs" rel="noreferrer">output field separator</a> (OFS) to double newlines, and then make sure you get a string when you send it to file:</p> <pre><code>$OFS = "`r`n`r`n" "$( gci -path hklm:\software\microsoft\windows\currentversion\uninstall | ForEach-Object -Process { write-output $_.GetValue('DisplayName') } )" | out-file addrem.txt </code></pre> <p>Beware to use the <kbd>`</kbd> and not the <kbd>'</kbd>. On my keyboard (US-English Qwerty layout) it's located left of the <kbd>1</kbd>.<br> (Moved here from the comments - Thanks Koen Zomers)</p>
1,351,966
Is there a pure CSS way to make an input transparent?
<p>How can I make this input transparent?</p> <pre><code>&lt;input type="text" class="foo"&gt; </code></pre> <p>I've tried this but it doesn't work.</p> <pre><code>background:transparent url(../img/transpSmall.png) repeat scroll 0 0; </code></pre>
1,351,969
7
4
null
2009-08-29 17:44:34.847 UTC
18
2020-09-04 16:57:44.543 UTC
2009-08-31 11:56:18.317 UTC
null
5,640
null
26,004
null
1
64
html|css
170,922
<pre><code>input[type="text"] { background: transparent; border: none; } </code></pre> <p>Nobody will even know it's there.</p>
2,251,290
storing money amounts in mysql
<p>I want to store 3.50 into a mysql table. I have a float that I store it in, but it stores as 3.5, not 3.50. How can I get it to have the trailing zero?</p>
2,251,311
7
0
null
2010-02-12 11:04:25.037 UTC
22
2017-06-25 03:02:59.883 UTC
2012-05-09 16:33:04.35 UTC
null
44,390
null
175,562
null
1
65
mysql|floating-point|currency|fixed-point
54,310
<p>Do not store money values as float, use the DECIMAL or NUMERIC type:</p> <p><a href="http://dev.mysql.com/doc/refman/5.1/en/numeric-types.html" rel="noreferrer">Documentation for MySQL Numeric Types</a></p> <p>EDIT &amp; clarification:</p> <p>Float values are vulnerable to rounding errors are they have limited precision so unless you do not care that you only get 9.99 instead of 10.00 you should use DECIMAL/NUMERIC as they are fixed point numbers which do not have such problems.</p>
2,025,789
Preserving a reference to "this" in JavaScript prototype functions
<p>I'm just getting into using prototypal JavaScript and I'm having trouble figuring out how to preserve a <code>this</code> reference to the main object from inside a prototype function when the scope changes. Let me illustrate what I mean (I'm using jQuery here):</p> <pre><code>MyClass = function() { this.element = $('#element'); this.myValue = 'something'; // some more code } MyClass.prototype.myfunc = function() { // at this point, "this" refers to the instance of MyClass this.element.click(function() { // at this point, "this" refers to the DOM element // but what if I want to access the original "this.myValue"? }); } new MyClass(); </code></pre> <p>I know that I can preserve a reference to the main object by doing this at the beginning of <code>myfunc</code>:</p> <pre><code>var myThis = this; </code></pre> <p>and then using <code>myThis.myValue</code> to access the main object's property. But what happens when I have a whole bunch of prototype functions on <code>MyClass</code>? Do I have to save the reference to <code>this</code> at the beginning of each one? Seems like there should be a cleaner way. And what about a situation like this:</p> <pre><code>MyClass = function() { this.elements $('.elements'); this.myValue = 'something'; this.elements.each(this.doSomething); } MyClass.prototype.doSomething = function() { // operate on the element } new MyClass(); </code></pre> <p>In that case, I can't create a reference to the main object with <code>var myThis = this;</code> because even the original value of <code>this</code> within the context of <code>doSomething</code> is a <code>jQuery</code> object and not a <code>MyClass</code> object.</p> <p>It's been suggested to me to use a global variable to hold the reference to the original <code>this</code>, but that seems like a really bad idea to me. I don't want to pollute the global namespace and that seems like it would prevent me from instantiating two different <code>MyClass</code> objects without them interfering with each other.</p> <p>Any suggestions? Is there a clean way to do what I'm after? Or is my entire design pattern flawed?</p>
2,025,839
7
0
null
2010-01-08 05:51:49.663 UTC
27
2015-02-10 11:05:35.31 UTC
2011-12-27 17:30:21.827 UTC
null
938,089
null
242,493
null
1
93
javascript|oop|scope|this|prototype-programming
70,014
<p>For preserving the context, the <code>bind</code> method is really useful, it's now part of the recently released <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" rel="noreferrer">ECMAScript 5th Edition</a> Specification, the implementation of this function is simple (only 8 lines long):</p> <pre><code>// The .bind method from Prototype.js if (!Function.prototype.bind) { // check if native implementation available Function.prototype.bind = function(){ var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function(){ return fn.apply(object, args.concat(Array.prototype.slice.call(arguments))); }; }; } </code></pre> <p>And you could use it, in your example like this:</p> <pre><code>MyClass.prototype.myfunc = function() { this.element.click((function() { // ... }).bind(this)); }; </code></pre> <p>Another example:</p> <pre><code>var obj = { test: 'obj test', fx: function() { alert(this.test + '\n' + Array.prototype.slice.call(arguments).join()); } }; var test = "Global test"; var fx1 = obj.fx; var fx2 = obj.fx.bind(obj, 1, 2, 3); fx1(1,2); fx2(4, 5); </code></pre> <p>In this second example we can observe more about the behavior of <code>bind</code>.</p> <p>It basically generates a new function, that will be the responsible of calling our function, preserving the function context (<code>this</code> value), that is defined as the first argument of <code>bind</code>.</p> <p>The rest of the arguments are simply passed to our function.</p> <p>Note in this example that the function <code>fx1</code>, is invoked without any <em>object context</em> (<code>obj.method()</code> ), just as a simple function call, in this type of invokation, the <code>this</code> keyword inside will refer to the Global object, it will alert "global test".</p> <p>Now, the <code>fx2</code> is the new function that the <code>bind</code> method generated, it will call our function preserving the context and correctly passing the arguments, it will alert "obj test 1, 2, 3, 4, 5" because we invoked it adding the two additionally arguments, it already had <em>binded</em> the first three.</p>
1,735,540
Creating a Pareto Chart with ggplot2 and R
<p>I have been struggling with how to make a <a href="http://en.wikipedia.org/wiki/Pareto_chart" rel="nofollow noreferrer">Pareto Chart</a> in R using the ggplot2 package. In many cases when making a bar chart or histogram we want items sorted by the X axis. In a Pareto Chart we want the items ordered descending by the value in the Y axis. Is there a way to get ggplot to plot items ordered by the value in the Y axis? I tried sorting the data frame first but it seems ggplot reorders them. </p> <p>Example:</p> <pre><code>val &lt;- read.csv("http://www.cerebralmastication.com/wp-content/uploads/2009/11/val.txt") val&lt;-with(val, val[order(-Value), ]) p &lt;- ggplot(val) p + geom_bar(aes(State, Value, fill=variable), stat = "identity", position="dodge") + scale_fill_brewer(palette = "Set1") </code></pre> <p>the data frame val is sorted but the output looks like this:</p> <p><a href="https://i.stack.imgur.com/F0Za1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F0Za1.png" alt="alt text"></a><br> <sub>(source: <a href="http://www.cerebralmastication.com/wp-content/uploads/2009/11/exp.png" rel="nofollow noreferrer">cerebralmastication.com</a>)</sub> </p> <p>Hadley correctly pointed out that this produces a much better graphic for showing actuals vs. predicted:</p> <pre><code>ggplot(val, aes(State, Value)) + geom_bar(stat = "identity", subset = .(variable == "estimate"), fill = "grey70") + geom_crossbar(aes(ymin = Value, ymax = Value), subset = .(variable == "actual")) </code></pre> <p>which returns:</p> <p><a href="https://i.stack.imgur.com/gnlX2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gnlX2.png" alt="alt text"></a><br> <sub>(source: <a href="http://www.cerebralmastication.com/wp-content/uploads/2009/11/exp1.png" rel="nofollow noreferrer">cerebralmastication.com</a>)</sub> </p> <p>But it's still not a Pareto Chart. Any tips?</p>
1,736,141
8
2
null
2009-11-14 20:46:51.707 UTC
12
2019-12-17 03:10:56.28 UTC
2019-05-08 19:04:52.697 UTC
null
4,751,173
null
37,751
null
1
20
r|graph|ggplot2
24,135
<p>The bars in ggplot2 are ordered by the ordering of the levels in the factor.</p> <pre><code>val$State &lt;- with(val, factor(val$State, levels=val[order(-Value), ]$State)) </code></pre>
1,883,425
Android Borderless Dialog
<p>I have created an AlertDialog using AlertDialog.Builder, but the Dialog border takes up too much space on the screen. How do I remove the border? I have tried using another Activity to emulate the dialog with a transparent background, but the dialog is used repeatedly, and creating a new Activity every time introduces a significant amount of lag.</p> <p>The answer from <a href="https://stackoverflow.com/questions/704295/android-show-an-indeterminate-progressbar-without-the-dialog">here</a> mentions that it can be found in the ApiDemos, but i can't seem to find it.</p>
1,892,367
8
0
null
2009-12-10 19:37:50.24 UTC
14
2014-04-16 19:33:39.713 UTC
2017-05-23 12:06:52.56 UTC
null
-1
null
196,980
null
1
28
android|dialog
34,632
<p>Alright, I'll answer my own question. Basically, instead of using AlertDialog.Builder, create a regular Dialog using it's constructor, and use a suitable theme instead of the default Dialog theme.</p> <p>So your code would look something like this:</p> <pre><code>Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar); </code></pre> <p>Hope this helps someone else.</p>
2,171,969
Determine whether or not there exist two elements in Set S whose sum is exactly x - correct solution?
<p>Taken from Introduction to Algorithms</p> <blockquote> <p>Describe a Θ(n lg n)-time algorithm that, given a set S of n integers and another integer x, determines whether or not there exist two elements in S whose sum is exactly x.</p> </blockquote> <p>This is my best solution implemented in Java so far:</p> <pre><code> public static boolean test(int[] a, int val) { mergeSort(a); for (int i = 0; i &lt; a.length - 1; ++i) { int diff = (val &gt;= a[i]) ? val - a[i] : a[i] - val; if (Arrays.binarySearch(a, i, a.length, diff) &gt;= 0) { return true; } } return false; } </code></pre> <p>Now my 1st question is: Is this a correct solution? From my understanding, mergeSort should perform the sort in O(n lg n), the loop should take O(n lg n) (n for the iteration multiplied by O(lg n) for the binary search, resulting in O(2n lg n), so it should be correct.</p> <p>My 2nd question is: Are there any better solutions? Is sorting the array essential?</p>
2,172,030
8
5
null
2010-01-31 14:18:05.337 UTC
13
2017-12-11 22:44:37.737 UTC
2012-05-11 05:22:32.287 UTC
null
227,665
null
1,178,669
null
1
36
java|arrays|algorithm
33,759
<p>Your solution seems fine. Yes you need to sort because its a pre requisite for binary search. You can make a slight modification to your logic as follows:</p> <pre><code>public static boolean test(int[] a, int val) { Arrays.sort(a); int i = 0; // index of first element. int j = a.length - 1; // index of last element. while(i&lt;j) { // check if the sum of elements at index i and j equals val, if yes we are done. if(a[i]+a[j] == val) return true; // else if sum if more than val, decrease the sum. else if(a[i]+a[j] &gt; val) j--; // else if sum is less than val, increase the sum. else i++; } // failed to find any such pair..return false. return false; } </code></pre>
2,295,845
How can I remove the location hash without causing the page to scroll?
<p>Is it possible to remove the hash from <code>window.location</code> without causing the page to jump-scroll to the top? I need to be able to modify the hash without causing any jumps.</p> <p>I have this:</p> <pre><code>$('&lt;a href="#123"&gt;').text('link').click(function(e) { e.preventDefault(); window.location.hash = this.hash; }).appendTo('body'); $('&lt;a href="#"&gt;').text('unlink').click(function(e) { e.preventDefault(); window.location.hash = ''; }).appendTo('body'); </code></pre> <p>See live example here: <a href="http://jsbin.com/asobi" rel="noreferrer">http://jsbin.com/asobi</a></p> <p>When the user clicks '<strong>link</strong>' the hash tag is modified without any page jumps, so that's working fine.</p> <p>But when the user clicks '<strong>unlink</strong>' the has tag is removed and the page scroll-jumps to the top. I need to remove the hash without this side-effect.</p>
2,295,896
8
4
null
2010-02-19 11:18:46.277 UTC
26
2018-10-04 15:30:39.85 UTC
2012-04-03 08:41:40.46 UTC
null
94,197
null
210,578
null
1
80
javascript|jquery|fragment-identifier
80,489
<p>I believe if you just put in a dummy hash it won't scroll as there is no match to scroll to.</p> <pre><code>&lt;a href="#A4J2S9F7"&gt;No jumping&lt;/a&gt; </code></pre> <p>or</p> <pre><code>&lt;a href="#_"&gt;No jumping&lt;/a&gt; </code></pre> <p><code>"#"</code> by itself is equivalent to <code>"_top"</code> thus causes a scroll to the top of the page</p>
1,625,105
How to write `is_complete` template?
<p>After answering <a href="https://stackoverflow.com/questions/1611771/deleting-object-with-private-destructor">this</a> question I was trying to find <code>is_complete</code> template in Boost library and I realized that there is no such template in Boost.TypeTraits. Why there is no such template in Boost library? How it should look like?</p> <pre><code>//! Check whether type complete template&lt;typename T&gt; struct is_complete { static const bool value = ( sizeof(T) &gt; 0 ); }; ... // so I could use it in such a way BOOST_STATIC_ASSERT( boost::is_complete&lt;T&gt;::value ); </code></pre> <p><strong>The code above is not correct, because it is illegal to apply <code>sizeof</code> to an incomplete type. What will be a good solution?</strong> Is it possible to apply SFINAE in this case somehow?</p> <hr> <p>Well, this problem couldn't be solved in general without violating the <a href="http://en.wikipedia.org/wiki/One_Definition_Rule" rel="noreferrer">ODR rule</a>, but there is there a platform specific <a href="https://stackoverflow.com/questions/1625105/how-to-write-is-complete-template/1956217#1956217">solution</a> which works for me.</p>
1,956,217
9
11
null
2009-10-26 14:21:54.4 UTC
11
2021-09-18 13:12:41.343 UTC
2021-08-17 08:30:42.993 UTC
null
123,111
null
123,111
null
1
29
c++|templates|typetraits|c++03
4,862
<p>The answer given by Alexey Malistov can be used on MSVC with a minor modification:</p> <pre><code>namespace { template&lt;class T, int discriminator&gt; struct is_complete { static T &amp; getT(); static char (&amp; pass(T))[2]; static char pass(...); static const bool value = sizeof(pass(getT()))==2; }; } #define IS_COMPLETE(X) is_complete&lt;X,__COUNTER__&gt;::value </code></pre> <p>Unfortunately, the <code>__COUNTER__</code> predefined macro is not part of the standard, so it would not work on every compiler.</p>
1,836,742
Using git, how do I ignore a file in one branch but have it committed in another branch?
<p>I've got a project that I'm deploying to <a href="http://heroku.com" rel="noreferrer">Heroku</a>. The source code tree includes a bunch of mp3 files (the website will be for a recording project I was heavily involved with). </p> <p>I'd like to put the source code for it up on <a href="http://github.com" rel="noreferrer">GitHub</a>, but GitHub has a 300 MB limit on their free accounts. I don't want to use 50 MB of my limit on a bunch of mp3 files. Obviously, I could add them to the <code>.gitignore</code> file to keep them out of my repo.</p> <p>However, I deploy to Heroku using <code>git push heroku</code>. The mp3 files must be present in the branch I push to Heroku so that they get get deployed.</p> <p>Ideally, I'd like to <code>.gitignore</code> the mp3 files in my local master branch so that when I push that to GitHub, the mp3s are not included. Then I'd keep a local production branch that has the mp3s committed rather than ignored. To deploy, I would merge master into production, and then push the production branch to Heroku.</p> <p>I can't get this to work right.</p> <p>Here's an example of what I'm trying to do...</p> <pre><code>$ git init git-ignore-test $ cd git-ignore-test $ echo "*.ignored" &gt;&gt; .gitignore $ git add .gitignore &amp;&amp; git commit -m "Ignore .ignored files" $ touch Foo.ignored </code></pre> <p>At this point, Foo.ignored is ignored in my master branch, but it's still present, so my project can use it.</p> <pre><code>$ git checkout -b unignored $ cat /dev/null &gt; .gitignore $ git add Foo.ignored .gitignore &amp;&amp; git commit -m "Unignore .ignored files" </code></pre> <p>Now I've got a branch with these files committed, as I want. However, when I switch back to my master branch, Foo.ignored is gone.</p> <p>Anyone got any suggestions for a better way to set this up?</p> <p>Edit: just to clarify, I want the mp3 files to be present in both branches so that when I run the site locally (using either branch) the site works. I just want the files ignored in one branch so when I push to GitHub they are not pushed as well. Usually .gitignore works well for this kind of thing (i.e. keeping a local copy of a file that does not get included in a push to a remote), but when I switch to the branch with the files checked in, and then back to the branch with the files ignored, the files vanish.</p>
4,044,387
9
8
null
2009-12-02 23:55:23.11 UTC
87
2022-05-27 07:37:34.443 UTC
2017-05-02 00:00:57.733 UTC
null
4,694,621
null
29,262
null
1
180
git|gitignore
90,546
<blockquote> <p>This solution appears to work only for certain, patched versions of git. See <a href="https://stackoverflow.com/a/39280410/5794048">a new answer pointing to workarounds</a> and <a href="https://stackoverflow.com/a/39285099/5794048">another answer and subsequent comments</a> for a hint which versions may work.</p> </blockquote> <p>I wrote a blog post on how to effectively use the <code>excludesfile</code> for different branches, like one for public github and one for heroku deployment. </p> <p>Here's the quick and dirty: </p> <pre><code>$ git branch public_viewing $ cd .git/ $ touch info/exclude_from_public_viewing $ echo "path/to/secret/file" &gt; info/exclude_from_public_viewing </code></pre> <p>then in the .git/config file add these lines:</p> <pre><code>[core] excludesfile = +info/exclude [branch "public_viewing"] excludesfile = +info/exclude_from_public_viewing </code></pre> <p>Now all the global ignore stuff is in the <code>info/exclude</code> file and the branch specific is in the <code>info/exclude_from_public_viewing</code></p> <p>Hope that helps!</p> <p><a href="http://cogniton-mind.tumblr.com/post/1423976659/howto-gitignore-for-different-branches" rel="noreferrer">http://cogniton-mind.tumblr.com/post/1423976659/howto-gitignore-for-different-branches</a></p>