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
19,697,210
Taking Screen shots of specific size
<p>What imaging modules for python will allow you to take a specific size screenshot (not whole screen)? I have tried PIL, but can't seem to make ImageGrab.grab() select a small rectangle and i have tried PyGame but i can't make it take a screen shot outside of it's main display panel</p>
19,697,425
5
0
null
2013-10-31 02:07:25.713 UTC
5
2020-07-17 03:47:24.357 UTC
null
null
null
null
2,259,569
null
1
5
python
49,596
<p>You can use <a href="https://pypi.python.org/pypi/pyscreenshot" rel="noreferrer">pyscreenshot</a> module. <br> The <code>pyscreenshot</code> module can be used to copy the contents of the screen to a <code>PIL</code> image memory or file. You can install it using <code>pip</code>.</p> <pre><code>$ sudo pip install pyscreenshot </code></pre> <p>Usage:</p> <pre><code>import pyscreenshot as ImageGrab # fullscreen im=ImageGrab.grab() im.show() # part of the screen im=ImageGrab.grab(bbox=(10,10,500,500)) im.show() # to file ImageGrab.grab_to_file('im.png') </code></pre>
32,187,565
Difference in Elm between type and type alias?
<p>In Elm, I can't figure out when <code>type</code> is the appropriate keyword vs. <code>type alias</code>. The documentation doesn't seem to have an explanation of this, nor can I find one in the release notes. Is this documented somewhere?</p>
32,188,856
5
0
null
2015-08-24 16:48:50.813 UTC
15
2019-05-19 18:20:33.057 UTC
null
null
null
null
86,381
null
1
102
elm
7,405
<p> How I think of it:</p> <p><code>type</code> is used for defining new union types:</p> <pre class="lang-elm prettyprint-override"><code>type Thing = Something | SomethingElse </code></pre> <p>Before this definition <code>Something</code> and <code>SomethingElse</code> didn't mean anything. Now they are both of type <code>Thing</code>, which we just defined.</p> <p><code>type alias</code> is used for giving a name to some other type that already exists:</p> <pre class="lang-elm prettyprint-override"><code>type alias Location = { lat:Int, long:Int } </code></pre> <p><code>{ lat = 5, long = 10 }</code> has type <code>{ lat:Int, long:Int }</code>, which was already a valid type. But now we can also say it has type <code>Location</code> because that is an alias for the same type.</p> <p>It is worth noting that the following will compile just fine and display <code>"thing"</code>. Even though we specify <code>thing</code> is a <code>String</code> and <code>aliasedStringIdentity</code> takes an <code>AliasedString</code>, we won't get an error that there is a type mismatch between <code>String</code>/<code>AliasedString</code>:</p> <pre class="lang-elm prettyprint-override"><code>import Graphics.Element exposing (show) type alias AliasedString = String aliasedStringIdentity: AliasedString -&gt; AliasedString aliasedStringIdentity s = s thing : String thing = "thing" main = show &lt;| aliasedStringIdentity thing </code></pre>
52,192,680
Is there a way to have `toHaveBeenCalledWith` match a regular expression?
<p>I have a function that appends a random number an then calls another function. I want to check that it was called with the text passed in and match any random number. I'd like to be able to pass a Regex without Jest literally matching the Regex. Something like:</p> <pre><code> const typeFn = jest.fn(); function type (text) { typeFn(text + Math.random()); }) type('hello') expect(typeFn).toHaveBeenCalledWith(/hello\d+/) </code></pre>
52,192,808
1
0
null
2018-09-05 20:05:42.213 UTC
5
2022-09-12 08:11:33.793 UTC
2022-09-12 08:11:33.793 UTC
null
542,251
null
1,769,217
null
1
42
javascript|jestjs
7,351
<p>You can use one of the helper functions in <code>expect</code> instead of an actual value:</p> <pre><code>expect(typeFn).toHaveBeenCalledWith(expect.stringMatching(/hello\d+/)); </code></pre> <p>Here's a live example: <a href="https://repl.it/@marzelin/FrighteningCapitalConferences" rel="noreferrer">https://repl.it/@marzelin/FrighteningCapitalConferences</a></p>
21,638,922
Custom error message json object with flask-restful
<p>It is easy to propagate error messages with flask-restful to the client with the <code>abort()</code> method, such as</p> <pre><code>abort(500, message="Fatal error: Pizza the Hutt was found dead earlier today in the back seat of his stretched limo. Evidently, the notorious gangster became locked in his car and ate himself to death.") </code></pre> <p>This will generate the following json output</p> <pre><code>{ "message": "Fatal error: Pizza the Hutt was found dead earlier today in the back seat of his stretched limo. Evidently, the notorious gangster became locked in his car and ate himself to death.", "status": 500 } </code></pre> <p>Is there a way to customise the json output with additional members? For example:</p> <pre><code>{ "sub_code": 42, "action": "redirect:#/Outer/Space" "message": "You idiots! These are not them! You've captured their stunt doubles!", "status": 500 } </code></pre>
21,639,552
7
0
null
2014-02-07 22:26:13.127 UTC
7
2022-04-09 10:35:30.853 UTC
2014-02-08 21:59:28.873 UTC
null
1,154,241
null
1,154,241
null
1
31
flask|werkzeug|flask-restful
22,674
<p>People tend to overuse <code>abort()</code>, while in fact it is very simple to generate your own errors. You can write a function that generates custom errors easily, here is one that matches your JSON:</p> <pre><code>def make_error(status_code, sub_code, message, action): response = jsonify({ 'status': status_code, 'sub_code': sub_code, 'message': message, 'action': action }) response.status_code = status_code return response </code></pre> <p>Then instead of calling <code>abort()</code> do this:</p> <pre><code>@route('/') def my_view_function(): # ... if need_to_return_error: return make_error(500, 42, 'You idiots!...', 'redirect...') # ... </code></pre>
21,641,849
Summing up each row and column in Java
<pre><code>/* * Programmer: Olawale Onafowokan * Date: February 6, 2014 * Purpose: Prints the row and column averages */ class Lab4 { public static void main(String[] args) { int [][] scores = {{ 20, 18, 23, 20, 16 }, { 30, 20, 18, 21, 20 }, { 16, 19, 16, 53, 24 }, { 25, 24, 22, 24, 25 }}; outputArray(scores); } public static void outputArray(int[][] array) { int sum= 0; int rowSize = array.length; int columnSize = array[0].length; System.out.println("rows=" + rowSize + "cols=" + columnSize); for (int i = 0; i &lt; array.length; i++) { for (int j = 0; j &lt; array[0].length; j++) { sum += array[i][j]; } System.out.println("Print the sum of rows = " + sum); } for (int i = 0; i &lt; array.length; i++) { sum = 0; sum = sum + array[i][j]; // It is telling me the j can't be resolved } } } </code></pre> <p>The program prints out:</p> <pre><code>rows=4cols=5 Print the sum of rows = 612 Print the sum of rows = 20358 Print the sum of rows = 652058 Print the sum of rows = 20866609 </code></pre> <p>I don’t understand why it isn't adding up the numbers correctly. I am trying to add up each row and column. I am not even sure where these numbers are coming from.</p>
21,641,864
7
0
null
2014-02-08 04:20:17.83 UTC
3
2017-03-26 09:46:02.28 UTC
2014-02-08 05:07:12.167 UTC
null
2,157,640
null
3,286,008
null
1
1
java|arrays|row|multiple-columns
53,176
<p>Here is your problem:</p> <pre><code>sum += sum + array[i][j]; </code></pre> <p><code>sum += sum + array[i][j]</code> is the same as <code>sum = sum + sum + array[i][j]</code> (<em>you added sum twice</em>)</p> <p>Should be:</p> <p><code>sum = sum + array[i][j];</code> <strong>Or</strong> <code>sum += array[i][j];</code></p> <p>If you want to print the sum of each <strong>row only</strong>, reset your <code>sum</code> to <code>0</code> for each iteration on outer <code>for-loop</code></p> <pre><code>for (int i = 0; i &lt; array.length; i++){ sum=0; .... </code></pre> <p>If you want to print the sum of each <strong>column only</strong>, you need to add this:</p> <pre><code>int[] colSum =new int[array[0].length]; </code></pre> <p>Then inside <code>for-loop</code> , add</p> <pre><code>colSum[j]+=array[i][j]; </code></pre> <p>So finally you will have this:</p> <pre><code>int[] colSum =new int[array[0].length]; for (int i = 0; i &lt; array.length; i++){ for (int j = 0; j &lt; array[i].length; j++){ sum += array[i][j]; colSum[j] += array[i][j]; } System.out.println("Print the sum of rows =" + sum); } for(int k=0;k&lt;colSum.length;k++){ System.out.println("Print the sum of columns =" + colSum[k]); } </code></pre>
18,991,981
Difference between code and verbatim in Org-mode?
<p>What is the intended difference between <code>~code~</code> and <code>=verbatim=</code> markup in Org-mode? Exporting to HTML in both cases yields <code>&lt;code&gt;</code> tags.</p>
19,012,601
2
0
null
2013-09-24 21:02:26.607 UTC
4
2020-07-15 09:32:03.01 UTC
2020-07-15 09:32:03.01 UTC
null
13,513,328
null
319,845
null
1
29
emacs|org-mode
3,214
<p>In Org 8.0 (ox-* exporters) there are a few differences.</p> <h3>In LaTeX</h3> <ul> <li>Code comes out as `\verb{sep}content{sep} where {sep} is found as an appropriate delimiter.</li> <li>Verbatim comes out as \texttt{content} with certain characters escaped/protected.</li> </ul> <h3>In HTML and ODT</h3> <p>Code and Verbatim are treated identically</p> <h3>In TeXInfo</h3> <p>The same behaviour is followed as in LaTeX.</p>
29,938,522
Difference between Task.Run and QueueBackgroundWorkItem in Asp.Net
<p>What exactly is the difference using </p> <pre><code>Task.Run(() =&gt; { LongRunningMethod(); }); </code></pre> <p>or</p> <pre><code>HostingEnvironment.QueueBackgroundWorkItem(clt =&gt; LongRunningMethod()); </code></pre> <p>I tested on an Asp.Net MVC application in which I kept on writing a line to a text file for about 10 minutes inside an asynchronous task which is invoked using Task.Run or QBWI.</p> <p>It goes fine both using Task and QBWI. My async method keeps on writing to that file without any issues till 10 minutes. No disturbance from IIS I observed regarding its recycling.</p> <p>So what is special about QueueBackgroundWorkItem then?</p>
29,938,563
3
1
null
2015-04-29 08:40:12.857 UTC
9
2017-04-17 19:57:33.37 UTC
2016-09-23 21:14:33.94 UTC
null
1,870,803
null
379,916
null
1
49
c#|.net|asp.net-mvc|asynchronous|task-parallel-library
27,838
<p>The <a href="https://msdn.microsoft.com/en-us/library/dn636893(v=vs.110).aspx" rel="noreferrer">documentation</a> has an excellent explanation:</p> <blockquote> <p>Differs from a normal ThreadPool work item in that <strong>ASP.NET can keep track of how many work items registered through this API are currently running, and the ASP.NET runtime will try to delay AppDomain shutdown until these work items have finished executing.</strong> This API cannot be called outside of an ASP.NET-managed AppDomain. The provided CancellationToken will be signaled when the application is shutting down.</p> </blockquote> <p><code>Task.Factory.StartNew</code> does not register work with the ASP.NET runtime at all. You're running your code for 10 minutes, that makes no difference. IIS recycle happens at particular times which are <a href="https://msdn.microsoft.com/en-us/library/ms525803%28v=vs.90%29.aspx" rel="noreferrer">preset in IIS</a>. If you really want to test whats going on, you can attempt to <a href="https://stackoverflow.com/questions/249927/restarting-recycling-an-application-pool">force a recycle</a>.</p>
51,985,367
After adding django-debug to App, getting "'djdt' is not a registered namespace"
<p>My question is about setting up to use django-debug. I'm getting the above error after installing the toolbar and panel, and enabling these in my app. I've seen many suggestions for this or a closely related issue, and nothing I've tried has helped.</p> <p>The specific error, during template rendering of /usr/lib/python3.6/site-packages/debug_toolbar/templates/debug_toolbar/base.html, is from:</p> <pre><code>16 data-render-panel-url="{% url 'djdt:render_panel' %}" </code></pre> <p>My relevant settings.py entries:</p> <pre><code>DEBUG = True INSTALLED_APPS = [ 'debug_toolbar', 'debug_panel', ... ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'debug_panel.middleware.DebugPanelMiddleware', ... ] INTERNAL_IPS = ['127.0.0.1',] </code></pre> <p>Appended to my urls.py:</p> <pre><code>if settings.DEBUG: try: import debug_toolbar urlpatterns += [url(r'^__debug__/', include(debug_toolbar.urls))] except ImportError: pass </code></pre> <p>What I've tried:</p> <ul> <li>changing the order of these Middleware entries in settings.py (first, middle and last)</li> <li>adding a namespace attribute to my urlpatterns entry</li> </ul> <p>Thanks for any further suggestions.</p>
55,876,710
5
0
null
2018-08-23 12:01:10.687 UTC
null
2021-12-04 11:00:21.417 UTC
null
null
null
null
5,738,287
null
1
28
django|django-debug-toolbar
15,577
<p>You need to manually add 'djdt' routes to the end of urls.py (if you use 'namespace' in your apps, add below codes to 'urls.py' in your project):</p> <pre><code>if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] </code></pre>
8,734,022
Is there a way to check if a variable is defined in Java?
<p>In my app in android I need to check if a variable has been defined yet so I dont get a null pointer exception. Any way around this?</p>
8,734,055
3
0
null
2012-01-04 21:06:15.98 UTC
2
2019-05-09 07:00:29.703 UTC
null
null
null
null
1,119,636
null
1
18
java|android|variables
64,534
<p>The code won't compile if you try to use an undefined variable, because, In Java, variables must be defined before they are used.</p> <p>But note that variables can be null, and it is possible to check if one is null to avoid <code>NullPointerException</code>:</p> <pre><code>if (var != null) { //... } </code></pre>
8,585,216
Spring forward with added parameters?
<p>Is there a way to forward a request to another Controller while adding some parameter data to it? I tried adding to the ModelMap, but it doesn't seem to hang around. I am doing something like:</p> <pre><code>return "forward:/my-other-controller"; </code></pre> <p>Only other way I can think of is to put the parameters on the session and then pop them off in the target controller.</p>
8,658,036
4
0
null
2011-12-21 04:52:51.863 UTC
13
2017-02-10 06:53:13.11 UTC
null
null
null
null
73,501
null
1
27
java|spring|controller|forward
75,486
<p><strong>The simplest way is to add the data to the request.</strong> Since this is a forward, the same request is passed around to different handlers within the server. </p> <p>As example, let's start with a simple setup of two controllers, one forwarding to the other:</p> <pre><code>@Controller public class TestController { @RequestMapping(value="/test") public String showTestPage() { return "forward:/test2"; } } @Controller public class TestController2 { @RequestMapping(value="/test2") public String showTestPage() { return "testPageView"; } } </code></pre> <p>First way to add the data is to set it as attributes on the request. The new controllers will look like this (<strong>A</strong>):</p> <pre><code>@Controller public class TestController { @RequestMapping(value="/test") public String showTestPage(HttpServletRequest request) { request.setAttribute("param1", "foo"); request.setAttribute("param2", "bar"); return "forward:/test2"; } } @Controller public class TestController2 { @RequestMapping(value="/test2") public String showTestPage(HttpServletRequest request) { String param1 = (String) request.getAttribute("param1"); String param2 = (String) request.getAttribute("param2"); return "testPageView"; } } </code></pre> <p>Since the view name in the <a href="http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html#mvc-redirecting-forward-prefix" rel="noreferrer">forward prefix is basically an URL</a>, you can also have the following versions (attribute changed to parameter) (<strong>B</strong>):</p> <pre><code>@Controller public class TestController { @RequestMapping(value="/test") public String showTestPage() { return "forward:/test2?param1=foo&amp;param2=bar"; } } @Controller public class TestController2 { @RequestMapping(value="/test2") public String showTestPage(HttpServletRequest request) { String param1 = request.getParameter("param1"); String param2 = request.getParameter("param2"); return "testPageView"; } } </code></pre> <p>You can also further simplify the second controller by using annotations instead:</p> <pre><code>@Controller public class TestController2 { @RequestMapping(value="/test2") public String showTestPage(@RequestParam String param1, @RequestParam String param2) { return "testPageView"; } } </code></pre> <p>And just for the fun of it, and to show Spring's binding behavior in action, you could do it even like this (<strong>C</strong>):</p> <pre><code>@Controller public class TestController { @RequestMapping(value="/test") public String showTestPage() { return "forward:/test2?param1=foo&amp;param2=bar"; } } @Controller public class TestController2 { @RequestMapping(value="/test2") public String showTestPage(@ModelAttribute DummyBinder params) { String param1 = params.getParam1(); String param2 = params.getParam2(); return "testPageView"; } } class DummyBinder { private String param1; private String param2; public String getParam1() { return param1; } public void setParam1(String param1) { this.param1 = param1; } public String getParam2() { return param2; } public void setParam2(String param2) { this.param2 = param2; } } </code></pre> <p><strong>I would personally go with solution A for many parameters, and solution B for a few.</strong> Solution C has a sort of "huh...?!" effect so I would avoid it (also it works with parameters added to the URL so a few of those or you get a messy URL).</p> <p>Adding the data in the session would also work off course, but would extend the data's life time unnecessarily, so the best place is to add it on the request during the transition to the second controller.</p>
8,373,415
Difference between SHL and SAL in 80x86
<p>I have learned how to work with 80x86 assembler, so in bit-wise shift operation, I faced a problem with SAL and SHL usage. I means the difference between lines of code as follow :</p> <pre><code>MOV X, 0AAH SAL X, 4 MOV X, 0AAH SHL X, 4 </code></pre> <p>When we should use SHL and when use SAL? What is the difference of them?</p>
8,373,433
7
0
null
2011-12-04 05:04:12.233 UTC
3
2019-06-16 17:47:15.193 UTC
2018-01-01 20:48:11.81 UTC
null
3,885,376
null
860,721
null
1
34
assembly|x86-16|bit-shift
54,053
<p>According to <a href="http://siyobik.info/main/reference/instruction/SAL/SAR/SHL/SHR" rel="noreferrer">this</a>, they are the same:</p> <blockquote> <p>The shift arithmetic left (SAL) and shift logical left (SHL) instructions perform the same operation; they shift the bits in the destination operand to the left (toward more significant bit locations). For each shift count, the most significant bit of the destination operand is shifted into the CF flag, and the least significant bit is cleared (see Figure 7-7 in the Intel®64 and IA-32 Architectures Software Developer'sManual, Volume 1).</p> </blockquote> <p>Both were probably included just for completeness since there <em>is</em> a distinction for right-shifts.</p>
8,755,211
What is meant by the term "Instrumentation"?
<p>As the title suggests. Many explanations are really vague, can anyone provide a more solid definition?</p> <p>The term is used a lot in Android testing, but I don't think it's restricted to that platform.</p>
8,755,337
4
0
null
2012-01-06 08:29:39.833 UTC
8
2021-07-31 16:07:14.153 UTC
2012-01-06 08:37:21.753 UTC
user166390
null
null
201,113
null
1
42
instrumentation
28,738
<p>Some performance measurement tools add instrumentation to the code. E.g. they may binary translate, and add instructions to read the timers at the beginning and end of functions. Or this instrumentation, this reading of the timers, may be added to assembly, or C code, by an automated tool, or a programmer.</p> <p>Other performance measurement tools do not change the code that is being measured. E.g. UNIX prof sampling runs special code that is invoked at the timer interrupt, which generates a histogram of the instruction at which the interrupt is received.</p> <p>Some tools are hybrid: e.g. UNIX gprof combines prof-style interrupt sampling with mcount instrumentation added by the compiler -pg option to count which functions call each other.</p> <p>All performance measurement has overhead, but instrumentation tends to have more overhead than interrupt based sampling. On the other hand, instrumentation can measure more stuff.</p>
8,638,012
Fix key settings (Home/End/Insert/Delete) in .zshrc when running Zsh in Terminator Terminal Emulator
<p>I'm running Ubuntu 11.04. I installed the <a href="http://software.jessies.org/terminator/">Terminator Terminal Emulator</a> 0.95, and Zsh, version 4.3.15. <br/> I have (commonly known) problems with my keys inside the Zsh. At least these:</p> <ul> <li>Home/End, nothing happens</li> <li>Insert/Delete/PageUp/PageDown: a "~" is typed</li> </ul> <p>I already tried some configurations for .zshrc which should solve the problem, but no approach really worked so far. Maybe this is related to the combination of Terminator and Zsh. I took the 2 configs on this page: <a href="https://bbs.archlinux.org/viewtopic.php?pid=428669">https://bbs.archlinux.org/viewtopic.php?pid=428669</a>. </p> <p>Does oneone have a similar configuration (especially Terminator and Zsh) and figured out what needs to be inserted into the .zshrc to fix the key settings?</p>
8,645,267
3
0
null
2011-12-26 18:01:49.163 UTC
30
2020-06-29 20:23:51.827 UTC
2017-11-15 06:47:44.663 UTC
null
2,681,088
null
319,905
null
1
67
ubuntu|keyboard-shortcuts|zsh|zshrc|terminator
36,933
<p>To know the code of a key, execute <code>cat</code>, press enter, press the key, then Ctrl+C.</p> <p>For me, <code>Home</code> sends <code>^[[H</code> and <code>End</code> <code>^[[F</code>, so i can put i my <code>.zshrc</code> in my home dir</p> <pre><code>bindkey "^[[H" beginning-of-line bindkey "^[[F" end-of-line bindkey "^[[3~" delete-char </code></pre> <p>These codes could change with the terminal emulator you use.</p> <p><code>autoload zkbd ; zkbd</code> will create a file with an array of keycodes to use, like <code>bindkey "${key[Home]}" beginning-of-line</code>, and you can source a different file depending on the terminal.</p>
8,627,902
How to add a new line in textarea element?
<p>I want to add a newline in a textarea. I tried with <code>\n</code> and <code>&lt;br/&gt;</code> tag but are not working. You can see above the HTML code. Can you help me to insert a newline in a textarea?</p> <pre><code>&lt;textarea cols='60' rows='8'&gt;This is my statement one.\n This is my statement2&lt;/textarea&gt; &lt;textarea cols='60' rows='8'&gt;This is my statement one.&lt;br/&gt; This is my statement2&lt;/textarea&gt; </code></pre>
8,627,926
15
0
null
2011-12-25 02:12:45.467 UTC
77
2022-05-14 16:05:02.213 UTC
2021-01-28 12:14:10.813 UTC
null
6,723,698
null
1,104,027
null
1
337
html|textarea|line-breaks
781,409
<p>Try this one:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;textarea cols='60' rows='8'&gt;This is my statement one.&amp;#13;&amp;#10;This is my statement2&lt;/textarea&gt;</code></pre> </div> </div> </p> <p><code>&amp;#10;</code> Line Feed and <code>&amp;#13;</code> Carriage Return are <a href="http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references" rel="noreferrer">HTML entities<sup>wikipedia</sup></a>. This way you are actually parsing the new line ("\n") rather than displaying it as text.</p>
55,303,216
Pycharm jupyter notebook wsl: Jupyter package is not installed
<p>I would like to use Jupyter notebook inside Pycharm. The project interpreter is a python2.7 from a virtual environment inside WSL (ubuntu 18.04).</p> <p>The Jupiter package is correctly installed inside the virtual environment (I can run it by <code>jupyter notebook</code>). </p> <p>My problem is that when I want to use Jupyter notebook inside Pycharm, I get the following error: <code>Run Error Jupyter package is not installed</code> (see picture).</p> <p><a href="https://i.stack.imgur.com/67AWY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/67AWY.png" alt="enter image description here"></a></p> <p>Any idea what's going on here?</p>
55,401,528
6
1
null
2019-03-22 15:41:20.633 UTC
9
2021-08-31 07:06:23.923 UTC
null
null
null
null
3,954,958
null
1
23
python|pycharm|jupyter-notebook|jupyter
24,627
<p>I had this problem in Python 3. Below are the steps I took to resolve the issue; I believe they should resolve the issue for you too:</p> <ol> <li><p>I had Jupyter Lab installed. Pycharm only works with Jupyter Notebook. Long story short, if you have Jupyter Lab installed you need to uninstall all your packages using:</p> <p>$ pip freeze | xargs pip uninstall -y</p></li> <li><p>Restart your computer</p></li> <li><p>Follow <a href="https://jupyter.org/install" rel="noreferrer">Jupyter Notebook installation instructions</a></p></li> <li><p>Make sure WSL is set up through pycharm instructions: <a href="https://www.jetbrains.com/help/pycharm/using-wsl-as-a-remote-interpreter.html" rel="noreferrer">wsl pycharm instructions</a></p></li> <li><p>In Pycharm, open an .ipynb file. Click the dropdown that says "Managed Jupyter server" It's right above the text editor. Select "configure Jupyter server". Check configured server.</p></li> <li><p>In your wsl terminal, type jupyter notebook. Copy and paste the text that looks like: <a href="http://localhost:8888/?token=874asdf687asd6fasd8f74ds6f4s9d8f7sddf" rel="noreferrer">http://localhost:8888/?token=874asdf687asd6fasd8f74ds6f4s9d8f7sddf</a> into the cofigured server box in Pycharm.</p></li> </ol> <p>That's it. You should be able to run the jupyter cells in pycharm now.</p>
48,261,227
Use Axios.Get with params and config together
<p>How do I use <code>axios.get</code> with params and config together? My code is not working. Please help me this basic issue!</p> <pre><code>let config = { 'headers': {'Authorization': 'JWT ' + this.$store.state.token} } let f = 0 axios.get('http://localhost:8000/api/v1/f/', { params: { page: f + 1 }, config: this.config }) </code></pre>
48,261,393
2
0
null
2018-01-15 10:36:18.78 UTC
7
2019-02-22 02:15:51.14 UTC
2019-02-22 00:47:24.693 UTC
null
7,680,801
null
7,155,095
null
1
15
javascript|axios
64,234
<p>Axios takes the entire config in the second argument, not a list of config objects. Put the params inside the config, and pass the entire object as the second argument:</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>let f = 0 let config = { headers: {'Authorization': 'JWT ' + this.$store.state.token}, params: { page: f + 1 }, } axios.get('http://localhost:8000/api/v1/f/', config)</code></pre> </div> </div> </p>
43,667,853
ngrx dealing with nested array in object
<p>I am learning the redux pattern and using ngrx with angular 2. I am creating a sample blog site which has following shape.</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>export interface BlogContent { id: string; header: string; tags: string[]; title: string; actualContent: ActualContent[]; }</code></pre> </div> </div> </p> <p>and my reducer and actions are as following:</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>import { ActionReducer, Action } from '@ngrx/store'; import * as _ from 'lodash'; export interface ActualContent { id: string; type: string; data: string; } export interface BlogContent { id: string; header: string; tags: string[]; title: string; actualContent: ActualContent[]; } export const initialState: BlogContent = { id: '', header: '', tags: [], title: '', actualContent: [], }; export const ADD_OPERATION = 'ADD_OPERATION'; export const REMOVE_OPERATION = 'REMOVE_OPERATION'; export const RESET_OPERATION = 'RESET_OPERATION'; export const ADD_IMAGE_ID = 'ADD_IMAGE_ID'; export const ADD_FULL_BLOG = 'ADD_FULL_BLOG'; export const ADD_BLOG_CONTENT_OPERATION = 'ADD_BLOG_CONTENT_OPERATION'; export const ADD_BLOG_TAG_OPERATION = 'ADD_BLOG_TAG_OPERATION'; export const blogContent: ActionReducer&lt;BlogContent&gt; = (state: BlogContent= initialState, action: Action ) =&gt; { switch (action.type) { case ADD_OPERATION : return Object.assign({}, state, action.payload ); case ADD_BLOG_CONTENT_OPERATION : return Object.assign({}, state, { actualContent: [...state.actualContent, action.payload]}); case ADD_BLOG_TAG_OPERATION : return Object.assign({}, state, { tags: [...state.tags, action.payload]}); case REMOVE_OPERATION : return Object.assign({}, state, { actualContent: state.actualContent.filter((blog) =&gt; blog.id !== action.payload.id) }); case ADD_IMAGE_ID : { let index = _.findIndex(state.actualContent, {id: action.payload.id}); console.log(index); if ( index &gt;= 0 ) { return Object.assign({}, state, { actualContent : [ ...state.actualContent.slice(0, index), action.payload, ...state.actualContent.slice(index + 1) ] }); } return state; } default : return state; } };</code></pre> </div> </div> </p> <p>and this is working fine but i am not sure if its the right approach or should i somehow separate the ActualContent into its own reducer and actions and then merge them. Sorry if this post does not belong here and you can guide me where should put this post and i will remove it from here. Thanks in advance.</p> <p>P.S. I have done some research but couldnt find any article that has complex nested objects so that i can refer. Please add any useful blog links of ngrx or related topic which can help me out.</p>
43,743,224
1
0
null
2017-04-27 21:03:38.1 UTC
10
2020-02-11 08:16:44.21 UTC
null
null
null
null
3,288,525
null
1
19
javascript|functional-programming|redux|ngrx
7,079
<p>Instead of having a nested structure</p> <pre><code>export interface BlogContent { id: string; header: string; tags: string[]; title: string; actualContent: ActualContent[]; &lt;------ NESTED } </code></pre> <p>You should have a normalized state.</p> <p>For example here you should have something like : </p> <pre><code>// this should be into your store export interface BlogContents { byId: { [key: string]: BlogContent }; allIds: string[]; } // this is made to type the objects you'll find in the byId export interface BlogContent { id: string; // ... actualContentIds: string[]; } // ---------------------------------------------------------- // this should be into your store export interface ActualContents { byId: { [key: string]: ActualContent }; allIds: string[]; } export interface ActualContent { id: string; // ... } </code></pre> <p>So if you try to populate your store it'd look like that :</p> <pre><code>const blogContentsState: BlogContents = { byId: { blogContentId0: { id: 'idBlogContent0', // ... actualContentIds: ['actualContentId0', 'actualContentId1', 'actualContentId2'] } }, allIds: ['blogContentId0'] }; const actualContentState: ActualContents = { byId: { actualContentId0: { id: 'actualContentId0', // ... }, actualContentId1: { id: 'actualContentId1', // ... }, actualContentId2: { id: 'actualContentId2', // ... } }, allIds: ['actualContentId0', 'actualContentId1', 'actualContentId2'] }; </code></pre> <p>In your logic or view (for example with Angular), you need your nested structure so you can iterate over your array and thus, you don't want to iterate on a string array of IDs. Instead you'd like <code>actualContent: ActualContent[];</code>.</p> <p>For that, you create a <code>selector</code>. Every time your store change, your selector will kicks in and generate a new "view" of your raw data.</p> <pre><code>// assuming that you can blogContentsState and actualContentsState from your store const getBlogContents = (blogContentsState, actualContentsState) =&gt; blogContentsState .allIds .map(blogContentId =&gt; ({ ...blogContentsState.byId[blogContentId], actualContent: blogContentsState .byId[blogContentId] .actualContentIds .map(actualContentId =&gt; actualContentsState.byId[actualContentId]) })); </code></pre> <p>I know it can be a lot to process at the beginning and I invite you to read the <a href="https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape/" rel="noreferrer">official doc about selectors and normalized state</a></p> <p>As you're learning ngrx, you might want to take a look into a small project I've made called Pizza-Sync. <a href="https://github.com/maxime1992/pizza-sync" rel="noreferrer">Code source is on Github</a>. It's a project were I've done something like that to demo :). (You should also definitely install the <a href="https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd" rel="noreferrer">ReduxDevTools app</a> to see how is the store).</p> <p>I made a small video focus only on Redux with Pizza-Sync if you're interested : <a href="https://youtu.be/I28m9lwp15Y" rel="noreferrer">https://youtu.be/I28m9lwp15Y</a></p>
41,979,458
How to get angular2 [innerHtml] to work
<p>I don't know what am doing wrong as no errors are report.</p> <p>I have a component class </p> <pre><code>import { Component, OnInit, ViewContainerRef } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { testhtml = "&lt;p&gt;Hello world&lt;/p&gt;"; constructor(){} } } </code></pre> <p>And in my template file, I do something like this:</p> <pre><code>&lt;div class="blog-post"&gt;[innerHtml]="testhtml"&lt;/div&gt; </code></pre> <p>But this doesn't seem to work. Is there something else I need to import?</p> <p>I am using angular-cli "version": "1.0.0-beta.26",</p>
41,979,685
2
2
null
2017-02-01 12:08:43.237 UTC
3
2018-06-05 14:51:32.093 UTC
null
null
null
null
6,180,766
null
1
29
angular
105,478
<p>Angular uses <code>{{property}}</code> for interpolation of values. That is the way that you would display plain text in your <code>div</code>, like so</p> <p><strong>Solution 1:</strong></p> <pre><code>&lt;div class="blog-post"&gt;{{testhtml}}&lt;/div&gt; </code></pre> <p>But that will write out text, not HTML.</p> <p>For HTML, you will need to bind to the property</p> <p><strong>Solution 2:</strong></p> <pre><code>&lt;div class="blog-post" [innerHtml]="testhtml"&gt;&lt;/div&gt; </code></pre> <p>Note I moved the <code>[innerHtml]</code> to inside the <code>div</code> tag.</p> <p>Leaving out the square brackets would bind to the attribute, so you would need to interpolate again</p> <p><strong>Solution 3:</strong></p> <pre><code>&lt;div class="blog-post" innerHtml="{{testhtml}}"&gt;&lt;/div&gt; </code></pre> <p>The property binding (<strong>Solution 2</strong>) is the preferred method.</p>
42,035,104
How to unit test Go errors
<p>When you are unit testing functions that have an <code>error</code> return type, I was wondering how to properly unit test for this error. Are you supposed to just check if the error is nil or not nil? Or are you supposed to verify the error string matches an expected string as well?</p>
42,036,847
4
2
null
2017-02-04 00:23:45.07 UTC
7
2022-07-20 06:59:09.533 UTC
2019-04-22 14:45:29.28 UTC
null
2,777,965
null
1,751,481
null
1
46
unit-testing|go|error-handling
60,830
<p>In most cases you can just check if the error is not nil.</p> <p>I'd recommend not checking error strings unless absolutely necessary. I generally consider error strings to be only for human consumption.</p> <p>If you need more detail about the error, one better alternative is to have custom error types. Then you can do a switch over the err.(type) and see if it's a type you expect. If you need even more detail, you can make the custom error types contain values which you can then check in a test.</p> <p>Go's error is just an interface for a type that has an <code>Error() string</code> method, so implementing them yourself is straightforward. <a href="https://blog.golang.org/error-handling-and-go" rel="noreferrer">https://blog.golang.org/error-handling-and-go</a></p>
35,286,094
How to close the whole browser window by keeping the webDriver active?
<p>In my batch execution, multiple browsers with multiple tabs are getting opened for first scenario. I wanted to close all these browsers before starting second scenario. </p> <p><code>Driver.close()</code> is just closing one tab of the browser. <code>Driver.quit()</code> is closing all the browsers and also ending the <code>WebDriver</code> session. So , am unable to run the batch execution. Please provide a solution for this.</p>
35,286,232
4
1
null
2016-02-09 07:20:59.913 UTC
7
2022-01-26 11:26:07.14 UTC
2017-04-06 13:09:47.573 UTC
null
1,509,764
null
5,520,468
null
1
22
selenium|selenium-webdriver|webdriver
104,579
<p>The below explanation should explain the difference between <strong>driver.close</strong> and <strong>driver.quit</strong> methods in WebDriver. I hope you find it useful.</p> <p><strong>driver.close</strong> and <strong>driver.quit</strong> are two different methods for closing the browser session in Selenium WebDriver. </p> <p>Understanding both of them and knowing when to use each method is important in your test execution. Therefore, I have tried to shed some light on both of these methods.</p> <blockquote> <p><strong>driver.close</strong> - This method closes the browser window on which the focus is set. <strong>driver.quit</strong> close the session of webdriver while <strong>driver.close</strong> only close the current window on which selenium control is present but webdriver session not close yet, if no other window open and you call <strong>driver.close</strong> then it also close the session of webdriver.</p> <p><strong>driver.quit</strong> – This method basically calls driver.dispose a now internal method which in turn closes all of the browser windows and ends the WebDriver session gracefully.</p> </blockquote> <p><strong>driver.dispose</strong> - As mentioned previously, is an internal method of WebDriver which has been silently dropped according to another answer - Verification needed. This method really doesn't have a use-case in a normal test workflow as either of the previous methods should work for most use cases.</p> <p>Explanation use case: You should use <strong>driver.quit</strong> whenever you want to end the program. It will close all opened browser windows and terminates the WebDriver session. If you do not use driver.quit at the end of the program, the WebDriver session will not close properly and files would not be cleared from memory. This may result in memory leak errors.</p> <p>............</p> <p>Now In that case you need to specific browser. Below is code which will close all the child windows except the Main window.</p> <pre><code>String homeWindow = driver.getWindowHandle(); Set&lt;String&gt; allWindows = driver.getWindowHandles(); //Use Iterator to iterate over windows Iterator&lt;String&gt; windowIterator = allWindows.iterator(); //Verify next window is available while(windowIterator.hasNext()) { //Store the Recruiter window id String childWindow = windowIterator.next(); } //Here we will compare if parent window is not equal to child window if (homeWindow.equals(childWindow)) { driver.switchTo().window(childWindow); driver.close(); } </code></pre> <p>Now here you need to modify or add the condition according to your need</p> <pre><code>if (homeWindow.equals(childWindow)) { driver.switchTo().window(childWindow); driver.close(); } </code></pre> <p>Currently it is checking only if home window is equal to childwindow or not. Here you need to specify the condition like which id's you want to close. I never tried it so just suggested you the way to achive your requirement.</p>
20,603,599
How to Open only UserForm of an excel macro from batch file
<p>I'm trying to open the UserForm1 of an excel macro through batch file. I'm able to open that but excel is also getting opened along with that. I want only UserForm1 to be opened not the excel. Below is my approach :</p> <p>I have written a macros to open the UserForm1</p> <pre><code>Sub open_form() UserForm1.Show End Sub </code></pre> <p>In batch File:</p> <pre><code>@echo off cd "c:\Test\" openFormTest.xlsm </code></pre> <p>By the above approach, When I'm running the batch file both UserForm1 and excel are getting open, but I want to open only UserForm1. Kindly help me out</p>
20,603,619
3
0
null
2013-12-16 04:41:18.463 UTC
1
2015-01-30 14:30:48.13 UTC
2015-01-30 14:30:48.13 UTC
null
1,505,120
null
3,003,807
null
1
6
vba|excel|batch-file
49,580
<p>You need to show the <code>UserForm</code> in <code>modeless</code> mode and then hide the application.</p> <p>try this</p> <pre><code>Sub open_form() Application.Visible = False UserForm1.Show vbModeless End Sub </code></pre> <p>and either in a button you need to set it back to true or you can use the <code>UserForm_QueryClose</code> event</p> <pre><code>Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) Application.Visible = True ThisWorkbook.Close SaveChanges:=False End Sub </code></pre>
20,061,529
Sublime Text CoffeeScript build system: `env: node: No such file or directory`
<p>I'm trying to set up a CoffeeScript build system in Sublime Text 3, but I keep getting the following error:</p> <pre><code>env: node: No such file or directory [Finished in 0.0s with exit code 127] [cmd: ['coffee', '-o','/Users/jcourtdemone/Sites/autotempest.com/new_design_sandbox/static/script', '-cw', '/Users/jcourtdemone/Sites/autotempest.com/new_design_sandbox/static/coffee']] [dir: /Users/jcourtdemone/Sites/autotempest.com/new_design_sandbox/static/coffee] [path: /usr/bin:/bin:/usr/sbin:/sbin] </code></pre> <p>My build system looks like this:</p> <pre><code>{ "name": "Coffee - AT", "cmd": ["coffee","-o","${project_path:${folder}}/static/script","-cw","${project_path:${folder}}/static/coffee"], "selector": "source.coffee", "path":"/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/lib/node_modules/coffee-script/bin" } </code></pre> <p>Two things strange about this.</p> <p>1) It says it's looking in <code>/usr/bin</code> where a symlink to <code>coffee</code> exists.</p> <p>2) Because of (1), I overrode <code>$PATH</code> to include the actual location of <code>coffee</code> which is <code>/usr/local/lib/node_modules/coffee-script/bin</code>, but for some reason, <code>$PATH</code> isn't being overridden properly, it's sticking with the default <code>$PATH</code>.</p> <p>Things to note:</p> <p>i) I've verified that all paths are correct and pass normally through a regular terminal command.</p> <p>ii) Tried with a <code>"shell": true</code> variable in the build system.</p> <p>iii) I have another build system for Compass like this that works fine.</p> <p>Anyone run into similar problems or issues? Any ideas?</p>
20,077,620
7
0
null
2013-11-19 01:38:22.75 UTC
20
2015-04-20 00:01:46.187 UTC
null
null
null
null
977,591
null
1
44
coffeescript|build-automation|sublimetext|sublimetext3
46,475
<p>In Terminal, type <code>which node</code>, then create a symlink to that location in <code>/usr/bin</code>. For example, if <code>node</code> lives in <code>/usr/local/bin</code>, create the symlink like so:</p> <pre><code>sudo ln -s /usr/local/bin/node /usr/bin/node </code></pre> <p>If you look at the source of your <code>coffee</code> script, you'll probably find that the first line is something along the lines of:</p> <pre><code>#!/usr/bin/env node </code></pre> <p>Exit code 127 in Sublime means that an <code>env</code> command has failed - so in your case, the build system is finding <code>coffee</code>, but it can't execute it because the <code>node</code> binary isn't in Sublime's default search path.</p> <p>There are two ways to redefine the default search path for Sublime. The first (and easiest) is to always open it from the command line using the built-in <a href="http://www.sublimetext.com/docs/3/osx_command_line.html" rel="noreferrer"><code>subl</code></a> command. If you're an OS X power user and don't mind messing with important system settings, check out <a href="https://unix.stackexchange.com/q/89076/19512">my post</a> on unix.SE on how to alter the default <code>/usr/bin:/bin:/usr/sbin:/sbin</code> path that you're seeing. Be forewarned that if you don't do things correctly, you may break your system. However, if you're running Mountain Lion (10.8.X) and you follow the instructions exactly, everything should be fine. (I haven't upgraded to Mavericks, so no guarantees on whether it'll work with that version.)</p>
20,349,189
Unable to access BigQuery from local App Engine development server
<p>This is specifically a question relating to server to server authorisation between a python Google AppEngine app and Google's BigQuery, but could be relevant for other cloud services.</p> <p><strong>tldr; Is it possible to get the App Engine local development server to authenticate with the remote BigQuery service? Better yet is there a local BigQuery?</strong></p> <p>I understand that AppAssertionCredentials does not currently work on the local development server, though that in itself is very frustrating.</p> <p>The alternative method which works for standard python code, outside of the local development server sandbox, detailed <a href="https://developers.google.com/bigquery/docs/authorization#service-accounts">here</a> does not work for the local development server because even with PyCrypto enabled the sandbox does not allow some posix modules e.g. 'pwd'.</p> <p>I have got <strong>AppAssertionCredentials</strong> working on the remote server and the <strong>SignedJwtAssertionCredentials</strong> method working in native python locally, so the service accounts are set up properly.</p> <p>The imports fail within oauth2client/crypt.py within the try/except blocks - after commenting them out the sandbox whitelist exceptions are easily seen.</p> <p>I've fiddled around with adding 'pwd' to the whitelist, then another problem crops up, so I scurried back out of that rabbit hole.</p> <p>I've tried including PyCrypto directly into the project with similar results.</p> <p>I've also tried with OpenSSL with similar results.</p> <p>I have looked for a local appengine specific PyCrypto to no avail, have I missed one? I should say this is on Mac OSX - perhaps I should fire up a linux box and give that a go?</p>
22,723,127
5
0
null
2013-12-03 10:55:56.417 UTC
16
2014-03-28 21:46:35.77 UTC
2014-03-28 21:06:16.29 UTC
null
2,415,668
null
326,722
null
1
25
google-app-engine|google-oauth|google-bigquery|google-api-python-client
6,356
<p>A recent release of Google App Engine SDK added support for the AppAssertionCredentials method on the development server. To use this method locally, add the following arguments to <code>dev_appserver.py</code>:</p> <pre><code>$ dev_appserver.py --help ... Application Identity: --appidentity_email_address APPIDENTITY_EMAIL_ADDRESS email address associated with a service account that has a downloadable key. May be None for no local application identity. (default: None) --appidentity_private_key_path APPIDENTITY_PRIVATE_KEY_PATH path to private key file associated with service account (.pem format). Must be set if appidentity_email_address is set. (default: None) </code></pre> <p>To use these:</p> <ol> <li><p>In <a href="https://console.developers.google.com/" rel="noreferrer">Google Developer Console</a>, select a project then navigate to &quot;API &amp; auth&quot; -&gt; &quot;Credentials&quot; -&gt; &quot;Create new client ID&quot;.</p> </li> <li><p>Select &quot;Service account&quot; and follow the prompts to download the private key in PKCS12 (.p12) format. Take note of the email address for the service account.</p> </li> <li><p>Make sure you add that service account email address to the &quot;Permissions&quot; tab for any project that contains data it needs to access, by default it is added to the project team in which it was created.</p> </li> <li><p>Convert the PKCS12 format to PKCS1 format using the following command:</p> <p><code>$ cat /path/to/xxxx-privatekey.p12 | openssl pkcs12 -nodes -nocerts -passin pass:notasecret | openssl rsa &gt; /path/to/secret.pem</code></p> </li> <li><p>Start <code>dev_appserver.py</code> as:</p> <p><code>$ dev_appserver.py --appidentity_email_address [email protected] --appidentity_private_key_path /path/to/secret.pem ...</code></p> </li> <li><p>Use <code>appidentity</code> module and <code>AppAssertionCredentials</code> in the same manner locally as you normally would in production.</p> </li> </ol> <p>Please ensure that <code>/path/to/secret.pem</code> is outside of your application source directory so that it is not accidentally deployed as part of your application.</p>
6,278,894
How to create a java.sql.Blob object in Java SE 1.5.0 with a byte[] input?
<p>I want to create a Blob object from a byte[] input to update a table using <code>PreparedStatement#setBlob()</code>. In J2SE 6, we have <a href="http://download.oracle.com/javase/6/docs/api/java/sql/Connection.html#createBlob%28%29"><code>java.sql.Connection#createBlob()</code></a> to get this done. Is there anything similar to this available in J2SE 1.5.0? What is the best way to update a BLOB type column with a <code>byte[]</code> data in J2SE 1.5.0?</p>
6,279,014
3
1
null
2011-06-08 12:46:30.563 UTC
3
2015-02-05 16:15:22.737 UTC
2015-02-05 16:15:22.737 UTC
null
251,173
null
697,926
null
1
19
java|jdbc|blob
41,792
<p>An example, using <a href="http://download.oracle.com/javase/6/docs/api/javax/sql/rowset/serial/SerialBlob.html">SerialBlob</a>:</p> <pre><code>import java.sql.Blob; import javax.sql.rowset.serial.SerialBlob; byte[] byteArray = .....; Blob blob = new SerialBlob(byteArray); </code></pre>
5,697,750
What exactly does the "u" do? "git push -u origin master" vs "git push origin master"
<p>I'm apparently terrible at using git, despite my best attempts to understand it. </p> <p>From <a href="http://www.kernel.org/pub/software/scm/git/docs/git-push.html">kernel.org</a> for <code>git push</code>:</p> <blockquote> <p>-u</p> <p>--set-upstream</p> <p>For every branch that is up to date or successfully pushed, add upstream (tracking) reference, used by argument-less git-pull(1) and other commands. For more information, see <code>branch.&lt;name&gt;.merge</code> in git-config(1).</p> </blockquote> <p>Here's <code>branch.&lt;name&gt;.merge</code> from <code>git config</code>:</p> <blockquote> <p><code>branch.&lt;name&gt;.merge</code></p> <p>Defines, together with <code>branch.&lt;name&gt;.remote</code>, the upstream branch for the given branch. It tells git fetch/git pull which branch to merge and can also affect git push (see push.default). When in branch <code>&lt;name&gt;</code>, it tells git fetch the default refspec to be marked for merging in FETCH_HEAD. The value is handled like the remote part of a refspec, and must match a ref which is fetched from the remote given by <code>"branch.&lt;name&gt;.remote"</code>. The merge information is used by git pull (which at first calls git fetch) to lookup the default branch for merging. Without this option, git pull defaults to merge the first refspec fetched. Specify multiple values to get an octopus merge. If you wish to setup git pull so that it merges into <code>&lt;name&gt;</code> from another branch in the local repository, you can point <code>branch.&lt;name&gt;.merge</code> to the desired branch, and use the special setting . (a period) for <code>branch.&lt;name&gt;.remote</code>.</p> </blockquote> <p>I successfully set up a remote repository with github, and I successfully pushed my first commit to it with:</p> <pre><code>git push -u origin master </code></pre> <p>Then, I unwittingly successfully pushed my second commit to my remote repository using:</p> <pre><code>git commit -m '[...]' </code></pre> <p>However, incorrectly thinking I would have to push again to <code>origin</code> from <code>master</code>, I ran:</p> <pre><code># note: no -u git push origin master </code></pre> <p>What did that do? It didn't seem to have any effect at all. Did I "undo" <code>git push -u origin master</code>?</p>
5,697,856
4
1
null
2011-04-18 01:42:48.45 UTC
182
2021-07-21 05:31:54.513 UTC
2011-04-18 01:55:23.95 UTC
null
527,623
null
527,623
null
1
425
git
239,772
<p>The key is "argument-less git-pull". When you do a <code>git pull</code> from a branch, without specifying a source remote or branch, git looks at the <code>branch.&lt;name&gt;.merge</code> setting to know where to pull from. <code>git push -u</code> sets this information for the branch you're pushing.</p> <p>To see the difference, let's use a new empty branch:</p> <pre><code>$ git checkout -b test </code></pre> <p>First, we push without <code>-u</code>:</p> <pre><code>$ git push origin test $ git pull You asked me to pull without telling me which branch you want to merge with, and 'branch.test.merge' in your configuration file does not tell me, either. Please specify which branch you want to use on the command line and try again (e.g. 'git pull &lt;repository&gt; &lt;refspec&gt;'). See git-pull(1) for details. If you often merge with the same branch, you may want to use something like the following in your configuration file: [branch "test"] remote = &lt;nickname&gt; merge = &lt;remote-ref&gt; [remote "&lt;nickname&gt;"] url = &lt;url&gt; fetch = &lt;refspec&gt; See git-config(1) for details. </code></pre> <p>Now if we add <code>-u</code>:</p> <pre><code>$ git push -u origin test Branch test set up to track remote branch test from origin. Everything up-to-date $ git pull Already up-to-date. </code></pre> <p>Note that tracking information has been set up so that <code>git pull</code> works as expected without specifying the remote or branch.</p> <p><strong>Update:</strong> Bonus tips:</p> <ul> <li>As Mark mentions in a comment, in addition to <code>git pull</code> this setting also affects default behavior of <code>git push</code>. If you get in the habit of using <code>-u</code> to capture the remote branch you intend to track, I recommend setting your <code>push.default</code> config value to <code>upstream</code>.</li> <li><code>git push -u &lt;remote&gt; HEAD</code> will push the current branch to a branch of the same name on <code>&lt;remote&gt;</code> (and also set up tracking so you can do <code>git push</code> after that).</li> </ul>
2,277,165
Qt single EXE with LGPL?
<p>I don't know much about the LGPL/GPL when it comes to distributing programs (without a Qt license); If I made a program, could I statically link the libraries to the exe so I have a single file to distribute when:</p> <ul> <li><p>The program does not cost anything, it's just being distributed (closed source or open source)?</p></li> <li><p>When you have to pay for the program can you still statically link?</p></li> </ul>
2,277,213
2
0
null
2010-02-16 23:25:23.47 UTC
12
2014-07-17 20:27:55.633 UTC
2012-10-24 08:37:15.193 UTC
null
321,731
null
263,026
null
1
12
qt|lgpl
7,913
<p>No, if your program is closed source and you want to link against the LGPL version of Qt you must use dynamic linking. If you want to statically link then you must buy a license for Qt.</p> <p>To use LGPL code in your closed source project, the user has to be able to replace the lgpl portion of the code. The easiest and by far the most common way to do this is to put all the LGPL code in a dll and then the user can replace the dll if they choose.</p> <p>You are also allowed to use whatever technical means your language allows to accomplish the same goal. You can distribute object files and then the user can relink as other commenter pointed out, but I have never seen this done in practice.</p> <p>It does not matter whether or not your product is free or pay. You can sell GPL/LGPL products.</p>
2,326,998
What happened to AssemblyDescription in Windows 7?
<p>We were using the AssemblyDescription attribute to add notes to our assemblies (e.g. fix/branch info).</p> <p>The text was visible on XP in the file Properties/Comments. However in Windows 7 this field has been hidden.</p> <p>Is there a way to show this field in explorer or any other tool?</p> <p>Does MS explain anywhere why this field was removed and what we should use instead? (AssemblyTitle?)</p>
2,327,095
2
1
null
2010-02-24 15:10:28.84 UTC
7
2017-02-28 15:46:53.317 UTC
2017-02-28 15:46:53.317 UTC
null
1,033,581
null
52,817
null
1
34
.net|windows-7
6,020
<p>In my test assembly I have this defined in my AssemblyInfo.cs</p> <pre><code>[assembly: AssemblyDescription("this is a description")] </code></pre> <p>I can use either of these lines to retrieve that text from the resultant assembly:</p> <p>via PowerShell</p> <pre><code>(dir $path).VersionInfo.Comments </code></pre> <p>via C#</p> <pre><code>System.Diagnostics.FileVersionInfo.GetVersionInfo(path).Comments </code></pre>
1,588,306
Base64 encoded string to file
<p>I have a base64 encoded string.</p> <p>How can I write this base64 encoded string to a file?</p>
1,588,323
2
0
null
2009-10-19 12:05:00.787 UTC
12
2022-01-13 14:39:20.29 UTC
2015-03-27 17:48:44.667 UTC
null
23,199
null
41,543
null
1
70
c#|encoding|base64
103,916
<p>Try this:</p> <pre><code>File.WriteAllBytes(@"c:\yourfile", Convert.FromBase64String(yourBase64String)); </code></pre>
5,765,955
Javascript array : why is this not valid?
<p>I have the following working code :</p> <pre><code>var routes = []; </code></pre> <p>Eclipse validator for javascript prints the following warning :</p> <pre><code>Type mismatch: cannot convert from any[] to any </code></pre> <p>What is wrong with my empty array ?</p> <p><strong>Edit</strong> : the warning disappeared later. Apparently Eclipse was wrong and the question needs to be closed. Sorry about that.</p>
7,214,586
5
7
null
2011-04-23 18:07:35.247 UTC
4
2016-01-19 14:11:02.553 UTC
2016-01-19 14:11:02.553 UTC
null
990,423
null
245,552
null
1
32
javascript|arrays
7,489
<p>Your JavaScript is valid, the problem is with JSDT plugin for Eclipse. In the latest version they introduced a type verification which is problematic in many situations - not only for empty arrays (like in your case). Another typical case may look like this: <code>a = b || c;</code> The plugin will complain when b and c are of different types (which is absolutely valid code for JavaScript). There is several bugs already reported to JSDT developers about this problem, but the issues are not fixed yet. </p> <p>Unfortunately currently it is not possible to switch off the type verification using JSDT configuration screen in Eclipse. I switched it off directly from the JSDT source code. To do this, please follow these steps:</p> <ol> <li>Download the JSDT source code from <a href="http://dev.eclipse.org/viewcvs/viewvc.cgi/?root=WebTools_Project" rel="noreferrer">Eclipse WebTools Project</a></li> <li>Open the <code>org.eclipse.wst.jsdt.debug.core</code> project with Eclipse. Make sure you have Eclipse SDK installed. It might also be required to adjust some dependencies in the <code>plugin.xml</code> file.</li> <li>The type verification is located in <code>computeSeverity</code> method of <code>ProblemReporter</code> class. </li> <li>To switch off type verification replace the line: <code>case IProblem.TypeMismatch: return ProblemSeverities.Warning;</code> with <code>case IProblem.TypeMismatch: return ProblemSeverities.Ignore;</code></li> <li>Build the project and close Eclipse.</li> <li>In Eclipse folder find the file named <code>org.eclipse.wst.jsdt.core&lt;version&gt;.jar</code> - make a safe copy of it, then open the jar file and replace the <code>ProblemReporter.class</code> file with the one you compiled in the step 5 (the file is in <code>bin</code> folder of your project).</li> <li>Start Eclipse and clean your JavaScript project. All type checking will be ignored by JSDT.</li> </ol> <p>Important! Make sure you've downloaded the same version of JSDT that you are using in Eclipse. Eventually instead of replacing a single file you can replace the entire plugin. </p> <p>If you don't want to download and compile the plugin by yourself you can try with my fixed version. I've placed it on my <a href="http://functionsack.com/eclipse/org.eclipse.wst.jsdt.core_1.1.100.v201104272153.jar" rel="noreferrer">FunctionSack</a> webpage. I am using Eclipse 3.7 (Indigo) with JSDT 1.3.0, so make sure you have similar configuration if you want to use my file.</p>
6,222,053
Problem reading JPEG Metadata (Orientation)
<p>I've got a JPEG image which was taken on an iphone. On my desktop PC (Windows Photo Viewer, Google Chrome, etc) the orientation is incorrect.</p> <p>I'm working on an ASP.NET MVC 3 web application where i need to upload photos (currently using plupload).</p> <p>I've got some server-side code to process images, including reading EXIF data.</p> <p>I've tried reading the <code>PropertyTagOrientation</code> field in the EXIF meta data (using GDI - <code>Image.PropertyItems</code>), but the field isn't present.</p> <p>So it's either some specific iphone meta data, or some other meta data.</p> <p>I've used another tool like Aurigma Photo Uploader, and it reads the meta data correctly and rotates the image. How does it do this?</p> <p>Does anyone know what other JPEG meta data could contain the information required in order to know that it needs to be rotated, that is used by Aurigma?</p> <p>Here's the code i'm using to read the EXIF data:</p> <pre><code>var image = Image.FromStream(fileStream); foreach (var prop in image.PropertyItems) { if (prop.Id == 112 || prop.Id == 5029) { // do my rotate code - e.g "RotateFlip" // Never get's in here - can't find these properties. } } </code></pre> <p>Any ideas?</p>
6,222,199
5
0
null
2011-06-03 01:15:56.673 UTC
23
2018-11-30 21:16:58.273 UTC
null
null
null
null
321,946
null
1
64
c#|image-processing|metadata|jpeg|gdi
38,484
<p>It appears that you forgotten that the orientation id values you looked up are in hex. Where you use 112, you should have used 0x112. </p> <p><a href="http://www.impulseadventure.com/photo/exif-orientation.html" rel="noreferrer">This article</a> explains how Windows ballsed-up orientation handing, and <a href="http://www.codeproject.com/tips/64116/Using-GDIplus-code-in-a-WPF-application-for-lossle.aspx" rel="noreferrer">this one</a> seems pretty relevant to what you are doing.</p>
5,998,764
Xcode Objective-C | iOS: delay function / NSTimer help?
<p>So I'm developing my first iOS application and I need help..</p> <p>Simple program for now, I have about 9 buttons and when I press the first button, or any button, I just want the first button to highlight for 60 milliseconds, unhighlight, second button highlights, wait 60 milliseconds, unhighlight and so on for the rest of the buttons so it looks like a moving LED.</p> <p>I've looked tried sleep/usleep but once that sleep duration is done it seems like it skips the highlight/unhighlight all together.</p> <p>For example:</p> <pre><code>- (void) button_circleBusy:(id)sender{ firstButton.enabled = NO; sleep(1); firstButton.enabled = YES; </code></pre> <p>and so on for the rest of the buttons. It DOES delay, but it doesn't delay the "firstButton.enabled = NO;". I have a picture for each button's "disabled state" and I never see it.</p> <p>Any help's appreciated! I've looked into NSTimer but I was unsure on how to implement it.</p> <p>Thanks.</p> <p>-Paul</p>
5,998,904
7
0
null
2011-05-13 23:31:29.337 UTC
8
2017-05-05 18:32:25.83 UTC
2011-09-05 01:29:21.827 UTC
null
111,783
null
753,156
null
1
33
objective-c|xcode|ios4|timer|delay
118,271
<p><code>sleep</code> doesn't work because the display can only be updated after your main thread returns to the system. NSTimer is the way to go. To do this, you need to implement methods which will be called by the timer to change the buttons. An example:</p> <pre><code>- (void)button_circleBusy:(id)sender { firstButton.enabled = NO; // 60 milliseconds is .06 seconds [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO]; } - (void)goToSecondButton:(id)sender { firstButton.enabled = YES; secondButton.enabled = NO; [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToThirdButton:) userInfo:nil repeats:NO]; } ... </code></pre>
6,220,836
How to jump down X amount of lines, over and over
<p>I'm using <code>10j</code> to jump down 10 lines, but I want to easily jump 10 lines over and over. I don't want to have to perform the jump with a macro <code>qv10jq@v@@</code>..</p> <p>I wish there was a method for repeating down keys like motion has f then ; to continually jump (, to go back) to the next character(s).</p> <p>is there anything shorter than my macro?</p>
6,220,931
7
2
null
2011-06-02 21:54:59.88 UTC
14
2021-06-10 10:30:37.687 UTC
null
null
null
null
61,410
null
1
48
vim
37,906
<p><a href="http://vim.sourceforge.net/scripts/script.php?script_id=2174" rel="noreferrer">Here's</a> a plugin to do what you want. It maps <kbd>;</kbd> to repeat the last motion command given with a count.</p>
5,864,076
Mocking Static Methods
<p>Recently, I've begun to use <a href="https://github.com/moq/moq4" rel="noreferrer">Moq</a> to unit test. I use Moq to mock out classes that I don't need to test.</p> <p>How do you typically deal with static methods?</p> <pre><code>public void foo(string filePath) { File f = StaticClass.GetFile(filePath); } </code></pre> <p>How could this static method, <code>StaticClass.GetFile()</code> get mocked?</p> <p>P.S. I'd appreciate any reading materials you recommend on Moq and Unit Testing.</p>
5,864,211
7
0
null
2011-05-03 01:12:19.177 UTC
16
2021-06-14 14:00:12.997 UTC
2016-12-28 18:31:26.67 UTC
null
52,920
null
409,976
null
1
83
c#|unit-testing|mocking|moq
103,475
<blockquote> <p>Mocking frameworks like Moq or Rhinomocks can only create mock instances of objects, this means mocking static methods is not possible.</p> </blockquote> <p>You can also <a href="http://www.google.com.au/search?sourceid=chrome&amp;ie=UTF-8&amp;q=moq%20static%20methods" rel="noreferrer">search Google</a> for more info.</p> <p>Also, there's a few questions previously asked on StackOverflow <a href="https://stackoverflow.com/questions/562129/how-do-i-use-moq-to-mock-an-extension-method">here</a>, <a href="https://stackoverflow.com/questions/2416362/mock-static-property-with-moq">here</a> and <a href="https://stackoverflow.com/questions/4282415/how-to-moq-a-static-class-with-a-static-method-unitofwork-case">here</a>.</p>
6,117,814
Get week of year in JavaScript like in PHP
<p>How do I get the current weeknumber of the year, like PHP's <code>date('W')</code>?</p> <p>It should be the <strong><a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO-8601</a></strong> week number of year, weeks starting on Monday.</p>
6,117,889
23
4
null
2011-05-24 22:51:58.763 UTC
75
2022-08-18 11:29:05.21 UTC
2011-06-04 07:08:37.56 UTC
null
63,550
null
508,666
null
1
188
javascript|date
278,344
<p>You should be able to get what you want here: <em><strike>http://www.merlyn.demon.co.uk/js-date6.htm#YWD</strike></em>.</p> <p>A better link on the same site is: <em><strike>Working with weeks</strike></em>.</p> <h3>Edit</h3> <p>Here is some code based on the links provided and that posted eariler by Dommer. It has been lightly tested against results at <em><strike>http://www.merlyn.demon.co.uk/js-date6.htm#YWD</strike></em>. Please test thoroughly, no guarantee provided.</p> <h3>Edit 2017</h3> <p>There was an issue with dates during the period that daylight saving was observed and years where 1 Jan was Friday. Fixed by using all UTC methods. The following returns identical results to Moment.js.</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>/* For a given date, get the ISO week number * * Based on information at: * * THIS PAGE (DOMAIN EVEN) DOESN'T EXIST ANYMORE UNFORTUNATELY * http://www.merlyn.demon.co.uk/weekcalc.htm#WNR * * Algorithm is to find nearest thursday, it's year * is the year of the week number. Then get weeks * between that date and the first day of that year. * * Note that dates in one year can be weeks of previous * or next year, overlap is up to 3 days. * * e.g. 2014/12/29 is Monday in week 1 of 2015 * 2012/1/1 is Sunday in week 52 of 2011 */ function getWeekNumber(d) { // Copy date so don't modify original d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())); // Set to nearest Thursday: current date + 4 - current day number // Make Sunday's day number 7 d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7)); // Get first day of year var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1)); // Calculate full weeks to nearest Thursday var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7); // Return array of year and week number return [d.getUTCFullYear(), weekNo]; } var result = getWeekNumber(new Date()); document.write('It\'s currently week ' + result[1] + ' of ' + result[0]);</code></pre> </div> </div> </p> <p>Hours are zeroed when creating the &quot;UTC&quot; date.</p> <p>Minimized, prototype version (returns only week-number):</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>Date.prototype.getWeekNumber = function(){ var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate())); var dayNum = d.getUTCDay() || 7; d.setUTCDate(d.getUTCDate() + 4 - dayNum); var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1)); return Math.ceil((((d - yearStart) / 86400000) + 1)/7) }; document.write('The current ISO week number is ' + new Date().getWeekNumber());</code></pre> </div> </div> </p> <h3>Test section</h3> <p>In this section, you can enter any date in YYYY-MM-DD format and check that this code gives the same week number as Moment.js ISO week number (tested over 50 years from 2000 to 2050).</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>Date.prototype.getWeekNumber = function(){ var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate())); var dayNum = d.getUTCDay() || 7; d.setUTCDate(d.getUTCDate() + 4 - dayNum); var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1)); return Math.ceil((((d - yearStart) / 86400000) + 1)/7) }; function checkWeek() { var s = document.getElementById('dString').value; var m = moment(s, 'YYYY-MM-DD'); document.getElementById('momentWeek').value = m.format('W'); document.getElementById('answerWeek').value = m.toDate().getWeekNumber(); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"&gt;&lt;/script&gt; Enter date YYYY-MM-DD: &lt;input id="dString" value="2021-02-22"&gt; &lt;button onclick="checkWeek(this)"&gt;Check week number&lt;/button&gt;&lt;br&gt; Moment: &lt;input id="momentWeek" readonly&gt;&lt;br&gt; Answer: &lt;input id="answerWeek" readonly&gt;</code></pre> </div> </div> </p>
55,939,860
How to fix error "ANCM In-Process Handler Load Failure"?
<p>I'm setting up the first site in IIS on Windows Server 2016 Standard. This is a <code>NET Core 2.2</code> application. I cannot get the site to show.</p> <p>I am getting this error:</p> <blockquote> <p>HTTP Error 500.0 - ANCM In-Process Handler Load Failure</p> </blockquote> <p>What can I change to clear this error and get my site to display?</p> <p>My application is a <code>dll</code>.</p> <p>I tested my application on the server through the Command Prompt with</p> <pre><code>dotnet ./MyApp.dll </code></pre> <p>it displays in the browser but only on the server itself with (<code>localhost:5001/</code>).</p> <p>Using this method the site cannot be accessed from any other server. When I set up the site through IIS, I get the In-Process error both on the server and from servers attempting to access the site.</p> <p>At first I was receiving the Out-Process error. Something I read said to add this (hostingModel=&quot;inprocess&quot;) to my <code>web.config</code> so I did but now I receive the In-Process error.</p> <p>The site works fine when installed on my development server.</p> <p>The Event Viewer shows this error for &quot;IIS AspNetCore Module V2&quot;:</p> <blockquote> <p>Failed to start application '/LM/W3SVC/2/ROOT', ErrorCode '0x8000ffff'.</p> </blockquote> <p>This is my <code>web.config</code>:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;customErrors mode=&quot;RemoteOnly&quot;&gt;&lt;/customErrors&gt; &lt;identity impersonate=&quot;false&quot; password=&quot;****&quot; userName=&quot;****&quot; /&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;handlers&gt; &lt;add name=&quot;aspNetCore&quot; path=&quot;*&quot; verb=&quot;*&quot; modules=&quot;AspNetCoreModuleV2&quot; resourceType=&quot;Unspecified&quot; /&gt; &lt;/handlers&gt; &lt;aspNetCore processPath=&quot;dotnet&quot; arguments=&quot;.\MyApp.dll&quot; stdoutLogEnabled=&quot;false&quot; hostingModel=&quot;inprocess&quot; stdoutLogFile=&quot;.\logs\stdout&quot; forwardWindowsAuthToken=&quot;false&quot;&gt; &lt;environmentVariables /&gt; &lt;/aspNetCore&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre>
58,127,980
25
5
null
2019-05-01 17:05:42.243 UTC
13
2022-01-27 19:05:56.177 UTC
2020-07-25 01:15:59.923 UTC
null
1,127,428
null
3,068,106
null
1
73
iis|asp.net-core|asp.net-core-2.2
115,286
<p>I had the same issue in .Net core 2.2. When I replace</p> <p><strong>web.config:</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;handlers&gt; &lt;add name=&quot;aspNetCore&quot; path=&quot;*&quot; verb=&quot;*&quot; modules=&quot;AspNetCoreModuleV2&quot; resourceType=&quot;Unspecified&quot; /&gt; &lt;/handlers&gt; </code></pre> <p>to</p> <pre class="lang-xml prettyprint-override"><code>&lt;handlers&gt; &lt;add name=&quot;aspNetCore&quot; path=&quot;*&quot; verb=&quot;*&quot; modules=&quot;AspNetCoreModule&quot; resourceType=&quot;Unspecified&quot; /&gt; &lt;/handlers&gt; </code></pre> <p>then it works fine.</p> <p><strong>Note:</strong> The same solution also works for .Net core 2.2 and other upper versions as well.</p>
44,347,397
What is Docker attach?
<p>I am very new to Docker and I have been able to understand 4 things</p> <ul> <li>Dockerfile</li> <li>Docker image</li> <li>Docker container</li> <li>docker-compose</li> </ul> <p>along with some basic commands like docker run, docker log etc.</p> <p>Now, I came across this command <code>docker attach</code> with a description here</p> <blockquote> <p>Use docker attach to attach to a running container using the container’s ID or name, either to view its ongoing output or to control it interactively. You can attach to the same contained process multiple times simultaneously, screen sharing style, or quickly view the progress of your detached process.`</p> </blockquote> <p>I have no idea what do they mean when they say we can attach if we want to view a container's <code>ongoing activity or output?</code> If I have a Container for a console application and I simply do <code>docker run</code> on it then I can see the output right there in the console window.</p> <p>What could be a few benefits of docker attach?</p>
44,347,530
3
0
null
2017-06-03 18:44:17.943 UTC
1
2020-01-22 18:54:24.707 UTC
2017-06-03 21:13:42.22 UTC
null
2,449,905
null
280,772
null
1
30
docker
37,268
<p>When containers are run with the interactive option, you can connect to the container and enter commands as if you are on the terminal:</p> <pre><code>$ docker run -itd --name busybox busybox dcaecf3335f9142e8c70a2ae05a386395b49d610be345b3a12d2961fccab1478 $ docker attach busybox / # echo hello world hello world </code></pre> <p>The <code>attach</code> option also allows multiple connections to view the same container and see what each is typing.</p> <p>Lastly, while connected to a container with the tty option (<code>-t</code>), you can type <kbd>Control</kbd>-<kbd>P</kbd> <kbd>Control</kbd>-<kbd>Q</kbd> to detach from that container and leave it running in the background. You can then attach to that container again in the future.</p>
27,551,032
Debugger stepping into if() block where condition is false
<p>Given this gem of code:</p> <pre><code>class Program { private static bool IsAdmin = true; static void Main(string[] args) { if (!IsAdmin) { throw new Exception(); } try { var x = 2342342; var y = 123132; } catch (Exception) { throw; } } } </code></pre> <p>Given the <code>this.IsAdmin</code> yields true - I would expect the debugger to not enter that if statement. In reality it does - and it steps over the throw but does not actually throw!</p> <p>Now this only happens when you have an exception inside an if statement followed by a try/catch block, on Visual Studio 2013, targeting .NET Framework 4, 64 bit, "Prefer 32 bit" unchecked. </p> <p>I have confirmed this oddity with colleagues on different machines. Step though the following code and the debugger will seem to step into the if branch, but no exception is thrown:</p> <p><img src="https://i.stack.imgur.com/mJoPP.png" alt="enter image description here"></p> <p>I am in debug mode, I have tried compiling and cleaning the project multiple times.</p> <p>Can anyone explain why this is happening?</p>
27,552,124
2
1
null
2014-12-18 16:15:01.057 UTC
5
2019-04-12 23:05:16.473 UTC
2014-12-18 17:07:55.65 UTC
null
1,139,830
user156888
null
null
1
34
c#
4,991
<p>Check out <a href="http://whileicompile.wordpress.com/2010/07/02/visual-studio-bug-if-followed-by-a-try-catch-causes-debugger-stepping-error/" rel="nofollow noreferrer">this</a> link. It's a known bug in some versions of visual studio and the .NET framework version. It's completely harmless and something you will just have to live with.</p>
27,656,389
JSON Parse error: Unterminated string
<p>I've met an usual problem when escaping a quote within the JSON parse function. If the escaped quote is present, in this case 'test"', it causes the following error 'SyntaxError: JSON Parse error: Unterminated string'.</p> <p><code>var information = JSON.parse('[{"-1":"24","0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[""],"12":"","13":"","14":"test\""}]');</code></p> <p>JSON Lint validates the JSON as valid.</p>
27,656,452
4
1
null
2014-12-26 11:17:34.063 UTC
1
2018-12-17 22:29:36.557 UTC
2017-04-24 03:58:26.71 UTC
null
2,308,683
null
2,948,168
null
1
7
javascript|json|syntax-error
42,935
<p>You'll have to double escape it, as in <code>"test\\""</code></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var information = JSON.parse('[{"-1":"24","0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[""],"12":"","13":"","14":"test\\""}]'); document.body.innerHTML = '&lt;pre&gt;' + JSON.stringify(information, null, 4) + '&lt;/pre&gt;';</code></pre> </div> </div> </p> <p>The first backslash escapes the second backslash in the javascript string literal. The second backslash escapes the quote in the JSON string literal.</p> <p>So it's parsed twice, and needs escaping twice.</p> <p>So even if it's valid JSON, you'll need one escape for javascript string literals that escapes the escape used in JSON.</p>
44,773,296
libstdc++.so.6: version `GLIBCXX_3.4.20' not found
<p>To upload the raw-reads > 2GB to SRA on Genebank, I installed aspera connect plug-in on ubuntu 16.04. But the plug-in did not pop up as indicated by the instruction on the genebank SRA portal. </p> <p>I got this error on the terminal as I initializing the plug-in locally (<code>~/.aspera/connect/bin/asperaconnect</code>):</p> <pre><code>lib/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by /usr/lib/x86_64-linux-gnu/libproxy.so.1) Failed to load module: /usr/lib/x86_64-linux-gnu/gio/modules/libgiolibproxy.so </code></pre> <p>I followed some of the threads, created a link to <code>/usr/lib/libstdc++.so.6</code> <strong>But it did not address the problem, still showing the error message above.</strong> running <code>strings /usr/lib/libstdc++.so.6 | grep GLIBCXX</code> got this:</p> <pre><code>strings /usr/lib/x86_64-linux-gnu/libstdc++.so.6 | grep GLIBCXX GLIBCXX_3.4 GLIBCXX_3.4.1 GLIBCXX_3.4.2 GLIBCXX_3.4.3 GLIBCXX_3.4.4 GLIBCXX_3.4.5 GLIBCXX_3.4.6 GLIBCXX_3.4.7 GLIBCXX_3.4.8 GLIBCXX_3.4.9 GLIBCXX_3.4.10 GLIBCXX_3.4.11 GLIBCXX_3.4.12 GLIBCXX_3.4.13 GLIBCXX_3.4.14 GLIBCXX_3.4.15 GLIBCXX_3.4.16 GLIBCXX_3.4.17 GLIBCXX_3.4.18 GLIBCXX_3.4.19 GLIBCXX_3.4.20 GLIBCXX_3.4.21 GLIBCXX_3.4.22 GLIBCXX_3.4.23 GLIBCXX_DEBUG_MESSAGE_LENGTH </code></pre> <p><strong>GLIBCXX_3.4.20 is in the list</strong>. I don't know how to make the plug-in recognize that.</p> <p>Thank you, Xp</p>
45,161,307
5
2
null
2017-06-27 06:09:12.477 UTC
11
2022-09-23 01:28:37.47 UTC
null
null
null
null
7,392,741
null
1
43
ubuntu-16.04|libstdc++
148,906
<p>Considering that <code>/usr/lib/x86_64-linux-gnu/libproxy.so.1</code> is supplied by Ubuntu, let's assume that it is compatible with the system libstdc++ library. This means that the application is not actually using that system library, but some other version. I'd suggest to check if the application sets <code>LD_LIBRARY_PATH</code> and if there is another copy of <code>libstdc++.so.6</code> on that path. In this case, try moving it away or deleting it—the application should then switch to the system library, which is newer and should be backwards-compatible.</p>
21,563,672
Google Chrome vertical scroll bars mysteriously appear and disappear?
<p>The website I've been working on has this odd, and seemingly non-consistent issue, and it only appears to happen on Google Chrome.</p> <p>My main content section will, occasionally, product vertical and horizontal scroll bars.</p> <p>When I open the page as a file, the scroll bars pop up intermittently upon opening the page, and refreshing the page. They usually do not show up, but every couple of refreshes or so, they will pop up.</p> <p>When I run the page locally using NGiNX, the scroll bars will pop up upon opening the page, but disappear when I refresh and no amount of refreshing will bring them back. If I click back and forth between two different test pages I have set up, the scroll bars stick around. Only upon hitting reload, do they disappear.</p> <p>I have not seen the issue when I run it from my temp free webhosting site, Zymic. I was actually not even going to worry about it because it didn't show up when it was live, but when I noticed the issue popping up from my locally ran web server, I figured I should look into this.</p> <p>I have no idea where to start looking for what may be causing the problem, but I'm providing a video that will clearly show the issue, and a link to my current live site. Based on reports of others and my own experiences, the issue will not show up from the live site, but it will give access to all of my current code (current-ish, I'm in the midst of trying some things out) and I will happily provide any specifically requested pieces of code. I would try and supply the bits right away that might be causing the problem, except that I have no idea :\ But if I narrow anything down, I will include that bit of the code along with what I've discovered.</p> <p>Short 58 second video of the problem: <a href="http://youtu.be/K7tjGJ8hIV0">http://youtu.be/K7tjGJ8hIV0</a></p> <p>Live site (issue should not occur from this link): <a href="http://jrltest.zxq.net/">http://jrltest.zxq.net/</a></p> <p>Thank you all very much!</p>
21,563,741
3
1
null
2014-02-04 21:19:19.957 UTC
2
2022-04-07 17:37:03.76 UTC
null
null
null
null
2,953,692
null
1
13
html|css|google-chrome
42,564
<p>This is caused by your <code>overflow:auto;</code> style on your <code>#maincontent</code> div. Just change the style to <code>overflow:hidden;</code> to make the scrollbars disappear permanently.</p> <p>Automatic overflow will work by doing nothing with the overflowing content if it fits in the container, but if it overflows by even a bit, it inserts scrollbars to allow the user to scroll. In your case, Chrome will probably recognise a single pixel of overflow, so insert scrollbars. This probably has to do with caching and image-loading. What I think is that if the image is already in the cache, Chrome knows exactly how big it is, and it knows the image will fit in the container, but when it's not cached yet, it reserves some space for the image to load in, and since that space is apparently slightly larger than the actual image, it will take up some extra space.</p>
21,499,467
How to access the subdomain of an IP address in the browser?
<p>To get to the IP address of an example website, you just visit</p> <pre><code>subdomain.example.com </code></pre> <p>However, if I try to visit</p> <pre><code>subdomain.2.1.33.111 (example ip) </code></pre> <p>Firefox returns an error.<br> Why?</p>
21,499,542
5
1
null
2014-02-01 14:47:27.967 UTC
5
2022-09-18 14:36:26.903 UTC
null
null
null
null
3,236,661
null
1
55
firefox|browser|web|ip|ip-address
61,624
<p>All browsers will return an error for this. The reason is that subdomains are part of the DNS (Domain Name Service) system, where IP addresses are related to the underlying IP protocol.</p> <p>The best way to think of this relationship is that domains (including subdomains) are human-readable labels which DNS then allows you to point to IP addresses. It would not be very catchy to have an IP address as your website on a TV ad, for example.</p> <p>There is much more detail on <a href="https://en.wikipedia.org/wiki/Domain_Name_System" rel="noreferrer">DNS</a> and <a href="https://en.wikipedia.org/wiki/IP_address" rel="noreferrer">IP addresses</a> if you want to delve into more detail than this.</p>
42,231,764
How can I rename a conda environment?
<p>I have a conda environment named <code>old_name</code>, how can I change its name to <code>new_name</code> without breaking references?</p>
42,231,765
8
2
null
2017-02-14 16:51:16.223 UTC
97
2022-07-23 00:47:46.093 UTC
2017-03-29 07:21:21.467 UTC
null
2,781,698
null
2,351,523
null
1
499
python|anaconda|conda
267,978
<h2>New answer:</h2> <p>From <a href="https://github.com/conda/conda/milestone/55" rel="noreferrer">Conda 4.14</a> you will be able to use just:</p> <pre><code>conda rename -n old_name -d new_name </code></pre> <p>Although, under the hood, <code>conda rename</code> still uses <a href="https://github.com/conda/conda/pull/11496/files#diff-2cf7ba1d1799c57376f2066177b166979c8f6854a2540c4dd5077f0b95031b93R241" rel="noreferrer">[1]</a><a href="https://github.com/conda/conda/pull/11496/files#diff-66bae0eac87592b832fa7e85ad41263739a925b211d4b2f386385092e7df3ca4" rel="noreferrer">[2]</a> undermentioned combination of <code>conda create</code> and <code>conda remove</code>.</p> <hr /> <h2>Old answer:</h2> <p>You can't.</p> <p>One workaround is to <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#creating-an-environment-with-commands" rel="noreferrer">create</a> clone a new environment and then <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#removing-an-environment" rel="noreferrer">remove</a> the original one.</p> <p>First, remember to deactivate your current environment. You can do this with the commands:</p> <ul> <li><code>deactivate</code> on Windows or</li> <li><code>source deactivate</code> on macOS/Linux.</li> </ul> <p>Then:</p> <pre><code>conda create --name new_name --clone old_name conda remove --name old_name --all # or its alias: `conda env remove --name old_name` </code></pre> <p>Notice there are several drawbacks of this method:</p> <ol> <li>It redownloads packages (you can use <code>--offline</code> flag to disable it)</li> <li>Time consumed on copying environment's files</li> <li>Temporary double disk usage</li> </ol> <p>There is an open <a href="https://github.com/conda/conda/issues/3097" rel="noreferrer">issue</a> requesting this feature.</p>
32,828,606
Intervention Image: Save image directly from an url with original file name and ext?
<p>How to get the filename, when taking image from a remote server? And how to save with original size and filename?</p> <pre><code>// Take remote image $img = Image::make('http://image.info/demo.jpg'); // how to save in the img/original/demo.jpg $img-&gt;save(????); </code></pre> <p><strong>I use Intervention,</strong> (<a href="http://image.intervention.io/api/make" rel="nofollow noreferrer">http://image.intervention.io/api/make</a>) to build CakePHP 3 image Behavior, I want to provide an easy uploading from remote servers, and keep the original image as a source for future manipulation.</p> <p><strong>EDIT</strong></p> <p><strong>I ask,</strong> is there the <strong>Intervention Image</strong> method that returns the name of the file, when taken from the remote server. I know php copy(), basename(), I can also use the CakePHP File utilities, but it gives me the duplicate request on remote file.</p>
32,834,576
3
2
null
2015-09-28 17:26:53.137 UTC
8
2020-12-06 11:19:08.513 UTC
2020-10-15 07:56:13.977 UTC
null
1,127,933
null
1,127,933
null
1
19
php|laravel|intervention|cakephp-3.1
38,537
<p>response() does not return the original filename like Salines was requesting. This should work </p> <pre><code>$path = 'https://i.stack.imgur.com/koFpQ.png'; $filename = basename($path); Image::make($path)-&gt;save(public_path('images/' . $filename)); </code></pre>
33,409,888
How can I await inside future-like object's __await__?
<p><a href="https://www.python.org/dev/peps/pep-0492/#await-expression" rel="noreferrer">PEP 0492</a> adds new <code>__await__</code> magic method. Object that implements this method becomes <em>future-like object</em> and can be awaited using <code>await</code>. It's clear:</p> <pre><code>import asyncio class Waiting: def __await__(self): yield from asyncio.sleep(2) print('ok') async def main(): await Waiting() if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) </code></pre> <p>Ok, but what if I want to call some <code>async def</code> defined function instead of <code>asyncio.sleep</code>? I can't use <code>await</code> because <code>__await__</code> is not <code>async</code> function, I can't use <code>yield from</code> because native coroutines requires <code>await</code> expression:</p> <pre><code>async def new_sleep(): await asyncio.sleep(2) class Waiting: def __await__(self): yield from new_sleep() # this is TypeError await new_sleep() # this is SyntaxError print('ok') </code></pre> <p>How can I solve it?</p>
33,420,721
6
2
null
2015-10-29 09:06:06.5 UTC
16
2019-07-19 21:33:49.073 UTC
2017-03-23 04:41:21.067 UTC
null
167,958
null
1,113,207
null
1
44
python|python-3.x|async-await|python-asyncio
16,046
<p>Use direct <code>__await__()</code> call:</p> <pre><code>async def new_sleep(): await asyncio.sleep(2) class Waiting: def __await__(self): return new_sleep().__await__() </code></pre> <p>The solution was recommended by Yury Selivanov (the author of <a href="https://www.python.org/dev/peps/pep-0492/">PEP 492</a>) for <a href="https://github.com/aio-libs/aioodbc/blob/e56615cd005cb402470bbffe6589b38cb5f7acee/aioodbc/utils.py#L27-L28">aioodbc library</a></p>
9,150,435
How can I recycle UITableViewCell objects created from a XIB?
<p>I'd like to create custom UITableViewCell using an XIB, but I'm not sure how to recycle it using UITableViewController's queueing mechanism. How can I accomplish this?</p> <p><sup>Folks, this question was intended to be self answered as per <a href="https://stackoverflow.com/faq">the FAQ</a>, although I love the awesome responses. Have some upvotes, treat yourself to a beer. I asked this because a friend asked me and I wanted to put it up on StackOverflow. If you have anything to contribute, by all means!</sup></p>
9,150,943
4
0
null
2012-02-05 15:28:53.82 UTC
13
2012-02-05 16:38:50.313 UTC
2017-05-23 10:30:16.07 UTC
null
-1
null
224,988
null
1
18
ios|uitableview|uikit|xib
13,259
<p>If you're using iOS 5 you can use</p> <pre><code>[self.tableView registerNib:[UINib nibWithNibName:@"nibname" bundle:nil] forCellReuseIdentifier:@"cellIdentifier"]; </code></pre> <p>Then whenever you call:</p> <pre><code>cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"]; </code></pre> <p>the tableview will either load the nib and give you a cell, or dequeue a cell for you!</p> <p>The nib need only be a nib with a single tableviewcell defined inside of it!</p>
9,253,512
Directory Listing in S3 Static Website
<p>I have set up an S3 bucket to host static files.</p> <p><strong>When using the website endpoint (http://.s3-website-us-east-1.amazonaws.com/):</strong> it forces me to set an index file. When the file isn't found, it throws an error instead of listing directory contents. </p> <p><strong>When using the s3 endpoint (.s3.amazonaws.com):</strong> I get an XML listing of the files, but I need an HTML listing that users can click the link to the file.</p> <p>I have tried setting the permissions of all files and the bucket itself to "List" for "Everyone" in the AWS Console, but still no luck.</p> <p>I have also tried some of the javascript alternatives, but they either don't work under the website url (that redirects to the index file) or just don't work at all. As a last resort, a collapsible javascript listing would be better than nothing, but I haven't found a good one.</p> <p>Is this possible? If so, do I need to change permissions, ACL or something else?</p>
11,613,880
7
0
null
2012-02-12 22:58:55.343 UTC
12
2021-05-08 20:00:06.11 UTC
null
null
null
null
1,073,837
null
1
56
amazon-s3|amazon-web-services
91,390
<p>I found <a href="https://github.com/powdahound/s3browser/" rel="nofollow noreferrer">s3browser</a>, which allowed me to set up a directory on the main web site that allowed browsing of the s3 bucket. It worked very well and was very easy to set up.</p>
9,602,901
What is the purpose of passing-in undefined?
<p>I have noticed <code>jQuery</code> and related keynote plugins like <code>jQuery.UI</code> pass <code>undefined</code> as a parameter into anonymous functions used in their module definitions, like so:</p> <pre><code>(function($, undefined) { ... })(jQuery); </code></pre> <p>Alternatively, I have noticed other plugins recommended by jQuery and/or others do NOT pass undefined in as a parameter.</p> <p>This is probably a silly question, but...</p> <p>Shouldn't it always be available anyway? Why pass it in? Is there some sort of other purpose or trick going on here?</p>
9,602,975
3
0
null
2012-03-07 14:03:12.237 UTC
21
2017-05-23 08:48:50.567 UTC
2012-03-07 14:42:01.813 UTC
null
312,317
null
312,317
null
1
60
javascript|jquery|plugins
8,199
<p>There are two reasons for that:</p> <p>1) If <code>undefined</code> is a variable in the function scope rather than a global object property, minifiers can reduce it to a single letter thus achieving a better compression rate.</p> <p>2) Before ES5*, <code>undefined</code> was a property of the global object without write-protection. So it could be overwritten, resulting in strange and unexpected behavior. You could do something like this: </p> <pre><code>var test = 123; undefined = 123; if (test === undefined){ // this will actually be true, since undefined now equals 123 } </code></pre> <p>By having an function argument <code>undefined</code> (the name actually does not matter) which you don't pass a parameter to, you could make sure you have a variable which really is <code>undefined</code> so you can test "undefinedness" against this variable.</p> <p>Btw. the safest method to test for undefined is: <code>typeof ( var ) === 'undefined'</code></p> <p>(*) With EcmaScript 5, the global properties <code>undefined</code>, <code>NaN</code> and <code>Infinity</code> became readonly. So with its general adoption in all modern browsers - of course with the exception of IE 9 - overwriting those values was not possible anymore.</p>
9,419,606
Unit testing a method dependent to the request context
<p>I'm writing a unit test for a method that contains the following line:</p> <pre><code>String sessionId = RequestContextHolder.currentRequestAttributes().getSessionId(); </code></pre> <p>I get the following error:</p> <blockquote> <p>java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.</p> </blockquote> <p>The reason is quite obvious — I'm not running the test in a request context.</p> <p>The question is, how can I test a method that contains a call to a method dependent to the request context in a test environnment?</p> <p>Thank you very much.</p>
9,430,545
5
0
null
2012-02-23 19:12:14.457 UTC
12
2019-04-16 02:54:24.91 UTC
null
null
null
null
1,031,658
null
1
80
spring|spring-mvc
49,252
<p>Spring-test has a flexible request mock called MockHttpServletRequest.</p> <pre><code>MockHttpServletRequest request = new MockHttpServletRequest(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); </code></pre>
47,429,141
why do I receive multiple FCM notifications on android 7
<p>I am trying to integrate FCM notification in my project. I have Cloud Function backend, and app runs on android. Below is cloud code to send notification:</p> <pre><code>exports.notificationTest = functions.database.ref(`/test/childA/childB/status`).onUpdate(event =&gt; { const status = event.data.val(); console.info("Processing notificationTest cloud function") console.info(`status : ${status}`) const token = "EnterYourNotificationTokenHere" const randomNum = Math.floor(Math.random() * 100) var message = { notification: { title : "My App", body : `Notification Test ${randomNum}`} } console.info(`Sending message on notification token`) return admin.messaging().sendToDevice(token, message) .then((response) =&gt; { console.info("Successfully sent notification") }).catch(function(error) { console.warn("Error sending notification " , error) }) }) </code></pre> <p>On native Android app, I receive notification multiple times with interval of few mins. Here, I have seen notification like this:</p> <pre><code>Notification Test 30 </code></pre> <p>then after 2,4,8,16,32 mins of previous notification time I again get below message</p> <pre><code>Notification Test 30 </code></pre> <p>I don't think I need to paste log here, because code is definitely executed just once (as the random number in notification stays the same).</p> <p>So, why is this happening and how to fix it?</p> <p>Below is my environment:</p> <pre><code>Native Android App Using Android 7 Latest Android Studio Stable Android Gradle Plugin - 3.1.1 Gradle - 4.1 Firebase-Ui - 3.1.0 Play Services - 11.4.2 </code></pre> <p>Please try to reproduce in environment mentioned above.</p>
47,616,279
2
3
null
2017-11-22 07:36:45.447 UTC
8
2018-03-08 16:58:43.147 UTC
2017-11-30 11:22:50.187 UTC
null
1,276,344
null
1,276,344
null
1
9
android|firebase|firebase-cloud-messaging|firebase-notifications
3,095
<p>I have resolved the issue by renaming my application package name eg old name: com.xyz to com.xyz2</p> <p>Using the new name i added this (new) android app to firebase project (it generated new app id). And the notifications started worked as expected (no retry).</p> <p>But its a shame that I have to rename app package to resolve it. If this app was released in google play then I could not have renamed the app, else no one can get further updates on this app, and it becomes a new app!</p> <p>It would still be great if some firebase developers could shed light on what is happening.</p> <p>Recreating firebase project and recreating android project did not help when app name / top level package name were the same. Changing app name and relevant namespaces in existing android project fixed it for now.</p> <p>Ideally I would like to know the proper fix for this and use the existing name rather than suffixing 2 at the end of app name. </p>
35,529,940
How to make gameplay ignore clicks on UI Button in Unity3D?
<p>I have a UI <code>Button</code> (using <code>UnityEngine.UI</code>).</p> <p>However, clicking on the <code>Button</code> seems to be <strong>clicking through</strong> onto the scene (in my case clicking a nav mesh).</p> <p>How to solve this problem?</p> <p>I've been using typical Unity3D code to get user in put in gameplay such as</p> <pre><code>if (Input.GetMouseButtonDown(0)) { </code></pre> <p>same if I try the approach</p> <pre><code>if( Input.touches.Length &gt; 0 ) { if ( Input.touches[0].phase == TouchPhase.Began ) { </code></pre> <p>and it seems to be the case on iOS, Android, and desktop.</p> <p>It seems to be a basic problem that clicks on the UI (<code>UnityEngine.UI.Button</code> etc) seem to fall through to the gameplay.</p>
35,530,316
3
1
null
2016-02-20 22:36:12.53 UTC
8
2021-10-18 08:49:41.6 UTC
2019-03-17 17:53:00.743 UTC
null
294,884
null
1,418,290
null
1
12
c#|unity3d|navmesh
26,830
<p>Here's how you do it in Unity today:</p> <ol> <li><p>Naturally you'll have an <code>EventSystem</code> in the hierarchy - just check that you do. (You get one of those automatically when, for example, you add a Canvas; usually, every scene in an Unity project already has an <code>EventSystem</code>, but just check that you do have one.)</p> </li> <li><p>Add a <strong>physics raycaster</strong> to the camera (that takes one click)</p> </li> <li><p>Do this:</p> </li> </ol> <p>.</p> <pre><code> using UnityEngine.EventSystems; public class Gameplay:MonoBehaviour, IPointerDownHandler { public void OnPointerDown(PointerEventData eventData) { Bingo(); } } </code></pre> <p><em><strong>Basically</strong></em>, again <em><strong>basically</strong></em>, that is all there is to it.</p> <p>Quite simply: that is how you handle touch in Unity. That's all there is to it.</p> <p>Add a raycaster, and have that code.</p> <p>It looks easy and it is easy. However, it can be complicated to do well.</p> <hr /> <p>(Footnote: some horrors of doing drags in Unity: <a href="https://stackoverflow.com/q/36048106/294884">Horrors of OnPointerDown versus OnBeginDrag in Unity3D</a> )</p> <hr /> <p>Unity's journey through touch technology has been fascinating:</p> <ol> <li><p>&quot;Early Unity&quot; ... was extremely easy. Utterly useless. Didn't work at all.</p> </li> <li><p>&quot;Current 'new' Unity&quot; ... Works beautifully. Very easy, but difficult to use in an expert manner.</p> </li> <li><p>&quot;Coming future Unity&quot; ... Around 2025 they will make it BOTH actually work AND be easy to use. Don't hold your breath.</p> </li> </ol> <p>(The situation is not unlike Unity's <strong>UI</strong> system. At first the UI system was laughable. Now, it is great, but somewhat complex to use in an expert manner. As of 2019, they are about to again totally change it.)</p> <p>(The networking is the same. At first it was total trash. The &quot;new&quot; networking is/was pretty good, but has some very bad choices. Just recently 2019 they have changed the networking again.)</p> <hr /> <p>Handy related tip!</p> <p>Remember! When you have a full-screen <em><strong>invisible</strong></em> panel which holds some buttons. On the full-screen invisible panel itself, you must <em><strong>turn off</strong></em> raycasting! It's easy to forget:</p> <p><a href="https://i.stack.imgur.com/iGUtT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iGUtT.png" alt="enter image description here" /></a></p> <hr /> <p>As a historic matter: here is the rough-and-ready quick-fix for &quot;ignoring the UI&quot;, which you <strong>used to be able to use</strong> in Unity years ago...</p> <pre><code>if (Input.GetMouseButtonDown(0)) { // doesn't really work... if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) return; Bingo(); } </code></pre> <p>You cannot do this any more, for some years now.</p>
8,829,490
Get Value from ASP.NET GridView cell
<p>How would I get the value from a GrivView cell when the edit button is clicked? I have tried other answer but none seem to work. I would like to be able to get the value of Questionnaire ID for the row when the edit button is pressed.</p> <p>Here is the gridview im working with.</p> <pre><code>&lt;asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="False" DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="edit" ShowFooter="true" FooterStyle-CssClass="view_table_footer"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"&gt;&lt;/asp:BoundField&gt; &lt;asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" /&gt; &lt;asp:TemplateField HeaderText="Results" HeaderStyle-Width="150px"&gt;&lt;/asp:TemplateField&gt; &lt;asp:CommandField HeaderText="Options" ShowDeleteButton="True" ShowEditButton="true" ItemStyle-CssClass="cart_delete"&gt; &lt;/asp:CommandField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;asp:label ID="ab" runat="server"&gt;&lt;/asp:label&gt; </code></pre> <p>The backend</p> <pre><code>protected void edit(object sender, GridViewEditEventArgs e) { string c = gvShowQuestionnaires.Rows[index].Cells[0].Text; ab.Text = c; } </code></pre>
8,829,601
2
1
null
2012-01-12 02:45:41.627 UTC
1
2015-10-30 14:43:00.167 UTC
null
null
null
null
1,000,231
null
1
3
c#|asp.net|gridview
59,248
<p>The <code>GridViewEventArgs</code> has the index of the row being edited. It doesn't look like you are using the index from the event args. Try this:</p> <pre><code>protected void edit(object sender, GridViewEditEventArgs e) { string c = gvShowQuestionnaires.Rows[e.NewEditIndex].Cells[0].Text; ... } </code></pre>
8,663,454
MySQL: Why does basic MySQLdump on db table fail with "Permission denied"
<p>This should be quick and simple, but after researching on Google quite a bit I am still stumped. I am mostly newbie with: server admin, CLI, MySQL.</p> <p>I am developing my PHP site locally, and now need to move some new MySQL tables from my local dev setup to the remote testing site. First step for me is just to dump the tables, one at a time. </p> <p>I successfully login to my local MySQL like so: </p> <pre><code>Govind% /usr/local/mysql/bin/mysql -uroot </code></pre> <p>but while in this dir (and NOT logged into MySQL): </p> <pre><code>/usr/local/mysql/bin </code></pre> <p>...when I try this </p> <pre><code>mysqldump -uroot -p myDBname myTableName &gt; myTestDumpedTable.sql </code></pre> <p>..then I keep getting this: </p> <pre><code>"myTestDumpedTable.sql: Permission denied." </code></pre> <p>Same result if I do any variation on that (try to dump the whole db, drop the '-p', etc.)</p> <p>I am embarrassed as I am sure this is going to be incredibly simple, or just reveal a gaping (basic) hole in my knowledge. .. but please help ;-)</p>
8,671,878
8
1
null
2011-12-29 02:39:30.96 UTC
2
2021-01-25 18:33:58.407 UTC
2021-01-25 18:33:58.407 UTC
null
10,907,864
null
530,006
null
1
16
mysql
44,649
<p>The answer came from a helpful person on the MySQL list:<br> As you guys (Anson and krazybean) were thinking - I did not have permission to be writing to the <code>/usr/local/mysql/bin/</code> dir. But starting from any other directory, calls to <code>mysqldump</code> were failing because my shell PATH var (if I said that right) is not yet set up to handle <code>mysqldump</code> from another dir. Also, for some reason I do not really understand yet, I also needed to use a full path on the <strong>output</strong>, even if I was calling mysqldump effectively, and even if I had permission to write to the output dir (e.g. <code>~/myTestDumpedTable.sql</code>. So here was my ticket, for now (quick answer):</p> <pre><code>Govind% /usr/local/mysql/bin/mysqldump -uroot -p myDBname myTableName &gt; /Users/Govind/myTestDumpedTable.sql </code></pre> <p>You can write to wherever your shell user has permission to do so. I just chose my user's home dir.</p> <p>Hope this helps someone someday.<br> Cheers.</p>
27,269,574
How to run Debug server for Django project in PyCharm Community Edition?
<p>Has anyone had issues setting up a debug configuration for Django project in PyCharm Community Edition? Community Edition of the IDE is lacking the project type option on project setup and then when I am setting up Debug or Run config it asks me for a script it should run. What script would it be for Django, manage.py? Thanks in advance</p>
28,256,637
2
2
null
2014-12-03 10:42:14.567 UTC
16
2022-09-06 03:16:13.08 UTC
2016-03-08 10:53:18.213 UTC
null
3,274,259
null
3,556,286
null
1
46
python|django|configuration|ide|pycharm
29,323
<p>Yes you can.</p> <ol> <li>In Run -> Edit Configurations create new configuration</li> <li>[+] / Python</li> <li>Name: runserver</li> <li>Scrip Path: path_to/manage.py</li> <li>Parameters: runserver</li> </ol>
27,188,593
Getting PdfStamper to work with MemoryStreams (c#, itextsharp)
<p>It came to me to rework old code which signs PDF files into new one, which signs MemoryStreams (byte arrays) that come and are sent by web services. Simple, right? Well, that was yesterday. Today I just can't get it to work.</p> <p>This is the old code, which uses FileStreams and it works:</p> <pre><code> public static string OldPdfSigner(PdfReader pdfReader, string destination, string password, string reason, string location, string pathToPfx) { using (FileStream pfxFile = new FileStream(pathToPfx, FileMode.Open, FileAccess.Read)) { ... using (PdfStamper st = PdfStamper.CreateSignature(pdfReader, new FileStream(destination, FileMode.Create, FileAccess.Write), '\0')) { PdfSignatureAppearance sap = st.SignatureAppearance; sap.SetCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.Reason = reason; sap.Location = location; return destination; } } } </code></pre> <p>Below is what I've redone myself which throws System.ObjectDisposedException: Cannot access a closed Stream.</p> <pre><code> public static byte[] PdfSigner(PdfReader pdfReader, string password, string reason, string location, string pathToPfx) { using (FileStream pfxFile = new FileStream(pathToPfx, FileMode.Open, FileAccess.Read)) { ... MemoryStream outputStream = new MemoryStream(); using (PdfStamper st = PdfStamper.CreateSignature(pdfReader, outputStream, '\0')) { st.Writer.CloseStream = false; PdfSignatureAppearance sap = st.SignatureAppearance; sap.SetCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.Reason = reason; sap.Location = location; st.Close(); outputStream.Position = 0; return outputStream.ToArray(); } } } </code></pre> <p>and if I comment out</p> <pre><code>st.Close(); </code></pre> <p>it creates an empty document. What am I doing wrong?</p>
27,209,002
1
2
null
2014-11-28 12:22:18.337 UTC
5
2018-01-02 22:30:16.96 UTC
2018-01-02 22:30:16.96 UTC
null
604,196
null
1,960,917
null
1
29
c#|pdf|itext|memorystream|pdfstamper
29,104
<p>Not specific to your signing code, but when working with <code>MemoryStream</code> and <code>PdfStamper</code>, follow this general pattern:</p> <pre><code>using (MemoryStream ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms, '\0', true)) { // do stuff } return ms.ToArray(); } </code></pre> <ul> <li><code>MemoryStream</code> implements <code>IDisposable</code>, so include a <code>using</code> statement.</li> <li>The <code>PdfStamper</code> <code>using</code> statement takes care of disposing the object, so you don't need to call <code>Close()</code>, and don't need to set the <code>CloseStream</code> property.</li> <li>Your code snippet is returning the byte array <strong>too soon</strong>, inside the <code>PdfStamper</code> <code>using</code> statement, so your <code>MemoryStream</code> is effectively a no-op. Return the byte array <strong>outside</strong> of the <code>PdfStamper</code> <code>using</code> statement, and <strong>inside</strong> the <code>MemoryStream</code> <code>using</code> statement.</li> <li>Generally there's no need to reset the <code>MemoryStream</code> <code>Position</code> property.</li> <li>Ignore the <code>PdfStamper</code> constructor above - it's from some test code I had for filling forms, and use whatever constructor/method you need to do your signing.</li> </ul>
27,257,522
What's the exact limitation on generic associated values in Swift enums?
<p>I am trying to understand the exact limits on enums with generic associated values in Swift.</p> <p>You might think that they are supported, since <code>Optional</code> is such a type. Here is the code defining <code>Optional</code> in the Swift standard library:</p> <pre><code>enum Optional&lt;T&gt; : Reflectable, NilLiteralConvertible { case None case Some(T) // ... } </code></pre> <p>It seems like the case member <code>Some</code> has an associated value of variable type <code>T</code>, right?</p> <p>However, it is mentioned in the book <a href="http://www.objc.io/books/">Functional Programming in Swift</a> (p 87), that such types are not supported:</p> <blockquote> <p>We would like to define a new enumeration that is generic in the result associated with Success:</p> <pre>enum Result&#x0003C;T&#x0003E; { case Success(T) case Failure(NSError) } </pre> <p>Unfortunately, generic associated values are not supported by the current Swift compiler.</p> </blockquote> <p>And indeed, if you type that snippet into the compiler, you get an error (<code>error: unimplemented IR generation feature non-fixed multi-payload enum layout</code>).</p> <p>So what is going on here? Is it just that it is not supported in general, but is supported for <code>Optional</code> as a special case? Is there any way to see how Optional receives this special support? Or if other standard library types also get special support?</p>
27,258,340
2
2
null
2014-12-02 19:37:12.16 UTC
12
2018-03-26 10:09:21.73 UTC
2014-12-02 20:17:16.53 UTC
null
577,888
null
577,888
null
1
15
generics|swift|enums
5,576
<p><em>This answer is out of date in Swift 2. Please see rickster's answer for Swift 2 updates.</em></p> <p>Your comments are correct. You can't have multiple cases with associated data if any of them have unknown size. Value types could be any size (since they're copied). Reference types (like objects) have a known size, because they store a pointer.</p> <p>The typical solution to this is to create an extra wrapper class to hold the generic type, as the FP book does. Everyone calls it <code>Box</code> by convention. There's reason to hope that the Swift team will fix this in the future. As you note, they refer to it as "unimplemented" not "unsupported."</p> <p>A typical implementation of <code>Box</code>:</p> <pre><code>final public class Box&lt;T&gt; { public let unbox: T public init(_ value: T) { self.unbox = value } } </code></pre>
19,339,305
Python function to get the t-statistic
<p>I am looking for a Python function (or to write my own if there is not one) to get the t-statistic in order to use in a confidence interval calculation.</p> <p>I have found tables that give answers for various probabilities / degrees of freedom like <a href="http://www.sussex.ac.uk/Users/grahamh/RM1web/t-testcriticalvalues.pdf" rel="noreferrer">this one</a>, but I would like to be able to calculate this for any given probability. For anyone not already familiar with this degrees of freedom is the number of data points (n) in your sample -1 and the numbers for the column headings at the top are probabilities (p) e.g. a 2 tailed significance level of 0.05 is used if you are looking up the t-score to use in the calculation for 95% confidence that if you repeated n tests the result would fall within the mean +/- the confidence interval.</p> <p>I have looked into using various functions within scipy.stats, but none that I can see seem to allow for the simple inputs I described above.</p> <p>Excel has a simple implementation of this e.g. to get the t-score for a sample of 1000, where I need to be 95% confident I would use: <code>=TINV(0.05,999)</code> and get the score ~1.96</p> <p>Here is the code that I have used to implement confidence intervals so far, as you can see I am using a very crude way of getting the t-score at present (just allowing a few values for perc_conf and warning that it is not accurate for samples &lt; 1000):</p> <pre><code># -*- coding: utf-8 -*- from __future__ import division import math def mean(lst): # μ = 1/N Σ(xi) return sum(lst) / float(len(lst)) def variance(lst): """ Uses standard variance formula (sum of each (data point - mean) squared) all divided by number of data points """ # σ² = 1/N Σ((xi-μ)²) mu = mean(lst) return 1.0/len(lst) * sum([(i-mu)**2 for i in lst]) def conf_int(lst, perc_conf=95): """ Confidence interval - given a list of values compute the square root of the variance of the list (v) divided by the number of entries (n) multiplied by a constant factor of (c). This means that I can be confident of a result +/- this amount from the mean. The constant factor can be looked up from a table, for 95% confidence on a reasonable size sample (&gt;=500) 1.96 is used. """ if perc_conf == 95: c = 1.96 elif perc_conf == 90: c = 1.64 elif perc_conf == 99: c = 2.58 else: c = 1.96 print 'Only 90, 95 or 99 % are allowed for, using default 95%' n, v = len(lst), variance(lst) if n &lt; 1000: print 'WARNING: constant factor may not be accurate for n &lt; ~1000' return math.sqrt(v/n) * c </code></pre> <p>Here is an example call for the above code:</p> <pre><code># Example: 1000 coin tosses on a fair coin. What is the range that I can be 95% # confident the result will f all within. # list of 1000 perfectly distributed... perc_conf_req = 95 n, p = 1000, 0.5 # sample_size, probability of heads for each coin l = [0 for i in range(int(n*(1-p)))] + [1 for j in range(int(n*p))] exp_heads = mean(l) * len(l) c_int = conf_int(l, perc_conf_req) print 'I can be '+str(perc_conf_req)+'% confident that the result of '+str(n)+ \ ' coin flips will be within +/- '+str(round(c_int*100,2))+'% of '+\ str(int(exp_heads)) x = round(n*c_int,0) print 'i.e. between '+str(int(exp_heads-x))+' and '+str(int(exp_heads+x))+\ ' heads (assuming a probability of '+str(p)+' for each flip).' </code></pre> <p>The output for this is:</p> <blockquote> <p>I can be 95% confident that the result of 1000 coin flips will be within +/- 3.1% of 500 i.e. between 469 and 531 heads (assuming a probability of 0.5 for each flip).</p> </blockquote> <p>I also looked into calculating the <a href="http://en.wikipedia.org/wiki/Student%27s_t-distribution" rel="noreferrer">t-distribution</a> for a range and then returning the t-score that got the probability closest to that required, but I had issues implementing the formula. Let me know if this is relevant and you want to see the code, but I have assumed not as there is probably an easier way.</p> <p>Thanks in advance.</p>
19,339,372
3
0
null
2013-10-12 21:18:44.557 UTC
7
2018-12-06 01:12:55.47 UTC
null
null
null
null
2,012,446
null
1
37
python|python-2.7|statistics|confidence-interval
67,823
<p>Have you tried scipy?</p> <p>You will need to installl the scipy library...more about installing it here: <a href="http://www.scipy.org/install.html" rel="noreferrer">http://www.scipy.org/install.html</a></p> <p>Once installed, you can replicate the Excel functionality like such:</p> <pre><code>from scipy import stats #Studnt, n=999, p&lt;0.05, 2-tail #equivalent to Excel TINV(0.05,999) print stats.t.ppf(1-0.025, 999) #Studnt, n=999, p&lt;0.05%, Single tail #equivalent to Excel TINV(2*0.05,999) print stats.t.ppf(1-0.05, 999) </code></pre> <p>You can also read about installing the library here: <a href="https://stackoverflow.com/questions/12735524/how-to-install-scipy-for-python">how to install scipy for python?</a></p>
19,646,889
Why should I use log.Println instead of fmt.Println?
<p>From <a href="http://golang.org/src/pkg/log/log.go" rel="noreferrer">log.go</a> (the implementation of the log package) : </p> <pre><code>167 // Println calls l.Output to print to the logger. 168 // Arguments are handled in the manner of fmt.Println. 169 func (l *Logger) Println(v ...interface{}) { l.Output(2, fmt.Sprintln(v...)) } </code></pre> <p><a href="http://golang.org/pkg/log/#Println" rel="noreferrer"><code>log.Println</code></a> is just a function wrapper for <a href="http://golang.org/pkg/fmt/#Sprintln" rel="noreferrer"><code>fmt.Sprintln</code></a> , why should I use it instead of <a href="http://golang.org/pkg/fmt/#Println" rel="noreferrer"><code>fmt.Println</code></a> or <a href="http://golang.org/pkg/fmt/#Sprintln" rel="noreferrer"><code>fmt.Sprintln</code></a> ?</p> <p>Any practical reasons ?</p>
19,646,964
1
0
null
2013-10-28 23:22:04.843 UTC
11
2019-03-27 12:17:50 UTC
2013-10-29 08:11:41.037 UTC
null
1,120,221
null
1,120,221
null
1
102
logging|go
29,167
<p>Two things are different:</p> <ol> <li><p>Printing via package log is safe from concurrent goroutines (while plain <code>fmt</code> isn't)</p></li> <li><p>Log can add timing information automatically.</p></li> </ol> <p>So these are two completely different things. log is for logging and <code>fmt</code> for formatting. (Okay, log uses the same verbs and flags, but that is just convenient).</p>
19,719,439
Calculate the number of ways to roll a certain number
<p>I'm a high school Computer Science student, and today I was given a problem to:</p> <blockquote> <p>Program Description: There is a belief among dice players that in throwing three dice a ten is easier to get than a nine. Can you write a program that proves or disproves this belief?</p> <p>Have the computer compute all the possible ways three dice can be thrown: 1 + 1 + 1, 1 + 1 + 2, 1 + 1 + 3, etc. Add up each of these possibilities and see how many give nine as the result and how many give ten. If more give ten, then the belief is proven.</p> </blockquote> <p>I quickly worked out a brute force solution, as such</p> <pre><code>int sum,tens,nines; tens=nines=0; for(int i=1;i&lt;=6;i++){ for(int j=1;j&lt;=6;j++){ for(int k=1;k&lt;=6;k++){ sum=i+j+k; //Ternary operators are fun! tens+=((sum==10)?1:0); nines+=((sum==9)?1:0); } } } System.out.println("There are "+tens+" ways to roll a 10"); System.out.println("There are "+nines+" ways to roll a 9"); </code></pre> <p>Which works just fine, and a brute force solution is what the teacher wanted us to do. However, it doesn't scale, and I am trying to find a way to make an algorithm that can calculate the number of ways to roll <i>n</i> dice to get a specific number. Therefore, I started generating the number of ways to get each sum with <i>n</i> dice. With 1 die, there is obviously 1 solution for each. I then calculated, through brute force, the combinations with 2 and 3 dice. These are for two: </p> <blockquote> <p>There are 1 ways to roll a 2<br> There are 2 ways to roll a 3<br> There are 3 ways to roll a 4<br> There are 4 ways to roll a 5<br> There are 5 ways to roll a 6<br> There are 6 ways to roll a 7<br> There are 5 ways to roll a 8<br> There are 4 ways to roll a 9<br> There are 3 ways to roll a 10<br> There are 2 ways to roll a 11<br> There are 1 ways to roll a 12<br></p> </blockquote> <p>Which looks straightforward enough; it can be calculated with a simple linear absolute value function. But then things start getting trickier. With 3:</p> <blockquote> <p>There are 1 ways to roll a 3<br> There are 3 ways to roll a 4<br> There are 6 ways to roll a 5<br> There are 10 ways to roll a 6<br> There are 15 ways to roll a 7<br> There are 21 ways to roll a 8<br> There are 25 ways to roll a 9<br> There are 27 ways to roll a 10<br> There are 27 ways to roll a 11<br> There are 25 ways to roll a 12<br> There are 21 ways to roll a 13<br> There are 15 ways to roll a 14<br> There are 10 ways to roll a 15<br> There are 6 ways to roll a 16<br> There are 3 ways to roll a 17<br> There are 1 ways to roll a 18<br></p> </blockquote> <p>So I look at that, and I think: Cool, Triangular numbers! However, then I notice those pesky 25s and 27s. So it's obviously not triangular numbers, but still some polynomial expansion, since it's symmetric. <br> So I take to Google, and I come across <a href="https://math.stackexchange.com/questions/68045/rolling-dice-such-that-they-add-up-to-13-is-there-a-more-elegant-way-to-solve">this page</a> that goes into some detail about how to do this with math. It is fairly easy(albeit long) to find this using repeated derivatives or expansion, but it would be much harder to program that for me. I didn't quite understand the second and third answers, since I have never encountered that notation or those concepts in my math studies before. Could someone please explain how I could write a program to do this, or explain the solutions given on that page, for my own understanding of combinatorics?</p> <p>EDIT: I'm looking for a mathematical way to solve this, that gives an exact theoretical number, not by simulating dice</p>
19,719,634
4
1
null
2013-11-01 01:27:40 UTC
8
2013-11-02 03:51:38.757 UTC
2017-04-13 12:19:15.777 UTC
null
-1
null
2,027,567
null
1
19
java|algorithm|probability|combinatorics
13,583
<p>The solution using the generating-function method with <code>N(d, s)</code> is probably the easiest to program. You can use recursion to model the problem nicely:</p> <pre><code>public int numPossibilities(int numDice, int sum) { if (numDice == sum) return 1; else if (numDice == 0 || sum &lt; numDice) return 0; else return numPossibilities(numDice, sum - 1) + numPossibilities(numDice - 1, sum - 1) - numPossibilities(numDice - 1, sum - 7); } </code></pre> <p>At first glance this seems like a fairly straightforward and efficient solution. However you will notice that many calculations of the same values of <code>numDice</code> and <code>sum</code> may be repeated and recalculated over and over, making this solution probably even less efficient than your original brute-force method. For example, in calculating all the counts for <code>3</code> dice, my program ran the <code>numPossibilities</code> function a total of <code>15106</code> times, as opposed to your loop which only takes <code>6^3 = 216</code> executions.</p> <p>To make this solution viable, you need to add one more technique - memoization (caching) of previously calculated results. Using a <code>HashMap</code> object, for example, you can store combinations that have already been calculated and refer to those first before running the recursion. When I implemented a cache, the <code>numPossibilities</code> function only runs <code>151</code> times total to calculate the results for <code>3</code> dice.</p> <p>The efficiency improvement grows larger as you increase the number of dice (results are based on simulation with my own implemented solution):</p> <pre><code># Dice | Brute Force Loop Count | Generating-Function Exec Count 3 | 216 (6^3) | 151 4 | 1296 (6^4) | 261 5 | 7776 (6^5) | 401 6 | 46656 (6^6) | 571 7 | 279936 (6^7) | 771 ... 20 | 3656158440062976 | 6101 </code></pre>
605,492
Hide/Show NavigationBar & Toolbar on tap
<p>I'm trying to hide my navigationBar and toolbars on tap, similar to the way the Photos application works. </p> <p>Any pointers would be greatly appreciated. </p> <p>Thanks!</p>
605,731
4
0
null
2009-03-03 08:01:57.31 UTC
12
2014-10-30 23:40:29.273 UTC
2012-11-26 10:35:35.897 UTC
null
1,809,253
dot
null
null
1
10
iphone
6,176
<p>Try to animate the y value of UINavigationBar and UIToolBar like this</p> <pre><code>[UIView beginAnimations: nil context:NULL]; [UIView setAnimationDuration:0.4]; [UIView setAnimationDelegate: self]; CGRect rect = self.navigationController.navigationBar.frame; rect.origin.y = -40; self.navigationController.navigationBar.frame = rect; [UIView commitAnimations]; </code></pre> <p>Hope this helps you too.</p> <p>A.</p>
78,592
What is a good equivalent to Perl lists in bash?
<p>In perl one would simply do the following to store and iterate over a list of names</p> <pre><code>my @fruit = (apple, orange, kiwi); foreach (@fruit) { print $_; } </code></pre> <p>What would the equivalent be in bash?</p>
78,631
4
0
null
2008-09-17 00:15:13.847 UTC
10
2019-03-12 19:04:18.73 UTC
2019-03-12 19:04:18.73 UTC
null
6,862,601
moran
10,747
null
1
24
arrays|bash
21,134
<p>bash (unlike POSIX sh) supports arrays:</p> <pre><code>fruits=(apple orange kiwi "dried mango") for fruit in "${fruits[@]}"; do echo "${fruit}" done </code></pre> <p>This has the advantage that array elements may contain spaces or other members of $IFS; as long as they were correctly inserted as separate elements, they are read out the same way.</p>
138,331
Any decent text diff/merge engine for .NET?
<p>Requirements:</p> <ul> <li>free, preferably open-source</li> <li>implemented in one of the .NET managed langs</li> </ul> <p>Google found these:</p> <ul> <li><a href="http://www.codeproject.com/KB/recipes/diffengine.aspx" rel="noreferrer">A Generic, Reusable Diff Algorithm</a> on codeproject</li> <li><a href="http://www.mathertel.de/Diff/" rel="noreferrer">An O(ND) Difference Algorithm for C#</a></li> <li><a href="http://razor.occams.info/code/diff/" rel="noreferrer">Diff/Merge/Patch Library for C#/.NET</a> by Joshua Tauberer</li> </ul> <p>EDIT:</p> <p>No apps please, only libraries.</p>
864,439
4
3
null
2008-09-26 08:42:34.65 UTC
60
2021-01-05 17:10:56.977 UTC
2008-09-26 09:36:42.397 UTC
aku
1,196
aku
1,196
null
1
114
.net|merge|diff
57,836
<p>You can grab <a href="https://stackoverflow.com/questions/848246/how-can-i-use-javascript-within-an-excel-macro">the COM component that uses Google's Diff/Patch/Match</a>. It works from .NET. </p> <p><strong>Update, 2010 Oct 17</strong>: The <a href="http://code.google.com/p/google-diff-match-patch/" rel="noreferrer">Google Diff/Patch/Merge code</a> has been ported to C#. The COM component still works, but if you're coming from .NET, you'll wanna use the .NET port directly. </p>
55,591,437
AttributeError: module 'tensorflow' has no attribute 'gfile'
<p>I trained a simple mnist model with <strong>tensorflow 2.0</strong> on <strong>Google Colab</strong> and saved it in the <strong>.json</strong> format. <a href="https://drive.google.com/open?id=15Pr20eximHhrkvsCGHPgwMUQKpPyShRd" rel="noreferrer">Click here</a> to check out the Colab Notebook where I've written the code. Then on running the command</p> <p><code>!simple_tensorflow_serving --model_base_path="/" --model_platform="tensorflow"</code></p> <p>It is showing the error AttributeError: module 'tensorflow' has no attribute 'gfile'</p> <p><a href="https://github.com/tobegit3hub/simple_tensorflow_serving" rel="noreferrer">simple_tensorflow_serving</a> helps in easily deploying trained tensorflow model into production.</p> <p><strong>Versions</strong> I'm using:</p> <p>(1) TensorFlow - 2.0</p> <p>(2) simple_tensorflow_serving - 0.6.4</p> <p>Thank you in advance :)</p>
55,595,294
5
1
null
2019-04-09 11:08:50.483 UTC
2
2022-09-20 18:51:22.623 UTC
null
null
null
null
9,841,117
null
1
18
google-colaboratory|tensorflow-serving|tensorflow2.0
47,952
<p>Simple Tensorflow Serving is not ready for Tensorflow 2.0, since it is using the old API. In Tensorflow 2.0 the <code>gfile</code> package has been moved into <code>tf.io</code>.</p> <p>Then, you have to downgrade your Tensorflow instance to TF 1.13 use Simple Tensorflow Serving</p>
40,866,675
Implementation difference between TensorFlow Variable and TensorFlow Tensor
<p>First of all, I am aware that a related question has been asked <a href="https://stackoverflow.com/questions/38556078/in-tensorflow-what-is-the-difference-between-a-variable-and-a-tensor">here</a>.</p> <p>However, this question is about the implementation and internals. I was reading the paper "<a href="https://arxiv.org/pdf/1610.01178.pdf" rel="noreferrer">A Tour of TensorFlow</a>". The following two points are quoted from there:</p> <p>1.</p> <blockquote> <p>A tensor itself does not hold or store values in memory, but provides only an interface for retrieving the value referenced by the tensor.</p> </blockquote> <p>This suggests to me that a Tensor is an object that simply stores the pointer to a result of an operation and, on retrieving the result or value of the tensor, it simply dereferences that pointer.</p> <p>2.</p> <blockquote> <p>Variables can be described as persistent, mutable handles to in-memory buffers storing tensors. As such, variables are characterized by a certain shape and a fixed type.</p> </blockquote> <p>At this I get confused because I thought, based on the previous point, that Tensors simply store a pointer. If they were simply pointers, they could be mutable as well.</p> <p>To be precise these are my questions:</p> <ol> <li>What is the meaning of "in-memory buffers"?</li> <li>What is the meaning of a "handle"?</li> <li>Is my initial assumption about the internals of a tensor correct? </li> <li>What is the essential internal implementation difference between a tensor and a variable? Why are they declared differently and why is that difference essential to TensorFlow?</li> </ol>
40,871,108
1
0
null
2016-11-29 13:06:36.81 UTC
24
2016-11-29 16:54:06.853 UTC
2017-05-23 12:34:42.623 UTC
null
-1
null
6,842,947
null
1
23
tensorflow
10,546
<p>Before explaining the distinction between tensors and variables, we should be precise about what the word "tensor" means in the context of TensorFlow:</p> <ul> <li><p>In the <strong>Python API</strong>, a <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/framework.html#Tensor" rel="noreferrer"><code>tf.Tensor</code></a> object represents the symbolic result of a TensorFlow operation. For example, in the expression <code>t = tf.matmul(x, y)</code>, <code>t</code> is a <code>tf.Tensor</code> object representing the result of multiplying <code>x</code> and <code>y</code> (which may themselves be symbolic results of other operations, concrete values such as NumPy arrays, or variables).</p> <p>In this context, a "symbolic result" is more complicated than a pointer to the result of an operation. It is more analogous to a function object that, when called (i.e. passed to <code>tf.Session.run()</code>) will run the necessary computation to produce the result of that operation, and return it to you as a concrete value (e.g. a NumPy array).</p></li> <li><p>In the <strong>C++ API</strong>, a <a href="https://github.com/tensorflow/tensorflow/blob/5657d0dee8d87f4594b3e5902ed3e3ca8d6dfc0a/tensorflow/core/framework/tensor.h" rel="noreferrer"><code>tensorflow::Tensor</code></a> object represents the concrete value of a multi-dimensional array. For example, the <code>MatMul</code> kernel takes two two-dimensional <code>tensorflow::Tensor</code> objects as inputs, and produces a single two-dimensional <code>tensorflow::Tensor</code> object as its output.</p></li> </ul> <p>This distinction is a little confusing, and we might choose different names if we started over (in other language APIs, we prefer the name <code>Output</code> for a symbolic result and <code>Tensor</code> for a concrete value).</p> <p>A similar distinction exists for variables. In the Python API, a <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/state_ops.html#Variable" rel="noreferrer"><code>tf.Variable</code></a> is the symbolic representation of a variable, which has methods for creating operations that read the current value of the variable, and assign values to it. In the C++ implementation, a <a href="https://github.com/tensorflow/tensorflow/blob/5657d0dee8d87f4594b3e5902ed3e3ca8d6dfc0a/tensorflow/core/kernels/variable_ops.h#L29" rel="noreferrer"><code>tensorflow::Var</code></a> object is a wrapper around a shared, mutable <code>tensorflow::Tensor</code> object.</p> <p>With that context out the way, we can address your specific questions:</p> <ol> <li><p><strong>What is the meaning of "in-memory buffers"?</strong></p> <p>An in-memory buffer is simply a contiguous region of memory that has been allocated with a TensorFlow allocator. <code>tensorflow::Tensor</code> objects contain a pointer to an in-memory buffer, which holds the values of that tensor. The buffer could be in host memory (i.e. accessible from the CPU) or device memory (e.g. accessible only from a GPU), and TensorFlow has operations to move data between these memory spaces.</p></li> <li><p><strong>What is the meaning of a "handle"?</strong> </p> <p>In the explanation in <a href="https://arxiv.org/pdf/1610.01178.pdf" rel="noreferrer">the paper</a>, the word "handle" is used in a couple of different ways, which are slightly different from how TensorFlow uses the term. The paper uses "symbolic handle" to refer to a <code>tf.Tensor</code> object, and "persistent, mutable handle" to refer to a <code>tf.Variable</code> object. The TensorFlow codebase uses "handle" to refer to a name for a stateful object (like a <code>tf.FIFOQueue</code> or <code>tf.TensorArray</code>) that can be passed around without copying all of the values (i.e. <a href="https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference" rel="noreferrer">call-by-reference</a>).</p></li> <li><p><strong>Is my initial assumption about the internal of a tensor correct?</strong></p> <p>Your assumption most closely matches the definition of a (C++) <code>tensorflow::Tensor</code> object. The (Python) <code>tf.Tensor</code> object is more complicated because it refers to a function for computing a value, rather than the value itself.</p></li> <li><p><strong>What is the essential internal implementation difference between a tensor and a variable?</strong></p> <p>In C++, a <code>tensorflow::Tensor</code> and <code>tensorflow::Var</code> are very similar; the only different is that <code>tensorflow::Var</code> also has a <code>mutex</code> that can be used to lock the variable when it is being updated.</p> <p>In Python, the essential difference is that a <code>tf.Tensor</code> is implemented as a dataflow graph, and it is read-only (i.e. by calling <code>tf.Session.run()</code>). A <code>tf.Variable</code> can be both read (i.e. by evaluating its read operation) and written (e.g. by running an assign operation).</p> <p><strong>Why are they declared differently and why is that difference essential to TensorFlow?</strong></p> <p>Tensors and variables serve different purposes. Tensors (<code>tf.Tensor</code> objects) can represent complex compositions of mathematical expressions, like loss functions in a neural network, or symbolic gradients. Variables represent state that is updated over time, like weight matrices and convolutional filters during training. While in principle you could represent the evolving state of a model without variables, you would end up with a very large (and repetetive) mathematical expression, so variables provide a convenient way to materialize the state of the model, and&mdash;for example&mdash;share it with other machines for parallel training.</p></li> </ol>
40,796,062
Sumifs in Excel-VBA
<p>I have some problem with <code>sumifs</code> in vba:</p> <pre><code>Dim Arg1 As Range 'the range i want to sum Dim Arg2 As Range 'criteria range Dim Arg3 As Variant 'the criteria Set Arg1 = ThisWB.Sheets("Sheet1").Range("B2:B100") Set Arg2 = ThisWB.Sheets("Sheet1").Range("C1:C100") Set Arg3 = ThisWB.Sheets("Sheet2").Range("A2:A12") For i = 2 To 12 Workbooks("x.xlsx").Worksheets("Sheet2").Cells(i, LastColumn) _ = Application.WorksheetFunction.SumIfs(Arg1, Arg2, Arg3) Next </code></pre> <p>I always get a "Type mismatch" error</p> <p>Could anybody help me to fix the code?</p> <p>Thank you in advance.</p>
40,796,148
1
0
null
2016-11-25 00:14:43.5 UTC
null
2018-05-09 06:59:00.577 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
7,185,786
null
1
3
vba|excel|sumifs
39,774
<p><a href="https://msdn.microsoft.com/en-us/library/office/ff193011.aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/office/ff193011.aspx</a></p> <pre><code>Sub test() Dim Arg1 As Range 'the range i want to sum Dim Arg2 As Range 'criteria range Dim Arg3 As Variant 'the criteria 'Arg1 and Arg2 must be the same size Set Arg1 = Sheets("Sheet1").Range("B2:B100") Set Arg2 = Sheets("Sheet1").Range("C2:C100") 'this is the criteria Arg3 = "=False" Dim ws As Worksheet Set ws = ActiveSheet Dim i As Integer For i = 2 To 12 ws.Cells(i, 8).Value = Application.WorksheetFunction.SumIfs(Arg1, Arg2, Arg3) Next End Sub </code></pre> <p>You can also specify Arg3 as a variant and pass a single-cell range if it has the criteria. Criteria can be True/False (=False), a number (20) or a string (">100"). </p> <pre><code> Dim Arg3 As Variant 'the criteria Arg3 = Sheets("Sheet2").Range("A2") </code></pre> <p>EDIT: I realized what you were trying to do. Each cell in Arg3 is a separate criteria that you want to do SumIf on. Here is the revised code.</p> <pre><code>Sub test2() Dim ThisWB As Workbook: Set ThisWB = ThisWorkbook Dim i As Integer Dim LastColumn As Integer: LastColumn = 3 Dim Arg1 As Range 'the range i want to sum Dim Arg2 As Range 'criteria range Dim Arg3 As Range 'the criteria (range) Set Arg1 = ThisWB.Sheets("Sheet1").Range("B2:B100") Set Arg2 = ThisWB.Sheets("Sheet1").Range("C2:C100") Set Arg3 = ThisWB.Sheets("Sheet2").Range("A2:A12") For i = 2 To 12 Workbooks("x.xlsx").Worksheets("Sheet2").Cells(i, LastColumn) _ = Application.WorksheetFunction.SumIfs(Arg1, Arg2, Arg3.Cells(i - 1, 1).Value) Next End Sub </code></pre> <p>Note how Arg3 is used in SumIfs <code>Arg3.Cells(i - 1, 1).Value</code>. Also note that Arg1 and Arg2 must be the same size.</p>
39,542,853
Enable VT-x in your BIOS security settings (refer to documentation for your computer)
<p>While I was adding a virtual device in my Android Studio, Android Studio is Showing This Error. See This Image: <a href="https://i.stack.imgur.com/X4fNh.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/X4fNh.jpg" alt="enter image description here"></a> .</p>
39,542,859
13
0
null
2016-09-17 04:28:06.79 UTC
19
2021-01-08 18:32:44.96 UTC
2016-09-17 04:47:41.257 UTC
null
2,101,822
null
6,737,231
null
1
58
android|android-studio|haxm
297,524
<p><a href="https://i.stack.imgur.com/H2zEE.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/H2zEE.gif" alt="enter image description here"></a></p> <p>shutdown you pc and open bios settings, and enable Virtual Technology-x option and restart your pc.</p> <p>done.</p>
33,889,410
Proper way to implement RESTful large file upload
<p>I've been making REST APIs for some time now, and I'm still bugged with one case - large file upload. I've read a couple of other APIs, like Google Drive, Twitter and other literature, and I got two ideas, but I'm not sure is any of them "proper". As in proper, I mean it is somewhat standardized, there is not too much client logic needed (since other parties will be implementing that client), or even better, it could be easily called with cURL. The plan is to implement it in Java, preferably Play Framework.</p> <p>Obviously I'll need some file partitioning and server-side buffering mechanism since the files are large.</p> <p>So, the first solution I've got is a multipart upload (<code>multipart/form-data</code>). I get this way and I have implemented it like this before, but it is always strange to me to actually emulate a form on the client side, especially since the client has to set the file key name, and in my experience, that is something that clients kinda forget or do not understand. Also, how is the chunk size/part size dictated? What keeps the client from putting the whole file in one chunk?</p> <p>Solution two, at least what I understood, but without finding an actual implementation implementation is that a "regular" POST request can work. The content should be chunked and data is buffered on the on the server side. However, I am not sure this is a proper understanding. How is data actually chunked, does the upload span multiple HTTP requests or is it chunked on the TCP level? What is the <code>Content-Type</code>? </p> <p>Bottom line, what of these two (or anything else?) should be a client-friendly, widely understandable, way of implementing a REST API for file upload?</p>
50,659,874
2
1
null
2015-11-24 09:06:33.873 UTC
15
2019-07-03 16:24:01.27 UTC
null
null
null
null
794,967
null
1
41
java|file|rest|curl|file-upload
43,808
<p>I would recommend taking a look at the Amazon S3 Rest API's solution to multipart file upload. The documentation can be found <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingRESTAPImpUpload.html" rel="noreferrer">here</a>.</p> <p>To summarize the procedure Amazon uses:</p> <ol> <li><p>The client sends a request to initiate a multipart upload, the API responds with an upload id</p></li> <li><p>The client uploads each file chunk with a part number (to maintain ordering of the file), the size of the part, the md5 hash of the part and the upload id; each of these requests is a separate HTTP request. The API validates the chunk by checking the md5 hash received chunk against the md5 hash the client supplied and the size of the chunk matches the size the client supplied. The API responds with a tag (unique id) for the chunk. If you deploy your API across multiple locations you will need to consider how to store the chunks and later access them in a way that is location transparent.</p></li> <li><p>The client issues a request to complete the upload which contains a list of each chunk number and the associated chunk tag (unique id) received from API. The API validates there are no missing chunks and that the chunk numbers match the correct chunk tag and then assembles the file or returns an error response.</p></li> </ol> <p>Amazon also supplies methods to abort the upload and list the chunks associated with the upload. You may also want to consider a timeout for the upload request in which the chunks are destroyed if the upload is not completed within a certain amount of time.</p> <p>In terms of controlling the chunk sizes that the client uploads, you won't have much control over how the client decides to split up the upload. You could consider having a maximum chunk size configured for the upload and supply error responses for requests that contain chunks larger than the max size.</p> <p>I've found the procedure works very well for handling large file uploads in REST APIs and facilitates the handling of the many edge cases associated with file upload. Unfortunately, I've yet to find a library that makes this easy to implement in any language so you pretty much have to write all of the logic yourself.</p>
2,297,453
Get CSS Div to fill available height
<p>I have a div with 2 elements.</p> <pre><code>&lt;div id="master"&gt; &lt;div id="follower"&gt;&lt;/div&gt; &lt;div id="decider"&gt;&lt;/div&gt; &lt;div&gt; </code></pre> <p>'master' div has the following CSS properties</p> <pre><code>height:auto; width:auto; margin:0; padding:10px; display:block; </code></pre> <p>The 'follower' div has the following CSS properties</p> <pre><code>position:relative; vertical-align:middle; height: auto; display: inline-block; margin-top: 0px; margin-bottom:0px; </code></pre> <p>The 'decider' div decides how tall the 'master' div is. Is it possible for the 'follower' div to fill up as much vertical space in the 'master' div as possible?</p> <p>I tried <code>height: 100%</code> but that just made the 'follower' div take up the whole screen (vertically)</p>
2,297,481
1
0
null
2010-02-19 15:36:07.373 UTC
2
2010-02-19 15:39:35.617 UTC
null
null
null
null
156,242
null
1
12
html|css
41,444
<p>The master should have</p> <pre><code>position: relative; </code></pre> <p>and then the follower should have</p> <pre><code>position: absolute; top: 0; bottom: 0; </code></pre> <p>That should work, except in IE6 (which an alarming amount of people are still using, but I would just disregard those and tell them to update their browser)</p>
1,570,589
Is the volatile keyword required for fields accessed via a ReentrantLock?
<p>My question refers to whether or not the use of a ReentrantLock guarantees visibility of a field in the same respect that the synchronized keyword provides. </p> <p>For example, in the following class <em>A</em>, the field <em>sharedData</em> does not need to be declared volatile as the synchronized keyword is used.</p> <pre><code>class A { private double sharedData; public synchronized void method() { double temp = sharedData; temp *= 2.5; sharedData = temp + 1; } } </code></pre> <p>For next example using a ReentrantLock however, is the volatile keyword on the field necessary?</p> <pre><code>class B { private final ReentrantLock lock = new ReentrantLock(); private volatile double sharedData; public void method() { lock.lock(); try { double temp = sharedData; temp *= 2.5; sharedData = temp + 1; } finally { lock.unlock(); } } } </code></pre> <p>I know that using the volatile keyword anyway will only likely impose a miniscule performance hit, but I would still like to code correctly.</p>
1,570,603
1
0
null
2009-10-15 06:18:35.867 UTC
5
2017-05-10 09:21:03.063 UTC
2017-05-10 09:21:03.063 UTC
null
57,461
null
85,418
null
1
30
java|concurrency|locking|volatile|reentrancy
3,373
<p>It's safe without volatility. <code>ReentrantLock</code> implements <code>Lock</code>, and the <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/Lock.html" rel="noreferrer">docs for <code>Lock</code></a> include this:</p> <blockquote> <p>All <code>Lock</code> implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock, as described in The Java Language Specification, Third Edition (17.4 Memory Model):</p> <ul> <li>A successful <code>lock</code> operation has the same memory synchronization effects as a successful <code>Lock</code> action.</li> <li>A successful <code>unlock</code> operation has the same memory synchronization effects as a successful <code>Unlock</code> action.</li> </ul> </blockquote>
1,917,773
Dynamic ListView in Android app
<p>Is there a working example out there that demonstrates how to append additional rows in ListView dynamically? For example:</p> <ol> <li>you are pulling RSS feeds from different domains</li> <li>you then display the first 10 items in the ListView (while you have other threads running in the background continue pulling feeds)</li> <li>you scroll and reach the bottom of the List and click at a button to view more items</li> <li>the ListView will then get appended with additional 10 items, which makes 20 items now in total.</li> </ol> <p>Any advice how to accomplish this?</p> <p>Nicholas</p>
1,917,861
1
0
null
2009-12-16 21:11:48.81 UTC
41
2016-10-15 20:24:56.52 UTC
null
null
null
null
226,582
null
1
33
java|android|listview|dynamic
66,077
<p>To add new item to your list dynamically you have to get adapter class from your ListActivity and simply add new elements. When you add items directly to adapter, notifyDataSetChanged is called automatically for you - and the view updates itself. <p> You can also provide your own adapter (extending ArrayAdapter) and override the constructor taking List parameter. You can use this list just as you use adapter, but in this case you have to call adapter.notifyDataSetChanged() by yourself - to refresh the view. <br> Please, take a look at the example below:<br></p> <pre><code>public class CustomList extends ListActivity { private LayoutInflater mInflater; private Vector&lt;RowData&gt; data; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE); data = new Vector&lt;RowData&gt;(); RowData rd = new RowData("item1", "description1"); data.add(rd); rd = new RowData("item2", "description2"); data.add(rd); rd = new RowData("item2", "description3"); data.add(rd); CustomAdapter adapter = new CustomAdapter(this, R.layout.custom_row,R.id.item, data); setListAdapter(adapter); getListView().setTextFilterEnabled(true); } public void onListItemClick(ListView parent, View v, int position, long id) { CustomAdapter adapter = (CustomAdapter) parent.getAdapter(); RowData row = adapter.getItem(position); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(row.mItem); builder.setMessage(row.mDescription + " -&gt; " + position ); builder.setPositiveButton("ok", null); builder.show(); } /** * Data type used for custom adapter. Single item of the adapter. */ private class RowData { protected String mItem; protected String mDescription; RowData(String item, String description){ mItem = item; mDescription = description; } @Override public String toString() { return mItem + " " + mDescription; } } private class CustomAdapter extends ArrayAdapter&lt;RowData&gt; { public CustomAdapter(Context context, int resource, int textViewResourceId, List&lt;RowData&gt; objects) { super(context, resource, textViewResourceId, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; //widgets displayed by each item in your list TextView item = null; TextView description = null; //data from your adapter RowData rowData= getItem(position); //we want to reuse already constructed row views... if(null == convertView){ convertView = mInflater.inflate(R.layout.custom_row, null); holder = new ViewHolder(convertView); convertView.setTag(holder); } // holder = (ViewHolder) convertView.getTag(); item = holder.getItem(); item.setText(rowData.mItem); description = holder.getDescription(); description.setText(rowData.mDescription); return convertView; } } /** * Wrapper for row data. * */ private class ViewHolder { private View mRow; private TextView description = null; private TextView item = null; public ViewHolder(View row) { mRow = row; } public TextView getDescription() { if(null == description){ description = (TextView) mRow.findViewById(R.id.description); } return description; } public TextView getItem() { if(null == item){ item = (TextView) mRow.findViewById(R.id.item); } return item; } } </code></pre> <p>}</p> <p>You can extend the example above and add "more" button - which just add new items to your adapter (or vector).<br> Regards!</p>
30,193,569
Get Content-Disposition parameters
<p>How do I get Content-Disposition parameters I returned from WebAPI controller using WebClient?</p> <p>WebApi Controller</p> <pre><code> [Route("api/mycontroller/GetFile/{fileId}")] public HttpResponseMessage GetFile(int fileId) { try { var file = GetSomeFile(fileId) HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(new MemoryStream(file)); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = file.FileOriginalName; /********* Parameter *************/ response.Content.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("MyParameter", "MyValue")); return response; } catch(Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); } } </code></pre> <p>Client</p> <pre><code> void DownloadFile() { WebClient wc = new WebClient(); wc.DownloadDataCompleted += wc_DownloadDataCompleted; wc.DownloadDataAsync(new Uri("api/mycontroller/GetFile/18")); } void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { WebClient wc=sender as WebClient; // Try to extract the filename from the Content-Disposition header if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"])) { string fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 10).Replace("\"", ""); //FileName ok /****** How do I get "MyParameter"? **********/ } var data = e.Result; //File OK } </code></pre> <p>I'm returning a file from WebApi controller, I'm attaching the file name in the response content headers, but also I'd like to return an aditional value. </p> <p>In the client I'm able to get the filename, but <strong>how do I get the aditional parameter?</strong></p>
30,193,961
4
0
null
2015-05-12 14:16:52.653 UTC
6
2019-11-10 10:21:06.29 UTC
2018-10-02 08:22:02.963 UTC
null
4,519,059
null
3,596,441
null
1
22
c#|asp.net-web-api2|webclient|httpresponse|content-disposition
38,643
<p>If you are working with .NET 4.5 or later, consider using the <a href="https://msdn.microsoft.com/en-us/library/system.net.mime.contentdisposition(v=vs.110).aspx" rel="noreferrer">System.Net.Mime.ContentDisposition</a> class:</p> <pre><code>string cpString = wc.ResponseHeaders["Content-Disposition"]; ContentDisposition contentDisposition = new ContentDisposition(cpString); string filename = contentDisposition.FileName; StringDictionary parameters = contentDisposition.Parameters; // You have got parameters now </code></pre> <p><strong>Edit:</strong></p> <p>otherwise, you need to parse Content-Disposition header according to it's <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html" rel="noreferrer">specification</a>.</p> <p>Here is a simple class that performs the parsing, close to the specification:</p> <pre><code>class ContentDisposition { private static readonly Regex regex = new Regex( "^([^;]+);(?:\\s*([^=]+)=((?&lt;q&gt;\"?)[^\"]*\\k&lt;q&gt;);?)*$", RegexOptions.Compiled ); private readonly string fileName; private readonly StringDictionary parameters; private readonly string type; public ContentDisposition(string s) { if (string.IsNullOrEmpty(s)) { throw new ArgumentNullException("s"); } Match match = regex.Match(s); if (!match.Success) { throw new FormatException("input is not a valid content-disposition string."); } var typeGroup = match.Groups[1]; var nameGroup = match.Groups[2]; var valueGroup = match.Groups[3]; int groupCount = match.Groups.Count; int paramCount = nameGroup.Captures.Count; this.type = typeGroup.Value; this.parameters = new StringDictionary(); for (int i = 0; i &lt; paramCount; i++ ) { string name = nameGroup.Captures[i].Value; string value = valueGroup.Captures[i].Value; if (name.Equals("filename", StringComparison.InvariantCultureIgnoreCase)) { this.fileName = value; } else { this.parameters.Add(name, value); } } } public string FileName { get { return this.fileName; } } public StringDictionary Parameters { get { return this.parameters; } } public string Type { get { return this.type; } } } </code></pre> <p>Then you can use it in this way:</p> <pre><code>static void Main() { string text = "attachment; filename=\"fname.ext\"; param1=\"A\"; param2=\"A\";"; var cp = new ContentDisposition(text); Console.WriteLine("FileName:" + cp.FileName); foreach (DictionaryEntry param in cp.Parameters) { Console.WriteLine("{0} = {1}", param.Key, param.Value); } } // Output: // FileName:"fname.ext" // param1 = "A" // param2 = "A" </code></pre> <p>The only thing that should be considered when using this class is it does not handle parameters (or filename) without a double quotation. </p> <p><strong>Edit 2:</strong></p> <p>It can now handle file names without quotations.</p>
29,825,198
NullPointerException - Attempt to get length of null array (readDirectory())
<p>I have the code as shown here. My Problem is a NullPointerException at files.length</p> <pre><code>for(int i=0; i &lt; files.length; i++){ </code></pre> <p>It is caused because i have a "fail readDirectory() errno=13" at</p> <pre><code>File[] files = f.listFiles(); </code></pre> <p>But why do I have a readDirectory fail when the path is good?</p> <pre><code>package com.example.androidexplorer; import java.io.File; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.os.Environment; import android.app.AlertDialog; import android.app.ListActivity; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends ListActivity { private List&lt;String&gt; item = null; private List&lt;String&gt; path = null; private String root; private TextView myPath; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myPath = (TextView)findViewById(R.id.path); root = Environment.getExternalStorageDirectory().getPath(); getDir(root); } private void getDir(String dirPath) { myPath.setText("Location: " + dirPath); item = new ArrayList&lt;String&gt;(); path = new ArrayList&lt;String&gt;(); File f = new File(dirPath); Log.v("Path: ", dirPath); Log.v("BEFORE", "Before Reading Fail..."); File[] files = f.listFiles(); Log.v("AFTER", "After Reading Fail..."); if(!dirPath.equals(root)) { item.add(root); path.add(root); item.add("../"); path.add(f.getParent()); } Log.v("CRASH", "1 Line before crash"); for(int i=0; i &lt; files.length; i++){ Log.v("AFTER CRASH", "1 Line after crash"); File file = files[i]; if(!file.isHidden() &amp;&amp; file.canRead()){ path.add(file.getPath()); if(file.isDirectory()){ item.add(file.getName() + "/"); }else{ item.add(file.getName()); } } } ArrayAdapter&lt;String&gt; fileList = new ArrayAdapter&lt;String&gt;(this, R.layout.row, item); setListAdapter(fileList); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub File file = new File(path.get(position)); if (file.isDirectory()) { if(file.canRead()){ getDir(path.get(position)); }else{ new AlertDialog.Builder(this) .setIcon(R.drawable.ic_launcher) .setTitle("[" + file.getName() + "] folder can't be read!") .setPositiveButton("OK", null).show(); } }else { new AlertDialog.Builder(this) .setIcon(R.drawable.ic_launcher) .setTitle("[" + file.getName() + "]") .setPositiveButton("OK", null).show(); } } } </code></pre> <p>LogCat:</p> <blockquote> <pre><code>&gt; 04-23 15:35:34.084: D/ResourcesManager(20672): creating new &gt; AssetManager and set to &gt; /data/app/com.example.androidexplorer-1/base.apk 04-23 15:35:34.104: &gt; I/art(20672): Created application space &gt; /data/dalvik-cache/arm/data@[email protected]@[email protected] &gt; at 0x76eb0000~0x76f15ff8 04-23 15:35:34.104: I/art(20672): Loaded art &gt; file: &gt; /data/dalvik-cache/arm/data@[email protected]@[email protected] &gt; 04-23 15:35:34.194: V/BitmapFactory(20672): &gt; DecodeImagePath(decodeResourceStream3) : &gt; res/drawable-xxhdpi-v4/ic_ab_back_holo_dark_am.png 04-23 15:35:34.204: &gt; V/BitmapFactory(20672): DecodeImagePath(decodeResourceStream3) : &gt; res/drawable-xxhdpi-v4/sym_def_app_icon.png 04-23 15:35:34.234: &gt; D/AbsListView(20672): Get MotionRecognitionManager 04-23 15:35:34.244: &gt; V/BitmapFactory(20672): DecodeImagePath(decodeResourceStream3) : &gt; res/drawable-xhdpi-v4/ic_launcher.png 04-23 15:35:34.254: &gt; V/Path:(20672): /storage/emulated/0 04-23 15:35:34.254: &gt; V/BEFORE(20672): Before Reading Fail... 04-23 15:35:34.254: &gt; E/File(20672): fail readDirectory() errno=13 04-23 15:35:34.254: &gt; V/AFTER(20672): After Reading Fail... 04-23 15:35:34.254: &gt; V/CRASH(20672): 1 Line before crash 04-23 15:35:34.254: &gt; D/AndroidRuntime(20672): Shutting down VM 04-23 15:35:34.254: &gt; E/AndroidRuntime(20672): FATAL EXCEPTION: main 04-23 15:35:34.254: &gt; E/AndroidRuntime(20672): Process: com.example.androidexplorer, PID: &gt; 20672 04-23 15:35:34.254: E/AndroidRuntime(20672): &gt; java.lang.RuntimeException: Unable to start activity &gt; ComponentInfo{com.example.androidexplorer/com.example.androidexplorer.MainActivity}: &gt; java.lang.NullPointerException: Attempt to get length of null array &gt; 04-23 15:35:34.254: E/AndroidRuntime(20672): at &gt; android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658) &gt; 04-23 15:35:34.254: E/AndroidRuntime(20672): at &gt; android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725) &gt; 04-23 15:35:34.254: E/AndroidRuntime(20672): at &gt; android.app.ActivityThread.access$900(ActivityThread.java:172) 04-23 &gt; 15:35:34.254: E/AndroidRuntime(20672): at &gt; android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422) &gt; 04-23 15:35:34.254: E/AndroidRuntime(20672): at &gt; android.os.Handler.dispatchMessage(Handler.java:102) 04-23 &gt; 15:35:34.254: E/AndroidRuntime(20672): at &gt; android.os.Looper.loop(Looper.java:145) 04-23 15:35:34.254: &gt; E/AndroidRuntime(20672): at &gt; android.app.ActivityThread.main(ActivityThread.java:5834) 04-23 &gt; 15:35:34.254: E/AndroidRuntime(20672): at &gt; java.lang.reflect.Method.invoke(Native Method) 04-23 15:35:34.254: &gt; E/AndroidRuntime(20672): at &gt; java.lang.reflect.Method.invoke(Method.java:372) 04-23 15:35:34.254: &gt; E/AndroidRuntime(20672): at &gt; com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388) &gt; 04-23 15:35:34.254: E/AndroidRuntime(20672): at &gt; com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) 04-23 &gt; 15:35:34.254: E/AndroidRuntime(20672): Caused by: &gt; java.lang.NullPointerException: Attempt to get length of null array &gt; 04-23 15:35:34.254: E/AndroidRuntime(20672): at &gt; com.example.androidexplorer.MainActivity.getDir(MainActivity.java:57) &gt; 04-23 15:35:34.254: E/AndroidRuntime(20672): at &gt; com.example.androidexplorer.MainActivity.onCreate(MainActivity.java:31) &gt; 04-23 15:35:34.254: E/AndroidRuntime(20672): at &gt; android.app.Activity.performCreate(Activity.java:6221) 04-23 &gt; 15:35:34.254: E/AndroidRuntime(20672): at &gt; android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) &gt; 04-23 15:35:34.254: E/AndroidRuntime(20672): at &gt; android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611) &gt; 04-23 15:35:34.254: E/AndroidRuntime(20672): ... 10 more </code></pre> </blockquote> <p><strong>UPDATE</strong></p> <p>Error was in my manifest with the permissions. What I had at the beginning:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.spicysoftware.infoid" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="15" android:targetSdkVersion="15" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:name="android.permission.READ_EXTERNAL_STORAGE"&gt; &lt;activity android:name=".MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".sysinfo"&gt;&lt;/activity&gt; &lt;activity android:name=".daten"&gt;&lt;/activity&gt; &lt;activity android:name=".storage"&gt;&lt;/activity&gt; &lt;activity android:name="org.achartengine.GraphicalActivity"&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>And Updated:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.spicysoftware.infoid" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="15" android:targetSdkVersion="15" /&gt; &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"&gt; &lt;activity android:name=".MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".sysinfo"&gt;&lt;/activity&gt; &lt;activity android:name=".daten"&gt;&lt;/activity&gt; &lt;activity android:name=".storage"&gt;&lt;/activity&gt; &lt;activity android:name="org.achartengine.GraphicalActivity"&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre>
29,825,321
4
0
null
2015-04-23 13:38:55.593 UTC
5
2021-11-09 01:58:50.143 UTC
2015-04-23 14:43:09.76 UTC
null
1,903,816
null
1,903,816
null
1
17
android|nullpointerexception|directory
84,213
<pre><code>f.listFiles() </code></pre> <p>will return null if the path does not exist.</p> <p>Please check your path.</p> <p><strong>Update</strong></p> <p>Android will also require a permission to read certain files. Maybe you need to add this to your manifest:</p> <pre><code> &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; </code></pre> <p>More information:</p> <p><a href="http://developer.android.com/reference/android/Manifest.permission.html">http://developer.android.com/reference/android/Manifest.permission.html</a></p>
58,469,229
React with Typescript -- Generics while using React.forwardRef
<p>I am trying to create a generic component where a user can pass the a custom <code>OptionType</code> to the component to get type checking all the way through. This component also required a <code>React.forwardRef</code>.</p> <p>I can get it to work without a forwardRef. Any ideas? Code below:</p> <p><strong>WithoutForwardRef.tsx</strong></p> <pre><code>export interface Option&lt;OptionValueType = unknown&gt; { value: OptionValueType; label: string; } interface WithoutForwardRefProps&lt;OptionType&gt; { onChange: (option: OptionType) =&gt; void; options: OptionType[]; } export const WithoutForwardRef = &lt;OptionType extends Option&gt;( props: WithoutForwardRefProps&lt;OptionType&gt;, ) =&gt; { const { options, onChange } = props; return ( &lt;div&gt; {options.map((opt) =&gt; { return ( &lt;div onClick={() =&gt; { onChange(opt); }} &gt; {opt.label} &lt;/div&gt; ); })} &lt;/div&gt; ); }; </code></pre> <p><strong>WithForwardRef.tsx</strong></p> <pre><code>import { Option } from './WithoutForwardRef'; interface WithForwardRefProps&lt;OptionType&gt; { onChange: (option: OptionType) =&gt; void; options: OptionType[]; } export const WithForwardRef = React.forwardRef( &lt;OptionType extends Option&gt;( props: WithForwardRefProps&lt;OptionType&gt;, ref?: React.Ref&lt;HTMLDivElement&gt;, ) =&gt; { const { options, onChange } = props; return ( &lt;div&gt; {options.map((opt) =&gt; { return ( &lt;div onClick={() =&gt; { onChange(opt); }} &gt; {opt.label} &lt;/div&gt; ); })} &lt;/div&gt; ); }, ); </code></pre> <p><strong>App.tsx</strong></p> <pre><code>import { WithoutForwardRef, Option } from './WithoutForwardRef'; import { WithForwardRef } from './WithForwardRef'; interface CustomOption extends Option&lt;number&gt; { action: (value: number) =&gt; void; } const App: React.FC = () =&gt; { return ( &lt;div&gt; &lt;h3&gt;Without Forward Ref&lt;/h3&gt; &lt;h4&gt;Basic&lt;/h4&gt; &lt;WithoutForwardRef options={[{ value: 'test', label: 'Test' }, { value: 1, label: 'Test Two' }]} onChange={(option) =&gt; { // Does type inference on the type of value in the options console.log('BASIC', option); }} /&gt; &lt;h4&gt;Custom&lt;/h4&gt; &lt;WithoutForwardRef&lt;CustomOption&gt; options={[ { value: 1, label: 'Test', action: (value) =&gt; { console.log('ACTION', value); }, }, ]} onChange={(option) =&gt; { // Intellisense works here option.action(option.value); }} /&gt; &lt;h3&gt;With Forward Ref&lt;/h3&gt; &lt;h4&gt;Basic&lt;/h4&gt; &lt;WithForwardRef options={[{ value: 'test', label: 'Test' }, { value: 1, label: 'Test Two' }]} onChange={(option) =&gt; { // Does type inference on the type of value in the options console.log('BASIC', option); }} /&gt; &lt;h4&gt;Custom (WitForwardRef is not generic here)&lt;/h4&gt; &lt;WithForwardRef&lt;CustomOption&gt; options={[ { value: 1, label: 'Test', action: (value) =&gt; { console.log('ACTION', value); }, }, ]} onChange={(option) =&gt; { // Intellisense SHOULD works here option.action(option.value); }} /&gt; &lt;/div&gt; ); }; </code></pre> <p>In the <code>App.tsx</code>, it says the <code>WithForwardRef</code> component is not generic. Is there a way to achieve this?</p> <p>Example repo: <a href="https://github.com/jgodi/generics-with-forward-ref" rel="noreferrer">https://github.com/jgodi/generics-with-forward-ref</a></p> <p>Thanks!</p>
58,473,012
2
0
null
2019-10-20 00:58:22.5 UTC
14
2022-09-21 16:30:01.193 UTC
null
null
null
null
2,133,032
null
1
63
reactjs|typescript|generics
24,608
<p>Creating a generic component as output of <code>React.forwardRef</code> is not directly possible <sup>1</sup> (see bottom). There are some alternatives though - let's simplify your example a bit for illustration:</p> <pre><code>type Option&lt;O = unknown&gt; = { value: O; label: string; } type Props&lt;T extends Option&lt;unknown&gt;&gt; = { options: T[] } const options = [ { value: 1, label: &quot;la1&quot;, flag: true }, { value: 2, label: &quot;la2&quot;, flag: false } ] </code></pre> <p>Choose variants (1) or (2) for simplicity. (3) will replace <code>forwardRef</code> by usual props. With (4) you globally chance <code>forwardRef</code> type definitions once in the app.</p> <h3>1. Use <a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions" rel="noreferrer">type assertion</a> (&quot;cast&quot;)</h3> <pre><code>// Given render function (input) for React.forwardRef const FRefInputComp = &lt;T extends Option&gt;(p: Props&lt;T&gt;, ref: Ref&lt;HTMLDivElement&gt;) =&gt; &lt;div ref={ref}&gt; {p.options.map(o =&gt; &lt;p&gt;{o.label}&lt;/p&gt;)} &lt;/div&gt; // Cast the output const FRefOutputComp1 = React.forwardRef(FRefInputComp) as &lt;T extends Option&gt;(p: Props&lt;T&gt; &amp; { ref?: Ref&lt;HTMLDivElement&gt; }) =&gt; ReactElement const Usage11 = () =&gt; &lt;FRefOutputComp1 options={options} ref={myRef} /&gt; // options has type { value: number; label: string; flag: boolean; }[] // , so we have made FRefOutputComp generic! </code></pre> <p>This works, as the return type of <code>forwardRef</code> in principle is a <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/9d56fee/types/react/index.d.ts#L800" rel="noreferrer">plain function</a>. We just need a generic function type shape. You might add an extra type to make the assertion simpler:</p> <pre><code>type ForwardRefFn&lt;R&gt; = &lt;P={}&gt;(p: P &amp; React.RefAttributes&lt;R&gt;) =&gt; ReactElement |null // `RefAttributes` is built-in type with ref and key props defined const Comp12 = React.forwardRef(FRefInputComp) as ForwardRefFn&lt;HTMLDivElement&gt; const Usage12 = () =&gt; &lt;Comp12 options={options} ref={myRef} /&gt; </code></pre> <h3>2. Wrap forwarded component</h3> <pre><code>const FRefOutputComp2 = React.forwardRef(FRefInputComp) // ↳ T is instantiated with base constraint `Option&lt;unknown&gt;` from FRefInputComp export const Wrapper = &lt;T extends Option&gt;({myRef, ...rest}: Props&lt;T&gt; &amp; {myRef: React.Ref&lt;HTMLDivElement&gt;}) =&gt; &lt;FRefOutputComp2 {...rest} ref={myRef} /&gt; const Usage2 = () =&gt; &lt;Wrapper options={options} myRef={myRef} /&gt; </code></pre> <h3>3. Omit <code>forwardRef</code> alltogether</h3> <p>Use a <a href="https://reactjs.org/docs/refs-and-the-dom.html#exposing-dom-refs-to-parent-components" rel="noreferrer">custom ref prop</a> instead. This one is my favorite - simplest alternative, a <a href="https://stackoverflow.com/questions/58578570/value-of-using-react-forwardref-vs-custom-ref-prop/60237948#60237948">legitimate way in React</a> and doesn't need <code>forwardRef</code>.</p> <pre><code>const Comp3 = &lt;T extends Option&gt;(props: Props&lt;T&gt; &amp; {myRef: Ref&lt;HTMLDivElement&gt;}) =&gt; &lt;div ref={myRef}&gt; {props.options.map(o =&gt; &lt;p&gt;{o.label}&lt;/p&gt;)} &lt;/div&gt; const Usage3 = () =&gt; &lt;Comp3 options={options} myRef={myRef} /&gt; </code></pre> <h3>4. Use global type augmentation</h3> <p>Add following code <em>once</em> in your app, perferrably in a separate module <code>react-augment.d.ts</code>:</p> <pre><code>import React from &quot;react&quot; declare module &quot;react&quot; { function forwardRef&lt;T, P = {}&gt;( render: (props: P, ref: ForwardedRef&lt;T&gt;) =&gt; ReactElement | null ): (props: P &amp; RefAttributes&lt;T&gt;) =&gt; ReactElement | null } </code></pre> <p>This will <a href="https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation" rel="noreferrer">augment</a> React module type declarations, overriding <code>forwardRef</code> with a new <a href="https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads" rel="noreferrer">function overload</a> type signature. Tradeoff: component properties like <code>displayName</code> now need a type assertion.</p> <hr /> <h2><sup>1</sup> Why does the original case not work?</h2> <p><a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/9d56fee/types/react/index.d.ts#L800" rel="noreferrer"><code>React.forwardRef</code></a> has following type:</p> <pre><code>function forwardRef&lt;T, P = {}&gt;(render: ForwardRefRenderFunction&lt;T, P&gt;): ForwardRefExoticComponent&lt;PropsWithoutRef&lt;P&gt; &amp; RefAttributes&lt;T&gt;&gt;; </code></pre> <p>So this function takes a <a href="https://www.typescriptlang.org/docs/handbook/2/generics.html" rel="noreferrer">generic</a> component-like <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/9d56fee/types/react/index.d.ts#L559-L572" rel="noreferrer">render function</a> <code>ForwardRefRenderFunction</code>, and returns the final component with type <code>ForwardRefExoticComponent</code>. These two are just function type declarations <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#properties-declarations-on-functions" rel="noreferrer">with additional properties</a> <code>displayName</code>, <code>defaultProps</code> etc.</p> <p>Now, there is a TypeScript 3.4 feature called <a href="https://github.com/microsoft/TypeScript/pull/30215" rel="noreferrer">higher order function type inference</a> akin to <a href="https://www.stephanboyer.com/post/115/higher-rank-and-higher-kinded-types" rel="noreferrer">Higher-Rank Types</a>. It basically allows you to propagate free type parameters (generics from the input function) on to the outer, calling function - <code>React.forwardRef</code> here -, so the resulting function component is still generic.</p> <p>But this feature can only work with plain function types, as Anders Hejlsberg explains in <a href="https://github.com/microsoft/TypeScript/issues/30650#issuecomment-478258803" rel="noreferrer">[1]</a>, <a href="https://github.com/microsoft/TypeScript/issues/30650#issuecomment-486680485" rel="noreferrer">[2]</a>:</p> <blockquote> <p>We only make higher order function type inferences when the source and target types are both pure function types, i.e. types with a single call signature <em>and no other members</em>.</p> </blockquote> <p>Above solutions will make <code>React.forwardRef</code> work with generics again.</p> <hr /> <p><a href="https://www.typescriptlang.org/play/?jsx=2&amp;ssl=19&amp;ssc=70&amp;pln=17&amp;pc=1#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDeikBm2y6MAogDZIhIB28AvnAVBCHAERSoYcBQfGAE8wSOAHkwMYBFoAecXAC8cAK60A1rQgB3WgD5luPnFNwAbigqqkALgkBuE2YooARkgr2AzjCjBaAHMnBgFhUTgABVYwbzkAFTgkAA8YOgATbwkpGXl1LV0DQxU8CBzZb3t4gG0AXThQgHpGuAArVV84bzYxMukKuHSUGBQ+NAr4PtyslWq8S2s7OABGbFcPL05XZY5sAldA+z8bBux5qxt7ACY19097Dlcr3eYD+wIrbzEGWrGJuBAQmQBCMJAwADo0NxhkhgXIABLxACyABkACLAcyUah0GD6AAUAEoBM0+M0VuC4ABhFCdYAwMmNEktADimLocACYFU8HG4GY0HwpHBBGgOhQUHSwL+tE6ADFgQBJWjcmBUthgIwJJKpDJZST9Az4sAxSpRU0JfTYbgEexwxGojFYqg0ej6QnKfTOUxydKYuA2pQ4G0MQw4E1lbzgqYVcEgFBgfEQT1wORgfQ4CDg9aeBhyRrpwlMfN+8xexnU2nwGAAC16PNVMvlwPEDZ56vAy1BPBgIrFEqlhHxCsIytVHbAHtp3tTiRSaVomWyhoJYHs0UjlrgADJcAHCAB+O2EBHI9GY7GuvEND1KQxg8gu3ECcay+AAVW8KECSGWXZURIpnII4EK2MDjhqXYxrKQbQd4TCBjggLAkwjReuScFwDWtJwOEYjnIs9i0KoIAeFADhwDmmy+P4QQUfs372G4EAQFQKC0BRDB1HAFbYN0cA6GI2HmGI8bpGIIFgRB-I-rQSD+GgACEzJwOCalwIKHRiOxOp+CguEiEggiGXAcr9pKwJyvICDFKmkRGDgobGuuO5ChCwIAIIwH4wBuDySBxDZt73j2l64nAAA+cDERQFAVp53n+H5aRZMAWR+cAFAwAAtAEAn0jW+4gux6RwBoSBCHAEaxIMhABEg6RNvAE7LFc3bCqKUDihZQ4gWO7YalOWRmV1A6WfIDrns6OJuk1cCft+v5tQBwWpi1bVwbB5SyghhBBshhCoeWpLklclIAOpQAmnIMqSc2SW2aoastbm9p13WDgQw5KiqA3gMS5KJGl+5gK4aANXAbiVfSWSvjRKABPABq5HI+TaHohh5Q94F-WAVwCCkkCwHAcPwJdCaiFAWpzrqi76ttBJ4AdRCqWp3CdAwtgzhusRbruTNAoQx7CvaZ5OmFbo3kB2PSXjuBqeC7MwLtBD7YLBBHS+-wLT+L2AXeqbk2AlMadt3hbYa8EAurasoXAaHMhWADMlJaSTHQwGwRVVTEnLePQqClRAILvWNhCMlrb7UhqTvU7perLrkq6muuFrxIY-PW8Cx4EKejoXk+ksMMFM6+v6iHM6GuDVVGcFxgmSZAemmbZncFB5gW7rFo0pZeqT81fj+scrUBE6x5tmZm0wzO24d9v6EAA" rel="noreferrer">Playground variants 1, 2, 3</a></p> <p><a href="https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDeA5FEJAEwFEAPCGYNAYQnAgDskmYBfOAMygbgCIoqDPwBQo4kjQAbFELggIxAK7SkAoehj9couHAD0BuADFocACoBlOGFkBPAOa9lTYthj2w60JFgBnOBYSOBgIOAAjdWV-ELCFFABrdRgAC3V-Qjt1NAYwYDUAOj1DYwBJJjhpCDQUaThJADdsewhlOFrKmPUzKAB3OUliZC5sZC1SNSI2MaQuAEEYGChgCOUYJEDiYCEMaXti-S5XDGBmbmgBqGG5gB4LbAAFOABeXHYAPgAKEv0hNyQUAAXHAvmBeGB-CDHtghFwQb5oDAvoJhNoAJSFXpXIYje4fdGvD5wRGwFGaESY8YYSZIabwAA%20QVU0hK6JBYIhULgzwAZCTGGTUVp%20FS5otlqt1pt8YSXsTScjhZTCtSYLT6XAmUwWaJ2OJgGxAVx0OpHlz8bp9CgQRY9eJckx-PALCgImpsYMRsgAVBXnB7k9-ThPj99OCIJDoRbHh9MCU4SC1VjLoMSHiLB9RHLibdto0PjgI5DCih2LcDPms6JHc7LG6PanriN6OB-cmuE2blwvq73UhPc25j7JFB0eIjHAABIQRqAuCz%20f8FA6YuBFBuIJUGgpdI7OCOViAmihLxIUSTkw7OvLnTAQLOlZMRzYWKO4jMkBRKA15h1%20ZgGA-pfDmoIlLcWb6Po9wNgOXYtnkcAoC8-CdhAOgGMSvwBn2jb9F6cytkByE4AAzJwmFwOBmHZgA3OIvawYO3ZEUh65MPYmLbP4dgoPYBBEKIjH9sxCFtiggQCSQFDbnQeTMKwMBcfevH8YQ564XB%20FDlwRGFNxqlSaUDQQJsTAAOTwH00CJKe3gALR9Pe6gbvYihCOIQA" rel="noreferrer">Playground variant 4</a></p>
24,315,753
elasticsearch - querying multiple indexes is possible?
<p>I have an elasticsearch cluster with 3 indexes:</p> <pre><code>/users/user /events/visit /events/register /pages/page </code></pre> <p>So, now I need to run queries processing multiple indexes.</p> <p>Eg: <strong>Get gender of users registered in page X.</strong> (<em>To get this info, I need infos from multiple indexes.</em>)</p> <p>Is this possible? Maybe integrating hadoop?</p>
24,333,514
3
0
null
2014-06-19 20:32:06.39 UTC
18
2021-09-22 08:52:49.273 UTC
null
null
null
null
3,175,226
null
1
60
elasticsearch
68,692
<p>This is quite easy within Elasticsearch itself! Anytime you would specify an index, you can separate additional indices by comma. </p> <pre><code>curl -XGET 'http://localhost:9200/index1,index2/_search?q=yourQueryHere' </code></pre> <p>You can also search all indices with _all.</p> <pre><code>curl -XGET 'http://localhost:9200/_all/_search?q=yourQueryHere' </code></pre> <p>Here's some helpful documentation from elasticsearch's website. This site has TONS of info, but it is a bit difficult to find sometimes, IMO.</p> <p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html" rel="noreferrer">https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html</a> <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-index.html" rel="noreferrer">https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-index.html</a></p>
36,020,110
How do I avoid unwrap when converting a vector of Options or Results to only the successful values?
<p>I have a <code>Vec&lt;Result&lt;T, E&gt;&gt;</code> and I want to ignore all <code>Err</code> values, converting it into a <code>Vec&lt;T&gt;</code>. I can do this:</p> <pre><code>vec.into_iter().filter(|e| e.is_ok()).map(|e| e.unwrap()).collect() </code></pre> <p>This is safe, but I want to avoid using <code>unwrap</code>. Is there a better way to write this?</p>
36,020,284
1
0
null
2016-03-15 19:13:08.977 UTC
3
2019-02-04 19:35:29.907 UTC
2019-02-04 19:35:10.093 UTC
null
155,423
null
941,764
null
1
33
rust|iterator
10,426
<blockquote> <p>I want to ignore all <code>Err</code> values</p> </blockquote> <p>Since <a href="https://doc.rust-lang.org/std/result/enum.Result.html#impl-IntoIterator" rel="noreferrer"><code>Result</code> implements <code>IntoIterator</code></a>, you can convert your <code>Vec</code> into an iterator (which will be an iterator of iterators) and then flatten it:</p> <ul> <li><p><a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flatten" rel="noreferrer"><code>Iterator::flatten</code></a>:</p> <pre><code>vec.into_iter().flatten().collect() </code></pre></li> <li><p><a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flat_map" rel="noreferrer"><code>Iterator::flat_map</code></a>:</p> <pre><code>vec.into_iter().flat_map(|e| e).collect() </code></pre></li> </ul> <p>These methods also work for <a href="https://doc.rust-lang.org/std/option/enum.Option.html" rel="noreferrer"><code>Option</code></a>, which <a href="https://doc.rust-lang.org/std/option/enum.Option.html#impl-IntoIterator-2" rel="noreferrer">also implements <code>IntoIterator</code></a>.</p> <hr> <p>You could also convert the <code>Result</code> into an <code>Option</code> and use <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter_map" rel="noreferrer"><code>Iterator::filter_map</code></a>:</p> <pre><code>vec.into_iter().filter_map(|e| e.ok()).collect() </code></pre>
41,930,608
Jenkins Git integration - How to disable SSL certificate validation
<p>I am getting the below error while creating a job from Jenkins. How do I disable certificate validation in Jenkins?</p> <p>From Git Bash I can use <code>git config --global http.sslVerify false</code> command to disable it, but not sure how to use it from Jenkins.</p> <p>Error:</p> <pre><code>Failed to connect to repository : Command "C:\Program Files (x86)\Git\cmd\git.exe ls-remote -h url ofmy repository.git HEAD" returned status code 128: stdout: stderr: fatal: unable to access 'url of my git/': SSL certificate problem: self signed certificate in certificate chain </code></pre>
41,932,902
7
0
null
2017-01-30 07:12:32.743 UTC
6
2022-08-22 12:36:46.643 UTC
2017-01-30 10:26:59.123 UTC
null
711,006
null
4,385,285
null
1
20
git|jenkins|jenkins-plugins
84,883
<p>Best option is to add the self-signed certificate to your certificate store</p> <p>Obtain the server certificate tree This can be done using chrome.</p> <ol> <li><p>Navigate to be server address. Click on the padlock icon and view the certificates. Export all of the certificate chain as base64 encoded files (PEM) format.</p></li> <li><p>Add the certificates to the trust chain of your GIT trust config file In Git bash on the the machine running the job run the following: </p></li> </ol> <blockquote> <p>"git config --list". </p> </blockquote> <p>find the <code>http.sslcainfo</code> configuration this shows where the certificate trust file is located. 3. Copy all the certificates into the trust chain file including the <code>"- -BEGIN- -"</code> and the <code>"- -END- -"</code>. Make sure you add the ROOT certificate Chain to the certificates file</p> <p>This should solve your issue with the self-signed certificates and using GIT.</p> <p>NOT RECOMMENDED</p> <p>The other way is to remote into your slave and run the following:</p> <blockquote> <p>git config --global http.sslVerify false</p> </blockquote> <p>This will save into the global config that this instance never does SSL verification, this is NOT recommended, it should be used only when testing and then disabled again. It should be done properly as above.</p>
50,355,045
How to apply classes to Vue.js Functional Component from parent component?
<p>Suppose I have a functional component:</p> <pre><code>&lt;template functional&gt; &lt;div&gt;Some functional component&lt;/div&gt; &lt;/template&gt; </code></pre> <p>Now I render this component in some parent with classes:</p> <pre><code>&lt;parent&gt; &lt;some-child class="new-class"&gt;&lt;/some-child&gt; &lt;/parent&gt; </code></pre> <p>Resultant <code>DOM</code> doesn't have <code>new-class</code> applied to the Functional child component. Now as I understand, <code>Vue-loader</code> compiles <strong>Functional</strong> component against <code>render</code> function <code>context</code> as <a href="https://vue-loader.vuejs.org/guide/functional.html" rel="noreferrer">explained here</a>. That means classes won't be directly applied and merge intelligently.</p> <p>Question is - <strong>how can I make Functional component play nicely with the externally applied class when using a template?</strong></p> <p><em>Note: I know it is easily possible to do so via render function:</em></p> <pre><code>Vue.component("functional-comp", { functional: true, render(h, context) { return h("div", context.data, "Some functional component"); } }); </code></pre>
50,728,775
3
0
null
2018-05-15 16:24:15.517 UTC
9
2022-07-15 01:03:18.18 UTC
null
null
null
null
5,723,098
null
1
24
javascript|vue.js|vuejs2|vue-component
10,123
<h2>TL;DR;</h2> <p>Use <code>data.staticClass</code> to get the class, and bind the other attributes using <code>data.attrs</code></p> <pre class="lang-html prettyprint-override"><code>&lt;template functional&gt; &lt;div class="my-class" :class="data.staticClass || ''" v-bind="data.attrs"&gt; //... &lt;/div&gt; &lt;/template&gt; </code></pre> <h2>Explanation:</h2> <p><code>v-bind</code> binds all the other stuff, and you may not need it, but it will bind attributes like <code>id</code> or <code>style</code>. The problem is that you can't use it for <code>class</code> because that's a reserved js object so vue uses <code>staticClass</code>, so binding has to be done manually using <code>:class="data.staticClass"</code>.</p> <p>This will fail if the <code>staticClass</code> property is not defined, by the parent, so you should use <code>:class="data.staticClass || ''"</code></p> <h2>Example:</h2> <p>I can't show this as a fiddle, since only <em>"Functional components defined as a Single-File Component in a *.vue file also receives proper template compilation"</em></p> <p>I've got a working codesandbox though: <a href="https://codesandbox.io/s/z64lm33vol" rel="noreferrer">https://codesandbox.io/s/z64lm33vol</a></p>
65,079,558
How to delete .eslintcache file in react?
<p>I'm new to React. I have a problem I can not solve. I have an &quot;.eslintcache&quot; file, which was created for me automatically as soon as I created a new app in React using &quot;create-react-app&quot;. I do not know why I have this file. I tried to delete it but it always comes back. I ran this command - &quot;npm uninstall -g eslint --save&quot; - to delete eslint's directory but it does not help. I do not know how to handle it, I did not find a solution to it, I would be happy to help.</p> <p><a href="https://i.stack.imgur.com/YGss9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YGss9.png" alt="enter image description here" /></a></p>
65,356,248
6
0
null
2020-11-30 18:58:57.8 UTC
6
2021-06-28 15:25:18.403 UTC
2021-02-15 21:14:58.713 UTC
null
14,093,555
null
14,093,555
null
1
64
reactjs
33,559
<p>This is part of the new version in react. I also had files &quot;reportWebVitals&quot; and &quot;setupTests&quot;, I deleted them and everything works properly.</p> <p>With &quot;reportWebVitals&quot; you can track real user performance on your site. And with &quot;setupTests&quot; you are Initializing Test Environment</p> <p>this feature is available with [email protected] and higher</p> <p>I do not need these properties, just deleted them and that's it, the eslintcache can not be deleted is part of the bundle.</p>
46,766,422
How to do an action if an optional boolean is true?
<p>In Java 8, I have a variable, holding an optional boolean.</p> <p>I want an action to be executed, if the optional is not empty, and the contained boolean is true.</p> <p>I am dreaming about something like <code>ifPresentAndTrue</code>, here a full example:</p> <pre><code>import java.util.Optional; public class X { public static void main(String[] args) { Optional&lt;Boolean&gt; spouseIsMale = Optional.of(true); spouseIsMale.ifPresentAndTrue(b -&gt; System.out.println("There is a male spouse.")); } } </code></pre>
46,766,608
6
0
null
2017-10-16 08:55:05.863 UTC
2
2019-09-04 11:27:09.063 UTC
2018-08-24 15:01:10.597 UTC
null
1,531,124
null
476,791
null
1
20
java|java-8|boolean|option-type
47,502
<p>For good order</p> <pre><code>if (spouseIsMale.orElse(false)) { System.out.println("There is a male spouse."); } </code></pre> <p>Clear.</p>
37,253,068
Programmatically get the name of the pod that a container belongs to in Kubernetes?
<p>Is there a way to programmatically get the name of the pod that a container belongs to in Kubernetes? If so how? I'm using fabric8's java client but curl or something similar will be fine as well.</p> <p>Note that I don't want to find the pod using a specific label since then (I assume) I may not always find the right pod if it's scaled with a replication controller.</p>
37,261,036
2
1
null
2016-05-16 11:39:57.057 UTC
11
2016-05-16 18:44:02.76 UTC
null
null
null
null
398,441
null
1
21
java|kubernetes|fabric8
20,398
<p>You can tell Kubernetes to put the pod name in an environment variable of your choice using the <a href="http://kubernetes.io/docs/user-guide/downward-api/" rel="noreferrer">downward API</a>.</p> <p>For example:</p> <pre><code>apiVersion: v1 kind: Pod metadata: name: dapi-test-pod spec: containers: - name: test-container image: gcr.io/google_containers/busybox command: [ "/bin/sh", "-c", "env" ] env: - name: MY_POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: MY_POD_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace - name: MY_POD_IP valueFrom: fieldRef: fieldPath: status.podIP restartPolicy: Never </code></pre>
48,000,307
Angular 5 reactive form set mat-checkbox to check
<p>I am trying to use mat-checkbox with reactive forms on Angular 5.1.2 and Angular Material 5.0.2.</p> <p>Everything is working well except that when I use patchValue({amateur: [false]) it is still checked. What is weird is I have other forms where I am doing the same thing and they work fine. It also isn't just the amateur checkbox, it is all the checkboxes are checked. Just using "amateur" as an example.</p> <p>The formControl amateur.value is always false. However once the patched value is executed, the control is checked.</p> <p>What am I missing?</p> <p>HTML5</p> <pre><code> &lt;form [formGroup]="showClassGrp"&gt; &lt;mat-checkbox id="amateur" class="amateur" color="primary" formControlName="amateur"&gt;Amateur&lt;/mat-checkbox&gt; &lt;/form&gt; </code></pre> <p>TypeScript</p> <p>FormBuilder works and display is correct.</p> <pre><code>this.showClassGrp = this.fb.group({ ... amateur: [false], ... }); </code></pre> <p>patch showClassGrp and all the checkboxes are checked even thou the formControl value for them are false. </p> <pre><code> this.showClassGrp.patchValue({ className: [this.showClass.className], //this works amateur: [false], // this changed the display to checked. ... }); </code></pre>
48,000,569
1
2
null
2017-12-28 00:48:11.007 UTC
1
2017-12-28 01:45:27.04 UTC
null
null
null
null
2,088,318
null
1
20
angular|angular-material2|angular-reactive-forms
78,856
<p>If you're using reactive from, you may want to assign a FormControl to each member in the form. Something like this</p> <p>component.ts</p> <pre><code> showClassGrp: FormGroup; constructor() { } ngOnInit() { this.showClassGrp = new FormGroup({ 'amateur': new FormControl(false), }); } onSubmit(){ console.log(this.showClassGrp.value.amateur); this.showClassGrp.patchValue({amateur: false}); console.log(this.showClassGrp.value.amateur); } </code></pre> <p>component.html</p> <pre><code>&lt;form [formGroup]="showClassGrp" (ngSubmit)="onSubmit()"&gt; &lt;mat-checkbox id="amateur" class="amateur" color="primary" formControlName="amateur"&gt;Amateur&lt;/mat-checkbox&gt; &lt;button class="btn btn-primary" type="submit"&gt; Submit &lt;/button&gt; &lt;/form&gt; </code></pre>
30,691,904
Rendering problems for Android Studio
<p>Since yesterday I have start to working with Android studio. My problem is when I make my layout. I've next error <em>(watch the screenshot for more information)</em>:</p> <blockquote> <p><strong>Rendering Problem:</strong> This version of the rendering library is more recent than your version of Android Studio. Please update Android Studio </p> </blockquote> <p><a href="https://i.stack.imgur.com/44DAm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/44DAm.jpg" alt="Problem"></a></p> <p>If I check for updates he say that I already have the latest version of Android studio and so I can't update.</p> <p><img src="https://i.stack.imgur.com/THPOw.jpg" alt="no updates"></p> <p>I have also install some things in the SDK manager, see screenshot below.</p> <p><a href="https://i.stack.imgur.com/eXuAd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eXuAd.jpg" alt="SDK manager"></a></p> <p>Can anyone help me to fix this problem? <br/> Thanks.</p>
30,731,758
2
1
null
2015-06-07 09:19:21.537 UTC
2
2016-11-15 08:28:54.76 UTC
2016-11-15 08:28:54.76 UTC
null
3,913,732
null
4,551,041
null
1
13
android-studio|rendering
38,112
<p>I had the same problem, current update, but rendering failed because I need to update.</p> <p>Try changing the update version you are on. The default is Stable, but there are 3 more options, Canary being the newest and potentially least stable. I chose to check for updates from the Dev Channel, which is a little more stable than Canary build. It fixed the problem and seems to work fine.</p> <p>To change the version, Check for Updates, then click the Updates link on the popup that says you already have the latest version.</p> <p>Good luck in the class!</p>
20,541,905
Convert matrix to 3-column table ('reverse pivot', 'unpivot', 'flatten', 'normalize')
<p>I need to convert the Excel matrix <code>FIRST</code> in the table <code>LATER</code>: </p> <p><strong>FIRST</strong>:</p> <pre><code> P1 P2 P3 P4 F1 X F2 X X F3 X X F4 X X </code></pre> <p><strong>LATER</strong>:</p> <pre><code>F P VALUE F1 P1 X F1 P2 F1 P3 F1 P4 F2 P1 X F2 P2 X F2 P3 F2 P4 F3 P1 F3 P2 X F3 P3 F3 P4 X F4 P1 F4 P2 X F4 P3 X F4 P4 </code></pre>
20,543,651
5
1
null
2013-12-12 11:11:20.75 UTC
35
2021-06-25 16:25:15.293 UTC
2015-09-29 01:53:01.903 UTC
null
1,505,120
null
3,095,042
null
1
39
excel|matrix|pivot-table|unpivot|powerquery
88,391
<h2>To “reverse pivot”, “unpivot” or “flatten”:</h2> <ol> <li><p>For Excel 2003: Activate any cell in your summary table and choose Data - PivotTable and PivotChart Report:</p> <p><img src="https://i.stack.imgur.com/JEIMk.gif" alt="SO20541905 first example"></p></li> </ol> <p>For later versions access the Wizard with <kbd>Alt</kbd>+<kbd>D</kbd>, <kbd>P</kbd>. </p> <p>For Excel for Mac 2011, it's <kbd>⌘</kbd>+<kbd>Alt</kbd>+<kbd>P</kbd> (<a href="https://support.office.com/en-us/article/Consolidate-multiple-data-sources-in-a-PivotTable-8f476919-40b3-4133-9870-26f4d9f21ad6">See here</a>).</p> <ol start="2"> <li><p>Select <em>Multiple consolidation ranges</em> and click <kbd>Next</kbd>.</p> <p><img src="https://i.stack.imgur.com/cDWJB.gif" alt="SO20541905 second example"> </p></li> <li><p>In “Step 2a of 3”, choose <em>I will create the page fields</em> and click <kbd>Next</kbd>. </p> <p><img src="https://i.stack.imgur.com/GNIfN.gif" alt="SO20541905 third example"></p></li> <li><p>In “Step 2b of 3” specify your summary table range in the <strong>Range</strong> field (A1:E5 for the sample data) and click <kbd>Add</kbd>, then <kbd>Next</kbd>.</p> <p><img src="https://i.stack.imgur.com/AXvW2.gif" alt="SO20541905 fourth example"></p></li> <li><p>In “Step 3 of 3”, select a location for the pivot table (the existing sheet should serve, as the PT is only required temporarily): </p> <p><img src="https://i.stack.imgur.com/ZE66T.gif" alt="SO20541905 fifth example"></p></li> <li><p>Click <kbd>Finish</kbd> to create the pivot table: </p> <p><img src="https://i.stack.imgur.com/1GQj1.gif" alt="SO20541905 sixth example"></p></li> <li><p>Drill down (ie double-click) on the intersect of the Grand Totals (here Cell V7 or <code>7</code>): </p> <p><img src="https://i.stack.imgur.com/wofg2.gif" alt="SO20541905 seventh example"></p></li> <li><p>The PT may now be deleted.</p></li> <li>The resulting Table may be converted to a conventional array of cells by selecting <strong>Table</strong> in the Quick Menu (right-click in the Table) and <strong>Convert to Range</strong>.</li> </ol> <hr> <p>There is a video on the same subject at <a href="http://www.launchexcel.com/pivot-table-flatten-crosstab/">Launch Excel</a> which I consider excellent quality.</p>
20,369,608
ng-if (Angularjs) is not working
<p>I am rendering json data to html page :</p> <pre><code>&lt;div ng-if="'done'={{task_detail.status}}"&gt; &lt;b&gt;Status :&lt;/b&gt; &lt;p class="label label-success"&gt;{{task_detail.status}}&lt;/p&gt; &lt;br&gt; &lt;br&gt; &lt;div class="progress progress-striped"&gt; &lt;div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width:{{task_detail.percentage_finished}}%"&gt; &lt;span class="sr-only"&gt;{{task_detail.percentage_finished}}% Complete&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Here is my rendered json data :</p> <pre><code>{ "id": 1, "title": "Launch an EC Instance", "desc": "Needed an EC instance to deploy the ccr code", "status": "done", "percentage_finished": 100 } </code></pre> <p>Issue : HTML view is not visible as control is not moving inside <code>ng-if</code> . Is syntax correct?</p>
20,369,659
5
2
null
2013-12-04 07:33:45.903 UTC
4
2017-06-30 11:39:22.217 UTC
2016-12-16 09:16:50.38 UTC
null
2,777,965
null
1,106,366
null
1
25
angularjs
75,548
<p><code>ngIf</code> accepts an expression(<em>JavaScript-like code snippet</em>). This means anything written in between the <code>" "</code> is already inside Angular's context and you dont need to use <code>{{ }}</code>:</p> <pre><code>&lt;div ng-if="task_detail.status == 'done'"&gt; </code></pre>
51,916,221
javax.xml.bind.JAXBException Implementation of JAXB-API has not been found on module path or classpath
<p>I'm trying to run my Spring Boot application on Java 9, and I've faced with JAXB problem, which described in the guides, but didn't work for me. I've added dependency on JAXB api, and application started working. If you get the following exception, as a result of missing JAXB missing implementation using Java version >=9:</p> <pre><code>javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath. at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:177) ~[jaxb-api-2.3.0.jar:2.3.0] at javax.xml.bind.ContextFinder.find(ContextFinder.java:364) ~[jaxb-api-2.3.0.jar:2.3.0] at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:508) ~[jaxb-api-2.3.0.jar:2.3.0] at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:465) ~[jaxb-api-2.3.0.jar:2.3.0] at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:366) ~[jaxb-api-2.3.0.jar:2.3.0] at com.sun.jersey.server.impl.wadl.WadlApplicationContextImpl.&lt;init&gt;(WadlApplicationContextImpl.java:107) ~[jersey-server-1.19.1.jar:1.19.1] at com.sun.jersey.server.impl.wadl.WadlFactory.init(WadlFactory.java:100) [jersey-server-1.19.1.jar:1.19.1] at com.sun.jersey.server.impl.application.RootResourceUriRules.initWadl(RootResourceUriRules.java:169) [jersey-server-1.19.1.jar:1.19.1] at com.sun.jersey.server.impl.application.RootResourceUriRules.&lt;init&gt;(RootResourceUriRules.java:106) [jersey-server-1.19.1.jar:1.19.1] at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1359) [jersey-server-1.19.1.jar:1.19.1] at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:180) [jersey-server-1.19.1.jar:1.19.1] at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:799) [jersey-server-1.19.1.jar:1.19.1] at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:795) [jersey-server-1.19.1.jar:1.19.1] at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193) [jersey-core-1.19.1.jar:1.19.1] at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795) [jersey-server-1.19.1.jar:1.19.1] at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790) [jersey-server-1.19.1.jar:1.19.1] at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509) [jersey-servlet-1.19.1.jar:1.19.1] at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339) [jersey-servlet-1.19.1.jar:1.19.1] at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605) [jersey-servlet-1.19.1.jar:1.19.1] at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207) [jersey-servlet-1.19.1.jar:1.19.1] at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394) [jersey-servlet-1.19.1.jar:1.19.1] at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:744) [jersey-servlet-1.19.1.jar:1.19.1] at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:270) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.ApplicationFilterConfig.&lt;init&gt;(ApplicationFilterConfig.java:106) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4491) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5135) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1427) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1417) [tomcat-embed-core-9.0.10.jar:9.0.10] at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) [na:na] at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) [tomcat-embed-core-9.0.10.jar:9.0.10] at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140) [na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1427) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1417) [tomcat-embed-core-9.0.10.jar:9.0.10] at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) [na:na] at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) [tomcat-embed-core-9.0.10.jar:9.0.10] at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140) [na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.apache.catalina.startup.Tomcat.start(Tomcat.java:371) [tomcat-embed-core-9.0.10.jar:9.0.10] at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:107) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.&lt;init&gt;(TomcatWebServer.java:86) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:413) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:174) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:179) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:152) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) [spring-context-5.1.0.RC1.jar:5.1.0.RC1] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:769) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:405) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.boot.SpringApplication.run(SpringApplication.java:334) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1252) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1240) [spring-boot-2.1.0.M1.jar:2.1.0.M1] at io.eureka.server.EurekaServerApp.main(EurekaServerApp.java:21) [classes/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.0.M1.jar:2.1.0.M1] Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory at org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedWebappClassLoader.loadClass(TomcatEmbeddedWebappClassLoader.java:70) ~[spring-boot-2.1.0.M1.jar:2.1.0.M1] at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1138) ~[tomcat-embed-core-9.0.10.jar:9.0.10] at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122) ~[jaxb-api-2.3.0.jar:2.3.0] at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155) ~[jaxb-api-2.3.0.jar:2.3.0] at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:174) ~[jaxb-api-2.3.0.jar:2.3.0] ... 66 common frames omitted </code></pre>
51,916,222
6
2
null
2018-08-19 09:21:10.173 UTC
17
2022-08-31 09:46:31.5 UTC
null
null
null
null
2,161,118
null
1
112
xml|exception|jaxb|bind|java-9
164,448
<p>Add these dependencies into your pom/gradle:</p> <p><strong>Gradle</strong>:</p> <pre><code>compile('javax.xml.bind:jaxb-api:2.3.0') compile('javax.activation:activation:1.1') compile('org.glassfish.jaxb:jaxb-runtime:2.3.0') </code></pre> <p><strong>Pom</strong>:</p> <pre><code>&lt;!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt; &lt;version&gt;2.3.0-b170201.1204&lt;/version&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/javax.activation/activation --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.activation&lt;/groupId&gt; &lt;artifactId&gt;activation&lt;/artifactId&gt; &lt;version&gt;1.1&lt;/version&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime --&gt; &lt;dependency&gt; &lt;groupId&gt;org.glassfish.jaxb&lt;/groupId&gt; &lt;artifactId&gt;jaxb-runtime&lt;/artifactId&gt; &lt;version&gt;2.3.0-b170127.1453&lt;/version&gt; &lt;/dependency&gt; </code></pre>
13,836,848
Show/Hide div, with plain JS
<p>My CSS:</p> <pre><code>#a_x200{ visibility: hidden; width: 200px; height: 200px; background-color: black; } </code></pre> <p>My JS:</p> <pre><code>&lt;script type="text/javascript"&gt; function show(id) { document.getElementById(id).style.display = 'block'; } &lt;/script&gt; </code></pre> <p>My Html </p> <pre><code>&lt;div id="a_x200"&gt;asd&lt;/div&gt; &lt;innput type="button" class="button_p_1" onclick="show('a_x200');"&gt;&lt;/input&gt; </code></pre> <p>Not working I think I missed something!</p>
13,836,933
6
4
null
2012-12-12 09:40:49.437 UTC
null
2019-12-22 21:29:21.19 UTC
2019-12-22 21:29:21.19 UTC
null
1,102,574
null
1,102,574
null
1
4
javascript|jquery|html|css
74,979
<p>You're using <code>visibility: hidden</code> to hide it, then attempting to use the <code>display</code> CSS property to make it visible. They're two completely separate properties, changing one won't magically change the other.</p> <p>If you want to make it visible again, change the value of the <code>visibility</code> property to <code>visible</code>:</p> <pre><code>document.getElementById('a_x200').style.visibility = 'visible'; </code></pre>
54,867,295
SpringBoot no main manifest attribute (maven)
<p>When running my jar file: <code>java -jar target/places-1.0-SNAPSHOT.jar</code></p> <p>I'm getting the next error :</p> <blockquote> <p>no main manifest attribute, in target/places-1.0-SNAPSHOT.jar</p> </blockquote> <p>The <code>pom.xml</code> contains the <code>spring-boot-maven-plugin</code>:</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;mainClass&gt;com.places.Main&lt;/mainClass&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre> <p>I also tried to create a <code>MANIFEST.MF</code> file and specifying the class, but it didnt help.</p> <p>In addition, I also tried:</p> <pre><code>&lt;properties&gt; &lt;!-- The main class to start by executing &quot;java -jar&quot; --&gt; &lt;start-class&gt;com.places.Main&lt;/start-class&gt; &lt;/properties&gt; </code></pre> <p>Main class:</p> <pre><code>@SpringBootApplication public class Main { public static void main(String[] args) throws InterruptedException { SpringApplication.run(Main.class,args); } } </code></pre> <p>Any idea what else can I try?</p>
54,867,850
7
5
null
2019-02-25 13:26:49.343 UTC
17
2022-03-15 16:46:21.897 UTC
2022-03-14 21:20:33.863 UTC
null
5,626,568
null
4,340,793
null
1
69
java|maven|spring-boot|manifest|spring-boot-maven-plugin
91,253
<p>Try adding <code>repackage</code> goal to execution goals.</p> <p>Otherwise you would need to call the plugin explicitly as <code>mvn package spring-boot:repackage</code>.</p> <p>With the goal added, you have to call only <code>mvn package</code>.</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;mainClass&gt;com.places.Main&lt;/mainClass&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;repackage&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre>
6,405,173
Static files won't load when out of debug in Django
<p>I'm creating a Django project. I just tried taking the project out of debug, <code>DEBUG = False</code> and for some reason all my static files do not show up. They give an error code of 500. How do i fix this?</p> <p>some of settings.py:</p> <pre><code>DEBUG = True TEMPLATE_DEBUG = DEBUG ... TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) </code></pre>
6,406,429
2
7
null
2011-06-19 21:17:51.187 UTC
10
2013-08-18 07:16:31.093 UTC
2011-06-19 22:34:33.22 UTC
null
576,831
null
576,831
null
1
18
django|debugging|static-files|django-static
16,670
<p>Static files app is not serving static media automatically in <code>DEBUG=False</code> mode. From <code>django.contrib.staticfiles.urls</code>: </p> <pre><code># Only append if urlpatterns are empty if settings.DEBUG and not urlpatterns: urlpatterns += staticfiles_urlpatterns() </code></pre> <p>You can serve it by appending to your <code>urlpatterns</code> manually or use a server to serve static files (like it is supposed to when running Django projects in non-DEBUG mode).</p> <p>Though one thing I am wondering is why you get a 500 status code response instead of 404. What is the exception in this case?</p> <p><strong>EDIT</strong></p> <p>So if you still want to serve static files via the staticfiles app add the following to your root url conf (<code>urls.py</code>):</p> <pre><code>if settings.DEBUG is False: #if DEBUG is True it will be served automatically urlpatterns += patterns('', url(r'^static/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), ) </code></pre> <p>Some things you need to keep in mind though:</p> <ul> <li>don't use this on a production environment (its slower since static files rendering goes through Django instead served by your web server directly)</li> <li>most likely you have to use management commands to collect static files into your <code>STATIC_ROOT</code> (<code>manage.py collectstatic</code>). See the <a href="https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/" rel="noreferrer">staticfiles app docs</a> for more information. This is simply necessary since you run on non-Debug mode.</li> <li>don't forget <code>from django.conf import settings</code> in your <code>urls.py</code> :)</li> </ul>
57,487,071
How do I change the shape of a button in MUI using theme?
<p>So the documentation on <code>Button</code> component has various sections and also a Codesandbox linked at <a href="https://codesandbox.io/s/npie4" rel="nofollow noreferrer">https://codesandbox.io/s/npie4</a></p> <p>However, there is nowhere mentioned how to change the shape of a button if needed.</p> <p><a href="https://i.stack.imgur.com/Tyc6l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tyc6l.png" alt="enter image description here" /></a></p> <p>I am using Google Material Sketch <a href="https://material.io/resources/theme-editor/" rel="nofollow noreferrer">file</a> and I want the buttons to be rounded</p> <p><a href="https://i.stack.imgur.com/FigpG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FigpG.png" alt="enter image description here" /></a></p> <p>How can I do that using the <code>theme</code> object so that in my entire app the <code>Button</code> component are always rounded?</p>
57,489,080
5
1
null
2019-08-14 01:25:06.92 UTC
4
2021-11-10 06:07:37.463 UTC
2021-11-10 06:07:37.463 UTC
null
9,449,426
null
379,235
null
1
13
javascript|reactjs|material-design|material-ui
41,403
<p>There is a global border radius shape value in the theme. You can change it like this:</p> <pre><code>const theme = createMuiTheme({ shape: { borderRadius: 8, }, }) </code></pre> <p>Alternatively, if you are only interested in the button style:</p> <pre><code>const theme = createMuiTheme({ overrides: { MuiButton: { root: { borderRadius: 8, }, }, }, }) </code></pre> <p>Or, you could target the global class name of the button: </p> <pre><code>.MuiButton-root { border-radius: 8px; } </code></pre>
7,403,553
How do I get the counter of a google plus +1 button?
<p>I have added a google +1 button to a website, but I want to get it's counter so i can do some math over it. is it possible to enter the iframe created by the standard method of creating the +1 button or do I need to make some adjustment?</p> <pre><code>&lt;script type="text/javascript" src="https://apis.google.com/js/plusone.js"&gt;&lt;/script&gt; &lt;g:plusone&gt;&lt;/g:plusone&gt; </code></pre> <p>I've tried this link:<a href="http://www.tomanthony.co.uk/blog/google_plus_one_button_seo_count_api/" rel="noreferrer">1</a> , but this is not very accurate</p>
7,409,062
3
0
null
2011-09-13 14:29:58.49 UTC
12
2015-11-18 16:00:58.773 UTC
2011-09-13 14:36:08.737 UTC
null
430,826
null
430,826
null
1
25
javascript|html|google-plus-one
15,992
<p>If you can access curl/file_get_contents/readfile/wget or some way to fetch an external URL, this is quite simple.</p> <p>Load the following URL: <code>https://plusone.google.com/_/+1/fastbutton?url=URLENCODED_URI</code> (<strong>UPDATED URL, see note below *</strong>)</p> <p>URLENCODED_URI is the site you wish to know the number of +1's for, e.g. <a href="http://www.google.com" rel="noreferrer">http://www.google.com</a> (http%3A%2F%2Fwww.google.com)</p> <p>For example, fetch the URI <code>https://plusone.google.com/_/+1/fastbutton?url=http://www.google.com/</code> (<strong>UPDATED URI</strong>) and locate the first occurance of <code>window.__SSR = {'c': 32414.0 ,'si'</code>. Preferably use regexp for this, but I'll leave the implementation to you and your chosen programming language (server side or client side).</p> <p>The float number following <code>'c'</code> is the number of +1's the site have. For google.com this is 32,414. Don't worry about the float, you can safely convert it to an integer.</p> <p><strong>* UPDATE:</strong> The URL has been updated as the old URL started to 404. Remember, this is expected as this is an unofficial method. There exist no official method (yet). </p>
48,479,666
Using method function in v-if
<p>I’m trying to use a function in a v-if directive like that in a vue template</p> <pre><code> &lt;template&gt; &lt;ul class="list-group"&gt; &lt;li class="list-group-item list-group-item-info"&gt; &lt;div class="row"&gt; &lt;div v-for="col in colss" class="" :class="bootstrapClass"&gt;{{col | capitalize}}&lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;li v-for="item in datas[collectionsindatas['reference']]" class="list-group-item"&gt; &lt;div class="row"&gt; &lt;div v-for="property in columns.slice(0,(columns.length))" class="" :class="bootstrapClass"&gt;{{ item[property] }}&lt;/div&gt; &lt;div v-if="compareCollections(item[comparecol],datas[collectionsindatas['compare'][comparecol]])" class="" :class="bootstrapClass"&gt; OK &lt;/div&gt; &lt;div v-else class="" :class="bootstrapClass"&gt;!!NOK!!&lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/template&gt; </code></pre> <p>and my methods are like that :</p> <pre><code>methods:{ compareCollections:function(reference,compare){ if(compare!='undefined' &amp;&amp; compare!=''){ if(compare===reference){ return true; } return false; } return false; }, } </code></pre> <p>It fails with this message : [Vue warn]: Property or method is not defined on the instance but referenced during render</p> <p>It fells myself better to use a method instead writing many things ugly in the v-if directive like</p> <pre><code>v-if="datas[collectionsindatas['compare'][comparecol]]!='undefined'&amp;&amp;(item[comparecol]===datas[collectionsindatas['compare'][comparecol]])" </code></pre> <p>what is the right way to do this ?</p> <p>Thanks for your help</p>
48,485,290
4
9
null
2018-01-27 19:24:01.673 UTC
null
2022-07-16 02:12:32.98 UTC
2018-01-27 20:52:44.71 UTC
null
5,794,757
null
5,794,757
null
1
8
vue.js|vuejs2
43,292
<p>OK, it could be improved but here is my way to resolve this :</p> <p>My list component receive by props a reference list of avalaible permissions and receive a comparing list to the role's permission so when the comparing returns true it will display a toggle switch wich appear set on ON position and OFF if it's false. So here is the app.js : </p> <pre><code>Vue.component('sort-table', sortTable); Vue.component('list-items', listItems); var csrf_token = $('meta[name="csrf-token"]').attr('content'); var newTable = new Vue({ el: '#appTableRoles', data: { columns: ['id', 'name', 'description', 'action'], cols: ['Id', 'Rôle', 'Description', 'Actions'], // ajax url url: 'Role/ajaxQuery', }, components: {sortTable}, }); var listTable = new Vue({ el: '#listmodal', data: { // collection des propriétés columns: ['id', 'name', 'description'], // collection d'affichage colss: ['Id', 'Nom', 'Description', 'Attribution'], urlajax:'', datas:[], // collectionsInDatas:{'reference':'allPermissions','compare':'rolePermissions'}, // critère de comparaison entre la collection de référence et la collection appartenant à l'item comparecol:'name', //objet contenant tous les résultats de comparaisons lastcol:{equal:[],display:[]}, }, methods: { showModal () { $('#permissionsModal').modal('show'); }, hideModal () { $('#permissionsModal').modal('hide'); }, getDatas(){ this.lastcol.equal =[]; this.lastcol.display =[]; MonThis = this; $.ajax({ url: this.urlajax, cache: false, dataType: 'json', success: function (data, textStatus, jqXHR) { if (jqXHR.status === 200) { //console.log(data); MonThis.datas = data; var index=0; //console.log(MonThis.datas[MonThis.collectionsInDatas['reference']]); for(item in MonThis.datas[MonThis.collectionsInDatas['reference']]){ //var index = MonThis.datas[MonThis.collectionsInDatas['reference']].indexOf(item); //console.log('index : '+index); console.log('reference name : '+MonThis.datas[MonThis.collectionsInDatas['reference']][index]['name']); //console.log('compare : '+MonThis.datas[MonThis.collectionsInDatas['compare']][index]); var j = 0; for(compare in MonThis.datas[MonThis.collectionsInDatas['compare']]){ //console.log('compare name : '+MonThis.datas[MonThis.collectionsInDatas['compare']][j]['name']); if(MonThis.datas[MonThis.collectionsInDatas['compare']][j]['name']===MonThis.datas[MonThis.collectionsInDatas['reference']][index]['name']){ MonThis.lastcol.equal.push(true); MonThis.lastcol.display.push('OK'); break; }else{ MonThis.lastcol.equal.push(false); MonThis.lastcol.display.push('Not OK'); } j++; } index++; } } } }); }, }, components:{listItems}, }); $(document).ready(function () { $(document).on('click', '.modal-permissions', function (e) { //console.log($(e.target).attr('href')); listTable.showModal(); listTable.$data.urlajax = $(e.target).attr('href'); listTable.getDatas(); }); }); </code></pre> <p>Here is the component call in the blade template : </p> <pre><code>&lt;list-items :colss="colss":columns="columns" :urlajax="urlajax" :datas="datas" :lastcol="lastcol" :collectiondatas="collectionsInDatas"&gt; &lt;/list-items&gt; </code></pre> <p>and Here is the vue file code :</p> <pre><code> &lt;template&gt; &lt;ul class="list-group"&gt; &lt;li class="list-group-item list-group-item-info"&gt; &lt;div class="row"&gt; &lt;div v-for="col in colss" class="" :class="bootstrapClass"&gt;{{col | capitalize}}&lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;li v-for="(item,index ) in datas[collectiondatas['reference']]" class="list-group-item"&gt; &lt;div class="row"&gt; &lt;div v-for="property in columns.slice(0,(columns.length))" class="" :class="bootstrapClass"&gt;{{ item[property] }}&lt;/div&gt; &lt;div class="" :class="bootstrapClass"&gt;{{ lastcol.display[index] }}&lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/template&gt; &lt;script&gt; var csrf_token = $('meta[name="csrf-token"]').attr('content'); export default { name: 'listItems', data(){ return { } }, props: ['colss','columns','lastcol','urlajax','datas','collectiondatas'], methods: { }, computed: { bootstrapClass: function() { return 'col-sm-' + (12 / this.colss.length ); }, }, mounted: function () { }, filters: { capitalize: function (str) { return str.charAt(0).toUpperCase() + str.slice(1) } }, } &lt;/script&gt; </code></pre>
21,682,714
"with" keyword in Dart
<p>Could somebody please write some formal definition of keyword <strong>with</strong> in Dart?</p> <p>In official Dart examples I have only found: </p> <pre><code>class TaskElement extends LIElement with Polymer, Observable { </code></pre> <p>But I still can't understand what is it exactly doing.</p>
21,682,826
2
2
null
2014-02-10 16:32:28.74 UTC
6
2020-04-17 15:56:19.52 UTC
null
null
null
null
2,776,733
null
1
51
dart
18,048
<p>The <code>with</code> keyword indicates the use of a "mixin". See <a href="https://dart.dev/guides/language/language-tour#adding-features-to-a-class-mixins" rel="noreferrer">here</a>.</p> <p>A mixin refers to the ability to add the capabilities of another class or classes to your own class, without inheriting from those classes. The methods of those classes can now be called on your class, and the code within those classes will execute. Dart does not have multiple inheritance, but the use of mixins allows you to fold in other classes to achieve code reuse while avoiding the issues that multiple inheritance would cause.</p> <p>I note that you have answered some questions about Java -- in Java terms, you can think of a mixin as an interface that lets you not merely specify that a given class will contain a given method, but also provide the code for that method.</p>
21,638,876
How to alert ajax response
<p>I've read dozens of related posts, but I still can't get this to work.</p> <p>I want to alert the response in jquery I get from PHP.</p> <p>PHP:</p> <pre><code>$msg=array(); if(empty($whatever)){ $msg['cenas']="Não há contas"; }else{ $msg['cenas']="Há contas"; }; echo json_encode($msg); </code></pre> <p>JS:</p> <pre><code>$.ajax({ url: 'myscript.php', dataType: 'json', success: function(response){ alert(response.cenas); } }); </code></pre> <p>PHP is echoing </p> <blockquote> <p>{cenas: "Há contas}" But I can't get it to alert in JS.</p> </blockquote>
21,639,775
3
3
null
2014-02-07 22:22:32.127 UTC
0
2014-02-07 23:43:14.883 UTC
2014-02-07 22:39:25.76 UTC
user882670
null
user882670
null
null
1
6
javascript|php|jquery|ajax
38,845
<p>The php should echo back <code>{"cenas": "Há contas"}</code>, but what did you get in the alert? Did you get an undefined? If so, try to use <code>jQuery.parseJSON</code> before alert. e.g:</p> <pre><code>$.ajax({ url:"myscript.php", dataType: "json", success:function(data){ var obj = jQuery.parseJSON(data); alert(obj.cenas); } }); </code></pre>
2,244,915
How do I search within an array of hashes by hash values in ruby?
<p>I have an array of hashes, @fathers.</p> <pre><code>a_father = { "father" =&gt; "Bob", "age" =&gt; 40 } @fathers &lt;&lt; a_father a_father = { "father" =&gt; "David", "age" =&gt; 32 } @fathers &lt;&lt; a_father a_father = { "father" =&gt; "Batman", "age" =&gt; 50 } @fathers &lt;&lt; a_father </code></pre> <p>How can I search this array and return an array of hashes for which a block returns true?</p> <p>For example:</p> <pre><code>@fathers.some_method("age" &gt; 35) #=&gt; array containing the hashes of bob and batman </code></pre> <p>Thanks.</p>
2,244,930
4
1
null
2010-02-11 14:10:08.637 UTC
69
2020-08-12 11:23:22.653 UTC
null
null
null
null
104,361
null
1
263
ruby|search|hash|arrays
213,510
<p>You're looking for <a href="https://ruby-doc.org/core-2.7.0/Enumerable.html#method-i-select" rel="noreferrer">Enumerable#select</a> (also called <code>find_all</code>):</p> <pre><code>@fathers.select {|father| father["age"] &gt; 35 } # =&gt; [ { "age" =&gt; 40, "father" =&gt; "Bob" }, # { "age" =&gt; 50, "father" =&gt; "Batman" } ] </code></pre> <p>Per the documentation, it "returns an array containing all elements of [the enumerable, in this case <code>@fathers</code>] for which block is not false."</p>
1,490,190
Python Modules most worthwhile reading
<p>I have been programming Python for a while and I have a very good understanding of its features, but I would like to improve my coding style. I think reading the source code of the Python Modules would be a good idea. Can anyone recommend any ones in particular?</p> <p>Related Threads:</p> <ul> <li><a href="https://stackoverflow.com/questions/125019/beginner-looking-for-beautiful-and-instructional-python-code">Beginner looking for beautiful and instructional Python code</a>: This thread actually inspired this question</li> </ul>
1,490,216
4
1
null
2009-09-29 01:48:51.29 UTC
27
2009-09-29 01:59:29.123 UTC
2017-05-23 12:11:20.897 UTC
null
-1
null
165,495
null
1
9
python
2,844
<p><a href="http://svn.python.org/view/python/trunk/Lib/Queue.py?revision=70405&amp;view=markup" rel="nofollow noreferrer">Queue.py</a> shows you how to make a class thread-safe, and the proper use of the <a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="nofollow noreferrer">Template Method</a> design pattern.</p> <p><a href="http://svn.python.org/view/python/trunk/Lib/sched.py?revision=72932&amp;view=markup" rel="nofollow noreferrer">sched.py</a> is a great example of the <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">Dependency Injection</a> pattern.</p> <p><a href="http://svn.python.org/view/python/trunk/Lib/heapq.py?revision=70691&amp;view=markup" rel="nofollow noreferrer">heapq.py</a> is a really well-crafted implementation of the <a href="http://en.wikipedia.org/wiki/Heap_(data_structure)" rel="nofollow noreferrer">Heap</a> data structure.</p> <p>If I had to pick my three favorite modules in the Python standard library, this triplet would probably be my choice. (It doesn't hurt that they're all so <strong>very</strong> useful... but I'm picking in terms of quality of code, comments and design, first and foremost).</p>
1,437,323
Assigning a keyboard shortcut for a specific Eclipse build configuration
<p>In our Java project in Eclipse, we have several build configurations, as we have an engine that when run, builds installation jar for a specific projects according to the parameters it gets, so each build configuration run the same build with different parameters to build installation for a specific project.</p> <p>Currently, I have to go to the Run Configuration drop-down button in the toolbar to start the engine, and I need to select the build configuration from the list in order to run (or debug) the engine with the required parameters.</p> <p>I have configured Eclipse to run the last run execution if the button is run instead of selecting from the drop-down menu, but I would really like to have separate buttons in the toolbar for each build configuration (or for my favorite configurations), and even better, have a keyboard shortcut to run (or debug) a specific build configuration. Is that possible?</p>
8,176,077
4
1
null
2009-09-17 07:52:58.38 UTC
21
2019-09-04 08:54:14.353 UTC
2011-09-11 11:17:38.687 UTC
null
321,366
null
46,635
null
1
22
eclipse|keyboard-shortcuts
14,938
<p>I was able to put together specific steps based on splintor's thread and get this working (I also added a loop at the top that finds any existing launch with the same name and terminates it, effectively making this a "restart" macro):</p> <p>To assign keyboard shortcuts to specific Eclipse launch configurations, perform the following steps:</p> <ul> <li><p>Install <a href="https://sourceforge.net/projects/practicalmacro/" rel="nofollow">https://sourceforge.net/projects/practicalmacro/</a>, which you can inside Eclipse via Help->Software Updates: <a href="http://puremvcnotificationviewer.googlecode.com/svn/trunk/PracticallyMacroGoogleUpdateSite" rel="nofollow">http://puremvcnotificationviewer.googlecode.com/svn/trunk/PracticallyMacroGoogleUpdateSite</a></p></li> <li><p>Restart Eclipse and open Eclipse Preferences. You will have a new section called "Practically Macro Options", expand that section.</p></li> <li><p>Click on "Editor Macro Definitions"</p></li> <li><p>Click on "new..." </p></li> <li><p>In the list of available commands, scroll down to "Editor Macro script (Beanshell)", select it and then click "Add->" </p></li> <li><p>When the script editor pops up, add the following code to the existing code:</p> <pre class="lang-java prettyprint-override"><code>import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.ui.DebugUITools; try { // Terminate process if it already exists from a previous launch org.eclipse.debug.core.ILaunch[] allLaunches=DebugPlugin.getDefault().getLaunchManager().getLaunches(); for (ILaunch l : allLaunches) { if (l.getLaunchConfiguration().getName().equals("YOUR CONFIG NAME HERE")) { console.write("terminating launch: " ); console.writeln(l.getLaunchConfiguration().getName()); l.terminate(); break; } } org.eclipse.debug.core.ILaunchConfiguration[] allConfigurations=DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(); for (ILaunchConfiguration config : allConfigurations) { if (config.getName().equals("YOUR CONFIG NAME HERE")) { DebugUITools.launch(config, "debug"); break; } } } catch (CoreException e) { e.printStackTrace(); } finally{} </code></pre></li> <li><p>Note line 11 that checks the configuration name, replace with whatever you want</p></li> <li><p>Also note DebugUITools.launch command on line 15, you can pass either "run" or "debug"</p></li> <li><p>In the "Macro info" section at the bottom of this dialog, specify a macro name</p></li> <li><p>IMPORTANT!: If you want to be able to see this macro in the standard Eclipse key binding dialog, you need to assign an id. I started with 1...</p></li> <li><p>Click OK</p></li> <li><p>Expand the "General" section and click on "Keys"</p></li> <li><p>You can now search the possible key bindings for your new macro's name and assign it to any key you want.</p></li> <li><p>NOTE: After assigning a key I often had to close and restart Eclipse before the key binding was respected.</p></li> </ul>
1,838,163
Click and drag selection box in WPF
<p>Is it possible to implement mouse click and drag selection box in WPF. Should it be done through simply drawing a rectangle, calculating coordinates of its points and evaluating position of other objects inside this box? Or are there some other ways?</p> <p>Could you give a bit of sample code or a link? </p>
2,019,638
4
2
null
2009-12-03 06:55:25.077 UTC
24
2020-12-27 22:05:25.377 UTC
2011-08-31 17:49:50.657 UTC
null
305,637
null
199,722
null
1
24
c#|wpf|mouse|selection|drag
33,193
<p>Here is sample code for a simple technique that I have used in the past to draw a drag selection box.</p> <p>XAML:</p> <pre><code>&lt;Window x:Class=&quot;DragSelectionBox.Window1&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; Title=&quot;Window1&quot; Height=&quot;300&quot; Width=&quot;300&quot; &gt; &lt;Grid x:Name=&quot;theGrid&quot; MouseDown=&quot;Grid_MouseDown&quot; MouseUp=&quot;Grid_MouseUp&quot; MouseMove=&quot;Grid_MouseMove&quot; Background=&quot;Transparent&quot; &gt; &lt;Canvas&gt; &lt;!-- This canvas contains elements that are to be selected --&gt; &lt;/Canvas&gt; &lt;Canvas&gt; &lt;!-- This canvas is overlaid over the previous canvas and is used to place the rectangle that implements the drag selection box. --&gt; &lt;Rectangle x:Name=&quot;selectionBox&quot; Visibility=&quot;Collapsed&quot; Stroke=&quot;Black&quot; StrokeThickness=&quot;1&quot; /&gt; &lt;/Canvas&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>C#:</p> <pre><code>public partial class Window1 : Window { public Window1() { InitializeComponent(); } bool mouseDown = false; // Set to 'true' when mouse is held down. Point mouseDownPos; // The point where the mouse button was clicked down. private void Grid_MouseDown(object sender, MouseButtonEventArgs e) { // Capture and track the mouse. mouseDown = true; mouseDownPos = e.GetPosition(theGrid); theGrid.CaptureMouse(); // Initial placement of the drag selection box. Canvas.SetLeft(selectionBox, mouseDownPos.X); Canvas.SetTop(selectionBox, mouseDownPos.Y); selectionBox.Width = 0; selectionBox.Height = 0; // Make the drag selection box visible. selectionBox.Visibility = Visibility.Visible; } private void Grid_MouseUp(object sender, MouseButtonEventArgs e) { // Release the mouse capture and stop tracking it. mouseDown = false; theGrid.ReleaseMouseCapture(); // Hide the drag selection box. selectionBox.Visibility = Visibility.Collapsed; Point mouseUpPos = e.GetPosition(theGrid); // TODO: // // The mouse has been released, check to see if any of the items // in the other canvas are contained within mouseDownPos and // mouseUpPos, for any that are, select them! // } private void Grid_MouseMove(object sender, MouseEventArgs e) { if (mouseDown) { // When the mouse is held down, reposition the drag selection box. Point mousePos = e.GetPosition(theGrid); if (mouseDownPos.X &lt; mousePos.X) { Canvas.SetLeft(selectionBox, mouseDownPos.X); selectionBox.Width = mousePos.X - mouseDownPos.X; } else { Canvas.SetLeft(selectionBox, mousePos.X); selectionBox.Width = mouseDownPos.X - mousePos.X; } if (mouseDownPos.Y &lt; mousePos.Y) { Canvas.SetTop(selectionBox, mouseDownPos.Y); selectionBox.Height = mousePos.Y - mouseDownPos.Y; } else { Canvas.SetTop(selectionBox, mousePos.Y); selectionBox.Height = mouseDownPos.Y - mousePos.Y; } } } } </code></pre> <p>I wrote an article about this:</p> <p><a href="https://www.codeproject.com/Articles/148503/Simple-Drag-Selection-in-WPF" rel="nofollow noreferrer">https://www.codeproject.com/Articles/148503/Simple-Drag-Selection-in-WPF</a></p>
1,864,394
VIM and NERD Tree - closing a buffer properly
<p>Does anyone know how to close a buffer in VIM when using NERDTree without messing up all your windows? NERD Tree normally breaks up your display into two vertical windows (the browser on your left, and then your main window on the right). If you close a buffer, then you are reduced to one giant file browsing window. If you select another file, then it opens up a second window but separating it horizontally. Any ideas?</p>
1,864,427
4
0
null
2009-12-08 03:33:47.867 UTC
9
2022-01-09 04:28:23.34 UTC
null
null
null
null
111,674
null
1
34
vim|nerdtree
9,572
<p>I don't use NERD Tree, but if I understand correctly, you wish to close a buffer without closing a window. If my reasoning is correct, try this script.</p> <pre><code>" Delete buffer while keeping window layout (don't close buffer's windows). " Version 2008-11-18 from http://vim.wikia.com/wiki/VimTip165 if v:version &lt; 700 || exists('loaded_bclose') || &amp;cp finish endif let loaded_bclose = 1 if !exists('bclose_multiple') let bclose_multiple = 1 endif " Display an error message. function! s:Warn(msg) echohl ErrorMsg echomsg a:msg echohl NONE endfunction " Command ':Bclose' executes ':bd' to delete buffer in current window. " The window will show the alternate buffer (Ctrl-^) if it exists, " or the previous buffer (:bp), or a blank buffer if no previous. " Command ':Bclose!' is the same, but executes ':bd!' (discard changes). " An optional argument can specify which buffer to close (name or number). function! s:Bclose(bang, buffer) if empty(a:buffer) let btarget = bufnr('%') elseif a:buffer =~ '^\d\+$' let btarget = bufnr(str2nr(a:buffer)) else let btarget = bufnr(a:buffer) endif if btarget &lt; 0 call s:Warn('No matching buffer for '.a:buffer) return endif if empty(a:bang) &amp;&amp; getbufvar(btarget, '&amp;modified') call s:Warn('No write since last change for buffer '.btarget.' (use :Bclose!)') return endif " Numbers of windows that view target buffer which we will delete. let wnums = filter(range(1, winnr('$')), 'winbufnr(v:val) == btarget') if !g:bclose_multiple &amp;&amp; len(wnums) &gt; 1 call s:Warn('Buffer is in multiple windows (use ":let bclose_multiple=1")') return endif let wcurrent = winnr() for w in wnums execute w.'wincmd w' let prevbuf = bufnr('#') if prevbuf &gt; 0 &amp;&amp; buflisted(prevbuf) &amp;&amp; prevbuf != w buffer # else bprevious endif if btarget == bufnr('%') " Numbers of listed buffers which are not the target to be deleted. let blisted = filter(range(1, bufnr('$')), 'buflisted(v:val) &amp;&amp; v:val != btarget') " Listed, not target, and not displayed. let bhidden = filter(copy(blisted), 'bufwinnr(v:val) &lt; 0') " Take the first buffer, if any (could be more intelligent). let bjump = (bhidden + blisted + [-1])[0] if bjump &gt; 0 execute 'buffer '.bjump else execute 'enew'.a:bang endif endif endfor execute 'bdelete'.a:bang.' '.btarget execute wcurrent.'wincmd w' endfunction command! -bang -complete=buffer -nargs=? Bclose call &lt;SID&gt;Bclose('&lt;bang&gt;', '&lt;args&gt;') nnoremap &lt;silent&gt; &lt;Leader&gt;bd :Bclose&lt;CR&gt; nnoremap &lt;silent&gt; &lt;Leader&gt;bD :Bclose!&lt;CR&gt; </code></pre>
2,172,647
Template Metaprogramming - Difference Between Using Enum Hack and Static Const
<p>I'm wondering what the difference is between using a static const and an enum hack when using template metaprogramming techniques.</p> <p>EX: (Fibonacci via TMP)</p> <pre><code>template&lt; int n &gt; struct TMPFib { static const int val = TMPFib&lt; n-1 &gt;::val + TMPFib&lt; n-2 &gt;::val; }; template&lt;&gt; struct TMPFib&lt; 1 &gt; { static const int val = 1; }; template&lt;&gt; struct TMPFib&lt; 0 &gt; { static const int val = 0; }; </code></pre> <p>vs.</p> <pre><code>template&lt; int n &gt; struct TMPFib { enum { val = TMPFib&lt; n-1 &gt;::val + TMPFib&lt; n-2 &gt;::val }; }; template&lt;&gt; struct TMPFib&lt; 1 &gt; { enum { val = 1 }; }; template&lt;&gt; struct TMPFib&lt; 0 &gt; { enum { val = 0 }; }; </code></pre> <p>Why use one over the other? I've read that the enum hack was used before static const was supported inside classes, but why use it now?</p>
2,172,766
4
2
null
2010-01-31 17:47:53.977 UTC
19
2020-06-04 09:06:34.973 UTC
2010-01-31 18:26:03.363 UTC
null
168,225
null
257,581
null
1
59
c++|templates|metaprogramming
7,063
<p>Enums aren't lvals, static member values are and if passed by reference the template will be instanciated:</p> <pre><code>void f(const int&amp;); f(TMPFib&lt;1&gt;::value); </code></pre> <p>If you want to do pure compile time calculations etc. this is an undesired side-effect.</p> <p>The main historic difference is that enums also work for compilers where in-class-initialization of member values is not supported, this should be fixed in most compilers now.<br> There may also be differences in compilation speed between enum and static consts.</p> <p>There are some details in the <a href="http://www.boost.org/development/int_const_guidelines.html" rel="noreferrer">boost coding guidelines</a> and an <a href="http://lists.boost.org/Archives/boost/2003/01/41847.php" rel="noreferrer">older thread</a> in the boost archives regarding the subject.</p>
52,627,194
Search by pattern on Cloud Firestore collection
<p>I'm trying to perform a filter by pattern over a Firestore collection. For exemple, in my Firestore database I have a brand called <code>adidas</code>. The user would have an search input, where typing "adi", "adid", "adida" or "adidas" returns the <code>adidas</code> document. I pointed out several solutions to do this :</p> <p><br/> 1. Get all documents and perform a front-end filter</p> <pre class="lang-js prettyprint-override"><code>var brands = db.collection("brands"); filteredBrands = brands.filter((br) =&gt; br.name.includes("pattern")); </code></pre> <p>This solution is obviously not an option due to the Firestore pricing. Moreover it could be quite long to perform the request if the number of documents is high.</p> <p><br/> 2. Use of <a href="https://www.elastic.co/" rel="noreferrer">Elasticsearch</a> or <a href="https://firebase.google.com/docs/firestore/solutions/search" rel="noreferrer">Algolia</a></p> <p>This could be interesting. However I think this is a bit overkill to add these solutions' support for only a pattern search, and also this can quickly become expensive.</p> <p><br/> 3. Custom <code>searchName</code> field at object creation</p> <p>So I had this solution : at document creation, create a field with an array of possible search patterns:</p> <pre><code>{ ... "name":"adidas", "searchNames":[ "adi", "adida", "adidas" ], ... } </code></pre> <p>so that the document could be accessed with :</p> <pre><code>filteredBrands = db.collection("brands").where("searchNames", "array-contains", "pattern"); </code></pre> <p>So I had several questions:</p> <ul> <li>What do you think about the pertinence and the efficiency of this 3rd solution? How far do you think this could be better than using a third party solution as Elasticsearch or Algolia?</li> <li>Do you have any other idea for performing pattern filter over a firestore collection?</li> </ul>
52,627,798
1
3
null
2018-10-03 12:36:23.96 UTC
12
2022-07-06 09:52:58.057 UTC
2020-04-11 02:59:38.293 UTC
null
190,309
null
10,122,791
null
1
22
firebase|google-cloud-firestore|full-text-search
7,825
<p>IMHO, the first solution is definitely <strong>not</strong> an option. Downloading an entire collection to search for fields client-side isn't practical at all and is also very costly.</p> <p>The second option is the best option considering the fact that will help you enable full-text search in your entire Cloud Firestore database. It's up to you to decide if it is worth using it or not.</p> <blockquote> <p>What do you think about the pertinence and the efficiency of this 3rd solution?</p> </blockquote> <p>Regarding the third solution, it might work but it implies that you create an array of possible search patterns even if the brand name is very long. As I see in your schema, you are adding the possible search patterns starting from the 3rd letter, which means that if someone is searching for <code>ad</code>, no result will be found. The downside of this solution is the fact that if you have a brand named <code>Asics Tiger</code> and the user is searching for <code>Tig</code> or <code>Tige</code>, you'll end up having again no results.</p> <blockquote> <p>Do you have any other ideas for performing pattern filters over a Firestore collection?</p> </blockquote> <p>If you are interested to get results only from a single word and using as a pattern the staring letters of the brand, I recommend you a better solution which is using a query that looks like this:</p> <pre><code>var brands = db.collection(&quot;brands&quot;); brands.orderBy(&quot;name&quot;).startAt(searchName).endAt(searchName + &quot;\uf8ff&quot;) </code></pre> <p>In this case, a search like <code>a</code> or <code>ad</code> will work perfectly fine. Besides that, there will be no need to create any other arrays. So there will be less document writing.</p> <p>I have also written an article called:</p> <ul> <li><a href="https://medium.com/firebase-tips-tricks/how-to-filter-firestore-data-cheaper-705f5efec444" rel="nofollow noreferrer">How to filter Firestore data cheaper?</a></li> </ul> <p>That might also help.</p>
26,312,301
Is it possible to make CursorAdapter be set in recycleview, just like ListView?
<p>I didn't google out a solution till now to replace listview in my project, because I need to use the cursor linked with the sqlite.</p> <p>Old way as followed: <code>listview.setAdapter(cursorAdapter)</code> in this way, I can get the cursor to deal with data in database</p> <p>but now, <code>recycleview.setAdapter(recycleview.adapter)</code> it doesn't recognize the adapter extending BaseAdapter</p> <p>so anyone can give me a hand?</p>
26,334,174
2
2
null
2014-10-11 07:37:59.633 UTC
8
2016-03-04 10:31:23.113 UTC
2016-03-04 10:31:23.113 UTC
null
2,016,562
null
4,131,783
null
1
18
android|android-recyclerview|android-support-library
10,531
<p>The new <code>RecyclerView</code> works with a new <code>RecyclerView.Adapter</code> base class. So it doesn't work with the <code>CursorAdapter</code>.</p> <p>Currently there is <strong>no default implementation</strong> of <code>RecyclerView.Adapter</code> available.</p> <p>May be with the official release, Google will add it.</p>