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
5,205,373
Understanding basic Java-specific interverview questions
<p>Last day I faced an interview and they asked me java questions among which for some questions I didn't know the answer. I am curious to know the answer for that question. Interviewer did not tell me the answer. I am asking that questions here:</p> <ul> <li>Does Java provide any construct to find out the size of an object? </li> <li>Give a simplest way to find out the time a method takes for execution without using any profiling tool? </li> <li>What are checked exceptions and runtime exceptions? </li> <li>If I write return at the end of the try block, will the finally block still execute? </li> <li>If I write System.exit (0); at the end of the try block, will the finally block still execute?</li> </ul> <p>Want to know answers of above question so that it can help me next time.</p> <p>Explanations, notes, and/or relevant links to the specification would be greatly appreciated over just the simple answers -- and what is a good way to learn this stuff?</p>
5,205,525
8
2
null
2011-03-05 17:13:51.76 UTC
11
2011-03-05 17:54:58.51 UTC
2011-03-05 17:25:03.573 UTC
user166390
null
null
559,070
null
1
7
java
1,549
<p>I think that all of these can be answered by searching for existing Stack Overflow questions. The reason I think it's worth answering this question with links to previous answers is that you've asked about a lot of different issues, each one of which is interesting in its own right. It's not so likely you'll get an in-depth discussion of these when asking about them all together, but in the answers and comments on previous questions here you'll find a lot of detail and discussion which (a) may be interesting and (b) may help in further interviews. (There may well be better choices - these are just the first reasonable SO answers I found.)</p> <blockquote> <p>Does Java provide any construct to find out the size of an object?</p> </blockquote> <ul> <li><a href="https://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object">In Java, what is the best way to determine the size of an object?</a></li> <li><a href="https://stackoverflow.com/questions/4115239/sizeof-java-object">sizeof java object</a></li> </ul> <blockquote> <p>Give a simplest way to find out the time a method takes for execution without using any profiling tool?</p> </blockquote> <ul> <li><a href="https://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java">How do I time a method&#39;s execution in Java?</a></li> </ul> <blockquote> <p>What are checked exceptions and runtime exceptions?</p> </blockquote> <ul> <li><a href="https://stackoverflow.com/questions/3162760/runtime-checked-unchecked-error-exception">Differences between Runtime/Checked/Unchecked/Error/Exception</a></li> </ul> <blockquote> <p>If I write return at the end of the try block, will the finally block still execute? </p> </blockquote> <ul> <li><a href="https://stackoverflow.com/questions/65035/in-java-does-return-trump-finally">Does finally always execute in Java?</a></li> </ul> <blockquote> <p>If I write System.exit (0); at the end of the try block, will the finally block still execute?</p> </blockquote> <ul> <li><a href="https://stackoverflow.com/questions/1410951/how-does-javas-system-exit-work-with-try-catch-finally-blocks">How does Java&#39;s System.exit() work with try/catch/finally blocks?</a></li> </ul>
5,200,269
List of running JVMs on the localhost
<p>How to get in Java 6+ the list of running JVMs on the localhost and their specs (i.e. Java version, running threads, etc.)?</p> <p>Does the Java API provide such features? Is there a Java library that can do this?</p>
5,200,305
8
1
null
2011-03-04 23:07:52.52 UTC
10
2017-10-19 01:24:04.173 UTC
null
null
null
null
645,535
null
1
14
java
32,754
<p>You can use <a href="http://download.oracle.com/javase/1.5.0/docs/tooldocs/share/jps.html" rel="noreferrer"><code>jps</code></a>, a command-line tool distributed with the jvm. I'm not aware of any normal Java API for it, though. However, JConsole can do what you ask, so I had a look at its source. It was quite scary, but while looking around I found references to the jVisualVM classes, which are OK seeing as you specify Java 6+. Here's what I found:</p> <p>The classes are all in <code>sun.tools</code>, so firstly you have to find the <code>jconsole.jar</code> that came with your JVM (assumes Sun JVM, of course) and add it to your classpath. Then a quick-n-dirty listing of the active VMs can be got like:</p> <pre><code>public static void main(final String[] args) { final Map&lt;Integer, LocalVirtualMachine&gt; virtualMachines = LocalVirtualMachine.getAllVirtualMachines(); for (final Entry&lt;Integer, LocalVirtualMachine&gt; entry : virtualMachines.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue().displayName()); } } </code></pre> <p>Once you've got a reference to your JVMs, you can communicate with them using the <a href="http://download.oracle.com/javase/6/docs/technotes/guides/attach/index.html" rel="noreferrer">Attach API</a>.</p>
4,939,382
Logging POST data from $request_body
<p>I have my config setup to handle a bunch of GET requests which render pixels that work fine to handle analytics and parse query strings for logging. With an additional third party data stream, I need to handle a POST request to a given url that has JSON in an expected loggable format inside of it's request body. I don't want to use a secondary server with <code>proxy_pass</code> and just want to log the whole response into an associated log file like what it does with GET requests. A snippet of some code that I'm using looks like the following:</p> <p>GET request (which works great):</p> <pre><code>location ^~ /rl.gif { set $rl_lcid $arg_lcid; if ($http_cookie ~* "lcid=(.*\S)") { set $rl_lcid $cookie_lcid; } empty_gif; log_format my_tracking '{ "guid" : "$rl_lcid", "data" : "$arg__rlcdnsegs" }'; access_log /mnt/logs/nginx/my.access.log my_tracking; rewrite ^(.*)$ http://my/url?id=$cookie_lcid? redirect; } </code></pre> <p>Here is kinda what I am trying to do: POST request (which does not work):</p> <pre><code>location /bk { log_format bk_tracking $request_body; access_log /mnt/logs/nginx/bk.access.log bk_tracking; } </code></pre> <p>Curling <code>curl http://myurl/bk -d name=example</code> gives me a 404 page not found.</p> <p>Then I tried:</p> <pre><code>location /bk.gif { empty_gif; log_format bk_tracking $request_body; access_log /mnt/logs/nginx/bk.access.log bk_tracking; } </code></pre> <p>Curling <code>curl http://myurl/bk.gif -d name=example</code> gives me a <code>405 Not Allowed</code>.</p> <p>My current version is <code>nginx/0.7.62</code>. Any help in the right direction is very much appreciated! Thanks!</p> <p><strong><em>UPDATE</em></strong> So now my post looks like this:</p> <pre><code>location /bk { if ($request_method != POST) { return 405; } proxy_pass $scheme://127.0.0.1:$server_port/dummy; log_format my_tracking $request_body; access_log /mnt/logs/nginx/my.access.log my_tracking; } location /dummy { set $test 0; } </code></pre> <p>It is logging the post data correctly, but returns a 404 on the requesters end. If I change the above code to return a 200 like so:</p> <pre><code>location /bk { if ($request_method != POST) { return 405; } proxy_pass $scheme://127.0.0.1:$server_port/dummy; log_format my_tracking $request_body; access_log /mnt/logs/nginx/my.access.log my_tracking; return 200; } location /dummy { set $test 0; } </code></pre> <p>Then it return the <code>200</code> correctly, but no longer records the post data.</p> <p><strong>ANOTHER UPDATE</strong> Kinda found a working solution. Hopefully this can help other on their way.</p>
7,473,603
8
2
null
2011-02-08 22:44:24.063 UTC
37
2022-03-15 09:03:47.803 UTC
2016-08-24 18:28:14.97 UTC
null
334,831
null
519,311
null
1
89
logging|nginx|http-post
228,565
<p>This solution works like a charm:</p> <pre><code>http { log_format postdata $request_body; server { location = /post.php { access_log /var/log/nginx/postdata.log postdata; fastcgi_pass php_cgi; } } } </code></pre> <p>I think the trick is making nginx believe that you will call a CGI script.</p> <p>Edit 2022-03-15: there is some discussion on where <code>log_format</code> should be set. The documentation clearly says that it needs to be in the <code>http</code> context: <a href="http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format" rel="noreferrer">http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format</a></p> <p>If you put <code>log_format</code> in the <code>server</code> context, nginx will fail to load the config: <code>nginx: [emerg] &quot;log_format&quot; directive is not allowed here in &lt;path&gt;:&lt;line&gt;</code> (tested with nginx 1.20 on ubuntu 18.04)</p>
5,596,521
What is the correct way to start a mongod service on linux / OS X?
<p>I've installed mongodb and have been able to run it, work with it, do simple DB read / write type stuff. Now I'm trying to set up my Mac to run mongod as a service.</p> <p>I get "Command not found" in response to: </p> <pre><code> init mongod start </code></pre> <p>In response to: </p> <pre><code>~: service mongod start service: This command still works, but it is deprecated. Please use launchctl(8) instead. service: failed to start the 'mongod' service </code></pre> <p>And if I try:</p> <pre><code>~: launchctl start mongod launchctl start error: No such process </code></pre> <p>So obviously I'm blundering around a bit. Next step seems to be typing in random characters until something works. The command which <em>does</em> work is: <code>mongod --quiet &amp;</code> I'm not sure, maybe that is the way you're supposed to do it? Maybe I should just take off 'quiet mode' and add <code>&gt; /logs/mongo.log</code> to the end of the command line?</p> <p>I'm building a development environment on a Mac with the intention of doing the same thing on a linux server. I'm just not sure of the Bash commands. All the other searches I do with trying to pull up the answer give me advice for windows machines. </p> <p>Perhaps someone knows the linux version of the commands?</p> <p>Thanks very much</p>
5,601,077
11
2
null
2011-04-08 14:24:02.917 UTC
66
2020-06-07 19:19:22.4 UTC
null
null
null
null
398,055
null
1
141
linux|mongodb|service|initialization
142,301
<p>With recent builds of mongodb community edition, this is straightforward.</p> <p>When you install via brew, it tells you what exactly to do. There is no need to create a new launch control file.</p> <pre><code>$ brew install mongodb ==&gt; Downloading https://homebrew.bintray.com/bottles/mongodb-3.0.6.yosemite.bottle.tar.gz ### 100.0% ==&gt; Pouring mongodb-3.0.6.yosemite.bottle.tar.gz ==&gt; Caveats To have launchd start mongodb at login: ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents Then to load mongodb now: launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist Or, if you don't want/need launchctl, you can just run: mongod --config /usr/local/etc/mongod.conf ==&gt; Summary /usr/local/Cellar/mongodb/3.0.6: 17 files, 159M </code></pre>
16,965,011
Append text to each row of the sql select query
<p>I have a query like this</p> <pre><code>SELECT COUNT(ID) 'Records Affected', TYPE FROM MASTER GROUP BY TYPE </code></pre> <p>The output for this is</p> <pre><code>Records Affected TYPE ---------------- ---- 4 F1 3 F2 5 F3 </code></pre> <p>Now I would like to change the query so that the output will be as follows</p> <pre><code>Records Affected ---------------- The number of records affected for F1 is : 4 The number of records affected for F2 is : 3 The number of records affected for F3 is : 5 "The number of records affected for " + TYPE + " is : " + COUNT. </code></pre> <p>How can I add the default text to each row of the result set instead of appending in the front end. I would like to simplify my task of just showing the records in the DataGrid as Summary.</p>
16,965,134
5
3
null
2013-06-06 14:38:56.21 UTC
3
2016-12-23 05:22:31.02 UTC
2013-06-06 14:53:58.25 UTC
null
1,572,750
null
1,407,900
null
1
8
sql-server-2008
79,720
<p>You can easily concatenate the string using the following. You will use the <code>+</code> to concatenate the string to the <code>type</code> column and the <code>count</code>. Note, the <code>count</code> needs to be converted to a <code>varchar</code> for this to work:</p> <pre><code>SELECT 'The number of records affected for '+ type + ' is : '+ cast(COUNT(ID) as varchar(50)) as'Records Affected' FROM yt GROUP BY TYPE; </code></pre> <p>See <a href="http://sqlfiddle.com/#!3/817e1/4">SQL Fiddle with Demo</a></p>
66,429,202
What are production use cases for the useRef, useMemo, useCallback hooks?
<p>Outside of the <strong>counter</strong> example seen in many YouTube tutorial videos, what are <strong>practical/real-world</strong> use cases for <code>useMemo</code> and <code>useCallback</code>?</p> <p>Also, I've only seen an <strong>input focus</strong> example for the <code>useRef</code> hook.</p> <p>Please share other use cases you've found for these hooks.</p>
66,626,493
3
9
null
2021-03-01 20:29:32.55 UTC
15
2022-01-22 13:26:17 UTC
2021-03-14 16:05:51.563 UTC
null
2,873,538
null
6,388,443
null
1
10
reactjs|react-hooks|use-ref|usecallback|react-usememo
14,406
<h2><code>useRef</code>:</h2> <p><strong>Syntax:</strong> <code>const refObject = useRef(initialValue);</code></p> <p>It simply returns a plain JavaScript <strong>object</strong>. Its value can be accessed and modified (<strong>mutability</strong>) as many times as you need without worrying about &quot;rerender&quot;.</p> <p>Its value will <strong>persist</strong> (won't be reset to the <code>initialValue</code> unlike an ordinary* object defined in your function component; it persists because <code>useRef</code> gives you the same object instead of creating a new one on subsequent renders) for the component lifetime.</p> <p>If you write <code>const refObject = useRef(0)</code> and print <code>refObject</code> on console, you would see the log an object - <code>{ current: 0 }</code>.</p> <p>*<strong>ordinary object vs refObject, example:</strong></p> <pre class="lang-js prettyprint-override"><code>function App() { const ordinaryObject = { current: 0 } // It will reset to {current:0} at each render const refObject = useRef(0) // It will persist (won't reset to the initial value) for the component lifetime return &lt;&gt;...&lt;/&gt; } </code></pre> <p><strong>Few common uses, examples:</strong></p> <ol> <li>To access the <a href="https://reactjs.org/docs/refs-and-the-dom.html" rel="noreferrer">DOM</a>: <code>&lt;div ref={myRef} /&gt;</code></li> <li>Store mutable value like <a href="https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables" rel="noreferrer">instance variable (in class)</a></li> <li>A render <a href="https://stackoverflow.com/a/66199206/2873538">counter</a></li> <li>A value to be used in <code>setTimeout</code> / <code>setInterval</code> without a <a href="https://stackoverflow.com/a/66435915/2873538">stale closure</a> issue.</li> </ol> <hr /> <h2><code>useMemo</code>:</h2> <p><strong>Syntax</strong>: <code>const memoizedValue = useMemo(() =&gt; computeExpensiveValue(a, b), [a, b]);</code></p> <p>It returns a <a href="https://en.wikipedia.org/wiki/Memoization" rel="noreferrer">memoized</a> <strong>value</strong>. The primary purpose of this hook is &quot;performance optimization&quot;. Use it sparingly to optimize the performance when needed.</p> <p>It accepts two arguments - &quot;create&quot; function (which should return a value to be memoized) and &quot;dependency&quot; array. It will recompute the memoized value only when one of the dependencies has changed.</p> <p><strong>Few common uses, examples:</strong></p> <ol> <li>Optimize expensive calculations (e.g. operations on data like sort, filter, changing format etc.) while rendering</li> </ol> <p><strong>Unmemoized example:</strong></p> <pre><code>function App() { const [data, setData] = useState([.....]) function format() { console.log('formatting ...') // this will print at every render const formattedData = [] data.forEach(item =&gt; { const newItem = // ... do somthing here, formatting, sorting, filtering (by date, by text,..) etc if (newItem) { formattedData.push(newItem) } }) return formattedData } const formattedData = format() return &lt;&gt; {formattedData.map(item =&gt; &lt;div key={item.id}&gt; {item.title} &lt;/div&gt;)} &lt;/&gt; } </code></pre> <p><strong>Memoized example:</strong></p> <pre><code>function App() { const [data, setData] = useState([.....]) function format() { console.log('formatting ...') // this will print only when data has changed const formattedData = [] data.forEach(item =&gt; { const newItem = // ... do somthing here, formatting, sorting, filtering (by date, by text,..) etc if (newItem) { formattedData.push(newItem) } }) return formattedData } const formattedData = useMemo(format, [data]) return &lt;&gt; {formattedData.map(item =&gt; &lt;div key={item.id}&gt; {item.title} &lt;/div&gt;)} &lt;&gt; } </code></pre> <hr /> <h2><code>useCallback</code>:</h2> <p><strong>Syntax</strong>: <code>const memoizedCallback = useCallback(() =&gt; { //.. do something with a &amp; b }, [a, b])</code></p> <p>It returns a <a href="https://en.wikipedia.org/wiki/Memoization" rel="noreferrer">memoized</a> <strong>function</strong> (or callback).</p> <p>It accepts two arguments - &quot;function&quot; and &quot;dependency&quot; array. It will return new i.e. re-created function only when one of the dependencies has changed, or else it will return the old i.e. memoized one.</p> <p><strong>Few common uses, examples:</strong></p> <ol> <li>Passing memoized functions to child components (that are optimized with <code>React.memo</code> or <code>shouldComponentUpdate</code> using shallow equal - <code>Object.is</code>) to avoid unnecessary rerender of child component due to functions passed as props.</li> </ol> <p><strong>Example 1, without <code>useCallback</code>:</strong></p> <pre><code>const Child = React.memo(function Child({foo}) { console.log('child rendering ...') // Child will rerender (because foo will be new) whenever MyApp rerenders return &lt;&gt;Child&lt;&gt; }) function MyApp() { function foo() { // do something } return &lt;Child foo={foo}/&gt; } </code></pre> <p><strong>Example 1, with <code>useCallback</code>:</strong></p> <pre><code>const Child = React.memo(function Child({foo}) { console.log('child rendering ...') // Child will NOT rerender whenever MyApp rerenders // But will rerender only when memoizedFoo is new (and that will happen only when useCallback's dependency would change) return &lt;&gt;Child&lt;&gt; }) function MyApp() { function foo() { // do something } const memoizedFoo = useCallback(foo, []) return &lt;Child foo={memoizedFoo}/&gt; } </code></pre> <ol start="2"> <li>Passing memoized functions to as dependencies in other hooks.</li> </ol> <p><strong>Example 2, without <code>useCallback</code>, Bad (But <code>eslint-plugin-react-hook</code> would give you warning to correct it):</strong></p> <pre><code>function MyApp() { function foo() { // do something with state or props data } useEffect(() =&gt; { // do something with foo // maybe fetch from API and then pass data to foo foo() }, [foo]) return &lt;&gt;...&lt;&gt; } </code></pre> <p><strong>Example 2, with <code>useCallback</code>, Good:</strong></p> <pre><code>function MyApp() { const memoizedFoo = useCallback(function foo() { // do something with state or props data }, [ /* related state / props */]) useEffect(() =&gt; { // do something with memoizedFoo // maybe fetch from API and then pass data to memoizedFoo memoizedFoo() }, [memoizedFoo]) return &lt;&gt;...&lt;&gt; } </code></pre> <p>These hooks rules or implementations may change in the future. So, please make sure to check <a href="https://reactjs.org/docs/hooks-reference.html#usecallback" rel="noreferrer">hooks reference</a> in docs. Also, it is important to pay attention to <strong>eslint-plugin-react-hook</strong> warnings about dependencies. It will guide you if omit any dependency of these hooks.</p>
41,240,414
Equivalent of Scala's foldLeft in Java 8
<p>What is the equivalent of of Scala's great <code>foldLeft</code> in Java 8?</p> <p>I was tempted to think it was <code>reduce</code>, but reduce has to return something of identical type to what it reduces on. </p> <p>Example:</p> <pre><code>import java.util.List; public class Foo { // this method works pretty well public int sum(List&lt;Integer&gt; numbers) { return numbers.stream() .reduce(0, (acc, n) -&gt; (acc + n)); } // this method makes the file not compile public String concatenate(List&lt;Character&gt; chars) { return chars.stream() .reduce(new StringBuilder(""), (acc, c) -&gt; acc.append(c)).toString(); } } </code></pre> <p>The problem in the code above is the <code>acc</code>umulator: <code>new StringBuilder("")</code></p> <p>Thus, could anyone point me to the proper equivalent of the <code>foldLeft</code>/fix my code?</p>
41,240,645
5
4
null
2016-12-20 10:43:09.973 UTC
6
2021-05-14 10:02:43.493 UTC
2017-10-17 09:48:00.517 UTC
null
3,975,247
null
3,975,247
null
1
33
java|java-8|reduce|foldleft
29,711
<p><strong>Update:</strong> </p> <p>Here is initial attempt to get your code fixed:</p> <pre><code>public static String concatenate(List&lt;Character&gt; chars) { return chars .stream() .reduce(new StringBuilder(), StringBuilder::append, StringBuilder::append).toString(); } </code></pre> <p>It uses the following <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#reduce-U-java.util.function.BiFunction-java.util.function.BinaryOperator-" rel="noreferrer">reduce method</a>:</p> <pre><code>&lt;U&gt; U reduce(U identity, BiFunction&lt;U, ? super T, U&gt; accumulator, BinaryOperator&lt;U&gt; combiner); </code></pre> <p>It may sound confusing but if you look at the javadocs there is a nice explanation that may help you quickly grasp the details. The reduction is equivalent to the following code:</p> <pre><code>U result = identity; for (T element : this stream) result = accumulator.apply(result, element) return result; </code></pre> <p>For a more in-depth explanation please check <a href="https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html" rel="noreferrer">this source</a>. </p> <p>This usage is not correct though because it violates the contract of reduce which states that the accumulator should be <em>an associative, non-interfering, stateless function for incorporating an additional element into a result</em>. In other words since the identity is mutable the result will be broken in case of parallel execution.</p> <p>As pointed in the comments below a correct option is using the reduction as follows:</p> <pre><code>return chars.stream().collect( StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); </code></pre> <p>The supplier <code>StringBuilder::new</code> will be used to create reusable containers which will be later combined. </p>
12,274,628
Compile a referenced LESS file into CSS with PHP automatically
<p>I want the following things to occur:</p> <ol> <li><p>Have the process automated server side.</p></li> <li><p>Simply be able to reference the LESS file as I would a CSS file in my code.</p></li> <li><p>The user is returned minified CSS instead of the LESS file - cached so the compiler doesn't need to run unless the LESS file has been updated.</p></li> <li><p>For this to work with <em>any</em> LESS file that is referenced anywhere within my domain.</p></li> </ol> <p>I spotted <a href="http://leafo.net/lessphp/">Lessphp</a>, but the documentation isn't very clear, nor does it explain how to dynamically get any LESS file to it. I thought I would post up how I got it all working as I haven't seen a run through on how to achieve this with PHP.</p>
12,274,629
1
0
null
2012-09-05 04:47:47.82 UTC
12
2013-09-03 13:06:11.127 UTC
2013-09-03 13:06:11.127 UTC
null
1,455,709
null
1,455,709
null
1
11
php|css|caching|compiler-construction|less
7,485
<p><strong>THIS ASSUMES LESSPHP v0.3.8+</strong> Unsure about earlier versions, but you'll get the gist of how it works if it doesn't straight out of the box.</p> <p><code>&lt;link rel="stylesheet" type="text/css" href="styles/main.less" /&gt;</code></p> <p>If you were using less.js to compile client side, make sure you change <code>rel="stylesheet/less"</code> to <code>rel="stylesheet"</code></p> <p>1) Grab <a href="http://leafo.net/lessphp/" rel="noreferrer">Lessphp</a> I placed these files in <code>/www/compilers/lessphp/</code> for the context of this demo</p> <p>2) Make a PHP script that we can throw out LESS files at. This will deal with caching, compiling to CSS and returning the CSS as a response. I have placed this file at <code>/www/compilers/</code> and called it <code>lessphp.php</code></p> <p>Most of this code was on the Lessphp site, except there were errors in it, and I have added the response at the end.</p> <pre><code>&lt;?php require "lessphp/lessc.inc.php"; $file = $_GET["file"]; function autoCompileLess($inputFile, $outputFile) { // load the cache $cacheFile = $inputFile.".cache"; if (file_exists($cacheFile)) { $cache = unserialize(file_get_contents($cacheFile)); } else { $cache = $inputFile; } $less = new lessc; $less-&gt;setFormatter("compressed"); $newCache = $less-&gt;cachedCompile($cache); if (!is_array($cache) || $newCache["updated"] &gt; $cache["updated"]) { file_put_contents($cacheFile, serialize($newCache)); file_put_contents($outputFile, $newCache['compiled']); } } autoCompileLess('../' . $file, '../' . $file . '.css'); header('Content-type: text/css'); readfile('../' . $file . '.css'); ?&gt; </code></pre> <p>This will compile the LESS file (eg, <code>styles/main.less</code>) to a cache file and a CSS file (eg, <code>styles/main.less.css</code>).</p> <p>3) Add a <code>mod_rewrite</code> rule so that any LESS files a user requests are redirected to our compiler, giving it its path. This was placed in the root <code>.htaccess</code> file.</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^([^.]*\.less)$ compilers/lessphp.php?file=$1 [R,QSA,L] &lt;/ifModule&gt; </code></pre> <p>If you are using WordPress, this rule will need to come after it - even if WordPress is in a sub directory, it seems to overwrite these rules, and LESS compilation will not occur for referenced files which exist below (directory wise) WordPress's <code>.htaccess</code> rules.</p> <p>4) Your LESS code should be relatively referenced in relation to the compilers location. Additionally, Lessphp compiler will fail if there are empty attributes, eg. <code>background-color: ;</code></p> <hr> <p>If all is working well, the following should occur:</p> <ol> <li><p>Directly browse your LESS file <code>http://domain.com/styles/main.less</code></p></li> <li><p>Be automatically redirected to <code>http://domain.com/compilers/lessphp?file=styles/main.less</code></p></li> <li><p>Be presented with minified CSS</p></li> <li><p><code>main.less.css</code> and <code>main.less.cache</code> should now exist in the same directory as your LESS file</p></li> <li><p>The last modified dates shouldn’t change unless you update your LESS file</p></li> </ol>
12,136,841
AVMutableVideoComposition rotated video captured in portrait mode
<p>I have used below code to add image overlay over video and then export the new generated video to document directory. But strangely,video gets rotated by 90 degrees. </p> <pre><code>- (void)buildTransitionComposition:(AVMutableComposition *)composition andVideoComposition:(AVMutableVideoComposition *)videoComposition { CMTime nextClipStartTime = kCMTimeZero; NSInteger i; // Make transitionDuration no greater than half the shortest clip duration. CMTime transitionDuration = self.transitionDuration; for (i = 0; i &lt; [_clips count]; i++ ) { NSValue *clipTimeRange = [_clipTimeRanges objectAtIndex:i]; if (clipTimeRange) { CMTime halfClipDuration = [clipTimeRange CMTimeRangeValue].duration; halfClipDuration.timescale *= 2; // You can halve a rational by doubling its denominator. transitionDuration = CMTimeMinimum(transitionDuration, halfClipDuration); } } // Add two video tracks and two audio tracks. AVMutableCompositionTrack *compositionVideoTracks[2]; AVMutableCompositionTrack *compositionAudioTracks[2]; compositionVideoTracks[0] = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid]; compositionVideoTracks[1] = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid]; compositionAudioTracks[0] = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid]; compositionAudioTracks[1] = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid]; CMTimeRange *passThroughTimeRanges = alloca(sizeof(CMTimeRange) * [_clips count]); CMTimeRange *transitionTimeRanges = alloca(sizeof(CMTimeRange) * [_clips count]); // Place clips into alternating video &amp; audio tracks in composition, overlapped by transitionDuration. for (i = 0; i &lt; [_clips count]; i++ ) { NSInteger alternatingIndex = i % 2; // alternating targets: 0, 1, 0, 1, ... AVURLAsset *asset = [_clips objectAtIndex:i]; NSValue *clipTimeRange = [_clipTimeRanges objectAtIndex:i]; CMTimeRange timeRangeInAsset; if (clipTimeRange) timeRangeInAsset = [clipTimeRange CMTimeRangeValue]; else timeRangeInAsset = CMTimeRangeMake(kCMTimeZero, [asset duration]); AVAssetTrack *clipVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]; [compositionVideoTracks[alternatingIndex] insertTimeRange:timeRangeInAsset ofTrack:clipVideoTrack atTime:nextClipStartTime error:nil]; /* CGAffineTransform t = clipVideoTrack.preferredTransform; NSLog(@"Transform1 : %@",t); */ AVAssetTrack *clipAudioTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]; [compositionAudioTracks[alternatingIndex] insertTimeRange:timeRangeInAsset ofTrack:clipAudioTrack atTime:nextClipStartTime error:nil]; // Remember the time range in which this clip should pass through. // Every clip after the first begins with a transition. // Every clip before the last ends with a transition. // Exclude those transitions from the pass through time ranges. passThroughTimeRanges[i] = CMTimeRangeMake(nextClipStartTime, timeRangeInAsset.duration); if (i &gt; 0) { passThroughTimeRanges[i].start = CMTimeAdd(passThroughTimeRanges[i].start, transitionDuration); passThroughTimeRanges[i].duration = CMTimeSubtract(passThroughTimeRanges[i].duration, transitionDuration); } if (i+1 &lt; [_clips count]) { passThroughTimeRanges[i].duration = CMTimeSubtract(passThroughTimeRanges[i].duration, transitionDuration); } // The end of this clip will overlap the start of the next by transitionDuration. // (Note: this arithmetic falls apart if timeRangeInAsset.duration &lt; 2 * transitionDuration.) nextClipStartTime = CMTimeAdd(nextClipStartTime, timeRangeInAsset.duration); nextClipStartTime = CMTimeSubtract(nextClipStartTime, transitionDuration); // Remember the time range for the transition to the next item. transitionTimeRanges[i] = CMTimeRangeMake(nextClipStartTime, transitionDuration); } // Set up the video composition if we are to perform crossfade or push transitions between clips. NSMutableArray *instructions = [NSMutableArray array]; // Cycle between "pass through A", "transition from A to B", "pass through B", "transition from B to A". for (i = 0; i &lt; [_clips count]; i++ ) { NSInteger alternatingIndex = i % 2; // alternating targets // Pass through clip i. AVMutableVideoCompositionInstruction *passThroughInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction]; passThroughInstruction.timeRange = passThroughTimeRanges[i]; AVMutableVideoCompositionLayerInstruction *passThroughLayer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:compositionVideoTracks[alternatingIndex]]; /* CGAffineTransform rotationTransform = CGAffineTransformMakeRotation(M_PI_2); CGAffineTransform rotateTranslate = CGAffineTransformTranslate(rotationTransform,320,0); [passThroughLayer setTransform:rotateTranslate atTime:kCMTimeZero]; */ passThroughInstruction.layerInstructions = [NSArray arrayWithObject:passThroughLayer]; [instructions addObject:passThroughInstruction]; if (i+1 &lt; [_clips count]) { // Add transition from clip i to clip i+1. AVMutableVideoCompositionInstruction *transitionInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction]; transitionInstruction.timeRange = transitionTimeRanges[i]; AVMutableVideoCompositionLayerInstruction *fromLayer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:compositionVideoTracks[alternatingIndex]]; AVMutableVideoCompositionLayerInstruction *toLayer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:compositionVideoTracks[1-alternatingIndex]]; if (self.transitionType == SimpleEditorTransitionTypeCrossFade) { // Fade out the fromLayer by setting a ramp from 1.0 to 0.0. [fromLayer setOpacityRampFromStartOpacity:1.0 toEndOpacity:0.0 timeRange:transitionTimeRanges[i]]; } else if (self.transitionType == SimpleEditorTransitionTypePush) { // Set a transform ramp on fromLayer from identity to all the way left of the screen. [fromLayer setTransformRampFromStartTransform:CGAffineTransformIdentity toEndTransform:CGAffineTransformMakeTranslation(-composition.naturalSize.width, 0.0) timeRange:transitionTimeRanges[i]]; // Set a transform ramp on toLayer from all the way right of the screen to identity. [toLayer setTransformRampFromStartTransform:CGAffineTransformMakeTranslation(+composition.naturalSize.width, 0.0) toEndTransform:CGAffineTransformIdentity timeRange:transitionTimeRanges[i]]; } transitionInstruction.layerInstructions = [NSArray arrayWithObjects:fromLayer, toLayer, nil]; [instructions addObject:transitionInstruction]; } } videoComposition.instructions = instructions; } </code></pre> <p>Please help,as I am not able to export portrait video in proper mode.Any help appreciated. Thank you.</p>
12,136,925
6
0
null
2012-08-27 05:56:24.617 UTC
11
2020-10-21 13:00:00.82 UTC
null
null
null
null
1,400,442
null
1
18
iphone|ios|avmutablecomposition
19,672
<p>By default, when you export video using <strong>AVAssetExportSession</strong> then video will be rotated from its original orientation. You have to apply its transform to set it exact orientation.You please try below code to do the same.</p> <pre><code>- (AVMutableVideoCompositionLayerInstruction *)layerInstructionAfterFixingOrientationForAsset:(AVAsset *)inAsset forTrack:(AVMutableCompositionTrack *)inTrack atTime:(CMTime)inTime { //FIXING ORIENTATION// AVMutableVideoCompositionLayerInstruction *videolayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:inTrack]; AVAssetTrack *videoAssetTrack = [[inAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]; UIImageOrientation videoAssetOrientation_ = UIImageOrientationUp; BOOL isVideoAssetPortrait_ = NO; CGAffineTransform videoTransform = videoAssetTrack.preferredTransform; if(videoTransform.a == 0 &amp;&amp; videoTransform.b == 1.0 &amp;&amp; videoTransform.c == -1.0 &amp;&amp; videoTransform.d == 0) {videoAssetOrientation_= UIImageOrientationRight; isVideoAssetPortrait_ = YES;} if(videoTransform.a == 0 &amp;&amp; videoTransform.b == -1.0 &amp;&amp; videoTransform.c == 1.0 &amp;&amp; videoTransform.d == 0) {videoAssetOrientation_ = UIImageOrientationLeft; isVideoAssetPortrait_ = YES;} if(videoTransform.a == 1.0 &amp;&amp; videoTransform.b == 0 &amp;&amp; videoTransform.c == 0 &amp;&amp; videoTransform.d == 1.0) {videoAssetOrientation_ = UIImageOrientationUp;} if(videoTransform.a == -1.0 &amp;&amp; videoTransform.b == 0 &amp;&amp; videoTransform.c == 0 &amp;&amp; videoTransform.d == -1.0) {videoAssetOrientation_ = UIImageOrientationDown;} CGFloat FirstAssetScaleToFitRatio = 320.0 / videoAssetTrack.naturalSize.width; if(isVideoAssetPortrait_) { FirstAssetScaleToFitRatio = 320.0/videoAssetTrack.naturalSize.height; CGAffineTransform FirstAssetScaleFactor = CGAffineTransformMakeScale(FirstAssetScaleToFitRatio,FirstAssetScaleToFitRatio); [videolayerInstruction setTransform:CGAffineTransformConcat(videoAssetTrack.preferredTransform, FirstAssetScaleFactor) atTime:kCMTimeZero]; }else{ CGAffineTransform FirstAssetScaleFactor = CGAffineTransformMakeScale(FirstAssetScaleToFitRatio,FirstAssetScaleToFitRatio); [videolayerInstruction setTransform:CGAffineTransformConcat(CGAffineTransformConcat(videoAssetTrack.preferredTransform, FirstAssetScaleFactor),CGAffineTransformMakeTranslation(0, 160)) atTime:kCMTimeZero]; } [videolayerInstruction setOpacity:0.0 atTime:inTime]; return videolayerInstruction; } </code></pre> <p>I hope this will help you.</p> <pre><code>AVAssetTrack *assetTrack = [[inAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]; AVMutableCompositionTrack *mutableTrack = [mergeComposition mutableTrackCompatibleWithTrack:assetTrack]; AVMutableVideoCompositionLayerInstruction *assetInstruction = [self layerInstructionAfterFixingOrientationForAsset:inAsset forTrack:myLocalVideoTrack atTime:videoTotalDuration]; </code></pre> <p>Above is the code to call mentioned method where <code>inAsset</code> is your video asset and <code>videoTotalDuration</code> is your video total duration in <code>CMTime.mergeComposition</code> is object of <code>AVMutableComposition</code> class.</p> <p>Hope this will help.</p> <p>EDIT: This is not any callback method or event, you have to call it expectedly with required parameters as mentioned above. </p>
12,406,032
get fraction part of a decimal number
<p>I am trying to get a fraction part of a decimal number in rails. For example I have a number, that "1.23" and I want to get "23" It is may be too easy but, does anyone have any idea about how can I do?</p>
12,406,132
9
0
null
2012-09-13 12:16:05.27 UTC
2
2020-04-26 06:28:24.637 UTC
2016-08-18 02:06:35.193 UTC
null
2,387,599
null
883,906
null
1
33
ruby-on-rails|ruby|ruby-on-rails-3
22,197
<p>I am not sure if it is the easiest way to do it - but you can simply split the number using "." character - like this:</p> <pre><code>number = 1.23 parts = number.to_s.split(".") result = parts.count &gt; 1 ? parts[1].to_s : 0 </code></pre>
3,387,191
Python csv without header
<p>With header information in csv file, city can be grabbed as:</p> <pre><code>city = row['city'] </code></pre> <p>Now how to assume that csv file does not have headers, there is only 1 column, and column is city.</p>
3,387,212
3
1
null
2010-08-02 11:16:50.277 UTC
4
2018-06-26 14:11:14.44 UTC
null
null
null
null
347,039
null
1
27
python|csv
81,145
<p>You can still use your line, if you declare the headers yourself, since you know it:</p> <pre><code>with open('data.csv') as f: cf = csv.DictReader(f, fieldnames=['city']) for row in cf: print row['city'] </code></pre> <p>For more information check <a href="http://docs.python.org/library/csv#csv.DictReader" rel="noreferrer"><code>csv.DictReader</code></a> info in the docs.</p> <p>Another option is to just use positional indexing, since you know there's only one column:</p> <pre><code>with open('data.csv') as f: cf = csv.reader(f) for row in cf: print row[0] </code></pre>
22,597,781
An Android Virtual Device that failed to load
<p>Note: this question is very similar to another question posed much earlier by another person, but does not solve my problem. (<em>not</em> the same question <a href="https://stackoverflow.com/questions/15749711/an-android-virtual-device-that-failed-to-load-click-details-to-see-the-error">here</a>)</p> <p>Situation: I just installed Eclipse/ADK/Android SDK, etc. and made sure to download/install Android 2.2, 4.2.2, &amp; 4.4.2 from the SDK Manager.</p> <p>I am now trying to create an Android Virtual Device akin to the Google Nexus 5, which uses 4.4.2. <strong>Using 512 MB of RAM</strong></p> <p>Problem arises when I finish "creating" it, the AVD fails to load. I can dismiss this error, but I actually can't run anything on that AVD - it's just a black screen... not even the simple Hello World! </p> <p><img src="https://i.stack.imgur.com/bH2R4.png" alt="AVD crashes when loading."></p> <p>When I try to launch an application, I get the following error:</p> <pre><code>Android Launch! adb is running normally. Performing com.XXX.myapp001.StartingPoint activity launch Automatic Target Mode: Preferred AVD 'AVD_for_Nexus_5_by_Google' is available on emulator 'emulator-5554' Uploading TheNewBoston.apk onto device 'emulator-5554' Installing TheNewBoston.apk... Installation error: Unknown failure Please check logcat output for more details. Launch canceled! </code></pre> <p>Thank you.</p>
25,505,963
2
10
null
2014-03-23 22:07:45.063 UTC
5
2016-01-04 10:24:38.583 UTC
2017-05-23 12:25:43.357 UTC
null
-1
user3453166
null
null
1
12
android|eclipse|avd
69,716
<p>Forgot to re-post this answer that I put in the comments section of my original post chain.</p> <p><strong>solution:</strong> was HAX allocation. Solution can be found in the following <a href="http://youtube.com/watch?v=tXnm8Lsl-dg" rel="nofollow">video</a>.</p>
18,840,422
Do negative numbers return false in C/C++?
<p>When evaluating integers as booleans in C/C++, are negative numbers true or false? Are they always true/false regardless of compilers?</p>
18,840,449
5
9
null
2013-09-17 02:36:54.167 UTC
21
2019-07-27 20:04:31.64 UTC
null
null
null
null
2,453,816
null
1
62
c++|c|boolean
73,548
<p>All non-zero values will be converted to <code>true</code>, and zero values to <code>false</code>. With negative numbers being non-zero, they are converted to <code>true</code>.</p> <p>Quoting from the C++11 standard (emphasis mine):</p> <blockquote> <p>4.12 Boolean conversions [conv.bool]</p> <p>1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. <strong>A zero value, null pointer value, or null member pointer value is converted to <code>false</code>; any other value is converted to <code>true</code>.</strong> A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.</p> </blockquote> <hr> <blockquote> <p>Are they always true/false regardless of compilers?</p> </blockquote> <p>You will only get the above guarantee when your compiler is standards-compliant, or at least, complies with this specific part of the standard. In practice, all compilers have this standard behavior, so there isn't much to worry about.</p>
20,731,402
Animated (Smooth) scrolling on ScrollViewer
<p>I have a <code>ScrollViewer</code> in my WPF App, and I want it to have smooth/animated scrolling effect just like <em>Firefox</em> has (if you know what I am talking about).</p> <p>I tried to search over the internet, and the only thing I've found is this:<br/></p> <p><a href="http://matthiasshapiro.com/DisneyShorts/how-to-create-an-animated-scrollviewer-or-listbox-in-wpf" rel="noreferrer">How To Create An Animated ScrollViewer (or ListBox) in WPF</a></p> <p>It works pretty good, but I have one problem with it - it animates the scrolling effect but the <code>ScrollViewer</code>'s <code>Thumb</code> goes directly to the point pressed - I want it to be animated aswell</p> <p>How can I cause the <code>ScrollViewer</code>'s <code>Thumb</code> to be animated as well, or else is there a working control with the same properties/features I want?</p>
20,846,310
4
3
null
2013-12-22 16:17:20.387 UTC
22
2022-01-11 21:39:40.99 UTC
2019-07-31 10:50:17.91 UTC
null
5,955,233
null
519,002
null
1
36
wpf|animation|scrollviewer
26,329
<p>In your example there are two controls inherited from <code>ScrollViewer</code> and <code>ListBox</code>, the animation is implemented by <code>SplineDoubleKeyFrame</code> <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.animation.splinedoublekeyframe%28v=vs.110%29.aspx" rel="noreferrer">[MSDN]</a>. In my time, I realized animation scrolling via the attached dependency property <code>VerticalOffsetProperty</code>, which allows you to directly transfer offset scrollbar into a double animation, like this:</p> <pre><code>DoubleAnimation verticalAnimation = new DoubleAnimation(); verticalAnimation.From = scrollViewer.VerticalOffset; verticalAnimation.To = some value; verticalAnimation.Duration = new Duration( some duration ); Storyboard storyboard = new Storyboard(); storyboard.Children.Add(verticalAnimation); Storyboard.SetTarget(verticalAnimation, scrollViewer); Storyboard.SetTargetProperty(verticalAnimation, new PropertyPath(ScrollAnimationBehavior.VerticalOffsetProperty)); // Attached dependency property storyboard.Begin(); </code></pre> <p>Examples can be found here:</p> <p><a href="http://blogs.msdn.com/b/delay/archive/2009/08/04/scrolling-so-smooth-like-the-butter-on-a-muffin-how-to-animate-the-horizontal-verticaloffset-properties-of-a-scrollviewer.aspx" rel="noreferrer">How to: Animate the Horizontal/VerticalOffset properties of a ScrollViewer</a></p> <p><a href="https://stackoverflow.com/questions/665719/wpf-animate-listbox-scrollviewer-horizontaloffset?rq=1">WPF - Animate ListBox.ScrollViewer.HorizontalOffset?</a></p> <p>In this case, works well smooth scrolling of the content and the <code>Thumb</code>. Based on this approach, and using your example<a href="http://matthiasshapiro.com/DisneyShorts/how-to-create-an-animated-scrollviewer-or-listbox-in-wpf" rel="noreferrer"> [How To Create An Animated ScrollViewer (or ListBox) in WPF]</a>, I created an attached behavior <code>ScrollAnimationBehavior</code>, which can be applied to <code>ScrollViewer</code>and <code>ListBox</code>.</p> <p>Example of using:</p> <p><code>XAML</code></p> <pre><code>&lt;Window x:Class="ScrollAnimateBehavior.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:AttachedBehavior="clr-namespace:ScrollAnimateBehavior.AttachedBehaviors" Title="MainWindow" WindowStartupLocation="CenterScreen" Height="350" Width="525"&gt; &lt;Window.Resources&gt; &lt;x:Array x:Key="TestArray" Type="{x:Type sys:String}"&gt; &lt;sys:String&gt;TEST 1&lt;/sys:String&gt; &lt;sys:String&gt;TEST 2&lt;/sys:String&gt; &lt;sys:String&gt;TEST 3&lt;/sys:String&gt; &lt;sys:String&gt;TEST 4&lt;/sys:String&gt; &lt;sys:String&gt;TEST 5&lt;/sys:String&gt; &lt;sys:String&gt;TEST 6&lt;/sys:String&gt; &lt;sys:String&gt;TEST 7&lt;/sys:String&gt; &lt;sys:String&gt;TEST 8&lt;/sys:String&gt; &lt;sys:String&gt;TEST 9&lt;/sys:String&gt; &lt;sys:String&gt;TEST 10&lt;/sys:String&gt; &lt;/x:Array&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;TextBlock Text="ScrollViewer" FontFamily="Verdana" FontSize="14" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="80,80,0,0" /&gt; &lt;ScrollViewer AttachedBehavior:ScrollAnimationBehavior.IsEnabled="True" AttachedBehavior:ScrollAnimationBehavior.TimeDuration="00:00:00.20" AttachedBehavior:ScrollAnimationBehavior.PointsToScroll="16" HorizontalAlignment="Left" Width="250" Height="100"&gt; &lt;StackPanel&gt; &lt;ItemsControl ItemsSource="{StaticResource TestArray}" FontSize="16" /&gt; &lt;/StackPanel&gt; &lt;/ScrollViewer&gt; &lt;TextBlock Text="ListBox" FontFamily="Verdana" FontSize="14" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,80,100,0" /&gt; &lt;ListBox AttachedBehavior:ScrollAnimationBehavior.IsEnabled="True" ItemsSource="{StaticResource TestArray}" ScrollViewer.CanContentScroll="False" HorizontalAlignment="Right" FontSize="16" Width="250" Height="100" /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p><code>Output</code></p> <p><img src="https://i.stack.imgur.com/y4Npk.png" alt="enter image description here"></p> <p><code>IsEnabled</code> property is responsible for the scrolling animation for <code>ScrollViewer</code> and for <code>ListBox</code>. Below its implementation:</p> <pre><code>public static DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(ScrollAnimationBehavior), new UIPropertyMetadata(false, OnIsEnabledChanged)); public static void SetIsEnabled(FrameworkElement target, bool value) { target.SetValue(IsEnabledProperty, value); } public static bool GetIsEnabled(FrameworkElement target) { return (bool)target.GetValue(IsEnabledProperty); } private static void OnIsEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var target = sender; if (target != null &amp;&amp; target is ScrollViewer) { ScrollViewer scroller = target as ScrollViewer; scroller.Loaded += new RoutedEventHandler(scrollerLoaded); } if (target != null &amp;&amp; target is ListBox) { ListBox listbox = target as ListBox; listbox.Loaded += new RoutedEventHandler(listboxLoaded); } } </code></pre> <p>In these <code>Loaded</code> handlers are set event handlers for <code>PreviewMouseWheel</code> and <code>PreviewKeyDown</code>. </p> <p>Helpers (auxiliary procedures) are taken from the example and provide a value of <code>double</code> type, which is passed to the procedure <code>AnimateScroll()</code>. Here and are the magic key of animation:</p> <pre><code>private static void AnimateScroll(ScrollViewer scrollViewer, double ToValue) { DoubleAnimation verticalAnimation = new DoubleAnimation(); verticalAnimation.From = scrollViewer.VerticalOffset; verticalAnimation.To = ToValue; verticalAnimation.Duration = new Duration(GetTimeDuration(scrollViewer)); Storyboard storyboard = new Storyboard(); storyboard.Children.Add(verticalAnimation); Storyboard.SetTarget(verticalAnimation, scrollViewer); Storyboard.SetTargetProperty(verticalAnimation, new PropertyPath(ScrollAnimationBehavior.VerticalOffsetProperty)); storyboard.Begin(); } </code></pre> <p><strong><code>Some notes</code></strong></p> <ul> <li><p>The example only implemented vertical animation, if you will accept this project, you will realize itself without problems horizontal animation.</p></li> <li><p>Selection of the current item in <code>ListBox</code> not transferred to the next element of this is due to the interception of events <code>PreviewKeyDown</code>, so you have to think about this moment.</p></li> <li><p>This implementation is fully suited for the MVVM pattern. To use this behavior in the <code>Blend</code>, you need to inherit interface <code>Behavior</code>. Example can be found <a href="http://wpftutorial.net/Behaviors.html" rel="noreferrer">here</a> and <a href="http://nnish.com/2012/04/22/attached-behaviors-mvvm/" rel="noreferrer">here</a>.</p></li> </ul> <p><em><code>Tested on Windows XP, Windows Seven, .NET 4.0.</code></em></p> <hr> <p>Sample project is available at this <a href="https://skydrive.live.com/redir?resid=3FC95A33B3F2DE8A!113&amp;authkey=!AGHJ-bCY6UXO_ik&amp;ithint=file,.zip" rel="noreferrer">link</a>. </p> <hr> <p>Below is a full code of this implementation:</p> <pre><code>public static class ScrollAnimationBehavior { #region Private ScrollViewer for ListBox private static ScrollViewer _listBoxScroller = new ScrollViewer(); #endregion #region VerticalOffset Property public static DependencyProperty VerticalOffsetProperty = DependencyProperty.RegisterAttached("VerticalOffset", typeof(double), typeof(ScrollAnimationBehavior), new UIPropertyMetadata(0.0, OnVerticalOffsetChanged)); public static void SetVerticalOffset(FrameworkElement target, double value) { target.SetValue(VerticalOffsetProperty, value); } public static double GetVerticalOffset(FrameworkElement target) { return (double)target.GetValue(VerticalOffsetProperty); } #endregion #region TimeDuration Property public static DependencyProperty TimeDurationProperty = DependencyProperty.RegisterAttached("TimeDuration", typeof(TimeSpan), typeof(ScrollAnimationBehavior), new PropertyMetadata(new TimeSpan(0, 0, 0, 0, 0))); public static void SetTimeDuration(FrameworkElement target, TimeSpan value) { target.SetValue(TimeDurationProperty, value); } public static TimeSpan GetTimeDuration(FrameworkElement target) { return (TimeSpan)target.GetValue(TimeDurationProperty); } #endregion #region PointsToScroll Property public static DependencyProperty PointsToScrollProperty = DependencyProperty.RegisterAttached("PointsToScroll", typeof(double), typeof(ScrollAnimationBehavior), new PropertyMetadata(0.0)); public static void SetPointsToScroll(FrameworkElement target, double value) { target.SetValue(PointsToScrollProperty, value); } public static double GetPointsToScroll(FrameworkElement target) { return (double)target.GetValue(PointsToScrollProperty); } #endregion #region OnVerticalOffset Changed private static void OnVerticalOffsetChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) { ScrollViewer scrollViewer = target as ScrollViewer; if (scrollViewer != null) { scrollViewer.ScrollToVerticalOffset((double)e.NewValue); } } #endregion #region IsEnabled Property public static DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(ScrollAnimationBehavior), new UIPropertyMetadata(false, OnIsEnabledChanged)); public static void SetIsEnabled(FrameworkElement target, bool value) { target.SetValue(IsEnabledProperty, value); } public static bool GetIsEnabled(FrameworkElement target) { return (bool)target.GetValue(IsEnabledProperty); } #endregion #region OnIsEnabledChanged Changed private static void OnIsEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var target = sender; if (target != null &amp;&amp; target is ScrollViewer) { ScrollViewer scroller = target as ScrollViewer; scroller.Loaded += new RoutedEventHandler(scrollerLoaded); } if (target != null &amp;&amp; target is ListBox) { ListBox listbox = target as ListBox; listbox.Loaded += new RoutedEventHandler(listboxLoaded); } } #endregion #region AnimateScroll Helper private static void AnimateScroll(ScrollViewer scrollViewer, double ToValue) { DoubleAnimation verticalAnimation = new DoubleAnimation(); verticalAnimation.From = scrollViewer.VerticalOffset; verticalAnimation.To = ToValue; verticalAnimation.Duration = new Duration(GetTimeDuration(scrollViewer)); Storyboard storyboard = new Storyboard(); storyboard.Children.Add(verticalAnimation); Storyboard.SetTarget(verticalAnimation, scrollViewer); Storyboard.SetTargetProperty(verticalAnimation, new PropertyPath(ScrollAnimationBehavior.VerticalOffsetProperty)); storyboard.Begin(); } #endregion #region NormalizeScrollPos Helper private static double NormalizeScrollPos(ScrollViewer scroll, double scrollChange, Orientation o) { double returnValue = scrollChange; if (scrollChange &lt; 0) { returnValue = 0; } if (o == Orientation.Vertical &amp;&amp; scrollChange &gt; scroll.ScrollableHeight) { returnValue = scroll.ScrollableHeight; } else if (o == Orientation.Horizontal &amp;&amp; scrollChange &gt; scroll.ScrollableWidth) { returnValue = scroll.ScrollableWidth; } return returnValue; } #endregion #region UpdateScrollPosition Helper private static void UpdateScrollPosition(object sender) { ListBox listbox = sender as ListBox; if (listbox != null) { double scrollTo = 0; for (int i = 0; i &lt; (listbox.SelectedIndex); i++) { ListBoxItem tempItem = listbox.ItemContainerGenerator.ContainerFromItem(listbox.Items[i]) as ListBoxItem; if (tempItem != null) { scrollTo += tempItem.ActualHeight; } } AnimateScroll(_listBoxScroller, scrollTo); } } #endregion #region SetEventHandlersForScrollViewer Helper private static void SetEventHandlersForScrollViewer(ScrollViewer scroller) { scroller.PreviewMouseWheel += new MouseWheelEventHandler(ScrollViewerPreviewMouseWheel); scroller.PreviewKeyDown += new KeyEventHandler(ScrollViewerPreviewKeyDown); } #endregion #region scrollerLoaded Event Handler private static void scrollerLoaded(object sender, RoutedEventArgs e) { ScrollViewer scroller = sender as ScrollViewer; SetEventHandlersForScrollViewer(scroller); } #endregion #region listboxLoaded Event Handler private static void listboxLoaded(object sender, RoutedEventArgs e) { ListBox listbox = sender as ListBox; _listBoxScroller = FindVisualChildHelper.GetFirstChildOfType&lt;ScrollViewer&gt;(listbox); SetEventHandlersForScrollViewer(_listBoxScroller); SetTimeDuration(_listBoxScroller, new TimeSpan(0, 0, 0, 0, 200)); SetPointsToScroll(_listBoxScroller, 16.0); listbox.SelectionChanged += new SelectionChangedEventHandler(ListBoxSelectionChanged); listbox.Loaded += new RoutedEventHandler(ListBoxLoaded); listbox.LayoutUpdated += new EventHandler(ListBoxLayoutUpdated); } #endregion #region ScrollViewerPreviewMouseWheel Event Handler private static void ScrollViewerPreviewMouseWheel(object sender, MouseWheelEventArgs e) { double mouseWheelChange = (double)e.Delta; ScrollViewer scroller = (ScrollViewer)sender; double newVOffset = GetVerticalOffset(scroller) - (mouseWheelChange / 3); if (newVOffset &lt; 0) { AnimateScroll(scroller, 0); } else if (newVOffset &gt; scroller.ScrollableHeight) { AnimateScroll(scroller, scroller.ScrollableHeight); } else { AnimateScroll(scroller, newVOffset); } e.Handled = true; } #endregion #region ScrollViewerPreviewKeyDown Handler private static void ScrollViewerPreviewKeyDown(object sender, KeyEventArgs e) { ScrollViewer scroller = (ScrollViewer)sender; Key keyPressed = e.Key; double newVerticalPos = GetVerticalOffset(scroller); bool isKeyHandled = false; if (keyPressed == Key.Down) { newVerticalPos = NormalizeScrollPos(scroller, (newVerticalPos + GetPointsToScroll(scroller)), Orientation.Vertical); isKeyHandled = true; } else if (keyPressed == Key.PageDown) { newVerticalPos = NormalizeScrollPos(scroller, (newVerticalPos + scroller.ViewportHeight), Orientation.Vertical); isKeyHandled = true; } else if (keyPressed == Key.Up) { newVerticalPos = NormalizeScrollPos(scroller, (newVerticalPos - GetPointsToScroll(scroller)), Orientation.Vertical); isKeyHandled = true; } else if (keyPressed == Key.PageUp) { newVerticalPos = NormalizeScrollPos(scroller, (newVerticalPos - scroller.ViewportHeight), Orientation.Vertical); isKeyHandled = true; } if (newVerticalPos != GetVerticalOffset(scroller)) { AnimateScroll(scroller, newVerticalPos); } e.Handled = isKeyHandled; } #endregion #region ListBox Event Handlers private static void ListBoxLayoutUpdated(object sender, EventArgs e) { UpdateScrollPosition(sender); } private static void ListBoxLoaded(object sender, RoutedEventArgs e) { UpdateScrollPosition(sender); } private static void ListBoxSelectionChanged(object sender, SelectionChangedEventArgs e) { UpdateScrollPosition(sender); } #endregion } </code></pre>
22,138,475
How to implement the same interface multiple times, but with different generics?
<p>I have the following interface, which I want to implement multiple times in my classes:</p> <pre><code>public interface EventListener&lt;T extends Event&gt; { public void onEvent(T event); } </code></pre> <p>Now, I want to be able to implement this interface in the following way:</p> <pre><code>class Foo implements EventListener&lt;LoginEvent&gt;, EventListener&lt;LogoutEvent&gt; { @Override public void onEvent(LoginEvent event) { } @Override public void onEvent(LogoutEvent event) { } } </code></pre> <p>However, this gives me the error: <code>Duplicate class com.foo.EventListener</code> on the line:</p> <pre><code>class Foo implements EventListener&lt;LoginEvent&gt;, EventListener&lt;LogoutEvent&gt; </code></pre> <p>Is it possible to implement the interface twice with different generics? If not, what's the next closest thing I can do to achieve what I'm trying to do here?</p>
22,138,640
3
5
null
2014-03-03 04:04:35.497 UTC
8
2020-02-19 10:55:30.55 UTC
null
null
null
null
49,153
null
1
44
java|generics|interface
20,537
<p>You need to use inner or anonymous classes. For instance:</p> <pre><code>class Foo { public EventListener&lt;X&gt; asXListener() { return new EventListener&lt;X&gt;() { // code here can refer to Foo }; } public EventListener&lt;Y&gt; asYListener() { return new EventListener&lt;Y&gt;() { // code here can refer to Foo }; } } </code></pre>
11,134,857
Using sendmail for HTML body and binary attachment
<p>Objective: To send mail (using sendmail) with HTML body and binary attachment.</p> <p>Followed the guidelines specified in the following links</p> <p><a href="http://www.unix.com/shell-programming-scripting/159522-sendmail-html-body-attachment-2.html">http://www.unix.com/shell-programming-scripting/159522-sendmail-html-body-attachment-2.html</a></p> <p><a href="http://www.unix.com/shell-programming-scripting/58448-sendmail-attachment.html">http://www.unix.com/shell-programming-scripting/58448-sendmail-attachment.html</a></p> <p>It is working to the extent that, either HTML body or the binary attachment with uuencode, but not both.</p> <p>Given below is a snippet of the shell script to sendmail. With this, the HTML body is coming fine, but the attachment is getting encoded/decoded wrongly and unable to view the same.</p> <p>Please advise.</p> <pre><code>#!/usr/bin/ksh export MAILFROM="noreply@site.dom" export MAILTO="somebody@somesite.com" export SUBJECT="Test PDF for Email" export BODY="email_body.htm" export ATTACH="file.pdf" export MAILPART=`uuidgen` ## Generates Unique ID ( echo "From: $MAILFROM" echo "To: $MAILTO" echo "Subject: $SUBJECT" echo "MIME-Version: 1.0" echo "Content-Type: multipart/mixed; boundary=\"-$MAILPART\"" echo "---$MAILPART" echo "Content-Type: text/html" echo "Content-Disposition: inline" cat $BODY echo "---$MAILPART" echo 'Content-Type: application/pdf; name="'$(basename $ATTACH)'"' echo "Content-Transfer-Encoding: base64" echo 'Content-Disposition: attachment; filename="'$(basename $ATTACH)'"' uuencode -m $ATTACH $(basename $ATTACH) echo "---$MAILPART--" ) | /usr/sbin/sendmail $MAILTO </code></pre> <p>I am using HP-UX ia64. Have searched through the forum and web and found references mostly to PHP, Python, etc.</p>
11,725,308
2
3
null
2012-06-21 09:04:23.627 UTC
3
2021-01-15 09:23:02.97 UTC
null
null
null
null
1,471,464
null
1
10
shell|unix|sendmail|ksh|uuencode
40,910
<p>Changing the Content transfer encoding type within the email from base64 to uuencode resolved the issue. Thanks for the inputs so far.</p> <p>Given below is the revised script that works.</p> <pre><code>#!/usr/bin/ksh export MAILFROM="noreply@domain.com" export MAILTO="mail.to@gmail.com" export SUBJECT="Test PDF for Email" export BODY="email_body.htm" export ATTACH="file.pdf" export MAILPART=`uuidgen` ## Generates Unique ID export MAILPART_BODY=`uuidgen` ## Generates Unique ID ( echo "From: $MAILFROM" echo "To: $MAILTO" echo "Subject: $SUBJECT" echo "MIME-Version: 1.0" echo "Content-Type: multipart/mixed; boundary=\"$MAILPART\"" echo "" echo "--$MAILPART" echo "Content-Type: multipart/alternative; boundary=\"$MAILPART_BODY\"" echo "" echo "--$MAILPART_BODY" echo "Content-Type: text/plain; charset=ISO-8859-1" echo "You need to enable HTML option for email" echo "--$MAILPART_BODY" echo "Content-Type: text/html; charset=ISO-8859-1" echo "Content-Disposition: inline" cat $BODY echo "--$MAILPART_BODY--" echo "--$MAILPART" echo 'Content-Type: application/pdf; name="'$(basename $ATTACH)'"' echo "Content-Transfer-Encoding: uuencode" echo 'Content-Disposition: attachment; filename="'$(basename $ATTACH)'"' echo "" #uuencode -m $ATTACH $(basename $ATTACH) uuencode $ATTACH $(basename $ATTACH) echo "--$MAILPART--" ) &gt; email_`date '+%Y%m%d_%H%M%S'`.out | /usr/sbin/sendmail $MAILTO </code></pre>
11,220,776
deserialize list of objects using json.net
<p>i have this class</p> <pre><code>public class Image { public string url { get; set; } public string url_40px { get; set; } public string url_50px { get; set; } } public class Category { public List&lt;int&gt; ancestor_ids { get; set; } public int parent_id { get; set; } public List&lt;object&gt; children_ids { get; set; } public string nodename { get; set; } public int num_parts { get; set; } public List&lt;Image&gt; images { get; set; } public string __class__ { get; set; } public int id { get; set; } } </code></pre> <p>and i deserialize it like this</p> <pre><code>retObject = JsonConvert.DeserializeObject(Of Category)(jsonResp) </code></pre> <p>but for a list of category returned, how do i convert to <code>List&lt;Category&gt;</code>? thanks</p>
11,220,872
1
1
null
2012-06-27 06:47:05.437 UTC
1
2021-02-22 16:31:41.26 UTC
2012-11-13 21:39:58.7 UTC
null
11,829
null
362,461
null
1
11
.net|json|deserialization|json.net
39,056
<p>The type parameter for <code>DeserializeObject</code> has to be <code>List&lt;Category&gt;</code> instead of <code>Category</code>.</p> <p>In C# it would be <code>JsonConvert.DeserializeObject&lt;List&lt;Category&gt;&gt;(json)</code></p> <p>And In VB.Net it would be <code>JsonConvert.DeserializeObject(Of List(Of Category))(json)</code></p>
11,386,033
GNU Octave, round a number to units precision
<p>In GNU Octave version 3.4.3 I want to round a matrix to 2 units precision on the contents of a matrix like this.</p> <pre><code>mymatrix=[1.1234567, 2.12345; 3.1234567891, 4.1234]; disp(mymatrix); </code></pre> <p>This prints:</p> <pre><code>1.1235 2.1235 3.1235 4.1234 </code></pre> <p>As you can see, the disp forces the precision to '5', I want the units precision to be 2. How do I do this?</p>
11,386,211
3
0
null
2012-07-08 19:33:16.603 UTC
2
2021-01-04 20:33:41.307 UTC
null
null
null
null
445,131
null
1
17
linux|matrix|rounding|precision|octave
48,897
<h2>How to round off elements in a matrix in Octave:</h2> <p>There are many different ways to round a matrix and round a number in octave.</p> <h2>Option 1, use of sprintf format feature</h2> <pre><code>mymatrix=[100.1234567, 2.12345; 3.1234567891, 4.1234]; rows = rows(mymatrix); cols = columns(mymatrix); for i = 1:rows for j = 1:cols sprintf(&quot;%5.2f&quot;, mymatrix(j,i)) endfor endfor </code></pre> <p><strong>Output</strong>, note the &quot;%5.2f&quot; token. The 'f' means expect a float, the 5 means occupy 5 spaces. The 2 means 2 units precision after the decimal point.</p> <pre><code>ans = 100.12 ans = 3.12 ans = 2.12 ans = 4.12 </code></pre> <h2>Option 2, round to significant digits using eval and mat2str</h2> <pre><code>mymatrix2=[100.1234567, 2.12345; 3.1234567891, 4.1234]; j = mat2str(mymatrix2, 3); mymatrix2=eval(j) </code></pre> <p><strong>Output</strong>, matrix rounded to 3 significant digits, notice 100.123 rounded to 100 while the 2.12345 was rounded to 2.12</p> <pre><code>mymatrix2 = 100.0000 2.1200 3.1200 4.1200 </code></pre> <h2>Option 3, use the round function</h2> <p>The round function does not have a precision parameter in Octave. However you can hack around it by multiplying each item in the matrix by 100, rounding it to the nearest int, then dividing each item by 100:</p> <pre><code>mymatrix=[100.1234567, 2.12345; 3.1234567891, 4.1234]; round(mymatrix .* 100) ./ 100 </code></pre> <p><strong>Output</strong>, round occurs correctly:</p> <pre><code>ans = 100.1200 2.1200 3.1200 4.1200 </code></pre> <h2>Option 4, specify a output_precision(num)</h2> <p>You noticed that option 3 above kept the trailing zeros, which may be undesirable, so you can tell them to go away by setting output_precision:</p> <pre><code>mymatrix=[100.1234567, 2.12345; 3.1234567891, 4.1234]; disp(mymatrix); output_precision(3) disp(mymatrix) </code></pre> <p><strong>Output</strong>:</p> <pre><code>100.1235 2.1235 3.1235 4.1234 100.123 2.123 3.123 4.123 </code></pre> <p>Octave has some odd behavior when trying to do rounding because octave tries hard to uniformly apply a uniform rounding to all items in a matrix. So if you have multiple columns with wildly different values, octave sees a tiny value and says: &quot;I should convert that to an exponential like <code>1.0e-04</code>, and so the same exponential is applied to the entire data structure in the matrix.</p>
11,190,405
How to schedule a task wether the user is logged on or not in PowerShell?
<p>I have a problem regarding how to make a scheduled task to run whether the user is logged on or not. It must be done in PowerShell. What I have done is:</p> <pre><code>$WINDIR/system32/schtasks.exe /create /tn TaskName /sc daily /st 15:05:00 /tr &quot;C:\cygwin\opt\IBM\tpchc\bin\tools\TheFileToRun.bat&quot; </code></pre> <p>But can I provide an extra argument making this task run no matter if the user is logged on or off?</p> <p>If it cant be done in PowerShell is it then possible to do it in another script language?</p>
11,196,228
3
1
null
2012-06-25 13:37:55.997 UTC
4
2022-08-03 15:49:19.917 UTC
2022-08-03 15:49:19.917 UTC
null
2,756,409
null
1,093,774
null
1
21
powershell|shell|cmd
41,694
<p>You'll need to specify a user (like <code>/RU system</code>), but it should be the default whether to run logged in or not. You can look at <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx" rel="noreferrer">this link</a> for a list of all <code>schtasks.exe</code> parameters.</p>
10,968,522
Excluding fields in JAXB
<p>I have 2 classes:</p> <pre><code>@XmlRootElement public class A { private Long id; private B b; // setters and getters } </code></pre> <p>and</p> <pre><code>@XmlRootElement public class B { private Long id; private String field1; private String field2; // setters and getters } </code></pre> <p>By default, if I transform an instance of class <code>A</code> to the XML, I will have all its fields (<code>id</code>) and the referenced <code>B</code> class fields (<code>id</code>, <code>field1</code>, <code>field2</code>) like this:</p> <pre><code>&lt;a&gt; &lt;id&gt;2&lt;/id&gt; &lt;b&gt; &lt;id&gt;5&lt;/id&gt; &lt;field1&gt;test1&lt;/field1&gt; &lt;field2&gt;test3&lt;/field2&gt; &lt;/b&gt; &lt;/a&gt; </code></pre> <p>Is is possible to modify <strong>what</strong> fields from referenced class <code>B</code> are included in the XML of the <code>A</code> class? E.g. I want to say that when I transform an instance of <code>A</code> class, I just want to get <code>id</code> from the <code>B</code> class (no <code>field1</code> and <code>field2</code> fields), so I want to get:</p> <pre><code>&lt;a&gt; &lt;id&gt;2&lt;/id&gt; &lt;b&gt; &lt;id&gt;5&lt;/id&gt; &lt;/b&gt; &lt;/a&gt; </code></pre> <p>I don't want to permanently annotate the <code>B</code> class (using <code>@XMLTransient</code> or <code>@XMLElement</code>) to achieve it, as there are cases in which I want to export whole <code>B</code> class as is (with <code>id</code>, <code>field1</code> and <code>field2</code>.)<br> I just don't want to export all these fields when the <code>B</code> class is referenced from <code>A</code>.</p> <p>Is this even possible with JAX-B?</p>
10,969,031
3
0
null
2012-06-10 12:05:09.167 UTC
7
2019-08-20 07:29:36.12 UTC
2015-08-28 12:40:01.18 UTC
null
1,743,880
null
920,607
null
1
47
java|xml|jaxb|java-ee-6
67,467
<p>You can use <a href="https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/XmlTransient.html" rel="noreferrer"><code>@XmlTransient</code></a> on the field. Also the default JAXB bindings can be overridden at a global scope or on a case-by-case basis as needed by using <a href="http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/2.0/tutorial/doc/JAXBUsing4.html" rel="noreferrer">custom binding declarations</a>.</p> <p>Check out the <a href="http://www.baeldung.com/jaxb" rel="noreferrer">Guide to JAXB</a> from Baeldung website for more examples.</p>
11,079,605
adapter-Any real example of Adapter Pattern
<p>I want to demonstrate use of <a href="https://en.wikipedia.org/wiki/Adapter_pattern" rel="noreferrer">Adapter Pattern</a> to my team. I've read many books and articles online. Everyone is citing an example which are useful to understand the concept (Shape, Memory Card, Electronic Adapter etc.), but there is no real case study.</p> <p>Can you please share any case study of Adapter Pattern?</p> <p>p.s. I tried searching existing questions on stackoverflow, but did not find the answer so posting it as a new question. If you know there's already an answer for this, then please redirect.</p>
13,323,703
15
8
null
2012-06-18 08:55:29.033 UTC
43
2021-02-09 18:34:43.473 UTC
2016-02-10 13:29:34.22 UTC
null
634,576
null
855,239
null
1
94
oop|design-patterns|adapter|software-design
66,636
<p>Many examples of Adapter are trivial or unrealistic (<a href="http://www.vincehuston.org/dp/adapter.html" rel="noreferrer">Rectangle vs. LegacyRectangle, Ratchet vs. Socket</a>, <a href="http://userpages.umbc.edu/~tarr/dp/lectures/Adapter-2pp.pdf" rel="noreferrer">SquarePeg vs RoundPeg</a>, <a href="http://my.safaribooksonline.com/book/software-engineering-and-development/patterns/0596007124/being-adaptive/hfdesignpat-chp-7-sect-3" rel="noreferrer">Duck vs. Turkey</a>). Worse, many don't show <strong>multiple Adapters for different Adaptees</strong> (<a href="https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns">someone cited Java's Arrays.asList as an example of the adapter pattern</a>). Adapting an interface of <em>only one class</em> to work with another seems a weak example of the GoF Adapter pattern. This pattern uses inheritance and polymorphism, so one would expect a good example to show <em>multiple implementations of adapters for different adaptees</em>. </p> <p>The <em>best example</em> I found is in Chapter 26 of <a href="https://rads.stackoverflow.com/amzn/click/com/0131489062" rel="noreferrer" rel="nofollow noreferrer">Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development (3rd Edition)</a>. The following images are from the instructor material provided on an FTP site for the book. </p> <p>The first one shows how an application can use multiple implementations (adaptees) that are functionally similar (e.g., tax calculators, accounting modules, credit authorization services, etc.) but have different APIs. We want to avoid hard-coding our domain-layer code to handle the different possible ways to calculate tax, post sales, authorize credit card requests, etc. Those are all external modules that might vary, and for which we can't modify the code. The adapter allows us to do the hard-coding in the adapter, whereas our domain-layer code always uses the same interface (the IWhateverAdapter interface).</p> <p><img src="https://i.stack.imgur.com/cqiSg.png" alt="Fig. 26.1"></p> <p>We don't see in the above figure the actual adaptees. However, the following figure shows how a polymorphic call to <code>postSale(...)</code> in the IAccountingAdapter interface is made, which results in a posting of the sale via SOAP to an SAP system. </p> <p><img src="https://i.stack.imgur.com/4u4N6.png" alt="Fig. 26.2"></p>
12,719,241
Alternatives to CKEditor for WSYIWYG text area editor
<p>Me and my company are looking for an alternative to CKEditor to use in our CMS. Preferably we would like something a bit more up to date and significantly more lightweight.</p> <p>We're a rails 3.2 shop, so something that integrates easily with rails would be nice.</p> <p>Really we are just looking for the formatting features, and possibly image uploading (though we have an api, so this might be difficult) via integration with paperclip.</p> <p>So far we've seen</p> <ul> <li>CKEditor</li> <li>TinyMCE</li> <li>Markdown</li> </ul> <p>Does anyone have any suggestions or thoughts?</p> <p>Thanks!</p>
12,719,274
4
4
null
2012-10-04 01:39:41.86 UTC
11
2014-12-09 18:55:20.993 UTC
null
null
null
null
117,554
null
1
32
javascript|jquery|ruby-on-rails|ruby-on-rails-3|wysiwyg
49,200
<p>I just found: </p> <p><a href="http://redactorjs.com/" rel="noreferrer">http://redactorjs.com/</a></p> <p><a href="http://aloha-editor.org/" rel="noreferrer">http://aloha-editor.org/</a></p> <p><a href="https://github.com/xing/wysihtml5" rel="noreferrer">https://github.com/xing/wysihtml5</a></p> <p><a href="http://jhollingworth.github.com/bootstrap-wysihtml5/" rel="noreferrer">http://jhollingworth.github.com/bootstrap-wysihtml5/</a></p> <p>Update (this one is pretty great and customizable): <a href="https://github.com/guardian/scribe" rel="noreferrer">https://github.com/guardian/scribe</a></p>
12,768,176
Unicode Characters in ggplot2 PDF Output
<p>How can I use Unicode characters for labels, titles and similar things in a PDF plot created with ggplot2?</p> <p>Consider the following example:</p> <pre><code>library(ggplot2) qplot(Sepal.Length, Petal.Length, data=iris, main="Aʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ") ggsave("t.pdf") </code></pre> <p>The title of the plot uses Unicode characters (small caps), which in the output appear as <code>...</code>. The problem occurs only with pdf plots; if I replace the last line with <code>ggsave("t.png")</code>, then the output is as expected.</p> <p>What am I doing wrong? The R script I have is in UTF-8 encoding. Some system information:</p> <pre><code>R version 2.14.1 (2011-12-22) Platform: x86_64-pc-linux-gnu (64-bit) locale: [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 [7] LC_PAPER=C LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C attached base packages: [1] stats graphics grDevices utils datasets methods base </code></pre> <p>When searching for a solution for this problem, I found some <a href="http://cran.r-project.org/doc/Rnews/Rnews_2006-2.pdf" rel="noreferrer">evidence</a> that R uses a single-byte encoding for mutli-byte encodigns such as UTF-8 for PDF or postscript output. I also found suggestions to, for instance, be able to get the <a href="https://stackoverflow.com/questions/6706226/plotting-euro-symbol-in-ggplot2">Euro sign working</a>, but no general solution.</p>
12,775,087
3
1
null
2012-10-07 10:55:24.12 UTC
10
2020-10-21 23:15:43.55 UTC
2017-05-23 12:02:11.54 UTC
null
-1
null
1,685,720
null
1
34
r|unicode|utf-8|ggplot2
15,395
<p>As Ben suggested, <code>cairo_pdf()</code> is your friend. It also allows you to embed non-postscript fonts (i.e. TTF/OTF) in the PDF via the <code>family</code> argument (crucial if you don't happen to have any postscript fonts that contain the glyphs you want to use). For example:</p> <pre><code>library(ggplot2) cairo_pdf("example.pdf", family="DejaVu Sans") qplot(Sepal.Length, Petal.Length, data=iris, main="Aʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ") dev.off() </code></pre> <p>...gives a PDF that looks like this: <img src="https://i.stack.imgur.com/zvbKB.png" alt="ggplot2 graph with custom font family and non-ASCII characters in the title"></p> <p>See also <a href="https://stackoverflow.com/questions/12378620/ttf-otf-font-selection-in-r-for-windows-onscreen-vs-pdf">this question</a>; though it doesn't look directly relevant from the title, there is a lot in there about getting fonts to do what you want in R.</p> <p><strong>EDIT</strong> per request in comments, here is the windows-specific code:</p> <pre><code>library(ggplot2) windowsFonts(myCustomWindowsFontName=windowsFont("DejaVu Sans")) cairo_pdf("example.pdf", family="myCustomWindowsFontName") qplot(Sepal.Length, Petal.Length, data=iris, main="Aʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ") dev.off() </code></pre> <p>To use the base graphics command <code>cairo_pdf()</code> it should suffice to just define your font family with the <code>windowsFonts()</code> command first, as shown above. Of course, make sure you use a font that you actually have on your system, and that actually has all the glyphs that you need.</p> <p>TThe instructions about DLL files in the comments below are what I had to do to get the <code>Cairo()</code> and <code>CairoPDF()</code> commands in <code>library(Cairo)</code> to work on Windows. Then:</p> <pre><code>library(ggplot2) library(Cairo) windowsFonts(myCustomWindowsFontName=windowsFont("DejaVu Sans")) CairoPDF("example.pdf") par(family="myCustomWindowsFontName") qplot(Sepal.Length, Petal.Length, data=iris, main="Aʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ") dev.off() </code></pre>
16,878,279
overflow:hidden ignored with border-radius and CSS transforms (webkit only)
<p>I want to have a square image inside a circle.</p> <p>When the user hovers over the image, the image should scale (zoom in).</p> <p>The circle should remain the same size.</p> <p>Only during the CSS transition, the square image overlaps the circle (as if overflow:hidden weren't there at all).</p> <p>Here's a demo with the weird behavior in Chrome and Safari: <a href="http://codepen.io/jshawl/full/flbau">http://codepen.io/jshawl/full/flbau</a></p> <p>Working ok in firefox.</p>
16,878,347
4
0
null
2013-06-01 23:28:06.783 UTC
12
2017-05-17 06:27:05.277 UTC
2013-06-01 23:55:04.143 UTC
null
850,825
null
850,825
null
1
21
css|css-transitions|css-transforms
15,542
<p>I removed some superfluous markup (the circle and square containers... only needs one) and styled the img itself:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper { width: 500px; height: 500px; border-radius: 50%; overflow: hidden; -webkit-mask-image: -webkit-radial-gradient(circle, white, black); } #test { width: 100%; height: 100%; transition: all 2s linear; } #test:hover { transform: scale(1.2); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="wrapper"&gt; &lt;img src="http://rack.3.mshcdn.com/media/ZgkyMDEzLzA1LzA4L2JlL2JhYmllc193aXRoLjA5NGNjLnBuZwpwCXRodW1iCTg1MHg1OTA-CmUJanBn/8f195417/e44/babies_with_swagg.jpg" id="test"&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
17,117,589
How can I skip tests in maven install goal, while running them in maven test goal?
<p>I have a multi-module maven project with both integration and unit tests in the same folder (src/test/java). Integration tests are marked with <code>@Category(IntegrationTest.class)</code>. I want to end up with the following setup:</p> <ol> <li>If I run <code>mvn install</code>, I want all tests to compile, but I do not want to execute any.</li> <li>If I run <code>mvn test</code>, I want all tests to compile, but execute only unit tests.</li> <li>If I run <code>mvn integration-test</code>, I want to compile and execute all tests.</li> </ol> <p><strong>The important point is, I want this configured in the <code>pom.xml</code> without any extra commandline arguments.</strong></p> <p>Currently I came up with the following setup in my parent pom.xml, where the only problem is #1, where all tests are executed:</p> <pre><code>&lt;build&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;source&gt;${project.java.version}&lt;/source&gt; &lt;target&gt;${project.java.version}&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.14.1&lt;/version&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.maven.surefire&lt;/groupId&gt; &lt;artifactId&gt;surefire-junit47&lt;/artifactId&gt; &lt;version&gt;2.14.1&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;configuration&gt; &lt;includes&gt; &lt;include&gt;**/*.class&lt;/include&gt; &lt;/includes&gt; &lt;excludedGroups&gt;cz.cuni.xrg.intlib.commons.IntegrationTest&lt;/excludedGroups&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt; &lt;version&gt;2.14.1&lt;/version&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.maven.surefire&lt;/groupId&gt; &lt;artifactId&gt;surefire-junit47&lt;/artifactId&gt; &lt;version&gt;2.14.1&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;configuration&gt; &lt;groups&gt;cz.cuni.xrg.intlib.commons.IntegrationTest&lt;/groups&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;integration-test&lt;/goal&gt; &lt;goal&gt;verify&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;includes&gt; &lt;include&gt;**/*.class&lt;/include&gt; &lt;/includes&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; </code></pre> <p>All child modules have the following plugin configuration in their pom.xml, which I believe should inherit from the parent pom:</p> <pre><code>&lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p>I tried using <code>&lt;skipTests&gt;true&lt;/skipTests&gt;</code>, but it disables test execution for all goals, which is not what I want (violates #2 and #3). It is also quite weird, that <code>mvn test</code> honors the <code>skipTests=true</code> option...why would I want to run it in the first place??</p> <p>After hours of googling and trying different combinations, I am hesitant whether it is even possible to not run tests in <code>mvn install</code>, while at the same time run them in <code>mvn test</code>. I hope someone proves this wrong. ;)</p> <p>I am also willing to accept a solution, where <code>mvn install</code> would execute only unit tests, but I don't think it makes much difference.</p>
17,123,957
7
2
null
2013-06-14 21:31:29.2 UTC
43
2019-05-01 17:41:35.27 UTC
2013-06-15 07:51:11.453 UTC
null
1,204,246
null
1,204,246
null
1
69
maven|integration-testing|maven-surefire-plugin|maven-failsafe-plugin
92,512
<p>It sounds like you didn't understand the concept of the <a href="http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html" rel="noreferrer">build life-cycle</a> in Maven. If you run <code>mvn install</code> all life-cycle phases (including the <code>install</code> phase itself) run before the install phase. This means running the following phases:</p> <ol> <li>validate</li> <li>initialize</li> <li>generate-sources</li> <li>process-sources</li> <li>generate-resources</li> <li>process-resources</li> <li>compile</li> <li>process-classes</li> <li>generate-test-sources</li> <li>process-test-sources</li> <li>generate-test-resources</li> <li>process-test-resources</li> <li>test-compile</li> <li>process-test-classes</li> <li>test</li> <li>prepare-package</li> <li>package</li> <li>pre-integration-test</li> <li>integration-test</li> <li>post-integration-test</li> <li>verify</li> <li>install</li> </ol> <p>which means in other words the <code>test</code> as well as <code>integration-test</code> life-cycle phases are included. So without any supplemental information it's not possible to change the behaviour as you wish it. </p> <p>It could be achieved by using a profile in Maven:</p> <pre><code> &lt;project&gt; [...] &lt;profiles&gt; &lt;profile&gt; &lt;id&gt;no-unit-tests&lt;/id&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;skipTests&gt;true&lt;/skipTests&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/profile&gt; &lt;/profiles&gt; [...] &lt;/project&gt; </code></pre> <p>So your first requirement:</p> <ol> <li>If I run <code>mvn install</code>, I want all tests to compile, but I do not want to execute any.</li> </ol> <p>can be achieved by using the following:</p> <pre><code>mvn -Pno-unit-test test </code></pre> <ol start="2"> <li>If I run <code>mvn test</code>, I want all tests to compile, but execute only unit tests.</li> </ol> <p>This can simply achieved by using the plain call:</p> <pre><code>mvn test </code></pre> <p>cause the integration tests phase is not run (see the build life cycle).</p> <ol start="3"> <li>If I run <code>mvn integration-test</code>, I want to compile and execute all tests.</li> </ol> <p>This means running the default which includes running the <code>test</code> phase which will run the unit tests (maven-surefire-plugin) and furthermore running the integration test which are handled by the maven-failsafe-plugin. But you should be aware that if you like to call the integration tests you should using the following command:</p> <pre><code>mvn verify </code></pre> <p>instead, cause you missed the <code>post-integration-test</code> phase in your previous call.</p> <p>Apart from the above you should follow the naming conventions for unit and integration tests where <a href="http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html" rel="noreferrer">unit tests</a> should be named like the following:</p> <pre><code>&lt;includes&gt; &lt;include&gt;**/*Test*.java&lt;/include&gt; &lt;include&gt;**/*Test.java&lt;/include&gt; &lt;include&gt;**/*TestCase.java&lt;/include&gt; &lt;/includes&gt; </code></pre> <p>and <a href="http://maven.apache.org/surefire/maven-failsafe-plugin/integration-test-mojo.html#includes" rel="noreferrer">integration tests</a> should be named like the following:</p> <pre><code>&lt;includes&gt; &lt;include&gt;**/IT*.java&lt;/include&gt; &lt;include&gt;**/*IT.java&lt;/include&gt; &lt;include&gt;**/*ITCase.java&lt;/include&gt; &lt;/includes&gt; </code></pre> <p>I hope you have configured the maven-failsafe-plugin like the following which is needed to bound the maven-failsafe-plugin to the correct life-cycle-phases:</p> <pre><code>&lt;project&gt; [...] &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt; &lt;version&gt;2.15&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;integration-test&lt;/goal&gt; &lt;goal&gt;verify&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; [...] &lt;/project&gt; </code></pre> <p>as you correctly did, but you should be aware that the <code>include</code> tags work on the source code (<em>.java) and not on the compiled names (</em>.class). I wouldn't use the Category annotation, just simply using the naming conventions makes the pom simpler and shorter.</p>
10,198,046
C++ Member Variables
<p>Consider the following class:</p> <pre><code>class A { A(); int number; void setNumber(int number); }; </code></pre> <p>You could implement 'setNumber' in 3 ways:</p> <p><strong>Method 1</strong>: Use the 'this' pointer.</p> <pre><code>void A::setNumber(int number) { this-&gt;number = number; } </code></pre> <p><strong>Method 2</strong>: Use the scope resolution operator.</p> <pre><code>void A::setNumber(int number) { A::number = number; } </code></pre> <p><strong>Method 3</strong>: Instead, denote all member variables with 'm' or '_' (this is my preferred method).</p> <pre><code>void A::setNumber(int number) { mNumber = number; } </code></pre> <p>Is this just personal preference, or is there a benefit to choosing a particular method?</p>
10,198,598
6
4
null
2012-04-17 19:44:35.753 UTC
5
2018-01-31 05:35:00.677 UTC
2015-05-07 18:50:30.89 UTC
null
445,131
null
1,339,615
null
1
21
c++|class|variables|scope|member
51,179
<p>This is mostly a personal preference, but let me share my perspective on the issue from inside a company where many small games are being made simultaneously (and so there are many coding styles being used around me).</p> <p>This link has several good, related, answers: <a href="https://stackoverflow.com/questions/1228161/why-use-prefixes-on-member-variables-in-c-classes">Why use prefixes on member variables in C++ classes</a></p> <p>Your option 1:</p> <pre><code>void A::setNumber(int number) { this-&gt;number = number; } </code></pre> <blockquote> <p>First off, many programmers tend to find this cumbersome, to continually type out the ' this-> '. Second, and more importantly, if any of your variables shares a name with a parameter or a local variable, a find-replace designed to say, change the name of 'number' might affect the member variables located in the find-replace scope as well.</p> </blockquote> <p>Your option 2:</p> <pre><code>void A::setNumber(int number) { A::number = number; } </code></pre> <blockquote> <p>The problem I've run into with this, is that in large classes, or classes with large functions (where you cannot see the function or the class is named unexpectedly), the formatting of A::(thing) looks very much like accessing a part of a namespace, and so can be misleading. The other issue is the same as #2 from the previous option, if your names are similar to any variables you're using there can be unexpected confusion sometimes.</p> </blockquote> <p>Your option 3:</p> <pre><code>void A::setNumber(int number) { mNumber = number; } </code></pre> <blockquote> <p>This is the best of those three presented options. By creating (and holding to!) a syntax that involves a clear and meaningful prefix, you not only create a unique name that a local (or global) variable won't share, but you make it immediately clear where that variable is declared, regardless of the context you find it in. I've seen it done both like this ' mVariable ' and like this 'm_variable' and it mostly depends upon if you prefer underscores to uppercase concatenation. In addition, if your style tends to add things like ' p 's on for pointers, or ' g 's on for globals, this style will mesh well and be expected by readers.</p> </blockquote>
9,698,059
Disable single javascript file with addon or extension
<p>I am looking for a Firefox addon or Chrome extension that would allow me to disable particular javascript file from running. There are many of those for disabling particular CSS file, cannot seem to find one that does the same with JS files. Is there some limitations or I should have searched better before posting?</p>
9,699,252
3
0
null
2012-03-14 08:14:47.69 UTC
12
2015-12-28 14:15:32.647 UTC
null
null
null
null
136,055
null
1
27
firefox|google-chrome|google-chrome-extension|firefox-addon
36,557
<p>AdBlock for Chrome can be used to block JS files.....<br> <a href="https://chrome.google.com/webstore/detail/gighmmpiobklfepjocnamgkkbiglidom" rel="noreferrer">https://chrome.google.com/webstore/detail/gighmmpiobklfepjocnamgkkbiglidom</a><br> ...Click on the AdBlock icon and select "Show the resource list" and look for the JS you want to block and tick the box next to it and make your selections.<br> <strong>Note</strong><br> In settings, "I'm an advanced user, show me advanced options." should be selected.</p>
9,760,662
Is there a constant which defines the max value of long or integer?
<p>In java, there is a constant for the max value of Long. Such as:</p> <pre><code>long minBillId = Long.MAX_VALUE </code></pre> <p>Is there a constant for the max value of long or int in Obj-C?</p>
9,760,691
3
0
null
2012-03-18 17:49:03.16 UTC
11
2012-12-24 13:21:37.503 UTC
2012-12-24 13:21:37.503 UTC
null
775,184
null
1,053,236
null
1
32
iphone|objective-c|ios|c|ipad
25,173
<p>If you import <code>limits.h</code> you can call <code>LONG_MAX</code></p> <p>For reference this <a href="http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html" rel="noreferrer">site</a> shows how to get the max for all types as such:</p> <pre><code>#import &lt;limits.h&gt; // ... NSLog(@"CHAR_MIN: %c", CHAR_MIN); NSLog(@"CHAR_MAX: %c", CHAR_MAX); NSLog(@"SHRT_MIN: %hi", SHRT_MIN); // signed short int NSLog(@"SHRT_MAX: %hi", SHRT_MAX); NSLog(@"INT_MIN: %i", INT_MIN); NSLog(@"INT_MAX: %i", INT_MAX); NSLog(@"LONG_MIN: %li", LONG_MIN); // signed long int NSLog(@"LONG_MAX: %li", LONG_MAX); NSLog(@"ULONG_MIN not defined, it's always zero: %lu", 0); NSLog(@"ULONG_MAX: %lu", ULONG_MAX); // unsigned long int NSLog(@"LLONG_MIN: %lli", LLONG_MIN); // signed long long int NSLog(@"LLONG_MAX: %lli", LLONG_MAX); NSLog(@"ULLONG_MIN not defined, it's always zero: %llu", 0); NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX); // unsigned long long int </code></pre>
10,014,165
Sublime Text 2 Code Formatting
<p>First let me say I come from a Microsoft background and Visual Studio is my bread and butter. It has a command (keybind is arbitrary) that auto-formats <em>any</em> code syntax. The same command works in HTML, CSS, Javascript, C#, etc. </p> <p>I have tried plugins for ST2 and so far I've found most don't work on a Windows box and if they do, it's for a very specific purpose like just Javascript.</p> <p>I have tried (and opened Issues where appropriate):</p> <p><a href="https://github.com/victorporof/Sublime-HTMLPrettify" rel="noreferrer">https://github.com/victorporof/Sublime-HTMLPrettify</a></p> <p><a href="https://github.com/jdc0589/JsFormat" rel="noreferrer">https://github.com/jdc0589/JsFormat</a> (this one actually works)</p> <p><a href="https://github.com/welovewordpress/SublimeHtmlTidy" rel="noreferrer">https://github.com/welovewordpress/SublimeHtmlTidy</a></p> <p>Have any Windows users of ST2 found anything that works to format CSS/HTML/Javascript, preferably in one shot?</p> <p><strong>Edit:</strong> Since this question is getting lots of views with no activity, I'll say that I <em>am</em> still looking for a plugin that can format various script types within the same command.</p> <p><strong>October 2013</strong> Still haven't found anything that covers JS+CSS+HTML well however I have settled on <a href="https://github.com/jdc0589/JsFormat" rel="noreferrer">JsFormat</a> as by far the most effective and bug free with the least amount of configuration for just JavaScript. </p>
10,299,234
4
0
null
2012-04-04 15:20:49.963 UTC
25
2017-08-01 18:44:53.757 UTC
2013-10-30 23:08:23.3 UTC
null
803,739
null
803,739
null
1
54
sublimetext|prettify|sublimetext2
123,366
<p>I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.) </p> <p>There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the HTMLPrettify.py file - <a href="https://github.com/victorporof/Sublime-HTMLPrettify/issues/12" rel="noreferrer">https://github.com/victorporof/Sublime-HTMLPrettify/issues/12</a></p>
10,236,953
The Pause monad
<p>Monads can do many amazing, crazy things. They can create variables which hold a superposition of values. They can allow you to access data from the future before you compute it. They can allow you to write destructive updates, but not really. And then the continuation monad allows you to <em>break people's minds!</em> Ususally your own. ;-)</p> <p>But here's a challenge: Can you make a monad which can be <em>paused</em>?</p> <pre> data Pause s x instance Monad (Pause s) mutate :: (s -> s) -> Pause s () yield :: Pause s () step :: s -> Pause s () -> (s, Maybe (Pause s ())) </pre> <p>The <code>Pause</code> monad is a kind of state monad (hence <code>mutate</code>, with the obvious semantics). Normally a monad like this has some sort of "run" function, which runs the computation and hands you back the final state. But <code>Pause</code> is different: It provides a <code>step</code> function, which runs the computation until it calls the magical <code>yield</code> function. Here the computation is paused, returning to the caller enough information to resume the computation later.</p> <p>For extra awesomness: Allow the caller to modify the state between <code>step</code> calls. (The type signatures above ought to allow this, for example.)</p> <hr/> <p>Use case: It's often easy to write code that does something complex, but a total PITA to transform it to also <em>output</em> the intermediate states in its operation. If you want the user to be able to <em>change</em> something mid-way through execution, things get complex really fast.</p> <p>Implementation ideas:</p> <ul> <li><p><em>Obviously</em> it can be done with threads, locks and <code>IO</code>. But can we do better? ;-)</p></li> <li><p>Something insane with a continuation monad?</p></li> <li><p>Maybe some kind of writer monad, where <code>yield</code> just logs the current state, and then we can "pretend" to <code>step</code> it by iterating over the states in the log. (Obviously this precludes altering the state between steps, since we're not really "pausing" anything now.)</p></li> </ul>
10,237,311
6
6
null
2012-04-19 21:20:14.683 UTC
48
2015-03-05 09:40:51.653 UTC
2015-03-05 09:40:51.653 UTC
null
412,549
null
1,006,010
null
1
72
haskell|monads|coroutine|monad-transformers|free-monad
6,174
<p>Sure; you just let any computation either finish with a result, or suspend itself, giving an action to be used on resume, along with the state at the time:</p> <pre><code>data Pause s a = Pause { runPause :: s -&gt; (PauseResult s a, s) } data PauseResult s a = Done a | Suspend (Pause s a) instance Monad (Pause s) where return a = Pause (\s -&gt; (Done a, s)) m &gt;&gt;= k = Pause $ \s -&gt; case runPause m s of (Done a, s') -&gt; runPause (k a) s' (Suspend m', s') -&gt; (Suspend (m' &gt;&gt;= k), s') get :: Pause s s get = Pause (\s -&gt; (Done s, s)) put :: s -&gt; Pause s () put s = Pause (\_ -&gt; (Done (), s)) yield :: Pause s () yield = Pause (\s -&gt; (Suspend (return ()), s)) step :: Pause s () -&gt; s -&gt; (Maybe (Pause s ()), s) step m s = case runPause m s of (Done _, s') -&gt; (Nothing, s') (Suspend m', s') -&gt; (Just m', s') </code></pre> <p>The <code>Monad</code> instance just sequences things in the normal way, passing the final result to the <code>k</code> continuation, or adding the rest of the computation to be done on suspension.</p>
7,983,076
Is it safe to use anchor to submit form?
<p>I've read somewhere, that using anchor tag to submit a form isn't very safe, so that's my question: Is it safe, to use anchor tag instead of <code>&lt;button&gt;</code> or <code>&lt;input type="submit" /&gt;</code> to submit a form? And if it isn't, <strong>why</strong>? The problem is, that I have a CSS class for a button, that shows what I want on <code>&lt;a class="button"&gt;</code>, but if I add it to an actual button it adds a weird border that I don't want.</p> <p>Thanks</p>
7,983,093
3
2
null
2011-11-02 15:37:28.027 UTC
10
2018-05-27 14:08:18.99 UTC
null
null
null
null
954,930
null
1
42
html|forms|button|anchor
81,783
<p>To use an anchor to submit a form would require the use of JavaScript to hook up the events. It's not safe in that if a user has JavaScript disabled, you won't be able to submit the form. For example:</p> <pre><code>&lt;form id="form1" action="" method="post"&gt; &lt;a href="#" onclick="document.getElementById('form1').submit();"&gt;Submit!&lt;/a&gt; &lt;/form&gt; </code></pre> <p>If you'd like you can use a <code>&lt;button&gt;</code>:</p> <pre><code>&lt;button type="submit"&gt;Submit!&lt;/button&gt; </code></pre> <p>Or stick with what we all know:</p> <pre><code>&lt;input type="submit" value="Submit!" /&gt; </code></pre> <p>You can style all three of them, but the latter two don't require JavaScript. You probably just need to change some CSS somewhere if you're having border issues.</p>
11,562,617
Installing Zend Framework 2 on XAMPP in Windows
<p>I know this question may have appeared few times here and in the internet. But still I feel it is not clear for somebody who wanted to enter into the world of frameworks. I have followed these links <a href="http://akrabat.com/zend-framework-2-tutorial/">Rob Allens Tutorial</a>, <a href="http://packages.zendframework.com/docs/latest/manual/en/zend.mvc.quick-start.html">ZF Quick Tutorial</a>.</p> <p>But some how I feel it is not quite clear with the installation part. I have a windows system basically Vista with the newest version of XAMPP installed. I have downloaded the latest version of ZFSkeletonApplication from this link <a href="https://github.com/zendframework/ZendSkeletonApplication/zipball/master">ZFSkeletonApp</a>, extracted the skeleton contents, renamed the folder to zendframework and moved it to xampp folder i.e now ZF skeleton is in c:\xampp\zendframework.</p> <p>So until here everything seems clear and easy, from here I am some how lost with the configurations. Can some one elaborate the things from here how to install the Zf and make it work, like changes in the include paths, .htaccess files and so on. Please do remember that I have windows with XAMPP on it. If some one can guide me exactly for this set up, it would be helpful.</p> <p>P.S. It would be good if one can provide info about the changes which I need to make with examples consisting of paths, so that I am not lost, for example like you can find .htaccess file here(ex pathname), changes in .htaccess file should be so and so.</p> <p>Thanks </p>
11,573,278
4
0
null
2012-07-19 14:05:42.643 UTC
13
2015-12-25 06:12:30.707 UTC
null
null
null
null
809,901
null
1
21
windows|xampp|zend-framework2
44,661
<p>For future references, i also made a big post on how to install ZF2 on a windows xampp environment right here <a href="http://samminds.com/2012/07/zend-framework-2-installation-on-xampp-for-windows/" rel="noreferrer" title="Install Zend Framework 2 on Windows Xampp">Install ZF2 on Windows Xampp</a></p> <p>OK, i have done this on multiple systems now. For a home system the following steps work quite well:</p> <ul> <li>Download <a href="http://msysgit.github.com/" rel="noreferrer">msysGit</a> and install it to any directory</li> <li>Run the git-cmd.bat from the msysGit-Folder</li> <li>Move into the directory you want i.e. <code>C:\xampp\htdocs\</code> (this is done via <code>cd dirname</code> or <code>cd ..</code> to go up a level, change partition with <code>D:</code> and hit enter)</li> </ul> <p>Run the following command. The <code>&lt;OptionalFolderName&gt;</code> would be the name of a Sub-Directory of <code>htdocs</code>, if you skip this, the folder will get named <code>ZendSkeletonApplication</code></p> <pre><code>git clone git://github.com/zendframework/ZendSkeletonApplication.git &lt;OptionalFolderName&gt; </code></pre> <p><strong>Possible Trouble Scenario</strong> (<em>fatal:unable to connect to github.com</em>)</p> <p>Once again at workplaces, pretty often the default port (9418) for the git-protocol is blocked. If this is the case for you, then you should try one of the following Commands</p> <pre><code>git clone https://github.com/zendframework/ZendSkeletonApplication.git &lt;OptionalFolderName&gt; git clone git@github.com:zendframework/ZendSkeletonApplication.git &lt;OptionalFolderName&gt; </code></pre> <p>Now you are not done yet. The skeleton Application is installed, but the framework is still missing, here some people might run into the first problems, but this actually is quite easy.</p> <p>We're still at the command line interface</p> <ul> <li><code>cd &lt;OptionalFolderName&gt;</code> or <code>cd ZendSkeletonApplication</code> depending on what you did earlier</li> <li><code>php composer.phar self-update</code></li> <li><code>php composer.phar install</code> (this might take a while)</li> </ul> <p>So, this is the part where lots of things can happen. I have two scenarios happened to me:</p> <p><strong>Scenario #1</strong> No directory write permissions</p> <p>This is easily handled by running the command line interface with administrator privileges</p> <p><strong>Scenario #2</strong> Working behind a router (i.e. at work)</p> <p>Personally i didn't have to do much to get this working, but the line might change depending on your proxy. Personally i did the following at the command line interface</p> <ul> <li><code>SET HTTP_PROXY=http://proxy.domain.tld:8080</code> you might also be good with</li> <li><code>SET HTTP_PROXY=proxy.domain.tld:8080</code> don't ask me why, but i needed the http://</li> </ul> <p>With all those done, you should have an almost running ZendSkeletonApplication. The other part is how to set up your virtual host, but i won't go into detail on this, as that's even ZF1 Stuff and everyone should be familiar with that by now, if not, there's <a href="http://framework.zend.com/manual/de/learning.quickstart.create-project.html#learning.quickstart.create-project.vhost" rel="noreferrer">good resources to learn</a> out there.</p> <p>I hope i could be of help to you.</p>
11,801,200
What is mass-assignment in Rails 3
<p>I have heard couple of people complaining and posting questions about mass-assignment in Rails. I have got same error couple of times and all I did was <code>attr_accessible</code>. But what exactly is mass assignment? could somebody explain with example?</p>
11,801,261
1
2
null
2012-08-03 18:20:33.29 UTC
13
2012-08-03 18:38:09.63 UTC
null
null
null
null
1,033,503
null
1
23
ruby-on-rails-3|activerecord|mass-assignment
11,835
<p><a href="http://guides.rubyonrails.org/security.html#mass-assignment">Mass Assignment</a> is the name Rails gives to the act of constructing your object with a parameters hash. It is "mass assignment" in that you are assigning multiple values to attributes via a single assignment operator.</p> <p>The following snippets perform mass assignment of the <code>name</code> and <code>topic</code> attribute of the <code>Post</code> model:</p> <pre><code>Post.new(:name =&gt; "John", :topic =&gt; "Something") Post.create(:name =&gt; "John", :topic =&gt; "Something") Post.update_attributes(:name =&gt; "John", :topic =&gt; "Something") </code></pre> <p>In order for this to work, your model must allow mass assignments for each attribute in the hash you're passing in.</p> <p>There are two situations in which this will fail:</p> <ul> <li>You have an <code>attr_accessible</code> declaration which does <em>not</em> include <code>:name</code></li> <li>You have an <code>attr_protected</code> which <em>does</em> include <code>:name</code></li> </ul> <p>It recently became the default that attributes had to be manually white-listed via a <code>attr_accessible</code> in order for mass assignment to succeed. Prior to this, the default was for attributes to be assignable unless they were explicitly black-listed <code>attr_protected</code> or any <em>other</em> attribute was white-listed with <code>attr_acessible.</code></p> <p>It is important to consider which attributes can be mass assigned because code like this is so common:</p> <pre><code>@post = Post.new(params[:post]) </code></pre> <p>Typically this is used when the user submits a form rendered by a <code>form_for @post</code>. In an ideal world, the <code>params[:post]</code> hash should only contain the fields we displayed on the form. However, it is trivial easy for the user to pass additional fields in their request, so in effect you're allowing a user to set <em>any</em> fields on <code>@post</code>, not just the ones displayed on the form.</p> <p>Failure to safely use mass assignment has led to several high profile bugs in some pretty big Rails applications, like the one that allowed somebody to <a href="http://www.infoq.com/news/2012/03/GitHub-Compromised/">inject their own public key</a> into the list of trusted keys on a Github repository and push code directly to a repository they should not have had access to.</p>
11,769,555
Regular expression to match a backslash followed by a quote
<p>How to write a regular expression to match this <code>\&quot;</code> (a backslash then a quote)? Assume I have a string like this:</p> <pre><code>&lt;a href=\&quot;google.com\&quot;&gt; click to search &lt;/a&gt; </code></pre> <p>I need to replace all the <code>\&quot;</code> with a <code>&quot;</code>, so the result would look like:</p> <pre><code>&lt;a href=&quot;google.com&quot;&gt; click to search &lt;/a&gt; </code></pre> <p>This one does not work: <code>str.replaceAll(&quot;\\\&quot;&quot;, &quot;\&quot;&quot;)</code> because it only matches the quote. Not sure how to get around with the backslash. I could have removed the backslash first, but there are other backslashes in my string.</p>
11,769,570
3
3
null
2012-08-02 00:43:03.223 UTC
13
2022-01-17 15:56:49.673 UTC
2022-01-17 15:56:49.673 UTC
null
466,862
null
1,570,058
null
1
26
java|regex
62,084
<p>If you <em><strong>don't need any of regex mechanisms like predefined character classes \d, quantifiers etc.</strong></em> instead of <code>replaceAll</code> which expects regex use <code>replace</code> which expects literals</p> <pre><code>str = str.replace(&quot;\\\&quot;&quot;,&quot;\&quot;&quot;); </code></pre> <p>Both methods will replace <em>all</em> occurrences of targets, but <code>replace</code> will treat targets literally.</p> <hr /> <p>BUT if you really <em><strong>must</strong></em> use regex you are looking for</p> <pre><code>str = str.replaceAll(&quot;\\\\\&quot;&quot;, &quot;\&quot;&quot;) </code></pre> <p><code>\</code> is special character in regex (used for instance to create <code>\d</code> - character class representing digits). To make regex treat <code>\</code> as normal character you need to place another <code>\</code> before it to turn off its special meaning (you need to escape it). So regex which we are trying to create is <code>\\</code>.</p> <p>But to create string literal representing text <code>\\</code> so you could pass it to regex engine you need to write it as four <code>\</code> (<code>&quot;\\\\&quot;</code>), because <code>\</code> is also special character in String literals (part of code written using <code>&quot;...&quot;</code>) since it can be used for instance as <code>\t</code> to represent tabulator. That is why you also need to escape <code>\</code> there.</p> <p>In short you need to escape <code>\</code> twice:</p> <ul> <li>in regex <code>\\</code></li> <li>and then in String literal <code>&quot;\\\\&quot;</code></li> </ul>
11,892,928
CoreData could not fulfill a fault for
<p>I have a really annoying problem, which I just can't seem to get fixed. </p> <p>I have a view when I send a message that gets saved to the Core Data, when thats done it asked the database for a random message (sentence) and saved that as well to an other row in the database.</p> <p>If I do the last part hardcoded, without fetching data from the DB, it works all fine and dandy, but as soon as I fetch the random row from the DB it goes crazy.</p> <p>In my AppDelegate.m:</p> <pre><code>- (void)save { NSAssert(self.context != nil, @"Not initialized"); NSError *error = nil; BOOL failed = [self.context hasChanges] &amp;&amp; ![self.context save:&amp;error]; NSAssert1(!failed,@"Save failed %@",[error userInfo]); } - (NSString*)selectRandomSentence { NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Sentences" inManagedObjectContext:self.managedObjectContext]; [request setEntity:entity]; NSError *error = nil; NSUInteger count = [self.context countForFetchRequest:request error:&amp;error]; NSUInteger offset = count - (arc4random() % count); [request setFetchOffset:offset]; [request setFetchLimit:1]; NSArray *sentenceArray = [self.context executeFetchRequest:request error:&amp;error]; [request release]; return [[sentenceArray objectAtIndex:0] sentence]; } - (NSManagedObjectContext *)context { if (_managedObjectContext != nil) return _managedObjectContext; NSPersistentStoreCoordinator *coordinator = [self coordinator]; if (coordinator != nil) { _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; } return _managedObjectContext; } </code></pre> <p>In my ChatController.m:</p> <pre><code>- (void)didRecieveMessage:(NSString *)message { [self addMessage:message fromMe:NO]; } #pragma mark - #pragma mark SendControllerDelegate - (void)didSendMessage:(NSString*)text { [self addMessage:text fromMe:YES]; } #pragma mark - #pragma mark Private methods - (void)responseReceived:(NSString*)response { [self addMessage:response fromMe:NO]; } - (void)addMessage:(NSString*)text fromMe:(BOOL)fromMe { NSAssert(self.repository != nil, @"Not initialized"); Message *msg = [self.repository messageForBuddy:self.buddy]; msg.text = text; msg.fromMe = fromMe; if (fromMe) { [self.bot talkWithBot:text]; } [self.repository asyncSave]; [self.tableView reloadData]; [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:[self.buddy.messages count] - 1] atScrollPosition:UITableViewScrollPositionBottom animated:YES]; } </code></pre> <p>In My OfflineBot.m:</p> <pre><code>- (void)talkWithBot:(NSString *)textFromMe { AppDelegate *delegate = [[UIApplication sharedApplication] delegate]; [self didRecieveMessage:[delegate selectRandomSentence]]; } - (void)didRecieveMessage:(NSString *)message { if ([self.delegate respondsToSelector:@selector(didRecieveMessage:)]) [self.delegate didRecieveMessage:message]; } </code></pre> <p>Repository.m</p> <pre><code>- (Message*)messageForBuddy:(Buddy*)buddy { Message *msg = [self.delegate entityForName:@"Message"]; msg.source = buddy; [self.delegate.managedObjectContext refreshObject:buddy mergeChanges:YES]; return msg; } - (void)asyncSave { [self.delegate save]; } </code></pre> <p>The error:</p> <blockquote> <p>2012-08-10 00:28:20.526 Chat[13170:c07] <strong>* Assertion failure in -[AppDelegate save], /Users/paulp/Desktop/TestTask/Classes/AppDelegate.m:28 2012-08-10 00:28:20.527 Chat[13170:c07] *</strong> Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Save failed {type = immutable dict, count = 2, entries => 1 : {contents = "NSAffectedObjectsErrorKey"} = ( " (entity: Sentences; id: 0x6b8bf10 ; data: )" ) 2 : {contents = "NSUnderlyingException"} = CoreData could not fulfill a fault for '0x6b8bf10 ' }</p> </blockquote> <p>What am I doing wrong?</p> <p><em><strong>Update</em></strong> I pinpointed the error to this row:</p> <pre><code>NSArray *sentenceArray = [self.context executeFetchRequest:request error:&amp;error]; </code></pre> <p>When I execute that row, I get the error... that is when fetching the data. The error, however, seems to turn up when saving the new data to the Messages entity. The random sentence is fetched from Sentences. </p> <p>After I changed the asyncSave method to saving directly (thus not using a new thread) it saves the first chat, but nothing after that. It dies.</p> <p><em><strong>Update</em></strong> It all seems to work using this in my <code>didFinishLaunchingWithOptions</code>:</p> <pre><code>[self.context setRetainsRegisteredObjects:YES]; </code></pre> <p>I understand that hereby the CodeData Object Model Context doesn't release its objects, which seems to be the problem betweens adding and saving. But why?</p>
11,934,958
5
14
null
2012-08-09 22:29:36.653 UTC
15
2017-07-07 02:56:27.45 UTC
2012-08-13 07:12:48.253 UTC
null
406,677
null
406,677
null
1
34
objective-c|ios|core-data|nsmanagedobject|nsmanagedobjectcontext
33,572
<p>It is not really conceptually possible to "<em>save</em>" Core Data objects "<em>in different rows</em>". Remember, Core Data is an object graph and not a database. </p> <p>If you want to "relocate" your sentence, the best way is to destroy it and recreate it. If you want to keep the old instance, just create a new one and then fill in the properties from the existing one.</p> <p>For destroying, use </p> <pre><code>[self.context deleteObject:sentenceObject]; </code></pre> <p>For recreating, use</p> <pre><code>Sentence *newSentence = [NSEntityDescription insertNewObjectForEntityForName: "Sentences" inManagedObjectContext:self.context]; newSentence.sentence = sentenceObject.sentence; // fill in other properties, then [self.context save:error]; </code></pre> <p>If you would like to read up on this, look at "<a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdUsingMOs.html#//apple_ref/doc/uid/TP40001803-213600">Copying and Copy and Paste</a>" in the "Using Managed Objects" section of the "Core Data Programming Guide".</p>
11,917,708
How to pipe multiple commands into a single command in the shell? (sh, bash, ...)
<p>How can I pipe the stdout of multiple commands to a single command? </p> <p>Example 1: combine and sort the output of all three echo commands:</p> <pre><code>echo zzz; echo aaa; echo kkk </code></pre> <p>desired output:</p> <pre><code>aaa kkk zzz </code></pre> <p>Example 2: rewrite the following so that all the commands are in a single command-line using pipes, without redirects to a temp file:</p> <pre><code>setopt &gt; /tmp/foo; unsetopt &gt;&gt; /tmp/foo; set &gt;&gt; /tmp/foo; sort /tmp/foo </code></pre>
11,917,709
3
0
null
2012-08-11 21:13:04.08 UTC
13
2022-09-13 14:39:12.18 UTC
2022-09-13 14:39:12.18 UTC
null
875,915
null
875,915
null
1
71
bash|shell|process|pipe|subshell
65,685
<p>Use parentheses ()'s to combine the commands into a single process, which will concatenate the stdout of each of them.</p> <p>Example 1 (note that <code>$</code> is the shell prompt):</p> <pre><code>$ (echo zzz; echo aaa; echo kkk) | sort aaa kkk zzz </code></pre> <p><br/> Example 2:</p> <pre><code>(setopt; unsetopt; set) | sort </code></pre>
11,892,729
How to "log in" to a website using Python's Requests module?
<p>I am trying to post a request to log in to a website using the Requests module in Python but its not really working. I'm new to this...so I can't figure out if I should make my Username and Password cookies or some type of HTTP authorization thing I found (??). </p> <pre><code>from pyquery import PyQuery import requests url = 'http://www.locationary.com/home/index2.jsp' </code></pre> <p>So now, I think I'm supposed to use "post" and cookies....</p> <pre><code>ck = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'} r = requests.post(url, cookies=ck) content = r.text q = PyQuery(content) title = q("title").text() print title </code></pre> <p>I have a feeling that I'm doing the cookies thing wrong...I don't know.</p> <p>If it doesn't log in correctly, the title of the home page should come out to "Locationary.com" and if it does, it should be "Home Page."</p> <p>If you could maybe explain a few things about requests and cookies to me and help me out with this, I would greatly appreciate it. :D</p> <p>Thanks.</p> <p>...It still didn't really work yet. Okay...so this is what the home page HTML says before you log in:</p> <pre><code>&lt;/td&gt;&lt;td&gt;&lt;img src="http://www.locationary.com/img/LocationaryImgs/icons/txt_email.gif"&gt; &lt;/td&gt; &lt;td&gt;&lt;input class="Data_Entry_Field_Login" type="text" name="inUserName" id="inUserName" size="25"&gt;&lt;/td&gt; &lt;td&gt;&lt;img src="http://www.locationary.com/img/LocationaryImgs/icons/txt_password.gif"&gt; &lt;/td&gt; &lt;td&gt;&lt;input class="Data_Entry_Field_Login" type="password" name="inUserPass" id="inUserPass"&gt;&lt;/td&gt; </code></pre> <p>So I think I'm doing it right, but the output is still "Locationary.com"</p> <p>2nd EDIT:</p> <p>I want to be able to stay logged in for a long time and whenever I request a page under that domain, I want the content to show up as if I were logged in.</p>
11,892,838
6
0
null
2012-08-09 22:12:14.537 UTC
105
2020-10-29 22:50:22.77 UTC
2012-08-09 22:39:20.423 UTC
null
1,587,751
null
1,587,751
null
1
140
python|python-requests|pyquery
328,543
<h2>If the information you want is on the page you are directed to immediately after login...</h2> <p>Lets call your <code>ck</code> variable <code>payload</code> instead, like in the <a href="http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests" rel="noreferrer">python-requests</a> docs:</p> <pre><code>payload = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'} url = 'http://www.locationary.com/home/index2.jsp' requests.post(url, data=payload) </code></pre> <h2>Otherwise...</h2> <p>See <a href="https://stackoverflow.com/a/17633072/111362">https://stackoverflow.com/a/17633072/111362</a> below.</p>
20,057,771
'No JUnit tests found' in Eclipse
<p>So I'm new to JUnit, and we have to use it for a homework assignment. Our professor gave us a project that has one test class, <code>BallTest.java</code>. When I right click > Run as > JUnit Test, I get a popup error that says 'No JUnit tests found'. I know the question has been answered here(<a href="https://stackoverflow.com/questions/2332832/no-tests-found-with-test-runner-junit-4">No tests found with test runner &#39;JUnit 4&#39;</a>), but closing eclipse, restarting, cleaning, and building doesn't seem to work. Below are screenshots of my run configuration, build path, and the class I'm trying to test.</p> <p><img src="https://i.stack.imgur.com/dU1T6.jpg" alt="Run Configuration"> <img src="https://i.stack.imgur.com/aPjIY.jpg" alt="Build Path"></p> <p><code>BallTest.java</code></p> <pre><code>import static org.junit.Assert.*; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class BallTest { Ball ball; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { System.out.println("Setting up ..."); Point2D p = new Point2D(0,0); ball = new Ball(p); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { System.out.println("Tearing down ..."); ball = null; } /** * Test method for {@link Ball#getCoordinates()}. */ @Test public void testGetCoordinates() { assertNotNull(ball); // don't need Assert. because of the import statement above. Assert.assertEquals(ball.getCoordinates().getX(), 0); Assert.assertEquals(ball.getCoordinates().getY(), 0); } /** * Test method for {@link Ball#setCoordinates(Point2D)}. */ @Test public void testSetCoordinates() { Assert.assertNotNull(ball); Point2D p = new Point2D(99,99); ball.setCoordinates(p); Assert.assertEquals(ball.getCoordinates().getX(), 99); Assert.assertEquals(ball.getCoordinates().getY(), 99); } /** * Test method for {@link Ball#Ball(Point2D)}. */ @Test public void testBall() { Point2D p = new Point2D(49,30); ball = new Ball(p); Assert.assertNotNull(ball); Assert.assertEquals(ball.getCoordinates().getX(), 49); Assert.assertEquals(ball.getCoordinates().getY(), 30); //fail("Not yet implemented"); } public static void main (String[] args) { Result result = JUnitCore.runClasses(BallTest.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } </code></pre>
20,062,207
23
5
null
2013-11-18 20:58:55.097 UTC
12
2021-07-15 11:30:06.603 UTC
2017-05-23 12:26:33.11 UTC
null
-1
null
994,541
null
1
52
java|eclipse|unit-testing|junit
141,409
<p>Right Click on Project > Properties > Java Build Path > Add the Test folder as source folder.</p> <p>All source folders including Test Classes need to be in Eclipse Java Build Path. So that the sources such as main and test classes can be compiled into the build directory (Eclipse default folder is bin).</p>
3,585,871
How can I get the current mouse (pointer) position co-ordinates in X
<p>This can either be some sample C code or a utility that will show me either gui or on the console it doesn't matter, but I have to be able to "command" it to grab the co-ordinates at an exact time which makes xev not very useful (that I could figure out).</p>
3,591,679
4
0
null
2010-08-27 15:45:31.547 UTC
9
2020-01-06 18:40:01.65 UTC
2011-07-28 17:08:29.793 UTC
null
102,937
null
376,403
null
1
22
xorg
21,476
<p>I'm not a C programmer by any means but I looked at a couple of online tutorials and think this is how you are supposed to read the current mouse position. This is my own code and I'd done nothing with Xlib before so it could be completely broken (for example, the error handler shouldn't just do nothing for every error) but it works. So here is another solution:</p> <pre><code>#include &lt;X11/Xlib.h&gt; #include &lt;assert.h&gt; #include &lt;unistd.h&gt; #include &lt;stdio.h&gt; #include &lt;malloc.h&gt; static int _XlibErrorHandler(Display *display, XErrorEvent *event) { fprintf(stderr, "An error occured detecting the mouse position\n"); return True; } int main(void) { int number_of_screens; int i; Bool result; Window *root_windows; Window window_returned; int root_x, root_y; int win_x, win_y; unsigned int mask_return; Display *display = XOpenDisplay(NULL); assert(display); XSetErrorHandler(_XlibErrorHandler); number_of_screens = XScreenCount(display); fprintf(stderr, "There are %d screens available in this X session\n", number_of_screens); root_windows = malloc(sizeof(Window) * number_of_screens); for (i = 0; i &lt; number_of_screens; i++) { root_windows[i] = XRootWindow(display, i); } for (i = 0; i &lt; number_of_screens; i++) { result = XQueryPointer(display, root_windows[i], &amp;window_returned, &amp;window_returned, &amp;root_x, &amp;root_y, &amp;win_x, &amp;win_y, &amp;mask_return); if (result == True) { break; } } if (result != True) { fprintf(stderr, "No mouse found.\n"); return -1; } printf("Mouse is at (%d,%d)\n", root_x, root_y); free(root_windows); XCloseDisplay(display); return 0; } </code></pre>
3,958,342
Convert audio to text
<p>I just want to know if there is any build in libraries or external libraries in Java or C# that allow me to take an audio file and parse it and extract the text from it.</p> <p>I need to make an application to do so, but I don't know from where I can start.</p>
3,958,634
5
6
null
2010-10-18 10:41:44.933 UTC
10
2012-03-17 17:09:48.313 UTC
2011-07-25 11:28:34.263 UTC
null
418,556
null
458,700
null
1
12
c#|java|speech-recognition|audio-processing
23,709
<p>Here are some of your options:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms723627%28VS.85%29.aspx" rel="noreferrer">Microsoft Speech</a></li> <li><a href="http://www.lumenvox.com/products/speech_engine/" rel="noreferrer">Lumenvox</a></li> <li><a href="http://www.nuance.com/for-developers/dragon/index.htm" rel="noreferrer">Dragon naturally speaking</a></li> <li><a href="http://cmusphinx.sourceforge.net/sphinx4/" rel="noreferrer">sphinx4</a></li> </ul>
3,230,633
How to register handler interceptors with spring mvc 3.0?
<p>It should be easy:</p> <pre><code>&lt;bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"&gt; &lt;property name="interceptors"&gt; &lt;list&gt; &lt;ref bean="myInterceptor" /&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>but this way the interceptor isn't called.</p>
3,231,197
5
2
null
2010-07-12 17:23:54.273 UTC
10
2012-11-08 00:28:28.85 UTC
null
null
null
null
203,907
null
1
18
java|spring|spring-mvc
27,625
<p>By default, Spring will register a <code>BeanNameUrlHandlerMapping</code>, and a <code>DefaultAnnotationHandlerMapping</code>, without any explicit config required. </p> <p>If you define your own <code>HandlerMapping</code> beans, then the default ones will not be registered, and you'll just get the explicitly declared ones.</p> <p>So far, so good.</p> <p>The problem comes when you add <code>&lt;mvc:annotation-driven/&gt;</code> to the mix. This <em>also</em> declares its own <code>DefaultAnnotationHandlerMapping</code>, which replaces the defaults. However, if you also declare your own one, then you end up with two. Since they are consulted in order of declaration, this usually means the one registered by <code>&lt;mvc:annotation-driven/&gt;</code> gets called first, and your own one gets ignored.</p> <p>It would be better if the <code>DefaultAnnotationHandlerMapping</code> registered by <code>&lt;mvc:annotation-driven/&gt;</code> acted like the default one, i.e. if explicitly declared ones took precedence, but that's not the way they wrote it.</p> <p>My current preference is to not use <code>&lt;mvc:annotation-driven/&gt;</code> at all, it's too confusing, and too unpredictable when mixed with other config options. It doesn't really do anything especially complex, it's not difficult or verbose to explicitly add the stuff that it does for you, and the end result is easier to follow.</p>
3,822,732
Android: getString(R.string) in static method
<p>When programming for Android sometimes you have to use static methods. But when you try to access you resources in a static method with <code>getString(R.string.text)</code> you'll get an error. Making it static doesn't work.</p> <p>Does anyone knows a good way around this? The resource files in Android are very helpful for creating things in different languages or making changes to a text.</p>
3,822,756
6
0
null
2010-09-29 14:43:24.353 UTC
2
2019-11-25 10:38:02.517 UTC
2014-02-28 11:13:09.773 UTC
null
1,542,891
null
461,864
null
1
30
android|static|getstring
32,708
<p>One way or another, you'll need a Context for that... For static methods this probably means you need to pass along a Context when calling them.</p>
3,649,639
limit on string size in c++?
<p>I have like a million records each of about 30 characters coming in over a socket. Can I read all of it into a single string? Is there a limit on the string size I can allocate?</p> <p>If so, is there someway I can send data over the socket records by record and receive it record by record. I dont know the size of each record until runtime.</p>
3,649,663
8
0
null
2010-09-06 07:06:15.733 UTC
null
2016-08-21 20:05:15.64 UTC
null
null
null
null
430,322
null
1
23
c++
80,874
<p>To answer your first question: The maximum size of a C++ string is given by <a href="http://en.cppreference.com/w/cpp/string/basic_string/max_size" rel="noreferrer">string::max_size</a></p>
3,786,881
What is a "method" in Python?
<p>Can anyone, please, explain to me in very simple terms what a "method" is in Python?</p> <p>The thing is in many Python tutorials for beginners this word is used in such way as if the beginner already knew what a method is in the context of Python. While I am of course familiar with the general meaning of this word, I have no clue what this term means in Python. So, please, explain to me what the "Pythonian" method is all about.</p> <p>Some very simple example code would be very much appreciated as a picture is worth thousand words.</p>
3,786,900
8
4
null
2010-09-24 12:07:07.263 UTC
51
2021-11-17 20:22:55.787 UTC
2012-07-16 20:07:11.007 UTC
null
1,288
null
206,857
null
1
80
python|methods
218,271
<p>It's a function which is a member of a class:</p> <pre><code>class C: def my_method(self): print(&quot;I am a C&quot;) c = C() c.my_method() # Prints(&quot;I am a C&quot;) </code></pre> <p>Simple as that!</p> <p>(There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing from your question that you're not asking about that, but rather just the basics.)</p>
3,973,994
How can I recover from an erronous git push -f origin master?
<p>I just committed the wrong source to my project using <code>--force</code> option.</p> <p>Is it possible to revert? I understand that all previous branches have been overwritten using <code>-f</code> option, so I may have screwed up my previous revisions.</p>
3,974,056
9
1
null
2010-10-20 00:54:59.673 UTC
43
2020-07-12 00:41:13.49 UTC
2016-11-25 17:43:16.3 UTC
null
971,141
null
297,201
null
1
118
git|git-commit|git-push
101,186
<p>Git generally doesn't throw anything away, but recovering from this may still be tricky.</p> <p>If you have the correct source then you could just push it into the remote with the <code>--force</code> option. Git won't have deleted any branches unless you told it to. If you have actually lost commits then take a look at <a href="http://www.programblings.com/2008/06/07/the-illustrated-guide-to-recovering-lost-commits-with-git/" rel="noreferrer">this useful guide to recovering commits</a>. If you know the SHA-1 of the commits you want then you're probably OK.</p> <p>Best thing to do: Back everything up and see what is still in your local repository. Do the same on the remote if possible. Use <code>git fsck</code> to see if you can recover things, and above all <strong>DO NOT run <code>git gc</code></strong>.</p> <p>Above above all, never use the <code>--force</code> option unless you really, really mean it.</p>
3,330,193
Early exit from function?
<p>I have a function:</p> <pre><code>function myfunction() { if (a == 'stop') // How can I stop the function here? } </code></pre> <p>Is there something like <code>exit()</code> in JavaScript?</p>
3,330,206
12
6
null
2010-07-25 17:16:24.91 UTC
73
2021-04-21 18:17:52.673 UTC
2018-05-30 18:04:29.337 UTC
null
881,229
null
291,772
null
1
466
javascript
975,821
<p>You can just use <code>return</code>.</p> <pre><code>function myfunction() { if(a == 'stop') return; } </code></pre> <p>This will send a return value of <code>undefined</code> to whatever called the function.</p> <pre><code>var x = myfunction(); console.log( x ); // console shows undefined </code></pre> <p>Of course, you can specify a different return value. Whatever value is returned will be logged to the console using the above example.</p> <pre><code>return false; return true; return "some string"; return 12345; </code></pre>
7,816,863
How to use document.getElementByName and getElementByTag?
<pre><code> document.getElementById('frmMain').elements </code></pre> <p>can i use like this </p> <pre><code>document.getElementByName('frmMain').elements </code></pre> <p>or </p> <pre><code>document.getElementBytag('table').elements` </code></pre>
7,816,899
6
1
null
2011-10-19 05:21:26.92 UTC
5
2019-05-11 17:49:33.693 UTC
2014-12-20 15:03:38.937 UTC
null
1,897,200
null
989,368
null
1
17
javascript
187,122
<ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById" rel="nofollow noreferrer">document.getElementById('frmMain').elements</a><br> assumes the form has an ID and that the ID is unique as IDs should be. Although it also accesses a <code>name</code> attribute in IE, please add ID to the element if you want to use getElementBy<strong>Id</strong></li> </ul> <hr> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName" rel="nofollow noreferrer">document.getElementsByName('frmMain')[0].elements</a><br> will get the elements of the first object named frmMain on the page - notice the plural getElement<strong>s</strong> - it will return a collection.</li> </ul> <hr> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName" rel="nofollow noreferrer">document.getElementsByTagName('form')[0].elements</a><br> will get the elements of the first form on the page based on the tag - again notice the plural getElement<strong>s</strong></li> </ul> <hr> <p>A great alternative is </p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector" rel="nofollow noreferrer">document.querySelector("form").elements</a><br> will get the elements of the first form on the page. The "form" is a valid CSS selector</li> </ul> <hr> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll" rel="nofollow noreferrer">document.querySelectorAll("form")[0].elements</a><br> notice the <code>All</code> - it is a collection. The [0] will get the elements of the first form on the page. The "form" is a valid CSS selector</li> </ul> <p>In all of the above, the <code>.elements</code> can be replaced by for example <code>.querySelectorAll("[type=text]")</code> to get all text elements </p>
7,972,785
Can a C macro definition refer to other macros?
<p>What I'm trying to figure out is if something such as this (written in <strong>C</strong>):</p> <pre><code>#define FOO 15 #define BAR 23 #define MEH (FOO / BAR) </code></pre> <p>is allowed? I would want the preprocessor to replace every instance of</p> <pre><code>MEH </code></pre> <p>with</p> <pre><code>(15 / 23) </code></pre> <p>but I'm not so sure that will work. Certainly if the preprocessor only goes through the code once then I don't think it'd work out the way I'd like.</p> <p>I found several similar examples but all were really too complicated for me to understand. If someone could help me out with this simple one I'd be eternally grateful!</p>
7,972,803
6
2
null
2011-11-01 20:56:06.6 UTC
7
2019-09-24 11:17:52.853 UTC
2015-11-28 16:12:16.357 UTC
null
4,370,109
null
1,024,485
null
1
66
c|c-preprocessor
52,418
<p>Short answer yes. You can nest defines and macros like that - as many levels as you want as long as it isn't recursive.</p>
8,320,172
Use Html.RadioButtonFor and Html.LabelFor for the same Model but different values
<p>I have this Razor Template</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;@Html.RadioButtonFor(i =&gt; i.Value, "1")&lt;/td&gt; &lt;td&gt;@Html.LabelFor(i =&gt; i.Value, "true")&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;@Html.RadioButtonFor(i =&gt; i.Value, "0")&lt;/td&gt; &lt;td&gt;@Html.LabelFor(i =&gt; i.Value, "false")&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>That gives me this HTML</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;input id="Items_1__Value" name="Items[1].Value" type="radio" value="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;label for="Items_1__Value"&gt;true&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input checked="checked" id="Items_1__Value" name="Items[1].Value" type="radio" value="0" /&gt;&lt;/td&gt; &lt;td&gt;&lt;label for="Items_1__Value"&gt;false&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>So I have the ID <code>Items_1__Value</code> twice which is - of course - not good and does not work in a browser when I click on the second label "false" the first radio will be activated.</p> <p>I know I could add an own Id at RadioButtonFor and refer to that with my label, but that's not pretty good, is it? Especially because I'm in a loop and cannot just use the name "value" with an added number, that would be end up in multiple Dom Ids in my final HTML markup as well.</p> <p>Shouldn't be a <em>good</em> solution for this?</p>
8,623,532
7
2
null
2011-11-30 01:45:44.103 UTC
14
2015-10-09 11:30:42.797 UTC
null
null
null
null
596,137
null
1
36
asp.net-mvc-3|razor
65,127
<p>I've been wondering how MVC determines "nested" field names and IDs. It took a bit of research into the MVC source code to figure out, but I think I have a good solution for you.</p> <h3>How EditorTemplates and DisplayTemplates determine field names and IDs</h3> <p>With the introduction of EditorTemplates and DisplayTemplates, the MVC framework added <code>ViewData.TemplateInfo</code> that contains, among other things, the current "field prefix", such as <code>"Items[1]."</code>. Nested templates use this to create unique names and IDs.</p> <h3>Create our own unique IDs:</h3> <p>The <a href="http://msdn.microsoft.com/en-us/library/ee310265.aspx" rel="noreferrer"><code>TemplateInfo</code></a> class contains an interesting method, <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.templateinfo.getfullhtmlfieldid.aspx" rel="noreferrer"><code>GetFullHtmlFieldId</code></a>. We can use this to create our own unique IDs like so: </p> <pre><code>@{string id = ViewData.TemplateInfo.GetFullHtmlFieldId("fieldName");} @* This will result in something like "Items_1__fieldName" *@ </code></pre> <h3>For The Win</h3> <p>Here's how to achieve the correct behavior for your example:</p> <pre><code>&lt;table&gt; &lt;tr&gt; @{string id = ViewData.TemplateInfo.GetFullHtmlFieldId("radioTrue");} &lt;td&gt;@Html.RadioButtonFor(i =&gt; i.Value, "1", new{id})&lt;/td&gt; &lt;td&gt;@Html.LabelFor(i =&gt; i.Value, "true", new{@for=id})&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; @{id = ViewData.TemplateInfo.GetFullHtmlFieldId("radioFalse");} &lt;td&gt;@Html.RadioButtonFor(i =&gt; i.Value, "0", new{id})&lt;/td&gt; &lt;td&gt;@Html.LabelFor(i =&gt; i.Value, "false", new{@for=id})&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Which will give you the following HTML:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;input id="Items_1__radioTrue" name="Items[1].Value" type="radio" value="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;label for="Items_1__radioTrue"&gt;true&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input checked="checked" id="Items_1__radioFalse" name="Items[1].Value" type="radio" value="0" /&gt;&lt;/td&gt; &lt;td&gt;&lt;label for="Items_1__radioFalse"&gt;false&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <h3>Disclaimer</h3> <p>My Razor syntax is underdeveloped, so please let me know if this code has syntax errors.</p> <h3>For what its worth</h3> <p>It's pretty unfortunate that this functionality isn't built-in to <code>RadioButtonFor</code>. It seems logical that all rendered Radio Buttons should have an ID that is a combination of its <code>name</code> AND <code>value</code>, but that's not the case -- maybe because that would be different from all other Html helpers.<br> Creating your own extension methods for this functionality seems like a logical choice, too. However, it might get tricky using the "expression syntax" ... so I'd recommend overloading <code>.RadioButton(name, value, ...)</code> instead of <code>RadioButtonFor(expression, ...)</code>. And you might want an overload for <code>.Label(name, value)</code> too.<br> I hope that all made sense, because there's a lot of "fill in the blanks" in that paragraph.</p>
8,045,556
Can't make the custom DialogFragment transparent over the Fragment
<p>I need to create a dialog over a fragment (that takes up the whole screen). The dialog needs to be a floating dialog that will be positioned over the fragment with the fragment darkened out outside of the fragment..</p> <p>For the custom Dialog, i have a linearLayout that has curved edges, no matter what i do, the dialog has a black bordering on all sides (very small). I've tried everything to make it transparent and go away (so that all of the dialog is just the linear layout - curved box)</p> <p>For the DialogFragment, this is what I have for onCreateView</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ LinearLayout layout =(LinearLayout)inflater.inflate(R.layout.custom_dialog, null); LinearLayout item = (LinearLayout)layout.findViewById(R.id.display_item); populateItemData(item, inflater); return layout; } </code></pre> <p>custom_dialog is just a LinearLayout that has android:backgroung set to #000000</p> <p>This is my style for the custom Dialog</p> <pre><code>&lt;style name="CustomDialog" parent="android:style/Theme.Dialog"&gt; &lt;item name="android:windowBackground"&gt;@null&lt;/item&gt; &lt;item name="android:windowNoTitle"&gt;true&lt;/item&gt; &lt;item name="android:windowIsFloating"&gt;true&lt;/item&gt; &lt;item name="android:windowIsTranslucent"&gt;true&lt;/item&gt; &lt;item name="android:alwaysDrawnWithCache"&gt;false&lt;/item&gt; &lt;item name="android:windowContentOverlay"&gt;@null&lt;/item&gt; &lt;/style&gt; </code></pre> <p>I tried all kinds of combinations in this style (from what I've seen online) and I can't get rid of that annoying black bordering, I can paint it white or any other color if i set that LinearLayout background to anything other than #000000... </p> <p>I've spent literally 3-4 hours on this, i hope someone else can help out...</p>
9,315,283
10
0
null
2011-11-08 03:20:20.343 UTC
32
2020-08-05 02:16:31.757 UTC
null
null
null
null
137,404
null
1
116
android|android-layout|android-fragments|android-dialog|android-dialogfragment
65,036
<p>Try</p> <pre><code>getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); </code></pre> <p>in your <code>DialogFragment</code>'s <code>onCreateView</code></p>
8,026,263
How to see if a user is online in a website with php and mysql driven databases?
<p>I'm building a community website. Users will login and logout as usually. </p> <p>I use the attribute status online/offline to set the user's status. But what if a user just clicks the X button or disconnects otherwise without logging out?</p> <p>Lately my computer crashed, when I opened the site with my laptop I could not login because I don't allow login in two places. I go to PHPMyAdmin and I see my status still online. Is there any fix for this. </p> <p>I tried the last_time activitiy thing but that doesn't work in case of a computer crash! And there was nothing neither interactivity or refresh to update the table.</p>
8,026,310
12
0
null
2011-11-06 09:50:29.16 UTC
9
2020-02-06 17:26:26.113 UTC
2017-01-25 07:34:40.283 UTC
null
6,887,672
null
929,729
null
1
10
php|mysql|database|login-control
42,785
<p>You don't need the online/offline flag, you just need to save the last activitity time. When displaying the user status, if last activity time is less than now+15 minutes then user is online, offline otherwise.</p>
4,781,070
How to insert tab character when expandtab option is on in Vim
<p>When I'm in insert mode and I have the <a href="https://vimhelp.org/options.txt.html#%27expandtab%27" rel="noreferrer"><code>expandtab</code></a> option switched on, pressing <kbd>Tab ↹</kbd> results in inserting the configured number of spaces.</p> <p>But occasionally I want to insert an actual tab character.</p> <p>Do you know how to do this?</p>
4,781,099
3
0
null
2011-01-24 10:46:56.54 UTC
92
2021-04-02 05:08:41.687 UTC
2020-05-04 11:05:46.837 UTC
null
775,954
null
529,397
null
1
371
vim
117,908
<p>You can use <code>&lt;CTRL-V&gt;&lt;Tab&gt;</code> in "insert mode". In insert mode, <code>&lt;CTRL-V&gt;</code> inserts a literal copy of your next character.</p> <p>If you need to do this often, @Dee`Kej suggested (in the comments) setting <kbd>Shift</kbd>+<kbd>Tab</kbd> to insert a real tab with this mapping:</p> <pre><code>:inoremap &lt;S-Tab&gt; &lt;C-V&gt;&lt;Tab&gt; </code></pre> <p>Also, as noted by @feedbackloop, on Windows you may need to press <code>&lt;CTRL-Q&gt;</code> rather than <code>&lt;CTRL-V&gt;</code>.</p>
4,116,681
How to load system properties file in Spring?
<p>I have a properties file which I would like loaded in to System Properties so that I can access it via <code>System.getProperty("myProp")</code>. Currently, I'm trying to use the Spring <code>&lt;context:propert-placeholder/&gt;</code> like so:</p> <pre><code>&lt;context:property-placeholder location="/WEB-INF/properties/webServerProperties.properties" /&gt; </code></pre> <p>However, when I try to access my properties via <code>System.getProperty("myProp")</code> I'm getting <code>null</code>. My properties file looks like this:</p> <pre><code>myProp=hello world </code></pre> <p>How could I achieve this? I'm pretty sure I could set a runtime argument, however I'd like to avoid this.</p> <p>Thanks!</p>
4,117,375
4
1
null
2010-11-07 06:04:01.43 UTC
9
2022-03-18 02:33:34.94 UTC
null
null
null
null
125,278
null
1
8
java|spring|spring-mvc
35,447
<p>While I subscribe to the Spirit of <a href="https://stackoverflow.com/questions/4116681/how-to-load-system-properties-file-in-spring/4117086#4117086">Bozho's answer</a>, I recently also had a situation where I needed to set System Properties from Spring. Here's the class I came up with:</p> <p><strong>Java Code:</strong></p> <pre><code>public class SystemPropertiesReader{ private Collection&lt;Resource&gt; resources; public void setResources(final Collection&lt;Resource&gt; resources){ this.resources = resources; } public void setResource(final Resource resource){ resources = Collections.singleton(resource); } @PostConstruct public void applyProperties() throws Exception{ final Properties systemProperties = System.getProperties(); for(final Resource resource : resources){ final InputStream inputStream = resource.getInputStream(); try{ systemProperties.load(inputStream); } finally{ // Guava Closeables.closeQuietly(inputStream); } } } } </code></pre> <p><strong>Spring Config:</strong></p> <pre><code>&lt;bean class="x.y.SystemPropertiesReader"&gt; &lt;!-- either a single .properties file --&gt; &lt;property name="resource" value="classpath:dummy.properties" /&gt; &lt;!-- or a collection of .properties file --&gt; &lt;property name="resources" value="classpath*:many.properties" /&gt; &lt;!-- but not both --&gt; &lt;/bean&gt; </code></pre>
4,718,417
Matlab: loading a .mat file, why is it a struct? can I just have the stored vars loaded into memory?
<p>Relevant code:</p> <pre><code>function result = loadStructFromFile(fileName, environmentName) result = load(fileName, environmentName); bigMatrix = loadStructFromFile('values.mat','bigMatrix'); </code></pre> <p>But when I look in the workspace, it shows 'bigMatrix' as a 1x1 struct. When I click on the struct, however, it is the actual data (in this case a a 998x294 matrix).</p>
4,718,603
4
0
null
2011-01-17 22:04:22.14 UTC
1
2020-10-07 21:56:34.657 UTC
2013-06-16 12:33:39.303 UTC
null
1,714,410
null
356,849
null
1
8
matlab|matlab-load
38,051
<p>As the documentation of <a href="http://www.mathworks.com/help/techdoc/ref/load.html" rel="noreferrer">LOAD</a> indicates, if you call it with an output argument, the result is returned in a struct. If you do not call it with an output argument, the variables are created in the local workspace with the name as which they were saved.</p> <p>For your function <code>loadStructFromFile</code>, if the saved variable name can have different names (I assume <code>environmentName</code>), you can return the variable by writing</p> <pre><code>function result = loadStructFromFile(fileName, environmentName) tmp = load(fileName, environmentName); result = tmp.(environmentName); </code></pre>
4,351,170
Do DDD and SOA really play well together?
<p>Please let me know, ever so gently, if I am totally mangling the DDD concept, but here is my dilemma.</p> <p>Let's say I have the following domain model:</p> <pre><code>Teacher IList&lt;Class&gt; Class Teacher IList&lt;Student&gt; Student Class </code></pre> <p>Now, from a DDD perspective, it seems like the Teacher is my root, and indeed, in a simple app, I might carry around my Teacher with her classes and students and act on them as needed. But in an SOA situation, let's say I've pulled down my Teacher, her classes and students for display purposes (as dtos), and she wants to add a student. Surely I am not going to send the whole object graph up to the server and retrieve the domain objects from the database just so that I can add a new student, right? </p> <p>Where is the sweet spot here, or am I totally missing the boat?</p> <p>Thanks!</p> <p>Late Upate: Maybe I'm answering my own question, but I guess one approach is to have my Teacher service have various student management methods (AddStudent, UpdateStudent) such that my root is still managing everything instead of having one service per object. </p>
4,352,840
4
0
null
2010-12-04 00:34:07.473 UTC
13
2010-12-16 00:55:44.183 UTC
2010-12-04 00:41:57.57 UTC
null
205,856
null
205,856
null
1
15
domain-driven-design|soa
5,300
<p>You are thinking about performance, but you will be surprised. In my SOA web services I use such complete object graphs and performance is well within acceptable limits. I would suggest to use business objects and business web methods like <code>SaveTeacher(Teacher t)</code> unless absolutely required to use DTOs for performance reason and associated CRUD web methods like <code>AddStudent(long teacherId, Student student)</code><br> But even if using the later you can apply the DDD concept by loading the teacher from your persistence store given the teacherId, attaching the student and saving the teacher back to persistence store.</p>
4,232,842
How to dynamically change filename while writing in a loop?
<p>I would like to do something like this: In a loop, first iteration write some content into a file named file0.txt, second iteration file1.txt and so on, just increase the number.</p> <pre><code>FILE *img; int k = 0; while (true) { // here we get some data into variable data file = fopen("file.txt", "wb"); fwrite (data, 1, strlen(data) , file); fclose(file ); k++; // here we check some condition so we can return from the loop } </code></pre>
4,232,864
5
0
null
2010-11-20 13:02:13.263 UTC
7
2021-03-20 18:36:42.793 UTC
2014-09-30 15:55:31.457 UTC
null
2,988,730
null
95,944
null
1
17
c
38,769
<pre><code>int k = 0; while (true) { char buffer[32]; // The filename buffer. // Put "file" then k then ".txt" in to filename. snprintf(buffer, sizeof(char) * 32, "file%i.txt", k); // here we get some data into variable data file = fopen(buffer, "wb"); fwrite (data, 1, strlen(data) , file); fclose(file ); k++; // here we check some condition so we can return from the loop } </code></pre>
4,453,349
what is the Class object (java.lang.Class)?
<p>The Java documentation for <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html" rel="noreferrer"><code>Class</code></a> says:</p> <blockquote> <p><code>Class</code> objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the <code>defineClass</code> method in the class loader.</p> </blockquote> <p>What are these <code>Class</code> objects? Are they the same as objects instantiated from a class by calling <code>new</code>?</p> <p>Also, for example <code>object.getClass().getName()</code> how can everything be typecasted to superclass <code>Class</code>, even if I don't inherit from <code>java.lang.Class</code>?</p>
4,453,378
7
0
null
2010-12-15 18:10:23.53 UTC
83
2019-11-20 17:36:03.173 UTC
2015-08-24 18:35:29.997 UTC
null
113,632
null
515,661
null
1
90
java|class|inheritance
81,800
<p>Nothing gets typecasted to <code>Class</code>. Every <code>Object</code> in Java belongs to a certain <code>class</code>. That's why the <code>Object</code> class, which is inherited by all other classes, defines the <code>getClass()</code> method.</p> <p><code>getClass()</code>, or the class-literal - <code>Foo.class</code> return a <code>Class</code> object, which contains some metadata about the class:</p> <ul> <li>name</li> <li>package</li> <li>methods</li> <li>fields</li> <li>constructors</li> <li>annotations</li> </ul> <p>and some useful methods like casting and various checks (<code>isAbstract()</code>, <code>isPrimitive()</code>, etc). <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Class.html" rel="noreferrer">the javadoc</a> shows exactly what information you can obtain about a class.</p> <p>So, for example, if a method of yours is given an object, and you want to process it in case it is annotated with the <code>@Processable</code> annotation, then:</p> <pre><code>public void process(Object obj) { if (obj.getClass().isAnnotationPresent(Processable.class)) { // process somehow; } } </code></pre> <p>In this example, you obtain the metadata about the class of the given object (whatever it is), and check if it has a given annotation. Many of the methods on a <code>Class</code> instance are called "reflective operations", or simply "reflection. <a href="http://download.oracle.com/javase/tutorial/reflect/index.html" rel="noreferrer">Read here</a> about reflection, why and when it is used.</p> <p>Note also that <code>Class</code> object represents enums and intefaces along with classes in a running Java application, and have the respective metadata.</p> <p>To summarize - each object in java has (belongs to) a class, and has a respective <code>Class</code> object, which contains metadata about it, that is accessible at runtime.</p>
4,393,716
Is there a a way to achieve closures in C
<p>I would like this to work, but it does not:</p> <pre><code>#include &lt;stdio.h&gt; typedef struct closure_s { void (*incrementer) (); void (*emitter) (); } closure; closure emit(int in) { void incrementer() { in++; } void emitter() { printf("%d\n", in); } return (closure) { incrementer, emitter }; } main() { closure test[] = { emit(10), emit(20) }; test[0] . incrementer(); test[1] . incrementer(); test[0] . emitter(); test[1] . emitter(); } </code></pre> <p>It actually <em>does</em> compile and does work for 1 instance ... but the second one fails. Any idea how to get closures in C?</p> <p>It would be truly awesome!</p>
4,393,782
9
0
null
2010-12-09 00:21:45.31 UTC
20
2022-05-10 21:19:54.43 UTC
null
null
null
null
535,759
null
1
43
c|closures
36,417
<p>Using <a href="https://savannah.gnu.org/projects/libffcall/" rel="nofollow noreferrer">FFCALL</a>,</p> <pre><code>#include &lt;callback.h&gt; #include &lt;stdio.h&gt; static void incrementer_(int *in) { ++*in; } static void emitter_(int *in) { printf(&quot;%d\n&quot;, *in); } int main() { int in1 = 10, in2 = 20; int (*incrementer1)() = alloc_callback(&amp;incrementer_, &amp;in1); int (*emitter1)() = alloc_callback(&amp;emitter_, &amp;in1); int (*incrementer2)() = alloc_callback(&amp;incrementer_, &amp;in2); int (*emitter2)() = alloc_callback(&amp;emitter_, &amp;in2); incrementer1(); incrementer2(); emitter1(); emitter2(); free_callback(incrementer1); free_callback(incrementer2); free_callback(emitter1); free_callback(emitter2); } </code></pre> <p>But usually in C you end up passing extra arguments around to fake closures.</p> <hr /> <p>Apple has a non-standard extension to C called <a href="http://en.wikipedia.org/wiki/Blocks_%28C_language_extension%29" rel="nofollow noreferrer">blocks</a>, which do work much like closures.</p>
4,196,201
Where are C/C++ main function's parameters?
<p>In C/C++, the main function receives parameters which are of type <code>char*</code>.</p> <pre><code>int main(int argc, char* argv[]){ return 0; } </code></pre> <p><code>argv</code> is an array of <code>char*</code>, and points to strings. Where are these string located? Are they on the heap, stack, or somewhere else?</p>
4,196,745
10
5
null
2010-11-16 16:06:48.797 UTC
15
2017-09-04 04:29:17.373 UTC
2017-05-11 17:36:36.587 UTC
null
1,763,356
null
500,638
null
1
62
c++|c|parameters|location|program-entry-point
21,388
<p>It's actually a combination of compiler dependence and operating system dependence. <code>main()</code> is a function just like any other C function, so the location of the two parameters <code>argc</code> and <code>argv</code> will follow standard for the compiler on the platform. e.g. for most C compilers targeting x86 they will be on the stack just above the return address and the saved base pointer (the stack grows downwards, remember). On x86_64 parameters are passed in registers, so <code>argc</code> will be in <code>%edi</code> and <code>argv</code> will be in <code>%rsi</code>. Code in the main function generated by the compiler then copies them to the stack, and that is where later references point. This is so the registers can be used for function calls from <code>main</code>.</p> <p>The block of <code>char*</code>s that argv points to and the actual sequences of characters could be anywhere. They will start in some operating system defined location and may be copied by the pre-amble code that the linker generates to the stack or somewhere else. You'll have to look at the code for <code>exec()</code> and the assembler pre-amble generated by the linker to find out.</p>
14,553,066
Less css &:hover
<p>How can I create this class with less?</p> <pre><code>.class { display: none; } a:hover .class { display: block; } </code></pre>
14,553,094
3
0
null
2013-01-27 22:27:43.91 UTC
1
2017-10-24 14:46:03.74 UTC
2017-10-24 14:46:03.74 UTC
null
2,678,454
null
1,238,583
null
1
13
less
49,902
<p>Like this?</p> <pre><code>.class { display: none; a:hover &amp; { display: block; } } </code></pre>
14,667,274
ASP.NET MVC Partial view ajax post?
<p><strong>Index.html (View)</strong></p> <pre><code>&lt;div class="categories_content_container"&gt; @Html.Action("_AddCategory", "Categories") &lt;/div&gt; </code></pre> <p><strong>_AddCategory.cshtml (PartialView)</strong></p> <pre><code>&lt;script&gt; $(document).ready(function () { $('input[type=submit]').click(function (e) { e.preventDefault(); $.ajax({ type: "POST", url: '@Url.Action("_AddCategory", "Categories")', dataType: "json", data: $('form').serialize(), success: function (result) { $(".categories_content_container").html(result); }, error: function () { } }); }); }); &lt;/script&gt; @using (Html.BeginForm()) { // form elements } </code></pre> <p>Controller</p> <pre><code>[HttpPost] public ActionResult _AddCategory(CategoriesViewModel viewModel) { if(//success) { // DbOperations... return RedirectToAction("Categories"); } else { // model state is not valid... return PartialView(viewModel); } } </code></pre> <p>Question: If operation is success I expect that redirect to another page (Categories). But no action, no error message. If operation is not success, it is working like my expected.</p> <p>How can I do this? How can I route another page with using AJAX post?</p>
14,667,550
2
3
null
2013-02-02 22:37:53.793 UTC
11
2015-04-10 18:26:33.437 UTC
2015-04-10 18:26:33.437 UTC
null
275,567
null
1,324,756
null
1
15
javascript|jquery|asp.net-mvc|asp.net-mvc-3|asp.net-mvc-4
38,830
<p>Don't redirect from controller actions that are invoked with AJAX. It's useless. You could return the url you want to redirect to as a JsonResult:</p> <pre><code>[HttpPost] public ActionResult _AddCategory(CategoriesViewModel viewModel) { if(//success) { // DbOperations... return Json(new { redirectTo = Url.Action("Categories") }); } else { // model state is not valid... return PartialView(viewModel); } } </code></pre> <p>and then on the client test for the presence of this url and act accordingly:</p> <pre><code>$.ajax({ type: "POST", url: '@Url.Action("_AddCategory", "Categories")', data: $('form').serialize(), success: function (result) { if (result.redirectTo) { // The operation was a success on the server as it returned // a JSON objet with an url property pointing to the location // you would like to redirect to =&gt; now use the window.location.href // property to redirect the client to this location window.location.href = result.redirectTo; } else { // The server returned a partial view =&gt; let's refresh // the corresponding section of our DOM with it $(".categories_content_container").html(result); } }, error: function () { } }); </code></pre> <p>Also notice that I have gotten rid of the <code>dataType: 'json'</code> parameter from your <code>$.ajax()</code> call. That's extremely important as we are not always returning JSON (in your case you were never returning JSON so this parameter was absolutely wrong). In my example we return JSON only in the case of a success and <code>text/html</code> (PartialView) in the case of failure. So you should leave jQuery simply use the <code>Content-Type</code> HTTP response header returned by the server to automatically deduce the type and parse the result parameter passed to your success callback accordingly.</p>
14,828,678
Disconnecting lambda functions in Qt5
<p>Is it possible to disconnect a lambda function? And if "yes", how?</p> <p>According to <a href="https://qt-project.org/wiki/New_Signal_Slot_Syntax" rel="noreferrer">https://qt-project.org/wiki/New_Signal_Slot_Syntax</a> I need to use a <code>QMetaObject::Connection</code> which is returned from the QObject::connect method, but then how can I pass that object to the lambda function?</p> <p>Pseudo-code example:</p> <pre><code>QMetaObject::Connection conn = QObject::connect(m_sock, &amp;QLocalSocket::readyRead, [this](){ QObject::disconnect(conn); //&lt;---- Won't work because conn isn't captured //do some stuff with sock, like sock-&gt;readAll(); } </code></pre>
14,829,520
3
4
null
2013-02-12 08:49:11.017 UTC
12
2022-08-11 22:08:30.003 UTC
null
null
null
null
940,158
null
1
43
c++|lambda|qt5
17,616
<p>If you capture <code>conn</code> directly, you're capturing an uninitialised object by copy, which results in undefined behaviour. You need to capture a smart pointer:</p> <pre><code>std::unique_ptr&lt;QMetaObject::Connection&gt; pconn{new QMetaObject::Connection}; QMetaObject::Connection &amp;conn = *pconn; conn = QObject::connect(m_sock, &amp;QLocalSocket::readyRead, [this, pconn, &amp;conn](){ QObject::disconnect(conn); // ... } </code></pre> <p>Or using a shared pointer, with slightly greater overhead:</p> <pre><code>auto conn = std::make_shared&lt;QMetaObject::Connection&gt;(); *conn = QObject::connect(m_sock, &amp;QLocalSocket::readyRead, [this, conn](){ QObject::disconnect(*conn); // ... } </code></pre> <p>From Qt 5.2 you could instead use a context object:</p> <pre><code>std::unique_ptr&lt;QObject&gt; context{new QObject}; QObject* pcontext = context.get(); QObject::connect(m_sock, &amp;QLocalSocket::readyRead, pcontext, [this, context = std::move(context)]() mutable { context.reset(); // ... }); </code></pre>
14,797,525
Differences between nuget-packing a csproj vs. nuspec
<p>Recently, I started to pack nuget packages out of my several projects. First I started with the Package Explorer application. It is a nice tool, but it's less useful if you do continuous integration. Then I looked into specifying the <em>nuspec</em> template file, and passing changing data, e.g. version number, as command line arguments. Later, I wondered how to define the nuget package dependencies. As it turns out, the nuget.exe already does this based on the <em>package.config</em> if you specify a <em>csproj</em>. Moreover, it extracts relevant data like Author, Version, Copyright right from the assembly info. What I'm missing right now is the ability to specify a licenseUrl in the command line. But I wanted the question to be more generic. And so I'm asking:</p> <p><strong>What is the prefered way to pack nuget packages?</strong></p>
14,808,085
4
0
null
2013-02-10 12:04:54.613 UTC
11
2019-05-23 11:49:09.383 UTC
2013-02-10 14:12:14.907 UTC
null
526,535
null
568,266
null
1
59
c#|.net|nuget
35,808
<p>Here's a little-known fact: <strong>you can combine both</strong>! Target a csproj file, and make sure there's a nuspec file in the same directory with the same name as the csproj file. NuGet will merge the two during package creation.</p> <p>So in short: target <code>&lt;ProjectName&gt;.csproj</code>, optionally add a corresponding <em><a href="http://docs.nuget.org/docs/reference/nuspec-reference#Replacement_Tokens">tokenized</a></em> <code>&lt;ProjectName&gt;.nuspec</code> file to be used as metadata by NuGet.exe. </p> <p>It saves you from managing output location, dependencies, version, and other stuff that can be derived from the project.</p>
19,617,621
Android: How to send http request via service every 10 seconds
<p>I need to receive a status from the server every 10 seconds.</p> <p>I tried to do that by sending a http request via service.</p> <p>The problem is that my code executes only once.</p> <p>This is the code for my service:</p> <pre><code>public class ServiceStatusUpdate extends Service { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { while(true) { try { Thread.sleep(10000); } catch (InterruptedException e) { new DoBackgroundTask().execute(Utilities.QUERYstatus); e.printStackTrace(); } return START_STICKY; } } private class DoBackgroundTask extends AsyncTask&lt;String, String, String&gt; { @Override protected String doInBackground(String... params) { String response = ""; String dataToSend = params[0]; Log.i("FROM STATS SERVICE DoBackgroundTask", dataToSend); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Utilities.AGENT_URL); try { httpPost.setEntity(new StringEntity(dataToSend, "UTF-8")); // Set up the header types needed to properly transfer JSON httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("Accept-Encoding", "application/json"); httpPost.setHeader("Accept-Language", "en-US"); // Execute POST HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); if (responseEntity != null) { response = EntityUtils.toString(responseEntity); } else { response = "{\"NO DATA:\"NO DATA\"}"; } } catch (ClientProtocolException e) { response = "{\"ERROR\":" + e.getMessage().toString() + "}"; } catch (IOException e) { response = "{\"ERROR\":" + e.getMessage().toString() + "}"; } return response; } @Override protected void onPostExecute(String result) { Utilities.STATUS = result; Log.i("FROM STATUS SERVICE: STATUS IS:", Utilities.STATUS); super.onPostExecute(result); } } } </code></pre> <p>Thank's alot Avi</p>
19,617,698
5
0
null
2013-10-27 11:38:32.79 UTC
8
2015-12-29 12:15:23.223 UTC
2013-10-27 11:55:07.223 UTC
null
1,511,951
null
2,924,926
null
1
11
java|android|service|httprequest
33,633
<p>Put a handler inside onPostExecute to send a http request after 10 secs</p> <pre><code>new Handler().postDelayed(new Runnable() { public void run() { requestHttp(); } }, 10000); </code></pre> <p>After 10 secs doInBackground will be executed again, after that onPostExecute again, handler again and so on and so on.. </p>
2,507,235
jquery flot xaxis time
<p>In this example in xaxis will compare the days...</p> <pre><code>$.plot($("#placeholder"), data, { yaxis: {}, xaxis: { mode: "time",minTickSize: [1, "day"],timeformat: "%d/%m/%y"},"lines": {"show": "true"},"points": {"show": "true"},clickable:true,hoverable: true }); </code></pre> <p>How I can print time?</p> <p>This is the result that I wanna:</p> <p><strong>22:00 23:00 00:00 01:00 02:00 ...... 23:00 00:00 01:00 02:00 .... 06:00</strong></p> <p>Is it possible?</p>
2,508,428
2
0
null
2010-03-24 11:33:52.883 UTC
6
2014-09-12 15:07:43.063 UTC
2012-10-03 14:38:45.347 UTC
null
970,544
null
109,227
null
1
19
jquery|flot
70,605
<pre><code>$.plot($("#placeholder"), data, { yaxis: { }, xaxis: { mode: "time",minTickSize: [1, "hour"], min: (new Date("2000/01/01")).getTime(), max: (new Date("2000/01/02")).getTime() }, "lines": {"show": "true"}, "points": {"show": "true"}, clickable:true,hoverable: true }); </code></pre> <p>use this as a starting point and you can see the result here <a href="http://jsfiddle.net/UEePE/" rel="noreferrer">http://jsfiddle.net/UEePE/</a></p>
2,386,793
Efficient looping through AS3 dictionary
<pre><code>for (var k in dictionary) { var key:KeyType = KeyType(k); var value:ValType = ValType(dictionary[k]); // &lt;-- lookup // do stuff } </code></pre> <p>This is what I use to loop through the entries in a dictionary. As you can see in every iteration I perform a lookup in the dictionary. Is there a more efficient way of iterating the dictionary (while keeping access to the key)?</p>
2,386,940
2
0
null
2010-03-05 12:53:12.113 UTC
8
2016-09-16 15:33:04.673 UTC
2010-03-05 13:21:18.427 UTC
null
85,821
null
85,821
null
1
45
actionscript-3|iterator|iteration
47,126
<p>Iterate through <strong>keys</strong> &amp; <strong>values</strong>: </p> <pre><code>for (var k:Object in dictionary) { var value:ValType = dictionary[k]; var key:KeyType = k; } </code></pre> <p>Iterate through <strong>values</strong> more concisely: </p> <pre><code>for each (var value:ValType in dictionary) { } </code></pre>
3,050,492
How can I set default storage engine used by MySQL?
<p>I've been working on writing SQL to create a MySQL database with several default options, including character set and collation. Is it possible to set the default storage engine for tables in this database to InnoDB? </p> <p>I've been looking through the MySQL 5.1 manual and I've found the statement <code>ENGINE=innodb</code> which would be appended to a <code>CREATE TABLE</code> statement, but I haven't found anything related to a <code>CREATE DATABASE</code> statement. </p> <p>Is there a normal way to do this as part of the database creation, or does it need to be specified on a table-by-table basis?</p>
3,050,502
2
0
null
2010-06-16 03:12:30.137 UTC
12
2014-09-25 10:22:58.003 UTC
2014-09-25 10:18:37.787 UTC
null
194,894
null
359,030
null
1
55
mysql|database|innodb
77,280
<p>Quoting the Reference Manual (<a href="http://dev.mysql.com/doc/refman/5.1/en/storage-engine-setting.html" rel="noreferrer">Setting the Storage Engine</a>):</p> <blockquote> <p>If you omit the <code>ENGINE</code> option, the default storage engine is used. Normally, this is MyISAM, but you can change it by using the <strong><code>--default-storage-engine</code></strong> server startup option, or by setting the <strong><code>default-storage-engine</code></strong> option in the <strong><code>my.cnf</code></strong> configuration file.</p> </blockquote> <p>The default-storage-engine option must be part of the mysqld section in <strong>my.cnf</strong>;</p> <pre><code>[mysqld] default-storage-engine = innodb </code></pre> <p>You may also want to change the default storage engine just for the current session. You can do this by setting the <code>storage_engine</code> variable:</p> <pre><code>SET storage_engine=INNODB; </code></pre>
33,773,477
JWT (JSON Web Token) in PHP without using 3rd-party library. How to sign?
<p>There are a few libraries for implementing JSON Web Tokens (JWT) in PHP, such as <a href="https://github.com/firebase/php-jwt" rel="noreferrer">php-jwt</a>. I am writing my own, very small and simple class but cannot figure out why my signature fails validation <a href="http://jwt.io/" rel="noreferrer">here</a> even though I've tried to stick to the standard. I've been trying for hours and I'm stuck. Please help!</p> <p>My code is simple</p> <pre><code>//build the headers $headers = ['alg'=&gt;'HS256','typ'=&gt;'JWT']; $headers_encoded = base64url_encode(json_encode($headers)); //build the payload $payload = ['sub'=&gt;'1234567890','name'=&gt;'John Doe', 'admin'=&gt;true]; $payload_encoded = base64url_encode(json_encode($payload)); //build the signature $key = 'secret'; $signature = hash_hmac('SHA256',"$headers_encoded.$payload_encoded",$key); //build and return the token $token = "$headers_encoded.$payload_encoded.$signature"; echo $token; </code></pre> <p>The <code>base64url_encode</code> function:</p> <pre><code>function base64url_encode($data) { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); } </code></pre> <p>My headers and payload perfectly match the <a href="http://jwt.io/" rel="noreferrer">validation site's</a> default JWT, but my signature doesn't match so my token is flagged as invalid. This standard seems really straightforward so what's wrong with my signature?</p>
33,773,850
3
0
null
2015-11-18 06:47:15.297 UTC
11
2021-10-06 20:08:22.49 UTC
null
null
null
null
3,977,061
null
1
24
php|json|authentication|jwt|sha
24,116
<p>I solved it! I did not realize that the signature itself needs to be base64 encoded. In addition, I needed to set the last optional parameter of the <code>hash_hmac</code> function to <code>$raw_output=true</code> (see <a href="http://php.net/manual/en/function.hash-hmac.php" rel="noreferrer">the docs</a>. In short I needed to change my code from the original:</p> <pre><code>//build the signature $key = 'secret'; $signature = hash_hmac('sha256',&quot;$headers_encoded.$payload_encoded&quot;,$key); //build and return the token $token = &quot;$headers_encoded.$payload_encoded.$signature&quot;; </code></pre> <p>To the corrected:</p> <pre><code>//build the signature $key = 'secret'; $signature = hash_hmac('sha256',&quot;$headers_encoded.$payload_encoded&quot;,$key,true); $signature_encoded = base64url_encode($signature); //build and return the token $token = &quot;$headers_encoded.$payload_encoded.$signature_encoded&quot;; echo $token; </code></pre>
34,507,160
How can I handle an event to open a window in react js?
<p>I want to open a window after clicking the fshare:</p> <p>My <code>render()</code> return is like this</p> <pre><code>&lt;Modal.Footer&gt; &lt;img src=&quot;/static/img/fshare.png&quot; onClick={this.fbShare} /&gt; &lt;Button onClick={this.hide}&gt;Close&lt;/Button&gt; &lt;/Modal.Footer&gt; </code></pre> <p>I am creating a function</p> <pre><code>fbShare: function(event) { }, </code></pre> <p>And I want to add the following code inside the function that basically opens a new window to share in Facebook:</p> <pre><code>window.open('https://www.facebook.com/dialog/feed?app_id=xxxxxxxxe='sharer', 'toolbar=0,status=0,width=548,height=325');&quot; target=&quot;_parent&quot; href=&quot;javascript: void(0)&quot;&gt; </code></pre> <p>But I am confused with how to handle this event.</p>
34,507,414
2
0
null
2015-12-29 08:17:40.56 UTC
2
2021-10-25 11:08:38.23 UTC
2020-12-23 00:39:22.463 UTC
null
1,783,163
null
4,796,134
null
1
14
reactjs|event-handling|modal-dialog
78,643
<p>You are on the right way!</p> <p>Is it something you need? I prepared the example: click <a href="https://jsfiddle.net/69z2wepo/25653/" rel="noreferrer" title="jsfiddle">here</a></p> <pre><code>var Example = React.createClass({ fbShare: function() { window.open('http://www.facebook.com/sharer.php?s=100&amp;p[title]=Fb Share&amp;p[summary]=Facebook share popup&amp;p[url]=javascript:fbShare("http://jsfiddle.net/stichoza/EYxTJ/")&amp;p[images][0]="http://goo.gl/dS52U"', 'sharer', 'toolbar=0,status=0,width=548,height=325'); }, render: function() { return (&lt;div&gt; &lt;img src="http://pasadenainstitute.com/fb-shareTransp122x42.png" onClick={this.fbShare} /&gt; &lt;/div&gt;); } }); ReactDOM.render( &lt;Example /&gt;, document.getElementById('container') ); </code></pre>
54,851,861
How do I activate type annotations hints in Kotlin like depicted?
<p>I was able to activate this option once in my MacOS intellij version, but could never find this option anymore, I forgot its name.</p> <p>I know there is the CTRL+SHIFT+P alternative to this, but it is not as user-friendly.</p> <p>How can I activate the option to make intellij show me all the inferred types like depicted? This screenshot came out of the intellij where I was able to put it showing "type hints" like this, so it is possible. I just don't remember where to find this option anymore so I can activate in all my other intellij's.</p> <p><a href="https://i.stack.imgur.com/tiqjc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tiqjc.png" alt="enter image description here"></a></p>
54,852,497
3
0
null
2019-02-24 12:26:44.413 UTC
20
2022-07-08 09:11:26.923 UTC
null
null
null
null
2,207,729
null
1
46
intellij-idea|kotlin
11,355
<p>For <strong>IntelliJ (2022.1)</strong> onwards got to <code>Settings -&gt; Editor -&gt; Inlay Hints -&gt; Types -&gt; Kotlin -&gt; Types -&gt; Parameter hints -&gt; Local variable types</code> or check all.</p> <p>I think you are allowed to say, that this feature configuration is a little bit hidden in the menues and was moved a lot between different releases.</p> <p><a href="https://i.stack.imgur.com/JYPel.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JYPel.png" alt="Configure parameter name hints" /></a></p> <p>Thanks to @vitfo, adding this to the top here. For <strong>IntelliJ (2020.3)</strong> onwards got to: <code>Settings -&gt; Editor -&gt; Inlay Hints -&gt; Kotlin -&gt; Parameter hints -&gt; Types</code></p> <p>In <strong>IntelliJ 2019.3.1</strong> onwards it is located at: <code>Settings -&gt; Editor -&gt; Inlay Hints -&gt; Kotlin -&gt; &quot;Show parameter hints&quot;</code> (thanks to @zero).</p> <p><strong>Original Answer for IntelliJ 2018</strong><br /> Go to <code>Settings -&gt; Editor -&gt; General -&gt; Appearance -&gt; &quot;Show parameter name hints&quot; -&gt; Configure... -&gt; Language: Kotlin -&gt; Options -&gt; &quot;Show local variable type hints&quot;</code></p>
29,087,882
Android Studio Run/Debug configuration error: Module not specified
<p>I am getting a 'Module not specified' error in my run config. I have no module showing in the drop down yet I can see my module no probs. The issue came about when I refactored my module name, changed the settings.gradle to new name.</p> <p>Now when I go to project structure and select my module nothing shows in the screen, not even an error.</p> <p>I'm not 100% sure, but the icon beside my module looks like a folder with a cup and not a folder with a phone.</p> <p>My exact steps -</p> <ol> <li>Open in Android view</li> <li>Refactor directory name</li> <li>refactor module name</li> <li>change settings.gradle contents: name to new name</li> </ol>
29,087,954
23
0
null
2015-03-16 22:11:01.917 UTC
31
2021-11-21 02:25:27.42 UTC
2017-09-08 14:17:22.853 UTC
null
2,350,083
null
510,981
null
1
174
android|android-studio|module|gradle
217,923
<p>never mind, i changed the name in settings.gradle and synced and then changed it back and synced again and it inexplicably worked this time.</p>
36,493,977
Flip a Bitmap image horizontally or vertically
<p>By using this code we can rotate an image:</p> <pre><code>public static Bitmap RotateBitmap(Bitmap source, float angle) { Matrix matrix = new Matrix(); matrix.postRotate(angle); return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); } </code></pre> <p>But how can we flip an image horizontally or vertically?</p>
36,494,192
6
0
null
2016-04-08 07:31:26.96 UTC
4
2020-09-01 06:42:35.83 UTC
2016-04-08 07:53:40.503 UTC
null
360,211
null
5,138,179
null
1
33
java|android|image|matrix|android-bitmap
24,643
<p>Given <code>cx,cy</code> is the centre of the image:</p> <p>Flip in x:</p> <pre><code>matrix.postScale(-1, 1, cx, cy); </code></pre> <p>Flip in y:</p> <pre><code>matrix.postScale(1, -1, cx, cy); </code></pre> <p>Altogether:</p> <pre><code>public static Bitmap createFlippedBitmap(Bitmap source, boolean xFlip, boolean yFlip) { Matrix matrix = new Matrix(); matrix.postScale(xFlip ? -1 : 1, yFlip ? -1 : 1, source.getWidth() / 2f, source.getHeight() / 2f); return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); } </code></pre>
40,476,233
How to mock an async repository with Entity Framework Core
<p>I'm trying to create a unit test for a class that calls into an async repository. I'm using ASP.NET Core and Entity Framework Core. My generic repository looks like this.</p> <pre><code>public class EntityRepository&lt;TEntity&gt; : IEntityRepository&lt;TEntity&gt; where TEntity : class { private readonly SaasDispatcherDbContext _dbContext; private readonly DbSet&lt;TEntity&gt; _dbSet; public EntityRepository(SaasDispatcherDbContext dbContext) { _dbContext = dbContext; _dbSet = dbContext.Set&lt;TEntity&gt;(); } public virtual IQueryable&lt;TEntity&gt; GetAll() { return _dbSet; } public virtual async Task&lt;TEntity&gt; FindByIdAsync(int id) { return await _dbSet.FindAsync(id); } public virtual IQueryable&lt;TEntity&gt; FindBy(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate) { return _dbSet.Where(predicate); } public virtual void Add(TEntity entity) { _dbSet.Add(entity); } public virtual void Delete(TEntity entity) { _dbSet.Remove(entity); } public virtual void Update(TEntity entity) { _dbContext.Entry(entity).State = EntityState.Modified; } public virtual async Task SaveChangesAsync() { await _dbContext.SaveChangesAsync(); } } </code></pre> <p>Then I have a service class that calls FindBy and FirstOrDefaultAsync on an instance of the repository:</p> <pre><code> public async Task&lt;Uri&gt; GetCompanyProductURLAsync(Guid externalCompanyID, string productCode, Guid loginToken) { CompanyProductUrl companyProductUrl = await _Repository.FindBy(u =&gt; u.Company.ExternalCompanyID == externalCompanyID &amp;&amp; u.Product.Code == productCode.Trim()).FirstOrDefaultAsync(); if (companyProductUrl == null) { return null; } var builder = new UriBuilder(companyProductUrl.Url); builder.Query = $"-s{loginToken.ToString()}"; return builder.Uri; } </code></pre> <p>I'm trying to mock the repository call in my test below:</p> <pre><code> [Fact] public async Task GetCompanyProductURLAsync_ReturnsNullForInvalidCompanyProduct() { var companyProducts = Enumerable.Empty&lt;CompanyProductUrl&gt;().AsQueryable(); var mockRepository = new Mock&lt;IEntityRepository&lt;CompanyProductUrl&gt;&gt;(); mockRepository.Setup(r =&gt; r.FindBy(It.IsAny&lt;Expression&lt;Func&lt;CompanyProductUrl, bool&gt;&gt;&gt;())).Returns(companyProducts); var service = new CompanyProductService(mockRepository.Object); var result = await service.GetCompanyProductURLAsync(Guid.NewGuid(), "wot", Guid.NewGuid()); Assert.Null(result); } </code></pre> <p>However, when the test executes the call to the repository, I get the following error:</p> <pre><code>The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IEntityQueryProvider can be used for Entity Framework asynchronous operations. </code></pre> <p>How can I properly mock the repository to get this to work?</p>
40,491,640
9
3
null
2016-11-07 23:01:15.59 UTC
27
2022-09-12 11:38:40.103 UTC
2016-11-07 23:13:56.543 UTC
null
5,233,410
null
6,162,143
null
1
99
c#|unit-testing|asp.net-core|moq|entity-framework-core
54,624
<p>Thanks to @Nkosi for pointing me to a link with an example of doing the same thing in EF 6: <a href="https://msdn.microsoft.com/en-us/library/dn314429.aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/dn314429.aspx</a>. This didn't work exactly as-is with EF Core, but I was able to start with it and make modifications to get it working. Below are the test classes that I created to "mock" IAsyncQueryProvider:</p> <pre><code>internal class TestAsyncQueryProvider&lt;TEntity&gt; : IAsyncQueryProvider { private readonly IQueryProvider _inner; internal TestAsyncQueryProvider(IQueryProvider inner) { _inner = inner; } public IQueryable CreateQuery(Expression expression) { return new TestAsyncEnumerable&lt;TEntity&gt;(expression); } public IQueryable&lt;TElement&gt; CreateQuery&lt;TElement&gt;(Expression expression) { return new TestAsyncEnumerable&lt;TElement&gt;(expression); } public object Execute(Expression expression) { return _inner.Execute(expression); } public TResult Execute&lt;TResult&gt;(Expression expression) { return _inner.Execute&lt;TResult&gt;(expression); } public IAsyncEnumerable&lt;TResult&gt; ExecuteAsync&lt;TResult&gt;(Expression expression) { return new TestAsyncEnumerable&lt;TResult&gt;(expression); } public Task&lt;TResult&gt; ExecuteAsync&lt;TResult&gt;(Expression expression, CancellationToken cancellationToken) { return Task.FromResult(Execute&lt;TResult&gt;(expression)); } } internal class TestAsyncEnumerable&lt;T&gt; : EnumerableQuery&lt;T&gt;, IAsyncEnumerable&lt;T&gt;, IQueryable&lt;T&gt; { public TestAsyncEnumerable(IEnumerable&lt;T&gt; enumerable) : base(enumerable) { } public TestAsyncEnumerable(Expression expression) : base(expression) { } public IAsyncEnumerator&lt;T&gt; GetEnumerator() { return new TestAsyncEnumerator&lt;T&gt;(this.AsEnumerable().GetEnumerator()); } IQueryProvider IQueryable.Provider { get { return new TestAsyncQueryProvider&lt;T&gt;(this); } } } internal class TestAsyncEnumerator&lt;T&gt; : IAsyncEnumerator&lt;T&gt; { private readonly IEnumerator&lt;T&gt; _inner; public TestAsyncEnumerator(IEnumerator&lt;T&gt; inner) { _inner = inner; } public void Dispose() { _inner.Dispose(); } public T Current { get { return _inner.Current; } } public Task&lt;bool&gt; MoveNext(CancellationToken cancellationToken) { return Task.FromResult(_inner.MoveNext()); } } </code></pre> <p>And here is my updated test case that uses these classes:</p> <pre><code>[Fact] public async Task GetCompanyProductURLAsync_ReturnsNullForInvalidCompanyProduct() { var companyProducts = Enumerable.Empty&lt;CompanyProductUrl&gt;().AsQueryable(); var mockSet = new Mock&lt;DbSet&lt;CompanyProductUrl&gt;&gt;(); mockSet.As&lt;IAsyncEnumerable&lt;CompanyProductUrl&gt;&gt;() .Setup(m =&gt; m.GetEnumerator()) .Returns(new TestAsyncEnumerator&lt;CompanyProductUrl&gt;(companyProducts.GetEnumerator())); mockSet.As&lt;IQueryable&lt;CompanyProductUrl&gt;&gt;() .Setup(m =&gt; m.Provider) .Returns(new TestAsyncQueryProvider&lt;CompanyProductUrl&gt;(companyProducts.Provider)); mockSet.As&lt;IQueryable&lt;CompanyProductUrl&gt;&gt;().Setup(m =&gt; m.Expression).Returns(companyProducts.Expression); mockSet.As&lt;IQueryable&lt;CompanyProductUrl&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(companyProducts.ElementType); mockSet.As&lt;IQueryable&lt;CompanyProductUrl&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(() =&gt; companyProducts.GetEnumerator()); var contextOptions = new DbContextOptions&lt;SaasDispatcherDbContext&gt;(); var mockContext = new Mock&lt;SaasDispatcherDbContext&gt;(contextOptions); mockContext.Setup(c =&gt; c.Set&lt;CompanyProductUrl&gt;()).Returns(mockSet.Object); var entityRepository = new EntityRepository&lt;CompanyProductUrl&gt;(mockContext.Object); var service = new CompanyProductService(entityRepository); var result = await service.GetCompanyProductURLAsync(Guid.NewGuid(), "wot", Guid.NewGuid()); Assert.Null(result); } </code></pre>
47,637,469
How to mat-button-toggle by default selected in angular
<p>How can I set default selected last button in toggle group.<br> This is my code.</p> <pre><code>&lt;mat-button-toggle-group #group="matButtonToggleGroup"&gt; &lt;mat-button-toggle value="Heritage"&gt; &lt;span&gt;Heritage&lt;/span&gt; &lt;/mat-button-toggle&gt; &lt;mat-button-toggle value="Nature"&gt; &lt;span&gt;Nature&lt;/span&gt; &lt;/mat-button-toggle&gt; &lt;mat-button-toggle value="People"&gt; &lt;span&gt;People&lt;/span&gt; &lt;/mat-button-toggle&gt; &lt;mat-button-toggle value="All"&gt; &lt;span&gt;All&lt;/span&gt; &lt;/mat-button-toggle&gt; &lt;/mat-button-toggle-group&gt; </code></pre>
47,991,657
7
0
null
2017-12-04 16:11:17.597 UTC
4
2022-02-08 15:07:12.3 UTC
2020-08-14 19:09:06.56 UTC
null
4,308,163
null
4,308,163
null
1
60
angular|angular-material|angular5
62,309
<p>I fixed it. Simply add the <code>value</code> attribute to the <code>mat-button-toggle-group</code> tag.</p> <pre><code>&lt;mat-button-toggle-group #group="matButtonToggleGroup" value="All"&gt; &lt;mat-button-toggle value="Heritage"&gt; &lt;span&gt;Heritage&lt;/span&gt; &lt;/mat-button-toggle&gt; &lt;mat-button-toggle value="Nature"&gt; &lt;span&gt;Nature&lt;/span&gt; &lt;/mat-button-toggle&gt; &lt;mat-button-toggle value="People"&gt; &lt;span&gt;People&lt;/span&gt; &lt;/mat-button-toggle&gt; &lt;mat-button-toggle value="All"&gt; &lt;span&gt;All&lt;/span&gt; &lt;/mat-button-toggle&gt; </code></pre> <p></p>
38,768,567
How to print object in Node JS
<p>In the below code (running on Node JS) I am trying to print an object obtained from an external API using <code>JSON.stringify</code> which results in an error: </p> <blockquote> <p>TypeError: Converting circular structure to JSON</p> </blockquote> <p>I have looked at the questions on this topic, but none could help. Could some one please suggest: </p> <p>a) How I could obtain <code>country</code> value from the <code>res</code> object ?</p> <p>b) How I could <strong>print</strong> the entire object itself ?</p> <pre><code> http.get('http://ip-api.com/json', (res) =&gt; { console.log(`Got response: ${res.statusCode}`); console.log(res.country) // *** Results in Undefined console.log(JSON.stringify(res)); // *** Resulting in a TypeError: Converting circular structure to JSON res.resume(); }).on('error', (e) =&gt; { console.log(`Got error: ${e.message}`); }); </code></pre>
38,771,700
8
3
null
2016-08-04 13:22:11.003 UTC
2
2022-06-22 18:35:30.303 UTC
null
null
null
null
2,652,541
null
1
27
javascript|json|node.js
91,433
<p>By using the http <code>request</code> client, I am able to print the JSON object as well as print the <code>country</code> value. Below is my updated code.</p> <pre><code>var request = require('request'); request('http://ip-api.com/json', function (error, response, body) { if (!error &amp;&amp; response.statusCode == 200) { console.log(response.body); // Prints the JSON object var object = JSON.parse(body); console.log(object['country']) // Prints the country value from the JSON object } }); </code></pre>
31,608,770
TABLEAU: calc field to get the last value available
<p>I'm using Tableau Desktop, my data are like this:</p> <pre><code>KPI,date,monthValue coffee break,01/06/2015,10.50 coffee break,01/07/2015,8.30 </code></pre> <p>and I want to build a table like this</p> <pre><code>KPI, year(date), last value coffee time, 2015, 8.30 </code></pre> <p>How can I set a calculated field in order to show me the last value available in that year? I tried to do:</p> <pre><code>LOOKUP([MonthValue], LAST()) </code></pre> <p>But it didn't work and tells me 'cannot mix aggregate and non-aggregate', so I did:</p> <pre><code>LOOKUP(sum([MonthValue]), LAST()) </code></pre> <p>But it didn't work too. How should I proceed?</p>
31,609,712
1
0
null
2015-07-24 10:56:10.253 UTC
null
2015-08-27 09:54:00.193 UTC
2015-08-27 09:54:00.193 UTC
null
1,213,296
null
5,151,915
null
1
4
field|tableau-api
48,359
<p>If you are using Tableau 9 then you can do this with an LOD calc that looks for the max value in your date field and then checks if the current date value is the same as the max date value.</p> <pre><code>[Date] == {fixed: max([Date])} </code></pre> <p>As you can see in the example below when you use the calc as a filter you will only get the last row from your example above.</p> <p><a href="https://i.stack.imgur.com/zmVUC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zmVUC.png" alt="enter image description here"></a></p> <p><strong>UPDATE:</strong> to get the values per year you can do something like:</p> <p>Here I am using a table calculation to find the max date per year and then ranking those dates and filtering down to the latest date in each year (which will be the one that has a rank equal to 1).</p> <p><a href="https://i.stack.imgur.com/cpu4i.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cpu4i.png" alt="enter image description here"></a></p> <p><code>!max date</code> is <code>WINDOW_MAX(ATTR(Date))</code></p> <p><code>!rank</code> is <code>RANK(Date)</code></p> <p>You need to make sure that the table calculations are computer in the correct way (in this case across the values of each year).</p>
35,479,080
How do I turn a Windows feature on/off from the command line in Windows 10?
<p>In Windows 10 and from "Programs and Features", you can turn Windows features on or off and then initiate a download and installation. I wish to turn ".NET Framework 3.5" ON and have it downloaded and installed, but I need to do it via e.g. a PowerShell script or via a command. I need to use the command line.</p> <p>How can this be achieved?</p> <p><a href="https://i.stack.imgur.com/ddT5J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ddT5J.png" alt="Enter image description here"></a></p>
37,999,562
3
0
null
2016-02-18 10:37:44.437 UTC
3
2019-12-10 16:47:06.63 UTC
2019-05-04 14:43:01.86 UTC
null
63,550
null
2,448,495
null
1
16
powershell|windows-10
41,493
<p>Run a command prompt <strong>as an administrator</strong> and use:</p> <pre><code>dism /online /Get-Features </code></pre> <p>This will display the feature names since they don't always match up with what you're seeing in that visual feature list. It will also show which are currently enabled/disabled. Once you find the feature that you'd like to enable (<strong>NetFx3</strong> in this case), run this:</p> <pre><code>dism /online /Enable-Feature /FeatureName:NetFx3 </code></pre> <p>And as Richard stated, you can then disable a feature by simply switching "Enable" to "Disable" ex.</p> <pre><code>dism /online /Disable-Feature /FeatureName:NetFx3 </code></pre> <p><strong>Note: Sometimes a restart is required to see changes with windows features.</strong></p>
35,369,419
How to use images in css with Webpack
<p>I am making a React w/ Webpack setup and am struggling to do what seems like should be a simple task. I want webpack to include images, and minimize them like I with gulp but I can't figure it out. I just want to be able to link an image in my css like so:</p> <pre><code>/* ./src/img/background.jpg */ body { background: url('./img/background.jpg'); } </code></pre> <p>I have all of my css/js/img folders inside a src folder. Webpack outputs to a dist folder, but I can't figure out how to get images there.</p> <p>Here is my webpack setup:</p> <pre><code> var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'cheap-eval-source-map', entry: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/dev-server', './src/index.js' ], output: { path: path.join(__dirname, 'dist'), // publicPath: './dist', filename: 'bundle.js' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' }) ], module: { loaders: [{ exclude: /node_modules/, test: /\.js?$/, loader: 'babel' }, { test: /\.scss$/, loader: 'style!css!sass' }, { test: /\.(png|jpg)$/, loader: 'file-loader' }] }, devServer: { historyApiFallback: true, contentBase: './dist', hot: true } }; </code></pre>
35,369,698
2
0
null
2016-02-12 18:09:45.36 UTC
12
2020-04-04 12:17:14.073 UTC
null
null
null
null
3,737,841
null
1
56
css|image|reactjs|webpack|loader
61,026
<p>I was stuck with similar issue and found that you can use <a href="https://github.com/webpack-contrib/url-loader" rel="noreferrer"><code>url-loader</code></a> to resolve <code>"url()"</code> statements in your CSS as any other require or import statements.</p> <p>To install it:</p> <p><code>npm install url-loader --save-dev</code> </p> <p>It will install the loader that can convert resolved paths as BASE64 strings.</p> <p>In your webpack config file use url-loader in loaders</p> <pre><code>{ test: /\.(png|jpg)$/, loader: 'url-loader' } </code></pre> <p>Also make sure that you are specifying your public path correctly and path of images you are trying to load.</p>
44,480,740
How to save a Docker container state
<p>I'm trying to learn the ins and outs of Docker, and I'm confused by the prospect of saving an image. </p> <p>I ran the basic Ubuntu image, installed Anaconda Python and a few other things...so now what's the best way to save my progress? Save, commit, export? </p> <p>None of these seem to work the same way as VirtualBox, which presents an obvious save-state file for your virtual machine.</p>
44,480,870
4
0
null
2017-06-11 05:40:56.16 UTC
31
2021-09-22 18:40:21.18 UTC
2018-08-06 12:23:11.1 UTC
null
63,550
null
3,325,401
null
1
116
docker
119,220
<p>The usual way is at least through a <a href="https://docs.docker.com/engine/reference/commandline/commit/" rel="noreferrer"><code>docker commit</code></a>: that will freeze the state of your container into a new image.</p> <p>Note: As <a href="https://stackoverflow.com/questions/44480740/how-to-saving-a-docker-container-state/44480870#comment78796162_44480870">commented</a> by <a href="https://stackoverflow.com/users/1316524/anchovylegend">anchovylegend</a>, this is not the best practice, and using a Dockerfile allows you to formally modeling the image content and ensure you can rebuild/reproduce its initial state.</p> <p>You can then list that image locally with <a href="https://docs.docker.com/engine/reference/commandline/images/" rel="noreferrer"><code>docker images</code></a>, and run it again.</p> <p>Example:</p> <pre><code>$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c3f279d17e0a ubuntu:12.04 /bin/bash 7 days ago Up 25 hours desperate_dubinsky 197387f1b436 ubuntu:12.04 /bin/bash 7 days ago Up 25 hours focused_hamilton $ docker commit c3f279d17e0a svendowideit/testimage:version3 f5283438590d $ docker images REPOSITORY TAG ID CREATED SIZE svendowideit/testimage version3 f5283438590d 16 seconds ago 335.7 MB </code></pre> <hr> <p>After that, <a href="https://docs.docker.com/registry/deploying/" rel="noreferrer">if you have deployed a registry server</a>, you can push your image to said server.</p>
65,837,109
When should I use "git push --force-if-includes"
<p>When I want to force push, I nearly always use <code>--force-with-lease</code>. Today I upgraded to Git 2.30 and discovered a new option: <code>--force-if-includes</code>.</p> <p>After reading the <a href="https://git-scm.com/docs/git-push" rel="noreferrer">updated documentation</a>, it's still not entirely clear to me under which circumstances I would use <code>--force-if-includes</code> instead of <code>--force-with-lease</code> like I usually do.</p>
65,839,129
3
0
null
2021-01-21 23:11:32.417 UTC
9
2022-03-09 18:45:45.01 UTC
2021-04-17 02:48:15.723 UTC
null
184,546
null
184,546
null
1
15
git|git-push
2,433
<p>The <code>--force-if-includes</code> option is, as you've noted, new. If you've never needed it before, you don't need it now. So the shortest answer to &quot;when should I use this&quot; would be &quot;never&quot;. The <em>recommended</em> answer is (or will be once it's proven?) <em>always</em>. (I'm not yet convinced one way or the other, myself.)</p> <p>A blanket &quot;always&quot; or &quot;never&quot; is not very useful though. Let's look at where you might want to use it. It is, strictly speaking, never <em>necessary</em> because all it does is modify <code>--force-with-lease</code> slightly. So we already have <code>--force-with-lease</code> in effect, if <code>--force-if-includes</code> is going to be used.<sup>1</sup> Before we look at <code>--force-with-includes</code> we should cover how <code>--force-with-lease</code> actually works. What <em>problem</em> are we trying to solve? What are our &quot;use cases&quot; or &quot;user stories&quot; or whatever the latest buzzwords might be when someone is reading this later?</p> <p>(Note: if you're already familiar with all of this, you can search for the next force-if-includes string to skip the next few sections, or just jump to the bottom and then scroll up to the section header.)</p> <p>The fundamental problem we have here is one of <em>atomicity</em>. Git is, in the end, mostly—or at least significantly—a database, and any good database has four properties for which we have the mnemonic <a href="https://en.wikipedia.org/wiki/ACID" rel="noreferrer">ACID</a>: Atomicity, Consistency, Isolation, and Durability. Git doesn't exactly achieve any or all of these on its own: for instance, for the Durability property, it relies (at least partly) on the OS to provide it. But three of these—the C, I, and D ones—are local within a Git repository in the first place: if your computer crashes, <em>your</em> copy of the database may or may not be intact, recoverable, or whatever, depending on the state of your own hardware and OS.</p> <p>Git is not, however, just a local database. It's a <em>distributed</em> one, distributed via replication, and its unit of atomicity—the commit—is spread out across multiple replications of the database. When we make a new commit locally, we can send it to some other copy or copies of the database, using <code>git push</code>. Those copies will try to provide their own ACID behavior, locally on <em>those</em> computers. But we'd like to preserve atomicity <em>during the push itself</em>.</p> <p>We can get this in several ways. One way is to start with the idea that every commit has a globally (or universally) unique identifier: a GUID or UUID.<sup>2</sup> (I'll use the UUID form here.) I can safely give you a new commit I've made as long as we both agree that it gets the UUID I gave it, that you didn't have.</p> <p>But, while Git does use these UUIDs to <em>find</em> the commits, Git also needs to have a <em>name</em> for the commit—well, for the <em>last</em> commit in some chain. This guarantees that whoever is using the repository has a way to find the commit: the name finds the <em>last</em> one in some chain, from which we find all the earlier ones in the same chain.</p> <p>If we both use the same <em>name</em>, we have a problem. Let's say we're using the name <code>main</code> to find commit <code>b789abc</code>, and they're using it to find the commit <code>a123456</code>.</p> <p>The solution we use with <code>git fetch</code> here is simple: we assign a name to their Git repository, e.g., <code>origin</code>. Then, when we get some new commit(s) from them, we take <em>their</em> name—the one that finds the last of these commits in some chain, that is—and <em>rename</em> it. If they used the name <code>main</code> to find that tip commit, we rename that to <code>origin/main</code>. We create or update our own <code>origin/main</code> to remember <em>their</em> commits, and it does not mess with our own <code>main</code>.</p> <p>But, when we're going the other way—pushing our commits to them—Git doesn't apply this idea. Instead, we ask them to update their <code>main</code> directly. We hand over commit <code>b789abc</code> for instance, and then ask them to set <em>their</em> <code>main</code> to <code>b789abc</code>. What they do, to make sure that they don't <em>lose</em> their <code>a123456</code> commit, is make sure that <code>a123456</code> is part of the <em>history</em> of our commit <code>b789abc</code>:</p> <pre><code> ... &lt;-a123456 &lt;-b789abc &lt;--main </code></pre> <p>Since our <code>main</code> points to <code>b789abc</code>, and <code>b789abc</code> has <code>a123456</code> as its parent, then having <em>them</em> update <em>their</em> <code>main</code> to point to <code>b789abc</code> is &quot;safe&quot;. For this to really be safe, <em>they</em> have to atomically replace their <code>main</code>, but we just leave that up to them.</p> <p>This method of <em>adding</em> commits to some remote Git repository works fine. What <em>doesn't</em> work is the case where we'd like to <em>remove</em> their <code>a123456</code>. We find there is something wrong or bad with <code>a123456</code>. Instead of making a simple correction, <code>b789abc</code>, that <em>adds on</em> to the branch, we make our <code>b789abc</code> so that it <em>bypasses</em> the bad commit:</p> <pre><code>... &lt;-something &lt;-a123456 &lt;--main </code></pre> <p>becomes:</p> <pre><code>... &lt;-something &lt;-b789abc &lt;--main \ a123456 ??? [no name, hence abandoned] </code></pre> <p>We then try to send this commit to them, and they reject our attempt with the gripe that it's not a &quot;fast-forward&quot;. We add <code>--force</code> to tell them to do the replacement anyway, and—if we have appropriate permissions<sup>3</sup>—their Git obeys. This effectively <em>drops</em> the bad commit from their clone, just as we dropped it from ours.<sup>4</sup></p> <hr /> <p><sup>1</sup>As the documentation you linked notes, <code>--force-if-includes</code> <em>without</em> <code>--force-with-lease</code> is just ignored. That is, <code>--force-if-includes</code> doesn't turn <em>on</em> <code>--force-with-lease</code> <em>for</em> you: you have to specify both.</p> <p><sup>2</sup>These are the <em>hash IDs</em>, and they need to be unique across all Gits that will ever meet and share IDs, but not across two Gits that never meet. There, we can safely have what I call &quot;doppelgängers&quot;: commits or other internal objects with the same hash ID, but different content. Still, it's best to just make them truly unique.</p> <p><sup>3</sup>Git as it is, &quot;out of the box&quot;, does not have this kind of permissions checking, but hosting providers like GitHub and Bitbucket add it, as part of their value-adding thing to convince us to use their hosting systems.</p> <p><sup>4</sup>The un-find-able commit doesn't actually <em>go away</em> right away. Instead, Git leaves this for a later housekeeping <code>git gc</code> operation. Also, dropping a commit from some name may still leave that commit reachable from other names, or via log entries that Git keeps for each name. If so, the commit will stick around longer, perhaps even forever.</p> <hr /> <h3>So far so good, but ...</h3> <p>The concept of a force-push is fine as far as it goes, but that's not far enough. Suppose we have a repository, hosted somewhere (GitHub or whatever), that receives <code>git push</code> requests. Suppose further that <em>we are not the only person / group doing pushes</em>.</p> <p>We <code>git push</code> some new commit, then discover it's bad and want to replace it with a new and improved commit immediately, so we take a few seconds or minutes—however long it takes to make the new improved commit—and get that in place and run <code>git push --force</code>. For concreteness, let's say this whole thing takes us one minute, or 60 seconds.</p> <p>That's sixty seconds during which <em>someone else</em> might:<sup>5</sup></p> <ul> <li>fetch our bad commit from the hosting system;</li> <li>add a new commit of their own; and</li> <li><code>git push</code> the result.</li> </ul> <p>So at this point, we <em>think</em> the hosting system has:</p> <pre><code>...--F--G--H &lt;-- main </code></pre> <p>where commit <code>H</code> is bad and needs replacement with our new-and-improved <code>H'</code>. But in fact, they now have:</p> <pre><code>...--F--G--H--I &lt;-- main </code></pre> <p>where commit <code>I</code> is from this other faster committer. Meanwhile, we now have, in <em>our</em> repository, the sequence:</p> <pre><code>...--F--G--H' &lt;-- main \ H ??? </code></pre> <p>where <code>H</code> is our bad commit, that we're about to replace. We now run <code>git push --force</code> and since we are allowed to force-push, the hosting provider Git accepts our new <code>H'</code> as the last commit in <em>their</em> <code>main</code>, so that <em>they</em> now have:</p> <pre><code>...--F--G--H' &lt;-- main \ H--I ??? </code></pre> <p>The effect is that our <code>git push --force</code> removed not only our bad <code>H</code>, but their (presumably still good, or at least, wanted) <code>I</code>.</p> <hr /> <p><sup>5</sup>They might do this by rebasing a commit they'd already made, after finding their own <code>git push</code> blocked because they had based their commit on <code>G</code> originally. Their rebase automatically copied their new commit to the one we're calling <code>I</code> here, with no merge conflicts, enabling them to run <code>git push</code> in fewer seconds than it took us to make our fixed-up commit <code>H'</code>.</p> <hr /> <h3>Enter <code>--force-with-lease</code></h3> <p>The <code>--force-with-lease</code> option, which internally Git calls a &quot;compare and swap&quot;, allows us to send a commit to some other Git, and then <em>have them check</em> that their branch name—whatever it is—contains the hash ID that we think it contains.</p> <p>Let's add, to our drawing of our own repository, the <code>origin/*</code> names. Since we sent commit <code>H</code> to the hosting provider earlier, and they took it, we actually have <em>this</em> in our repository:</p> <pre><code>...--F--G--H' &lt;-- main \ H &lt;-- origin/main </code></pre> <p>When we use <code>git push --force-with-lease</code>, we have the option of controlling this <code>--force-with-lease</code> completely and exactly. The complete syntax for doing this is:</p> <pre><code>git push --force-with-lease=refs/heads/main:&lt;hash-of-H&gt; origin &lt;hash-of-H'&gt;:refs/heads/main </code></pre> <p>That is, we'll:</p> <ul> <li>send to <code>origin</code> commits ending with the one found via hash ID <code>H'</code>;</li> <li>ask them to update their name <code>refs/heads/main</code> (their <code>main</code> branch); and</li> <li>ask them to force this update, but <em>only</em> if their <code>refs/heads/main</code> currently has in it the hash ID of commit <code>H</code>.</li> </ul> <p>This gives us a chance to catch the case where some commit <code>I</code> has been added to their <code>main</code>. They, using the <code>--force-with-lease=refs/heads/main:&lt;hash&gt;</code> part, <em>check</em> their <code>refs/heads/main</code>. If it's not the given <code>&lt;hash&gt;</code>, they refuse the entire transaction, keeping their database intact: they retain commits <code>I</code> and <code>H</code>, and drop our new commit <code>H'</code> on the floor.<sup>6</sup></p> <p>The overall transaction—the forced-with-lease update of their <code>main</code>—has locking inserted so that if someone else is attempting to push some commit (perhaps <code>I</code>) now, the someone-else gets held off until we finish—fail or succeed—with our <code>--force-with-lease</code> operation.</p> <p>We usually don't spell all this out, though. Usually we would just run:</p> <pre><code>git push --force-with-lease origin main </code></pre> <p>Here, <code>main</code> provides both the hash ID of the last commit we want sent—<code>H'</code>—and the ref-name we want them to update (<code>refs/heads/main</code>, based on the fact that our <code>main</code> is a branch name). The <code>--force-with-lease</code> has no <code>=</code> part so Git fills in the rest: the ref name is the one we want them to update—<code>refs/heads/main</code>—and the expected commit is the one in our corresponding <em>remote-tracking name</em>, i.e., the one in our own <code>refs/remotes/origin/main</code>.</p> <p>This all comes out the same: our <code>origin/main</code> provides the <code>H</code> hash, and our <code>main</code> provides the <code>H'</code> hash and all the other names. It's shorter and does the trick.</p> <hr /> <p><sup>6</sup>This depends on their Git having the &quot;quarantine&quot; feature in it, but anyone who has force-with-lease has this feature, I think. The quarantine feature dates back quite a while. Really-old versions of Git that lack the quarantine feature can leave the pushed commits around until a <code>git gc</code> collects them, even if they've never been incorporated.</p> <hr /> <h3>This finally brings us to <code>--force-if-includes</code></h3> <p>The example use case with <code>--force-with-lease</code> above shows how we replace a bad commit <em>we made</em>, when <em>we figured that out ourselves</em>. All we did was replace it and push. But this isn't how people always work.</p> <p>Suppose we make a bad commit, exactly as before. We wind up in this situation in our own local repository:</p> <pre><code>...--F--G--H' &lt;-- main \ H &lt;-- origin/main </code></pre> <p>But now we run <code>git fetch origin</code>. Perhaps we're trying to be conscientious; perhaps we're under stress and making mistakes. Whatever is going on, we now get:</p> <pre><code>...--F--G--H' &lt;-- main \ H--I &lt;-- origin/main </code></pre> <p>in our own repository.</p> <p>If we use <code>git push --force-with-lease=main:&lt;hash-of-H&gt; origin main</code>, the push will fail—like it <em>should</em>—because we explicitly state that we expect origin's <code>main</code> to contain hash ID <code>H</code>. As we can see from our <code>git fetch</code>, though, it actually has hash ID <code>I</code>. If we use the simpler:</p> <pre><code>git push --force-with-lease origin main </code></pre> <p>we'll ask the hosting-provider Git to swap out their <code>main</code> for commit <code>H'</code> if they have commit <code>I</code> as their last commit. Which, as we can see, they did: we got commit <code>I</code> into our repository. We just <em>forgot to put it in.</em></p> <p>So, our force-with-lease works and we wipe out commit <code>I</code> over on <code>origin</code>, all because we ran <code>git fetch</code> and forgot to check the result. The <code>--force-if-includes</code> option is <em>intended</em> to catch these cases.</p> <p>How it actually works is that it depends on Git's reflogs. It scans your own reflog for your <code>main</code> branch, and picks out commit <code>H</code> rather than <code>I</code>, to be used as the hash ID in <code>--force-with-lease</code>. This is similar to the fork-point mode for <code>git rebase</code> (though that one uses your remote-tracking reflog). I'm not 100% convinced, myself, that this <code>--force-if-includes</code> option is going to work in all cases: <code>--fork-point</code> does not, for instance. But it does work in <em>most</em> cases, and I suspect <code>--force-if-includes</code> will too.</p> <p>So, you can try it out by using it for all <code>--force-with-lease</code> pushes. All it does is use a different algorithm—one the Git folks are <em>hoping</em> will be more reliable, given the way humans are—to pick the hash ID for the atomic &quot;swap out your branch name if this matches&quot; operation that <code>--force-with-lease</code> uses. You can do this manually by providing the <code>=&lt;refname&gt;:&lt;hash&gt;</code> part of <code>--force-with-lease</code>, but the goal is to do it automatically, in a safer way than the current automatic way.</p>
49,454,202
React Native Unable to find a matching configuration of project (Build only)
<p>My react native build works fine when running <code>react-native run-android</code> or <code>cd android &amp;&amp; ./gradlew assembleDebug</code>. But I'll get the following for all every react native package I have installed when running <code>./gradlew assembleRelease</code></p> <pre><code>&gt; Could not resolve project :react-native-fbsdk. Required by: project :app &gt; Unable to find a matching configuration of project :react-native-fbsdk: - Configuration 'debugApiElements': - Required com.android.build.api.attributes.BuildTypeAttr 'releaseStaging' and found incompatible value 'debug'. - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'. - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required. - Required org.gradle.api.attributes.Usage 'java-runtime' and found incompatible value 'java-api'. - Configuration 'debugRuntimeElements': - Required com.android.build.api.attributes.BuildTypeAttr 'releaseStaging' and found incompatible value 'debug'. - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'. - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required. - Required org.gradle.api.attributes.Usage 'java-runtime' and found compatible value 'java-runtime'. - Configuration 'releaseApiElements': - Required com.android.build.api.attributes.BuildTypeAttr 'releaseStaging' and found incompatible value 'release'. - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'. - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required. - Required org.gradle.api.attributes.Usage 'java-runtime' and found incompatible value 'java-api'. - Configuration 'releaseRuntimeElements': - Required com.android.build.api.attributes.BuildTypeAttr 'releaseStaging' and found incompatible value 'release'. - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'. - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required. - Required org.gradle.api.attributes.Usage 'java-runtime' and found compatible value 'java-runtime'. </code></pre> <p>Upon getting more details by running <code>./gradlew assembleRelease --info</code> I found that this message is printed for all of my problematic packages:</p> <pre><code>file or directory '/path/to/my/project/node_modules/react-native-fcm/android/libs', not found </code></pre> <p>Looking in this folder, there is no "libs" folder, and settings.gradle does not tell it to point to a "libs" folder.</p> <pre><code>include ':react-native-fcm' project(':react-native-fcm').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fcm/android') </code></pre> <p>Should something be generating this folder? I do have <code>compile fileTree(dir: "libs", include: ["*.jar"])</code> in my app/build.gradle.</p> <p>For reference here are some important files:</p> <p>build.gradle</p> <pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() google() } dependencies { classpath 'com.android.tools.build:gradle:3.0.0' classpath 'com.google.gms:google-services:3.1.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() jcenter() configurations.all { resolutionStrategy { force 'com.facebook.android:facebook-android-sdk:4.28.0' } } maven { url "https://maven.google.com" } maven { url "https://jitpack.io" } maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$rootDir/../node_modules/react-native/android" } google() } } </code></pre> <p>app/build.gradle</p> <pre><code>apply plugin: "com.android.application" import com.android.build.OutputFile /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation * entryFile: "index.android.js", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"], * * // override which node gets called and with what additional arguments * nodeExecutableAndArgs: ["node"], * * // supply additional arguments to the packager * extraPackagerArgs: [] * ] */ project.ext.react = [ entryFile: "index.js" ] apply from: "../../node_modules/react-native/react.gradle" apply from: "../../node_modules/react-native-code-push/android/codepush.gradle" /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false android { compileSdkVersion 26 buildToolsVersion "26.0.2" defaultConfig { applicationId "com.gauge" minSdkVersion 16 targetSdkVersion 26 multiDexEnabled true versionCode 24 versionName "1.2.9" ndk { abiFilters "armeabi-v7a", "x86" } } signingConfigs { release { if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) { storeFile file(MYAPP_RELEASE_STORE_FILE) storePassword MYAPP_RELEASE_STORE_PASSWORD keyAlias MYAPP_RELEASE_KEY_ALIAS keyPassword MYAPP_RELEASE_KEY_PASSWORD } } } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86" } } buildTypes { debug { // Note: CodePush updates should not be tested in Debug mode as they are overriden by the RN packager. However, because CodePush checks for updates in all modes, we must supply a key. buildConfigField "String", "CODEPUSH_KEY", '""' } releaseStaging { minifyEnabled enableProguardInReleaseBuilds signingConfig signingConfigs.release buildConfigField "String", "CODEPUSH_KEY", '"1psOppiGxP0-cJpCePhMqgEjeO4l2533309f-9929-415c-8999-d7fda42c3857"' } release { minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" signingConfig signingConfigs.release buildConfigField "String", "CODEPUSH_KEY", '"0wPxPhihmtxxEdma3mU4zIGIFNdi2533309f-9929-415c-8999-d7fda42c3857"' } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -&gt; variant.outputs.each { output -&gt; // For each separate APK per architecture, set a unique version code as described here: // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits def versionCodes = ["armeabi-v7a":1, "x86":2] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = versionCodes.get(abi) * 1048576 + defaultConfig.versionCode } } } } buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'io.fabric.tools:gradle:1.22.1' } } apply plugin: 'io.fabric' repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { compile project(':react-native-code-push') compile (project(':react-native-code-push')) { exclude(group: 'android.arch.core') } compile project(':react-native-config') compile project(':react-native-vector-icons') compile(project(':react-native-radar')) { exclude group: 'com.google.android.gms' exclude module: 'support-v4' } compile project(':react-native-push-notification') compile project(':react-native-photo-view') compile project(':react-native-linear-gradient') compile project(':react-native-image-picker') compile project(':react-native-fcm') compile fileTree(dir: "libs", include: ["*.jar"]) compile(project(':react-native-fbsdk')){ exclude(group: 'com.facebook.android', module: 'facebook-android-sdk') } compile "com.facebook.android:facebook-android-sdk:4.22.1" compile "com.android.support:appcompat-v7:26.0.2" compile "com.facebook.react:react-native:+" // From node_modules compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') { transitive = true } compile 'com.android.support:multidex:1.0.2' compile "com.google.android.gms:play-services-location:12.0.0" } // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.compile into 'libs' } // ADD THIS AT THE BOTTOM apply plugin: 'com.google.gms.google-services' </code></pre> <p>settings.gradle</p> <pre><code>rootProject.name = 'MyProject' include ':app' include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android') include ':react-native-radar' project(':react-native-radar').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-radar/android') include ':react-native-push-notification' project(':react-native-push-notification').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-push-notification/android') include ':react-native-photo-view' project(':react-native-photo-view').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-photo-view/android') include ':react-native-linear-gradient' project(':react-native-linear-gradient').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-linear-gradient/android') include ':react-native-image-picker' project(':react-native-image-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-picker/android') include ':react-native-fcm' project(':react-native-fcm').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fcm/android') include ':react-native-code-push' project(':react-native-code-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-code-push/android/app') include ':react-native-intercom' project(':react-native-intercom').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-intercom/android') include ':react-native-video' project(':react-native-video').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-video/android') include ':react-native-fbsdk' project(':react-native-fbsdk').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fbsdk/android') include ':react-native-config' project(':react-native-config').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-config/android') </code></pre> <p>Update: I created a clean project with react-native init and ran the build and it created the same problem, so I guess it's something specific to my environment or there is some kind of temporary problem with the dependencies.</p> <p>Update: Built everything on a Windows machine. Same problem.</p> <p>Update: I have been able to get certain versions of this working, but not the main project. It might be due to these warnings:</p> <pre><code>Configuration 'compile' in project ':react-native-code-push' is deprecated. Use 'implementation' instead. WARNING: The specified Android SDK Build Tools version (23.0.1) is ignored, as it is below the minimum supported version (26.0.2) for Android Gradle Plugin 3.0.1. Android SDK Build Tools 26.0.2 will be used. To suppress this warning, remove "buildToolsVersion '23.0.1'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools. </code></pre>
49,699,547
6
0
null
2018-03-23 16:21:37.173 UTC
1
2021-06-01 06:35:07.897 UTC
2018-04-06 17:49:14.753 UTC
null
3,750,636
null
3,750,636
null
1
31
android|react-native|gradle|android-gradle-plugin|gradlew
53,731
<p>Upgrade Gradle and add <code>matchingFallbacks</code> to your non-standard build type. Your libraries do not know what build type to match.</p> <p>Eg.</p> <pre><code>buildType { ... mySpecialRelease { ... matchingFallbacks = ['release', 'debug'] } } </code></pre>
24,629,705
Django using get_user_model vs settings.AUTH_USER_MODEL
<p>Reading the Django Documentation:</p> <p><strong>get_user_model()</strong></p> <blockquote> <p>Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active User model – the custom User model if one is specified, or User otherwise.</p> <p>When you define a foreign key or many-to-many relations to the User model, you should specify the custom model using the AUTH_USER_MODEL setting.</p> </blockquote> <p>I'm confused with the above text. Should I be doing this:</p> <pre><code>author = models.ForeignKey(settings.AUTH_USER_MODEL) </code></pre> <p>or this...</p> <pre><code>author = models.ForeignKey(get_user_model()) </code></pre> <p>Both seem to work.</p>
24,630,589
6
0
null
2014-07-08 10:40:48.407 UTC
34
2022-07-08 23:16:35.417 UTC
null
null
null
null
578,822
null
1
135
python|django
91,272
<p>Using <code>settings.AUTH_USER_MODEL</code> will delay the retrieval of the actual model class until all apps are loaded. <code>get_user_model</code> will attempt to retrieve the model class at the moment your app is imported the first time. </p> <p><code>get_user_model</code> cannot guarantee that the <code>User</code> model is already loaded into the app cache. It might work in your specific setup, but it is a hit-and-miss scenario. If you change some settings (e.g. the order of <code>INSTALLED_APPS</code>) it might very well break the import and you will have to spend additional time debugging.</p> <p><code>settings.AUTH_USER_MODEL</code> will pass a string as the foreign key model, and if the retrieval of the model class fails at the time this foreign key is imported, the retrieval will be delayed until all model classes are loaded into the cache. </p>
2,541,865
Copying nested lists in Python
<p>I want to copy a 2D list, so that if I modify one list, the other is not modified.</p> <p>For a one-dimensional list, I just do this:</p> <pre><code>a = [1, 2] b = a[:] </code></pre> <p>And now if I modify <code>b</code>, <code>a</code> is not modified.</p> <p>But this doesn't work for a two-dimensional list:</p> <pre><code>a = [[1, 2],[3, 4]] b = a[:] </code></pre> <p>If I modify <code>b</code>, <code>a</code> gets modified as well.</p> <p>How do I fix this?</p>
2,541,882
3
12
null
2010-03-29 23:10:34.033 UTC
17
2022-07-09 19:05:49.18 UTC
2018-03-17 15:17:20.603 UTC
null
2,301,450
null
236,924
null
1
64
python|list|copy|deep-copy
42,481
<p>For a more general solution that works regardless of the number of dimensions, use <code>copy.deepcopy()</code>:</p> <pre><code>import copy b = copy.deepcopy(a) </code></pre>
2,444,001
How Does Appcelerator Titanium Mobile Work?
<p>I'm working on building an iPhone app with Titanium Mobile 1.0 and I see that it compiles down to a native iPhone binary. How does this work? Seems like it would take a lot of heavy lifting to analyze the JavaScript code and do a direct translation into Objective-C without having a superset language like 280 North's Objective-J and Cappuccino.</p>
2,471,774
3
8
null
2010-03-14 22:17:07.73 UTC
47
2013-06-20 07:11:10.017 UTC
2010-03-17 18:26:57.21 UTC
null
55,589
null
55,589
null
1
79
javascript|objective-c|titanium
41,811
<p>Titanium takes your Javascript code, analyzes and preprocesses it and then pre-compiles it into a set of symbols that are resolved based on your applications uses of Titanium APIs. From this symbol hierarchy we can build a symbol dependency matrix that maps to the underlying Titanium library symbols to understand which APIs (and related dependencies, frameworks, etc) specifically your app needs. I'm using the word symbol in a semi-generic way since it's a little different based on the language. In iPhone, the symbol maps to a true C symbol that ultimately maps to a compiled .o file that has been compiled for ARM/i386 architectures. For Java, well, it's more or less a .class file, etc. Once the front end can understand your dependency matrix, we then invoke the SDK compiler (i.e. GCC for iPhone, Java for Android) to then compile your application into the final native binary. </p> <p>So, a simple way to think about it is that your JS code is compiled almost one to one into the representative symbols in nativeland. There's still an interpreter running in interpreted mode otherwise things like dynamic code wouldn't work. However, its much faster, much more compact and it's about as close to pure native mapping as you can get. </p> <p>We're obviously still got plenty of room to improve this and working on that. So far in our latest 1.0 testing, it's almost indistinguishable from the same objective-c direct code (since in most cases it's exactly mapped to that). From a CompSci standpoint, we can now however start to optimize things that a human really couldn't easily do that - much like the GCC compiler already does today.</p>
3,160,888
How can I pattern match on a range in Scala?
<p>In Ruby I can write this:</p> <pre><code>case n when 0...5 then "less than five" when 5...10 then "less than ten" else "a lot" end </code></pre> <p>How do I do this in Scala?</p> <p>Edit: preferably I'd like to do it more elegantly than using <code>if</code>.</p>
3,161,234
4
1
null
2010-07-01 19:06:30.377 UTC
5
2015-08-26 21:38:04.49 UTC
2011-09-26 01:36:43.03 UTC
null
109,618
null
1,109
null
1
41
scala|pattern-matching|range
14,746
<p>Inside pattern match it can be expressed with guards:</p> <pre><code>n match { case it if 0 until 5 contains it =&gt; "less than five" case it if 5 until 10 contains it =&gt; "less than ten" case _ =&gt; "a lot" } </code></pre>
36,338,890
Enable Lambda function to an S3 bucket using cloudformation
<p>We are creating an S3 bucket using a CloudFormation template. I would like to associate (Add an event to S3 bucket) a Lambda function whenever a file is added to the S3 bucket.</p> <p>How is it possible through CloudFormation templates. What are the properties which needs to be used in CloudFormation.</p>
41,518,559
5
1
null
2016-03-31 16:28:30.783 UTC
16
2020-06-05 14:20:40.083 UTC
2016-04-01 19:22:45.8 UTC
null
1,065,358
null
1,065,358
null
1
36
amazon-web-services|amazon-s3|amazon-cloudformation
43,323
<p>Here's a complete, self-contained CloudFormation template that demonstrates how to trigger a Lambda function whenever a file is added to an S3 bucket:</p> <p><a href="https://console.aws.amazon.com/cloudformation/home#/stacks/new?stackName=lambda-s3-event&amp;templateURL=https://s3.amazonaws.com/wjordan-cf-templates/36338890-lambda-s3-event.yml" rel="noreferrer"><img src="https://cdn.rawgit.com/buildkite/cloudformation-launch-stack-button-svg/master/launch-stack.svg" alt="Launch Stack"></a></p> <pre class="lang-yaml prettyprint-override"><code>Description: Upload an object to an S3 bucket, triggering a Lambda event, returning the object key as a Stack Output. Parameters: Key: Description: S3 Object key Type: String Default: test Body: Description: S3 Object body content Type: String Default: TEST CONTENT BucketName: Description: S3 Bucket name Type: String Resources: Bucket: Type: AWS::S3::Bucket DependsOn: BucketPermission Properties: BucketName: !Ref BucketName NotificationConfiguration: LambdaConfigurations: - Event: 's3:ObjectCreated:*' Function: !GetAtt BucketWatcher.Arn BucketPermission: Type: AWS::Lambda::Permission Properties: Action: 'lambda:InvokeFunction' FunctionName: !Ref BucketWatcher Principal: s3.amazonaws.com SourceAccount: !Ref "AWS::AccountId" SourceArn: !Sub "arn:aws:s3:::${BucketName}" BucketWatcher: Type: AWS::Lambda::Function Properties: Description: Sends a Wait Condition signal to Handle when invoked Handler: index.handler Role: !GetAtt LambdaExecutionRole.Arn Code: ZipFile: !Sub | exports.handler = function(event, context) { console.log("Request received:\n", JSON.stringify(event)); var responseBody = JSON.stringify({ "Status" : "SUCCESS", "UniqueId" : "Key", "Data" : event.Records[0].s3.object.key, "Reason" : "" }); var https = require("https"); var url = require("url"); var parsedUrl = url.parse('${Handle}'); var options = { hostname: parsedUrl.hostname, port: 443, path: parsedUrl.path, method: "PUT", headers: { "content-type": "", "content-length": responseBody.length } }; var request = https.request(options, function(response) { console.log("Status code: " + response.statusCode); console.log("Status message: " + response.statusMessage); context.done(); }); request.on("error", function(error) { console.log("send(..) failed executing https.request(..): " + error); context.done(); }); request.write(responseBody); request.end(); }; Timeout: 30 Runtime: nodejs4.3 Handle: Type: AWS::CloudFormation::WaitConditionHandle Wait: Type: AWS::CloudFormation::WaitCondition Properties: Handle: !Ref Handle Timeout: 300 S3Object: Type: Custom::S3Object Properties: ServiceToken: !GetAtt S3ObjectFunction.Arn Bucket: !Ref Bucket Key: !Ref Key Body: !Ref Body S3ObjectFunction: Type: AWS::Lambda::Function Properties: Description: S3 Object Custom Resource Handler: index.handler Role: !GetAtt LambdaExecutionRole.Arn Code: ZipFile: !Sub | var response = require('cfn-response'); var AWS = require('aws-sdk'); var s3 = new AWS.S3(); exports.handler = function(event, context) { console.log("Request received:\n", JSON.stringify(event)); var responseData = {}; if (event.RequestType == 'Create') { var params = { Bucket: event.ResourceProperties.Bucket, Key: event.ResourceProperties.Key, Body: event.ResourceProperties.Body }; s3.putObject(params).promise().then(function(data) { response.send(event, context, response.SUCCESS, responseData); }).catch(function(err) { console.log(JSON.stringify(err)); response.send(event, context, response.FAILED, responseData); }); } else if (event.RequestType == 'Delete') { var deleteParams = { Bucket: event.ResourceProperties.Bucket, Key: event.ResourceProperties.Key }; s3.deleteObject(deleteParams).promise().then(function(data) { response.send(event, context, response.SUCCESS, responseData); }).catch(function(err) { console.log(JSON.stringify(err)); response.send(event, context, response.FAILED, responseData); }); } else { response.send(event, context, response.SUCCESS, responseData); } }; Timeout: 30 Runtime: nodejs4.3 LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: {Service: [lambda.amazonaws.com]} Action: ['sts:AssumeRole'] Path: / ManagedPolicyArns: - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" Policies: - PolicyName: S3Policy PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - 's3:PutObject' - 'S3:DeleteObject' Resource: !Sub "arn:aws:s3:::${BucketName}/${Key}" Outputs: Result: Value: !GetAtt Wait.Data </code></pre>
38,155,039
What is the difference between native int type and the numpy.int types?
<p>Can you please help understand what are the main differences (if any) between the native int type and the numpy.int32 or numpy.int64 types?</p>
38,156,888
3
0
null
2016-07-01 23:34:58.38 UTC
14
2016-07-02 05:46:55.29 UTC
null
null
null
null
6,510,497
null
1
55
python|numpy
44,957
<p>Another way to look at the differences is to ask what methods do the 2 kinds of objects have.</p> <p>In Ipython I can use tab complete to look at methods:</p> <pre><code>In [1277]: x=123; y=np.int32(123) </code></pre> <p><code>int</code> methods and attributes:</p> <pre><code>In [1278]: x.&lt;tab&gt; x.bit_length x.denominator x.imag x.numerator x.to_bytes x.conjugate x.from_bytes x.real </code></pre> <p><code>int</code> 'operators'</p> <pre><code>In [1278]: x.__&lt;tab&gt; x.__abs__ x.__init__ x.__rlshift__ x.__add__ x.__int__ x.__rmod__ x.__and__ x.__invert__ x.__rmul__ x.__bool__ x.__le__ x.__ror__ ... x.__gt__ x.__reduce_ex__ x.__xor__ x.__hash__ x.__repr__ x.__index__ x.__rfloordiv__ </code></pre> <p><code>np.int32</code> methods and attributes (or properties). Some of the same, but a lot more, basically all the <code>ndarray</code> ones:</p> <pre><code>In [1278]: y.&lt;tab&gt; y.T y.denominator y.ndim y.size y.all y.diagonal y.newbyteorder y.sort y.any y.dtype y.nonzero y.squeeze ... y.cumsum y.min y.setflags y.data y.nbytes y.shape </code></pre> <p>the <code>y.__</code> methods look a lot like the <code>int</code> ones. They can do the same math.</p> <pre><code>In [1278]: y.__&lt;tab&gt; y.__abs__ y.__getitem__ y.__reduce_ex__ y.__add__ y.__gt__ y.__repr__ ... y.__format__ y.__rand__ y.__subclasshook__ y.__ge__ y.__rdivmod__ y.__truediv__ y.__getattribute__ y.__reduce__ y.__xor__ </code></pre> <p><code>y</code> is in many ways the same as a 0d array. Not identical, but close.</p> <pre><code>In [1281]: z=np.array(123,dtype=np.int32) </code></pre> <p><code>np.int32</code> is what I get when I index an array of that type:</p> <pre><code>In [1300]: A=np.array([0,123,3]) In [1301]: A[1] Out[1301]: 123 In [1302]: type(A[1]) Out[1302]: numpy.int32 </code></pre> <p>I have to use <code>item</code> to remove all of the <code>numpy</code> wrapping.</p> <pre><code>In [1303]: type(A[1].item()) Out[1303]: int </code></pre> <p>As a <code>numpy</code> user, an <code>np.int32</code> is an <code>int</code> with a <code>numpy</code> wrapper. Or conversely a single element of an <code>ndarray</code>. Usually I don't pay attention as to whether <code>A[0]</code> is giving me the 'native' <code>int</code> or the numpy equivalent. In contrast to some new users, I rarely use <code>np.int32(123)</code>; I would use <code>np.array(123)</code> instead.</p> <pre><code>A = np.array([1,123,0], np.int32) </code></pre> <p>does not contain 3 <code>np.int32</code> objects. Rather its data buffer is 3*4=12 bytes long. It's the array overhead that interprets it as 3 ints in a 1d. And <code>view</code> shows me the same databuffer with different interpretations:</p> <pre><code>In [1307]: A.view(np.int16) Out[1307]: array([ 1, 0, 123, 0, 0, 0], dtype=int16) In [1310]: A.view('S4') Out[1310]: array([b'\x01', b'{', b''], dtype='|S4') </code></pre> <p>It's only when I index a single element that I get a <code>np.int32</code> object.</p> <p>The list <code>L=[1, 123, 0]</code> is different; it's a list of pointers - pointers to <code>int</code> objects else where in memory. Similarly for a dtype=object array.</p>
38,237,942
cron expression in AWS CloudWatch: How to run once a week
<p>In Amazon AWS CloudWatch it is possible to run a rule according to a schedule that is defined in a cron expression.</p> <p>The rules for this are outlined <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/ScheduledEvents.html" rel="noreferrer">here</a>.</p> <p>After some trying around, I wasn't able to compose an expression that will run <strong>once a week</strong> (e.g. at 4 pm on Sunday). The following attempts were rejected by CloudWatch with the message <code>Parameter ScheduleExpression is not valid..</code>.</p> <pre><code>0 16 * * SUN * 0 16 * * 6 * 0 16 * * SUN-SUN * 0 16 * * 6-6 * </code></pre>
38,239,183
1
0
null
2016-07-07 05:14:39.917 UTC
3
2019-01-21 06:23:02.55 UTC
null
null
null
null
270,662
null
1
38
amazon-web-services|cron|cloudwatch
36,512
<p>Try <code>0 16 ? * 1 *</code> The question marks "says" that it must no be executed everyday, so it must check the week day value.</p>
757,809
django-paypal setup
<p>Has anyone setup django-paypal? Here is the link to it <a href="https://github.com/johnboxall/django-paypal" rel="noreferrer">here</a>? </p> <p>I have "myproject" setup, and my folder sturecture looks like this:</p> <p>myproject > paypal > (stdandard and pro folders)</p> <p>to my settins.py file I added</p> <pre><code>INSTALLED_APPS = ( 'myproject.paypal.standard', 'myproject.paypal.pro', ) </code></pre> <p>in my url's file for my account app I added:</p> <pre><code>urlpatterns += patterns('myproject.account.views', (r'^payment-url/$', 'buy_my_item'), ) </code></pre> <p>and in my account view I added:</p> <pre><code>from myproject.paypal.pro.views import PayPalPro from myproject.paypal.pro.forms import PaymentForm, ConfirmForm def buy_my_item(request): item = {'amt':"10.00", # amount to charge for item 'inv':"1111", # unique tracking variable paypal 'custom':"2222", # custom tracking variable for you 'cancelurl':"http://127.0.0.1:8000/", # Express checkout cancel url 'returnurl':"http://127.0.0.1:8000/"} # Express checkout return url kw = {'item':'item', # what you're selling 'payment_template': 'pro/payment.html', # template to use for payment form 'confirm_template': ConfirmForm, # form class to use for Express checkout confirmation 'payment_form_cls': PaymentForm, # form class to use for payment 'success_url': '/success', # where to redirect after successful payment } ppp = PayPalPro(**kw) return ppp(request) </code></pre> <p>--- EDIT --------- Then, I added the pro and standard template folders to my projects template folder.</p> <p>When I go to <a href="http://127.0.0.1:8000/account/payment-url/" rel="noreferrer">http://127.0.0.1:8000/account/payment-url/</a> and submit the form...</p> <p>I get a ValueError : "dictionary update sequence element #0 has length 1; 2 is required"</p> <p>Traceback:</p> <pre><code>File "...\accounts\views.py" in buy_my_item 655. return ppp(request) File "...\paypal\pro\views.py" in __call__ 115. return self.validate_payment_form() File "...\paypal\pro\views.py" in validate_payment_form 133. success = form.process(self.request, self.item) File "...\paypal\pro\forms.py" in process </code></pre> <ol start="35"> <li>params.update(item)</li> </ol>
757,820
2
2
null
2009-04-16 19:57:51.277 UTC
17
2011-08-09 19:24:34.867 UTC
2011-08-09 19:24:34.867 UTC
null
529,829
null
74,474
null
1
14
python|django|paypal
13,052
<p>In your code...</p> <pre><code> 'payment_form_cls': 'payment_form_cls', # form class to use for payment </code></pre> <p>This must be a Form object that's used for validation.</p> <pre><code> 'payment_form_cls': MyValidationForm, # form class to use for payment </code></pre> <hr> <p><strong>Edit</strong></p> <p><a href="http://github.com/johnboxall/django-paypal/tree/master" rel="noreferrer">http://github.com/johnboxall/django-paypal/tree/master</a></p> <p>Your request is supposed to include a notify-url, return-url and cancel-return. All three url's YOU provide to Paypal.</p> <p>Paypal will send messages to these URL's.</p> <p>Since Paypal will send messages to these URL's, YOU must put them in your urls.py. You must write view functions for these three urls'. These urls will have your paypal responses sent to them.</p>
1,306,595
Git confused when merging an update into my subtree
<p>We previously used many submodules in our main repositories, but to increase the maintainability of our projects we started an experimental branch where we replaced them all with subtrees.</p> <p>This worked good - but now when I'm trying to update one of the subtrees it erroneously merges the update into a completely wrong directory that isn't even a subtree.</p> <p>The main repository, where the branch "subtree" contains the experimental branch, is: <strong>git://github.com/hugowetterberg/goodold_drupal.git</strong></p> <p>The repository to merge in updates from: <strong>git://github.com/voxpelli/drupal-oembed.git</strong></p> <p>Merging by doing: <strong>git merge -s subtree oembed/master</strong></p> <p>The path the updates should be merged into: <strong>sites/all/modules/oembed/</strong></p> <p>The path they are merged into: <strong>modules/aggregator/translations/</strong></p> <p>Anyone having an idea of how to get the updates into the subtrees or what the error can be?</p>
1,307,817
2
0
null
2009-08-20 14:31:00.48 UTC
9
2013-10-14 11:54:48.94 UTC
2013-10-14 11:54:48.94 UTC
null
20,667
null
20,667
null
1
20
git|merge|git-subtree|subtree
3,164
<p>Unfortunately this is a bug (or missing feature) in the "git merge -s subtree" code. It actually <em>guesses</em> the subtrees that you want to merge. Usually, this magically turns out to be correct, but if your subtree contains a lot of changes (or was originally empty, or whatever), then it can fail spectacularly.</p> <p>The best way to work around it is:</p> <ol> <li><p>Merge the files as you did above.</p></li> <li><p>Manually move all the resulting files to where they <em>should</em> have gone.</p></li> <li><p><code>git commit -a --amend</code> to correct the merge commit.</p></li> </ol> <p>Future merges will probably work fine, unless this directory is constantly in unbelievable amounts of flux.</p> <p>The experimental "<a href="http://github.com/apenwarr/git-subtree" rel="noreferrer">git subtree</a>" command has a <code>--prefix</code> parameter that should let you override this, but unfortunately it doesn't work at the moment (since it requires working around "git merge -s subtree" features and there hasn't been time to do it).</p> <p>Anyway, this should be a rare situation and the workaround won't be needed even for future merges of the same project.</p>
2,400,482
How do I make a "div" button submit the form its sitting in?
<p>I have ASP.Net code generating my button's HTML for me using divs to get it to look and behave how I want. This question is regarding the <strong>HTML produced</strong> by the ASP.Net code.</p> <p>A standard button is easy, just set the onClick event of the div to change the page location:</p> <pre><code>&lt;div name="mybutton" id="mybutton" class="customButton" onClick="javascript:document.location.href='wherever.html';"&gt; Button Text &lt;/div&gt; </code></pre> <p>This works great, however, if I want a button like this to submit the form in which it resides, I would have imagined something like below:</p> <pre><code>&lt;form action="whatever.html" method="post"&gt; &lt;div name="mysubmitbutton" id="mysubmitbutton" class="customButton" onClick="javascript:this.form.submit();"&gt; Button Text &lt;/div&gt; &lt;/form&gt; </code></pre> <p>However, that does not work :( Does anyone have any sparkling ideas?</p>
2,400,507
6
3
null
2010-03-08 10:05:23.813 UTC
12
2020-12-22 16:36:16.09 UTC
2020-12-22 16:36:16.09 UTC
null
1,783,163
null
175,893
null
1
39
html|asp.net|forms|submit
130,970
<pre><code>onClick="javascript:this.form.submit();"&gt; </code></pre> <p><code>this</code> in div onclick don't have attribute <code>form</code>, you may try <code>this.parentNode.submit()</code> or <code>document.forms[0].submit()</code> will do</p> <p>Also, <code>onClick</code>, should be <strong><code>onclick</code></strong>, some browsers don't work with <code>onClick</code></p>
3,172,985
JavaScript - Use variable in string match
<p>I found several similar questions, but it did not help me. So I have this problem:</p> <pre><code>var xxx = "victoria"; var yyy = "i"; alert(xxx.match(yyy/g).length); </code></pre> <p>I don't know how to pass variable in match command. Please help. Thank you.</p>
3,172,994
6
2
null
2010-07-03 21:52:42.51 UTC
20
2019-06-09 07:10:51.86 UTC
2019-06-09 07:10:51.86 UTC
null
2,792,083
null
382,854
null
1
108
javascript|variables|match
145,386
<p>Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:</p> <pre><code>var re = new RegExp(yyy, 'g'); xxx.match(re); </code></pre> <p>Any flags you need (such as /g) can go into the second parameter. </p>
2,856,438
How can I link to a specific glibc version?
<p>When I compile something on my Ubuntu Lucid 10.04 PC it gets linked against glibc. Lucid uses 2.11 of glibc. When I run this binary on another PC with an older glibc, the command fails saying there's no glibc 2.11... </p> <p>As far as I know glibc uses symbol versioning. Can I force gcc to link against a specific symbol version?</p> <p>In my concrete use I try to compile a gcc cross toolchain for ARM. </p>
2,858,996
6
2
null
2010-05-18 10:45:23.663 UTC
70
2022-08-17 13:10:58.583 UTC
2010-10-26 17:14:07.587 UTC
Roger Pate
null
null
184,207
null
1
171
linux|gcc|linker|glibc|libc
150,518
<p>You are correct in that glibc uses symbol versioning. If you are curious, the symbol versioning implementation introduced in glibc 2.1 is described <a href="http://people.redhat.com/drepper/symbol-versioning" rel="noreferrer">here</a> and is an extension of Sun's symbol versioning scheme described <a href="http://download.oracle.com/docs/cd/E19253-01/817-1984/appendixb-45356/index.html" rel="noreferrer">here</a>.</p> <p>One option is to statically link your binary. This is probably the easiest option.</p> <p>You could also build your binary in a chroot build environment, or using a glibc-<em>new</em> =&gt; glibc-<em>old</em> cross-compiler.</p> <p>According to the <a href="https://web.archive.org/web/20110208085632/http://www.trevorpounds.com/blog/" rel="noreferrer">http://www.trevorpounds.com</a> blog post <a href="https://web.archive.org/web/20160107032111/http://www.trevorpounds.com/blog/?p=103" rel="noreferrer"><em><strong>Linking to Older Versioned Symbols (glibc)</strong></em></a>, it is possible to to force any symbol to be linked against an older one so long as it is valid by using the same <em><code>.symver</code></em> pseudo-op that is used for defining versioned symbols in the first place. The following example is excerpted from the <a href="https://web.archive.org/web/20160107032111/http://www.trevorpounds.com/blog/?p=103" rel="noreferrer">blog post</a>.</p> <p>The following example makes use of glibc’s realpath, but makes sure it is linked against an older 2.2.5 version.</p> <pre><code>#include &lt;limits.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; __asm__(&quot;.symver realpath,realpath@GLIBC_2.2.5&quot;); int main() { const char* unresolved = &quot;/lib64&quot;; char resolved[PATH_MAX+1]; if(!realpath(unresolved, resolved)) { return 1; } printf(&quot;%s\n&quot;, resolved); return 0; } </code></pre>
2,717,949
When should I use a semicolon after curly braces?
<p>Many times I've seen a semicolon used after a function declaration, or after the anonymous "return" function of a Module Pattern script. When is it appropriate to use a semicolon after curly braces?</p>
2,717,956
8
0
null
2010-04-27 00:27:52.64 UTC
23
2020-10-08 20:59:33.207 UTC
2019-03-24 11:06:42.95 UTC
null
10,607,772
null
321,781
null
1
66
javascript|syntax
31,285
<p>You use a semicolon after a statement. This is a statement:</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 foo = function() { alert("bar"); };</code></pre> </div> </div> </p> <p>because it is a variable assignment (i.e. creating and assigning an anonymous function to a variable).</p> <p>The two things that spring to mind that aren't statements are function declarations:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function foo() { alert("bar"); }</code></pre> </div> </div> </p> <p>and blocks:</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>{ alert("foo"); }</code></pre> </div> </div> </p> <p><strong>Note:</strong> that same block construct without semi-colon also applies to <code>for</code>, <code>do</code> and <code>while</code> loops.</p>
2,828,255
How do I increase the capacity of the Eclipse output console?
<p>Even with the "scroll lock" option enabled for the Eclipse console, eventually it overfills and starts auto-scrolling on me. </p> <p>Is there some way of increasing the capacity of the console so that it stores more lines? I wasn't able to find the option. </p>
2,828,293
10
4
null
2010-05-13 15:56:09.48 UTC
47
2021-06-17 23:49:36.067 UTC
null
null
null
null
23,072
null
1
348
eclipse|console
191,025
<p>Under <code>Window &gt; Preferences</code>, go to the <code>Run/Debug &gt; Console</code> section, then you should see an option "Limit console output." You can uncheck this or change the number in the "Console buffer size (characters)" text box below.</p> <p>(This is in Galileo, Helios CDT, Kepler, Juno, Luna, Mars, Neon, Oxygen and 2018-09)</p>
3,199,588
Fastest way to convert JavaScript NodeList to Array?
<p>Previously answered questions here said that this was the fastest way:</p> <pre><code>//nl is a NodeList var arr = Array.prototype.slice.call(nl); </code></pre> <p>In benchmarking on my browser I have found that it is more than 3 times slower than this:</p> <pre><code>var arr = []; for(var i = 0, n; n = nl[i]; ++i) arr.push(n); </code></pre> <p>They both produce the same output, but I find it hard to believe that my second version is the fastest possible way, especially since people have said otherwise here.</p> <p>Is this a quirk in my browser (Chromium 6)? Or is there a faster way?</p> <p>EDIT: For anyone who cares, I settled on the following (which seems to be the fastest in every browser that I tested):</p> <pre><code>//nl is a NodeList var l = []; // Will hold the array of Node's for(var i = 0, ll = nl.length; i != ll; l.push(nl[i++])); </code></pre> <p>EDIT2: I found an even faster way</p> <pre><code>// nl is the nodelist var arr = []; for(var i = nl.length; i--; arr.unshift(nl[i])); </code></pre>
3,199,627
15
5
null
2010-07-07 23:04:49.827 UTC
85
2022-08-21 14:15:55.137 UTC
2014-10-28 02:04:56.84 UTC
null
527,702
null
237,140
null
1
329
javascript|arrays|nodelist
194,160
<h2>2021 update: <a href="https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach" rel="noreferrer">nodeList.forEach() is now standard</a> and supported in all current browsers (<a href="https://caniuse.com/mdn-api_nodelist_foreach" rel="noreferrer">around 95% on both desktop &amp; mobile</a>).</h2> <p>So you can simply do:</p> <pre><code>document.querySelectorAll('img').forEach(highlight); </code></pre> <hr /> <p><strong>Other cases</strong></p> <p>If you for some reason want to convert it to an array, not just iterate over it - which is a completely relevant use-case - you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer"><code>[...destructuring]</code></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from" rel="noreferrer"><code>Array.from</code></a> since ES6</p> <pre><code>let array1 = [...mySetOfElements]; // or let array2 = Array.from(mySetOfElements); </code></pre> <p>This also works for other array-like structures that aren't NodeLists</p> <ul> <li><code>HTMLCollection</code> returned by e.g. <code>document.getElementsByTagName</code></li> <li>objects with a length property and indexed elements</li> <li>iterable objects (objects such as <code>Map</code> and <code>Set</code>)</li> </ul> <hr /> <hr /> <hr /> <p><strong>Outdated 2010 Answer</strong></p> <p>The second one tends to be faster in some browsers, but the main point is that you have to use it because the first one is just not cross-browser. Even though The Times They Are a-Changin'</p> <p><strong><a href="http://perfectionkills.com/jscript-and-dom-changes-in-ie9-preview-3/" rel="noreferrer">@kangax</a></strong> (<em><strong>IE 9 preview</strong></em>)</p> <blockquote> <p><strong>Array.prototype.slice</strong> can now convert certain host objects (e.g. NodeList’s) to arrays — something that majority of modern browsers have been able to do for quite a while.</p> </blockquote> <p>Example:</p> <pre><code>Array.prototype.slice.call(document.childNodes); </code></pre>
6,165,077
How do I create a progress bar for data loading in R?
<p>Is it possible to create a progress bar for data loaded into R using <a href="http://www.inside-r.org/r-doc/base/load" rel="noreferrer">load()</a>?</p> <p>For a data analysis project large matrices are being loaded in R from .RData files, which take several minutes to load. I would like to have a progress bar to monitor how much longer it will be before the data is loaded. R already has nice <a href="http://stat.ethz.ch/R-manual/R-patched/library/utils/html/txtProgressBar.html" rel="noreferrer">progress bar</a> functionality integrated, but load() has no hooks for monitoring how much data has been read. If I can't use load directly, is there an indirect way I can create such a progress bar? Perhaps loading the .RData file in chucks and putting them together for R. Does any one have any thoughts or suggestions on this? </p>
6,300,431
2
4
null
2011-05-28 23:47:13.923 UTC
10
2013-01-04 04:54:03.36 UTC
null
null
null
null
61,793
null
1
26
file|r|load|progress-bar|binary-data
7,195
<p>I came up with the following solution, which will work for file sizes less than 2^32 - 1 bytes. </p> <p>The R object needs to be serialized and saved to a file, as done by the following code.</p> <pre><code>saveObj &lt;- function(object, file.name){ outfile &lt;- file(file.name, "wb") serialize(object, outfile) close(outfile) } </code></pre> <p>Then we read the binary data in chunks, keeping track of how much is read and updating the progress bar accordingly.</p> <pre><code>loadObj &lt;- function(file.name){ library(foreach) filesize &lt;- file.info(file.name)$size chunksize &lt;- ceiling(filesize / 100) pb &lt;- txtProgressBar(min = 0, max = 100, style=3) infile &lt;- file(file.name, "rb") data &lt;- foreach(it = icount(100), .combine = c) %do% { setTxtProgressBar(pb, it) readBin(infile, "raw", chunksize) } close(infile) close(pb) return(unserialize(data)) } </code></pre> <p>The code can be run as follows:</p> <pre><code>&gt; a &lt;- 1:100000000 &gt; saveObj(a, "temp.RData") &gt; b &lt;- loadObj("temp.RData") |======================================================================| 100% &gt; all.equal(b, a) [1] TRUE </code></pre> <p>If we benchmark the progress bar method against reading the file in a single chunk we see the progress bar method is slightly slower, but not enough to worry about.</p> <pre><code>&gt; system.time(unserialize(readBin(infile, "raw", file.info("temp.RData")$size))) user system elapsed 2.710 0.340 3.062 &gt; system.time(b &lt;- loadObj("temp.RData")) |======================================================================| 100% user system elapsed 3.750 0.400 4.154 </code></pre> <p>So while the above method works, I feel it is completely useless because of the file size restrictions. Progress bars are only useful for large files that take a long time to read in.</p> <p><strong>It would be great if someone could come up with something better than this solution!</strong></p>
21,349,950
Entity Framework 6 Code First - Is Repository Implementation a Good One?
<p>I am about to implement an Entity Framework 6 design with a repository and unit of work.</p> <p>There are so many articles around and I'm not sure what the best advice is: For example I realy like the pattern implemented here: for the reasons suggested in the article <a href="http://codefizzle.wordpress.com/2012/07/26/correct-use-of-repository-and-unit-of-work-patterns-in-asp-net-mvc/">here</a></p> <p>However, <code>Tom Dykstra (Senior Programming Writer on Microsoft's Web Platform &amp; Tools Content Team)</code> suggests it should be done in another article: <a href="http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application">here</a></p> <p>I subscribe to <code>Pluralsight</code>, and it is implemented in a slightly different way pretty much every time it is used in a course so choosing a design is difficult.</p> <p>Some people seem to suggest that unit of work is already implemented by <code>DbContext</code> as in this <a href="http://social.msdn.microsoft.com/Forums/en-US/435bf3a3-a358-41cf-a1b0-9f4387dcf5f2/is-unit-of-work-functionality-already-available-inside-the-dbcontext-in-ef-5?forum=adodotnetentityframework">post</a>, so we shouldn't need to implement it at all.</p> <p>I realise that this type of question has been asked before and this may be subjective but my question is direct:</p> <p>I like the approach in the first (Code Fizzle) article and wanted to know if it is perhaps more maintainable and as easily testable as other approaches and safe to go ahead with?</p> <p>Any other views are more than welcome.</p>
21,352,268
7
1
null
2014-01-25 11:30:13.377 UTC
73
2019-07-19 08:18:18.91 UTC
null
null
null
null
402,421
null
1
51
entity-framework|repository-pattern|unit-of-work
37,136
<p>@Chris Hardie is correct, EF implements UoW out of the box. However many people overlook the fact that EF also implements a generic repository pattern out of the box too:</p> <pre><code>var repos1 = _dbContext.Set&lt;Widget1&gt;(); var repos2 = _dbContext.Set&lt;Widget2&gt;(); var reposN = _dbContext.Set&lt;WidgetN&gt;(); </code></pre> <p>...and this is a pretty good generic repository implementation that is built into the tool itself.</p> <p>Why go through the trouble of creating a ton of other interfaces and properties, when DbContext gives you everything you need? If you want to abstract the DbContext behind application-level interfaces, and you want to apply command query segregation, you could do something as simple as this:</p> <pre><code>public interface IReadEntities { IQueryable&lt;TEntity&gt; Query&lt;TEntity&gt;(); } public interface IWriteEntities : IReadEntities, IUnitOfWork { IQueryable&lt;TEntity&gt; Load&lt;TEntity&gt;(); void Create&lt;TEntity&gt;(TEntity entity); void Update&lt;TEntity&gt;(TEntity entity); void Delete&lt;TEntity&gt;(TEntity entity); } public interface IUnitOfWork { int SaveChanges(); } </code></pre> <p>You could use these 3 interfaces for all of your entity access, and not have to worry about injecting 3 or more different repositories into business code that works with 3 or more entity sets. Of course you would still use IoC to ensure that there is only 1 DbContext instance per web request, but all 3 of your interfaces are implemented by the same class, which makes it easier.</p> <pre><code>public class MyDbContext : DbContext, IWriteEntities { public IQueryable&lt;TEntity&gt; Query&lt;TEntity&gt;() { return Set&lt;TEntity&gt;().AsNoTracking(); // detach results from context } public IQueryable&lt;TEntity&gt; Load&lt;TEntity&gt;() { return Set&lt;TEntity&gt;(); } public void Create&lt;TEntity&gt;(TEntity entity) { if (Entry(entity).State == EntityState.Detached) Set&lt;TEntity&gt;().Add(entity); } ...etc } </code></pre> <p>You now only need to inject a single interface into your dependency, regardless of how many different entities it needs to work with:</p> <pre><code>// NOTE: In reality I would never inject IWriteEntities into an MVC Controller. // Instead I would inject my CQRS business layer, which consumes IWriteEntities. // See @MikeSW's answer for more info as to why you shouldn't consume a // generic repository like this directly by your web application layer. // See http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91 and // http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92 for more info // on what a CQRS business layer that consumes IWriteEntities / IReadEntities // (and is consumed by an MVC Controller) might look like. public class RecipeController : Controller { private readonly IWriteEntities _entities; //Using Dependency Injection public RecipeController(IWriteEntities entities) { _entities = entities; } [HttpPost] public ActionResult Create(CreateEditRecipeViewModel model) { Mapper.CreateMap&lt;CreateEditRecipeViewModel, Recipe&gt;() .ForMember(r =&gt; r.IngredientAmounts, opt =&gt; opt.Ignore()); Recipe recipe = Mapper.Map&lt;CreateEditRecipeViewModel, Recipe&gt;(model); _entities.Create(recipe); foreach(Tag t in model.Tags) { _entities.Create(tag); } _entities.SaveChanges(); return RedirectToAction("CreateRecipeSuccess"); } } </code></pre> <p>One of my favorite things about this design is that it <em>minimizes the entity storage dependencies on the <strong>consumer</em></strong>. In this example the <code>RecipeController</code> is the consumer, but in a real application the consumer would be a command handler. (For a query handler, you would typically consume <code>IReadEntities</code> only because you just want to return data, not mutate any state.) But for this example, let's just use <code>RecipeController</code> as the consumer to examine the dependency implications: </p> <p>Say you have a set of unit tests written for the above action. In each of these unit tests, you new up the Controller, passing a mock into the constructor. Then, say your customer decides they want to allow people to create a new Cookbook or add to an existing one when creating a new recipe. </p> <p>With a repository-per-entity or repository-per-aggregate interface pattern, you would have to inject a new repository instance <code>IRepository&lt;Cookbook&gt;</code> into your controller constructor (or using @Chris Hardie's answer, write code to attach yet another repository to the UoW instance). This would immediately make all of your other unit tests break, and you would have to go back to modify the construction code in all of them, passing yet another mock instance, and widening your dependency array. However with the above, all of your other unit tests will still at least compile. All you have to do is write additional test(s) to cover the new cookbook functionality.</p>
35,562,622
In ionic framework how to set first ion-segment-button in active state by default?
<p>In <code>ionic2</code> how to set the first <code>ion-segment-button</code> in <code>ion-segment</code> to be in <code>active state</code>? I have tried to do it with providing the <code>active class</code> to the <code>ion-segment-button</code> like : </p> <pre><code> &lt;div padding&gt; &lt;ion-segment [(ngModel)]="home_tabs"&gt; &lt;ion-segment-button class="segment-button segment-activated" value="A"&gt;A &lt;/ion-segment-button&gt; &lt;ion-segment-button value="B"&gt;B &lt;/ion-segment-button&gt; &lt;/ion-segment&gt; &lt;/div&gt; </code></pre> <p>But this didn't worked. I want make the first <code>ion-segment-button</code> to be inactive state and corresponding, </p> <pre><code>&lt;ion-list *ngSwitchWhen="'A'" &gt;&lt;/ion-list&gt; </code></pre> <p>to be active state. How to do this? </p>
35,576,561
3
0
null
2016-02-22 19:55:26.353 UTC
3
2019-04-09 07:29:14.253 UTC
2016-02-23 08:25:28.82 UTC
null
1,823,740
null
1,823,740
null
1
14
android|ios|ionic-framework|ionic2
40,181
<p>This should be helpful: <a href="http://ionicframework.com/docs/v2/components/#segment" rel="noreferrer">http://ionicframework.com/docs/v2/components/#segment</a></p> <p>Also, if you dont have a value for home_tabs at the beginning than the ion-segment component will not know what exactly you want. To solve this you can make home_tabs = 'A' by default on the constructor so the first button will always be active</p> <p>This is in your component:</p> <pre><code>export class SegmentPage { constructor() { this.pet = "puppies"; } } </code></pre> <p>This is in your html:</p> <pre><code>&lt;ion-segment [(ngModel)]="pet"&gt; &lt;ion-segment-button value="puppies"&gt; Puppies &lt;/ion-segment-button&gt; &lt;ion-segment-button value="kittens"&gt; Kittens &lt;/ion-segment-button&gt; &lt;ion-segment-button value="ducklings"&gt; Ducklings &lt;/ion-segment-button&gt; &lt;/ion-segment&gt; </code></pre> <p>You can see ngModel is pet, and in the constructor it is setting pet to be "puppies" so the ion-segment component will make the button that has value 'puppies' the active ion-segment-button</p> <p><a href="https://github.com/driftyco/ionic-preview-app/tree/master/app/pages/segments/basic" rel="noreferrer">https://github.com/driftyco/ionic-preview-app/tree/master/app/pages/segments/basic</a></p>
53,189,729
Typescript Error: setInterval - Type 'Timer' is not assignable to type 'number'
<p>I have the following code:</p> <pre><code>let onSizeChangeSetInterval = setInterval(() =&gt; {...}, 30); </code></pre> <p>When I compile this code, I'm getting the following error:</p> <blockquote> <p>ERROR in src/components/popover/popover.component.ts(98,17): error TS2322: Type 'Timer' is not assignable to type 'number'. src/modules/forms-ui/formly/types/daterange/picker.daterange.component.ts(186,9): error TS2322: Type 'Timer' is not assignable to type 'number'.</p> </blockquote>
53,189,769
3
0
null
2018-11-07 12:46:02.877 UTC
2
2021-09-23 14:26:14.65 UTC
null
null
null
null
5,148,197
null
1
28
javascript|angular|typescript
18,314
<p>Use <code>window.setInterval</code> instead</p>