pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
9,954,869 | 0 | <p>If I understood well, you would like include the code from <code>includefile.php</code> into your test.php ?</p> <p>You can't use include like that, but you should do it like that.</p> <pre><code>file_put_contents($file, file_get_contents('includefile.php'), FILE_APPEND); </code></pre> <p>This will append the content from <code>includefile.php</code> into your <code>test.php</code></p> |
1,017,873 | 0 | <p>I separated the values by Environment.NewLine and then used a pre tag in html to emulate the effect I was looking for</p> |
10,311,565 | 0 | <p>As I understand the problem this will work:</p> <pre><code>SELECT t.value, t.from_id, t.to_id, t.loop_id FROM MyResults t INNER JOIN ( SELECT From_ID, To_ID, MIN(Value) [Value] FROM MyResults WHERE Loop_ID % 2 = 0 GROUP BY From_ID, To_ID ) MinT ON MinT.From_ID = t.From_ID AND MinT.To_ID = t.To_ID AND MinT.Value = t.Value </code></pre> <p>However, if you had duplicate values for a From_ID and To_ID combination e.g.</p> <pre><code>value from_id to_id loop_id ------------------------------------- 0.1 A B 2 0.1 A B 4 </code></pre> <p>This would return both rows.</p> <p>If you are using SQL-Server 2005 or later and you want the duplicate rows as stated above you could use:</p> <pre><code>SELECT Value, From_ID, To_ID, Loop_ID FROM ( SELECT *, MIN(Value) OVER(PARTITION BY From_ID, To_ID) [MinValue] FROM MyResults ) t WHERE Value = MinValue </code></pre> <p>If you did not want the duplicate rows you could use this:</p> <pre><code>SELECT Value, From_ID, To_ID, Loop_ID FROM ( SELECT *, ROW_NUMBER() OVER(PARTITION BY From_ID, To_ID ORDER BY Value, Loop_ID) [RowNumber] FROM MyResults ) t WHERE RowNumber = 1 </code></pre> |
1,624,454 | 0 | <p>Install an SSH client on you iPhone, e.g. pTerm. I choose this solution for sending the occasional command to an appliance.</p> <p>There is a somewhat half baked recipe on compiling libssh2 for use on the iPhone at:</p> <p><a href="http://sites.google.com/site/olipion/cross-compilation/libssh2" rel="nofollow noreferrer"><a href="http://sites.google.com/site/olipion/cross-compilation/libssh2" rel="nofollow noreferrer">http://sites.google.com/site/olipion/cross-compilation/libssh2</a></a></p> <p>Examples can be found on the libssh2 website</p> <p><a href="http://www.libssh2.org/examples/" rel="nofollow noreferrer"><a href="http://www.libssh2.org/examples/" rel="nofollow noreferrer">http://www.libssh2.org/examples/</a></a></p> |
11,377,999 | 0 | <p>I see that pretty much all the different options have already been laid out in different answers, but instead of commenting on all to give you my impression on what I think you should do, I'll just create an answer myself.</p> <p>Just to be clear on how I understand how the system works: All users can have multiple belongings, but any belonging can only be help by one person.</p> <p>In this case, it makes the most sense to have a user_id in the belongings table that can tie a belonging to a person. Once a user_id is set, nobody else can claim it anymore.</p> <p>Now, as to the 'favorite' part, there are several things you can do. What truly is the best way to do it strongly depends on the queries you plan on running on it. Some consider adding a JOIN table, but honestly this is a lot of additional data that is rather pointless; there is likely going to be the exact amount of rows in it as the user table and by putting it in a separate table, there is a lot you can't do (for example, see how many people DON'T have a favorite). Likewise, a JOIN table would make no sense for the user_belonging relationship, as there is a 1:1 relationship between the belonging and the amount of people who can have it.<br /> So I believe there are two viable options: either add a field (/switch) in the belongings table to indicate of a user's belonging is his/ her favorite, or add a field to the user table to indicate which belonging is the user's favorite. I would personally think that the latter holds the most merit, but depending on the queries you run, it might make more sense to to the former. Overall, the biggest difference is whether you want to process things pre-insert or post-select; e.g. in the latter situation, you will have to run an independent query to figure out if the user already has a favorite (in the former case this won't be necessary as you would put a unique index on the field in the user table), whereas in a post-select situation you will have to do cross reference which of the selected belongings from the belonging table is the user's favorite.</p> <p>Please let me know if I explained myself clearly, or if you have any further questions.</p> |
33,743,362 | 0 | <p>You are experiencing a side-effect from <code>i++</code> which puts you at the mercy of the optimizer which has some leverage as to when to do the increment the way you wrote the code. To be safe, do</p> <pre><code>data[i] = temp[i]; i++; </code></pre> |
22,688,525 | 0 | <p>Have you tried to replace </p> <pre><code>return false; </code></pre> <p>by</p> <pre><code>return true; </code></pre> <p>on your <code>onLongClick(View v)</code> method ? </p> |
35,760,750 | 0 | <p>Thanks to the help of @RenatoMendesFigueiredo, @hasumedic & (the most part) @Cerad, without need of premium plan, I can see the point of this warning and figure it out.</p> <p>In fact, a long time ago, I would make my service extending the <a href="http://api.symfony.com/3.0/Symfony/Component/DependencyInjection/ContainerAware.html" rel="nofollow noreferrer"><code>ContainerAware</code></a> rather than write the method directly, but forced to live with its limits (the service could not have extended another class). </p> <p>In 2.4, the <a href="http://api.symfony.com/3.0/Symfony/Component/DependencyInjection/ContainerAwareTrait.html" rel="nofollow noreferrer"><code>ContainerAwareTrait</code></a> was added. </p> <p>My guess is that the warning has been added in the same time as this trait, because :</p> <p>1) No reason to write a setter or a constructor to inject the container if a trait that do it already exists.</p> <p>2) No need of pass the container as an argument in an another goal than inject it to a service.</p> <p>Also, I removed the <code>setContainer</code> method from the class of my service, make it use the <code>ContainerAwareTrait</code> and keep the the service definition as before.</p> <p><em>And ...</em></p> <p><a href="https://i.stack.imgur.com/RKt0e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RKt0e.png" alt="Kudos"></a></p> <p><strong>Kudos</strong>!</p> |
36,071,391 | 0 | <p>I'm surprised you had to ask, since it's basic Javascript, really... </p> <p>Since <code>press</code> is invoked from <code>oToggleButton</code>, the <code>this</code> keyword now holds a reference to <code>oToggleButton</code>, and <strong>not</strong> the controller (hence why the <code>getView()</code> method fails). Search for 'this keyword in inner function' for more info.</p> <p>To solve this, simply add a reference to this outside the inner function:</p> <p><code>var that = this;</code></p> <p>and in your inner function, use the reference instead:</p> <p><code>that.getView().addStyleClass("sapUiSizeCompact");</code></p> |
5,270,408 | 0 | <p>Your WHERE clause contains only joins. There are no filters. This means your query needs to consider all the rows in at least one table. From this it follows that your query should execute a FULL TABLE SCAN of at least one of your tables, not an indexed read. A full table scan is the most efficient way of getting all the rows in a table. </p> <p>So don't fix the syntax of your INDEX hint, get rid of it.</p> <p>Next, figure out which table should drive your query. This is business logic. Probably your requirement is something like </p> <blockquote> <p>"Summarise BL_DETAILS and BL_FREIGHT for every row in BL_CONTAINERS."</p> </blockquote> <p>In which case you might think you need a full table scan of BL_CONTAINERS. But if BL_FREIGHT has more rows than BL_CONTAINERS and every BLF_REF_NO matches a BL_REF_NO (i.e. there is a foreign key on BL_FREIGHT.BLF_REF_NO referencing BL_CONTAINERS.BL_REF_NO) it would probably be better to drive from BL_FREIGHT.</p> <p>Note that this is true if you are only interested in BL_CONTAINERS which have matching BL_FREIGHT rows. But if you want to include containers which have not been used (i.e. they have no matching no BL_FREIGHT records) you need to use outer joins and drive off the BL_CONTAINERS table.</p> <p>These considerations get more complicated when you throw BL_DETAILS into the mix. Your report seems to be based around the BL_DETAILS categories (as Jeffrey observes it is hard for us to understand your query without aliases or describes). So perhaps BL_DETAILS is the right candidate for driving table.</p> <p>As you can see, tuning requires insight into the business logic and the details of the data model. You have that local knowledge, we do not.</p> <p>There are tools which can help you. Oracle has EXPLAIN PLAN which will show you how the database will execute the query. The query optimizer gets better with each release so it matters which version of the database you're using. Here is <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm" rel="nofollow">the documentation for 10g</a>.</p> <p>The important thing to note is that you need to give the database accurate statistics, in order for it to come up with a good plan. <a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_stats.htm" rel="nofollow">Find out more.</a> </p> |
20,816,944 | 0 | <pre><code>perl -ne 'print [ split /\(/ ]->[0]' 8-8TRI.txt ^__ backslash for '(' </code></pre> <p>You don't need array reference, so</p> <pre><code>perl -ne 'print( (split /\(/ )[0] )' 8-8TRI.txt </code></pre> |
26,288,633 | 0 | Tcl file parser for PYTHON <p>I have a .tcl file. </p> <p>Is there any parser available which directly extracts data from .tcl file ? I don't want to use REGEX for this task. Is pyparsing will work for this problem ?</p> <p>I am using Python 2.7 </p> |
25,283,128 | 0 | <p>I would say you try a total clean reinstall/rebuild with cordova. First off all you have to install cordova for that. If you want to know, how to get started with that you should have a look into the cordova documentation: <a href="http://cordova.apache.org/docs/en/3.5.0/guide_cli_index.md.html#The%20Command-Line%20Interface" rel="nofollow">Cordova CLI-Docs</a></p> <p>After you installed cordova, you enter the Terminal and type in the following commands:</p> <ul> <li>cd ~/desktop</li> <li>cordova create test com.example.test test</li> <li>cd test</li> <li>cordova platform add android</li> <li>cordova plugin add org.apache.cordova.device-motion</li> <li>cordova build</li> </ul> <p>Open the builded project in Eclipse and add </p> <pre><code><!DOCTYPE html> <html> <head> <title>Acceleration Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // document.addEventListener("deviceready", onDeviceReady, false); // device APIs are available // function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration(onSuccess, onError); } // onSuccess: Get a snapshot of the current acceleration // function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } </script> </head> <body> <h1>Example</h1> <p>getCurrentAcceleration</p> </body> </html> </code></pre> <p>Save all and deploy the project to your device. And let me know, if this worked or not.</p> |
15,091,724 | 0 | In jQuery SVG why do coordinates not work as expected <p>I load two images in jQuery SVG using the code:</p> <pre><code>svg.image(0, 0, 330, 540, 'images/img1.jpg', {id: 'img'}); svg.image(0, 0, 330, 540, 'images/iPhone5png.png', {id: 'imgphone'}); </code></pre> <p>After the images are loaded it looks like this:</p> <p><img src="https://i.stack.imgur.com/XVy6h.png" alt="enter image description here"></p> <p>I rotate the images (of bottles) to 90 degree:</p> <p><img src="https://i.stack.imgur.com/AwUlb.png" alt="enter image description here"></p> <p>Now if I try to more the (bottle) image left or right interactively using following code:</p> <pre><code>//Move Left $('#moveleft').click(function(){ var svg = $('#svgphone').svg('get'); var cx = $('#img', svg.root()).attr('x'); cx = eval(cx) - 10; $('#img', svg.root()).attr('x', cx); }); //Move Right $('#moveright').click(function(){ var svg = $('#svgphone').svg('get'); var cx = $('#img', svg.root()).attr('x'); cx = eval(cx) + 10; $('#img', svg.root()).attr('x', cx); }); </code></pre> <p>It moves up or down instead of left (moved down) or right (moves up) as shown below:</p> <p><img src="https://i.stack.imgur.com/e3jwQ.png" alt="enter image description here"></p> <p>Why and how to solve this problem?</p> <p>TIA</p> <p>Yogi Yang</p> |
25,552,324 | 0 | <p>git prevents you from altering your working directory in a way that overwrites local changes (e.g. in case of a checkout).</p> <p>Since your checkout went smooth, it simply means that the local changes were not overwritten by it, so there's no need to worry. You're still in a consistent state.</p> <p>Were you switching to a new branch perhaps? Or maybe the local changes were newly added files? That would explain why the checkout generated no conflicts.</p> |
25,459,070 | 0 | Why does MySQL keeps prompting me for undeclared password? <p>i am new to this so please go easy on me :-). i searched the net and this site for answers but was unable to find anything similar, or its because my knowledge is only limited.</p> <p>I installed MySQL workbench, that was okay. Open the program and created a new connections, i didn't specify any password, even click "clear" several times but i am still being prompted with a password which i have no idea what it is? </p> <p>Sorry for the beginners question but i have no idea what i am doing wrong</p> <p>many thanks</p> |
19,944,383 | 0 | <p>If you always want to do a lookup on the string after the first space, then maybe you don't want to use an ArrayList</p> <p>Maybe you should use a <code>Map<String, String></code> of product, full name e.g. <code>"S4", "Samsung S4"</code> Then lookups will be much faster.</p> |
38,395,747 | 0 | Bootstrap same height cards within cols <p>With Bootstrap 3.3.6 I want to make 3 cards.</p> <pre><code><div class="row"> <div class="col-md-4"> <div class="card"> <p>Some dummy text here</p> <button>Click Here</button> </div> </div> <div class="col-md-4"> <div class="card"> <p>Some dummy text here</p> <button>Click Here</button> </div> </div> <div class="col-md-4"> <div class="card"> <p>Some dummy text here</p> <button>Click Here</button> </div> </div> </div> .card { border: 1px solid #ddd; border-radius: 5px; padding: 20px; } </code></pre> <p>Now that the Dummy text is not the same length, the cards will not be the same height.</p> <p>I found a trick using flexbox here: <a href="http://stackoverflow.com/questions/19695784/how-can-i-make-bootstrap-columns-all-the-same-height">How can I make Bootstrap columns all the same height?</a>, but this will be working on the immediate children of the .row not the .card</p> <p>Another thing, even if the cards will be the same height, the buttons will not be on the same line as they will follow the the text.</p> |
31,938,109 | 0 | Matter.js Gravity Point <p>Is it possible to create a single gravity / force point in matter.js that is at the center of x/y coordinates?</p> <p>I have managed to do it with d3.js but wanted to enquire about matter.js as it has the ability to use multiple polyshapes.</p> <p><a href="http://bl.ocks.org/mbostock/1021841" rel="nofollow">http://bl.ocks.org/mbostock/1021841</a></p> |
28,798,893 | 0 | <p>Rather than retrieving the <code>id</code> of the first <code>.link</code> element within the <code>mouseover</code> event listener, you need to get the <code>id</code> of the element you are mousing over.</p> <p>Within the event listener, <code>this</code> refers to the element that is currently being moused over, therefore you would access the <code>id</code> using <code>$(this).attr("id")</code> or <code>this.id</code>:</p> <p><a href="http://jsfiddle.net/b7m5L332/" rel="nofollow"><strong>Example Here</strong></a></p> <pre><code>$(".link").on('mouseover', function () { $("#header").html("<h1>I mousedover on " + this.id + "</h1>"); }); </code></pre> <p>It's worth pointing out that <code>$(".link")</code> returns a collection (a jQuery object) of elements. When accessing the <code>id</code> using <code>$(".link").attr("id")</code>, you are accessing the <code>id</code> of the <em>first</em> element within the jQuery object. That's why you text would always say 'london'.</p> |
13,793,359 | 0 | <p>You can't disable cookies only on your web browser control. The control is essentially an embedded Internet Explorer and shares the user's Internet Explorer settings. If you don't mind blocking cookies on all other instances of Internet Explorer (maybe you use Chrome or Firefox for the rest of your browsing) you can do the following:</p> <p>(From: <a href="http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/90834f20-c89f-42f9-92a8-f67ccee3799a/" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/90834f20-c89f-42f9-92a8-f67ccee3799a/</a>)</p> <blockquote> <p>To block Cookies in WebBrowser control you can take the following steps, in fact, it's the same as to block Cookies in IE.</p> <ol> <li>Choose "Internet Options" under the "Tools" menu on the IE;</li> <li>Select the "Privacy" tab.</li> <li>Click the "Advanced..." button in the "Settings" groupbox.</li> <li>Check the "Override automatic cookie handling" option.</li> <li>Check both "Block" options.</li> <li>Click "OK"</li> </ol> </blockquote> <p>You could also delete all the cookies after you visit a page, but I don't think this will fulfill your goal of being completely anonymous.</p> <p>I did a little digging and I think you can use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa385114%28v=vs.85%29.aspx" rel="nofollow">InternetSetOption</a> and the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa385328%28v=vs.85%29.aspx" rel="nofollow">INTERNET_SUPPRESS_COOKIE_PERSIST</a> flag. According to the documentation, this will only work for Internet Explorer 8 and later.</p> <pre><code>private const int INTERNET_OPTION_SUPPRESS_BEHAVIOR = 3; //INTERNET_SUPPRESS_COOKIE_PERSIST - Suppresses the persistence of cookies, even if the server has specified them as persistent. [DllImport("wininet.dll", SetLastError = true)] private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength); </code></pre> <p>Then when you initialize your app try:</p> <pre><code>InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SUPPRESS_BEHAVIOR, IntPtr.Zero, 0); </code></pre> <p>Hopefully this puts you on the right track. See also: </p> <p><a href="http://stackoverflow.com/questions/1688991/how-to-set-and-delete-cookies-from-webbrowser-control-for-arbitrary-domains">How to set and delete cookies from WebBrowser Control for arbitrary domains</a></p> <p><a href="http://stackoverflow.com/questions/6353715/how-do-i-use-internetsetoption">How do I use InternetSetOption?</a></p> <p><a href="http://stackoverflow.com/questions/8880281/clear-cookies-cache-for-multiple-webbrowser-control-with-wininet-in-winform-appl">Clear Cookies Cache for Multiple WebBrowser Control with WinInet in Winform Application</a></p> |
7,522,492 | 0 | <p>This should do the trick:</p> <pre><code>$ps_albums.children('div').bind('click',function(){ var album_name = $(this).find('img').attr('src').split('/')[1]; }); </code></pre> |
40,318,479 | 0 | <p>First of all you will need to install some dependencies: matplotlib and numpy.</p> <p>The first option is to use matplotlib animation like in this example:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def update_line(num, data, line): line.set_data(data[..., :num]) return line, fig1 = plt.figure() data = np.random.rand(2, 25) l, = plt.plot([], [], 'r-') plt.xlim(0, 1) plt.ylim(0, 1) plt.xlabel('x') plt.title('test') line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data,l),interval=50, blit=True) plt.show() </code></pre> <p>A more mathematical option is this one:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import time x = np.linspace(0, 1, 20) y = np.random.rand(1, 20)[0] plt.ion() fig = plt.figure() ay = fig.add_subplot(111) line1, = ay.plot(x, y, 'b-') for i in range(0,100): y = np.random.rand(1, 20)[0] line1.set_ydata(y) fig.canvas.draw() time.sleep(0.1) </code></pre> <p>I hope this is what you were searching for.</p> |
20,768,336 | 0 | <p>Have you tried <code>getRelatedEntities()</code> instead of <code>getRelatedEntity()</code>. From your explanation I understand that A has a collection of B, so try</p> <p><code>List<OEntity> bsOEntities = a.getLink("bs", OLink.class).getRelatedEntities();</code></p> <p>It works for me.</p> |
4,422,474 | 0 | <p>I did something similar with what you want few months (years?) ago. Take a look <a href="http://iamntz.com/experiments/dSlide/" rel="nofollow">here</a>. Is just a proof of concept, but i guess is still a good start.</p> |
3,425,010 | 0 | Should I use `while (true)` or `for (;;)` (in languages that support both)? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/2288856/when-implementing-an-infinite-loop-is-there-a-difference-in-using-while1-vs-fo">When implementing an infinite loop, is there a difference in using while(1) vs for(;;) vs goto (in C)?</a> </p> </blockquote> <p>In languages where <code>while (true)</code> or <code>for (;;)</code> both mean "loop forever", which should I use?</p> |
5,268,875 | 0 | Is it a waste of time to use "Build Automatically" option for Java projects in Eclipse? <p>I'm developing J2EE webapps in Eclipse (RAD, actually). I've always used the "Project > Build automatically" option. However, I noticed that this isn't always necessary because Eclipse seems to push out changes to my server when I save a file. This works great but I'm wondering why this would be checked by default.</p> <p>I can think of a few times when it makes sense to fully build and deploy the app:</p> <ul> <li>After changing a XML configuation file that gets loaded at app startup (application.xml, web.xml, bean configuration xml files, etc)</li> <li>After changing a static variable on a class </li> </ul> <p>Other than this, I can't think of other times when it would be crucial (or useful) to enable the build automatically option. Am I incorrect in my above assumptions? Am I just wasting a bunch of time by building automatically??</p> |
9,533,643 | 0 | <p>Try using <a href="http://mvcgrabbag.codeplex.com/" rel="nofollow">MVCGrabBag</a>. It has a common code base for all the inputs. It uses enums and a bit of a different style in terms of getting it to work. But once you get your head wrapped around the basics you will not be disappointed. All you do is do a <code>@Html.FullFieldEditor</code> and it takes care of the rest with code. There is basically a Selector.cs and some other files that figure out, much like the <code>@Html.EditorFor</code> helper does, what input to create. And instead of using a bunch of <code>/EditorTemplates/</code> it just has one that takes care of everything.</p> <p>It appears to be fairly new, so I trust it will gain momentum. I have to imagine for those of us non-superhuman coders out there that this would alleviate the problem of not having any uniform structure to something that has been around since the dawn of the web (I'm talking inputs). </p> <p>Good luck.</p> |
27,829,864 | 0 | <p>Your are asking the wrong question, so any answer we will give is also going to be wrong. </p> <p>You are asking how to more effectively use the tool you have (SQL Server) to solve an unspecified problem.</p> <p>The "job to be done" may be more easily solved with some other tool or a completely different design.</p> <p>If you really-really need to use a Cartesian product of this volume, you should look at using <a href="http://en.wikipedia.org/wiki/Lazy_evaluation" rel="nofollow">Lazy Evaluation</a> or the call-by-need design pattern. How you do this depends on the client language involved. </p> <p>You MAY be able to create a T-SQL lazy-evaluation with a procedure and a few sequences, but that is just a hunch.</p> |
40,517,894 | 0 | <p>I would recommend against following the push paradigm that is suggested above and switch to the pull paradigm. The purpose of AWSIdentityProviderManager is to prompt you for a token only when the SDK needs it, not for you to set it externally periodically whether the SDK needs it or not. This way you don't have to manage token expiry yourself, just make sure your token is valid when logins is called and if it isn't you can use an AWSCompletionSource to get a fresh one.</p> <p>Assuming you have integrated Facebook login, your <a href="http://docs.aws.amazon.com/AWSiOSSDK/latest/Protocols/AWSIdentityProviderManager.html" rel="nofollow noreferrer">IdentityProviderManager</a> should look something like this: </p> <pre><code>import Foundation import AWSCore import FacebookLogin import FacebookCore class FacebookProvider: NSObject, AWSIdentityProviderManager { func logins() -> AWSTask<NSDictionary> { if let token = AccessToken.current?.authenticationToken { return AWSTask(result: [AWSIdentityProviderFacebook:token]) } return AWSTask(error:NSError(domain: "Facebook Login", code: -1 , userInfo: ["Facebook" : "No current Facebook access token"])) } } </code></pre> <p>To use it:</p> <pre><code>let credentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegionType.YOUR_REGION, identityPoolId: "YOUR_IDENTITY_POOL_ID", identityProviderManager: FacebookProvider()) let configuration = AWSServiceConfiguration(region: AWSRegionType.usEast1, credentialsProvider: credentialsProvider) AWSServiceManager.default().defaultServiceConfiguration = configuration </code></pre> <p>And then to test getting credentials:</p> <pre><code>AWSServiceManager.default().defaultServiceConfiguration.credentialsProvider.credentials().continue(with: AWSExecutor.default(), with: { (task) -> Any? in print(task.result ?? "nil") return task }) </code></pre> <p>BTW, I needed to add this to my app delegate to get Facebook Login to work with Swift which is not mentioned in the instructions here <a href="https://developers.facebook.com/docs/swift/login" rel="nofollow noreferrer">https://developers.facebook.com/docs/swift/login</a> :</p> <pre><code>func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) } </code></pre> |
8,575,093 | 0 | Auto refresh script in command line <p>I'm using the command line to execute my php scripts instead of executing them in the browser, so I can look for errors a bit quicker. For browser there are some auto-refresh applications/plugins, so you don't have to hit CMD+R all the time. </p> <p>For my error log I can use the <code>tail -f</code> command, but sure enough it doesn't execute/compile, so I can't use it for php files in the command-line. </p> <p>Is there some equivalent or any work-around for compiled php-files ? Would be even greater to only output something in case of an error (native php-error like warnings, notices)!</p> <p>Working on mac os/x if that's somehow helpful.</p> |
994,661 | 0 | <p>By the way, Grails have its data persistence build on top of Hibernate. How do you think JDO would help you in something Hibernate will not? I don't see why one would choose JDO over the default. </p> <p>As far as JPA is concerned, I would recommend you to use JPA, Hibernate implementation of JPA which comes handy with Grails, and not any of the Hibernate specific feature, unless otherwise compelling.</p> <p><strong>[No more relevant after a significant change in question]</strong></p> <p>Thats perfectly fine to have CRUD operations in your entity itself. But there are cases where you may find yourself operating over multiple entities, in that case a layer comes handy and clean, IMHO. Again, its the matter of requirement.</p> |
7,323,715 | 0 | <p>No. A generator is not asynchronous. This isn't multiprocessing. </p> <p>If you want to avoid waiting for the calculation, you should use the <code>multiprocessing</code> package so that an independent process can do your expensive calculation.</p> <p>You want a separate process which is calculating and enqueueing results.</p> <p>Your "generator" can then simply dequeue the available results.</p> |
1,749,629 | 0 | <p>In <em>single dispatch</em> the function executed depends on just the object type. In <em>double dispatch</em> the function executed depends on the object type and a parameter. </p> <p>In the following example, the function <code>Area()</code> is invoked using single dispatch, and <code>Intersect()</code> relies on double dispatch because it takes a Shape parameter.</p> <pre><code>class Circle; class Rectangle; class Shape { virtual double Area() = 0; // Single dispatch // ... virtual double Intersect(const Shape& s) = 0; // double dispatch, take a Shape argument virtual double Intersect(const Circle& s) = 0; virtual double Intersect(const Rectangle& s) = 0; }; struct Circle : public Shape { virtual double Area() { return /* pi*r*r */; } virtual double Intersect(const Shape& s); { return s.Intersect(*this) ; } virtual double Intersect(const Circle& s); { /*circle-circle*/ } virtual double Intersect(const Rectangle& s); { /*circle-rectangle*/ } }; </code></pre> <p>The example is based on this <a href="http://www.eptacom.net/pubblicazioni/pub_eng/mdisp.html" rel="nofollow noreferrer">article</a>.</p> |
25,976,872 | 0 | <p>to respond with you'll have to do somethiing liek this:</p> <pre><code>format.json do render json: { booking_attr: @booking.attr, booking_second_attr: @booking_second_attr, id: @booking.id } end end </code></pre> |
35,480,180 | 0 | <p>You can use <a href="https://docs.datastax.com/en/cql/3.3/cql/cql_reference/timeuuid_functions_r.html" rel="nofollow">toDate() functions</a> that are builded inside Cassandra</p> <p>For example <code>SELECT toDate(columTimeUUID) FROM YourTable</code> will give you a date formated as : <code>YYYY-MM-DD</code></p> <p>However, it works for Cassandra versions greater than 2.2</p> |
16,594,155 | 0 | How to pass parameters in proper manner in C#? <p>I have stored procedure as below:</p> <pre><code>ALTER PROCEDURE [dbo].[Insert_tblCustomer] -- Add the parameters for the stored procedure here @Username varchar(20) = null, @Password varchar(20)= null, @UserType varchar(20)='User', @FirstName varchar(50)=null, @LastName varchar(50)=null, @DateOfBirth varchar(50)=null, @Gender varchar(10)=null, @Unit_No int = null, @St_No int=null, @St_Name varchar(20)=null, @Suburb varchar(20)=null, @State varchar(20)=null, @Postcode int=null, @Email varchar(50)='', @Phone varchar(15)=null </code></pre> <p>AS... and There are 5 fields i.e. username,password,firstname,lastname and email are must fields. Now from c#, I am trying this :</p> <pre><code>dbConnection target = new dbConnection(); // TODO: Initialize to an appropriate value string _query = string.Empty; // TODO: Initialize to an appropriate value SqlParameter[] param = new SqlParameter[5]; // TODO: Initialize to an appropriate value param[0] = new SqlParameter("@Username", "hakoo"); param[1] = new SqlParameter("@Password", "hakoo"); param[2] = new SqlParameter("@FirstName", "Hakoo"); param[3] = new SqlParameter("@LastName", "Hakoo"); param[4] = new SqlParameter("@Email", "[email protected]"); bool expected = true; // TODO: Initialize to an appropriate value bool actual; actual = target.Execute_InsertQuery("dbo.Insert_tblCustomer", param); </code></pre> <p>But, I am getting Assertfail exception. I am newbie to use stored procedures with test. Can anyone correct me where I am wrong?</p> <p>"Added Assert part"</p> <pre><code>bool expected = true; // TODO: Initialize to an appropriate value bool actual; actual = target.Execute_InsertQuery("dbo.Insert_tblCustomer", param); </code></pre> <p>dbConnection is my created core class, where I am putting generic query :</p> <pre><code>public bool Execute_InsertQuery(string _query, SqlParameter[] param) { try { SqlCommand cmd = new SqlCommand(); cmd.Connection = OpenConnection(); cmd.CommandText = _query; cmd.Parameters.AddRange(param); cmd.ExecuteNonQuery(); return true; } catch (Exception ex) { Console.Write(ex.StackTrace.ToString()); return false; } } </code></pre> <p>Update for getting Error : I tried to pass all parameters in this manner : </p> <pre><code>dbConnection c = new dbConnection(); System.Data.SqlClient.SqlParameter[] param = new System.Data.SqlClient.SqlParameter[15]; param[0] = new SqlParameter("@Username", "hakoo"); param[1] = new SqlParameter("@Password", "hakoo"); param[2] = new SqlParameter("@UserType", "User"); param[3] = new SqlParameter("@FirstName", "Hakoo"); param[4] = new SqlParameter("@LastName", "Hakoo"); param[5] = new SqlParameter("@DateOfBirth", "02/11/88"); param[6] = new SqlParameter("@Gender", ""); param[7] = new SqlParameter("@Unit_No", null); param[8] = new SqlParameter("@St_No", 25); param[9] = new SqlParameter("@St_Name", "anc st"); param[10] = new SqlParameter("@Suburb", "ancst"); param[11] = new SqlParameter("@State", "assadd@few"); param[12] = new SqlParameter("@Postcode", 2615); param[13] = new SqlParameter("@Email", "[email protected]"); param[14] = new SqlParameter("@Phone", "165103548"); c.Execute_InsertQuery("dbo.Insert_tblCustomer", param); </code></pre> <p>But for this, I am getting this error :</p> <blockquote> <p>The parameterized query '(@Username nvarchar(5),@Password nvarchar(5),@UserType nvarchar(' expects the parameter '@Unit_No', which was not supplied. I can execute this Store procedure in SQL Server.</p> </blockquote> |
29,838,931 | 0 | AWS iOS SDK TLS Support <p>Related Question: <a href="http://stackoverflow.com/questions/29656452/aws-s3-disabling-sslv3-support">AWS S3 Disabling SSLv3 Support</a></p> <p>This is more of an inquiry for the mobile iOS SDK. Wondering what I have to do or where to start since am a bit clueless. </p> <p>Also just received a notice that Amazon is deprecating SSLv3 and that I need to modify my requests to use TLS. </p> <p>This is an older iOS app still using the AWS iOS SDK 1.7 version. This basically just accesses S3 Buckets for both upload and download of images. </p> <p>Now is this normally handled already by the library or do I have to update to the v2 library, thereby dropping iOS 6 support. Or can it just be through code changes, etc.</p> |
9,190,487 | 0 | <p>It is used to inform the compiler to disable C++ name mangling for the functions defined within the braces. <a href="http://en.wikipedia.org/wiki/Name_mangling" rel="nofollow">http://en.wikipedia.org/wiki/Name_mangling</a></p> |
7,646,493 | 0 | <p>The compiler is picking the <code>IEnumerator<int> GetEnumerator</code> method by following the rules in 8.8.4 of the C# language specification which <em>first</em> looks for an accessible <code>GetEnumerator()</code> method on the <code>BarList</code> type. The only one of those which is available is the one returning <code>IEnumerator<int></code>.</p> <p>If you had made <em>that</em> method use explicit interface implementation as well, then it would have gone onto the later stages of section 8.8.4, which states that if there is more than one type T such that there is an implicit conversion from the expression type (<code>BarList</code> here) to <code>IEnumerable<T></code> then an error is produced.</p> <p>I would say this <em>is</em> a confusing design - I would probably add properties or methods to retrieve appropriate "views" on the data.</p> |
2,865,363 | 0 | Zend Framework - Not Connecting to IMAP mail server - instead dumps empty php file <p>Hi guys I'm trying to connect to an imap mail server using zend frameworks Zend_Mail_Storage_Imap function. Its working with some accounts but with most accounts it just dies out. I'm connecting using:</p> <pre><code>$mail = new Zend_Mail_Storage_Imap(array('host' =>$current_dept->incoming_server, 'ssl' =>$current_dept->ssl, 'port'=>$current_dept->incoming_port, 'folder'=>$mbox_name, 'user' =>$current_dept->email, 'password' =>$current_dept->email_psd)); </code></pre> <p>WIth some email accounts teh code doesn't go past this statement - and instead I'm prompted to 'download' the php file being run. Whats happening here - the mail server details are correct.</p> |
3,172,886 | 0 | <p>Views bulk operations and exposed filters can solve this problem for you. Normally you use it to create a customized node view, but the same principal can be used for users. </p> |
34,645,326 | 1 | Selenium test works in local machine, but fails on Jenkins <p>My test works just fine on my machine. However, on Jenkins, I have the following error:</p> <pre><code>Traceback (most recent call last): File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/.env/local/lib/python2.7/site-packages/django/test/utils.py", line 216, in inner return test_func(*args, **kwargs) File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/twist/tests/interface/test_hello.py", line 42, in test_login open_login_modal_btn.click() File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 75, in click self._execute(Command.CLICK_ELEMENT) File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 454, in _execute return self._parent.execute(command, params) File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute self.error_handler.check_response(response) File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response raise exception_class(message, screen, stacktrace) ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with Stacktrace: at fxdriver.preconditions.visible (file:///tmp/tmpl_3zEO/extensions/[email protected]/components/command-processor.js:9981) at DelayedCommand.prototype.checkPreconditions_ (file:///tmp/tmpl_3zEO/extensions/[email protected]/components/command-processor.js:12517) at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpl_3zEO/extensions/[email protected]/components/command-processor.js:12534) at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpl_3zEO/extensions/[email protected]/components/command-processor.js:12539) at DelayedCommand.prototype.execute/< (file:///tmp/tmpl_3zEO/extensions/[email protected]/components/command-processor.js:12481) </code></pre> <p>I installed dependencies as it follows:</p> <pre><code>$ sudo apt-get install xvfb python-pip $ sudo pip install pyvirtualdisplay </code></pre> <p>Here is my test code:</p> <pre><code>class MySeleniumTests(LiveServerTestCase): fixtures = ['user-data.json'] def setUp(self): self.display = Display(visible=0, size=(800, 600)) self.display.start() group = Group.objects.get_or_create(name="Test")[0] user_adm = User.objects.create(username="adm", is_active=True, is_staff=True, is_superuser=True) user_adm.set_password("123") user_adm.groups.add(group) user_adm.save() self.selenium.get('%s' % (self.live_server_url)) self.browser = self.selenium def tearDown(self): self.display.stop() @classmethod def setUpClass(cls): super(MySeleniumTests, cls).setUpClass() cls.selenium = WebDriver() @classmethod def tearDownClass(cls): cls.selenium.quit() super(MySeleniumTests, cls).tearDownClass() @override_settings(DEBUG=True) def test_login(self): open_login_modal_btn = self.browser.find_element_by_xpath("//a[@class='btn btn-nav']") open_login_modal_btn.click() # Login info username_html_id = "lm-email" password_html_id = "lm-password" login_value = "adm" password_value = "123" username = self.browser.find_element_by_id(username_html_id) password = self.browser.find_element_by_id(password_html_id) # Sending login info username.send_keys(login_value) password.send_keys(password_value) desired_url = self.live_server_url + "/panel/" form = self.browser.find_element_by_xpath('//form[@id="login-modal"]') form.submit() time.sleep(5) # Testing if successful login # Logging in current_url = self.browser.current_url self.assertEqual(current_url, desired_url) </code></pre> <p>Are there any clues on how to fix it? Any help on how to debug/fix it will be appreciated! :-)</p> <p>-- EDIT:</p> <p>My issue is solved, if you are facing similar problem, take a look at: <a href="http://stackoverflow.com/questions/34562061/webdriver-click-vs-javascript-click">WebDriver click() vs JavaScript click()</a> It was the case in my problem.</p> |
27,711,510 | 0 | <p>with 3.x ... use the name property of CCNode to your advantage.</p> <pre><code>-(void)createNewCactus { CCSprite *newCactus = [CCSprite spriteWithImageNamed:@"cactusclipart.png"]; [newCactus setScale:0.25]; newCactus.name = @"cactusclipart.png"; if (cactiCount <= 21) { cactiCount++; if (cactiCount < 7) [newCactus setPosition:ccp(43*cactiCount, 140)]; else if (cactiCount < 13) [newCactus setPosition:ccp(43*cactiCount-258, 90)]; else [newCactus setPosition:ccp(43*cactiCount-516, 40)]; [self addChild:newCactus]; } else { [newCactus removeFromParentAndCleanup:YES]; // <- this will never happen } } </code></pre> <p>and to remove do something like :</p> <pre><code>CCSprite *cac; while (cac = [self getChildByName:@"cactusclipart.png" recursively:NO]) { [cac revoveFromParentAndCleanup:YES]; } </code></pre> |
19,932,083 | 0 | <p>Perhaps the confusion is between a variable and a field. A field is a property that is associated with an object. A variable exists only in the context of a method. When the method finishes, the variable vanishes.</p> <p>A field, on the other hand, looks exactly the same as a variable except that a field is declared outside of any method, directly on the class "body". Fields and methods are declared at the same hierarchical level. You can see that on Eclipse. Check the "outline" view.</p> <p>If you need several methods to read and write the same "variable", then what you need is a field. I hope this clarifies. </p> |
27,831,535 | 0 | <p>I believe that the way 'iisnode' works is that it intercepts requests for files with ".js" extension. I do not think it can be set up to run same way as you would run it using <code>node</code> or <code>nodemon</code>.</p> <p>In my case I set up a production Node.js server with IIS by doing the following:</p> <ol> <li><p>I set up my port in server.js to run on different port (say 81) so that it does not interfere with IIS.</p></li> <li><p>I set up node to run in a service, so that it auto-restarts when server restarts, console window will not get closed accidently, etc (there are few options you can use - for example <a href="http://nssm.cc/" rel="nofollow">http://nssm.cc/</a> but we wrote our own wrapper service). </p></li> <li><p>I set up <a href="http://dvisagie.blogspot.ca/2013/02/running-nodejs-alongside-iis-on-windows.html" rel="nofollow" title="forwarding">forwarding</a> from IIS to that node server - that way I could still use port 80 for the site externally and I was able to use host header filtering (there are multiple sites running on one server)</p></li> </ol> |
9,298,524 | 0 | <p>Look into <a href="http://ncalc.codeplex.com/">nCalc</a>.</p> <p>You could store your calculations in a database field then simply execute them on demand. Pretty simple and powerful. We are using this in a multi-tenant environment to help with similar types of customization. </p> |
3,653,522 | 0 | zpt xml-schema definition <p>Where can i find xml-schema definition for ZPT attribute language?</p> |
2,678,085 | 0 | <p>The entry is completely optional, but the bug you are pointing to is related to compilation, not runtime, so it is highly unlikely that this is the problem.</p> <p>Application Servers are often very file hungry, and if nothing has been done to increase the limit of open files, the default may not be high enough.</p> <p>On CentOS for example, we found that even in QA (not load testing, just functional testing) a server could max out its ulimit with JBoss 4.2.</p> <p>EDIT: The only thing wrong with the code that you posted in terms of holding files open is that you should use <a href="http://stackoverflow.com/questions/2649322/how-do-i-close-a-file-after-catching-an-ioexception-in-java">finally</a> to close your stream. In a server application, it could be that this code often throws an exception, causing files to not be closed (because you don't close them in a finally) and over time those open file handles add up. There are other issues in how you are doing it (like relying on the <code>available()</code> to determine the size of the byte array), but that should not affect your problem.</p> <p>Another possibility is that under *nix systems sockets consume the same resource as files, so it could be that you have too many sockets (above what the system is configured to allow) open, causing this code to be unable to execute.</p> |
15,289,516 | 0 | <p>Session is a good way to store and remember data but why complicate things? Consider if the form has many fields, developer has to store lots of values in session. Why not simply print or echo.</p> <p>Example:</p> <p>Form is submitted with input ssName and hidden field ssAct with value of send</p> <p>Get the ssName and ssAct on form submit</p> <pre><code>$ssAct=$_REQUEST["ssAct"]; $ssName=$_REQUEST["ssName"]; </code></pre> <p>and the form</p> <pre><code><input type="text" name="ssName" value="<?php if($ssAct=='send' && $ssName!='') { echo "$ssName"; } ?>"> <input type="hidden" name="ssAct" value="send"> </code></pre> <p>On submit name will be echoed if it was submitted and was not empty.</p> |
7,379,017 | 0 | <p>Humans.</p> <p>You want to improve readability, and since readability is mostly a human thing it should be taught by a human.</p> <p>Ask more experienced developers to review your expressions and give tips.</p> <p>For example, see my answer here: <a href="http://stackoverflow.com/questions/5924611/what-is-the-best-way-performance-wise-to-test-if-a-value-falls-within-a-thresho/5924659#5924659">What is the best way (performance-wise) to test if a value falls within a threshold?</a></p> |
24,769,785 | 0 | More efficient way of running multiple update queries on an Access database? <p>I have multiple queries like this right now which involve updating different fields of the same row in an Access database:</p> <pre><code>//Update database string updatequery = "UPDATE [table] SET [Last10Attempts] = ? WHERE id = ?"; OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=" + "database.accdb"); con.Open(); OleDbDataAdapter da = new OleDbDataAdapter(updatequery, con); var accessUpdateCommand = new OleDbCommand(updatequery, con); accessUpdateCommand.Parameters.AddWithValue("Last10Attempts", last10attempts); accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1); da.UpdateCommand = accessUpdateCommand; da.UpdateCommand.ExecuteNonQuery(); //update last10attemptssum updatequery = "UPDATE [table] SET [Last10AttemptsSum] = ? WHERE id = ?"; accessUpdateCommand = new OleDbCommand(updatequery, con); accessUpdateCommand.Parameters.AddWithValue("Last10AttemptsSum", counter); accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1); da.UpdateCommand = accessUpdateCommand; da.UpdateCommand.ExecuteNonQuery(); //increment totalquestionattempt updatequery = "UPDATE [table] SET [total-question-attempts] = ? WHERE id = ?"; accessUpdateCommand = new OleDbCommand(updatequery, con); accessUpdateCommand.Parameters.AddWithValue("total-question-attempts", questionattempts + 1); accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1); da.UpdateCommand = accessUpdateCommand; da.UpdateCommand.ExecuteNonQuery(); con.Close(); </code></pre> <p>I was wondering if there is a more efficient way of running these update queries - ie. combining them into one query.</p> |
34,594,701 | 0 | delete section at indexPath swift <p>I have an array which populates a table view - myPosts.</p> <p>The first row of the table view is not part of the array.</p> <p>Each row is its own section (with its own custom footer)</p> <p>I am trying to perform a delete with the following code:</p> <pre><code> func tableView(profileTableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { myPosts?.removeAtIndex(indexPath.section - 1) profileTableView.beginUpdates() let indexSet = NSMutableIndexSet() indexSet.addIndex(indexPath.section - 1) profileTableView.deleteSections(indexSet, withRowAnimation: UITableViewRowAnimation.Automatic) profileTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) profileTableView.endUpdates() ... WS Call ... } } </code></pre> <p>And the log is reporting the following:</p> <pre><code> 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).' </code></pre> <p>Obviously the issue is related to 0 moved in, 0 moved out but I don't understand why that is? or what the solution would be?</p> <p>number of sections in tableView is as follows:</p> <pre><code>func numberOfSectionsInTableView(tableView: UITableView) -> Int { if self.myPosts == nil { return 1 } return self.myPosts!.count + 1 } </code></pre> |
20,876,239 | 0 | <p>The setInterval executes after the function is run, by which point i has incremented to 4. You should create a closure over the element to preserve it</p> <pre><code>setInterval(runnable(elements[i], text, target_date), 1000); // also pass target_date since it is needed function runnable(el, text, target_date) { return function () { // find the amount of "seconds" between now and target var current_date = new Date().getTime(); var seconds_left = (target_date - current_date) / 1000; // do some time calculations days = parseInt(seconds_left / 86400); seconds_left = seconds_left % 86400; hours = parseInt(seconds_left / 3600); seconds_left = seconds_left % 3600; minutes = parseInt(seconds_left / 60); seconds = parseInt(seconds_left % 60); // format countdown string + set tag value el.innerHTML = text + days + "d, " + hours + "h, " + minutes + "m, " + seconds + "s"; } } </code></pre> <p>Demo: <a href="http://jsfiddle.net/87zbG/1/" rel="nofollow">http://jsfiddle.net/87zbG/1/</a></p> |
6,345,513 | 0 | <p>I have modified little bit your <code>encodeIcon()</code>. Now its working fine. it is having the actual image</p> <pre><code>public static void encodeIcon(Drawable icon){ String appIcon64 = new String(); Drawable ic = icon; if(ic !=null){ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // bitmap.compress(CompressFormat.PNG, 0, outputStream); BitmapDrawable bitDw = ((BitmapDrawable) ic); Bitmap bitmap = bitDw.getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] bitmapByte = stream.toByteArray(); bitmapByte = Base64.encode(bitmapByte,Base64.DEFAULT); System.out.println("..length of image..."+bitmapByte.length); } } </code></pre> <p>Thanks Deepak</p> |
22,419,730 | 0 | <p>If I understood your question correctly then you need to use <code>scroll:1</code> instead of <code>scroll:true</code>, Which will not disable scroll bar, but it will solve your issue.</p> |
10,809,728 | 0 | Backbone Marionette CompositeView "Event Zombie" <p>I have a fairly simple table created using a Backbone Marionette CompositeView. The only requirements on this table are that it display data and allow the user to sort it by clicking the header row. When the table is sorted, the columns used to sort the header column are tagged with classes to allow an arrow to be displayed using CSS (e.g. 'class="sort asc"').</p> <p>Here is the problem: When the header row is clicked, the element that is passed to the callback (via event.target) is not part of the table that is on the DOM. Instead, using Chrome's debugging tools it appears that the target element is actually part of the template script block, and not the element the user actually sees.</p> <p>The best work-around I've got right now is to lookup the element actually attached to the DOM by retrieving unique info from its clone in the template.</p> <p>Here's the composite view code (borrowed from one of Derick Bailey's sample Fiddle's):</p> <pre><code>// The grid view var GridView = Backbone.Marionette.CompositeView.extend({ tagName: "table", template: "#grid-template", itemView: GridRow, events: { 'click th': 'doSort' }, doSort: function(event) { var target = $(event.target); this.collection.sortByField(target.data('sortby')); target.parent('tr').find('.sort').removeAttr('class'); target.addClass('sort ' + this.collection.sortdir); debugger; // NOTE: no change to elements in the DOM. WTH? target = this.$('[data-sortby=' + target.data('sortby') + ']'); target.parent('tr').find('.sort').removeAttr('class'); target.addClass('sort ' + this.collection.sortdir); debugger; // NOTE: DOM updated. }, appendHtml: function(collectionView, itemView) { collectionView.$("tbody").append(itemView.el); } }); </code></pre> <p>The template is simple as well:</p> <pre><code><script id="grid-template" type="text/template"> <thead> <tr> <th data-sortby="username">Username</th> <th data-sortby="fullname">Full Name</th> </tr> </thead> <tbody></tbody> </script> </code></pre> <p>A fork of Derek's original demo Fiddle modified to demonstrate the problem can be found here: <a href="http://jsfiddle.net/ccamarat/9stvM/14/" rel="nofollow">http://jsfiddle.net/ccamarat/9stvM/14/</a></p> <p>I've meandered a bit. My question is, I appear to have a spawned a Zombie View of sorts; is this a jQuery/Backbone/Underscore bug, or am I simply going about this all wrong?</p> <p>** EDIT ** Here's the console output showing the different parent hierarchies of the two elements: </p> <pre><code>console.log(target, targetb): [<th data-sortby="username" class="sort asc">Username</th>] [<th data-sortby="username">Username</th>] console.log(target.parents(), targetb.parents()): [<tr>…</tr>, <thead>…</thead>] [<tr>…</tr>, <thead>…</thead>, <table>…</table>, <div id="grid">…</div>, <body>…</body>, <html>…</html>] console.log(target === targetb): false </code></pre> |
17,346,620 | 0 | <p>PHP is a server-side language and you won't be able to load it up in a web browser just like that. You'll have to use a web server, like <a href="http://www.wampserver.com/en/" rel="nofollow">WAMP</a> or <a href="http://www.apachefriends.org/en/xampp.html" rel="nofollow">XAMPP</a> for example.</p> <p>Make sure of these things first:</p> <ul> <li>that PHP is installed and running on your computer</li> <li>that the file extension is <code>.php</code></li> <li>that you're accessing the php file with something like <code>localhost/yourfile.php</code> and not <code>file://yourfile.php</code></li> <li>that the permission for your files is correct (644 or 755 would be enough, I think)</li> </ul> <p>Hope this helps.</p> |
7,932,272 | 0 | Could these patterns be matched by regular expression or context free grammar? <p>This is an exercise of compiler. We are asked if it's possible to match the following patterns with regular expression or context free grammar:</p> <ol> <li>n 'a' followed by n 'b', like 'aabb'</li> <li>palindrome, like 'abbccbba'</li> <li>n 'a', then n 'b', then n 'c', like 'aabbcc'</li> </ol> <p>Note that n could be any positive integer. (Otherwise it's too simple)</p> <p>Only 3 character 'abc' could appear in the text to parse.</p> <p>I'm confused because as far as I can see, non of these patterns can be described by regular expression and context free grammar.</p> |
39,307,989 | 0 | <p><strong>1.</strong> Your function signature takes 3 arguments, and you only supply 1. How it compiles, I do not know, as I don't think it should. </p> <p><strong>2.</strong> The <code>CalculateAirTime</code> function prints a variable before calculating it. You first do this: <code>printf("Total air time: %f\n", time);</code> , and then calculate the actual air time: <code>time = ((2*velocity)*sin(angle)/GRAVITY);</code></p> <p><strong>3.</strong> As an advice, since the <code>CalculateAirTime</code> function needs velocity and angle to return a calculated time, do not pass time as a parameter. It's useless. You can either declare a double variable inside the function or directly return the calculated time.</p> <p>Replace <code>double CalculateAirTime(double velocity, double angle, double time){...}</code> with <code>double CalculateAirTime(double velocity, double angle){...}</code></p> <p><strong>*EDIT!</strong> For clarity purposes, here is how I would probably write your program:**</p> <pre><code>#include <stdio.h> #include <math.h> #define PI 3.14159265358979323846 #define GRAVITY 9.8 /* I renamed some variables. Just from the variable names, I think you do not understand the solution for this "air time" problem well. I might be mistaken tough. If you have any questions, please ask them. You are not leaving this place until you fully understand what is happening. */ // Function DECLARATION: double CalculateAirTime(double Initial_Velocity, double Launch_Angle); int main(void) { // variables double Initial_Velocity; double Launch_Angle; // Initial_Velocity = 20.0 should work aswell. This is called a cast. You will learn about it later Initial_Velocity = (double)(20.0); // Converting 45 degrees to radians, because the sin() library function works with radians Launch_Angle = (double)((45.0/180.0)*PI); //Call function using our declared values as input CalculateAirTime(Initial_Velocity,Launch_Angle); return 0; } // Function DEFINITION //Try to use the same name for paramaters here, as you did in the declaration! double CalculateAirTime(double Initial_Velocity, double Launch_Angle) { double Air_Time; Air_Time = (double)((2*Initial_Velocity)*sin(Launch_Angle)/GRAVITY); printf("Total air time: %f\n", Air_Time)); return time; } </code></pre> |
39,182,338 | 0 | <p>You cannot use <code>$this</code> as this is an explicit reserved variable for the class inside reference to the class instance itself. Make a copy to <code>$this</code> and then pass it to the <code>use</code> language construct.</p> <pre><code>class Foo { var $callbacks = array(); function __construct() { $class = $this; $this->callbacks[] = function($arg) use ($class) { return $class->bar($arg); }; } function bar($arg) { return $arg * $arg; } } </code></pre> |
13,732,018 | 0 | Java Thread interrupt(). Is it normal exception? <p>I am starting my Thread like this: </p> <pre><code>public void startTask(Runnable r) { running = true; Log.i(tag, "-----------start.Runnable-----------"); final Thread first = new Thread(r); currentTask = first; first.start(); Thread second = new Thread(new Runnable() { @Override public void run() { try{ first.join(); } catch(InterruptedException e){ } running = false; } }); second.start(); } </code></pre> <p>And when I want to cancel current operation, I am doing such with a Theread according to this article: <a href="http://forward.com.au/javaProgramming/HowToStopAThread.html" rel="nofollow">http://forward.com.au/javaProgramming/HowToStopAThread.html</a> :</p> <pre><code>public void cancelTask() { Log.i(tag, "-----------cancelTask()-----------"); try{ currentTask.interrupt(); running = false; } catch(SecurityException e){ e.printStackTrace(); } } </code></pre> <p>Application is still running after cancelTask, but I have exception: </p> <pre><code>12-05 20:29:00.274: W/System.err(13533): java.lang.InterruptedException 12-05 20:29:00.274: W/System.err(13533): at java.lang.VMThread.sleep(Native Method) 12-05 20:29:00.294: W/System.err(13533): at java.lang.Thread.sleep(Thread.java:1047) 12-05 20:29:00.294: W/System.err(13533): at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:331) 12-05 20:29:00.304: W/System.err(13533): at com.rsd.myfirstapp3.ProgressServiceActivity$2.run(ProgressServiceActivity.java:174) 12-05 20:29:00.314: W/System.err(13533): at java.lang.Thread.run(Thread.java:864) </code></pre> <p>.</p> <p><strong>Is it normal exception in such operations with threads?</strong> </p> |
4,411,065 | 0 | <p><code>ShellExecute</code> or <code>CreateProcess</code> should be able to open link file. If they can't find the associated file and/or the program, you can always use those API and delegate the hard work to "cmd start" or "explorer". E.g. <code>ShellExecute(0, "open", "explorer", linkfile, 0, SW_SHOW);</code></p> |
4,322,916 | 0 | <p>No, null values are not set to the default, as null is itself a valid value for a variable or field in SQL.</p> <p>To ensure a parameter gets its default value, do not pass in the parameter at all. So for your proc:</p> <pre><code>-- @myVar will get default EXEC TestVarcharMaxIsNull -- @myVar will be null EXEC TestVarcharMaxIsNull @myVar=NULL -- @myVar will be "Hello" EXEC TestVarcharMaxIsNull @myVar='Hello' </code></pre> |
35,408,345 | 0 | Need advice to choose graph database <p>I'm looking for options for graph database to be used in a project. I expect to have ~100000 writes (vertix + edge) per day. And much less reads (several times per hour). The most frequent query takes 2 edges depth tracing that I expect to return ~10-20 result nodes. I don't have experience with graph databases and want to work with gremlin to be able to switch to another graph database if needed. Now I consider 2 possibilities: neo4j and Titan.</p> <p>As I can see there is enough community, information and tools for Neo4j, so I'd prefer to start from it. Their capacity numbers should be enough for our needs (∼ 34 billion nodes, ∼ 34 billion edges). But I'm not sure which hardware requirements will I face in this case. Also I didn't see any parallelisation options for their queries.</p> <p>On the other hand Titan is built for horizontal scalability and has integrations with intensively parallel tools like spark. So I can expect that hardware requirements can scale in a linear way. But there is much less information/community/tools for Titan.</p> <p>I'll be glad to hear your suggestions</p> |
22,755,488 | 0 | Best way to store ROE in C# <p>I want to save Rate of Exchange of all currencies corresponding different base currency. What is the best and efficient type or struct to save the same. Currently i am using</p> <pre><code>Dictionary<string, Dictionary<string, decimal>>(); </code></pre> <p>Thanks in advance. Please suggest</p> |
16,255,864 | 0 | uncrustify adds space between double-paranthesis (C/Objective-C) <p>I'm having a very peculiar issue with uncrustify (v0.60) that no option seems to affect. The issue only occurs when there are parenthesis enclosed within parenthesis:</p> <pre><code>// from a C header file: #define BEGIN_STACK_MODIFY(L) int __index = lua_gettop( (L) ); ^ ^ // from an ObjC (.m) implementation file: if ( (self = [super init]) ) ^ ^ </code></pre> <p>I want to reformat those to look like this, but uncrustify always adds those spaces between parenthesis (when I manually reformat to the code below, uncrustify will reformat it to the version above, so it's not just being ignored by uncrustify):</p> <pre><code>// from an ObjC header file: #define BEGIN_STACK_MODIFY(L) int __index = lua_gettop((L)); // from an ObjC (.m) implementation file: if ((self = [super init])) </code></pre> <p>I used UncrustifyX to check all (well, a great number of) variations of possibly related settings for spaces and parenthesis with no luck.</p> <p>You can check my <a href="https://gist.github.com/LearnCocos2D/5474209" rel="nofollow">uncrustify config file here on gist</a>.</p> <p>If you have any idea what settings I should try, or perhaps settings that may be in conflict with each other, I'd be happy to test it.</p> |
5,825,887 | 0 | <p>Try setting it on the NSTextView's layer, not the NSTextView itself.</p> <pre><code>[[myTextView layer] setCornerRadius:10.0f]; </code></pre> |
20,329,948 | 0 | Inset a new field in an array of sub-document <p>I have the following schema:</p> <pre><code>{ "name" : "MyName", "actions" : [{ "kind" : "kind1", "result" : "result1" }, { "kind":"kind1", "result":"result1" } ] } </code></pre> <p>I want to insert a new field called 'expected' in different subdocument in actions. I tried the following command but I have an issue with it:</p> <pre><code>db.tasks.update({},{$push:{ "actions.expected" : "MyExpected" }},false,true) can't append to array using string field name expected </code></pre> |
20,836,263 | 0 | <pre><code>if __name__ == "__main__": MLL = LinkedList() LL1 = LinkedList() LL2 = LinkedList() array_list1 = [2, 4, 5, 7, 11, 12, 15, 20] array_list2 = [3, 6, 9, 10] for p in array_list1: LL1.addElement(p) for q in array_list2: LL2.addElement(q) cur_node_l1 = LL1.Head cur_node_l2 = LL2.Head cur_node = MLL.Head; while(cur_node_l1 and cur_node_l2): e1 = cur_node_l1.element e2 = cur_node_l2.element if e1 < e2: if not cur_node: cur_node = cur_node_l1; MLL.Head = cur_node else: cur_node.Next = cur_node_l1; cur_node = cur_node_l1 cur_node_l1 = cur_node_l1.Next # MLL.TAIL = cur_node_l1; else: if not cur_node: cur_node = cur_node_l2; MLL.Head = cur_node else: cur_node.Next = cur_node_l2; cur_node = cur_node_l2; cur_node_l2 = cur_node_l2.Next # MLL.TAIL = cur_node_l2; if (cur_node_l1): cur_node.Next = cur_node_l1 cur_node = LL1.Tail; if (cur_node_l2): cur_node.Next = cur_node_l2 cur_node = LL2.Tail; MLL.Tail = cur_node MLL.size = LL1.size + LL2.size MLL.displayLinkedList() </code></pre> |
18,617,150 | 0 | why does this output hex rather than a sentence? connector/c++ <p>I was expecting to see a short english sentence as output but i see hex value of it instread. I cannot find any information on this getblob function but i hear its what should be used for varchar columns. Before i used getString and it crashes the app, its funny though becuase it crashes after it successfully prints the sentence sometimes. However i cant have it crashing so i need to make it work with getblob, it returns an std::istream which i no nothing about. I experimented with converting istream to string but my lack of understanding of what an isteam is did not get me far.</p> <pre><code>#include <iostream> #include <sstream> #include <memory> #include <string> #include <stdexcept> #include "cppconn\driver.h" #include "cppconn\connection.h" #include "cppconn\statement.h" #include "cppconn\prepared_statement.h" #include "cppconn\resultset.h" #include "cppconn\metadata.h" #include "cppconn\resultset_metadata.h" #include "cppconn\exception.h" #include "cppconn\warning.h" #include "cppconn\datatype.h" #include "cppconn\parameter_metadata.h" #include "mysql_connection.h" #include "mysql_driver.h" using namespace std; int main() { sql::mysql::MySQL_Driver *driver; sql::Connection *con; sql::Statement *stmt; // ... driver = sql::mysql::get_mysql_driver_instance(); cout<<"Connecting to database...\n"; con = driver->connect("tcp://xx.xxx.xxx.xxx:3306", "xxxxx", "xxxxxx"); sql::ResultSet *res; // ... stmt = con->createStatement(); // ... con->setSchema("mrhowtos_main"); res = stmt->executeQuery("SELECT english FROM `eng` WHERE `ID` = 16;"); while (res->next()) { istream *stream = res->getBlob(1); string s; getline(*stream, s); //crashes here - access violation cout << s << endl; } cout<<"done\n"; delete res; delete stmt; delete con; system("PAUSE"); return 0; } </code></pre> <p>UPDATE: crashes on getline</p> <p>value of stream after getblob:</p> <ul> <li>stream 0x005f3e88 {_Chcount=26806164129143632 } std::basic_istream > *</li> </ul> |
23,560,397 | 0 | <p>Simply: </p> <pre><code>rerun --pattern '{Gemfile.lock,config/application.rb,config/environment.rb,config/environments/development.rb,config/initializers/*.rb,lib/**/*.rb,config/**/*.yml}' --no-growl --signal INT --background --clear -- rails s </code></pre> <p>won't work?</p> |
17,095,480 | 0 | Get Host of HttpResponseMessage in Windows Store App <p>I have a Windows Store App (C#) where I am sending a HttpRequest and I want to check if the response I am getting is from a Captive/Limited Access Network or from the actual host specified in the HttpRequest. </p> <p>So lets say I am sending a request to www.serverA.com I look at the response of that request and determine if it was success based on the status code.</p> <p>Imagine the same scenario in a captive network(airport networks/starbucks where they redirect you to a login page):</p> <ul> <li>I am sending a request to www.serverA.com </li> <li>My request gets redirected to www.serverB.com/AirPortLoginPage </li> <li>I get back a response that the AirportLoginPage loaded successfully with a 200 response</li> <li>My code sees that as a success because of the 200 status code, but I wanted to know if my original request was successful</li> </ul> <p>So, is there a way to determine the host of the server where the Response Message is coming from?</p> |
34,820,819 | 0 | Unable to remove index.php in Codeigniter <p>I want to remove index.php to access my controllers directly. However, I cannot directly go my controller. I have to use index.php. For example: I want to go <a href="http://example.com/my_controller/method" rel="nofollow">http://example.com/my_controller/method</a> instead of <a href="http://example.com/index.php/my_controller/method" rel="nofollow">http://example.com/index.php/my_controller/method</a></p> <p>By the way, I used my test server, not local server like XAMPP. I enabled apache mod rewrite in my server. </p> <p>I tried a lot of htaccess rules, conditions but I cannot work it. Please help me!</p> <p>This is my .htaccess file:</p> <pre><code><IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule> </code></pre> <p>my config.php:</p> <pre><code>$config['index_page'] = ''; $config['uri_protocol'] = 'REQUEST_URI'; </code></pre> <p>How can I go directly?</p> |
36,399,800 | 0 | How can I make a TimerJob going to retrieve the users present in the AD? <p>what I want to do is retrieve users from AD , and update an address book on SharePoint Server 2013. thanks</p> |
3,785,883 | 0 | <p><code>StringBuffer</code> - introduced in JDK 1.0 - is thread safe (all of its methods are <code>synchronized</code>), while <code>StringBuilder</code> - since JDK 1.5 - is not. Thus it is recommended to use the latter under normal circumstances.</p> <p><code>StringTokenizer</code> is meant for a whole different purpose then the former two: cutting strings into pieces, rather than assembling. As @Henning noted, it is also "retired" since JDK 1.5 - it is recommended to use <code>String.split</code> instead.</p> |
1,138,262 | 0 | <p>Hard to say.</p> <ul> <li>Massive parallel queries?</li> <li>Thousands of small ones?</li> <li>OLTP or warehouse?</li> <li>CPU or IO or Memory bound?</li> <li>Server hardware and settings? MAXDOP, RAID etc</li> <li>Same set of data? (in buffer pool or lots of churning of in-memory data)</li> </ul> <p>We have 100 million rows tables with sub 1 second aggregate queries running many time during working hours, and 10,000 rows table queries that take 20 seconds but only run once at 4am.</p> |
6,874,494 | 0 | Calling a living object from one Process while running in another Process <p>Not really sure how to ask this question because I really don't know what I'm talking about. I have two DLLs (.NET), each is an AddIn that runs in two different application processes i.e. application one loads DLL one and application two loads DLL two. I wanted these DLLs to be able to communicate while loaded. In each DLL, I know the exact class that will be instantiated by the host process and I want these two living objects in each process to be able to communicate (call methods on each other). This seems like it would be possible. Has anyone done something like this before?</p> |
20,216,083 | 0 | <p>Use <strong>String</strong> replaceAll method with following pattern:</p> <p><strong>Pattern</strong></p> <pre><code>(?<=\.).*(?=\?) </code></pre> <p><strong>Code</strong></p> <pre><code>String s = "blah.t!@Z8-st?asdas"; System.out.println(s.ReplaceAll("(?<=\\.).*(?=\\?)", "")); </code></pre> |
725,060 | 0 | <p>Does it have to be an actual enum? How about using a <code>Dictionary<string,int></code> instead?</p> <p>for example </p> <pre><code>Dictionary<string, int> MyEnum = new Dictionary(){{"One", 1}, {"Two", 2}}; Console.WriteLine(MyEnum["One"]); </code></pre> |
22,736,726 | 0 | <p>I tested the following methods for 10M strings to count "," symbol.</p> <pre><code>// split a string by "," public static int nof1(String s) { int n = 0; if (s.indexOf(',') > -1) n = s.split(",").length - 1; return n; } // end method nof1 // count "," using char[] public static int nof2(String s) { char[] C = s.toCharArray(); int n = 0; for (char c : C) { if (c == ',') n++; } // end for c return n; } // end method nof2 // replace "," and calculate difference in length public static int nof3(String s) { String s2 = s.replaceAll(",", ""); return s.length() - s2.length(); } // end method nof3 // count "," using charAt public static int nof4(String s) { int n = 0; for(int i = 0; i < s.length(); i++) { if (',' == s.charAt(i) ) n++; } // end for i return n; } // end method nof4 // count "," using Pattern public static int nof5(String s) { // Pattern pattern = Pattern.compile(","); // compiled outside the method Matcher matcher = pattern.matcher(s); int n = 0; while (matcher.find() ) { n++; } return n; } // end method nof5 </code></pre> <p>The results:</p> <pre><code>nof1: 4538 ms nof2: 474 ms nof3: 4357 ms nof4: 357 ms nof5: 1780 ms </code></pre> <p>So, charAt is the fastest one. BTW, <code>grep -o ',' | wc -l</code> took 7402 ms.</p> |
33,268,121 | 0 | Font formatting performance in Excel 2007 <p>I have macro which sets font for whole range to size 9:</p> <pre><code>Range("A1:Z20000").Font.Size = 9 </code></pre> <p>When I run it on Excel 2010 or 2013 it takes approximately 1 second to process (there's almost no formatting on range). But when I run it on Excel 2007 it takes 15+ seconds to process this single line of code. I couldn't find any article regarding this, but obviously MS fixed it in newer versions of Office (Excel). </p> <p>Is there a way to set font size for a big range (500,000+ cells) in Office 2007 without killing performance?</p> |
9,315,982 | 0 | Java Swing: Changing border width/height on BorderLayout <p>I am a newbie to Java Swing. I am trying to make a frame containing three buttons; one in the center, another on the top, and the last one on the right. I want to make the NORTH and EAST borders the same width. But right now, the EAST border is wider than the NORTH border.</p> <p>I was wondering if there was a way of changing the width of the WEST/EAST borders or the height of the NORTH/SOUTH borders, in BorderLayout. </p> |
34,386,337 | 0 | Documenting Spring's login/logout API in Swagger <p>I am developing demo REST service using <code>Spring Boot</code> where user has to login in order to to perform certain subset of operations. After adding <code>Swagger UI</code> (using <code>springfox</code> library) with that simple configuration:</p> <pre><code>@Bean public Docket docApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(any()) .paths(PathSelectors.ant("/api/**")) .build() .pathMapping("/") .apiInfo(apiInfo()) .directModelSubstitute(LocalDate.class, String.class) .useDefaultResponseMessages(true) .enableUrlTemplating(true); } </code></pre> <p>I end up with all apis with all operations listed on <code>Swagger UI</code> page. Unfortunately I don't have login/logout endpoints listed among them.</p> <p>The problem is that part of that operations cannot be performed via <code>Swagger UI</code> built-in form (I find it really nice feature and would like make it work), because user is not logged in. Is there any solution to that problem? Can I define manually some endpoints in <code>Swagger</code>?</p> <p>If there was a form to submit credentials (i.e. login/logout endpoints) I could perform authorization before using that secured endpoints. Then, <code>Swagger</code> user could extract <code>token/sessionid</code> from response and paste it to custom query parameter defined via <code>@ApiImplicitParams</code>.</p> <p>Below you can find my security configuration:</p> <pre><code>@Override protected void configure(HttpSecurity http) throws Exception { http .formLogin() .loginProcessingUrl("/api/login") .usernameParameter("username") .passwordParameter("password") .successHandler(new CustomAuthenticationSuccessHandler()) .failureHandler(new CustomAuthenticationFailureHandler()) .permitAll() .and() .logout() .logoutUrl("/api/logout") .logoutSuccessHandler(new CustomLogoutSuccessHandler()) .deleteCookies("JSESSIONID") .permitAll() .and() .csrf() .disable() .exceptionHandling() .authenticationEntryPoint(new CustomAuthenticationEntryPoint()) .and() .authorizeRequests() .and() .headers() .frameOptions() .disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); } </code></pre> |
34,351,478 | 0 | <p>I now did it with unbinding the function on 'a's.</p> <pre><code>$('a').hover( function () { $('#tooltip').hide().addClass("hover"); ... </code></pre> <p>and</p> <pre><code>$("body").on( "click", function() { .... }); $("a").click(function() { $("body").off("click"); }); </code></pre> |
32,801,723 | 0 | <p>Running JavaScript on backend requires NodeJS runtime environment. Download it here <a href="https://nodejs.org/en/" rel="nofollow">https://nodejs.org/en/</a></p> <p>Alternatively you can can configure an instance on Heroku and run your application there. But I would suggest to try the first one.</p> |
23,157,933 | 0 | Scala Override Return Type <p>I have a task in which I need to override the return type of a method. The problem is the method is called yet the return type is not overridden. Please help!</p> <pre><code>abstract class Parser { type T1 <: Any; def test1(): T1; type T2 <: String; def test2(): T2; } //class path: parser.ParserA class ParserA extends Parser { type T1 = String; override def test1(): T1= { return "a,b,c"; } type T2 = String; override def test2(): T2= { return "a,b,c"; } } //some where in the project val pa = Class.forName("parser.ParserA").newInstance().asInstanceOf[Parser]; println(pa.test1().length());// error: value length is not a member of pa.TYPE_4 println(pa.test2().length());// this works, print 5; </code></pre> <p>Please Help! Thank you in advance!</p> |
38,350,373 | 0 | <p>If I understand correctly, the behavior you want is to drop each of your columns market with class="col" into a row, when your media query for small screens comes into effect.</p> <p>First of all, Outlook will strip out all in-line styling (as you noticed using F12), so best to double that up using the equivalent html attributes for each of your elements. </p> <p>Secondly, max-width is not supported by Outlook (and Lotus Notes 8 & 8.5), so you will need to wrap each of your <code><table></code>s that are inside you 'col' columns into conditional code which creates a table with a set width to hold everything in, that targets IE and Microsoft Outlook. You will need to use something like:</p> <pre><code><!--[if (gte mso 9)|(IE)]> <table width="525" align="left" cellpadding="0" cellspacing="0" border="0"> <tr> <td> <![endif]--> <table style="table-layout: auto; background-color: white; padding-left: 10px; padding-right: 10px;" border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody> <tr> <td style="padding-top: 15px;padding-right: 20px;padding-bottom: 0;padding-left: 20px;font-size: 26px;line-height: 30px;font-weight:400; font-family: Arial, sans-serif; color: #0056a6;" align="left"><img src="/resources/handlers/dcimage.ashx" style="height: auto; display: inline;" border="0">,</td> </tr> <tr> <td style="padding-top: 15px;padding-right: 20px;padding-bottom: 20px;padding-left: 20px; font-size: 14px; font-weight:normal; line-height: 14px; font-family: Arial, sans-serif; color: #2d353d;" align="left"> LOREM IPSUM </td> </tr> </tbody> </table> <!--[if (gte mso 9)|(IE)]> </td> </tr> </table> <![endif]--> </code></pre> <p>I would strongly recommend following this <a href="http://webdesign.tutsplus.com/articles/creating-a-simple-responsive-html-email--webdesign-12978" rel="nofollow">guide to build responsive emails that work on all major mail clients</a> for a more in-depth explanation of this, and also other very useful tricks for making email work even on Outlook :)</p> |
1,285,100 | 0 | <p>You can alter the temp path for the XMLSerializer explicitly without having to change the environment variables for the machine. To do this, put </p> <pre><code><xmlSerializer tempFilesLocation="c:\\newTemp"/> </code></pre> <p>in you app.config file. </p> <p>Scott Hanselman has an article entitled "<a href="http://www.hanselman.com/blog/ChangingWhereXmlSerializerOutputsTemporaryAssemblies.aspx" rel="nofollow noreferrer">Changing where XmlSerializer Outputs Temporary Assemblies</a>" about it.</p> |
7,235,961 | 0 | <p>You can have multiple programs in a shader, but not the other way around.</p> <p>To make multiple combinations, the easiest way is to store each major chunk as a fragment with a named entry point, then include them from another program or combine them at runtime into a single program, calling them in the order you need. That can get messy though, when handling input and outputs.</p> <p>You can use multiple passes, with different effects and programs in each pass. That has some additional overhead, but can be easier to set up.</p> |
18,169,635 | 0 | <p>jBilling has both installation guides (for <a href="http://www.jbilling.com/documentation/users/installation/windows" rel="nofollow">windows</a> and for <a href="http://www.jbilling.com/documentation/users/installation/mac-linux" rel="nofollow">mac/linux</a>) and a <a href="http://www.jbilling.com/documentation/users/getting-started/mediation" rel="nofollow">Getting Started Guide</a> on their website that list each step and walk you through the process. Try starting with those.</p> |
9,959,678 | 0 | <p>Try the following:</p> <pre><code>return int(float(value) / float(total) * 100.0) </code></pre> <p>to ensure that both value and total are float. This way strings could be passed in and still get a proper answer.</p> |
5,503,463 | 0 | <p>Dates and times in Excel are stored as floating point numbers. Dates are days since 1900 (a date of 1 is 01/01/1900), and times are fractions of a day (so 0.5 is 12 hours).</p> <p>Depending on what format you need the value to be in before you put it in a database, then you might just want to take the numeric value and multiple by 24 to get the hours and fractional hours, eg:</p> <pre><code>double time = cell.getNumericCellValue() * 24; int hours = (int)time; int minutes = (time - hours) * 60; </code></pre> <p>Alternately, if you want a string, then the DataFormatter class will happily format a value of 1.5 as HH:MM to 36:00</p> |
33,205,298 | 0 | How to use Powershell to download a script file then execute it with passing in arguments? <p>I usually have this command to run some powershell script:</p> <p><code>& ".\NuGet\NuGet Package and Publish.ps1" -Version $env:appveyor_build_version -NuGet "C:\Tools\NuGet\nuget.exe" -apiKey $env:apiKey</code></p> <p>works fine but the script is found locally on my server. </p> <p>I'm hoping to say: run this script with arguments, etc.. fine .. but the script is located as a GIST or in some GitHub public repo.</p> <p>Is this possible?</p> |
24,817,352 | 0 | <p>Redirect the output to <code>/dev/null</code>:</p> <pre><code>if pmset -g | grep pre >/dev/null 2>&1 ; then pmset -g | grep pre | cut -d'(' -f2 | cut -d')' -f1 else printf "Nothing\n" fi </code></pre> |
8,295,816 | 0 | How to Create an excel dropdown list that displays text with a numeric hidden value <p>I am trying to create a drop down list that displays text with a hidden numerical value attached. Then I will have a standard formula on the same row that calculates a value based upon the hidden value selected.</p> |
38,586,495 | 0 | ubuntu 16.04 rails 5 passenger nginx, node.js don't work as javascript runtime <p>Hy there, I'm working ours and don't find the solution.</p> <p>When I'm starting rails 5 with puma on ubuntu 16.04 in development mode, everything works fine, node.js works as JavaScript runtime.</p> <p>But when im starting the same application with nginx and passenger in production (precomiled with RAILS_ENV=production) I become the message: "Message from application: There was an error while trying to load the gem 'uglifier'. Gem Load Error is: Could not find a JavaScript runtime."</p> <p>I know that I can use the gem 'therubyracer' but for some reasons I don't want.</p> <p>Do somebody has an idea why node.js don't work with nginx and passenger.</p> <p>Thanks ahead for every suggestion! </p> |
23,368,691 | 0 | <p><code>var secondCharFromTheLeft = packageAData[1];</code></p> <p>He asked how to get the second char, that gives the second element in the array, not much more you can say about it.</p> |
11,792,203 | 0 | <p>Like written in the comment. This just seemed to be a <em>random</em> phenomenon.</p> |
25,249,191 | 0 | For Each Row in Range - Incorrect Row Iteration <p>I'm creating a single-column index file from multi-row/-cell source data in Excel. I have two worksheets - a source and destination - in a single workbook. Iterating through each row (11 in dev, ~15,000 in prod) of the source worksheet the <code>For Each</code> loop I wrote should:</p> <ul> <li>Find the first empty cell in Column A of the destination worksheet</li> <li>Use <code>LastCell.Value =</code> to input a set value in that cell</li> <li>Use <code>LastCell.Offset(r, c).Value =</code> to pair a set value with a copied value from each cell in a single row of the source worksheet to the next destination cell down. There are eight to be copied and a ninth that is set</li> </ul> <p>The loop works perfectly <strong>once</strong>, then fails to iterate to the next row. Each subsequent loop shifts copied values up by one and leaves the set values, with blanks, in place. It does this once for each cell in the source row and only after that does it move on to the next row down.</p> <p>When I say set value I'm referring to what is in quotes, and copied values are those of the <code>Row.Offset</code>.</p> <p>The code is:</p> <pre><code>Sub Export_Index_File() Dim wb As Workbook Dim ws1 As Worksheet, ws2 As Worksheet Dim sr As Range Set wb = ActiveWorkbook Set ws1 = wb.Worksheets("Source Data") Set ws2 = wb.Worksheets("Index File") Set sr = ws1.Range("A2:H13") For Each Row In sr.Cells Set LastCell = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Offset(1) LastCell.Value = "Begin Doc" LastCell.Offset(1, 0).Value = "Account Number: " & Row.Offset(0, 0).Value LastCell.Offset(2, 0).Value = "Account Type: " & Row.Offset(0, 1).Value LastCell.Offset(3, 0).Value = "Date: " & Row.Offset(0, 2).Value LastCell.Offset(4, 0).Value = "Doc Type: " & Row.Offset(0, 3).Value LastCell.Offset(5, 0).Value = "File Path: " & Row.Offset(0, 4).Value LastCell.Offset(6, 0).Value = "Institution: " & Row.Offset(0, 5).Value LastCell.Offset(7, 0).Value = "Name: " & Row.Offset(0, 6).Value LastCell.Offset(8, 0).Value = "TIN: " & Row.Offset(0, 7).Value LastCell.Offset(9, 0).Value = "End Doc" Next Row End Sub </code></pre> <p>Here are two output examples. Successful on the left, unsuccessful on the right:</p> <pre><code>Begin Doc |Begin Doc Account Number: 123456 |Account Number: Checking Account Type: Checking |Account Type:01/01/2001 Date: 01/01/2001 |Date: Statement Doc Type: Statement |Doc Type: 123456.pdf File Path: 123456.pdf |File Path: 123 Institution: 123 |Institution: Jane Doe Name: Jane Doe |Name: 123-45-6789 TIN: 123-45-6789 |TIN: End Doc |End Doc </code></pre> <p>Notice the one-line shift up. To fix this, I changed the loop to read <code>For Each Row In sr.Rows</code> but received Type 13 Mismatch errors. </p> <p>I copied this code from a working spreadsheet before expanding it to include more rows. It is nearly identical to the working code. What am I doing wrong?</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.