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
38,645,060
What is the equivalent of Serial.available() in pyserial?
<p>When I am trying to read multiple lines of serial data on an Arduino, I use the following idiom:</p> <pre><code>String message = ""; while (Serial.available()){ message = message + serial.read() } </code></pre> <p>In Arduino C, <code>Serial.available()</code> returns the number of bytes available to be read from the serial buffer (See <a href="https://www.arduino.cc/en/Serial/Available" rel="noreferrer">Docs</a>). <em>What is the equivalent of <code>Serial.available()</code> in python?</em></p> <p>For example, if I need to read multiple lines of serial data I would expect to ues the following code:</p> <pre><code>import serial ser = serial.Serial('/dev/ttyACM0', 9600, timeout=0.050) ... while ser.available(): print ser.readline() </code></pre>
38,646,191
6
1
null
2016-07-28 19:22:19.653 UTC
4
2021-07-22 19:21:47.323 UTC
2016-07-30 19:30:21.9 UTC
null
1,713,185
null
1,713,185
null
1
17
python|serial-port
62,789
<p>The property <a href="https://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.in_waiting" rel="noreferrer"><code>Serial.in_waiting</code></a> returns &quot;the number of bytes in the receive buffer&quot;.</p> <p>This seems to be the equivalent of <a href="https://www.arduino.cc/en/Serial/Available" rel="noreferrer"><code>Serial.available()</code></a>'s description: &quot;the number of bytes ... that's already arrived and stored in the serial receive buffer.&quot;</p> <p>Try:</p> <pre><code>import serial ser = serial.Serial('/dev/ttyACM0', 9600, timeout=0.050) ... while ser.in_waiting: # Or: while ser.inWaiting(): print ser.readline() </code></pre> <p>For versions prior to pyserial 3.0, use <code>.inWaiting()</code>. To determine your pyserial version, do this:</p> <pre><code>import serial print(serial.__version__) </code></pre>
48,724,902
Python Datetime : use strftime() with a timezone-aware date
<p>Suppose I have date <code>d</code> like this : </p> <pre><code>&gt;&gt;&gt; d datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200)) </code></pre> <p>As you can see, it is "timezone aware", there is an offset of 2 Hour, utctime is </p> <pre><code>&gt;&gt;&gt; d.utctimetuple() time.struct_time(tm_year=2009, tm_mon=4, tm_mday=19, tm_hour=23, tm_min=12, tm_sec=0, tm_wday=6, tm_yday=109, tm_isdst=0) </code></pre> <p>So, real UTC date is 19th March 2009 <strong>23</strong>:12:00, right ? </p> <p>Now I need to format my date in string, I use </p> <pre><code>&gt;&gt;&gt; d.strftime('%Y-%m-%d %H:%M:%S.%f') '2009-04-19 21:12:00.000000' </code></pre> <p>Which doesn't seems to take this offset into account. How to fix that ? </p>
48,725,037
4
0
null
2018-02-10 19:48:43.367 UTC
7
2021-08-05 09:28:09.743 UTC
null
null
null
null
5,075,502
null
1
38
python|datetime|utc
90,998
<p>In addition to what @Slam has already answered:</p> <p>If you want to output the UTC time without any offset, you can do</p> <pre><code>from datetime import timezone, datetime, timedelta d = datetime(2009, 4, 19, 21, 12, tzinfo=timezone(timedelta(hours=-2))) d.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f') </code></pre> <p>See <a href="https://docs.python.org/3.6/library/datetime.html#datetime.datetime.astimezone" rel="noreferrer">datetime.astimezone</a> in the Python docs.</p>
29,709,849
How to do findAll in the new mongo C# driver and make it synchronous
<p>I was using official C# driver to do a <code>FindAll</code> and upgraded to the new driver 2.0. <code>FindAll</code> is obsolete and is replaced with Find. I am trying to convert a simple method that returns me a list of <code>Class1</code>. Cant find a realistic example using a POCO in their documentation </p> <p><code>var collection = database.GetCollection&lt;ClassA&gt;(Collection.MsgContentColName); return collection.FindAll().ToList();</code></p> <p>Can someone please help me convert with 2.0 driver and return a list and not a task?</p>
29,709,880
6
0
null
2015-04-17 21:41:25.157 UTC
null
2019-04-11 14:01:39.773 UTC
2015-06-17 14:24:47.343 UTC
null
885,318
null
558,460
null
1
24
c#|.net|mongodb|mongodb-.net-driver|mongodb-csharp-2.0
48,214
<p>you could do this to achieve the same using 2.0 driver,</p> <pre><code>var collection = database.GetCollection&lt;ClassA&gt;(Collection.MsgContentColName); var doc = collection.Find(filter).ToListAsync(); doc.Wait(); return doc.Result; </code></pre>
26,204,283
bootstrap container-fluid - remove margins the right way (overflow)
<p>How can I remove all margins from boostrap <code>container-fluid</code> class and its rows?</p> <pre><code>.container-fluid { padding: 0;} </code></pre> <p>This does basically what I want, but it adds 20px overflow to body. So should I just do this:</p> <pre><code>body, html { overflow-x: hidden; } </code></pre> <p>Do something with <code>.container-fluid &gt; .row</code></p>
26,204,586
3
0
null
2014-10-05 15:44:39.067 UTC
7
2022-04-26 10:47:45.573 UTC
2018-07-24 22:12:43.567 UTC
null
6,742,754
null
1,913,517
null
1
26
css|twitter-bootstrap
71,281
<p>To be specific about your question:</p> <p>The <code>.row</code> has a negative left and right margin equal to the left/right padding value of the <code>col-*-*</code>, that is why there are horizontal scrollbars when you fiddle with the grid without understanding how it works. If you manipulate the column classes with zero padding on the left and right or with some other value, the negative margin on the .row must be equal to the the padding on the left and right of the column classes. The .container also has padding that matches the value of the column classes to prevent the scrollbars. </p> <p>So the answer is: <code>.container-fluid &gt; .row</code> -- make the margin:0 on the left and right if you remove the padding on the left and right of the column classes. If all is zero, then you can just adjust the .container or .container fluid with zero padding on the left and right, but if you use different values > 15px L &amp; R, then it's a different story as the <code>.container/.container-fluid</code> will need to be adjusted if the left and right padding on the columns is greater than 15px.</p> <p>There are no margins on the <code>col-*-*</code> it's padding which is quite different when you use box-sizing:border-box globally as Boostrap 3 does. </p> <p>If you want a tight grid, remove all padding on the <strong>left</strong> and <strong>right</strong> of all column classes and then <strong>remove</strong> the <strong>negative</strong> <strong>margin</strong> on the <strong>left</strong> and <strong>right</strong> of the <code>.row</code>, and then you can remove the left and right <em>padding</em> on the <code>.container</code>. </p> <p>DEMO: <a href="http://jsbin.com/jeqase/2/">http://jsbin.com/jeqase/2/</a></p> <p>Removes all padding and negative margin for a tight grid and full width of the .container with any surrounding element (body, html, whatever) with the class <code>.alt-grid</code>:</p> <pre><code>.alt-grid [class*="col-"] {padding-left:0;padding-right:0} .alt-grid .row {margin-left:0;margin-right:0} /* container adjusted */ .alt-grid .container {width:100%;max-width:none;padding:0;} </code></pre> <p>You can also do this with <code>.container-fluid</code> - the only thing to zero out is the left and right padding.</p>
27,912,003
API end point returning "Authorization has been denied for this request." when sending bearer token
<p>I've followed a tutorial to protect a Web API with OAuth in C#. </p> <p>I'm doing some tests and so far I've been able to get the access token successfully from <code>/token</code>. I'm using a Chrome extension called "Advanced REST Client" to test it. </p> <pre><code>{"access_token":"...","token_type":"bearer","expires_in":86399} </code></pre> <p>This is what I get back from <code>/token</code>. Everything looks good.</p> <p>My next request is to my test API Controller:</p> <pre><code>namespace API.Controllers { [Authorize] [RoutePrefix("api/Social")] public class SocialController : ApiController { .... [HttpPost] public IHttpActionResult Schedule(SocialPost post) { var test = HttpContext.Current.GetOwinContext().Authentication.User; .... return Ok(); } } } </code></pre> <p>The request is a <code>POST</code> and has the header:</p> <pre><code>Authorization: Bearer XXXXXXXTOKEHEREXXXXXXX </code></pre> <p>I get: <code>Authorization has been denied for this request.</code> returned in JSON.</p> <p>I tried doing a GET as well and I get what I would expect, that the method isn't supported since I didn't implement it.</p> <p>Here is my Authorization Provider:</p> <pre><code>public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (var repo = new AuthRepository()) { IdentityUser user = await repo.FindUser(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role, "User")); context.Validated(identity); } } </code></pre> <p>Any help would be great. I'm not sure if it is the request or the code that is wrong. </p> <p>edit: Here is my <code>Startup.cs</code></p> <pre><code>public class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); ConfigureOAuth(app); } public void ConfigureOAuth(IAppBuilder app) { var oAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new SimpleAuthorizationServerProvider() }; // Token Generation app.UseOAuthAuthorizationServer(oAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); } } </code></pre>
32,150,447
3
0
null
2015-01-12 22:42:14.06 UTC
6
2017-02-21 23:45:15.777 UTC
2015-01-13 14:48:12.917 UTC
null
3,508,270
null
3,508,270
null
1
18
c#|oauth|asp.net-web-api2|owin
49,735
<p>Issue is pretty simple: <strong>Change order of your OWIN pipeline</strong>.</p> <pre><code>public void Configuration(IAppBuilder app) { ConfigureOAuth(app); var config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); } </code></pre> <p>For OWIN pipeline order of your configuration quite important. In your case, you try to use your Web API handler before the OAuth handler. Inside of it, you validate your request, found you secure action and try to validate it against current <code>Owin.Context.User</code>. At this point this user not exist because its set from the token with OAuth Handler which called later.</p>
26,941,144
How do you customize the color of the diff header in git diff?
<p>When I run <code>git diff</code>, the header part of each diff comes out in white text. Since I'm using a light background it is hard to read, so I want to change it.</p> <p>I have found that I can change other colors in the diff output like this (in <code>.gitconfig</code>):</p> <pre><code>[color "diff"] old = green new = red </code></pre> <p>But I can't figure out what to put there for the header color. Even better, is there someplace where all of the default <code>git config</code> settings are documented?</p> <p>By 'diff header' I mean lines like this:</p> <pre><code>diff --git a/README.md b/README.md index f102026..c5e3428 100644 --- a/README.md +++ b/README.md </code></pre>
26,941,235
4
0
null
2014-11-15 00:36:25.867 UTC
8
2021-07-09 02:06:05.183 UTC
2018-05-10 15:49:28.12 UTC
null
354,577
null
708,333
null
1
29
git
9,268
<p>Try setting <code>color.diff.meta</code>, e.g.</p> <pre><code>git config --global color.diff.meta blue </code></pre> <p>or by manually editing the configuration file</p> <pre><code>[color "diff"] meta = blue </code></pre> <p>You can look through the various <code>color.</code> settings <a href="http://git-scm.com/docs/git-config">in the <code>git-config</code> reference</a> for more possible settings. The <code>color.diff.meta</code> setting is listed here:</p> <blockquote> <p><code>color.diff.&lt;slot&gt;</code><br> Use customized color for diff colorization. <code>&lt;slot&gt;</code> specifies which part of the patch to use the specified color, and is one of <code>plain</code> (context text), <code>meta</code> (metainformation), <code>frag</code> (hunk header), <code>func</code> (function in hunk header), <code>old</code> (removed lines), <code>new</code> (added lines), <code>commit</code> (commit headers), or <code>whitespace</code> (highlighting whitespace errors). The values of these variables may be specified as in <code>color.branch.&lt;slot&gt;</code>.</p> </blockquote>
2,337,470
SVN move single directory into other repository (with history)
<p>Related question: <a href="https://stackoverflow.com/questions/1646003/svn-moving-repository-trunk-to-anothers-branch-with-history">Moving repository trunk to another’s branch (with history)</a></p> <hr> <p>I know that one can dump a <em>complete</em> SVN repository with history and load it into a user-defined (sub)directory of the target repository using:</p> <pre><code>// in source repo &gt; svnadmin dump . &gt; mydumpfilename // in destination repo (backslashes because I'm using Windows) &gt; svnadmin load . &lt; mydumpfilename --parent-dir some\sub\directory </code></pre> <p>But this will import the full repository into the target repository's sub-directory. What I want is to define a sub-directory in the source repository that should be exported. Something like <code>svnadmin dump . --source-path old\sub\dir &gt; mydumpfilename</code>.</p> <p>How can I achieve that? If TortoiseSVN can do that, please say so ;)</p> <hr> <p><strong>SOLUTION:</strong> Thanks to Tim Henigan's answer, here's the correct way to do it:</p> <pre><code>// execute in destination repo svndumpfilter include source\sub\dir &lt; mydumpfilename | svnadmin load . --parent-dir destination\sub\dir </code></pre> <p>Hope this will help others, too...</p>
2,337,503
1
3
null
2010-02-25 20:42:53.88 UTC
17
2015-04-30 16:30:17.04 UTC
2017-05-23 11:46:11.58 UTC
null
-1
null
245,706
null
1
40
svn|tortoisesvn|repository|subdirectory|svnadmin
24,655
<p>Check out <a href="http://svnbook.red-bean.com/en/1.7/svn.reposadmin.html" rel="noreferrer"><code>svndumpfilter</code></a> and this section on <a href="http://svnbook.red-bean.com/en/1.7/svn.reposadmin.maint.html#svn.reposadmin.maint.filtering" rel="noreferrer">Repository Maintenance</a>.</p> <p>Once you have a dumpfile for the entire old repository, you can use <code>svndumpfilter</code> to extract just the portion that you want.</p> <p>I am not aware of a way to do this with TortoiseSVN.</p>
46,713,186
matplotlib loop make subplot for each category
<p>I am trying to write a loop that will make a figure with 25 subplots, 1 for each country. My code makes a figure with 25 subplots, but the plots are empty. What can I change to make the data appear in the graphs?</p> <pre><code>fig = plt.figure() for c,num in zip(countries, xrange(1,26)): df0=df[df['Country']==c] ax = fig.add_subplot(5,5,num) ax.plot(x=df0['Date'], y=df0[['y1','y2','y3','y4']], title=c) fig.show() </code></pre>
46,718,194
2
0
null
2017-10-12 15:15:07.407 UTC
11
2017-10-12 20:19:11.577 UTC
null
null
null
null
4,863,798
null
1
7
python|matplotlib
48,164
<p>You got confused between the matplotlib plotting function and the pandas plotting wrapper.<br> The problem you have is that <code>ax.plot</code> does not have any <code>x</code> or <code>y</code> argument. </p> <h3>Use <code>ax.plot</code></h3> <p>In that case, call it like <code>ax.plot(df0['Date'], df0[['y1','y2']])</code>, without <code>x</code>, <code>y</code> and <code>title</code>. Possibly set the title separately. Example:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt countries = np.random.choice(list("ABCDE"),size=25) df = pd.DataFrame({"Date" : range(200), 'Country' : np.repeat(countries,8), 'y1' : np.random.rand(200), 'y2' : np.random.rand(200)}) fig = plt.figure() for c,num in zip(countries, xrange(1,26)): df0=df[df['Country']==c] ax = fig.add_subplot(5,5,num) ax.plot(df0['Date'], df0[['y1','y2']]) ax.set_title(c) plt.tight_layout() plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/y4tHe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/y4tHe.png" alt="enter image description here"></a></p> <h3>Use the pandas plotting wrapper</h3> <p>In this case plot your data via <code>df0.plot(x="Date",y =['y1','y2'])</code>. </p> <p>Example:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt countries = np.random.choice(list("ABCDE"),size=25) df = pd.DataFrame({"Date" : range(200), 'Country' : np.repeat(countries,8), 'y1' : np.random.rand(200), 'y2' : np.random.rand(200)}) fig = plt.figure() for c,num in zip(countries, xrange(1,26)): df0=df[df['Country']==c] ax = fig.add_subplot(5,5,num) df0.plot(x="Date",y =['y1','y2'], title=c, ax=ax, legend=False) plt.tight_layout() plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/yVRNv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yVRNv.png" alt="enter image description here"></a></p>
3,147,874
Oracle insert if row does not exist
<pre><code>insert ignore into table1 select 'value1',value2 from table2 where table2.type = 'ok' </code></pre> <p>When I run this I get the error &quot;missing INTO keyword&quot;.</p>
3,147,888
3
0
null
2010-06-30 09:13:16.243 UTC
5
2021-02-11 10:00:09.143 UTC
2021-02-11 10:00:09.143 UTC
null
2,753,501
null
236,112
null
1
19
sql|oracle|insert
64,634
<blockquote> <p>When I run this I get the error "missing INTO keyword" .</p> </blockquote> <p>Because IGNORE is not a keyword in Oracle. That is MySQL syntax.</p> <p>What you can do is use MERGE.</p> <pre><code>merge into table1 t1 using (select 'value1' as value1 ,value2 from table2 where table2.type = 'ok' ) t2 on ( t1.value1 = t2.value1) when not matched then insert values (t2.value1, t2.value2) / </code></pre> <p>From Oracle 10g we can use merge without handling both branches. In 9i we had to use a "dummy" MATCHED branch. </p> <p>In more ancient versions the only options were either :</p> <ol> <li>test for the row's existence before issuing an INSERT (or in a sub-query);</li> <li>to use PL/SQL to execute the INSERT and handle any resultant DUP_VAL_ON_INDEX error.</li> </ol>
3,154,443
Push notification guide?
<p>i need a rundown on how to fully utilise the push notification system. Iv read the push notification guide on the apple website but still unclear of some things.</p> <p>Lets say i have a windows PC and an iPad. 1) what should the PC be configured with to become a "provider"? Should it be configured to be like a server, giving out data upon requests. 2) How does the provider send the token to the APNs? </p> <p>The reason for using the push notification system is so that i can invoke a (tablereload data) method so that it would update the table as it has some custom images added as its subview so it would change images if some conditions in the server side were met.</p> <p>Thanks for reading guys , hoping for any kind of feedback or help.</p> <p>Cheers, Ephist</p>
3,154,874
4
0
null
2010-07-01 00:49:52.083 UTC
10
2016-07-03 11:36:46.657 UTC
2010-07-01 03:05:05.573 UTC
null
122,864
null
354,467
null
1
2
iphone|push-notification
10,315
<p>For anything other than development and testing, you'll generally want to run the provider on a server infrastructure that's not hosted on a home Windows machine. </p> <p>You can either use a commercial provider like <a href="http://www.ilime.com/push-notification/" rel="noreferrer">iLime</a> or <a href="http://urbanairship.com/products/push/" rel="noreferrer">Urban Airship</a>, but there's also a few tutorials and open source solutions out there:</p> <ul> <li><a href="http://www.easyapns.com" rel="noreferrer">EasyAPNS</a> (Push notifications using PHP &amp; MySQL)</li> <li><a href="http://blog.boxedice.com/2009/07/10/how-to-build-an-apple-push-notification-provider-server-tutorial/" rel="noreferrer">How to build an Apple Push Notification provider server (tutorial)</a></li> <li><a href="http://github.com/sebastianborggrewe/PHP-Apple-Push-Notification-Server#readme" rel="noreferrer">PHP Apple Push Notification Server</a></li> <li><a href="http://mobiforge.com/developing/story/programming-apple-push-notification-services" rel="noreferrer">Programming Apple Push Notification Services</a> (contains details on certificate configuration)</li> </ul> <p>There's also a local test app for Mac OS called <a href="http://stefan.hafeneger.name/download/PushMeBabySource.zip" rel="noreferrer">PushMeBaby</a> that you can use for development purposes.</p>
3,216,752
What is the difference between macro constants and constant variables in C?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1674032">“static const” vs “#define” in C</a> </p> </blockquote> <p>I started to learn C and couldn't understand clearly the differences between macros and constant variables.</p> <p>What changes when I write,</p> <pre><code>#define A 8 </code></pre> <p>and </p> <pre><code>const int A = 8 </code></pre> <p>?</p>
3,216,754
4
0
null
2010-07-09 21:42:58.123 UTC
7
2019-08-26 21:10:10.59 UTC
2017-05-23 11:45:26.457 UTC
null
-1
null
388,142
null
1
23
c|constants|c-preprocessor
48,214
<p>Macros are handled by the pre-processor - the pre-processor does text replacement in your source file, replacing all occurances of 'A' with the literal 8.</p> <p>Constants are handled by the compiler. They have the added benefit of type safety.</p> <p>For the actual compiled code, with any modern compiler, there should be zero performance difference between the two.</p>
2,545,961
How to synchronize a python dict with multiprocessing
<p>I am using Python 2.6 and the multiprocessing module for multi-threading. Now I would like to have a synchronized dict (where the only atomic operation I really need is the += operator on a value). </p> <p>Should I wrap the dict with a multiprocessing.sharedctypes.synchronized() call? Or is another way the way to go?</p>
2,556,974
4
0
null
2010-03-30 14:26:33.407 UTC
18
2018-09-17 05:13:47.86 UTC
null
null
null
null
85,514
null
1
28
python|multiprocessing|dictionary
20,333
<h2>Intro</h2> <p>There seems to be a lot of arm-chair suggestions and no working examples. None of the answers listed here even suggest using multiprocessing and this is quite a bit disappointing and disturbing. As python lovers we should support our built-in libraries, and while parallel processing and synchronization is never a trivial matter, I believe it can be made trivial with proper design. This is becoming extremely important in modern multi-core architectures and cannot be stressed enough! That said, I am far from satisfied with the multiprocessing library, as it is still in its infancy stages with quite a few pitfalls, bugs, and being geared towards functional programming (which I detest). Currently I still prefer the <a href="https://pythonhosted.org/Pyro4/" rel="noreferrer">Pyro</a> module (which is way ahead of its time) over multiprocessing due to multiprocessing's severe limitation in being unable to share newly created objects while the server is running. The "register" class-method of the manager objects will only actually register an object BEFORE the manager (or its server) is started. Enough chatter, more code:</p> <h2>Server.py</h2> <pre><code>from multiprocessing.managers import SyncManager class MyManager(SyncManager): pass syncdict = {} def get_dict(): return syncdict if __name__ == "__main__": MyManager.register("syncdict", get_dict) manager = MyManager(("127.0.0.1", 5000), authkey="password") manager.start() raw_input("Press any key to kill server".center(50, "-")) manager.shutdown() </code></pre> <p>In the above code example, Server.py makes use of multiprocessing's SyncManager which can supply synchronized shared objects. This code will not work running in the interpreter because the multiprocessing library is quite touchy on how to find the "callable" for each registered object. Running Server.py will start a customized SyncManager that shares the syncdict dictionary for use of multiple processes and can be connected to clients either on the same machine, or if run on an IP address other than loopback, other machines. In this case the server is run on loopback (127.0.0.1) on port 5000. Using the authkey parameter uses secure connections when manipulating syncdict. When any key is pressed the manager is shutdown.</p> <h2>Client.py</h2> <pre><code>from multiprocessing.managers import SyncManager import sys, time class MyManager(SyncManager): pass MyManager.register("syncdict") if __name__ == "__main__": manager = MyManager(("127.0.0.1", 5000), authkey="password") manager.connect() syncdict = manager.syncdict() print "dict = %s" % (dir(syncdict)) key = raw_input("Enter key to update: ") inc = float(raw_input("Enter increment: ")) sleep = float(raw_input("Enter sleep time (sec): ")) try: #if the key doesn't exist create it if not syncdict.has_key(key): syncdict.update([(key, 0)]) #increment key value every sleep seconds #then print syncdict while True: syncdict.update([(key, syncdict.get(key) + inc)]) time.sleep(sleep) print "%s" % (syncdict) except KeyboardInterrupt: print "Killed client" </code></pre> <p>The client must also create a customized SyncManager, registering "syncdict", this time without passing in a callable to retrieve the shared dict. It then uses the customized SycnManager to connect using the loopback IP address (127.0.0.1) on port 5000 and an authkey establishing a secure connection to the manager started in Server.py. It retrieves the shared dict syncdict by calling the registered callable on the manager. It prompts the user for the following:</p> <ol> <li>The key in syncdict to operate on</li> <li>The amount to increment the value accessed by the key every cycle</li> <li>The amount of time to sleep per cycle in seconds</li> </ol> <p>The client then checks to see if the key exists. If it doesn't it creates the key on the syncdict. The client then enters an "endless" loop where it updates the key's value by the increment, sleeps the amount specified, and prints the syncdict only to repeat this process until a KeyboardInterrupt occurs (Ctrl+C).</p> <h2>Annoying problems</h2> <ol> <li>The Manager's register methods MUST be called before the manager is started otherwise you will get exceptions even though a dir call on the Manager will reveal that it indeed does have the method that was registered.</li> <li>All manipulations of the dict must be done with methods and not dict assignments (syncdict["blast"] = 2 will fail miserably because of the way multiprocessing shares custom objects)</li> <li>Using SyncManager's dict method would alleviate annoying problem #2 except that annoying problem #1 prevents the proxy returned by SyncManager.dict() being registered and shared. (SyncManager.dict() can only be called AFTER the manager is started, and register will only work BEFORE the manager is started so SyncManager.dict() is only useful when doing functional programming and passing the proxy to Processes as an argument like the doc examples do)</li> <li>The server AND the client both have to register even though intuitively it would seem like the client would just be able to figure it out after connecting to the manager (Please add this to your wish-list multiprocessing developers)</li> </ol> <h2>Closing</h2> <p>I hope you enjoyed this quite thorough and slightly time-consuming answer as much as I have. I was having a great deal of trouble getting straight in my mind why I was struggling so much with the multiprocessing module where Pyro makes it a breeze and now thanks to this answer I have hit the nail on the head. I hope this is useful to the python community on how to improve the multiprocessing module as I do believe it has a great deal of promise but in its infancy falls short of what is possible. Despite the annoying problems described I think this is still quite a viable alternative and is pretty simple. You could also use SyncManager.dict() and pass it to Processes as an argument the way the docs show and it would probably be an even simpler solution depending on your requirements it just feels unnatural to me.</p>
31,789,939
Calculate the standard deviation of grouped data in a Spark DataFrame
<p>I have user logs that I have taken from a csv and converted into a DataFrame in order to leverage the SparkSQL querying features. A single user will create numerous entries per hour, and I would like to gather some basic statistical information for each user; really just the count of the user instances, the average, and the standard deviation of numerous columns. I was able to quickly get the mean and count information by using groupBy($"user") and the aggregator with SparkSQL functions for count and avg:</p> <pre><code>val meanData = selectedData.groupBy($"user").agg(count($"logOn"), avg($"transaction"), avg($"submit"), avg($"submitsPerHour"), avg($"replies"), avg($"repliesPerHour"), avg($"duration")) </code></pre> <p>However, I cannot seem to find an equally elegant way to calculate the standard deviation. So far I can only calculate it by mapping a string, double pair and use StatCounter().stdev utility:</p> <pre><code>val stdevduration = duration.groupByKey().mapValues(value =&gt; org.apache.spark.util.StatCounter(value).stdev) </code></pre> <p>This returns an RDD however, and I would like to try and keep it all in a DataFrame for further queries to be possible on the returned data.</p>
31,791,275
2
0
null
2015-08-03 14:28:31.987 UTC
10
2019-10-03 22:36:06.013 UTC
null
null
null
null
5,024,531
null
1
23
scala|apache-spark|apache-spark-sql
44,715
<p><strong>Spark 1.6+</strong></p> <p>You can use <code>stddev_pop</code> to compute population standard deviation and <code>stddev</code> / <code>stddev_samp</code> to compute unbiased sample standard deviation:</p> <pre><code>import org.apache.spark.sql.functions.{stddev_samp, stddev_pop} selectedData.groupBy($"user").agg(stdev_pop($"duration")) </code></pre> <p><strong>Spark 1.5 and below</strong> (<em>The original answer</em>):</p> <p>Not so pretty and biased (same as the value returned from <code>describe</code>) but using formula:</p> <p><a href="https://i.stack.imgur.com/jWcyQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jWcyQ.png" alt="wikipedia sdev"></a></p> <p>you can do something like this:</p> <pre><code>import org.apache.spark.sql.functions.sqrt selectedData .groupBy($"user") .agg((sqrt( avg($"duration" * $"duration") - avg($"duration") * avg($"duration") )).alias("duration_sd")) </code></pre> <p>You can of course create a function to reduce the clutter:</p> <pre><code>import org.apache.spark.sql.Column def mySd(col: Column): Column = { sqrt(avg(col * col) - avg(col) * avg(col)) } df.groupBy($"user").agg(mySd($"duration").alias("duration_sd")) </code></pre> <p>It is also possible to use Hive UDF:</p> <pre><code>df.registerTempTable("df") sqlContext.sql("""SELECT user, stddev(duration) FROM df GROUP BY user""") </code></pre> <hr> <p>Source of the image: <a href="https://en.wikipedia.org/wiki/Standard_deviation" rel="noreferrer">https://en.wikipedia.org/wiki/Standard_deviation</a></p>
31,839,578
How to define a JSON schema that requires at least one of many properties
<p>I would like to know if I can define a JSON schema (draft 4) that requires at least one of many properties possible for an object. I already know of <code>allOf</code>, <code>anyOf</code> and <code>oneOf</code> but just can't figure out how to use them in the way I want.</p> <p>Here are some example JSON to illustrate :</p> <pre><code>// Test Data 1 - Should pass { "email": "[email protected]", "name": "John Doe" } // Test Data 2 - Should pass { "id": 1, "name": "Jane Doe" } // Test Data 3 - Should pass { "id": 1, "email": "[email protected]", "name": "John Smith" } // Test Data 4 - Should fail, invalid email { "id": 1, "email": "thisIsNotAnEmail", "name": "John Smith" } // Test Data 5 - Should fail, missing one of required properties { "name": "John Doe" } </code></pre> <p>I would like to require at least <code>id</code> or <code>email</code> (also accepting both of them) and still pass validation according to format. Using <code>oneOf</code> fails validation if I provide both (test 3), <code>anyOf</code> passes validation even if one of them is not valid (test 4)</p> <p>Here is my schema :</p> <pre><code>{ "$schema": "http://json-schema.org/draft-04/schema#", "id": "https://example.com", "properties": { "name": { "type": "string" } }, "anyOf": [ { "properties": { "email": { "type": "string", "format": "email" } } }, { "properties": { "id": { "type": "integer" } } } ] } </code></pre> <p>Can you help me how to achieve correct validation for my use case ?</p>
31,841,897
2
0
null
2015-08-05 17:56:55.147 UTC
4
2021-06-28 00:18:44.203 UTC
null
null
null
null
165,055
null
1
62
json|jsonschema
30,449
<p>To require at least one of a set of properties, use <code>required</code> inside a series of <code>anyOf</code> options:</p> <pre><code>{ "type": "object", "anyOf": [ {"required": ["id"]}, {"required": ["email"]} // any other properties, in a similar way ], "properties": { // Your actual property definitions here } { </code></pre> <p>If any of the properties you want is present (<code>"id"</code>, <code>"email"</code>), then it will pass the corresponding option in <code>allOf</code>.</p>
56,488,382
Invalid number of channels in input image
<p>I am receiving an error when running my program, I think specifically about color manipulation in the OpenCV library.</p> <p>I'm trying to build a program that takes a video feed from a Raspberry Pi camera and analyze it. I want to find the brightest point in the video and calculate the distance and angle the point is at from the center of the video feed.</p> <p>The project I am doing has the camera pointed at the center of a dark box, with a moving point of light.</p> <p>I am using OpenCV 4.0.0 and C++ on a Raspberry Pi 3, as well as the <a href="https://github.com/cedricve/raspicam" rel="noreferrer">raspicam</a> library.</p> <p>I am taking pointers from <a href="https://www.pyimagesearch.com/2014/09/29/finding-brightest-spot-image-using-python-opencv/" rel="noreferrer">this</a> guide, but I am using C++ and a video feed instead of Python and a static image.</p> <pre class="lang-cpp prettyprint-override"><code> raspicam::RaspiCam_Cv Camera; cv::Mat image; cv::Mat gray; int nCount=100; int nR, nC; // numRows, numCols cv::Point imgMid; Vect toCenter; // for recording brightest part of img double minVal, maxVal; cv::Point minLoc, maxLoc; Camera.set(cv::CAP_PROP_FORMAT, CV_8UC1); #ifdef DEBUG cout &lt;&lt; "Opening camera..." &lt;&lt; endl; if (!Camera.open()) { cerr &lt;&lt; "Error opening the camera" &lt;&lt; endl; return -1; } cout &lt;&lt; "Capturing " &lt;&lt; nCount &lt;&lt; " frames ...." &lt;&lt; endl; #endif for (int i=0; i&lt; nCount; i++) { Camera.grab(); Camera.retrieve(image); nR = image.rows; nC = image.cols; imgMid.x = nC / 2; imgMid.y = nR / 2; // convert to grayscale image cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY); // find x, y coord of brightest part of img cv::minMaxLoc(gray, &amp;minVal, &amp;maxVal, &amp;minLoc, &amp;maxLoc); // calculate vector to the center of the camera toCenter.first = distBtwn(imgMid.x, maxLoc.x, imgMid.y, maxLoc.y); toCenter.second = angle(imgMid.x, maxLoc.x, imgMid.y, maxLoc.y); </code></pre> <p>I expect the program to take a frame of the video feed, convert it to grayscale, find the brightest part of the frame, and finally do some calculations to find the distance to the center of the frame and angle of the point from the positive x-axis.</p> <p>This is the error</p> <p><img src="https://i.imgur.com/Ae8AsHq.jpg" alt=""></p> <p>I apologize for the phone camera, but I am working with somebody else in a different city, where they have the testing equipment (I am the coder) and this is what they sent me.</p>
56,489,504
2
0
null
2019-06-07 05:21:55.777 UTC
null
2022-02-28 08:16:46.613 UTC
2019-06-07 05:29:34.573 UTC
null
6,622,587
null
11,612,263
null
1
20
c++|opencv|raspberry-pi
51,413
<p>As error message said, the image given in input to the color conversion function has an invalid number of channels.</p> <p>The point is that you are acquiring frames as single 8bit channel</p> <pre><code>Camera.set(cv::CAP_PROP_FORMAT, CV_8UC1) </code></pre> <p>and then you try to convert this frame in grayscale</p> <pre><code>cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY) </code></pre> <p>You have 2 easy options to solve this issue:</p> <ol> <li>you change the camera acquisition format in order to have color information in your frames, for example using CV_32S or CV_32F</li> <li>you skip the color conversion as you already have grayscale image, thus no need to convert it.</li> </ol> <p><a href="https://docs.opencv.org/3.4/de/d06/tutorial_js_basic_ops.html" rel="nofollow noreferrer">Take a look to this link for OpenCV color manipulation</a></p>
957,284
<%$, <%@, <%=, <%# ... what's the deal?
<p>I've programmed in both classic ASP and ASP.NET, and I see different tags inside of the markup for server side code. </p> <p>I've recently come across a <a href="http://blogs.msdn.com/dancre/archive/2007/02/13/the-difference-between-lt-and-lt-in-asp-net.aspx" rel="noreferrer">good blog on MSDN</a> that goes over the difference between:</p> <ul> <li><code>&lt;%=</code> (percentage together with equals sign) and </li> <li><code>&lt;%#</code> (percent sign and hash/pound/octothorpe) </li> </ul> <p>(<code>&lt;%#</code> is evaluated only at databind, and <code>&lt;%=</code> is evaluated at render), but I also see:</p> <ul> <li><code>&lt;%$</code> (percent and dollar sign) and </li> <li><code>&lt;%@</code> (percent sign and at symbol).</li> </ul> <p>I believe <code>&lt;%@</code> loads things like assemblies and perhaps <code>&lt;%$</code> loads things from config files? I'm not too sure.</p> <p>I was just wondering if anyone could clarify all of this for me and possibly explain why it's important to create so many different tags that seemingly have a similar purpose?</p>
957,321
2
6
null
2009-06-05 18:12:53.08 UTC
156
2016-08-16 08:36:13.247 UTC
2013-09-16 13:48:37.73 UTC
null
3,619
null
106,672
null
1
221
asp.net|server-tags
31,950
<ul> <li><code>&lt;% %&gt;</code> - is for <a href="http://msdn.microsoft.com/en-us/library/k6xeyd4z%28v=vs.100%29.aspx" rel="noreferrer">inline code</a> (especially logic flow)</li> <li><code>&lt;%$ %&gt;</code> - is for <a href="http://msdn.microsoft.com/en-us/library/d5bd1tad.aspx" rel="noreferrer">evaluating expressions</a> (like resource variables)</li> <li><code>&lt;%@ %&gt;</code> - is for <a href="http://msdn.microsoft.com/en-us/library/xz702w3e%28v=vs.100%29.aspx" rel="noreferrer">Page directives</a>, registering assemblies, importing namespaces, etc.</li> <li><code>&lt;%= %&gt;</code> - is short-hand for <code>Response.Write</code> (discussed <a href="http://msdn.microsoft.com/en-us/library/ms178135.aspx" rel="noreferrer">here</a>)</li> <li><code>&lt;%# %&gt;</code> - is used for <a href="http://support.microsoft.com/kb/307860#1a" rel="noreferrer">data binding expressions</a>.</li> <li><code>&lt;%: %&gt;</code> - is short-hand for <a href="http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx" rel="noreferrer">Response.Write(Server.HTMLEncode())</a> ASP.net 4.0+</li> <li><code>&lt;%#: %&gt;</code> - is used for <a href="http://support.microsoft.com/kb/307860#1a" rel="noreferrer">data binding expressions</a> and is automatically HTMLEncoded.</li> <li><code>&lt;%-- --%&gt;</code> - is for <a href="http://msdn.microsoft.com/en-us/library/4acf8afk%28v=vs.100%29.aspx" rel="noreferrer">server-side comments</a></li> </ul>
2,422,289
Any recommended Java profiling tutorial?
<p>Is there any recommended Java application profiling tutorial? </p> <p>I am now using <a href="http://en.wikipedia.org/wiki/JProfiler" rel="noreferrer">JProfiler</a> and <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a> <a href="http://en.wikipedia.org/wiki/Test_&amp;_Performance_Tools_Platform" rel="noreferrer">Test &amp; Performance Tools Platform</a> (TPTP) with my profiling. However, although equipped with wonderful weapons, as someone new to new in Java profiling, I am still missing the general theory and skill in pinpointing the bottleneck.</p>
2,425,217
5
0
null
2010-03-11 03:15:31.027 UTC
25
2013-06-19 17:51:03.353 UTC
2012-08-21 18:47:25.977 UTC
null
63,550
null
113,037
null
1
27
java|performance|profiling
17,036
<p>Profiling is a subject having more than one school of thought.</p> <p>The more popular one is that you proceed by getting <em>measurements</em>. That is, you try to see how long each function takes and/or how many times it is called. Clearly, if a function takes very little time, then speeding it up will gain you little. But if it takes a lot of time, then you have to do detective work to figure out what part of the function is responsible for the time. Do not expect function times to add up to total time, because functions call each other, and the reason function A may take a lot of time is that it calls function B that also takes a lot of time.</p> <p>This approach can find a lot of problems, but it depends on you being a good detective and being able to think clearly about different kinds of time, like wall-clock time versus CPU time, and self-time versus inclusive time. For example, an application may appear to be slow but the function times may be all reported as near zero. This can be caused by the program being I/O bound. If the I/O is something that you expect, that may be fine, but it may be doing some I/O that you don't know about, and then you are back to detective work.</p> <p>General expectation with profilers is that if you can fix enough things to get a 10% or 20% speedup, that's pretty good, and I never hear stories of profilers being used repeatedly to get speedups of much more than that.</p> <p>Another approach is not to measure, but to <em>capture</em>. It is based on the idea that, during a time when the program is taking longer (in wall-clock time) than you would like, you want to know what it is doing, predominantly, and one way to find out is to stop it and ask, or take a snapshot of its state and analyze it to understand completely what it is doing and why it is doing it at that particular point in time. If you do this multiple times and you see something that it is trying to do at multiple times, then that activity is something that you could fruitfully optimize. The difference is that you are not asking <em>how much</em>; you are asking <em>what</em> and <em>why</em>. <a href="https://stackoverflow.com/questions/406760/whats-your-most-controversial-programming-opinion/1562802#1562802">Here's another explanation.</a> (Notice that the speed of taking such a snapshot doesn't matter, because you're not asking about time, you're asking what the program is doing and why.)</p> <p>In the case of Java, <a href="https://stackoverflow.com/questions/266373/one-could-use-a-profiler-but-why-not-just-halt-the-program/317160#317160">here is one low-tech but highly effective</a> way to do that, or you can use the "pause" button in Eclipse. Another way is to use a particular type of profiler, one that samples the entire call stack, on wall-clock time (not CPU unless you want to be blind to I/O), when you want it to sample (for example, not when waiting for user input), and summarizes at the level of lines of code, not just at the level of functions, and percent of time, not absolute time. To get percent of time, it should tell you, for each line of code that appears on any sample, the percent of samples containing that line, because if you could make that line go away, you would save that percent. (You should ignore other things it tries to tell you about, like call graphs, recursion, and self-time.) There are very few profilers that meet this specification, but one is <a href="http://www.rotateright.com/" rel="noreferrer">RotateRight/Zoom</a>, but I'm not sure if it works with Java, and there may be others.</p> <p>In some cases it may be difficult to get stack samples when you want them, during the time of actual slowness. Then, since what you are after is percentages, you can do anything to the code that makes it easier to get samples without altering the percentages. One way is to <em>amplify</em> the code by wrapping a temporary loop around it of, say, 100 iterations. Another way is, under a debugger, to set a data-change breakpoint. This will cause the code to be interpreted 10-100 times slower than normal. Another way is to employ an alarm-clock timer to go off during the period of slowness, and use it to grab a sample.</p> <p>With the capturing technique, if you use it repeatedly to find and perform multiple optimizations, you can expect to reach near-optimal performance. In the case of large software, where bottlenecks are more numerous, this can mean substantial factors. People on Stack&nbsp;Overflow have reported factors from 7x to 60x. <a href="https://stackoverflow.com/questions/926266/performance-optimization-strategies-of-last-resort/927773#927773">Here is a detailed example of 43x.</a></p> <p>The capturing technique has trouble with cases where it is hard to figure out why the threads are waiting when they are, such as when waiting for a transaction to complete on another processor. (Measuring has the same problem.) In those cases, I use a laborious method of merging time-stamped logs.</p>
2,503,807
Declaring an enum within a class
<p>In the following code snippet, the <code>Color</code> enum is declared within the <code>Car</code> class in order to limit the scope of the enum and to try not to "pollute" the global namespace.</p> <pre><code>class Car { public: enum Color { RED, BLUE, WHITE }; void SetColor( Car::Color color ) { _color = color; } Car::Color GetColor() const { return _color; } private: Car::Color _color; }; </code></pre> <p>(1) Is this a good way to limit the scope of the <code>Color</code> enum? Or, should I declare it outside of the <code>Car</code> class, but possibly within its own namespace or struct? I just came across this article today, which advocates the latter and discusses some nice points about enums: <a href="http://gamesfromwithin.com/stupid-c-tricks-2-better-enums" rel="noreferrer">http://gamesfromwithin.com/stupid-c-tricks-2-better-enums</a>.</p> <p>(2) In this example, when working <em>within</em> the class, is it best to code the enum as <code>Car::Color</code>, or would just <code>Color</code> suffice? (I assume the former is better, just in case there is another <code>Color</code> enum declared in the global namespace. That way, at least, we are explicit about the enum to we are referring.)</p>
2,503,845
5
0
null
2010-03-23 21:36:10.44 UTC
55
2018-11-01 18:40:22.443 UTC
2017-10-06 17:52:28.483 UTC
null
3,885,376
null
117,028
null
1
170
c++|class|enums|namespaces|scope
296,388
<ol> <li><p>If <code>Color</code> is something that is specific to just <code>Car</code>s then that is the way you would limit its scope. If you are going to have another <code>Color</code> enum that other classes use then you might as well make it global (or at least outside <code>Car</code>).</p></li> <li><p>It makes no difference. If there is a global one then the local one is still used anyway as it is closer to the current scope. Note that if you define those function outside of the class definition then you'll need to explicitly specify <code>Car::Color</code> in the function's interface.</p></li> </ol>
2,883,726
How to convert an arbitrary object to String with EL + JSTL? (calling toString())
<p>Is there any way to call toString() on an object with the EL and JSTL? (I need the String representation of an enum as index in a map in a JSP EL expression.) I hoped something like <code>${''+object}</code> would work like in java, but EL isn't that nice, and there does not seem to be any function that does it.</p> <p>Clarification: I have a variable <code>somemap</code> that maps Strings to Strings, and I have a variable <code>someenum</code> that is an enumeration. I'd like to do something like <code>${somemap[someenum.toString()]}</code>. (Of course .toString() does not work, but what does?)</p>
2,883,779
6
4
null
2010-05-21 16:20:14.657 UTC
1
2019-03-13 07:02:20.333 UTC
2010-05-25 12:19:37.15 UTC
null
21,499
null
21,499
null
1
12
java|jsp|jstl|el
59,866
<p>You just do it like this:</p> <pre><code>${object} </code></pre> <p>And it'll <code>toString</code> it for you.</p> <hr> <p><strong>edit</strong>: Your nested expression can be resolved like this:</p> <pre><code>&lt;c:set var="myValue"&gt;${someenum}&lt;/c:set&gt; ${somemap[myValue]} </code></pre> <p>The first line stringifies (using <code>toString()</code>) the <code>${someenum}</code> expression and stores it in the <code>myValue</code> variable. The second line uses <code>myValue</code> to index the map.</p>
2,677,300
Learning emacs - useful mnemonics?
<p>Are there any mnemonics or patterns that make memorizing emacs key combos easier?</p>
2,677,377
6
3
2010-04-20 17:45:54.827 UTC
2010-04-20 17:35:04.307 UTC
9
2016-07-26 08:05:49.613 UTC
2010-04-20 17:45:05.207 UTC
user65663
null
user65663
null
null
1
17
emacs|keyboard-shortcuts
4,855
<p>Well, the main important ones are: `</p> <ul> <li><kbd>C-k</kbd> to "<code>K</code>ill" a line and <kbd>C-y</kbd> to "<code>Y</code>ank" it back from the kill buffer (aka: clipboard). </li> <li><kbd>C-s</kbd> to "<code>S</code>earch "</li> <li><kbd>C-h</kbd> for "<code>H</code>elp"</li> <li><kbd>C-t</kbd> "<code>T</code>ranspose" two characters.</li> <li><kbd>C-p</kbd> "<code>P</code>revious" line</li> <li><kbd>C-n</kbd> "<code>N</code>ext" line</li> <li><kbd>C-f</kbd> "<code>F</code>orward" char</li> <li><kbd>C-b</kbd> "<code>B</code>ackward" char</li> <li><kbd>C-e</kbd> "<code>E</code>nd" of line</li> <li><kbd>C-a</kbd> .... a is the beginning of the alphabet, so "<code>A</code> beginning" of line</li> </ul> <p>Other than that I mostly use the arrow keys, the mouse, the menus, or a select group of actual commands. The few exceptions to this (eg: macro creation and use) I learned pretty much by muscle-memory. </p>
2,364,818
When should database synonyms be used?
<p>I've got the syntax down but I'm wondering if somebody can provide an illustrative use case where database synonyms are very useful.</p>
2,364,877
6
2
null
2010-03-02 16:34:55.987 UTC
7
2013-03-06 16:30:33.46 UTC
2010-11-02 08:46:27.347 UTC
null
224,671
null
208,066
null
1
31
sql|oracle|database-design|plsql|synonym
29,816
<p>It is excellent for staging mock tables when testing. For example, if your source tables contain millions of records and you want to test a small subset of data, you can use synonyms to re-direct the source table to a smaller table you control so you can stage various scenarios.</p> <p>In this way, you can update/delete the data in the mock table without affecting your source table. When you are ready to use the source table, all you need to do is re-direct the synonym.</p>
2,642,141
How to Create Deterministic Guids
<p>In our application we are creating Xml files with an attribute that has a Guid value. This value needed to be consistent between file upgrades. So even if everything else in the file changes, the guid value for the attribute should remain the same. </p> <p>One obvious solution was to create a static dictionary with the filename and the Guids to be used for them. Then whenever we generate the file, we look up the dictionary for the filename and use the corresponding guid. But this is not feasible because we might scale to 100's of files and didnt want to maintain big list of guids.</p> <p>So another approach was to make the Guid the same based on the path of the file. Since our file paths and application directory structure are unique, the Guid should be unique for that path. So each time we run an upgrade, the file gets the same guid based on its path. I found one cool way to generate such '<a href="http://geekswithblogs.net/EltonStoneman/archive/2008/06/26/generating-deterministic-guids.aspx" rel="noreferrer">Deterministic Guids</a>' (Thanks Elton Stoneman). It basically does this:</p> <pre><code>private Guid GetDeterministicGuid(string input) { //use MD5 hash to get a 16-byte hash of the string: MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider(); byte[] inputBytes = Encoding.Default.GetBytes(input); byte[] hashBytes = provider.ComputeHash(inputBytes); //generate a guid from the hash: Guid hashGuid = new Guid(hashBytes); return hashGuid; } </code></pre> <p>So given a string, the Guid will always be the same. </p> <p>Are there any other approaches or recommended ways to doing this? What are the pros or cons of that method?</p>
5,657,517
6
0
null
2010-04-15 01:21:46.943 UTC
42
2021-07-27 12:45:00.433 UTC
2010-04-15 01:48:44.713 UTC
null
37,971
null
125,422
null
1
119
c#|.net|guid|uuid
49,705
<p>As mentioned by @bacar, <a href="http://www.ietf.org/rfc/rfc4122.txt" rel="noreferrer">RFC 4122</a> §4.3 defines a way to create a name-based UUID. The advantage of doing this (over just using a MD5 hash) is that these are guaranteed not to collide with non-named-based UUIDs, and have a very (very) small possibility of collision with other name-based UUIDs.</p> <p>There's no native support in the .NET Framework for creating these, but I posted <a href="https://github.com/Faithlife/FaithlifeUtility/blob/master/src/Faithlife.Utility/GuidUtility.cs" rel="noreferrer">code on GitHub</a> that implements the algorithm. It can be used as follows:</p> <pre><code>Guid guid = GuidUtility.Create(GuidUtility.UrlNamespace, filePath); </code></pre> <p>To reduce the risk of collisions with other GUIDs even further, you could create a private GUID to use as the namespace ID (instead of using the URL namespace ID defined in the RFC).</p>
2,812,520
Dealing with multiple Python versions and PIP?
<p>Is there any way to make <code>pip</code> play well with multiple versions of Python? For example, I want to use <code>pip</code> to explicitly install things to either my site 2.5 installation or my site 2.6 installation.</p> <p>For example, with <code>easy_install</code>, I use <code>easy_install-2.{5,6}</code>.</p> <p>And, yes — I know about virtualenv, and no — it's not a solution to this particular problem.</p>
4,910,393
27
3
null
2010-05-11 16:32:18.193 UTC
251
2022-08-18 14:21:06.537 UTC
2019-03-11 09:54:35.39 UTC
null
608,639
null
71,522
null
1
677
python|pip
844,064
<p>The <a href="https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/" rel="noreferrer">current recommendation</a> is to use <code>python -m pip</code>, where <code>python</code> is the version of Python you would like to use. This is the recommendation because it works across all versions of Python, and in all forms of virtualenv. For example:</p> <pre><code># The system default python: $ python -m pip install fish # A virtualenv's python: $ .env/bin/python -m pip install fish # A specific version of python: $ python-3.6 -m pip install fish </code></pre> <p>Previous answer, left for posterity:</p> <p>Since version 0.8, Pip supports <code>pip-{version}</code>. You can use it the same as <code>easy_install-{version}</code>:</p> <pre><code>$ pip-2.5 install myfoopackage $ pip-2.6 install otherpackage $ pip-2.7 install mybarpackage </code></pre> <hr /> <p><strong>EDIT</strong>: pip changed its schema to use <code>pipVERSION</code> instead of <code>pip-VERSION</code> in version 1.5. You should use the following if you have <code>pip &gt;= 1.5</code>:</p> <pre><code>$ pip2.6 install otherpackage $ pip2.7 install mybarpackage </code></pre> <p>Check <a href="https://github.com/pypa/pip/pull/1053" rel="noreferrer">https://github.com/pypa/pip/pull/1053</a> for more details</p> <hr /> <p>References:</p> <ul> <li><a href="https://github.com/pypa/pip/issues/200" rel="noreferrer">https://github.com/pypa/pip/issues/200</a></li> <li><s>http://www.pip-installer.org/docs/pip/en/0.8.3/news.html#id4</s><br /> <a href="https://pip.pypa.io/en/stable/news/#v0-8" rel="noreferrer">https://pip.pypa.io/en/stable/news/#v0-8</a> or<br /> <a href="https://web.archive.org/web/20140310013920/http://www.pip-installer.org:80/docs/pip/en/0.8.3/news.html#id4" rel="noreferrer">https://web.archive.org/web/20140310013920/http://www.pip-installer.org:80/docs/pip/en/0.8.3/news.html#id4</a></li> </ul>
25,180,252
SQL Server Service not available in service list after installation of SQL Server Management Studio
<p>I have Windows 7 Home edition SP1 installed on my system, and downloaded SQL Server 2008 R2 Management Studio and got it installed. But when I try to connect via .\SQLEXPRESS, SSMS shows error</p> <p>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (Microsoft SQL Server, Error: -1) For help, click: <a href="http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&amp;EvtSrc=MSSQLServer&amp;EvtID=-1&amp;LinkId=20476" rel="noreferrer">http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&amp;EvtSrc=MSSQLServer&amp;EvtID=-1&amp;LinkId=20476</a>.</p> <p>I go back to check the local services there I don't find any SQL Server service running.</p> <p>What I have to do for this? DO I need to install any SQL service on my system? or how I should proceed?</p>
25,180,322
3
0
null
2014-08-07 10:33:59.027 UTC
4
2022-02-10 15:56:23.687 UTC
2014-08-07 14:31:52.74 UTC
null
2,671,940
null
2,671,940
null
1
13
sql|sql-server|sql-server-2008
125,929
<blockquote> <p>downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?</p> </blockquote> <p>You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.</p> <p><a href="http://www.microsoft.com/en-us/download/details.aspx?id=1695">http://www.microsoft.com/en-us/download/details.aspx?id=1695</a></p>
23,484,623
How can I force homebrew to recompile?
<p>I'm trying to install wxWidgets on Mac OS X 10.9. It's already installed, but I'm having the problem described <a href="https://github.com/Homebrew/homebrew/issues/23666">here</a>. Someone suggested to add <code>ENV.append_to_cflags "-stdlib=libc++"</code>. I did, but I'm not able to recompile the code.</p> <pre><code>$ brew install wxmac Warning: wxmac-3.0.0 already installed $ brew edit wxmac =&gt; ok, modifications done, now I want to recompile and reinstall $ brew uninstall wxmac Uninstalling /usr/local/Cellar/wxmac/3.0.0... $ brew install wxmac ==&gt; Downloading https://downloads.sf.net/project/machomebrew/Bottles/wxmac- 3.0.0.mavericks.bottle.2.tar.gz Already downloaded: /Library/Caches/Homebrew/wxmac-3.0.0.mavericks.bottle.2.tar.gz ==&gt; Pouring wxmac-3.0.0.mavericks.bottle.2.tar.gz /usr/local/Cellar/wxmac/3.0.0: 775 files, 41M </code></pre> <p>How can I force homebrew to recompile?</p>
23,490,170
2
0
null
2014-05-06 01:36:19.853 UTC
15
2017-01-04 16:15:41.967 UTC
null
null
null
null
490,774
null
1
68
homebrew
35,241
<p>Homebrew is installing wxmac in bottle form (a pre-compiled binary of wxmac). To build from source, add the <code>--build-from-source</code> flag when calling <code>brew install</code>:</p> <pre><code>$ brew install --build-from-source wxmac </code></pre>
23,664,877
Pandas equivalent of Oracle Lead/Lag function
<p>First I'm new to pandas, but I'm already falling in love with it. I'm trying to implement the equivalent of the Lag function from Oracle.</p> <p>Let's suppose you have this DataFrame:</p> <pre><code>Date Group Data 2014-05-14 09:10:00 A 1 2014-05-14 09:20:00 A 2 2014-05-14 09:30:00 A 3 2014-05-14 09:40:00 A 4 2014-05-14 09:50:00 A 5 2014-05-14 10:00:00 B 1 2014-05-14 10:10:00 B 2 2014-05-14 10:20:00 B 3 2014-05-14 10:30:00 B 4 </code></pre> <p>If this was an oracle database and I wanted to create a lag function grouped by the "Group" column and ordered by the Date I could easily use this function:</p> <pre><code> LAG(Data,1,NULL) OVER (PARTITION BY Group ORDER BY Date ASC) AS Data_lagged </code></pre> <p>This would result in the following Table:</p> <pre><code>Date Group Data Data lagged 2014-05-14 09:10:00 A 1 Null 2014-05-14 09:20:00 A 2 1 2014-05-14 09:30:00 A 3 2 2014-05-14 09:40:00 A 4 3 2014-05-14 09:50:00 A 5 4 2014-05-14 10:00:00 B 1 Null 2014-05-14 10:10:00 B 2 1 2014-05-14 10:20:00 B 3 2 2014-05-14 10:30:00 B 4 3 </code></pre> <p>In pandas I can set the date to be an index and use the shift method:</p> <pre><code>db["Data_lagged"] = db.Data.shift(1) </code></pre> <p>The only issue is that this doesn't group by a column. Even if I set the two columns Date and Group as indexes, I would still get the "5" in the lagged column.</p> <p>Is there a way to implement the equivalent of the Lead and lag functions in Pandas?</p>
23,664,988
2
0
null
2014-05-14 20:51:34.423 UTC
25
2021-10-31 12:03:56.353 UTC
2015-11-25 02:06:50.96 UTC
null
210,945
null
2,474,854
null
1
65
python|pandas
73,446
<p>You could perform a <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#group-by-split-apply-combine" rel="noreferrer">groupby/apply (shift) operation</a>:</p> <pre><code>In [15]: df['Data_lagged'] = df.groupby(['Group'])['Data'].shift(1) In [16]: df Out[16]: Date Group Data Data_lagged 2014-05-14 09:10:00 A 1 NaN 2014-05-14 09:20:00 A 2 1 2014-05-14 09:30:00 A 3 2 2014-05-14 09:40:00 A 4 3 2014-05-14 09:50:00 A 5 4 2014-05-14 10:00:00 B 1 NaN 2014-05-14 10:10:00 B 2 1 2014-05-14 10:20:00 B 3 2 2014-05-14 10:30:00 B 4 3 [9 rows x 4 columns] </code></pre> <p>To obtain the <code>ORDER BY Date ASC</code> effect, you must sort the DataFrame first:</p> <pre><code>df['Data_lagged'] = (df.sort_values(by=['Date'], ascending=True) .groupby(['Group'])['Data'].shift(1)) </code></pre>
33,713,084
Download link for Google Spreadsheets CSV export - with Multiple Sheets
<p>I'm trying to find a link which allows me to download a CSV formatted version of my Google Spreadsheet. Currently I'm using:</p> <pre><code>https://docs.google.com/spreadsheets/d/DOCID/export?format=csv </code></pre> <p>This works great except that it only download the first Sheet. My document has multiple sheets. Does anyone know how to format this link so that it downloads either all the sheets or a specific sheet? Something like:</p> <pre><code>&amp;sheet=all </code></pre> <p>or</p> <pre><code>&amp;sheet=3 </code></pre>
33,727,897
8
1
null
2015-11-14 20:38:51.96 UTC
58
2021-12-20 10:56:14.34 UTC
2020-07-18 21:49:51.487 UTC
null
1,595,451
null
4,364,535
null
1
114
google-sheets|google-visualization|google-sheets-export-url
93,565
<p>Every document in Google Sheets supports the "Chart Tools datasource protocol", which is explained (in a rather haphazard way) in these articles:</p> <ol> <li><a href="https://developers.google.com/chart/interactive/docs/spreadsheets" rel="noreferrer">"Creating a Chart from a Separate Spreadsheet"</a></li> <li><a href="https://developers.google.com/chart/interactive/docs/querylanguage" rel="noreferrer">"Query Language Reference"</a></li> <li><a href="https://developers.google.com/chart/interactive/docs/dev/implementing_data_source" rel="noreferrer">"Implementing the Chart Tools Datasource Protocol"</a></li> </ol> <p>To download a specific sheet as a CSV file, replace <code>{key}</code> with the document's ID and <code>{sheet_name}</code> with the name of the sheet to export:</p> <p><code>https://docs.google.com/spreadsheets/d/{key}/gviz/tq?tqx=out:csv&amp;sheet={sheet_name}</code></p> <p>The datasource protocol is quite flexible. Various other options include:</p> <p><strong>Response Format:</strong> Options include <code>tqx=out:csv</code> (CSV format), <code>tqx=out:html</code> (HTML table), and <code>tqx=out:json</code> (JSON data).</p> <p><strong>Export part of a sheet:</strong> Supply the <code>range={range}</code> option, where the range can be any valid range specifier, e.g. <code>A1:C99</code> or <code>B2:F</code>.</p> <p><strong>Execute a SQL query:</strong> Supply the <code>tq={query}</code> option, such as <code>tq=SELECT a, b, (d+e)*2 WHERE c &lt; 100 AND x = 'yes'</code>.</p> <p><strong>Export textual data:</strong> Supply the <code>headers=0</code> option in case your fields contain textual data, otherwise they might be cut out during export.</p>
42,256,877
How to create chat bubbles like facebook Messenger
<p><a href="https://i.stack.imgur.com/q1zVa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/q1zVa.png" alt="enter image description here"></a></p> <p>How would I create chat bubbles like this. More specifically how to group two ore more consecutive messages by one type of user into a bubble as a whole. For example FOR THE SENDER - the first message has right bottom border a 0, the messages in between have right top,bottom as 0 border radius and the last one has top right 0 border radius . Do I have to use javascript or can it be done using css. </p> <p>HTML structure ca be</p> <pre><code>&lt;ul&gt; &lt;li class="him"&gt;By Other User&lt;/li&gt; &lt;li class="me"&gt;By this User, first message&lt;/li&gt; &lt;li class="me"&gt;By this User, secondmessage&lt;/li&gt; &lt;li class="me"&gt;By this User, third message&lt;/li&gt; &lt;li class="me"&gt;By this User, fourth message&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>What kind of css class/styles should i be using?</p>
42,257,283
4
1
null
2017-02-15 18:01:50.533 UTC
8
2017-02-15 22:00:33.49 UTC
2017-02-15 18:10:35.823 UTC
null
3,090,583
null
3,090,583
null
1
18
html|css|chat
29,231
<p>This is a rather basic example but it should explain all of the fundamentals you require.</p> <p>Most of the solution lies within <code>+</code> <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors" rel="noreferrer">adjacent sibling selector</a>. In this case, it's used to apply a different border radius to multiple messages in a row from the same person.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>ul{ list-style: none; margin: 0; padding: 0; } ul li{ display:inline-block; clear: both; padding: 20px; border-radius: 30px; margin-bottom: 2px; font-family: Helvetica, Arial, sans-serif; } .him{ background: #eee; float: left; } .me{ float: right; background: #0084ff; color: #fff; } .him + .me{ border-bottom-right-radius: 5px; } .me + .me{ border-top-right-radius: 5px; border-bottom-right-radius: 5px; } .me:last-of-type { border-bottom-right-radius: 30px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li class="him"&gt;By Other User&lt;/li&gt; &lt;li class="me"&gt;By this User, first message&lt;/li&gt; &lt;li class="me"&gt;By this User, secondmessage&lt;/li&gt; &lt;li class="me"&gt;By this User, third message&lt;/li&gt; &lt;li class="me"&gt;By this User, fourth message&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
6,002,811
"call-cc" patterns in Scala?
<p>I found a good <a href="http://repository.readscheme.org/ftp/papers/PLoP2001_dferguson0_1.pdf" rel="noreferrer">article</a>, about <code>call with current continuation</code> patterns. As I understand, they use Scheme and <code>undelimited continuations</code>. Can the patterns from the article be implemented in Scala? Is there any article about <code>delimited continuations</code> patterns in Scala ?</p>
6,004,732
2
0
null
2011-05-14 15:30:05.487 UTC
9
2016-04-20 11:17:54.92 UTC
2011-05-14 15:50:09.433 UTC
null
650,444
null
650,444
null
1
14
scala|continuations
1,170
<p>Yes, they absolutely can. <code>callCC</code> looks like this in Scala:</p> <pre><code>def callCC[R, A, B](f: (A =&gt; Cont[R, B]) =&gt; Cont[R, A]): Cont[R, A] = Cont(k =&gt; f(a =&gt; Cont(_ =&gt; k(a))) run k) </code></pre> <p>Where <code>Cont</code> is a data structure that captures a continuation:</p> <pre><code>case class Cont[R, A](run: (A =&gt; R) =&gt; R) { def flatMap[B](f: A =&gt; Cont[R, B]): Cont[R, B] = Cont(k =&gt; run(a =&gt; f(a) run k)) def map[B](f: A =&gt; B): Cont[R, B] = Cont(k =&gt; run(a =&gt; k(f(a)))) } </code></pre> <p>Here's how you might use it to simulate checked exceptions:</p> <pre><code>def divExcpt[R](x: Int, y: Int, h: String =&gt; Cont[R, Int]): Cont[R, Int] = callCC[R, Int, String](ok =&gt; for { err &lt;- callCC[R, String, Unit](notOK =&gt; for { _ &lt;- if (y == 0) notOK("Denominator 0") else Cont[R, Unit](_(())) r &lt;- ok(x / y) } yield r) r &lt;- h(err) } yield r) </code></pre> <p>You would call this function as follows:</p> <pre><code>scala&gt; divExcpt(10, 2, error) run println 5 scala&gt; divExcpt(10, 0, error) run println java.lang.RuntimeException: Denominator 0 </code></pre>
5,824,639
Monitoring when a radio button is unchecked
<p>I have an application that shows one div when a certain radio button is selected and then hides that div when the radio button is unselected. The problem is that the change event attached to the radio button only gets called when the radio button is checked, not when another one is checked (unchecking the previous one). My current code is as follows:</p> <pre><code>&lt;form name="newreport" action="#buildurl('report.filters')#" method="post"&gt; &lt;dl class="oneColumn"&gt; &lt;dt class="first"&gt;&lt;label for="txt_name"&gt;Name&lt;/label&gt;&lt;/dt&gt; &lt;dd&gt;&lt;input type="text" name="name" id="txt_name" class="text" /&gt;&lt;/dd&gt; &lt;dt&gt;&lt;strong&gt;Type&lt;/strong&gt;&lt;/dt&gt; &lt;dt&gt;&lt;input type="radio" name="type" id="rdo_list" value="list" checked="checked" /&gt;&lt;label for="rdo_type" style="display:inline;"&gt;List&lt;/label&gt;&lt;/dt&gt; &lt;dd&gt;List a group of records&lt;/dd&gt; &lt;dt&gt;&lt;input type="radio" name="type" id="rdo_fields" value="fields" /&gt;&lt;label for="rdo_fields" style="display:inline;"&gt;Field Breakdown&lt;/label&gt;&lt;/dt&gt; &lt;dd&gt;Breaks down distinct field values for comparison&lt;/dd&gt; &lt;dt&gt;&lt;input type="radio" name="type" id="rdo_history" value="history" /&gt;&lt;label for="rdo_history" style="display:inline;"&gt;Historical Comparison&lt;/label&gt;&lt;/dt&gt; &lt;dd&gt;Provides record changes over a group of years for growth comparisons&lt;/dd&gt; &lt;dt&gt;&lt;input type="radio" name="type" id="rdo_breakdown" value="breakdown" /&gt;&lt;label for="rdo_breakdown" style="display:inline;"&gt;Student Breakdown&lt;/label&gt;&lt;/dt&gt; &lt;dd&gt;Breaks down students by school, district or grade&lt;/dd&gt; &lt;div class="reportyear"&gt; &lt;dt&gt;&lt;label for="txt_year"&gt;Year to Report&lt;/label&gt;&lt;/dt&gt; &lt;dd&gt;&lt;input type="text" name="year" id="txt_year" class="text" value="#year(Rc.yearstart)#" /&gt;&lt;/dd&gt; &lt;/div&gt; &lt;div class="date-spans" style="display:none;"&gt; &lt;dt&gt;&lt;label for="txt_yearstart"&gt;Year Start&lt;/label&gt;&lt;/dt&gt; &lt;dd&gt;&lt;input type="text" name="yearstart" id="txt_yearstart" class="text" value="#evaluate(year(Rc.yearstart)-5)#" /&gt;&lt;/dd&gt; &lt;dt&gt;&lt;label for="txt_yearend"&gt;Year End&lt;/label&gt;&lt;/dt&gt; &lt;dd&gt;&lt;input type="text" name="yearend" id="txt_yearend" class="text" value="#year(Rc.yearstart)#" /&gt;&lt;/dd&gt; &lt;/div&gt; &lt;/dl&gt; &lt;/form&gt; &lt;script type="text/javascript"&gt; $(function(){ $('##rdo_history').change(function(e){ var isChecked = $(this).attr(checked); var $datespan = $('form .date-spans'); var $year = $('form .reportyear'); if(isChecked){ $year.css({display:'none'}); $datespan.fadeIn('fast'); }else{ $datespan.css({display:'none'}); $year.fadeIn('fast'); } }); }); &lt;/script&gt; </code></pre> <p>It seems like a pretty simple script, but the event only gets called on the check event, not on the uncheck event. Can anyone tell me why?</p>
5,824,701
2
1
null
2011-04-28 20:35:45.417 UTC
5
2019-09-05 15:38:34.35 UTC
2019-09-05 15:38:34.35 UTC
null
4,370,109
null
526,895
null
1
49
jquery|events|jquery-events
65,216
<p>Handle the change event on the radio group, not each button. Then look to see which one is checked.</p> <p>Here's is some untested code that hopefully shows what I'm talking about :)...</p> <pre><code>$("input[name='type']").change(function(e){ if($(this).val() == 'history') { $year.css({display:'none'}); $datespan.fadeIn('fast'); } else { $datespan.css({display:'none'}); $year.fadeIn('fast'); } }); </code></pre>
19,739,507
Nested if else in Twig
<p>Is there any way to implement nested if else functionality in twig? I have tried the following but it isn't working:</p> <pre><code>&lt;body {% if page|default('login') == 'login' %} class="login" {% else if( page == 'other') %} class="login" {% else %} class="noclass" {% endif %}&gt; &lt;/body&gt; </code></pre>
19,739,722
2
0
null
2013-11-02 06:20:30.927 UTC
3
2017-09-26 17:25:35.947 UTC
2017-09-26 17:25:35.947 UTC
null
576,746
null
1,931,097
null
1
32
symfony|twig|conditional
89,503
<p><code>elseif</code> needs to be single word tag/keyword and expression shouldn't have parenthesis same as <code>if</code> expression. </p> <p><a href="http://twig.sensiolabs.org/doc/tags/if.html" rel="noreferrer">http://twig.sensiolabs.org/doc/tags/if.html</a></p> <pre><code>&lt;body {% if page|default('login') == 'login' %} class="login" {% elseif page == 'other' %} class="login" {% else %} class="noclass" {% endif %}&gt; &lt;/body&gt; </code></pre>
34,078,296
HttpClient PostAsync() never return response
<p>My problem is very similar to this <a href="https://stackoverflow.com/questions/20734575/wp8-httpclient-postasync-never-returns-result">question</a> here. I have an <code>AuthenticationService</code> class that makes an <code>HttpClient</code> <code>PostAsync()</code> and never returns the result when I am running it from the ASP project, but when I implement it in a Console app it works just fine.</p> <p>This is my Authentication Service class:</p> <pre><code>public class AuthenticationService : BaseService { public async Task&lt;Token&gt; Authenticate (User user, string url) { string json = JsonConvert.SerializeObject(user); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await _client.PostAsync(url, content); string responseContent = await response.Content.ReadAsStringAsync(); Token token = JsonConvert.DeserializeObject&lt;Token&gt;(responseContent); return token; } } </code></pre> <p>And it is here where it hangs: <code>HttpResponseMessage response = await _client.PostAsync(url, content);</code></p> <p>Here is my Controller calling the service:</p> <pre><code>public ActionResult Signin(User user) { // no token needed to be send - we are requesting one Token token = _authenticationService.Authenticate(user, ApiUrls.Signin).Result; return View(); } </code></pre> <p>Here is an example of how I have been testing the service using a Console app, and it runs just fine.</p> <pre><code>class Program { static void Main() { AuthenticationService auth = new AuthenticationService(); User u = new User() { email = "[email protected]", password = "password123" }; Token newToken = auth.Authenticate(u, ApiUrls.Signin).Result; Console.Write("Content: " + newToken.user._id); Console.Read(); } } </code></pre>
34,079,103
3
0
null
2015-12-03 23:32:27.967 UTC
2
2020-01-27 17:03:13.623 UTC
2020-01-27 16:21:31.207 UTC
null
4,404,544
null
4,142,653
null
1
29
c#|asp.net|asynchronous|httpclient
34,034
<p>Since you are using <code>.Result</code>, this will end up causing a deadlock in your code. The reason this is working in a console application is because console applications don't have contexts, but ASP.NET apps do (see <a href="http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html" rel="noreferrer">Stephen Cleary's Don't Block on Async Code</a>). You should make the <code>Signin</code> method in your controller <code>async</code> and <code>await</code> the call to <code>_authenticationService.Authenticate</code> to resolve the deadlock issue.</p>
21,392,675
CALayer Antialiasing not as good as UIView antialiasing
<p>I've been trying to animate circle drawing using CALayer. It all works well, but the problem is - drawn circle is not antialiased enough. It has a bit too rough borders, (or blurred if rasterize is used). (AntiAliasing is enabled)</p> <p>Tried also:</p> <blockquote> <p>edgeAntialiasingMask = kCALayerLeftEdge | kCALayerRightEdge | kCALayerBottomEdge | kCALayerTopEdge;</p> </blockquote> <p>to no avail.</p> <p>Here is an example how it looks like without rasterization: <img src="https://i.stack.imgur.com/5oTPk.png" alt="enter image description here"></p> <p>And here is an example with rasterization: (tried values from 1.0 till 4.0 (just to be sure. Result - the same.))</p> <p><img src="https://i.stack.imgur.com/p5P5g.png" alt="enter image description here"></p> <p>And here is the same circle, but drawn inside UIView drawrect:</p> <p><img src="https://i.stack.imgur.com/4aA0L.png" alt="enter image description here"></p> <p>You can see, that circle drawn using UIView drawrect is looking much better.</p> <p>The reason I cannot use UIView is because I need to animate circle filling. Using CALayer it is really easy, but to do the same on UIView, I don't really know if it is even possible. (I could try to launch drawrect: every 1/60 seconds, but I think it will get laggy, as it is not intended that way).</p> <p><strong>So - does anyone have any solution how I could make drawn circles/lines on CALayer look the same as drawn on UIView?</strong> </p>
21,392,863
1
1
null
2014-01-27 22:04:41.667 UTC
9
2014-01-27 22:18:00.547 UTC
null
null
null
null
894,671
null
1
19
ios|objective-c|uiview|calayer
5,468
<p>I've had issues with pixelated drawing in a <code>CALayer</code> on retina devices before. (I'm assuming you're seeing the issue on retina devices) Doing the following fixed the issue I was experiencing:</p> <pre><code>layer.contentsScale = [[UIScreen mainScreen] scale]; </code></pre> <p>You shouldn't need to deal with rasterization or antialiasing. In my own code, I had initially implemented drawing something to a <code>UIView</code> that I later changed to be drawn in a <code>CALayer</code>, and simply setting the <code>contentsScale</code> property made both draw identically.</p>
46,811,149
Multiple commands in package.json
<p>This command: <code>&quot;start&quot;: &quot;node server/server.js&quot;</code> starts my server, but before running this I also want a command to run automatically: <code>'webpack'</code>.</p> <p>I want to build a script that can be run with <code>npm run someCommand</code> - it should first run <code>webpack</code> in the terminal, followed by <code>node server/server.js</code>.</p> <p>(I know how configure this with gulp, but I don't want to use it)</p>
46,811,356
5
0
null
2017-10-18 13:17:52.063 UTC
13
2022-05-31 07:56:36.133 UTC
2021-08-14 21:28:11.547 UTC
null
498,403
null
8,096,318
null
1
75
node.js|package.json
79,066
<p>If I understood you correctly, you want firstly run webpack and after compile run nodejs. Maybe try this:</p> <pre><code>"start": "webpack &amp;&amp; node server/server.js" </code></pre>
43,405,426
Why use Bootstrap's .w-100 class to split a row's columns into two rows, when you could just make two rows?
<p>On this page in the Bootstrap documentation at <a href="https://v4-alpha.getbootstrap.com/layout/grid/#equal-width-multi-row" rel="noreferrer">https://v4-alpha.getbootstrap.com/layout/grid/#equal-width-multi-row</a> they give this example:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col"&gt;col&lt;/div&gt; &lt;div class="col"&gt;col&lt;/div&gt; &lt;div class="w-100"&gt;&lt;/div&gt; &lt;div class="col"&gt;col&lt;/div&gt; &lt;div class="col"&gt;col&lt;/div&gt; &lt;/div&gt; </code></pre> <p>This creates two rows with two equal-sized columns in each row. However, you can achieve this just by creating two rows:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col"&gt;col&lt;/div&gt; &lt;div class="col"&gt;col&lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col"&gt;col&lt;/div&gt; &lt;div class="col"&gt;col&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Is there any difference between using the <code>.w-100</code> CSS class and just creating two rows instead?</p>
43,413,034
1
0
null
2017-04-14 04:58:31.953 UTC
13
2021-03-11 04:50:09.287 UTC
2018-02-28 15:47:50.61 UTC
null
171,456
null
1,893,164
null
1
22
twitter-bootstrap|bootstrap-4|twitter-bootstrap-4
21,173
<p>In this specific case, there is no difference.</p> <p>However, keeping <strong>the cols in a single <code>.row</code> is generally better</strong> for these reasons...</p> <p><strong>Column ordering</strong></p> <p>Suppose you instead want to switch the order of the first and last columns on <code>md</code> and up. This would not be possible with separate <code>.row</code> containers. Keeping all the <code>col</code> in a single <code>.row</code> makes it possible.</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col flex-md-last"&gt;col 1&lt;/div&gt; &lt;div class="col"&gt;col 2&lt;/div&gt; &lt;div class="w-100"&gt;&lt;/div&gt; &lt;div class="col"&gt;col 3&lt;/div&gt; &lt;div class="col flex-md-first"&gt;col 4&lt;/div&gt; &lt;/div&gt; </code></pre> <hr> <p><strong>Responsive layouts</strong></p> <p>Another example. Suppose you instead wanted a layout of:<br></p> <ul> <li>4 cols across 1 row on <code>md</code> width (4x1)</li> <li>2 cols across 2 rows on <code>xs</code> width (2x2)</li> </ul> <p>Again, this would not be possible with separate <code>.row</code> divs. But, since the <code>w-100</code> can be used responsively, this is possible by keeping all the cols in a single row.</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col col-md-3"&gt;col 1&lt;/div&gt; &lt;div class="col col-md-3"&gt;col 2&lt;/div&gt; &lt;div class="w-100 hidden-md-up"&gt;&lt;/div&gt; &lt;div class="col col-md-3"&gt;col 3&lt;/div&gt; &lt;div class="col col-md-3"&gt;col 4&lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="http://www.codeply.com/go/5fVEzEq16H" rel="noreferrer">Demo of the layouts</a></p>
8,448,019
Prevent NA from being used in a lm regresion
<p>I have a vector Y containing future returns and a vector X contain current returns. The last Y element is NA, as the last current return is also the very end of the available series.</p> <pre><code>X = { 0.1, 0.3, 0.2, 0.5 } Y = { 0.3, 0.2, 0.5, NA } Other = { 5500, 222, 523, 3677 } lm(Y ~ X + Other) </code></pre> <p>I want to make sure that the last element of each series is <strong>not</strong> included in the regression. I read the na.action documentation but I'm not clear if this is the default behaviour.</p> <p>For cor(), is this the correct solution to exclude X[4] and Y[4] from the calculation?</p> <pre><code>cor(X, Y, use = "pairwise.complete.obs") </code></pre>
8,448,077
1
0
null
2011-12-09 15:50:55.423 UTC
null
2017-03-26 19:24:11.217 UTC
2017-03-26 19:24:11.217 UTC
null
792,066
null
382,271
null
1
8
r|lm
39,947
<p>The factory-fresh default for <code>lm</code> is to disregard observations containing <code>NA</code> values. Since this could be overridden using global options, you might want to explicitly set <code>na.action</code> to <code>na.omit</code>:</p> <pre><code>&gt; summary(lm(Y ~ X + Other, na.action=na.omit)) Call: lm(formula = Y ~ X + Other, na.action = na.omit) [snip] (1 observation deleted due to missingness) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ </code></pre> <p>As to your second question <code>cor(X,Y,use='pairwise.complete.obs')</code> is correct. Since there are only two variables, <code>cor(X,Y,use='complete.obs')</code> would also produce the expected result.</p>
8,806,673
HTML : How to retain formatting in textarea?
<ul> <li>I am using HTML textarea for user to input some data and save that to App Engine's model</li> <li>The problem is that when I retrieve the content it is just text and all formatting is gone </li> <li>The reason is because in textarea there is no formatting that we can make </li> </ul> <p>Question: </p> <ul> <li>is there any way to retain the format that user provides?</li> <li>is there any other element(other than textarea), that i'll have to use?(which one?)</li> </ul> <p>P.S I am very new to area of web development and working on my first project </p> <p>Thank you</p>
8,806,802
4
0
null
2012-01-10 16:25:36.49 UTC
7
2020-10-26 11:55:31.283 UTC
null
null
null
null
379,235
null
1
18
html|google-app-engine|formatting|textarea
41,515
<p>What you want is a <a href="http://en.wikipedia.org/wiki/Online_rich-text_editor" rel="noreferrer">Rich Text Editor</a>. The standard HTML <code>&lt;textarea&gt;</code> tag only accepts plain text (even if the text is or includes HTML markup). There are a lot of example out there (including some listed on the page linked) but I would highly recommend using a prepackaged one for this. Coding your own is fairly complicated for people who are new, and even for a lot who have some experience. Both <a href="http://www.tinymce.com/" rel="noreferrer">TinyMCE</a> and <a href="http://ckeditor.com/" rel="noreferrer">CKEditor</a> are very common ones, but there are many others as well.</p>
8,522,813
How to set root_url
<p>In my Ruby on Rails 3.1 app I have a link like this: </p> <pre><code>&lt;%= link_to 'Home', root_url %&gt; </code></pre> <p>On My dev. machine it renders a link with "localhost:3000". On production it renders a link with an IP Address like this "83.112.12.27:8080". I would like to force rails to render the domain address instead of the IP Address. How can I set root_url?</p>
8,522,946
3
0
null
2011-12-15 15:52:14.197 UTC
4
2013-05-30 13:59:52.45 UTC
null
null
null
null
661,327
null
1
25
ruby-on-rails-3
40,709
<p>In your routes set:</p> <pre><code> root :to =&gt; 'welcome#index' </code></pre> <p>and in your links set:</p> <pre><code>&lt;%=link_to "Home", root_path %&gt; </code></pre> <p>It will render</p> <pre><code>&lt;a href="/"&gt;Home&lt;/a&gt; </code></pre> <p>So in your localhost It'd take you to</p> <p><code>http://localhost:3000/</code></p> <p>and in your production server It'd take you to</p> <p><code>http://yourdomian.com/</code></p> <p>and the <code>routes.rb</code> will render the <code>index</code> action of the controller <code>welcome</code> by default.</p> <p>PS. you also need to remove <code>index.html</code> from <code>public</code> directory in order to use this.</p> <hr> <p>UPDATE</p> <p>A little bit more on routing:</p> <p><a href="http://guides.rubyonrails.org/routing.html" rel="noreferrer">Rails Routing from the Outside In</a></p>
8,619,869
XPath wildcard in attribute value
<p>I have the following XPath to match attributes of the class span:</p> <pre><code>//span[@class='amount'] </code></pre> <p>I want to match all elements that have the class attribute of "amount" but also may have other classes as well. I thought I could do this:</p> <pre><code>//span[@class='*amount*'] </code></pre> <p>but that doesn't work...how can I do this?</p>
8,619,923
2
0
null
2011-12-23 19:24:26.403 UTC
7
2020-04-13 18:23:19.433 UTC
2011-12-23 19:33:12.543 UTC
null
1,583
null
812,161
null
1
38
c#|xpath|html-agility-pack
30,721
<p>Use the following expression:</p> <pre><code>//span[contains(concat(' ', @class, ' '), ' amount ')] </code></pre> <p>You could use <code>contains</code> on its own, but that would also match classes like <code>someamount</code>. Test the above expression on the following input:</p> <pre><code>&lt;root&gt; &lt;span class="test amount blah"/&gt; &lt;span class="amount test"/&gt; &lt;span class="test amount"/&gt; &lt;span class="amount"/&gt; &lt;span class="someamount"/&gt; &lt;/root&gt; </code></pre> <p>It will select the first four <code>span</code> elements, but not the last one.</p>
57,553,821
Is there a way to include Multiple Children inside a Container?
<p>This is full code:</p> <pre class="lang-dart prettyprint-override"><code>class Application extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new Scaffold( body: new Container( color: Color(0xff258DED), height: 400.0, alignment: Alignment.center, child: new Container( height: 200.0, width: 200.0, decoration: new BoxDecoration( image: DecorationImage( image: new AssetImage('assets/logo.png'), fit: BoxFit.fill ), shape: BoxShape.circle ), ), child: new Container( child: new Text('Welcome to Prime Message', textAlign: TextAlign.center, style: TextStyle( fontFamily: 'Aleo', fontStyle: FontStyle.normal, fontWeight: FontWeight.bold, fontSize: 25.0, color: Colors.white ), ), ), ), ), ); } } </code></pre> <p>I tried to add a <code>Container</code> on top and then added two children inside it. First child works fine, but second child giving me error like "the argument for the named parameter 'child' was already specified".</p>
57,553,958
4
1
null
2019-08-19 09:22:16.287 UTC
4
2022-02-08 19:06:23.053 UTC
2019-08-19 09:32:38.827 UTC
null
6,509,751
null
11,662,344
null
1
18
flutter|dart|flutter-layout
55,095
<p>If you try to put more than one child in a container, you want to look as <code>Row()</code> or <code>Column()</code> class for linear ones. <code>Stack()</code> is used if you want to have floating children on top of each other.</p> <p>Eg:</p> <pre><code>class Application extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new Scaffold( body: new Container( color: Color(0xff258DED), height: 400.0, alignment: Alignment.center, child: new Column( children: [ new Container( height: 200.0, width: 200.0, decoration: new BoxDecoration( image: DecorationImage( image: new AssetImage('assets/logo.png'), fit: BoxFit.fill ), shape: BoxShape.circle ), ), new Container( child: new Text('Welcome to Prime Message', textAlign: TextAlign.center, style: TextStyle( fontFamily: 'Aleo', fontStyle: FontStyle.normal, fontWeight: FontWeight.bold, fontSize: 25.0, color: Colors.white ), ), ), ], ), ), ), ); } } </code></pre>
26,804,153
OpenCL: work group concept
<p>I don't really understand the purpose of Work-Groups in OpenCL.</p> <p>I understand that they are a group of Work Items (supposedly, hardware threads), which ones get executed in parallel.</p> <p>However, why is there this need of coarser subdivision ? Wouldn't it be OK to have only the grid of threads (and, <em>de facto</em>, only one W-G)?</p> <p>Should a Work-Group exactly map to a physical core ? For example, the TESLA c1060 card is said to have 240 cores. How would the Work-Groups map to this??</p> <p>Also, as far as I understand, work-items inside a work group can be synchronized thanks to memory fences. Can work-groups synchronize or is that even needed ? Do they talk to each other via shared memory or is this only for work items (not sure on this one)?</p>
26,812,146
4
0
null
2014-11-07 15:07:47.043 UTC
10
2020-06-22 11:45:29.89 UTC
2016-04-20 18:46:54.753 UTC
null
41,071
null
2,098,831
null
1
30
parallel-processing|opencl
20,078
<p>Part of the confusion here I think comes down to terminology. What GPU people often call cores, aren't really, and what GPU people often call threads are only in a certain sense.</p> <p><strong>Cores</strong> A core, in GPU marketing terms may refer to something like a CPU core, or it may refer to a single lane of a SIMD unit - in effect a single core x86 CPU would be four cores of this simpler type. This is why GPU core counts can be so high. It isn't really a fair comparison, you have to divide by 16, 32 or a similar number to get a more directly comparable core count.</p> <p><strong>Work-items</strong> Each work-item in OpenCL is a thread in terms of its control flow, and its memory model. The hardware may run multiple work-items on a single thread, and you can easily picture this by imagining four OpenCL work-items operating on the separate lanes of an SSE vector. It would simply be compiler trickery that achieves that, and on GPUs it tends to be a mixture of compiler trickery and hardware assistance. OpenCL 2.0 actually exposes this underlying hardware thread concept through sub-groups, so there is another level of hierarchy to deal with.</p> <p><strong>Work-groups</strong> Each work-group contains a set of work-items that must be able to make progress in the presence of barriers. In practice this means that it is a set, all of whose state is able to exist at the same time, such that when a synchronization primitive is encountered there is little overhead in switching between them and there is a guarantee that the switch is possible. </p> <p>A work-group must map to a single compute unit, which realistically means an entire work-group fits on a single entity that CPU people would call a core - CUDA would call it a multiprocessor (depending on the generation), AMD a compute unit and others have different names. This locality of execution leads to more efficient synchronization, but it also means that the set of work-items can have access to locally constructed memory units. They are expected to communicate frequently, or barriers wouldn't be used, and to make this communication efficient there may be local caches (similar to a CPU L1) or scratchpad memories (local memory in OpenCL).</p> <p>As long as barriers are used, work-groups can synchronize internally, between work-items, using local memory, or by using global memory. Work-groups cannot synchronize with each other and the standard makes no guarantees on forward progress of work-groups relative to each other, which makes building portable locking and synchronization primitives effectively impossible.</p> <p>A lot of this is due to history rather than design. GPU hardware has long been designed to construct vector threads and assign them to execution units in a fashion that optimally processes triangles. OpenCL falls out of generalising that hardware to be useful for other things, but not generalising it so much that it becomes inefficient to implement.</p>
909,933
SQL Server export to Excel with OPENROWSET
<p>I am successfully exporting to excel with the following statement:</p> <pre><code>insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\template.xls;', 'SELECT * FROM [SheetName$]') select * from myTable </code></pre> <p>Is there any standard way to use this template specifying a new name for the excel sheet so that the template never gets written to or do I have to come up with some work-around?</p> <p>What's the best way to do this in people experience?</p>
910,199
3
1
null
2009-05-26 10:11:45.137 UTC
3
2020-07-29 03:54:49.707 UTC
2016-05-09 13:03:38.57 UTC
null
4,519,059
null
1,311,500
null
1
4
sql|sql-server|excel|export-to-excel|openrowset
54,694
<p>You'd have to use dynamic SQL. <code>OPENROWSET</code> etc only allows literals as parameters.</p> <pre><code>DECLARE @myfile varchar(800) SET @myfile = 'C:\template.xls' EXEC (' insert into OPENROWSET(''Microsoft.Jet.OLEDB.4.0'', ''Excel 8.0;Database=' + @myfile + ';'', ''SELECT * FROM [SheetName$]'') select * from myTable ') </code></pre> <blockquote> <p>Remember: the path is relative to where SQL Server is running</p> </blockquote>
594
cx_Oracle: How do I iterate over a result set?
<p>There are several ways to iterate over a result set. What are the tradeoff of each?</p>
595
3
1
null
2008-08-03 01:15:08.507 UTC
10
2016-10-15 20:47:11.027 UTC
2016-10-14 18:15:27.42 UTC
Mark Harrison
116
null
116
null
1
55
python|sql|database|oracle|cx-oracle
57,408
<p>The canonical way is to use the built-in cursor iterator.</p> <pre><code>curs.execute('select * from people') for row in curs: print row </code></pre> <hr> <p>You can use <code>fetchall()</code> to get all rows at once.</p> <pre><code>for row in curs.fetchall(): print row </code></pre> <p>It can be convenient to use this to create a Python list containing the values returned:</p> <pre><code>curs.execute('select first_name from people') names = [row[0] for row in curs.fetchall()] </code></pre> <p>This can be useful for smaller result sets, but can have bad side effects if the result set is large.</p> <ul> <li><p>You have to wait for the entire result set to be returned to your client process.</p></li> <li><p>You may eat up a lot of memory in your client to hold the built-up list.</p></li> <li><p>It may take a while for Python to construct and deconstruct the list which you are going to immediately discard anyways.</p></li> </ul> <hr> <p>If you know there's a single row being returned in the result set you can call <code>fetchone()</code> to get the single row.</p> <pre><code>curs.execute('select max(x) from t') maxValue = curs.fetchone()[0] </code></pre> <hr> <p>Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator.</p> <pre><code>row = curs.fetchone() while row: print row row = curs.fetchone() </code></pre>
5,914,110
How to get the index of an <li> in a <ul>
<blockquote> <p><strong>Possible Duplicates:</strong><br> <a href="https://stackoverflow.com/questions/2048718/how-to-get-index-of-li-element">How to get index of &lt;li&gt; element</a><br> <a href="https://stackoverflow.com/questions/3204349/jquery-get-the-index-of-a-element-with-a-certain-class">jQuery - get the index of a element with a certain class</a> </p> </blockquote> <p>I have:</p> <pre><code>&lt;ul id="parent"&gt; &lt;li id="li1"&gt;li1&lt;/li&gt; &lt;li id="li2"&gt;li2&lt;/li&gt; &lt;li id="li3"&gt;li3&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>There are some other <code>&lt;ul&gt;</code> and <code>&lt;li&gt;</code> tags elsewhere. </p> <p>I want to get the index of <strong>li2</strong> which is in the <code>&lt;ul&gt;</code> with id <strong>parent</strong> using jQuery</p>
5,914,150
3
3
null
2011-05-06 16:11:36.583 UTC
5
2011-05-06 16:23:35.773 UTC
2017-05-23 11:54:27.82 UTC
null
-1
null
695,663
null
1
25
javascript|jquery|jquery-ui
58,569
<p><strong>OLD</strong> simple answer: <code>$('ul#parent li:eq(1)').index()</code></p> <p><strong>NEW</strong> <code>$('#li2').index()</code></p>
5,946,659
What is Sharepoint development from a developers point of view?
<p>I hear a lot of talk about Sharepoint these days, but I'm having problems grasping exactly what it is through all the enterprise and marketing jargon. Trying it out hands-on seems too much of a hassle as well (several heavy software packages that you can't just download for free).</p> <p>Could someone give a good developer-to-developer description of what Sharepoint is? I'd especially like to know what Sharepoint developers generally do. </p>
5,948,618
3
5
null
2011-05-10 07:32:20.57 UTC
15
2017-03-09 09:02:03.04 UTC
2012-12-28 01:58:44.663 UTC
null
237,838
null
39,321
null
1
45
sharepoint
71,955
<p><strong>== Edit 2017 ==</strong> </p> <p>This is a fairly old post and SharePoint have changed a lot the past years. Most parts of the original post are still valid but some would only apply if you do on premise installations where the future of SharePoint seem to lean towards SharePoint Online. That being said, most functionality are still there with some improvements.</p> <p><strong>== Original post ==</strong></p> <p>SharePoint is a very complex CMS (Content Management System) with a lot of nice BSS (Business support system) features. There are so many advantages of it that it's hard to limit what to mention. However, some of the obvious stuff would be that you can mix so many "environments" at the same server, these environments are separated as sites.</p> <p>What do I mean by environments?</p> <p>Let's say you run a logistics company and are sick of having so many different systems just to keep your business up and running. Many of the systems also have different providers so the ecosystem around the company gets equally complex as well, here comes SharePoint to the rescue since it's a system that actually can host all required environments. In example.</p> <ul> <li>External web page, hosted either by SharePoint or by an integrated web page</li> <li>Order management</li> <li>Customer support and ticketing</li> <li>Item handling of freight</li> <li>Intranet sites with document management</li> </ul> <p>Each and every of these environments can benefit from SharePoints built-in features like workflows and custom content types.</p> <p>I'd say that the foremost reason to choose SharePoint would be it's versatility of storing different types of data. It's not a system to choose if you are planning one million transactions each second even if the performance can be greatly upgraded with several servers in a farm. </p> <p>My point of view as a developer is that SharePoint is pretty much all about the lists, libraries and the metadata store since it's where most of the data is kept. This is something you need to learn and to understand how to structure your data and how you'll implement your information model.</p> <p>The most common assignment in my world would be integration SharePoint with an external CMS, like EPIServer or Joomla, to set up an integration where the visitors shall be able to send messages from the web directly into SharePoint. These assignments then trails into creating a workflow what will happend with this message when it's received by the customer support / sales staff or whatever, all the way until the errand can be closed. When done with this I might build some graphs in a custom web part using mschart displaying some sales data or statistics of support errands. Currently im planing the data structure using SharePoint as a webshop. And there you go again, versatility!</p> <p>There is also a very powerful API in SharePoint if you are into integrations. I am myself involved in the production of an ADO.NET Connector for SharePoint which turns SharePoint into a SQL server enabling developers to skip using CAML. And, there are plenty of other cool tools out there.</p> <p>Let's not forget the second biggest advantage of using SharePoint. You can focus on forward development, the backend is already there.</p>
6,079,253
Running Maven Exec Plugin Inside Eclipse
<p>Using m2eclipse, what is the simplest way to use the <a href="http://mojo.codehaus.org/exec-maven-plugin/" rel="noreferrer">Codehaus Mojo Exec Plugin</a> to launch my project <em>without leaving eclipse</em>? So far on the pom plugins screen I have set up the org.codehuas.mojo plugin.</p> <p>Specifically, I would like to execute the following from inside eclipse:</p> <pre><code>mvn exec:java -Dexec.mainClass=org.sonatype.mavenbook.weather.Main </code></pre>
6,083,254
4
0
null
2011-05-21 02:36:23.707 UTC
9
2019-10-18 10:20:26.05 UTC
null
null
null
null
355,325
null
1
17
eclipse|maven|maven-plugin|m2eclipse
31,862
<ol> <li>go to Run menu -> run configurations</li> <li>you should see a "Maven Build" item on the list of the left, double click it to create a new configuration of that type</li> <li>name it as you want</li> <li>browse workspace to select the base directory of your project</li> <li>set exec:java as the goal, and exec.mainClass / yourClass as parameters. </li> </ol> <p>This is how it looks on my set-up:</p> <p><img src="https://i.stack.imgur.com/oN4CA.png" alt="enter image description here"></p> <p>PD: if you have set the mainClass argument on the pom.xml, then the parameter from the execution will be disregarded.</p>
5,773,993
Catch all type exceptions programming Android
<p>I'm developing an application for Android OS. Since this is my first application, I think I've committed some programming mistakes cause I hardly can trace bugs back to their causes. Thus, I was guessing, while i'm trying to fix bugs, is there a way to catch ALL types of exception in my entire activity lifecycle with one try-catch?</p> <p>That would be awesome, i'm getting bored watching my galaxy S say :"Sorry the application App has stopped unexpectly" :(</p>
5,774,131
4
0
null
2011-04-24 23:41:36.193 UTC
5
2015-05-10 06:23:52.563 UTC
null
null
null
null
723,054
null
1
19
java|android|exception|exception-handling
42,670
<p>I really, really don't recommend this...</p> <pre><code>try { ... } catch (Exception e) { // This will catch any exception, because they are all descended from Exception } </code></pre> <p>Are you looking at your stack traces to debug your issues? It should not be hard to track them down. Look at LogCat and review the big block of red text to see which method caused your crash and what your error was.</p> <p>If you catch all your errors this way, your program is not going to behave as expected, and you will not get error reports from Android Market when your users report them.</p> <p>You can use an UncaughtExceptionHandler to possibly prevent some crashes. I use one, but only to print stack traces to a file, for when I'm debugging an app on a phone away from my computer. But I pass on the uncaught exception to the default Android UncaughtExceptionHandler after I've done that, because I want Android to be able to handle it correctly, and give the user the opportunity to send me a stack trace.</p>
5,823,572
ValueError: unknown url type in urllib2, though the url is fine if opened in a browser
<p>Basically, I am trying to download a URL using urllib2 in python.</p> <p>the code is the following:</p> <pre><code>import urllib2 req = urllib2.Request('www.tattoo-cover.co.uk') req.add_header('User-agent','Mozilla/5.0') result = urllib2.urlopen(req) </code></pre> <p>it outputs ValueError and the program crushes for the URL in the example. When I access the url in a browser, it works fine.</p> <p>Any ideas how to handle the problem?</p> <p><strong>UPDATE:</strong></p> <p>thanks for Ben James and sth the problem is detected => add 'http://'</p> <p>Now the question is refined: Is it possible to handle such cases automatically with some builtin function or I have to do error handling with subsequent string concatenation?</p>
5,823,607
4
0
null
2011-04-28 18:54:40.107 UTC
5
2018-11-06 18:36:37.087 UTC
2011-04-28 19:05:48.46 UTC
null
717,980
null
717,980
null
1
25
python|urllib2|httprequest
48,679
<p>When you enter a URL in a browser without the protocol, it defaults to HTTP. <code>urllib2</code> won't make that assumption for you; you need to prefix it with <code>http://</code>.</p>
52,752,654
Unknown format code 'f' for object of type 'str'- Folium
<p>I have a dataframe that looks like below</p> <pre><code> Number Names latitude longitude 0 1 Josh 25.713277 80.746531 1 2 Jon 25.713277 80.746531 2 3 Adam 25.713277 80.746531 3 4 Barsa 25.713277 80.746531 4 5 Fekse 25.713277 80.746531 5 6 Bravo 25.713277 80.746531 6 7 Levine 25.713277 80.746531 7 8 Talyo 25.713277 80.746531 8 9 Syden 25.713277 80.746531 9 10 Zidane 25.713277 80.746531 </code></pre> <p>I am trying to create a folium map for this dataframe, I wanted the <code>Number</code> column <strong>values</strong> to be displayed in some color based on the values of <code>Names</code> column with the following code, basically I want the number <strong>1 to 10</strong> to be displayed in some color for a place based on the Names. For example, <code>1</code> should be displayed in <code>lightblue</code>, <code>2</code> should be displayed in <code>green</code> color and rest of the numbers should be displayed in <code>red</code> color</p> <pre><code>for Number,Names,latitude,longitude in zip(dsa['Number'],dsa['Names'],dsa['latitude'],dsa['longitude']): folium.Marker(location=[latitude,longitude], icon=folium.DivIcon( html=f"""&lt;div style="font-family: courier new; color: {'lightblue' if Names == 'Josh' else 'green' if Names == 'Jon' else 'red'}"&gt;{"{:.0f}".format(Number)}&lt;/div&gt;""") ).add_to(m) m.save(os.path.join('color_popups1231.html')) </code></pre> <p>But when I execute this I am getting this error:</p> <pre><code>ValueError: Unknown format code 'f' for object of type 'str' </code></pre> <p>What am I missing here?</p>
52,752,749
1
2
null
2018-10-11 05:13:35.547 UTC
null
2018-10-11 05:58:05.02 UTC
2018-10-11 05:58:05.02 UTC
null
5,638,397
null
10,409,218
null
1
8
python|pandas|folium
42,177
<p>The <code>f</code> format code in <code>"{:.0f}".format(Number)</code> for the Python string formatter requires a floating number, and yet you're passing to it the variable <code>Number</code>, which is derived from <code>dsa['Number']</code>, a string value from the dataframe. You should convert <code>Number</code> to a floating number before passing it to the formatter with <code>"{:.0f}".format(float(Number))</code> instead.</p>
1,501,959
UITableViewCell transparent background (including imageView/accessoryView)
<p>When I set the UITableViewCells <code>backgroundColor</code> to a semi-transparent color, it looks good, but the color doesn't cover the entire cell.</p> <p>The area around the <code>imageView</code> and <code>accessoryView</code> are coming up as <code>[UIColor clearColor]</code>...</p> <p><img src="https://s3.amazonaws.com/ember/kjEaVb9IePn82yRh4933AX8tjBOv4J9v_m.png" alt="alt text"></p> <p>I've tried explicitly setting the <code>cell.accessoryView.backgroundColor</code> and <code>cell.imageView.backgroundColor</code> to be the same color as the cell's <code>backgroundColor</code>, but it doesn't work. It puts a tiny box around the icon, but doesn't expand to fill the left edge. The right edge seems unaffected by this.</p> <p>How can I fix this?</p> <p><strong>EDIT</strong> : Here is the raw table cell code:</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; cell.opaque = NO; cell.textLabel.backgroundColor = [UIColor clearColor]; cell.backgroundColor = [UIColor colorWithRed:.1 green:.1 blue:.1 alpha:.4]; cell.textColor = [UIColor whiteColor]; } cell.imageView.image = [icons objectAtIndex:indexPath.row]; cell.textLabel.text = [items objectAtIndex:indexPath.row]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } </code></pre>
1,512,511
2
0
null
2009-10-01 04:55:54.847 UTC
11
2015-11-30 05:43:08.427 UTC
2017-02-08 14:15:48.433 UTC
null
-1
null
3,381
null
1
10
iphone|iphone-sdk-3.0|uitableview
14,406
<p>Ben and I figured this out today, here's the summary for the group in case this catches anybody else.</p> <p>You have to set the cell background and <code>cell.textLabel.backgroundColor</code> every time <code>cellForRowAtIndexPath</code> is called, not just during the <code>alloc/init</code> phase (i.e. if the <code>tableView</code> has a dequeue cache miss).</p> <p>So, the code becomes this:</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; cell.opaque = NO; } // All bgColor configuration moves here cell.textLabel.backgroundColor = [UIColor clearColor]; cell.backgroundColor = [UIColor colorWithRed:.1 green:.1 blue:.1 alpha:.4]; cell.textColor = [UIColor whiteColor]; cell.imageView.image = [icons objectAtIndex:indexPath.row]; cell.textLabel.text = [items objectAtIndex:indexPath.row]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } </code></pre>
1,427,926
Detecting Client Death in WCF Duplex Contracts
<p>I'm trying to build a SOA where clients can perform long running queries on the server and the server responds using a callback.</p> <p>I'd like to be able to detect if the client disconnects (through user initiated shutdown, unhandled exception or loss of network connectivity) so that the server can choose to cancel the expensive request. </p> <p>I'm testing a variety of failure cases but I can't seem to get certain event handlers to fire.</p> <p>Tested Failure Cases: Killing the Client Process After the request. Using a program like CurrPorts to close the TCP Connection. </p> <p>Test Code: </p> <pre><code>using System; using System.ServiceModel; using System.Threading; namespace WCFICommunicationObjectExperiments { class Program { static void Main(string[] args) { var binding = new NetTcpBinding(SecurityMode.None); var serviceHost = new ServiceHost(typeof (Server)); serviceHost.AddServiceEndpoint(typeof (IServer), binding, "net.tcp://localhost:5000/Server"); serviceHost.Open(); Console.WriteLine("Host is running, press &lt;ENTER&gt; to exit."); Console.ReadLine(); } } [ServiceContract(CallbackContract = typeof(IClient))] public interface IServer { [OperationContract] void StartProcessing(string Query); } public interface IClient { [OperationContract] void RecieveResults(string Results); } [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)] public class Server : IServer { public void StartProcessing(string Query) { Thread.Sleep(5000); //Callback Channel var clientCallback = OperationContext.Current.GetCallbackChannel&lt;IClient&gt;(); var clientCallbackCommunicationObject = ((ICommunicationObject) clientCallback); EventHandler faultedHandlerCallback = (o, s) =&gt; Console.WriteLine("Client Channel Faulted."); EventHandler closedHandlerCallback = (o, s) =&gt; Console.WriteLine("Client Channel Closed."); clientCallbackCommunicationObject.Faulted += faultedHandlerCallback; clientCallbackCommunicationObject.Closed += closedHandlerCallback; //Request Channel var requestChannel = OperationContext.Current.Channel; EventHandler faultedHandlerRequest = (o, s) =&gt; Console.WriteLine("Request Channel Faulted."); EventHandler closedHandlerRequest = (o, s) =&gt; Console.WriteLine("Request Channel Closed."); requestChannel.Faulted += faultedHandlerRequest; requestChannel.Closed += closedHandlerRequest; try { clientCallback.RecieveResults("42."); } catch (CommunicationObjectAbortedException ex) { Console.WriteLine("Client Aborted the connection"); } catch (CommunicationObjectFaultedException ex) { Console.WriteLine("Client Died."); } clientCallbackCommunicationObject.Faulted -= faultedHandlerCallback; clientCallbackCommunicationObject.Faulted -= closedHandlerCallback; requestChannel.Faulted -= faultedHandlerRequest; requestChannel.Closed -= closedHandlerRequest; } } public class ClientToTestStates : IClient { private IServer m_Server; private readonly ManualResetEvent m_ReceivedEvent = new ManualResetEvent(false); private readonly ManualResetEvent m_ChannelFaulted = new ManualResetEvent(false); private readonly ManualResetEvent m_ChannelClosed = new ManualResetEvent(false); public ClientToTestStates() { var binding = new NetTcpBinding(SecurityMode.None); var channelFactory = new DuplexChannelFactory&lt;IServer&gt;(this, binding, new EndpointAddress("net.tcp://localhost:5000/Server")); m_Server = channelFactory.CreateChannel(); ((ICommunicationObject)m_Server).Open(); ((ICommunicationObject)m_Server).Faulted += ChannelFaulted; ((ICommunicationObject)m_Server).Closed += ChannelClosed; m_Server.StartProcessing("What is the answer?"); WaitHandle.WaitAny(new WaitHandle[] {m_ReceivedEvent, m_ChannelFaulted, m_ChannelClosed}); } void ChannelFaulted(object sender, EventArgs e) { m_ChannelFaulted.Set(); Console.WriteLine("Channel Faulted."); } void ChannelClosed(object sender, EventArgs e) { m_ChannelClosed.Set(); Console.WriteLine("Channel Closed."); } public void RecieveResults(string results) { m_ReceivedEvent.Set(); Console.WriteLine("Recieved Results {0}", results); } } } </code></pre> <p>What's the best practice to handle these sorts of failure cases? I'd like to be able to use the underlying tcp connection to detect some of these things.</p>
1,428,238
2
1
null
2009-09-15 15:35:41.24 UTC
22
2012-11-23 14:39:09.713 UTC
null
null
null
null
129,573
null
1
31
c#|wcf|callback|duplex|nettcpbinding
30,276
<p>In his 'Programming WCF Services' book, Juval Lowy explains that WCF does not provide a mechansim for managing service callbacks, and this must be managed by the service and client explicitly. If the service attempts to invoke a callback which has been closed on the client, an ObjectDisposedException will be thrown on the service channel.</p> <p>He recommends adding a Connect and Disconnect method to the service contract - since the callback must be provided to the service when these are called, the service can manage client callbacks. It is then up to the client to ensure that it calls Disconnect when it no longer wishes to recieve callbacks from the service, and the service must handle any exceptions when invoking callbacks to the client.</p>
57,003,084
When to use useEffect?
<p>I'm currently looking at the react doc's example for useEffect</p> <pre><code>import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); // Similar to componentDidMount and componentDidUpdate: useEffect(() =&gt; { // Update the document title using the browser API document.title = `You clicked ${count} times`; }); return ( &lt;div&gt; &lt;p&gt;You clicked {count} times&lt;/p&gt; &lt;button onClick={() =&gt; setCount(count + 1)}&gt; Click me &lt;/button&gt; &lt;/div&gt; ); } </code></pre> <p>My question is that we can easily make a handleClick function for the button. We don't have to use useEffect</p> <pre><code>const handleButtonClick = () =&gt;{ setCount(count+1) document.title = `You clicked ${count +1} times` } &lt;button onClick={handleButtonClick}/&gt; </code></pre> <p>So which way is considered good practice? Is it best to only use useEffect to trigger side effects that strictly couldn't be done along with the main effect(i.e when component receive new prop)</p>
57,003,200
4
1
null
2019-07-12 08:28:26.623 UTC
7
2022-08-24 11:21:38.47 UTC
null
null
null
null
11,764,170
null
1
33
reactjs
18,155
<p>You showed two different examples,</p> <p><code>handleButtonClick</code> fires on <code>Button 1</code> click, while <code>useEffect</code> fires on every state change state (according to the dependency array).</p> <p>In the next example, you notice that <code>useEffect</code> will log on every button click (<code>Button 1/2</code>), and <code>handleButtonClick</code> will log only on <code>Button 2</code> click.</p> <pre class="lang-js prettyprint-override"><code>import React, { useState, useEffect } from &quot;react&quot;; function Example() { const [count, setCount] = useState(0); useEffect(() =&gt; { console.log(`You rendered ${count} times`); }, [count]); const handleButtonClick = () =&gt; { setCount(count + 1); console.log(`You clicked ${count + 1} times`); }; return ( &lt;div&gt; &lt;p&gt;You clicked {count} times&lt;/p&gt; &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Button 1&lt;/button&gt; &lt;button onClick={handleButtonClick}&gt;Button 2&lt;/button&gt; &lt;/div&gt; ); } </code></pre> <ul> <li>Check similar question on <a href="https://stackoverflow.com/questions/59841800/react-useeffect-in-depth-use-of-useeffect/59841947#59841947"><code>useEffect</code> use cases</a></li> <li><a href="https://reactjs.org/docs/hooks-effect.html" rel="nofollow noreferrer">Refer to <code>useEffect</code> docs</a></li> </ul>
50,333,767
HTML5 Video: Streaming Video with Blob URLs
<p>I have an array of Blobs (binary data, really -- I can express it however is most efficient. I'm using Blobs for now but maybe a <code>Uint8Array</code> or something would be better). Each Blob contains 1 second of audio/video data. Every second a new Blob is generated and appended to my array. So the code roughly looks like so:</p> <pre><code>var arrayOfBlobs = []; setInterval(function() { arrayOfBlobs.append(nextChunk()); }, 1000); </code></pre> <p>My goal is to stream this audio/video data to an HTML5 element. I know that a Blob URL can be generated and played like so:</p> <pre><code>var src = URL.createObjectURL(arrayOfBlobs[0]); var video = document.getElementsByTagName("video")[0]; video.src = src; </code></pre> <p>Of course this only plays the first 1 second of video. I also assume I can trivially concatenate all of the Blobs currently in my array somehow to play more than one second:</p> <pre><code>// Something like this (untested) var concatenatedBlob = new Blob(arrayOfBlobs); var src = ... </code></pre> <p>However this will still eventually run out of data. As Blobs are immutable, I don't know how to keep appending data as it's received.</p> <p>I'm certain this should be possible because YouTube and many other video streaming services utilize Blob URLs for video playback. How do <strong><em>they</em></strong> do it?</p>
50,354,182
2
2
null
2018-05-14 15:16:07.2 UTC
31
2021-06-29 21:33:49.26 UTC
null
null
null
null
436,976
null
1
22
javascript|html|video|html5-video|blob
49,538
<h2>Solution</h2> <p>After some significant Googling I managed to find the missing piece to the puzzle: <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaSource" rel="noreferrer">MediaSource</a></p> <p>Effectively the process goes like this:</p> <ol> <li>Create a <code>MediaSource</code></li> <li>Create an object URL from the <code>MediaSource</code></li> <li>Set the video's <code>src</code> to the object URL</li> <li>On the <code>sourceopen</code> event, create a <code>SourceBuffer</code></li> <li>Use <code>SourceBuffer.appendBuffer()</code> to add all of your chunks to the video</li> </ol> <p>This way you can keep adding new bits of video without changing the object URL.</p> <h2>Caveats</h2> <ul> <li>The <code>SourceBuffer</code> object is <strong><em>very</em></strong> picky about codecs. These have to be declared, and must be exact, or it won't work</li> <li>You can only append one blob of video data to the <code>SourceBuffer</code> at a time, and you can't append a second blob until the first one has finished (asynchronously) processing</li> <li>If you append too much data to the <code>SourceBuffer</code> without calling <code>.remove()</code> then you'll eventually run out of RAM and the video will stop playing. I hit this limit around 1 hour on my laptop</li> </ul> <h2>Example Code</h2> <p>Depending on your setup, some of this may be unnecessary (particularly the part where we build a queue of video data before we have a <code>SourceBuffer</code> then slowly append our queue using <code>updateend</code>). If you are able to wait until the <code>SourceBuffer</code> has been created to start grabbing video data, your code will look much nicer.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;video id="video"&gt;&lt;/video&gt; &lt;script&gt; // As before, I'm regularly grabbing blobs of video data // The implementation of "nextChunk" could be various things: // - reading from a MediaRecorder // - reading from an XMLHttpRequest // - reading from a local webcam // - generating the files on the fly in JavaScript // - etc var arrayOfBlobs = []; setInterval(function() { arrayOfBlobs.append(nextChunk()); // NEW: Try to flush our queue of video data to the video element appendToSourceBuffer(); }, 1000); // 1. Create a `MediaSource` var mediaSource = new MediaSource(); // 2. Create an object URL from the `MediaSource` var url = URL.createObjectURL(mediaSource); // 3. Set the video's `src` to the object URL var video = document.getElementById("video"); video.src = url; // 4. On the `sourceopen` event, create a `SourceBuffer` var sourceBuffer = null; mediaSource.addEventListener("sourceopen", function() { // NOTE: Browsers are VERY picky about the codec being EXACTLY // right here. Make sure you know which codecs you're using! sourceBuffer = mediaSource.addSourceBuffer("video/webm; codecs=\"opus,vp8\""); // If we requested any video data prior to setting up the SourceBuffer, // we want to make sure we only append one blob at a time sourceBuffer.addEventListener("updateend", appendToSourceBuffer); }); // 5. Use `SourceBuffer.appendBuffer()` to add all of your chunks to the video function appendToSourceBuffer() { if ( mediaSource.readyState === "open" &amp;&amp; sourceBuffer &amp;&amp; sourceBuffer.updating === false ) { sourceBuffer.appendBuffer(arrayOfBlobs.shift()); } // Limit the total buffer size to 20 minutes // This way we don't run out of RAM if ( video.buffered.length &amp;&amp; video.buffered.end(0) - video.buffered.start(0) &gt; 1200 ) { sourceBuffer.remove(0, video.buffered.end(0) - 1200) } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>As an added bonus this automatically gives you DVR functionality for live streams, because you're retaining 20 minutes of video data in your buffer (you can seek by simply using <code>video.currentTime = ...</code>)</p>
32,273,072
Updating excel file using Apache POI
<p>I am trying to update an existing excel file using Apache POI. Every time I run my code I receive an error as shown below. I have also tried FileInputStreamNewFile thing.</p> <pre><code>Exception in thread "main" java.lang.NullPointerException at com.gma.test.WriteExcelTest.writeXLSXFile(WriteExcelTest.java:26) at com.gma.test.WriteExcelTest.main(WriteExcelTest.java:44) </code></pre> <p>Please find the code below. Appreciate your help.</p> <pre><code>package com.gma.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class WriteExcelTest { public static void writeXLSXFile(int row, int col) throws IOException { try { FileInputStream file = new FileInputStream("C:\\Anuj\\Data\\Data.xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); Cell cell = null; //Update the value of cell cell = sheet.getRow(row).getCell(col); cell.setCellValue("Pass"); file.close(); FileOutputStream outFile =new FileOutputStream(new File("C:\\Anuj\\Data\\Data.xlsx")); workbook.write(outFile); outFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub writeXLSXFile(3, 3); } } </code></pre>
32,273,371
3
2
null
2015-08-28 14:10:30.303 UTC
4
2016-08-16 17:34:06.023 UTC
2015-08-28 14:45:25.1 UTC
null
1,496,124
null
4,455,512
null
1
18
java|excel|apache|selenium|selenium-webdriver
56,976
<p>If you replace </p> <pre><code>//Update the value of cell cell = sheet.getRow(row).getCell(col); cell.setCellValue("Pass"); </code></pre> <p>With</p> <pre><code>//Retrieve the row and check for null HSSFRow sheetrow = sheet.getRow(row); if(sheetrow == null){ sheetrow = sheet.createRow(row); } //Update the value of cell cell = sheetrow.getCell(col); if(cell == null){ cell = sheetrow.createCell(col); } cell.setCellValue("Pass"); </code></pre> <p>It will work!</p>
6,215,782
Do unused functions get optimized out?
<p>Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?</p>
6,215,800
8
1
null
2011-06-02 14:19:54.687 UTC
18
2022-09-09 23:16:44.017 UTC
2022-09-09 23:16:44.017 UTC
null
63,550
null
627,005
null
1
58
c++|c|compiler-construction|compiler-optimization
34,007
<p>It depends on the compiler. Visual C++ 9 can do that - unused <code>static</code> functions are removed at compilation phase (there's even a <a href="https://docs.microsoft.com/en-gb/cpp/error-messages/compiler-warnings/compiler-warning-level-4-c4505" rel="noreferrer">C4505 warning</a> for that), unused functions with external linkage can be removed at link phase <a href="https://docs.microsoft.com/en-us/cpp/build/reference/linker-options" rel="noreferrer">depending on linker settings</a>.</p>
6,026,713
How do I change Emacs' default font size and font type?
<p>I am using Emacs 23.3. How can I change the font size and font type?</p>
6,026,790
9
1
null
2011-05-17 05:44:57.987 UTC
22
2022-04-03 18:07:19.417 UTC
2021-07-26 20:23:59.07 UTC
null
63,550
null
240,759
null
1
89
emacs|emacs23
88,090
<p>You can use the menu bar. Go to <code>Options</code>-><code>Set Default Font...</code>.</p> <p>After you choose a font, don't forget to press <code>Options</code>-><code>Save Options</code>&mdash;otherwise your new font will not be saved after you close Emacs.</p>
6,265,298
ACTION_VIEW intent for a file with unknown MimeType
<p>My app has a feature that browse files on your phone and SD card and open them using other apps. I want a solution where I don't have to specify the MimeType and can work with any type of file.</p> <p>Here is my code:</p> <pre><code>Intent myIntent = new Intent(Intent.ACTION_VIEW); myIntent.setData(Uri.fromFile(item)); startActivity(myIntent); </code></pre> <p>However, I'm getting the following error:</p> <pre><code>android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.PICK dat=file:///sdcard/dropbox/test.pdf } </code></pre>
6,381,479
13
0
null
2011-06-07 12:42:18.41 UTC
33
2020-05-27 14:34:50.11 UTC
2011-11-14 18:02:53.553 UTC
null
648,313
null
112,381
null
1
68
android
86,165
<p>This should detect the mimetype and open with default:</p> <pre><code>MimeTypeMap myMime = MimeTypeMap.getSingleton(); Intent newIntent = new Intent(Intent.ACTION_VIEW); String mimeType = myMime.getMimeTypeFromExtension(fileExt(getFile()).substring(1)); newIntent.setDataAndType(Uri.fromFile(getFile()),mimeType); newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(newIntent); } catch (ActivityNotFoundException e) { Toast.makeText(context, "No handler for this type of file.", Toast.LENGTH_LONG).show(); } </code></pre> <p>Using this function:</p> <pre><code>private String fileExt(String url) { if (url.indexOf("?") &gt; -1) { url = url.substring(0, url.indexOf("?")); } if (url.lastIndexOf(".") == -1) { return null; } else { String ext = url.substring(url.lastIndexOf(".") + 1); if (ext.indexOf("%") &gt; -1) { ext = ext.substring(0, ext.indexOf("%")); } if (ext.indexOf("/") &gt; -1) { ext = ext.substring(0, ext.indexOf("/")); } return ext.toLowerCase(); } } </code></pre>
5,993,779
Use String.split() with multiple delimiters
<p>I need to split a string base on delimiter <code>-</code> and <code>.</code>. Below are my desired output. </p> <p><code>AA.BB-CC-DD.zip</code> -> </p> <pre><code>AA BB CC DD zip </code></pre> <p>but my following code does not work.</p> <pre><code>private void getId(String pdfName){ String[]tokens = pdfName.split("-\\."); } </code></pre>
5,993,823
15
5
null
2011-05-13 14:56:36.18 UTC
50
2022-09-01 07:43:19.83 UTC
2017-04-15 20:24:04.123 UTC
null
360,211
null
240,337
null
1
242
java|regex
480,440
<p>I think you need to include the regex <strong>OR operator</strong>:</p> <pre><code>String[]tokens = pdfName.split("-|\\."); </code></pre> <p>What you have will match:<br> [DASH followed by DOT together] <code>-.</code><br> not<br> [DASH or DOT any of them] <code>-</code> or <code>.</code></p>
43,996,782
How to correct the [Composer\Downloader\TransportException] error for composer
<p>Good day people, I have been having this problem for days now, when I try to download dependencies for my php project using composer I get this error</p> <pre><code>c:\wamp64\www\Test&gt;composer global require "fxp/composer-asset-plugin:^1.3.1" Changed current directory to C:/Users/Nwachukwu Favour/AppData/Roaming/Composer ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Installation failed, reverting ./composer.json to its original content. [Composer\Downloader\TransportException] The "http://packagist.org/p/provider-2014%241cf88bd0ed4076dc091407477ba2a76483e8598ee5365673381262e6c1d40fcf.jso n" file could not be downloaded: failed to open stream: HTTP request failed! require [--dev] [--prefer-source] [--prefer-dist] [--no-plugins] [--no-progress] [--no-update] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--] [&lt;packages&gt;]... </code></pre> <p>I am running a windows 10 OS and am suspecting that my system cannot download from the command line. I would be very glad if someone can help me solve this problem because it is hindering my project. Thanks in advance.</p>
56,696,736
13
0
null
2017-05-16 08:56:00.293 UTC
4
2022-09-06 16:07:07.2 UTC
2020-06-13 23:52:39.557 UTC
null
6,665,041
null
6,665,041
null
1
17
php|composer-php
50,589
<p>You could also run this command on the CLI before installing any dependencies. It forces composer to use https to download all resources:</p> <pre><code>composer config -g repo.packagist composer https://packagist.org </code></pre>
44,106,910
Angular - There is no directive with "exportAs" set to "ngModel"
<p>Following are the files in the AngularJS project. As suggested in some posts, I have added:</p> <pre><code>ngModel name="currentPassword" #currentPassword="ngModel </code></pre> <p>in the input field, but still getting an error.</p> <p><strong>package.json</strong></p> <pre><code>......... "dependencies": { "@angular/common": "^2.3.1", "@angular/compiler": "^2.3.1", "@angular/core": "^2.3.1", "@angular/forms": "^2.3.1", "@angular/http": "^2.3.1", "@angular/platform-browser": "^2.3.1", "@angular/platform-browser-dynamic": "^2.3.1", "@angular/router": "^3.3.1", "core-js": "^2.4.1", "rxjs": "^5.0.1", "ts-helpers": "^1.1.1", "zone.js": "^0.7.2" }, ............... </code></pre> <p><strong>change-password.component.html</strong></p> <pre><code>&lt;form #f="ngForm" [formGroup]="changePasswordForm"&gt; &lt;div class="form-group"&gt; &lt;label for="currentPassword"&gt;Current Password&lt;/label&gt; &lt;input placeholder="currentPassword" ngModel name="currentPassword" #currentPassword="ngModel" id="currentPassword" name="currentPassword" type="text" class="form-control" required minlength="6" formControlName="currentPassword"&gt; &lt;/div&gt; &lt;/div&gt; &lt;button class="btn btn-primary" type="submit"&gt;Change Password&lt;/button&gt; &lt;/form&gt; </code></pre> <p><strong>change-password.component.ts</strong></p> <pre><code>import { Component, OnInit } from '@angular/core'; import { FormBuilder, Validators, ControlContainer, FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-change-password', templateUrl: './change-password.component.html', styleUrls: ['./change-password.component.css'] }) export class ChangePasswordComponent implements OnInit { changePasswordForm; constructor(formBuilder: FormBuilder) { this.changePasswordForm = formBuilder.group({ currentPassword: new FormControl('', Validators.compose([Validators.required])) }); } ngOnInit() { } } </code></pre> <p><strong>app.module.ts has imports</strong></p> <pre><code>............ imports: [ BrowserModule, HttpModule, FormsModule, ReactiveFormsModule ] ........... </code></pre> <p>I am getting the following error:</p> <blockquote> <p>Unhandled Promise rejection: Template parse errors: There is no directive with "exportAs" set to "ngModel" ("urrent Password ]#currentPassword="ngModel" id="currentPassword" name="currentPassword" type="text" class="form-co"): ChangePasswordComponent@5:4 ; Zone: ; Task: Promise.then ; Value: SyntaxError {__zone_symbol__error: Error: Template parse errors: There is no directive with "exportAs" set to "ngModel" ("urrent Passwo……} Error: Template parse errors: There is no directive with "exportAs" set to "ngModel" ("urrent Password ]#currentPassword="ngModel" id="currentPassword" name="currentPassword" type="text" class="form-co"): ChangePasswordComponent@5:4 at SyntaxError.ZoneAwareError (<a href="http://localhost:4200/polyfills.bundle.js:6884:33" rel="noreferrer">http://localhost:4200/polyfills.bundle.js:6884:33</a>) at SyntaxError.BaseError [as constructor] (<a href="http://localhost:4200/vendor.bundle.js:64475:16" rel="noreferrer">http://localhost:4200/vendor.bundle.js:64475:16</a>) at new SyntaxError (<a href="http://localhost:4200/vendor.bundle.js:5727:16" rel="noreferrer">http://localhost:4200/vendor.bundle.js:5727:16</a>)</p> </blockquote>
44,107,702
6
0
null
2017-05-22 07:22:28.29 UTC
7
2021-10-06 10:52:33.3 UTC
2018-03-10 13:12:13.607 UTC
null
660,828
null
2,414,160
null
1
18
angular|angular2-forms|angular2-ngmodel
46,783
<p>You are using an odd mix of template driven and model driven form. Choose either and do not mix those two. So here is sample on the model-driven form:</p> <p>No need to set <code>required</code> or <code>minlength</code> in template, we handle thid in the component. Also we do not need any <code>ngModel</code>, <code>name</code> etc, since we use <code>formControlName</code>. Also remove <code>#f="ngForm"</code> as that is related to template-driven form. So your template should look like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;form [formGroup]="changePasswordForm"&gt; &lt;label for="currentPassword"&gt;Current Password&lt;/label&gt; &lt;input formControlName="currentPassword"&gt; &lt;button type="submit"&gt;Change Password&lt;/button&gt; &lt;/form&gt; </code></pre> <p>And when building the form, we set all validators we need, in this case <code>required</code> and <code>minLength</code>:</p> <pre class="lang-ts prettyprint-override"><code>constructor(formBuilder: FormBuilder) { this.changePasswordForm = formBuilder.group({ currentPassword: new FormControl('', Validators.compose([Validators.required, Validators.minLength(6)])) }); } </code></pre> <p>So that's it! :)</p> <p>I suggest you read about forms, here is <strong><a href="https://angular.io/guide/forms" rel="noreferrer">the guide for template driven forms</a></strong> and <strong><a href="https://angular.io/guide/reactive-forms" rel="noreferrer">guide for reactive forms</a></strong> </p> <p><strong>EDIT:</strong></p> <p>For form validation, check the <strong><a href="https://angular.io/docs/ts/latest/cookbook/form-validation.html" rel="noreferrer">official docs</a></strong> for form validation. If you have plenty fields, you might want to adapt their solution, where storing all form errors in a separate object. </p> <p>But here is a basic solution to check for form errors for each form control. So the following would be for your validations:</p> <pre class="lang-html prettyprint-override"><code>&lt;small *ngIf="changePasswordForm.get('currentPassword').hasError('required')"&gt;Required!&lt;/small&gt; &lt;small *ngIf="changePasswordForm.get('currentPassword').hasError('minlength')"&gt;Minimum 6 chars&lt;/small&gt; </code></pre> <p>You might also want to show perhaps error messages when field is touched (??). This all you can find in the link I provided for validation :)</p> <p><a href="http://plnkr.co/edit/sABeltA8iRlwwagASXGE?p=preview" rel="noreferrer"><strong>Updated Demo</strong></a></p>
55,587,708
Cannot assign to read only property 'closed' of object '[object Object]'
<p>I've been cracking my head on this for a few days now, but I can't find the reason why this is happening.</p> <p>So I'm getting the following error message: </p> <blockquote> <p>TypeError: Cannot assign to read only property 'closed' of object '[object Object]'</p> </blockquote> <p><a href="https://i.stack.imgur.com/AV7fT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AV7fT.png" alt="enter image description here"></a></p> <p>So as you can see, it happens in the civilliability-step3.component.ts at the sendProposal function:</p> <p><code>civilliability-step3.component.ts</code></p> <pre><code>@Component({ selector: 'app-civilliability-step3', templateUrl: './civilliability-step3.component.html', styleUrls: ['./civilliability-step3.component.scss'] }) export class CivilliabilityStep3Component implements OnInit, OnDestroy { @Output() modelChange = new EventEmitter&lt;CivilLiabilityRequestType&gt;(); @Output() onCloseForm = new EventEmitter(); @Input() model: CivilLiabilityRequestType; public formGroup: FormGroup; private closedProposalSub: Subscription; constructor(private formBuilder: FormBuilder, private store: Store) {} ngOnInit() { this.buildForm(); if (this.model !== undefined &amp;&amp; this.model.details.closed) { disableFormGroup(this.formGroup); } this.closedProposalSub = this.store .select(ProposalsState.closedProposalResult) .subscribe(val =&gt; { if (val !== undefined) { this.modelChange.emit(val); this.onCloseForm.emit(); } }); } ngOnDestroy() { if (this.closedProposalSub &amp;&amp; !this.closedProposalSub.closed) { this.closedProposalSub.unsubscribe(); } this.store.dispatch(new ResetClosedProposalResult()); } sendProposal() { this.model.details.closed = true; this.store.dispatch(new CloseProposal(this.model)); } closeForm() { disableFormGroup(this.formGroup); } private buildForm() { this.formGroup = this.formBuilder.group({}); } } </code></pre> <p>Useage of the component:</p> <p><code>civilliability-detail.component.html</code></p> <pre><code>&lt;app-civilliability-step3 (onCloseForm)="step1.closeForm(); step2.closeForm(); step3.closeForm()" [(model)]="model" #step3&gt;&lt;/app-civilliability-step3&gt; </code></pre> <p>I've tried assigning the true value differently, because I figured maybe I can't add it directly to the model, which is an <code>Input</code>. But that didn't help either.</p> <pre><code> sendProposal() { const detailsModel = this.model.details; detailsModel.closed = true; // &lt;-- same error this.model.details = detailsModel; const tmpModel = this.model; tmpModel.details.closed = true; // &lt;-- same error this.model = tmpModel; // this.model.details.closed = true; this.store.dispatch(new CloseProposal(this.model)); } </code></pre> <p><strong>UPDATE 1:</strong> Added CivilLiabilityRequestType</p> <pre><code>export interface CivilLiabilityRequestType extends IRequestData { details: CivilLiabilityDetailsModel; questionnaire: CivilLiabilityQuestionnaireModel; comments: CivilLiabilityCommentsModel; } export class CivilLiabilityDetailsModel { baseReqId: number; startDate: string; branch: NamedResource; fractioning: NamedResource; closed: boolean; } </code></pre> <p><strong>UPDATE 2:</strong> Show origin of this.model:</p> <p><code>civilliability-detail.component.ts</code> </p> <pre><code>export class CivilliabilityProposalDetailComponent implements OnInit, OnDestroy { @Input() model: CivilLiabilityRequestType; @Input() tab: Tab; @Input() tabs: Tab[] = []; @Input() selectedTabIndex; @Input() idx: number; constructor() {} ngOnInit() {} ngOnDestroy() { this.model = getEmptyCivilLiabilityRequest(); } } </code></pre> <p><code>detail.component.html</code></p> <pre><code>&lt;mat-tab *ngFor="let tab of tabs; let idx = index"&gt; ... &lt;app-civilliability-proposal-detail [model]="tab.tabData.data" [tab]="tab" [tabs]="tabs" [selectedTabIndex]="selectedTabIndex" [idx]="idx" &gt; &lt;/app-civilliability-proposal-detail&gt; ... &lt;/mat-tab&gt; </code></pre> <p><code>detail.component.ts</code></p> <pre><code>@Component({ selector: 'app-detail', templateUrl: './detail.component.html', styleUrls: ['./detail.component.scss'] }) export class DetailComponent implements OnInit { public tabs: Tab[] = []; public selectedTabIndex = 0; public quote?: QuoteData; public quoteModel: QuoteData; public originalModel: any[]; public readonly = false; @Input() public requestType; constructor(private activeRoute: ActivatedRoute) {} ngOnInit() { const snapshot = this.activeRoute.snapshot; this.originalModel = snapshot.data['model']; if (this.originalModel) { this.tabs = this.createTabsFromQuoteModel(this.originalModel); } } private createTabsFromQuoteModel(model: any): Tab[] { let tabs: Tab[] = []; for (const key of Object.keys(model)) { const element = model[key]; let type: RequestTypes; let proposalData: IRequestData = {}; if (key === 'civilLiability') { type = RequestTypes.CivilLiability; proposalData.type = RequestTypes.CivilLiability; proposalData.data = element; } tabs = [...tabs, { type: type, name: '', tabData: proposalData }]; proposalData = {}; } return tabs; } } </code></pre> <p>And just to give an overview of the structure, to keep us sane:</p> <pre><code>&lt;app-detail&gt; &lt;mat-tab *ngFor="let tab of tabs; let idx = index"&gt; &lt;app-civilliability-proposal-detail [model]="tab.tabData.data"&gt; &lt;app-civilliability-step3 [(model)]="model" &gt;&lt;/app-civilliability-step3&gt; &lt;/app-civilliability-step3 &lt;/app-civilliability-proposal-detail&gt; &lt;/mat-tab &lt;/app-detail&gt; </code></pre> <p><strong>UPDATE 3:</strong> Add tabs data: <a href="https://i.stack.imgur.com/PXs2m.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PXs2m.png" alt="enter image description here"></a></p>
55,588,643
2
9
null
2019-04-09 07:54:57.043 UTC
1
2020-11-04 08:08:23.31 UTC
2019-04-09 10:49:30.307 UTC
null
2,664,414
null
2,664,414
null
1
25
javascript|angular
49,006
<p>I believe this happens because you cannot modify an object that is stored in the state (ngRx), you could try something like this instead:</p> <pre><code>sendProposal() { this.store.dispatch(new CloseProposal(Object.assign({}, this.model, { details: { closed: true } }))); } </code></pre>
25,311,593
ChromeWebDriver - unknown error: Chrome failed to start: crashed
<p>I'm trying to test my application on Chrome with ChromeWebDriver but every time I try I get following exception:</p> <pre><code> org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: crashed (Driver info: chromedriver=2.10.267521,platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 61.46 seconds Build info: version: '2.41.0', revision: '3192d8a6c4449dc285928ba024779344f5423c58', time: '2014-03-27 11:29:39' System info: host: 'PADAMSKI-W', ip: '10.10.8.60', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.6.0_37' Driver info: pl.axit.test.selenium.env.KoralinaChromeDriver at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193) at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:595) at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:240) at org.openqa.selenium.chrome.ChromeDriver.startSession(ChromeDriver.java:181) at org.openqa.selenium.remote.RemoteWebDriver.&lt;init&gt;(RemoteWebDriver.java:126) at org.openqa.selenium.remote.RemoteWebDriver.&lt;init&gt;(RemoteWebDriver.java:139) at org.openqa.selenium.chrome.ChromeDriver.&lt;init&gt;(ChromeDriver.java:160) at org.openqa.selenium.chrome.ChromeDriver.&lt;init&gt;(ChromeDriver.java:149) </code></pre> <p>In chromedriver.log I see</p> <pre><code>[0.681][INFO]: Launching chrome: "C:\Users\padamski.AXIT.PL\AppData\Local\Google\Chrome\Application\chrome.exe" --disable-background-networking --disable-client-side-phishing-detection --disable-component-update --disable-default-apps --disable-hang-monitor --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-logging --ignore-certificate-errors --load-extension="C:\Users\PADAMS~1.PL\AppData\Local\Temp\scoped_dir4048_12236\internal" --logging-level=1 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=12573 --safebrowsing-disable-auto-update --safebrowsing-disable-download-protection --use-mock-keychain --user-data-dir="C:\Users\PADAMS~1.PL\AppData\Local\Temp\scoped_dir4048_22909" --window-size=6000,6000 data:, [60.836][INFO]: RESPONSE InitSession unknown error: Chrome failed to start: crashed </code></pre> <p>I'm using:</p> <ul> <li>Chrome 36 </li> <li>ChromeWebDriver 2.10</li> <li>Windows 7</li> </ul> <p>In Process Explorer I can see that chromedriver.exe process is running but no window is opened and after few seconds I get above exception.</p> <p>My starting code is:</p> <pre><code> File f = ResourceProvider.getResource("tools/win/chromedriver.exe"); System.setProperty("webdriver.chrome.driver", f.getAbsolutePath()); return new ChromeDriver(); </code></pre>
25,564,186
10
2
null
2014-08-14 15:13:44.703 UTC
2
2021-09-07 09:24:26.997 UTC
2017-08-22 08:48:31.733 UTC
null
1,268,294
null
1,268,294
null
1
21
google-chrome|selenium|chrome-web-driver
78,851
<p>Eventually I found out that WebDriver was trying to run Chrome from <code>C:\Users\______\AppData\Local\Google\Chrome\Application\chrome.exe</code>, which was not working even when trying it manually. It was very strange because when I launch Chrome I use one installed in <code>Program Files</code> directory and it works without problems.</p> <p>So I had uninstalled Chrome, deleted everything from <code>c:\Users______\AppData\Local\Google\Chrome\</code> and installed Chrome again. After that it started working. </p>
21,718,351
Create if record does not exist
<p>I have 3 models in my rails app</p> <pre><code>class Contact &lt; ActiveRecord::Base belongs_to :survey, counter_cache: :contact_count belongs_to :voter has_many :contact_attempts end class Survey &lt; ActiveRecord::Base has_many :questions has_many :contacts end class Voter &lt; ActiveRecord::Base has_many :contacts end </code></pre> <p>the Contact consists of the voter_id and a survey_id. The Logic of my app is that a there can only be one contact for a voter in any given survey.</p> <p>right now I am using the following code to enforce this logic. I query the contacts table for records matching the given voter_id and survey_id. if does not exist then it is created. otherwise it does nothing.</p> <pre><code>if !Contact.exists?(:survey_id =&gt; survey, :voter_id =&gt; voter) c = Contact.new c.survey_id = survey c.voter_id = voter c.save end </code></pre> <p>Obviously this requires a select and a insert query to create 1 potential contact. When I am adding potentially thousands of contacts at once.</p> <p>Right now I'm using Resque to allow this run in the background and away from the ui thread. What can I do to speed this up, and make it more efficient?</p>
21,718,500
4
1
null
2014-02-12 04:01:47.517 UTC
4
2018-04-07 13:52:43.34 UTC
2014-02-12 04:11:02.863 UTC
null
438,992
null
72,357
null
1
35
ruby-on-rails|ruby-on-rails-4
42,177
<p>You should add first a database index to force this condition at the lowest level as possible:</p> <pre><code>add_index :contacts, [:voter_id, :survey_id], unique: true </code></pre> <p>Then you should add an uniqueness validation at an ActiveRecord level:</p> <pre><code>validates_uniqueness_of :voter_id, scope: [:survey_id] </code></pre> <p>Then <code>contact.save</code> will return <code>false</code> if a contact exists for a specified voter and survey.</p> <p>UPDATE: If you create the index, then the uniqueness validation will run pretty fast.</p>
42,319,247
how to compare two strings in javascript if condition
<p>I'm having trouble recalling how to compare these two strings in an if statement. What I'm string to do is check if my variable <code>compare</code> equals <code>page1</code> or <code>page2</code> if not, go to the else statement. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var compare = "page3"; if (compare === "page1" || "page2") { document.body.innerHTML = "github url"; } else { document.body.innerHTML = "non-github url"; }</code></pre> </div> </div> </p>
42,319,257
4
2
null
2017-02-18 18:46:14.363 UTC
5
2020-03-06 18:36:34.02 UTC
2020-03-06 18:36:34.02 UTC
null
860,099
null
710,887
null
1
12
javascript|if-statement|string-comparison
116,631
<p>You could check every option.</p> <pre><code>if (compare === "page1" || compare === "page2") { </code></pre> <p>Or you could use an array and check with an existential quantifier like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some" rel="noreferrer"><code>Array#some</code></a> against, like</p> <pre><code>if (["page1", "page2"].some(a =&gt; a === compare)) { </code></pre> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var compare = "page3"; if (compare === "page1" || compare === "page2") { document.body.innerHTML = "github url"; } else { document.body.innerHTML = "non-github url"; }</code></pre> </div> </div> </p>
32,984,859
delete confirmation in laravel
<p>I have the following code:</p> <pre><code>@foreach($results as $result) &lt;tr&gt; &lt;td&gt;{{$result-&gt;my_id}}&lt;/td&gt; &lt;td&gt;{{$result-&gt;province_name}}&lt;/td&gt; &lt;td&gt;{{$result-&gt;city_name}}&lt;/td&gt; &lt;td&gt; &lt;a class="btn btn-primary" href="{{route('city-edit', $result-&gt;my_id)}}"&gt;&lt;i class="fa fa-edit"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a class="btn btn-danger" href="{{route('city-delete', $result-&gt;my_id)}}"&gt;&lt;i class="fa fa-trash"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; @endforeach </code></pre> <p>How to add a confirmation on delete each data?</p>
32,985,803
6
1
null
2015-10-07 06:04:46.527 UTC
6
2019-09-07 04:31:05.68 UTC
2015-10-07 07:18:17.947 UTC
null
3,219,613
null
4,860,664
null
1
23
javascript|php|laravel
64,152
<p>I prefer a more easier way, just add <code>onclick="return confirm('Are you sure?')"</code>, as bellow:</p> <pre><code>&lt;a class="btn btn-danger" onclick="return confirm('Are you sure?')" href="{{route('city-delete', $result-&gt;my_id)}}"&gt;&lt;i class="fa fa-trash"&gt;&lt;/i&gt;&lt;/a&gt; </code></pre>
9,319,532
Return value from SQL Server Insert command using c#
<p>Using C# in Visual Studio, I'm inserting a row into a table like this:</p> <pre><code>INSERT INTO foo (column_name) VALUES ('bar') </code></pre> <p>I want to do something like this, but I don't know the correct syntax:</p> <pre><code>INSERT INTO foo (column_name) VALUES ('bar') RETURNING foo_id </code></pre> <p>This would return the <code>foo_id</code> column from the newly inserted row.</p> <p>Furthermore, even if I find the correct syntax for this, I have another problem: I have <code>SqlDataReader</code> and <code>SqlDataAdapter</code> at my disposal. As far as I know, the former is for reading data, the second is for manipulating data. When inserting a row with a return statement, I am both manipulating and reading data, so I'm not sure what to use. Maybe there's something entirely different I should use for this?</p>
9,319,609
3
0
null
2012-02-16 21:43:10.8 UTC
7
2012-02-17 06:13:35.27 UTC
2012-02-17 06:13:35.27 UTC
null
13,302
null
598,639
null
1
25
c#|sql-server|ado.net|insert|return-value
78,203
<p><a href="http://msdn.microsoft.com/en-us/library/ms190315.aspx" rel="noreferrer">SCOPE_IDENTITY</a> returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.</p> <p>You can use <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx" rel="noreferrer">SqlCommand.ExecuteScalar</a> to execute the insert command and retrieve the new ID in one query.</p> <pre><code>using (var con = new SqlConnection(ConnectionString)) { int newID; var cmd = "INSERT INTO foo (column_name)VALUES (@Value);SELECT CAST(scope_identity() AS int)"; using (var insertCommand = new SqlCommand(cmd, con)) { insertCommand.Parameters.AddWithValue("@Value", "bar"); con.Open(); newID = (int)insertCommand.ExecuteScalar(); } } </code></pre>
9,120,552
How do I paste a column of text after a different column of text in Vim?
<p>I have two columns full of text, and I want to get them side-by-side. For example, I have</p> <pre><code>abc def ghi </code></pre> <p>and</p> <pre><code>123 456 789 </code></pre> <p>and I want</p> <pre><code>123 abc 456 def 789 ghi </code></pre> <p>All I can find is how to paste the <em>same</em> line onto the end of every line in a column. I can't figure out how to paste a multi-line block of text on the end of another column.</p>
9,120,598
7
0
null
2012-02-02 21:51:58.537 UTC
32
2022-02-02 06:56:49.307 UTC
2016-08-23 01:24:12.513 UTC
null
4,694,621
null
582
null
1
90
vim
57,550
<p>Use visual block (<code>ctrl-v</code>) to cut the letter column. Then move to the first line of the number column. Move to the end and make one space. Then paste the letter column.</p>
10,370,298
How do I animate in jQuery without stacking callbacks?
<p>Let's say I have three divs, and I'd like each to animate once the previous one is done. Currently, I write this:</p> <pre><code>$('div1').fadeOut('slow', function() { $('div2').fadeOut('slow', function() { $('div3').fadeOut('slow'); }); }); </code></pre> <p>Which is ugly, but manageable.</p> <p>Now imagine I have 10 different animations that need to happen one after the other <strong>on different elements</strong>. Suddenly the code gets so clunky that it's extremely hard to manage...</p> <p>Here's pseudocode for what I'm looking to do:</p> <pre><code>$('div1').fadeOut('slow' { delay_next_function_until_done: true } ); $('div2').fadeOut('slow' { delay_next_function_until_done: true } ); $('div3').animate({ top: 500 }, 1000 ); </code></pre> <p>How do I achieve this?</p>
10,371,485
7
1
null
2012-04-29 06:50:25.023 UTC
11
2013-02-26 15:21:02.263 UTC
2012-04-29 07:22:55.287 UTC
null
601,179
null
118,175
null
1
15
jquery|html|jquery-ui|jquery-animate|jquery-callback
4,919
<p>If you're using a recent version of jQuery, use the animation promises:</p> <pre><code>$('div1').fadeOut('slow').promise().pipe(function() { return $('div2').fadeOut('slow'); }).pipe(function() { return $('div3').animate({ top: 500 }, 1000 ); }); </code></pre> <p>You can make it generic:</p> <pre><code>$.chain = function() { var promise = $.Deferred().resolve().promise(); jQuery.each( arguments, function() { promise = promise.pipe( this ); }); return promise; }; var animations = $.chain(function() { return $('div1').fadeOut('slow'); }, function() { return $('div2').fadeOut('slow'); }, function() { return $('div3').animate({ top: 500 }, 1000 ); }); $.when( animations ).done(function() { // ALL ANIMATIONS HAVE BEEN DONE IN SEQUENCE }); </code></pre> <p>Still a lot of function closures but that's the very nature of Javascript. However, it's much more natural and a lot more flexible using Deferreds/Promises since you avoid callbacks "inception".</p>
22,523,131
dplyr summarise: Equivalent of ".drop=FALSE" to keep groups with zero length in output
<p>When using <code>summarise</code> with <code>plyr</code>'s <code>ddply</code> function, empty categories are dropped by default. You can change this behavior by adding <code>.drop = FALSE</code>. However, this doesn't work when using <code>summarise</code> with <code>dplyr</code>. Is there another way to keep empty categories in the result?</p> <p>Here's an example with fake data.</p> <pre><code>library(dplyr) df = data.frame(a=rep(1:3,4), b=rep(1:2,6)) # Now add an extra level to df$b that has no corresponding value in df$a df$b = factor(df$b, levels=1:3) # Summarise with plyr, keeping categories with a count of zero plyr::ddply(df, "b", summarise, count_a=length(a), .drop=FALSE) b count_a 1 1 6 2 2 6 3 3 0 # Now try it with dplyr df %.% group_by(b) %.% summarise(count_a=length(a), .drop=FALSE) b count_a .drop 1 1 6 FALSE 2 2 6 FALSE </code></pre> <p>Not exactly what I was hoping for. Is there a <code>dplyr</code> method for achieving the same result as <code>.drop=FALSE</code> in <code>plyr</code>?</p>
54,757,520
4
1
null
2014-03-20 03:52:09.237 UTC
30
2019-05-13 13:37:06.297 UTC
2018-03-04 00:16:57.69 UTC
null
496,488
null
496,488
null
1
114
r|dplyr|plyr|tidyr
50,485
<p>Since <em>dplyr 0.8</em> <code>group_by</code> gained the <code>.drop</code> argument that does just what you asked for:</p> <pre class="lang-r prettyprint-override"><code>df = data.frame(a=rep(1:3,4), b=rep(1:2,6)) df$b = factor(df$b, levels=1:3) df %&gt;% group_by(b, .drop=FALSE) %&gt;% summarise(count_a=length(a)) #&gt; # A tibble: 3 x 2 #&gt; b count_a #&gt; &lt;fct&gt; &lt;int&gt; #&gt; 1 1 6 #&gt; 2 2 6 #&gt; 3 3 0 </code></pre> <p>One additional note to go with @Moody_Mudskipper's answer: Using <code>.drop=FALSE</code> can give potentially unexpected results when one or more grouping variables are not coded as factors. See examples below:</p> <pre><code>library(dplyr) data(iris) # Add an additional level to Species iris$Species = factor(iris$Species, levels=c(levels(iris$Species), "empty_level")) # Species is a factor and empty groups are included in the output iris %&gt;% group_by(Species, .drop=FALSE) %&gt;% tally #&gt; Species n #&gt; 1 setosa 50 #&gt; 2 versicolor 50 #&gt; 3 virginica 50 #&gt; 4 empty_level 0 # Add character column iris$group2 = c(rep(c("A","B"), 50), rep(c("B","C"), each=25)) # Empty groups involving combinations of Species and group2 are not included in output iris %&gt;% group_by(Species, group2, .drop=FALSE) %&gt;% tally #&gt; Species group2 n #&gt; 1 setosa A 25 #&gt; 2 setosa B 25 #&gt; 3 versicolor A 25 #&gt; 4 versicolor B 25 #&gt; 5 virginica B 25 #&gt; 6 virginica C 25 #&gt; 7 empty_level &lt;NA&gt; 0 # Turn group2 into a factor iris$group2 = factor(iris$group2) # Now all possible combinations of Species and group2 are included in the output, # whether present in the data or not iris %&gt;% group_by(Species, group2, .drop=FALSE) %&gt;% tally #&gt; Species group2 n #&gt; 1 setosa A 25 #&gt; 2 setosa B 25 #&gt; 3 setosa C 0 #&gt; 4 versicolor A 25 #&gt; 5 versicolor B 25 #&gt; 6 versicolor C 0 #&gt; 7 virginica A 0 #&gt; 8 virginica B 25 #&gt; 9 virginica C 25 #&gt; 10 empty_level A 0 #&gt; 11 empty_level B 0 #&gt; 12 empty_level C 0 Created on 2019-03-13 by the reprex package (v0.2.1) </code></pre>
23,245,365
MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'
<p>I am new to <code>MVC</code>. In My Application , I'm Retrieving the Data from Mydatabase. but when I run my Application it show Error Like This this is my url </p> <pre><code>http://localhost:7317/Employee/DetailsData/4 Exception Details: System.ArgumentException: The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult DetailsData(Int32)' in 'MVCViewDemo.Controllers.EmployeeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters </code></pre> <p>this is my web.config file code</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="EmployeeContext" connectionString="Server=.;Database=mytry;integrated security=true; ProviderName=System.Data.SqlClient"/&gt; &lt;/connectionStrings&gt; </code></pre> <p>this is my Employee Model Class(Employee.cs)</p> <pre><code>[Table("emp")] /* to map tablename with our class name*/ public class Employee { public int EmpId { get; set; } public string Name { get; set; } public string Gender { get; set; } public string City { get; set; } } </code></pre> <p>My EmployeeContext.cs Model class</p> <pre><code> public class EmployeeContext:DbContext { public DbSet&lt;Employee&gt; Employees { get; set; } } </code></pre> <p>my EmployeeController.cs</p> <pre><code> public ActionResult DetailsData(int k) { EmployeeContext Ec = new EmployeeContext(); Employee emp = Ec.Employees.Single(X =&gt; X.EmpId == k); return View(emp); } </code></pre> <p>and my view </p> <pre><code>&lt;h2&gt;DetailsData&lt;/h2&gt; @Model.Name&lt;br /&gt; @Model.City&lt;br /&gt; @Model.Gender&lt;br /&gt; @Model.EmpId </code></pre>
23,245,648
5
1
null
2014-04-23 13:10:17.173 UTC
5
2019-09-12 06:42:10.023 UTC
2015-10-30 06:48:51.023 UTC
user3559349
null
null
2,465,787
null
1
53
c#|asp.net-mvc|asp.net-mvc-4
136,069
<p>It appears that you are using the default route which is defined as this:</p> <pre><code>routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); </code></pre> <p>The key part of that route is the <code>{id}</code> piece. If you look at your action method, your parameter is <code>k</code> instead of <code>id</code>. You need to change your action method to this so that it matches the route parameter:</p> <pre><code>// change int k to int id public ActionResult DetailsData(int id) </code></pre> <p>If you wanted to leave your parameter as k, then you would change the URL to be:</p> <pre><code>http://localhost:7317/Employee/DetailsData?k=4 </code></pre> <p>You also appear to have a problem with your connection string. In your web.config, you need to change your connection string to this (provided by haim770 in another answer that he deleted):</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="EmployeeContext" connectionString="Server=.;Database=mytry;integrated security=True;" providerName="System.Data.SqlClient" /&gt; &lt;/connectionStrings&gt; </code></pre>
35,414,479
Containerized Node server inaccessible with server.listen(port, '127.0.0.1')
<p>I set up a simple Node server in Docker.</p> <p><strong>Dockerfile</strong></p> <pre><code>FROM node:latest RUN apt-get -y update ADD example.js . EXPOSE 1337 CMD node example.js </code></pre> <p><strong>example.js</strong></p> <pre class="lang-js prettyprint-override"><code>var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'+new Date); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); </code></pre> <p>Now build the image</p> <pre><code>$ docker build -t node_server . </code></pre> <p>Now run in container</p> <pre><code>$ docker run -p 1337:1337 -d node_server $ 5909e87302ab7520884060437e19ef543ffafc568419c04630abffe6ff731f70 </code></pre> <p>Verify the container is running and ports are mapped:</p> <pre><code>$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5909e87302ab node_server &quot;/bin/sh -c 'node exa&quot; 7 seconds ago Up 6 seconds 0.0.0.0:1337-&gt;1337/tcp grave_goldberg </code></pre> <p>Now let's attach to the container and verify the server is running inside:</p> <pre><code>$ docker exec -it 5909e87302ab7520884060437e19ef543ffafc568419c04630abffe6ff731f70 /bin/bash </code></pre> <p>And in the container command line type:</p> <pre><code>root@5909e87302ab:/# curl http://localhost:1337 Hello World Mon Feb 15 2016 16:28:38 GMT+0000 (UTC) </code></pre> <p>Looks good right?</p> <p><strong>The problem</strong></p> <p>When I execute the same curl command on the host (or navigate with my browser to http://localhost:1337) I see nothing.</p> <p>Any idea why the port mapping between container and host doesn't work?</p> <p>Things I already tried:</p> <ul> <li>Running with the <code>--expose 1337</code> flag</li> </ul>
35,415,406
2
1
null
2016-02-15 16:36:14.56 UTC
32
2020-12-25 22:35:00.26 UTC
2020-12-25 22:35:00.26 UTC
null
10,008,173
null
2,019,611
null
1
80
networking|docker|port
76,642
<p>Your ports are being exposed correctly but your server is listening to connections on <code>127.0.0.1</code> inside your container:</p> <pre class="lang-js prettyprint-override"><code>http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'+new Date); }).listen(1337, '127.0.0.1'); </code></pre> <p>You need to run your server like this:</p> <pre class="lang-js prettyprint-override"><code>http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'+new Date); }).listen(1337, '0.0.0.0'); </code></pre> <p>Note the 0.0.0.0 instead of 127.0.0.1.</p>
35,432,326
How to get latest offset for a partition for a kafka topic?
<p>I am using the Python high level consumer for Kafka and want to know the latest offsets for each partition of a topic. However I cannot get it to work. </p> <pre><code>from kafka import TopicPartition from kafka.consumer import KafkaConsumer con = KafkaConsumer(bootstrap_servers = brokers) ps = [TopicPartition(topic, p) for p in con.partitions_for_topic(topic)] con.assign(ps) for p in ps: print "For partition %s highwater is %s"%(p.partition,con.highwater(p)) print "Subscription = %s"%con.subscription() print "con.seek_to_beginning() = %s"%con.seek_to_beginning() </code></pre> <p>But the output I get is </p> <pre><code>For partition 0 highwater is None For partition 1 highwater is None For partition 2 highwater is None For partition 3 highwater is None For partition 4 highwater is None For partition 5 highwater is None .... For partition 96 highwater is None For partition 97 highwater is None For partition 98 highwater is None For partition 99 highwater is None Subscription = None con.seek_to_beginning() = None con.seek_to_end() = None </code></pre> <p>I have an alternate approach using <code>assign</code> but the result is the same</p> <pre><code>con = KafkaConsumer(bootstrap_servers = brokers) ps = [TopicPartition(topic, p) for p in con.partitions_for_topic(topic)] con.assign(ps) for p in ps: print "For partition %s highwater is %s"%(p.partition,con.highwater(p)) print "Subscription = %s"%con.subscription() print "con.seek_to_beginning() = %s"%con.seek_to_beginning() print "con.seek_to_end() = %s"%con.seek_to_end() </code></pre> <p>It seems from some of the documentation that I might get this behaviour if a <code>fetch</code> has not been issued. But I cannot find a way to force that. What am I doing wrong?</p> <p>Or is there a different/simpler way to get the latest offsets for a topic?</p>
35,438,403
7
1
null
2016-02-16 12:13:02.63 UTC
10
2022-05-05 11:26:22.807 UTC
null
null
null
null
1,229,509
null
1
32
python|apache-kafka|kafka-consumer-api|kafka-python
53,172
<p>Finally after spending a day on this and several false starts, I was able to find a solution and get it working. Posting it her so that others may refer to it.</p> <pre><code>from kafka import SimpleClient from kafka.protocol.offset import OffsetRequest, OffsetResetStrategy from kafka.common import OffsetRequestPayload client = SimpleClient(brokers) partitions = client.topic_partitions[topic] offset_requests = [OffsetRequestPayload(topic, p, -1, 1) for p in partitions.keys()] offsets_responses = client.send_offset_request(offset_requests) for r in offsets_responses: print "partition = %s, offset = %s"%(r.partition, r.offsets[0]) </code></pre>
35,450,417
Error:Cause: failed to find target with hash string 'Google Inc.:Google APIs:23' in: E:\AndroidStudio\SDK
<p>I have the above error and have no clue why I still have it. I have reinstalled API 23 numerous times and done googling and the only fix I found was to reinstall the API but still have the issue. </p> <p>Does anyone have a fix for it?</p> <pre><code> apply plugin: 'com.android.application' android { compileSdkVersion 'Google Inc.:Google APIs:23' buildToolsVersion '23.0.2' defaultConfig { applicationId "com.example.app" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } lintOptions { disable 'InvalidPackage' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' compile 'me.neavo:volley:2014.12.09' compile 'com.google.code.gson:gson:2.5' compile 'com.jakewharton:butterknife:7.0.1' compile 'com.android.support:support-v4:23.1.1' } </code></pre>
35,450,642
7
1
null
2016-02-17 07:31:03.807 UTC
7
2019-01-10 20:07:21.733 UTC
2016-02-17 07:41:15.067 UTC
null
4,578,531
null
4,578,531
null
1
32
java|android|android-studio
32,992
<p>Try to use <code>compileSdkVersion 23</code> instead of <code>compileSdkVersion 'Google Inc.:Google APIs:23'</code></p>
20,978,189
How does "304 Not Modified" work exactly?
<ul> <li><p>How are "304 Not Modified" responses generated?</p></li> <li><p>How does a browser determine whether the response to an HTTP request is 304?</p></li> <li><p>Is it set by the browser or sent from the server?</p></li> <li><p>If sent by the server, how does the server know the data available in cache, also how does it set 304 to an image?</p></li> </ul> <p><strong>My guess, if it's generated by the browser:</strong></p> <pre><code>function is_modified() { return get_data_from_cache() === get_data_from_url(); } function get_data_from_cache() { return some_hash_or_xxx_function(cache_data); } function get_data_from_url() { return some_hash_or_xxx_function(new_data); } function some_hash_or_xxx_function(data) { // Do something with the data. // What is that algorithm? return result; } console.log(is_modified()); </code></pre> <p>I am relying on a third party API provider to get data, parse &amp; push it to my database. The data may or may not change during every request, but the header always sends <code>200</code>. I do not want to parse, check the last Unique ID in DB and so on... to determine the change in data, nor compare the result directly rather I <code>md5()</code>, <code>sha1()</code> and <code>crc32()</code> hashed the result and works fine, but I'm wondering about the algorithm to determine <code>304</code>.</p> <p>I want to use the same kind of algorithm to determine the change in my data.</p>
20,978,279
2
2
null
2014-01-07 17:36:48.33 UTC
36
2020-04-19 08:33:06.817 UTC
2020-04-19 08:33:06.817 UTC
null
6,862,601
null
1,008,278
null
1
190
http|browser|http-headers|http-status-code-304
169,800
<p>When the browser puts something in its cache, it also stores the <code>Last-Modified</code> or <code>ETag</code> header from the server.</p> <p>The browser then sends a request with the <code>If-Modified-Since</code> or <code>If-None-Match</code> header, telling the server to send a 304 if the content still has that date or ETag.</p> <p>The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.</p>
1,746,115
Substring to truncate text?
<p>I'm trying to figure out how to truncate the first paragraph, and I've tried:</p> <pre><code>$div.children( ('p:eq(0)').substring(0,100)); $div.children( ('p:eq(0)'.substring(0,100))); </code></pre> <p>But neither have worked... </p> <p>Here's the complete code (which someone here helped me with!) </p> <pre><code>$j('#hp-featured-item &gt; div[id^="post-"]').each(function() { var $div = $j(this), $h2 = $div.find('h2:first'), $obj = $div.find('object, embed, img').filter(':first'), id = this.id.match(/^post-([0-9]+)$/); if( $obj.size() &gt; 0){ // Find parent var $par = $obj.closest('p'); // Move to top of div $obj.prependTo($div); // Remove the now empty parent $par.remove(); if( $obj.is('img')){ // You can't wrap objects and embeds with links, so make sure we just wrap images $obj.wrap( $j('&lt;a&gt;&lt;/a&gt;').attr('href', '/blog/?p='+id[1])); } } // Wrap the contents of the h2, not the h2 itself, with a link $h2.wrapInner( $j('&lt;a&gt;&lt;/a&gt;').attr('href', '/blog/?p='+id[1]) ); $div.children( ('p:eq(0)').substring(0,100)); $div.children('p:gt(0)').remove(); }); </code></pre>
1,746,142
3
0
null
2009-11-17 01:53:40.323 UTC
2
2012-03-23 22:51:47.123 UTC
2011-07-11 13:17:36.347 UTC
null
560,648
null
183,819
null
1
6
jquery|substring
73,198
<p>This should work:</p> <pre><code>$fC = $div.children("p:first-child"); $fC.html($fC.html().substring(0, 100)); </code></pre> <p>Tested: it worked for me. My mock-up code: <a href="http://pastebin.com/f737f7ce9" rel="nofollow noreferrer">http://pastebin.com/f737f7ce9</a></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;p&gt;Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.&lt;/p&gt; &lt;p&gt;It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).&lt;/p&gt; &lt;/div&gt; &lt;div&gt; &lt;p&gt;Integer ut sapien vitae orci vehicula mattis at eget lacus. Duis enim purus, sagittis nec euismod vitae, laoreet sit amet augue. Sed lacus risus, congue ac cursus et, consectetur at erat. Vestibulum lobortis tincidunt risus, in malesuada lacus ultrices et. Nulla commodo lectus pharetra purus pulvinar auctor. Duis urna felis, consequat ac facilisis id, ultrices ac tellus. Aliquam id semper dolor. Aenean eu augue augue. Vestibulum a elit turpis. Sed sed dignissim augue. Maecenas malesuada aliquet mi, sit amet facilisis quam posuere ut. Nulla luctus nulla vitae est vehicula mattis. Sed in nisi ac urna egestas condimentum. Nulla facilisi. Proin sit amet justo purus. &lt;/p&gt; &lt;p&gt;Vestibulum ut elit neque, eget blandit nulla. Mauris tortor nulla, tincidunt gravida placerat vel, iaculis nec ipsum. Donec sed quam massa, at dignissim arcu. Sed porta mattis elementum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In hac habitasse platea dictumst. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur vel turpis eget urna eleifend egestas sit amet ut nibh. Integer vitae varius neque. Nullam leo libero, condimentum in mollis ut, ornare et nulla. Etiam at quam quis sapien rutrum porttitor. Ut pellentesque mi vitae odio pellentesque sagittis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus a sapien nulla, a ultricies nibh. Curabitur lectus quam, rhoncus quis elementum a, congue auctor sem. &lt;/p&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt;//&lt;!-- $(window).ready(function(){ $("div").each(function(){ var $div = $(this); var $fC = $div.children("p:first-child"); $fC.html($fC.html().substring(0,100)); }); }); // --&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
2,038,414
Are literal strings and function return values lvalues or rvalues?
<ol> <li><p>Just wonder if a literal string is an lvalue or an rvalue. Are other literals (like int, float, char etc) lvalue or rvalue? </p></li> <li><p>Is the return value of a function an lvalue or rvalue?</p></li> </ol> <p>How do you tell the difference?</p>
2,038,427
3
4
null
2010-01-10 20:08:41.777 UTC
16
2015-06-18 13:55:54.843 UTC
2015-06-18 13:55:54.843 UTC
Roger Pate
895,245
null
156,458
null
1
31
c|lvalue|rvalue
12,481
<ol> <li>string literals are lvalues, but you can't change them</li> <li>rvalue, but if it's a pointer and non-NULL, the object it points to is an lvalue</li> </ol> <p>The C standard recognizes the original terms stood for <em>left</em> and <em>right</em> as in <code>L = R</code>; however, it says to think of lvalue as <em>locator value</em>, which roughly means you can get the address of an object and therefore that object has a location. (See 6.3.2.1 in <a href="http://www.open-std.org/jtc1/sc22/wg14/www/standards.html" rel="noreferrer">C99</a>.)</p> <p>By the same token, the standard has abandoned the term rvalue, and just uses "the value of an expression", which is practically everything, including literals such as ints, chars, floats, etc. Additionally, anything you can do with an rvalue can be done with an lvalue too, so you can think of all lvalues as being rvalues.</p>
8,935,575
align div in the bottom of another div using css
<p>I want to align the <code>DIV c</code> in the bottom of the <code>DIV b</code> not <code>DIV a</code> </p> <pre><code>&lt;div id="a"&gt; &lt;div id="b"&gt; &lt;div id="c"&gt; Div c &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
8,935,596
3
1
null
2012-01-20 01:03:10.933 UTC
5
2017-04-24 06:30:09.807 UTC
2012-01-20 01:06:46.183 UTC
null
873,060
null
508,377
null
1
11
css|html
45,183
<p>This should work:</p> <pre><code>#b { position: relative; } #c { position: absolute; bottom: 0px; } </code></pre> <p>The trick is <code>position: relative;</code> on the parent element. Without that, <code>#c</code> will float away to the bottom of the page.</p>
8,513,408
C++ abstract base class constructors/destructors - general correctness
<p>I would like to have a C++ <code>Interface</code> that must be overridden (if this is possible) when inherited. So far, I have the following:</p> <pre><code>class ICommand{ public: // Virtual constructor. Needs to take a name as parameter //virtual ICommand(char*) =0; // Virtual destructor, prevents memory leaks by forcing clean up on derived classes? //virtual ~ICommand() =0; virtual void CallMe() =0; virtual void CallMe2() =0; }; class MyCommand : public ICommand { public: // Is this correct? MyCommand(char* Name) { /* do stuff */ } virtual void CallMe() {} virtual void CallMe2() {} }; </code></pre> <p>I have purposely left how I think the constructor/destructor's should be implemented in <code>ICommand</code>. I know if I remove the comments, it will not compile. Please could someone:</p> <ol> <li>Show me how to declare the constructor/destructor's in <code>ICommand</code> and how they are meant to be used in <code>MyCommand</code></li> <li>Have I set things up correctly in <code>ICommand</code> so that <code>MyCommand</code> must override <code>CallMe</code> and <code>CallMe2</code>.</li> </ol>
8,513,537
2
1
null
2011-12-14 23:53:36.473 UTC
4
2020-09-14 14:24:52.497 UTC
2020-09-14 14:24:52.497 UTC
null
571,711
null
315,711
null
1
21
c++|inheritance|abstract-class|virtual-inheritance
50,071
<p>C++ does not allow for virtual constructors. A simple implementation (without the virtual constructor) would look something like this:</p> <pre><code>class ICommand { public: virtual ~ICommand() = 0; virtual void callMe() = 0; virtual void callMe2() = 0; }; ICommand::~ICommand() { } // all destructors must exist </code></pre> <p>Note that even a pure virtual destructor <a href="https://stackoverflow.com/questions/630950/pure-virtual-destructor-in-c">must</a> be defined.</p> <p>A concrete implementation would look exactly like your example:</p> <pre><code>class MyCommand : public ICommand { public: virtual void callMe() { } virtual void callMe2() { } }; </code></pre> <p>You have a couple of <a href="http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8" rel="noreferrer">options</a> for the constructor. One option is to disable the default constructor for <code>ICommand</code>, so that subclasses will <em>have</em> to implement a constructor that calls your ICommand constructor:</p> <pre><code>#include &lt;string&gt; class ICommand { private: const std::string name; ICommand(); public: ICommand(const std::string&amp; name) : name(name) { } virtual ~ICommand() = 0; virtual void callMe() = 0; virtual void callMe2() = 0; }; ICommand::~ICommand() { } // all destructors must exist </code></pre> <p>A concrete implementation would now look something like this:</p> <pre><code>class MyCommand : public ICommand { public: MyCommand(const std::string&amp; name) : ICommand(name) { } virtual void callMe() { } virtual void callMe2() { } }; </code></pre>
8,938,498
Get the index of a pattern in a string using regex
<p>I want to search a string for a specific pattern. </p> <p>Do the regular expression classes provide the positions (indexes within the string) of the pattern within the string?<br> There can be more that 1 occurences of the pattern.<br> Any practical example? </p>
8,938,549
3
1
null
2012-01-20 08:19:32.837 UTC
22
2017-06-01 20:56:11.297 UTC
null
null
null
null
384,706
null
1
104
java|regex|string
111,416
<p>Use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html" rel="noreferrer">Matcher</a>:</p> <pre><code>public static void printMatches(String text, String regex) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); // Check all occurrences while (matcher.find()) { System.out.print("Start index: " + matcher.start()); System.out.print(" End index: " + matcher.end()); System.out.println(" Found: " + matcher.group()); } } </code></pre>
19,377,476
Forbidden: You don't have permission to access / on this server, WAMP Error
<p>I have installed <strong>wamp</strong> on <strong>windows 8</strong> and received above error whenever I go to localhost or phpmyadmin. After much searching I found many answers which includes modifying the httpd.conf to <code>Allow from All</code> etc. <a href="https://stackoverflow.com/questions/10873295/error-message-forbidden-you-dont-have-permission-to-access-on-this-server">This</a> link shows such a common answer with further information.</p> <p>My problem is that many have argued that it gives permission to all users to access phpMyAdmin and it is insecure and vulnerable etc. I want to create perfectly secure WAMP server and is it OK if I do this? </p> <p>Can someone please provide me with some reference or information?</p>
19,384,498
5
1
null
2013-10-15 09:18:27.913 UTC
6
2017-11-12 07:20:34.96 UTC
2017-05-23 11:47:23.237 UTC
null
-1
null
2,601,683
null
1
16
apache|windows-8|phpmyadmin|wamp|wampserver
151,758
<p>I find the best (and least frustrating) path is to start with <code>Allow from All</code>, then, when you know it will work that way, scale it back to the more secure <code>Allow from 127.0.0.1</code> or <code>Allow from ::1</code> (localhost). </p> <p>As long as your firewall is configured properly, <code>Allow from all</code> shouldn't cause any problems, but it is better to only allow from localhost if you don't need other computers to be able to access your site. </p> <p>Don't forget to restart Apache whenever you make changes to httpd.conf. They will not take effect until the next start.</p> <p>Hopefully this is enough to get you started, there is lots of documentation available online.</p>
651,664
Can Hibernate be used in performance sensitive applications?
<p>I'm seeing performance problems with retrieving multiple instances of objects that have many relationships with other objects. I'm using Spring and Hibernate's JPA implementation with MySQL. The issue is that when executing a JPA query, Hibernate does not automatically join to other tables. This results in n*r + 1 SQL queries, where n is the number of objects being retrieved and r is the number of relationships.</p> <p>Example, a Person lives at an Address, has many Hobbies, and has visited many Countries:</p> <pre><code>@Entity public class Person { @Id public Integer personId; public String name; @ManyToOne public Address address; @ManyToMany public Set&lt;Hobby&gt; hobbies; @ManyToMany public Set&lt;Country&gt; countriesVisited; } </code></pre> <p>When I perform a JPA query to get all Persons named Bob, and there are 100 Bobs in the database:</p> <pre><code>SELECT p FROM Person p WHERE p.name='Bob' </code></pre> <p>Hibernate translates this to 301 SQL queries:</p> <pre><code>SELECT ... FROM Person WHERE name='Bob' SELECT ... FROM Address WHERE personId=1 SELECT ... FROM Address WHERE personId=2 ... SELECT ... FROM Hobby WHERE personId=1 SELECT ... FROM Hobby WHERE personId=2 ... SELECT ... FROM Country WHERE personId=1 SELECT ... FROM Country WHERE personId=2 ... </code></pre> <p>According to the Hibernate FAQ (<a href="http://www.hibernate.org/118.html#A23" rel="noreferrer">here</a> and <a href="http://www.hibernate.org/117.html#A30" rel="noreferrer">here</a>), the solution is to specify LEFT JOIN or <a href="http://www.hibernate.org/117.html#A12" rel="noreferrer">LEFT OUTER JOIN (for many-to-many)</a> in the query. So now my query looks like:</p> <pre><code>SELECT p, a, h, c FROM Person p LEFT JOIN p.address a LEFT OUTER JOIN p.hobbies h LEFT OUTER JOIN p.countriesVisited c WHERE p.name = 'Bob' </code></pre> <p>This works, but there appears to be a bug if there's more than one LEFT OUTER JOIN in which case Hibernate is incorrectly looking for a non-existent column:</p> <pre><code>could not read column value from result set: personId69_2_; Column 'personId69_2_' not found. </code></pre> <p>The bug behavior appears to be possibly addressed by <a href="http://opensource.atlassian.com/projects/hibernate/browse/HHH-3636" rel="noreferrer">Hibernate Core bug HHH-3636</a>. Unfortunately the fix is not part of any released Hibernate JAR. I've ran my application against the snapshot build but the bug behavior is still present. I've also built my own Hibernate Core JAR from the latest code in the repository and the bug behavior is still present. So maybe HHH-3636 doesn't address this.</p> <p>This Hibernate performance limitation is very frustrating. If I query for 1000 objects then 1000*r + 1 SQL queries are made to the database. In my case I have 8 relationships so I get 8001 SQL queries, which results in horrible performance. The official Hibernate solution to this is to left join all relationships. But this isn't possible with more than one many-to-many relationships due to the bug behavior. So I'm stuck with left joins for many-to-one relationships and n*r+1 queries due to the many-to-many relationships. I plan to submit the LEFT OUTER JOIN problem as a Hibernate bug, but in the meantime my customer needs an app that has reasonable performance. I currently use a combination of batch fetch (BatchSize), ehcache and custom in-memory caching but the performance is still pretty poor (it improved retrieving 5000 objects from 30 to 8 seconds). The bottom line is that too many SQL queries are hitting the database. </p> <p>So, my questions, is it possible to use Hibernate in performance sensitive applications where tables have multiple relationships with each other? I would love to hear how successful Hibernate uses address performance. Should I be hand writing SQL (which somewhat defeats the purpose of using Hibernate)? Should I de-normalize my database schema to reduce the number of joined tables? Should I not be using Hibernate if I need fast query performance? Is there something faster?</p>
651,985
4
1
null
2009-03-16 18:44:49.993 UTC
13
2012-04-25 17:03:54.837 UTC
null
null
null
Steve Kuo
24,396
null
1
21
java|performance|hibernate|jpa|jakarta-ee
10,862
<p>See my answer to your <a href="https://stackoverflow.com/questions/467282/jpa-hibernate-maximum-number-of-joins">other question</a>, if you read the whole of the FAQ you linked to:</p> <blockquote> <p>Follow the best practices guide! Ensure that all and mappings specify lazy=&quot;true&quot; in Hibernate2 (this is the new default in Hibernate3). Use HQL LEFT JOIN FETCH to specify which associations you need to be retrieved in the initial SQL SELECT.</p> <p>A second way to avoid the n+1 selects problem is to use <em><strong>fetch=&quot;subselect&quot;</strong></em> in Hibernate3.</p> <p>If you are still unsure, refer to the Hibernate documentation and Hibernate in Action.</p> </blockquote> <p>See the tips on <a href="http://www.hibernate.org/hib_docs/v3/reference/en-US/html/performance.html" rel="noreferrer">improving performance</a>. If you are not careful with joins, you will end up with <a href="http://en.wikipedia.org/wiki/Cartesian_product" rel="noreferrer">Cartesian Product</a> problems.</p>
928,179
Matching on repeated substrings in a regex
<p>Is it possible for a regex to match based on other parts of the same regex?</p> <p>For example, how would I match lines that begins and end with the same sequence of 3 characters, regardless of what the characters are?</p> <p>Matches:</p> <pre><code>abcabc xyz abc xyz </code></pre> <p>Doesn't Match:</p> <pre><code>abc123 </code></pre> <p>Undefined: (Can match or not, whichever is easiest)</p> <pre><code>ababa a </code></pre> <p>Ideally, I'd like something in the perl regex flavor. If that's not possible, I'd be interested to know if there are any flavors that <em>can</em> do it.</p>
928,195
4
0
null
2009-05-29 21:11:53.887 UTC
3
2009-05-29 21:29:42.447 UTC
null
null
null
null
55,245
null
1
31
regex
33,604
<p>Use capture groups and backreferences.</p> <pre><code>/^(.{3}).*\1$/ </code></pre> <p>The <code>\1</code> refers back to whatever is matched by the contents of the first capture group (the contents of the <code>()</code>). Regexes in most languages allow something like this.</p>
147,908
How do I databind a ColumnDefinition's Width or RowDefinition's Height?
<p>Under the View-Model-ViewModel pattern for WPF, I am trying to databind the Heights and Widths of various definitions for grid controls, so I can store the values the user sets them to after using a GridSplitter. However, the normal pattern doesn't seem to work for these particular properties.</p> <p><em>Note: I'm posting this as a reference question that I'm posting as Google failed me and I had to work this out myself. My own answer to follow.</em></p>
147,928
4
0
null
2008-09-29 08:18:32.457 UTC
7
2022-05-24 23:09:44.81 UTC
null
null
null
Nidonocu
483
null
1
38
wpf|data-binding|grid|column-width|row-height
36,404
<p>There were a number of gotchas I discovered:</p> <ol> <li>Although it may appear like a double in XAML, the actual value for a *Definition's Height or Width is a 'GridLength' struct.</li> <li>All the properties of GridLength are readonly, you have to create a new one each time you change it.</li> <li>Unlike every other property in WPF, Width and Height don't default their databinding mode to 'TwoWay', you have to manually set this.</li> </ol> <p>Thusly, I used the following code:</p> <pre><code>private GridLength myHorizontalInputRegionSize = new GridLength(0, GridUnitType.Auto) public GridLength HorizontalInputRegionSize { get { // If not yet set, get the starting value from the DataModel if (myHorizontalInputRegionSize.IsAuto) myHorizontalInputRegionSize = new GridLength(ConnectionTabDefaultUIOptions.HorizontalInputRegionSize, GridUnitType.Pixel); return myHorizontalInputRegionSize; } set { myHorizontalInputRegionSize = value; if (ConnectionTabDefaultUIOptions.HorizontalInputRegionSize != myHorizontalInputRegionSize.Value) { // Set the value in the DataModel ConnectionTabDefaultUIOptions.HorizontalInputRegionSize = value.Value; } OnPropertyChanged("HorizontalInputRegionSize"); } } </code></pre> <p>And the XAML:</p> <pre><code>&lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="*" MinHeight="100" /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="{Binding Path=HorizontalInputRegionSize,Mode=TwoWay}" MinHeight="50" /&gt; &lt;/Grid.RowDefinitions&gt; </code></pre>
25,579,962
Convert Int to UInt32 in Swift
<p>Im making a Tcp client and therefore using the <code>CFStreamCreatePairWithSocketToHost</code> which is expecting an UInt32 for the second parameter.</p> <p>Here is a sample of what I'm trying to do.:</p> <pre><code>func initNetwork(IP: String, Port: Int) { // relevant stuff //Convert Port:Int to UInt32 to make this shit work! CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, IP as NSString , Port , &amp;readStream, &amp;writeStream) // Irelevant stuff } </code></pre> <p>I have been looking around for a solution for some time now, and i can't seem to find one!</p>
25,580,013
4
0
null
2014-08-30 07:13:54.763 UTC
3
2015-08-19 06:34:53.41 UTC
2014-08-30 15:53:18.923 UTC
null
2,171,063
null
2,171,063
null
1
46
swift|type-conversion
56,065
<p>You can do it easily:</p> <pre><code>var x = UInt32(yourInt) </code></pre>
19,432,092
Can I use a min-height for table, tr or td?
<p>I am trying to show some details of a receive in a table.</p> <p>I want that table to have a min height to show the products. So if there is only one product, the table would have at least some white space at the end. In the other hand if there are 5 or more products, it won't have that empty space.</p> <p>I have tried this CSS:</p> <pre><code>table,td,tr{ min-height:300px; } </code></pre> <p>But it is not working.</p>
19,432,261
7
0
null
2013-10-17 16:21:21.25 UTC
22
2022-01-04 13:01:31.657 UTC
2022-01-04 13:01:31.657 UTC
null
8,839,059
null
1,857,879
null
1
166
html|css
138,766
<p>It's not a nice solution but try it like this:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;div&gt;Lorem&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;div&gt;Ipsum&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>and set the divs to the min-height:</p> <pre><code>div { min-height: 300px; } </code></pre> <p>Hope this is what you want ...</p>
48,583,243
use mat-datepicker directly without input
<p>I want to put the datepicker in a permanent sidebar always visible and not dependent on an input, is this possible? I imagined that just putting the component and adding opened = true could leave the datepicker inside a box always visible.</p>
49,373,845
3
1
null
2018-02-02 12:58:27.77 UTC
4
2020-01-22 16:16:45.133 UTC
null
null
null
null
1,068,412
null
1
31
angular|angular-material2
23,819
<p>turns out this is pretty straightforward import the MatDatePickerModule as per usual and then simply use the mat-calendar selector</p> <pre><code>&lt;mat-calendar&gt;&lt;/mat-calendar&gt; </code></pre> <p>In order to hook into the selection via typescript </p> <pre><code> @ViewChild(MatCalendar) _datePicker: MatCalendar&lt;Date&gt; ngOnInit() { this._datePicker.selectedChange.subscribe(x =&gt; { console.log(x); }); } </code></pre>
33,267,383
How to configure X-Frame-Options in Django to allow iframe embedding of one view?
<p>I'm trying to enable django to allow one specific view to be embedded on external sites, preferabilly without sites restrictions.</p> <p>In my <em>views.py</em> file, I have added the following code, where the view <em>futurebig</em> is the one I want to enable to be embedded:</p> <pre><code>from django.views.decorators.clickjacking import xframe_options_sameorigin ... @xframe_options_sameorigin def futurebig(request): ... return render_to_response('templates/iframe/future_clock_big.html', context_dict, context) </code></pre> <p>which doesn't help as I understand because it only enables embedding in the same server.</p> <p>How can I set the headers for that specific view to enable it to be embedded in any website?</p> <p>For the record, I'm just a frontend developer, the backend developer who developed the site is no longer working with me and refused to document his code, so, If anyone could help me and explain carefully where and what modifications I should do, I'll apreciatte it very much. </p> <p>Thanks.</p> <p>As far as I know, the Django version is 1.6 </p>
33,267,908
3
0
null
2015-10-21 19:12:00.9 UTC
6
2021-02-13 20:08:30.197 UTC
null
null
null
user1230041
null
null
1
37
django|iframe|http-headers|x-frame-options
37,428
<p>You are going in the right direction, but exact decorator which you will need to achieve this is 'xframe_options_exempt'.</p> <pre><code>from django.http import HttpResponse from django.views.decorators.clickjacking import xframe_options_exempt @xframe_options_exempt def ok_to_load_in_a_frame(request): return HttpResponse("This page is safe to load in a frame on any site.") </code></pre> <p>PS: DJango 1.6 is no longer supported. It is good time to get an upgrade.</p>
59,904,719
Instagram Profile Header Layout In Flutter
<p>I've been investigating SliverAppBar, CustomScrollView, NestedScrollView, SliverPersistentHeader, and more. I cannot find a way to build something like the Instagram user profile screen's header where only the tab bar is pinned. The main body of the screen is a TabBarView and each pane has a scrollable list.</p> <p>With SliverAppBar, it is easy to add the TabBar in the bottom parameter. But I want to have an extra widget of unknown/variable height above that TabBar. The extra widget should scroll out of the way when the page is scrolled and and then the TabBar is what is pinned at the top of the screen.</p> <p><a href="https://i.stack.imgur.com/b94cY.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/b94cY.gif" alt="enter image description here"></a></p> <p>All I could manage was a fixed content before the tab bar and a fixed tab bar. I cannot get the header to scroll up and stick the <code>TabBar</code> at the top just just below the <code>AppBar</code>.</p> <pre><code>import 'package:flutter/material.dart'; void main() { runApp(MaterialApp(home: MyApp())); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return DefaultTabController( length: 2, child: Scaffold( appBar: AppBar( title: Text("pabloaleko"), ), body: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: &lt;Widget&gt;[ SliverToBoxAdapter( child: SafeArea( child: Text("an unknown\namount of content\n goes here in the header"), ), ), SliverToBoxAdapter( child: TabBar( tabs: [ Tab(child: Text('Days', style: TextStyle(color: Colors.black))), Tab(child: Text('Months', style: TextStyle(color: Colors.black))), ], ), ), SliverFillRemaining( child: TabBarView( children: [ ListView( children: &lt;Widget&gt;[ ListTile(title: Text('Sunday 1')), ListTile(title: Text('Monday 2')), ListTile(title: Text('Tuesday 3')), ListTile(title: Text('Wednesday 4')), ListTile(title: Text('Thursday 5')), ListTile(title: Text('Friday 6')), ListTile(title: Text('Saturday 7')), ListTile(title: Text('Sunday 8')), ListTile(title: Text('Monday 9')), ListTile(title: Text('Tuesday 10')), ListTile(title: Text('Wednesday 11')), ListTile(title: Text('Thursday 12')), ListTile(title: Text('Friday 13')), ListTile(title: Text('Saturday 14')), ], ), ListView( children: &lt;Widget&gt;[ ListTile(title: Text('January')), ListTile(title: Text('February')), ListTile(title: Text('March')), ListTile(title: Text('April')), ListTile(title: Text('May')), ListTile(title: Text('June')), ListTile(title: Text('July')), ListTile(title: Text('August')), ListTile(title: Text('September')), ListTile(title: Text('October')), ListTile(title: Text('November')), ListTile(title: Text('December')), ], ), ], ), ), ], ), ), ); } } </code></pre> <p><a href="https://i.stack.imgur.com/iZ5rk.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/iZ5rk.gif" alt="enter image description here"></a></p>
59,981,330
2
0
null
2020-01-24 22:56:31.293 UTC
17
2021-06-16 09:19:52.513 UTC
2020-10-06 14:45:14.1 UTC
user10563627
null
null
7,034,640
null
1
19
flutter|dart|flutter-layout|customscrollview|flutter-sliverappbar
7,265
<p>You can achieve this behaviour using <code>NestedScrollView</code> with <code>Scaffold</code>. </p> <p>As we need the widgets between the <code>AppBar</code> and <code>TabBar</code> to be dynamically built and scrolled until <code>TabBar</code> reaches <code>AppBar</code>, use the <code>appBar</code> property of the <code>Scaffold</code> to build your <code>AppBar</code> and use <code>headerSliverBuilder</code> to build other widgets of unknown heights. Use the <code>body</code> property of <code>NestedScrollView</code> to build your tab views.</p> <p>This way the elements of the <code>headerSliverBuilder</code> would scroll away till the <code>body</code> reaches the bottom of the <code>AppBar</code>. </p> <p>Might be a little confusing to understand with mere words, here is an example for you.</p> <p><strong>Code:</strong></p> <pre><code>// InstaProfilePage class InstaProfilePage extends StatefulWidget { @override _InstaProfilePageState createState() =&gt; _InstaProfilePageState(); } class _InstaProfilePageState extends State&lt;InstaProfilePage&gt; { double get randHeight =&gt; Random().nextInt(100).toDouble(); List&lt;Widget&gt; _randomChildren; // Children with random heights - You can build your widgets of unknown heights here // I'm just passing the context in case if any widgets built here needs access to context based data like Theme or MediaQuery List&lt;Widget&gt; _randomHeightWidgets(BuildContext context) { _randomChildren ??= List.generate(3, (index) { final height = randHeight.clamp( 50.0, MediaQuery.of(context).size.width, // simply using MediaQuery to demonstrate usage of context ); return Container( color: Colors.primaries[index], height: height, child: Text('Random Height Child ${index + 1}'), ); }); return _randomChildren; } @override Widget build(BuildContext context) { return Scaffold( // Persistent AppBar that never scrolls appBar: AppBar( title: Text('AppBar'), elevation: 0.0, ), body: DefaultTabController( length: 2, child: NestedScrollView( // allows you to build a list of elements that would be scrolled away till the body reached the top headerSliverBuilder: (context, _) { return [ SliverList( delegate: SliverChildListDelegate( _randomHeightWidgets(context), ), ), ]; }, // You tab view goes here body: Column( children: &lt;Widget&gt;[ TabBar( tabs: [ Tab(text: 'A'), Tab(text: 'B'), ], ), Expanded( child: TabBarView( children: [ GridView.count( padding: EdgeInsets.zero, crossAxisCount: 3, children: Colors.primaries.map((color) { return Container(color: color, height: 150.0); }).toList(), ), ListView( padding: EdgeInsets.zero, children: Colors.primaries.map((color) { return Container(color: color, height: 150.0); }).toList(), ) ], ), ), ], ), ), ), ); } } </code></pre> <p><strong>Output:</strong></p> <p><a href="https://i.stack.imgur.com/6emor.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/6emor.gif" alt="Output Image"></a></p> <p>Hope this helps!</p>
23,359,886
selecting rows in numpy ndarray based on the value of two columns
<p>I have a big <code>np.ndarray (3600000,3)</code>, the <code>HUE</code>, the <code>VALUE</code>, and an associated <code>CLASS</code> number. For each pairs of <code>HUE</code> and <code>VALUE</code> I would like to find, using this array the corresponding <code>Class</code> number. I'm a very beginner in Python and have a hard time doing it. Do you know a way to do it? </p> <p>Thank you in advance!</p>
23,361,571
2
0
null
2014-04-29 08:50:03.9 UTC
15
2014-07-20 09:26:58.783 UTC
2014-04-29 09:06:37.303 UTC
null
553,095
null
3,584,444
null
1
25
python|numpy|multidimensional-array
44,041
<p>I assume your array looks like:</p> <pre><code> |(HUE)(VALUE)(CLASS) row/col| 0 1 2 -------+----------------- 0 | 0 1 2 1 | 3 4 5 2 | 6 7 8 . | . . . . | . . . 3599999| . . . </code></pre> <p>And here is the sample code. For simplicity I changed the size 3600000 to 5.</p> <pre><code>a = np.array(xrange(5 * 3)) a.shape = (5, 3) </code></pre> <p>Now array <code>a</code> look like this:</p> <pre><code>array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]) </code></pre> <p>If you want row with <code>HUE=9</code>, do like this:</p> <pre><code>a[np.where(a[:,0] == 9)] #array([[ 9, 10, 11]]) </code></pre> <p>If you want row with <code>VALUE=4</code>, do like this:</p> <pre><code>a[np.where(a[:,1] == 4)] #array([[3, 4, 5]]) </code></pre> <p>If you want row with <code>HUE=0</code> and <code>VALUE=1</code>, do like this:</p> <pre><code>a[np.where((a[:,0] == 0) * (a[:,1] == 1))] #array([[0, 1, 2]]) </code></pre>
23,375,748
Publish DACPAC to SQL Server 2014 using SqlPackage.exe?
<p>I've been successfully publishing DACPACs to SQL Server 2008-2012 instances using SqlPackage.exe, as installed by SQL Server Data Tools (and typically found in <code>C:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin</code>). However, in attempting to publish a 2014-targeted DACPAC to a SQL Server 2014 instance using this same SqlPackage.exe, I get the following:</p> <pre><code>*** Could not deploy package. Internal Error. The database platform service with type Microsoft.Data.Tools. Schema.Sql.Sql120DatabaseSchemaProvider is not valid. You must make sure the service is loaded, or you must provide the full type name of a valid database platform service. </code></pre> <p>I've found minimal info regarding this; the closest I have found is was a <a href="http://social.msdn.microsoft.com/Forums/windowsazure/en-US/8ac0ae34-e614-4d35-8a50-46931cdad20a/internal-error-import-bacpac-file?forum=ssdsgetstarted" rel="noreferrer">problem</a> publishing to Azure.</p> <p>I've kept up to date with SSDT patches but would guess that the SqlPackage.exe I have (which shows an 11.0.2902.0 version) is simply incompatible. I am able to publish to this same instance using Visual Studio 2012's Publish command so the instance itself does not seem to be the issue.</p> <p>Is there a newer version of SqlPackage available that would support publishing a 2014 DACPAC to a 2014 server? Or another scriptable way to do this?</p>
23,376,593
3
0
null
2014-04-29 21:36:17.387 UTC
14
2017-11-13 15:37:56.427 UTC
2016-12-16 14:12:16.113 UTC
null
466,874
null
466,874
null
1
30
sql-server-2014|sql-server-data-tools|sqlpackage
27,422
<p>Yes, there is a new version supporting SQL Server 2005-2016 available and it installs into a different location than the previous (SQL Server 2012 and lower) version. In fact, you'll have different install locations depending on if you just use SSDT or if you install it as part of SSMS or the standalone installer.</p> <ul> <li><p>SSDT installs the Dac DLLs inside Visual Studio in the latest releases. This is to avoid side by side issues (Visual Studio 2012 vs 2013 vs SSMS) that required all to be updated to use the latest code. </p> <ul> <li>If you have <a href="https://msdn.microsoft.com/en-us/library/mt204009.aspx">updated to the latest SSDT</a>, you'll find SqlPackage.exe and the related DLLs in the <strong>VS Install Directory\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\130</strong>. For VS2013 the VS install directory is <strong>C:\Program Files (x86)\Microsoft Visual Studio 12.0</strong>, and it's 14.0 for VS2015.</li> </ul></li> <li><p><a href="https://msdn.microsoft.com/en-us/library/mt238290.aspx">SQL Server Management Studio (SSMS)</a> and the standalone <a href="https://www.microsoft.com/en-us/download/details.aspx?id=53013">Dac Framework MSI</a> both install to the system-wide location. This is <strong>C:\Program Files (x86)\Microsoft SQL Server\130\Dac\bin</strong>.</p></li> </ul>
21,789,899
How to create single instance WPF Application that restores the open window when an attempt is made to open another instance?
<p>Sorry it the title is hard to understand. I wasn't sure how to word it.</p> <p>I have an application that should only be allowed to run one instance per user session. If the user clicks to launch the application again, I want to bring the one already to focus.</p> <p>The window will likely have Visibility to collapsed.</p> <p>If it's visible I know I can use</p> <pre><code>if (IsIconic(hWnd)) { ShowWindowAsync(hWnd, swRestore); } SetForegroundWindow(hWnd); </code></pre> <p>but if the window is collapsed, is there a way for me to bring it back to visible?</p>
21,791,103
2
0
null
2014-02-14 21:34:10.76 UTC
11
2021-07-09 16:42:12.74 UTC
2014-02-14 23:14:02.513 UTC
null
249,281
null
974,840
null
1
13
c#|wpf
16,194
<p>You're looking for the <a href="http://msdn.microsoft.com/en-us/library/system.threading.mutex%28v=vs.110%29.aspx" rel="noreferrer"><code>Mutex</code> Class</a>. It's pretty complicated, but luckily the Singleton Pattern has been widely discussed. There are several good articles on it, but you can find a good implementation of it in the <a href="http://sanity-free.org/143/csharp_dotnet_single_instance_application.html" rel="noreferrer">C# .NET Single Instance Application</a> page on the Sanity Free Coding website. From the linked page:</p> <pre><code>static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] static void Main() { if(mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); mutex.ReleaseMutex(); } else { MessageBox.Show("only one instance at a time"); } } } </code></pre> <p>Now you're probably wondering how to have a <code>Main</code> method in a WPF Application, right? Well there's a few things that you have to do, but it's not difficult. See the <a href="http://ludovic.chabant.com/devblog/2010/04/20/writing-a-custom-main-method-for-wpf-applications/" rel="noreferrer">Writing a custom Main() method for WPF applications</a> article which explains this in detail. From that article:</p> <blockquote> <p>You basically need to change the application’s build action from “Application Definition” to “Page”, create a constructor that calls “InitializeComponent”, and write your Main() by eventually calling one of the application’s “Run” method overloads. ... Don’t forget, also, to remove the “StartupUri” from the App.xaml, otherwise another copy of window will show up (unless you get an error because the URI points to a non existing XAML resource).</p> </blockquote> <p>So by amalgamating these two resources, we can see that your <code>App.xaml.cs</code> file should look something like this:</p> <pre><code>public partial class App : Application { private static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); private static MainWindow mainWindow = null; App() { InitializeComponent(); } [STAThread] static void Main() { if(mutex.WaitOne(TimeSpan.Zero, true)) { App app = new App(); mainWindow = new MainWindow(); app.Run(mainWindow); mutex.ReleaseMutex(); } else { mainWindow.WindowState = WindowState.Normal; } } } </code></pre>
21,525,328
Python: converting a list of dictionaries to json
<p>I have a list of dictionaries, looking some thing like this:</p> <pre><code>list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}] </code></pre> <p>and so on. There may be more documents in the list. I need to convert these to one JSON document, that can be returned via bottle, and I cannot understand how to do this. Please help. I saw similar questions on this website, but I couldn't understand the solutions there.</p>
21,525,380
4
0
null
2014-02-03 10:50:18.293 UTC
18
2020-01-02 11:53:59.423 UTC
2016-02-18 09:17:55.193 UTC
null
2,314,737
null
3,164,623
null
1
115
python|json|list|dictionary
190,532
<p>use json library</p> <pre><code>import json json.dumps(list) </code></pre> <p>by the way, you might consider changing variable list to another name, <code>list</code> is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.</p>
29,929,411
Disable pinch zoom in webkit (or electron)
<p>Is there any way to disable pinch zoom in an <a href="http://electron.atom.io/" rel="noreferrer">electron</a> app?</p> <p>I can't get it to work from inside the web-view with normal javascript methods as described here: <a href="https://stackoverflow.com/a/23510108/665261">https://stackoverflow.com/a/23510108/665261</a></p> <p>It seems the <code>--disable-pinch</code> flag is <a href="https://github.com/atom/electron/blob/master/docs/api/chrome-command-line-switches.md" rel="noreferrer">not supported by electron</a>.</p> <p>I have experimented with various methods using:</p> <ol> <li><code>event.preventDefault()</code> on javascript <code>touchmove/mousemove</code> events</li> <li><code>meta viewport</code> tags in HTML</li> <li><code>-webkit-text-size-adjust</code> in CSS</li> <li>flags/config for electron</li> </ol> <p>Is there any method either for webkit in general, or <a href="http://electron.atom.io/" rel="noreferrer">electron</a> in particular?</p>
29,994,607
9
0
null
2015-04-28 20:35:31.62 UTC
7
2020-07-01 08:35:12.18 UTC
2017-05-23 11:54:50.79 UTC
null
-1
null
665,261
null
1
37
javascript|html|css|webkit|electron
13,822
<p><strong>UPDATE 2:</strong></p> <p>Use <a href="https://github.com/atom/electron/blob/master/docs/api/web-frame.md#webframesetzoomlevellimitsminimumlevel-maximumlevel">webFrame.setZoomLevelLimits</a> (v0.31.1+) in <strong>render process</strong> (<a href="https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md#differences-between-main-process-and-renderer-process">Differences Between Main Process and Renderer Process</a>). Because smart zoom on mac still work with document.addEventListener.</p> <p>Example <code>require('electron').webFrame.setZoomLevelLimits(1, 1)</code></p> <hr> <p><strong>UPDATE:</strong></p> <p><code>deltaY</code> property for pinch zoom has <code>float</code> value, but normal scroll event return <code>int</code> value. Now solution has no problem with ctrl key.</p> <p><strong><a href="http://output.jsbin.com/tehidu">Demo 2</a></strong>.</p> <pre><code>document.addEventListener('mousewheel', function(e) { if(e.deltaY % 1 !== 0) { e.preventDefault(); } }); </code></pre> <hr> <p>Using Chromium <code>monitorEvents(document)</code> I found that is responsible for this event <code>mousewheel</code>. I don't know, why <code>mousewheel</code> triggered with pinch zoom. Next step, find difference between normal scroll and pinch zoom.</p> <p>Pinch zoom has an attribute <code>e.ctrlKey = true</code>, and normal scroll event has <code>e.ctrlKey = false</code>. But if you hold down <code>ctrl</code> key and scroll a page, <code>e.ctrlKey</code> equal <code>true</code>.</p> <p>I couldn't find a better solution. :(</p> <p><strong><a href="http://output.jsbin.com/yosezo">Demo</a></strong></p> <pre><code>document.addEventListener('mousewheel', function(e) { if(e.ctrlKey) { e.preventDefault(); } }); </code></pre>
34,906,338
Installing anaconda over existing python system?
<p>I found an old windows xp machine running Python <code>2.5.2</code>. I would like to use Anaconda instead. Can I just install Anaconda on it and do I have to uninstall Python 2.5.2? Similarly, I have a Mac system with Python <code>2.7.9</code> working with some NLT libraries and I'd like to get Anaconda running on it too. What's the best course of action to get Anaconda over an existing system that already has python?</p>
34,906,504
3
0
null
2016-01-20 17:14:44.293 UTC
4
2017-07-24 09:44:18.42 UTC
2016-01-20 17:29:30.4 UTC
null
4,952,130
null
1,324,362
null
1
26
python|installation|anaconda|conda
38,102
<p><em>Simply install</em>. </p> <p>Anaconda manages Python for you and creates the appropriate <code>bin</code> directory containing the executable and <code>pkgs</code> directory containing installed packages. All this in a directory structure named <code>anaconda</code> (or <code>anaconda3</code> if using Python 3). Additionally, it alters the search path so the Python inside the <code>anaconda/bin/</code> directory is the one used when the command <code>python</code> is issued.</p> <p>On Ubuntu, it looks like this:</p> <pre><code># added by Anaconda 2.3.0 installer export PATH="/home/jim/anaconda/bin:$PATH" </code></pre> <p>By adding the new path in the beginning of <code>PATH</code> it assures the anaconda <code>bin/python</code> will be located first.</p> <h3>Warning:</h3> <blockquote> <p>do I have to uninstall Python 2.5.2?</p> </blockquote> <p>In general <strong>never remove the 'original' Python unless explicitly allowed by official sources</strong>. In many operating systems Python <strong>is a dependency</strong>; it <strong>must</strong> stay around. I can't speak for old versions of Windows but in general if you're not sure if it is needed or not <strong>leave it</strong>. </p> <p>Removing it might <em>break</em> some completely unrelated things.</p>
34,979,680
ASP.NET Core MVC: setting expiration of identity cookie
<p>In my ASP.NET Core MVC app the lifetime of the authentication cookie is set to 'Session', so it lasts until I close the browser. I use the default authentication scheme for MVC:</p> <pre><code>app.UseIdentity(); </code></pre> <p>How can I extend the lifetime of the cookie?</p>
34,981,457
6
0
null
2016-01-24 18:27:55.96 UTC
19
2017-12-27 07:01:38.273 UTC
2016-03-11 21:13:34.133 UTC
null
1,620,696
null
2,141,207
null
1
40
asp.net-mvc|asp.net-identity|asp.net-core|asp.net-core-mvc
78,577
<p>The ASP.NET Identity middleware which you are using is a wraper around some calls to <code>UseCookieAuthentication</code> which includes the Cookie Authentication middleware on the pipeline. This can be seen on the source code for the builder extensions of the Identity middleware <a href="https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity/BuilderExtensions.cs">here on GitHub</a>. In that case the options needed to configure how the underlying Cookie Authentication should work are encapsulated on the <code>IdentityOptions</code> and configured when setting up dependency injection.</p> <p>Indeed, looking at the source code I linked to you can see that the following is run when you call <code>app.UseIdentity()</code>:</p> <pre><code>var options = app.ApplicationServices.GetRequiredService&lt;IOptions&lt;IdentityOptions&gt;&gt;().Value; app.UseCookieAuthentication(options.Cookies.ExternalCookie); app.UseCookieAuthentication(options.Cookies.TwoFactorRememberMeCookie); app.UseCookieAuthentication(options.Cookies.TwoFactorUserIdCookie); app.UseCookieAuthentication(options.Cookies.ApplicationCookie); return app; </code></pre> <p>To setup the <code>IdentityOptions</code> class, the <code>AddIdentity&lt;TUser, TRole&gt;</code> method has one overloaded version which allows to configure the options with one lambda. Thus you just have to pass in a lambda to configure the options. In that case you just access the <code>Cookies</code> properties of the options class and configure the <code>ApplicationCookie</code> as desired. To change the time span you do something like</p> <pre><code>services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;(options =&gt; { options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(1); }); </code></pre> <p><strong>EDIT:</strong> The <code>ExpireTimeSpan</code> property is only used if when calling <code>HttpContext.Authentication.SignInAsync</code> we pass in an instance of <code>AuthenticationProperties</code> with <code>IsPersistent</code> set to <code>true</code>. </p> <p>Trying out just with the Cookie Authentication Middleware it turns out that this works: if we just sign in without this option, we get a cookie that lasts for the session, if we send this together we get a cookie which lasts what we setup when configuring the middleware.</p> <p>With ASP.NET Identity the way to do is pass the parameter <code>isPersistent</code> of the <code>PasswordSignInAsync</code> with value <code>true</code>. This ends up being a call to <code>SignInAsync</code> of the <code>HttpContext</code> passing in the <code>AuthenticationProperties</code> with the <code>IsPersistent</code> set to true. The call ends up being something like:</p> <pre><code>var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); </code></pre> <p>Where the <code>RememberMe</code> is what configures if we are setting <code>IsPersistent</code> to true or false.</p>
17,765,301
Graphviz dot: How to change the colour of one record in multi-record shape
<p>I have the following dot sample. I would like to give the first section in each record (the table name) a different background and foreground colour. I can't find any examples of how to do this for a record. Basically I want the table name in the sql query schema diagram to stand out. Can anyone help?</p> <pre><code>digraph G { rankdir=LR; node [shape=record]; corpus_language [label="corpus_language|&lt;id&gt; id\len\l|&lt;name&gt; name\lEnglist\l|&lt;sentence_count&gt; sentence_count\l1027686\l"]; corpus_sentence [label="corpus_sentence|&lt;id&gt; id\l1241798\l|&lt;text&gt; text\lBaseball is a sport\l|&lt;creator_id&gt; creator_id\l10859\l|&lt;created_on&gt; created_on\l2006-11-14 17:58:09.303128\l|&lt;language_id&gt; language_id\len\l|&lt;activity_id&gt; activity_id\l11\l|&lt;score&gt; score\l124\l"]; corpus_language:id -&gt; corpus_sentence:language_id [arrowhead=normal label=language_id]; } </code></pre>
17,795,344
1
1
null
2013-07-20 18:23:49.737 UTC
12
2013-07-22 19:01:03.25 UTC
null
null
null
null
941,397
null
1
25
graphviz|dot
14,377
<p>I'm pretty sure that it's not possible. Instead you should use HTML-style labels, that are a more developped form of record nodes. You can define your node using the <code>&lt;table&gt;</code> tag, and set the color using <code>bgcolor="your_color"</code>. A list of available colors is available here: <a href="http://www.graphviz.org/doc/info/colors.html" rel="noreferrer">http://www.graphviz.org/doc/info/colors.html</a> (you also have a RGBA way of doing it, as described here: <a href="http://www.graphviz.org/doc/info/attrs.html#k:color" rel="noreferrer">http://www.graphviz.org/doc/info/attrs.html#k:color</a>)</p> <p>With HTML labels, your example becomes as follows:</p> <pre><code>digraph G { rankdir = LR; node1 [ shape = none label = &lt;&lt;table border="0" cellspacing="0"&gt; &lt;tr&gt;&lt;td port="port1" border="1" bgcolor="red"&gt;corpus_language&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td port="port2" border="1"&gt;id: en&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td port="port3" border="1"&gt;name: Englist&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td port="port4" border="1"&gt;sentence_count: 1027686&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt;&gt; ] node2 [ shape = none label = &lt;&lt;table border="0" cellspacing="0"&gt; &lt;tr&gt;&lt;td port="port1" border="1" bgcolor="blue"&gt;corpus_sentence&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td port="port2" border="1"&gt;id: 1241798&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td port="port3" border="1"&gt;text: Baseball is a sport&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td port="port4" border="1"&gt;creator_id: 10859&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td port="port5" border="1"&gt;created_on: 2006-11-14 17:58:09.303128&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td port="port6" border="1"&gt;language_id: en&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td port="port7" border="1"&gt;activity_id: 11&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td port="port8" border="1"&gt;score: 124&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt;&gt; ] node1:port2 -&gt; node2:port6 [label="language_id"] } </code></pre> <p>Here is the result:</p> <p><img src="https://i.stack.imgur.com/PKMo3.png" alt="enter image description here"></p>
49,629,797
Routing on button click in angular 5
<p>I need to route to a home component when the user clicks a button. I know how to do that using: <code>&lt;a href=””&gt;</code>, but not using: <code>routerLink</code>. Is there any way to do that using a <code>button</code> <code>click</code> event?</p> <pre><code>&lt;a class="nav-item nav-link-edit" [routerLink]="['']"&gt;home&lt;/a&gt; </code></pre> <p>The code above is how I use an <code>&lt;a href=""&gt;</code> tag to route.</p>
49,629,857
2
0
null
2018-04-03 12:10:50.903 UTC
1
2019-09-23 16:21:17.527 UTC
2019-09-23 16:21:17.527 UTC
null
1,314,132
null
4,156,974
null
1
19
angular|routing|angular5
61,629
<p>Yes, <code>routerLink</code> works on both anchor tags and button tags. You can do this:</p> <pre class="lang-html prettyprint-override"><code>&lt;button class="nav-item nav-link-edit" [routerLink]="['']"&gt;home&lt;/button &gt; </code></pre>
34,844,711
convert entire pandas dataframe to integers in pandas (0.17.0)
<p>My question is very similar to <a href="https://stackoverflow.com/questions/33126477/pandas-convert-objectsconvert-numeric-true-deprecated">this one</a>, but I need to convert my entire dataframe instead of just a series. The <code>to_numeric</code> function only works on one series at a time and is not a good replacement for the deprecated <code>convert_objects</code> command. Is there a way to get similar results to the <code>convert_objects(convert_numeric=True)</code> command in the new pandas release?</p> <p>Thank you Mike Müller for your example. <code>df.apply(pd.to_numeric)</code> works very well if the values can all be converted to integers. What if in my dataframe I had strings that could not be converted into integers? Example: </p> <pre><code>df = pd.DataFrame({'ints': ['3', '5'], 'Words': ['Kobe', 'Bryant']}) df.dtypes Out[59]: Words object ints object dtype: object </code></pre> <p>Then I could run the deprecated function and get:</p> <pre><code>df = df.convert_objects(convert_numeric=True) df.dtypes Out[60]: Words object ints int64 dtype: object </code></pre> <p>Running the <code>apply</code> command gives me errors, even with try and except handling.</p>
34,844,867
4
0
null
2016-01-17 22:48:58.22 UTC
12
2020-12-29 22:45:45.527 UTC
2017-05-23 12:02:51.35 UTC
null
-1
null
5,104,502
null
1
66
python|pandas
119,709
<h2>All columns convertible</h2> <p>You can apply the function to all columns:</p> <pre><code>df.apply(pd.to_numeric) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'a': ['1', '2'], 'b': ['45.8', '73.9'], 'c': [10.5, 3.7]}) &gt;&gt;&gt; df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 2 entries, 0 to 1 Data columns (total 3 columns): a 2 non-null object b 2 non-null object c 2 non-null float64 dtypes: float64(1), object(2) memory usage: 64.0+ bytes &gt;&gt;&gt; df.apply(pd.to_numeric).info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 2 entries, 0 to 1 Data columns (total 3 columns): a 2 non-null int64 b 2 non-null float64 c 2 non-null float64 dtypes: float64(2), int64(1) memory usage: 64.0 bytes </code></pre> <h2>Not all columns convertible</h2> <p><code>pd.to_numeric</code> has the keyword argument <code>errors</code>:</p> <blockquote> <pre><code> Signature: pd.to_numeric(arg, errors='raise') Docstring: Convert argument to a numeric type. Parameters ---------- arg : list, tuple or array of objects, or Series errors : {'ignore', 'raise', 'coerce'}, default 'raise' - If 'raise', then invalid parsing will raise an exception - If 'coerce', then invalid parsing will be set as NaN - If 'ignore', then invalid parsing will return the input </code></pre> </blockquote> <p>Setting it to <code>ignore</code> will return the column unchanged if it cannot be converted into a numeric type.</p> <p>As pointed out by Anton Protopopov, the most elegant way is to supply <code>ignore</code> as keyword argument to <code>apply()</code>:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'ints': ['3', '5'], 'Words': ['Kobe', 'Bryant']}) &gt;&gt;&gt; df.apply(pd.to_numeric, errors='ignore').info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 2 entries, 0 to 1 Data columns (total 2 columns): Words 2 non-null object ints 2 non-null int64 dtypes: int64(1), object(1) memory usage: 48.0+ bytes </code></pre> <p>My previously suggested way, using <a href="https://docs.python.org/3/library/functools.html?highlight=partial#functools.partial" rel="noreferrer">partial</a> from the module <code>functools</code>, is more verbose:</p> <pre><code>&gt;&gt;&gt; from functools import partial &gt;&gt;&gt; df = pd.DataFrame({'ints': ['3', '5'], 'Words': ['Kobe', 'Bryant']}) &gt;&gt;&gt; df.apply(partial(pd.to_numeric, errors='ignore')).info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 2 entries, 0 to 1 Data columns (total 2 columns): Words 2 non-null object ints 2 non-null int64 dtypes: int64(1), object(1) memory usage: 48.0+ bytes </code></pre>
34,434,218
IOS stackview addArrangedSubview add at specific index
<p>How is it possible to add a arranged subview in a particular index in a UIStackView?</p> <p>something like: </p> <pre><code>stackView.addArrangedSubview(nibView, atIndex: index) </code></pre>
34,434,267
2
0
null
2015-12-23 11:02:53.57 UTC
6
2020-12-04 10:09:26.117 UTC
null
null
null
null
2,364,774
null
1
50
ios|swift|uistackview
18,345
<p>You mean you want to insert, not add:</p> <pre><code>func insertArrangedSubview(_ view: UIView, atIndex stackIndex: Int) </code></pre>
29,216,057
Time Series Breakout/Change/Disturbance Detection in R: strucchange, changepoint, BreakoutDetection, bfast, and more
<p>I would like for this to become a sign-post for various time series breakout/change/disturbance detection methods in R. My question is to describe the motivation and differences in approaches with each of the following packages. That is, when does it make more sense to use one approach over the other, similarities/differences, etc.</p> <p>Packages in question:</p> <ul> <li><a href="http://cran.r-project.org/web/packages/strucchange/index.html" rel="nofollow noreferrer">strucchange</a> (example <a href="http://rpubs.com/sinhrks/plot_ts" rel="nofollow noreferrer">here</a>)</li> <li><a href="http://cran.r-project.org/web/packages/changepoint/index.html" rel="nofollow noreferrer">changepoint</a> (example <a href="http://rpubs.com/sinhrks/plot_ts" rel="nofollow noreferrer">here</a>)</li> <li><a href="https://github.com/twitter/BreakoutDetection" rel="nofollow noreferrer">BreakoutDetection</a> (link includes simple example)</li> <li><a href="http://cran.r-project.org/web/packages/qcc/qcc.pdf" rel="nofollow noreferrer">qcc's Control Charts</a> (tutorial <a href="http://blog.yhathq.com/posts/quality-control-in-r.html" rel="nofollow noreferrer">here</a>)</li> <li><a href="http://cran.r-project.org/web/packages/bfast/index.html" rel="nofollow noreferrer">bfast</a></li> <li>Perhaps (?) to a lesser extent: <a href="https://github.com/twitter/AnomalyDetection" rel="nofollow noreferrer">AnomalyDetection</a> and <a href="http://cran.r-project.org/web/packages/mvoutlier/index.html" rel="nofollow noreferrer">mvOutlier</a></li> </ul> <p>I am hopeful for targeted answers. Perhaps a paragraph for each method. It is easy to slap each of these across a time series but that can come at the cost of abusing/violating assumptions. There are resources that provide guidelines for ML supervised/unsupervised techniques. I (and surely others) would appreciate some guidepost/pointers around this area of time-series analysis. </p>
29,441,399
1
0
null
2015-03-23 17:03:25.727 UTC
9
2017-12-24 01:04:04.757 UTC
2017-12-24 01:02:30.183 UTC
null
2,587,908
null
2,572,423
null
1
10
r|time-series|data-mining
3,743
<p>Two very different motivations have led to time-series analysis:</p> <ol> <li><strong>Industrial quality control</strong> and <strong>detection of outliers</strong>, detecting deviations from a stable noise.</li> <li><strong>Scientific understanding of trends</strong>, where the understanding of trends and of their determinants is of central importance.</li> </ol> <p>Of course both are to a large extent two sides of a same coin and the <strong>detection of outliers</strong> can be important for time series cleaning before trends analysis. I will nevertheless try hereafter to use this distinction as a red line to explain the diversity of packages offered by R to study time-series. </p> <p>In <strong>quality control</strong>, the stability of the mean and standard deviation are of major importance as exemplified by the <a href="http://en.wikipedia.org/wiki/Control_chart#History" rel="nofollow noreferrer">history of one of the first statistical efforts to maintain industrial quality, the control chart</a>. In this respect, <a href="http://cran.r-project.org/web/packages/qcc/index.html" rel="nofollow noreferrer">qcc</a> is a reference implementation of the <a href="https://inst.eecs.berkeley.edu/~ee290h/fa05/Lectures/PDF/lecture%2014%20CUSUM%20and%20EWMA.pdf" rel="nofollow noreferrer">most classical quality control diagrams: Shewhart quality control, cusum and EWMA charts</a>. </p> <p>The old but still active <a href="http://cran.r-project.org/web/packages/mvoutlier/index.html" rel="nofollow noreferrer">mvoutlier</a> and the more recent <a href="https://github.com/twitter/AnomalyDetection" rel="nofollow noreferrer">AnomalyDetection</a> focus on <strong>outliers detection</strong>. mvoutlier mainly uses the Mahalanobis distance and can work with two dimensional datasets (rasters) and even multi-dimensional datasets using using the algorithm of Filzmoser, Maronna, and Werner (2007). AnomalyDetection uses the <a href="http://en.wikipedia.org/wiki/Decomposition_of_time_series" rel="nofollow noreferrer">time series decomposition</a> to identify both local anomalies (outlyers) and global anomalies (variations not explained by seasonal patterns). and <a href="https://github.com/twitter/BreakoutDetection" rel="nofollow noreferrer">BreakoutDetection</a> </p> <p>As AnomalyDetection, <a href="https://github.com/twitter/BreakoutDetection" rel="nofollow noreferrer">BreakoutDetection</a> have been open-sourced by twitter in 2014. <a href="https://github.com/twitter/BreakoutDetection" rel="nofollow noreferrer">BreakoutDetection</a>, <a href="http://www.r-bloggers.com/evaluating-breakoutdetection/" rel="nofollow noreferrer">open-sourced in 2014 by Twitter</a>, intends to detect <strong>breakouts</strong> it time series, that is groups of anomalies, using non-parametric statistics. The detection of breakouts comes very close to the detection of trends and understanding of patterns. In a similar optic, the <a href="http://cran.r-project.org/web/packages/bcpa/index.html" rel="nofollow noreferrer">brca</a> package focuses on the analysis of irregularly sampled time-series, particularly to identify <a href="http://wiki.cbr.washington.edu/qerm/index.php/Behavioral_Change_Point_Analysis" rel="nofollow noreferrer">behavioral changes in animal movement</a>.</p> <p>Definitely shifting to determination of <strong>changes in trends</strong> <a href="http://cran.r-project.org/web/packages/changepoint/changepoint.pdf" rel="nofollow noreferrer">changepoint</a> implements multiple (simple) frequentist and non-parametric methods to detect single or multiple breaks in time series trends. <a href="http://cran.r-project.org/web/packages/strucchange/index.html" rel="nofollow noreferrer">strucchange</a> allows to fit, plot and test trend changes using regression models. Finally, <a href="http://cran.r-project.org/web/packages/bfast/index.html" rel="nofollow noreferrer">bfast</a> builds on strucchange to analyze raster (e.g. satellite images) time series and handles missing data.</p>