pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
23,219,898 | 0 | <pre><code><!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#hide").click(function(){ $("p").hide(); }); $("#show").click(function(){ $("p").show(); }); }); </script> </head> <body> <p>If you click on the "Hide" button, I will disappear.</p> <button id="hide">Hide</button> <button id="show">Show</button> </body> </html> </code></pre> |
20,697,027 | 0 | <p>I suppose you have in Gemfile</p> <pre><code>gem 'sprockets', '>= 2.2.1' gem 'tilt', '2.0.0' </code></pre> <p>is <code>tilt</code> version 2.0.0 critical important? If it possible to downgrade it you can do following.</p> <p>change in Gemfile</p> <pre><code>gem 'tilt', '1.4.1' # the previous version http://rubygems.org/gems/tilt </code></pre> <p>run</p> <pre><code>bundle update tilt </code></pre> <p>After this you can remove tilt version from Gemfile</p> |
21,623,242 | 0 | <p>execute following commands (with root or sudoers privilege)</p> <pre><code>cd /etc/yum.repos.d ##Moving to a certain directory wget http://people.centos.org/hughesjr/chromium/6/chromium-el6.repo ##Download the chromium package yum install chromium ##Install the chromium packages in the mentioned directory </code></pre> |
18,305,658 | 0 | <p>If you follow this tutorial it should work: </p> <p><a href="http://sfmlcoder.wordpress.com/2011/08/16/building-sfml-2-0-with-make-for-gcc/" rel="nofollow">http://sfmlcoder.wordpress.com/2011/08/16/building-sfml-2-0-with-make-for-gcc/</a></p> <p>then put the sfml 2 folder with all the dependencies inside of your /usr/include/ folder and compile with <code>g++ main.o -o main -lsfml-graphics -lsfml-window -lsfml-system</code> and run with with <code>./main</code> it should work perfectly. I actually setup a key mapping in vim that compiles using that command and then runs it and its works flawlessly for me.</p> |
19,695,545 | 0 | The entity type [xxx] is not part of the model for the current context <blockquote> <p>Blockquote</p> </blockquote> <p>I been going at this problem for a few days now. I'm trying to create a db connection using Visual Studio 2010 MVC2 EF 6.0. I can connect to the DB using the server explorer. </p> <p>Here is what I done so far:</p> <ol> <li>Created a Model: ModelEntities.edmx (connects to a SQL Server DB)</li> </ol> <p><strike> 2. Created a Model for the table I'm trying to access: Table.cs ( has all the public members)</p> <pre><code>public class Quickfix { public int FIX_ID { get; set; } public string NAME { get; set; } public string TYPE { get; set; } public string DESCRIPTION { get; set; } } </code></pre> <ol> <li><p>Created a DAL folder and added my context to it: (ModelEntitesContext.cs )</p> <p>using ServiceDesk_Solution.Models;</p> <p>namespace ServiceDesk_Solution.DAL{</p> <pre><code> public class ModelEntitiesContext : DbContext { public ModelEntitiesContext() : base("ModelEntities") { } public DbSet<Quickfix> Quickfixs { get; set; } } } </code></pre> <p></strike></p></li> <li><p>I created a controller for my View: (Called my controller DBController.cs)</p> <p>public class DBController : Controller { // // GET: /DB/</p> <pre><code><strike>ModelEntitiesContext db = new ModelEntitiesContext ();</strike> ModelEntities db = new ModelEntities(); public ActionResult DB() { return View(db.Quickfix.ToList();); } </code></pre> <p>}</p></li> <li><p>Finally I create a strong view using my Model <strike>(DB.aspx)</strike> ModelEntities.Quickfix <strike>and this is when I get the context error (see error and stack trace bellow)</strike></p></li> <li><p>My config file:</p> <p>add name="ModelEntities" connectionString="metadata=res://<em>/Models.CSCEntities.csdl| res://</em>/Models.ModelEntities.ssdl| res://*/Models.ModelEntities.msl; provider=System.Data.SqlClient; provider connection string=" data source=devsql;initial catalog=Model; persist security info=True;user id=user;password=password; multipleactiveresultsets=True; App=EntityFramework"" providerName="System.Data.EntityClient"</p></li> </ol> <p><strong>No more error</strong></p> <p><strike>Error Message:</p> <pre><code>The entity type Quickfix is not part of the model for the current context. </code></pre> <p>Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. </p> <p>Exception Details: System.InvalidOperationException: The entity type Quickfix is not part of the model for the current context.</p> <pre><code>Source Error: Line 14: public ActionResult DB() Line 15: { Line 16: db.Quickfix.ToList(); Line 17: return View(); Line 18: } Source File: ***_Solution\Controllers\DBController.cs Line: 16 Stack Trace: [InvalidOperationException: The entity type Quickfix is not part of the model for the current context.] System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType) +191 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +46 System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +125 System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +33 System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +100 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +315 System.Linq.Enumerable.ToList(IEnumerable`1 source) +58 ServiceDesk_Solution.Controllers.DBController.DB() in ***_Solution\ServiceDesk_Solution\Controllers\DBController.cs:16 lambda_method(Closure , ControllerBase , Object[] ) +96 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +51 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +409 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +52 System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +127 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436 System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +61 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +305 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830 System.Web.Mvc.Controller.ExecuteCore() +136 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8981789 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272 </code></pre> <p></strike></p> |
13,275,654 | 0 | <p>You can do this with a merge..output to a table variable followed by an update.</p> <p><a href="http://sqlfiddle.com/#!3/6c36a/3">SQL Fiddle</a></p> <p><strong>MS SQL Server 2008 Schema Setup</strong>:</p> <pre><code>create table Items ( ItemsId int identity primary key, ItemName nvarchar(50) not null, ItemsLanguageTextId int null ); create table ItemsLanguageText ( ItemsLanguageTextId int identity primary key, Text nvarchar(50) not null ); insert into Items values('Name 1', null); insert into Items values('Name 2', null); insert into Items values('Name 3', null); </code></pre> <p><strong>Query 1</strong>:</p> <pre><code>declare @T table ( ItemsId int, ItemsLanguageTextId int ); merge ItemsLanguageText as T using ( select ItemsId, ItemName from Items where ItemsLanguageTextId is null ) as S on 0 = 1 when not matched then insert (Text) values (S.ItemName) output S.ItemsId, inserted.ItemsLanguageTextId into @T; update Items set ItemsLanguageTextId = T.ItemsLanguageTextId from @T as T where T.ItemsId = Items.ItemsId; </code></pre> <p><strong><a href="http://sqlfiddle.com/#!3/6c36a/3/0">Results</a></strong>:</p> <p><strong>Query 2</strong>:</p> <pre><code>select * from Items; </code></pre> <p><strong><a href="http://sqlfiddle.com/#!3/6c36a/3/1">Results</a></strong>:</p> <pre><code>| ITEMSID | ITEMNAME | ITEMSLANGUAGETEXTID | -------------------------------------------- | 1 | Name 1 | 13 | | 2 | Name 2 | 14 | | 3 | Name 3 | 15 | </code></pre> <p><strong>Query 3</strong>:</p> <pre><code>select * from ItemsLanguageText; </code></pre> <p><strong><a href="http://sqlfiddle.com/#!3/6c36a/3/2">Results</a></strong>:</p> <pre><code>| ITEMSLANGUAGETEXTID | TEXT | -------------------------------- | 13 | Name 1 | | 14 | Name 2 | | 15 | Name 3 | </code></pre> |
1,772,094 | 0 | <p>I look at vertical space in code the way I look at paragraphs in written prose. Just as a paragraph is meant to group sentences together that have a common point or idea, lines that are related should be grouped together.</p> <p>The overall objective is to improve the readability of the code. Just as an article without any paragraphs would be difficult to read, so to is code without any vertical space. And just as with prose, there is a balance between composing paragraphs that are too short or too long. But in the end, it mostly comes down to personal style and preference.</p> |
8,836,470 | 0 | <p>Linq was build with an functional style in mind. Using it the imperative way would not end up in elegant code. So don't transform after the query but in the query - put the logic in the projection section (select). (Much like Anthony's answer)</p> <pre><code>var str = (from i in Regex.Split("TheQuickBrownFox", "") select Regex.IsMatch(i, "[A-Z]") ? " " + i : i) .Aggregate((str1, str2) => str1 + str2); Console.WriteLine(str); </code></pre> |
3,671,136 | 0 | <p>Write it in C first, compile and view the assembly listing to see what the compiler generated. This is the easiest way to learn. If you see an instruction that you don't understand look for it in the Intel Instruction Set Reference PDFs.</p> |
29,483,549 | 0 | <p>I would define a question class that has a list of answers and return that. </p> <pre><code>public class Answer { public string AnswerText {get; set;} } public class Question { public List<Answer> Answers {get; set; } } </code></pre> <p>In your class that calls getQuestion, you should return the question object you're looking for that contains its answers. </p> <pre><code>public class MainClass { public List<Question> Questions {get; set;} public Question GetQuestion(/* some criteria, like question number or something */) { var selectedQuestion = // get the question from Questions based on some criteria return selectedQuestion; } } </code></pre> <p>And then do whatever you need to do in the presentation layer for the end-user to show them the question and answers. </p> |
19,315,061 | 0 | <p>You can get path of executable of default browser from registry (look at the following answer for example: <a href="http://stackoverflow.com/a/17599201/2870402">http://stackoverflow.com/a/17599201/2870402</a>) and create new process passing the URL as the parameter:</p> <pre><code>string pathToExecutable = ...; string url = @"file:///c:\Projects\HTMLTest\Debug\help\index.htm#Modules\Administration\UserInterface\MainWindow\Processing.htm"; System.Diagnostics.Process.Start(pathToExecutable, url); </code></pre> |
16,914,759 | 0 | <p>The string should start (<code>^</code>) with any character (<code>.</code>) followed by at least 5 (<code>{5,}</code>) non witespace characters (<code>[\\S]</code>) then it should end (<code>$</code>)</p> |
21,098,752 | 0 | <p>Like @CL was saying you can't have 2 records with the same <code>PRIMARY KEY</code></p> <p>this Table should be built with 3 columns.</p> <ol> <li><code>A_ID</code> PRIMARY KEY AUTO INCREMENT NOT NULL</li> <li><code>time</code> DATETIME (probably <code>NOT NULL</code> as well</li> <li><code>data</code> REAL</li> </ol> <hr> <p>in other words, Never set the Primary key in your code, let the database auto increment it for you, or use a GUID. </p> <p>this line </p> <pre><code>data=(1,2) </code></pre> <p>is the only thing that is being inserted into your database. so the only record in the database will be the one you insert, which is <code>1,2</code></p> |
25,405,933 | 0 | <p>I can not add my solution as comment. so writing here.</p> <p>I was facing the same issue. Root cause was Images.xcassets folder. This image folder got corrupted. Solution. Delete existing "Images.xcassets". Create new black project and drag the Images.xcassets from new projects to existing project.</p> <p>If anyone facing this issue. Try this at least once.</p> |
27,088,277 | 0 | <p>The type is incomplete, like it says. This is not legal (intrusive containers need to know the implementation details - bases, size etc. - at instantiation time).</p> <p>The documentation specifically mentions that you should avoid deducing hook types when you do this kind of 'nested' use.</p> <p>Given this, there are several ways to fix it:</p> <ol> <li><p>You could just shuffle things around: <strong><a href="http://coliru.stacked-crooked.com/a/d32fc155b70a8889" rel="nofollow">Live On Coliru</a></strong>.</p></li> <li><p>If you really would like <code>InputBufferSglList</code> to be a global typedef, of course, you can just alias it: <strong><a href="http://coliru.stacked-crooked.com/a/d0f70d45810bc94e" rel="nofollow">Live On Coliru</a></strong></p></li> <li><p><strong>UPDATE</strong> To the comment, it seems you're really insisting on making this a forward-declared list type, and you can, as described here <a href="http://www.boost.org/doc/libs/1_57_0/doc/html/intrusive/recursive.html" rel="nofollow">in the documentation</a>:</p> <pre><code>typedef boost::intrusive::slist_base_hook<> InputBufferSglHook; class InputBufferSglNode; // list typedef boost::intrusive::slist< InputBufferSglNode, boost::intrusive::base_hook<InputBufferSglHook>, boost::intrusive::cache_last<true> > InputBufferSglList; typedef InputBufferSglList::iterator InputBufferSglIterator; </code></pre> <p>Job Done. See it <strong><a href="http://coliru.stacked-crooked.com/a/4e4b79fa1acef65e" rel="nofollow">Live On Coliru</a></strong> too.</p></li> </ol> <h3>Full Demo</h3> <p>The third version in full, for future reference:</p> <pre><code>#include <boost/intrusive/slist.hpp> typedef boost::intrusive::slist_base_hook<> InputBufferSglHook; class InputBufferSglNode; // list typedef boost::intrusive::slist< InputBufferSglNode, boost::intrusive::base_hook<InputBufferSglHook>, boost::intrusive::cache_last<true> > InputBufferSglList; typedef InputBufferSglList::iterator InputBufferSglIterator; class InputBufferSglNode : public InputBufferSglHook { public: InputBufferSglNode(const void* buffer, size_t size); ~InputBufferSglNode() {}; // copy 'size_t' bytes from list to target, if list doesn't have enough space, method shall return false static bool copy_buffer_from_list(InputBufferSglList &list, InputBufferSglIterator &iter, size_t &offset_in_node, const InputBufferSglIterator& end, uint8_t *target, size_t size); void reset(); public: const void *m_buffer; size_t m_size; }; // empty list const InputBufferSglList s_EMPTY_INPUT_BUFF_SGL = InputBufferSglList(); InputBufferSglNode::InputBufferSglNode(const void* buffer, size_t size) : InputBufferSglHook(), m_buffer(buffer), m_size(size) { // empty } void InputBufferSglNode::reset() { m_buffer = nullptr; m_size = 0; } bool InputBufferSglNode::copy_buffer_from_list(InputBufferSglList &list, InputBufferSglIterator &iter, size_t &offset_in_node, const InputBufferSglIterator& end, uint8_t *target, size_t size) { // implementation } int main() { } </code></pre> |
30,901,882 | 0 | <p>Works for me:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.editbtn').click(function() { $(this).html($(this).html() == 'edit' ? 'modify' : 'edit'); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <button class="editbtn">edit</button> </td> </tr> <tr> <td> <button class="editbtn">edit</button> </td> </tr> <tr> <td> <button class="editbtn">edit</button> </td> </tr> <tr> <td> <button class="editbtn">edit</button> </td> </tr> </table></code></pre> </div> </div> </p> |
20,367,715 | 0 | Shared events text on search results <p>We have a multisite solution . It looks like </p> <pre><code>Sitecore - Contenent -Country one -Country Two .... -Contry X </code></pre> <p>We have shared events for country sites:</p> <pre><code> /Global/Events/Event One /Global/Events/Events Two .... /Global/Events/Events X </code></pre> <p>These events are displayed on Country Site . My problem is when we search on country site text displayed on events doesn't appear on search results.</p> |
36,503,261 | 0 | <p>If you want to do it with DSC, here's a sample: <a href="https://github.com/bmoore-msft/AzureRM-Samples/tree/master/VMDSCInstallFile" rel="nofollow">https://github.com/bmoore-msft/AzureRM-Samples/tree/master/VMDSCInstallFile</a>. Ed's answer might be a simpler approach though. The key here is getting the credentials to the VM to be able to pull from storage. That means whether you're using DSC or a custom script, you need to get the location/uri and a sasToken to the script (unless the files are unsecured). The DSC sample above will give you a way to pass the uri/token that will work in either workflow. Look at the PS script in the root to see how the uri & token are created and passed to the template deployment.</p> |
40,279,061 | 0 | <p>You can use the time function </p> <pre><code>import time start = time.time() #do stuff end = time.time() logger.debug("time:{0}".format(end-start)) </code></pre> |
41,028,112 | 0 | How to use my api in Flexapp? <p>I'm using restful service with slim framework.</p> <p>I'm using <a href="http://flexapp.com/" rel="nofollow noreferrer">FlexAPP</a> for Mobile app developing without knowing any code.</p> <p>example: <a href="http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/" rel="nofollow noreferrer">http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/</a></p> <p>How can I use this API to pull the JSON data?</p> <ol> <li>I created main page and second page.</li> <li>That redirects to "second page" when the "main page image" is clicked</li> <li>I creating an invisible label on "second page" and I'm using "change value" to label.</li> <li>My label value is my article ID value.</li> </ol> <p>My API has this information:</p> <ul> <li><code>wine_title</code>,</li> <li><code>wine_description</code>,</li> <li><code>article</code>, and</li> <li><code>image</code></li> </ul> <p>my app screenshot: <a href="http://prntscr.com/dgn7ol" rel="nofollow noreferrer">http://prntscr.com/dgn7ol</a></p> <p>How do I get the variable?</p> |
12,972,853 | 0 | Generating random string by TypoScript <p>Is it possible to auto generate a mixed string of digits and letters by TypoScript, e.g. <code>12A54</code> or something similar?</p> |
34,865,334 | 0 | <p>By default, ISO-8859-1 encoding is used when reading properties files. Characters not available in that encoding must be converted using Unicode escapes ("\u1234"), e.g. using the <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/native2ascii.html" rel="nofollow">native2ascii</a> tool. See <a href="http://stackoverflow.com/questions/4659929/how-to-use-utf-8-in-resource-properties-with-resourcebundle">this answer</a> to a related question for some more details.</p> <p>Alternatively, you could plug in a custom <code>ResourceBundleLocator</code> which reads properties using UTF-8 encoding. The Hibernate Validator reference guide <a href="http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-resource-bundle-locator" rel="nofollow">describes</a> how to do this. As a starting point, you could take <a href="https://github.com/hibernate/hibernate-validator/blob/master/engine/src/main/java/org/hibernate/validator/resourceloading/PlatformResourceBundleLocator.java" rel="nofollow">PlatformResourceBundleLocator</a> and adapt it as per your requirements.</p> |
12,326,604 | 0 | Mathematica: Plotting a module with FindRoot in it <p>I run into this problem occasionally, and I haven't found a way around it. It usually happens when I'm finding the root of an equation, and want to maximize/minimize/plot that root according to some parameter. So I try to wrap the the code in a module so it can all be executed with just an input number, but it won't work inside functions like Plot. For example:</p> <pre><code>f[din_] := Module[{d = din}, sol = NDSolve[{y'[x] == y[x], y[0] == 1}, y[x], {x, 0, 10}]; t1 = Flatten[FindRoot[y[x] - d /. sol, {x, 1}]]; x /. t1 ] f[2] f[2.5] f[3] Plot[f[x], {x, 2, 3}] </code></pre> <p>The calls to f with a number all work as expected, but the f in the Plot function seems to be evaluated with the symbol 'x' - or something and just gives a lot of error text.</p> <p>Any way around this?</p> <p>Looking around the forums I found some suggestions for similar problems - like making the definition like this:</p> <pre><code> f[din_?NumericQ]:= </code></pre> <p>and I tried everything I could but nothing seems to make a difference. I'm using Mathematica 8.0</p> |
25,411,166 | 0 | Progressbar for two or more operations <p>I have this code in doInBackground method of an AsyncTask:</p> <pre><code> for (int i = 0; i < lenght; i++) { // Do something count++; publishProgress(count * 100 / lenght); } </code></pre> <p>and all works fine. If i add another operation, how to reflect this with the progress bar?</p> <p>Now i have this code:</p> <pre><code> for (int i = 0; i < lenght1; i++) { // Do something count++; publishProgress(count * 100 / lenght1); } for (int i = 0; i < lenght2; i++) { // Do something count++; publishProgress(count * 100 / lenght2); } </code></pre> <p>How to make the bar start from 0 when operation 1 starts and finish at 100 when operation 2 ends? I tried to change count*100 to count*50 but it seems not to be the right way...</p> |
8,658,092 | 0 | I need to parse the XML file in my android application. I dont know how many nodes it got <p>My activity class look like this:</p> <pre><code>AssetManager assetmgr= getAssets(); String list[] = assetmgr.list("subdir"); if (list != null) { DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(getAssets().open("subdir/fullSurvey.xml")); </code></pre> <p>xml object class looks like this:</p> <pre><code>NodeList root = doc.getElementsByTagName("root"); NodeList nlQuestions = root.item(0).getChildNodes(); QuestionObject[] allQuestions = new QuestionObject[nlQuestions.getLength()]; for (int i = 0; i < nlQuestions.getLength(); i++) { Node question = nlQuestions.item(i); NodeList childNodes = question.getChildNodes(); QuestionObject x = new QuestionObject(); for (int j = 0; j < childNodes.getLength(); j++) { Node child = childNodes.item(j); if (child.getNodeName() !="#text") { Questions t = Questions.valueOf(child.getNodeName()); // etc. </code></pre> <p>I dont know how to parse xml file according to attribute value</p> |
16,098,167 | 0 | <p>Its a rails method. You can get into a rails console by <code>rails c</code> and pass <code>include ActionView::Helpers::DateHelper</code>. Then work around something like</p> <pre><code>t = Time.parse("2013-04-19 11:07:37 +0530") time_ago_in_words(t) </code></pre> <p>HTH</p> |
10,339,384 | 0 | <p>Here is a stab at a solution. It needs a bit of cleanup but should give you everything you need.</p> <p>Create a custom ActionFilter, and then decorate your methods with it. </p> <pre><code>[ManagerIdAuthentication] public ActionResult Details(int id) { // Gets executed if the filter allows it to go through. } </code></pre> <p>The next class can be created in a separate library so you can include it in all your actions that require this validation.</p> <pre><code>public class ManagerIdAuthentication : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { // the next line needs improvement, only works on an httpGet since retrieves // the id from the url. Improve this line to obtain the id regardless of // the method (GET, POST, etc.) var id = filterContext.HttpContext.Request.QueryString["id"]; var employee = employeeRepository.Get(id); var user = filterContext.HttpContext.User.Identity; if (employee.managerId == user.managerId) { var res = filterContext.HttpContext.Response; res.StatusCode = 402; res.End(); filterContext.Result = new EmptyResult(); //may use content result if want to provide additional info in the error message. } else { // OK, let it through. } } } </code></pre> |
37,668,301 | 1 | Move Rows Up By One Of Specified Column In Pandas <p>I have a file like this:</p> <pre><code>value1, value2, value3, value4, value5 NAN NAN value8, value9, value0 value6, value7, NAN NAN NAN </code></pre> <p>And I would like to push row 3 up to do the following:</p> <pre><code>value1, value2, value3, value4, value5 value6, value7, value8, value9, value0 NAN NAN NAN NAN NAN </code></pre> <p>I would also like the rows below these rows to move up as well.</p> <p>How is this done in pandas?</p> |
3,084,255 | 0 | <p>Try to initialize the object linked to the field in the previous action method.</p> <p>In your java File:</p> <pre><code>X object = new X() ; object.setDesc(""); request.setAttribute("theFormObject",object); </code></pre> <p>In your JSP:</p> <pre><code><s:textarea name="theFormObject" property="desc" ... /> </code></pre> |
28,065,131 | 0 | <p><strong>Specific Photo would be something like this:</strong></p> <pre><code>//photo_id just example $photo_id = '1'; SELECT pt.id as id, pt.photo_id as photo_id, pt.tag_id as tag_id, t.tag_title, p.photo_title, p.path FROM photos p INNER JOIN photo_tags pt ON pt.photo_id = $photo_id INNER JOIN tags t ON t.tag_id = pt.tag_id </code></pre> <p><strong>All Phosts:</strong></p> <pre><code>SELECT pt.id as id, pt.photo_id as photo_id, pt.tag_id as tag_id, t.tag_title, p.photo_title, p.path FROM photos p INNER JOIN photo_tags pt ON pt.photo_id = p.photo_id INNER JOIN tags t ON t.tag_id = pt.tag_id </code></pre> |
8,294,891 | 0 | <p>Good call on the thread dump. Try issuing a Conn.stop(). It seems the JMS client still has non daemon threads running</p> |
4,810,935 | 0 | <p>I chalk this one up to bad drivers.</p> |
34,915,726 | 0 | Why is the slider not updating the label when I make the slider programmatically? <p>I made a slider and label <strong>PROGRAMMATICALLY</strong>. I wanted the label to display the value of the slider, but the label only displays the value I initially assigned.</p> <p>Code:</p> <pre><code>var num: CGFloat = 9 override func viewDidLoad() { let label = UILabel(frame: CGRectMake(0, 0, 60, 40)) label.text = "\(num)" self.view.addSubview(label) let slider = UISlider(frame:CGRectMake(0, 0, 60, 30)) slider.value = Float(num) slider.addTarget(self, action: "changedSliderValue:", forControlEvents: .ValueChanged) self.view.addSubview(slider) } func changedSliderValue(sender: UISlider!){ num = CGFloat(sender.value) label.text = "\(num)" } </code></pre> <p>When I did <code>print(label.text!)</code>, it showed me that <code>label.text</code> was changing as I changed the slider value. But then, why doesn't the label change on my view controller?</p> |
32,844,803 | 0 | <p>Since your file is not a valid JSON, you can use <code>eval</code> (it's a dirty hack but it works), example :</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>data = '{name:"sda"}'; eval('foo = ' + data); console.log(foo);</code></pre> </div> </div> </p> |
36,510,826 | 0 | <p>You're problem is that you are trying to pass data in STRING FORMAT. In your script you pass the $row out of while loop so it doesn't pass anything useful for you. If you have more than one button you can't use ID ATTRIBUTE but you have to use CLASS. Set a data-id attribute so you can pass the value from the database and set an ID to the input so you can take its value also. Try this:</p> <pre><code><?php if(mysqli_num_rows($result)){ while($row = mysqli_fetch_assoc($result)){ print "<div class='item col-xs`-4 col-lg-4'>". "<div class='row'>". "<div class='col-xs-10'>". "<p class='list-group-item-text'>". "<input type='text' class='form-control' id='input-" . $row["id"] . "'>". "<button data-id='". $row["id"] . "' class='mybutton btn btn-success'>Calculate</button>". "</div>". "</div>". "</div>"; } } ?> <script type="text/javascript"> $(document).ready(function(){ $(".mybutton").on("click", function(){ var myid = $(this).attr('data-id'); var myinput = $('#input-'+myid).val(); alert("MY ID IS: " + myid); alert("MY INPUT VALUE IS: " + myinput); }); }); </script> </code></pre> |
2,727,848 | 0 | <p>If you want to send the data using <code>POST</code> you'll need to bring those variables down as hidden input fields on your form before your users clicks submit:</p> <pre><code><input type="hidden" name="firstname" value="<?php echo($_SESSION['firstname']); ?>" /> <input type="hidden" name="surname" value="<?php echo($_SESSION['surname']); ?>" /> <input type="hidden" name="age" value="<?php echo($_SESSION['age']); ?>" /> </code></pre> <p>Alternatively you could just reference the <code>$_SESSION</code> when your at the processing stage, if this is applicable.</p> |
3,064,377 | 0 | Introduction into video compression tech <p>Is it useful to study the H.261 specification for an introduction into modern video compression technology, or should I start somewhere else? I'm not sure where to start, but H.261 seems simple enough to make it easy to grasp the concepts.</p> |
13,744,019 | 0 | <p>As the forum post you point to says, Attachments aren't implemented in the OpenNETCF Mail code. We just never got around to doing it. An email with attachments is simply multipart MIME message, which is not terribly complex and is <a href="http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html" rel="nofollow">covered in RFC 1341</a>. You would have to extend the code to build up a multipart MIME message, and then set the appropriate content-type.</p> |
26,322,174 | 0 | Microsoft Visual Studio 2013 Command Prompt Truncates <p>When I print out my results in C++ (multiple, multiple lines are printed) my output gets truncated by the command prompt attached to Visual Studio. I tried changing my buffer size via the OS preferences, but it seems as though VS has their own settings. I have tried finding the answer to this problem to no avail. If anyone can help out it would be much appreciated!</p> |
36,428,996 | 0 | Get most viewed youtube videos for the last 7 days <p>Is there any way to search in youtube api for the most viewed videos in last 7 days?</p> <p>It's good if i can filter the videos over 1000 views.</p> <p>Thanks in advance.</p> |
29,832,169 | 0 | <p>Maybe I did not understand the question right, but isnt it as simple as use the hidden class?</p> <pre><code><li class="hidden-xs"><a href="#">Action</a></li> </code></pre> |
27,953,649 | 0 | <p>Even if you look up the method in both cases (i.e. before 2nd and 3rd loop), the first lookup takes way less time than the second lookup, which should have been the other way around and less than a regular method call on my machine.</p> <p>Neverthless, if you use the 2nd loop with method lookup, and <code>System.out.println</code> statement, I get this:</p> <pre class="lang-none prettyprint-override"><code>regular call : 740 ms look up(2nd loop) : 640 ms look up ( 3rd loop) : 800 ms </code></pre> <p>Without <code>System.out.println</code> statement, I get:</p> <pre class="lang-none prettyprint-override"><code>regular call : 78 ms look up (2nd) : 37 ms look up (3rd ) : 112 ms </code></pre> |
12,450,365 | 0 | Checking if divisible with 90+180*n <p>I want, in php, to check if $var1 == 90+180*n</p> <p>Where n is all natural numbers, ie. 1,2,3,4...</p> <p>Thanks in advance.</p> |
7,443,951 | 0 | <p>When you modify the dom tree, you modify it in memory, but the original file where this dom tree comes from is not affected. You need to write the modified dom tree to the file in order to persist the changes you have made in memory. </p> <p>It's exactly the same as if you read a whole file in a StringBuilder. Modifying the StringBuilder won't magically write the new content to the file.</p> <p>See <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPXSLT4.html" rel="nofollow">http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPXSLT4.html</a> for example code to write a DOM tree to a file.</p> |
12,308,086 | 0 | <p>By default all the controls in WPF have a default <code>ContextMenu</code> that allows copy, paste and cut. You can disable this menu by setting this property as <code>“{x:Null}”</code>, but the keys associated with the menu options still work. In order to disable this commands we can use the <code>DataObject</code> class, which have handlers to attach any <code>DepencencyObject</code> in case on Copy or Paste:</p> <pre><code>DataObject.AddPastingHandler(control, this.OnCancelCommand); DataObject.AddCopyingHandler(control, this.OnCancelCommand); </code></pre> <p>Finally in the event handler we need to cancel the current command:</p> <pre><code>private void OnCancelCommand(object sender, DataObjectEventArgs e) { e.CancelCommand(); } </code></pre> <p>The CancelCommand method will cancel any <code>ApplicationCommand.Copy, ApplicationCommand.Paste</code> and ApplicationCommand.Cut sent over the control.Now if you want to enable copying than delete the dateobject calling <code>AddCopyingHandler</code> code and it will work than.</p> |
25,062,571 | 0 | <p><code>Mainclass</code> class does not have a method with name <code>SetName</code> so the error <code>The method Setname(String) is undefined for the type Mainclass".</code></p> |
28,614,445 | 0 | <p>You did not set the flag, in your <code>findLonelyInteger()</code> method's first <code>if</code> condition!</p> <pre><code>if ((i+1) == inputLength) { System.out.println("Lonely Integer: " + inputArray[i]); foundLonelyInteger = true; // --> HERE break; } </code></pre> <p>Command Prompt? Start using Eclipse! And learn debugging!</p> |
2,130,059 | 0 | <p>Sounds like the mysqld-nt's network connections are being exhausted hence the telnet fails and a restart cures it, are you using too many connections, try increasing the connections allowed/permitted for the server itself.</p> <p>Hope this helps, Best regards, Tom.</p> |
33,474,952 | 0 | <p>Login into the FIWARE Cloud Portal with your credentials. Press on <em>Cloud link</em> on top, then you should see a menu to the left and go to <em>Compute->Images</em>.</p> <p>All the images available in the FIWARE Catalog will be displayed. You can always deploy a VM from any of the images by pressing the <em>Lauch</em> bottom that appears at the right side of the images.</p> <p>BR Jesus</p> |
28,194,149 | 0 | <p><em>Update:</em></p> <p>The original answer (below) still applies, but given that the form is actually loaded using AJAX, you can't bind the event listeners in the <code>$(document).ready</code> callback. The best option for you is to use event delegation. This is done by attaching an event listener to a DOM element that <em>does</em> exist from the start, but have that listener pick up on events for elements that might be added later on. For example: the body element will always exist, so you can listen for a form submission there, whether or not that form exists doesn't matter:</p> <pre><code>$('body').on('submit', '#form-id', function(e) { console.log('#form-id was submitted, do AJAX => submission stopped'); return false; //or e.preventDefault(); e.stopPropagation(); }); </code></pre> <p>The why and how this works is very well explained <a href="http://www.quirksmode.org/js/events_order.html" rel="nofollow">here</a>. It boils down to the fact that all events pass through all of the parent DOM elements of the target node, so you can attach listeners anywhere in the DOM, and handle the events before they reach their target.<br> I think <a href="http://stackoverflow.com/a/17352923/1230836">this old answer of mine</a> might explain a thing or 2, too. It doesn't use jQ, but it contains a simplified version of the code that jQ uses internally for delegation.</p> <hr> <p>You're preventing the default effects of the click event on <code>$('#edit-comment')</code>, but that event still propagates through to the form. You might want to add <code>e.stopPropagation()</code>, too. Or simply <code>return false;</code> from the callback (which prevents the default <em>and</em> stops propagation).</p> <p>However, a better way to prevent the form from being submitted is to use the <code>submit</code> event, and stop the submission there:</p> <pre><code>$('#form-id').on('submit', function(e) { console.log('Do ajax call here'); return false; //or e.preventDefault(); e.stopPropagation(); }); </code></pre> |
16,051,074 | 0 | <ol> <li>Have a Version table in the database</li> <li>Use a <a href="http://weblogs.asp.net/bradleyb/archive/2005/12/02/432150.aspx" rel="nofollow">custom MSBuild Task</a> to get the build number</li> <li>You can update a sql file with the <a href="http://benchmarkitconsulting.com/colin-stasiuk/2009/02/27/merge-statement-upsert-with-working-example/" rel="nofollow">'MERGE'</a> with build number using <a href="http://stackoverflow.com/questions/8658972/using-msbuild-i-want-to-update-a-config-file-with-values-from-teamcity">FileUpdate MSBuild community task </a></li> <li>Execute it as part of deployment.</li> </ol> <p>Now, you'll have same version number in both database & your assemblies.</p> |
38,905,262 | 0 | SELECT with date field in WHERE clause fails via Ajax <p>A jquery builder (from <a href="http://querybuilder.js.org/" rel="nofollow">http://querybuilder.js.org/</a> ) is used to let the user pick a date and further select data for a DataTables (datatables.net/ ) via a PHP function.</p> <p>The DataTables and especially Ajax function looks like this:</p> <pre><code>var table = $(id).DataTable({ serverSide: true, searching: true, processing: true,, ajax: { url: "controllers/myAjax.php", type: "POST", data: result } }); </code></pre> <p>The object passed as <em>data</em> is defined by queryBuilder and appended to my query string in the PHP script. To nail things down I pass the data as plain SQL (<a href="http://querybuilder.js.org/plugins.html#import-export" rel="nofollow">http://querybuilder.js.org/plugins.html#import-export</a>). In my problem test case this is:</p> <pre><code>WHERE birthdate < '1990-01-01' </code></pre> <p>This would result in the SELECT query:</p> <pre><code>SELECT * from table_1 WHERE birthdate < '1990-01-01' </code></pre> <p>This query throws a MySQL error:</p> <pre><code>"[...] check the manual that corresponds to your MySQL server version for the right syntax to use near '\'1990-01-01\' " </code></pre> <p>Obviously the date doesn't get escaped correctly. But when I enter exactly this query to my MySQL workbench, the server executes and returns a correct set of results. Even more, the workbench doesn't care if I use single quote (') or double quote ("). </p> <p>Further, I tried to manually remove those escape chars using PHP str_replace. The function then returns values, but obviously interpreted as int and breaking other queries (like equal ID). Same goes for msqli.real-escape-string (<a href="http://php.net/manual/de/mysqli.real-escape-string.php" rel="nofollow">http://php.net/manual/de/mysqli.real-escape-string.php</a>). </p> <p>Another approach I tried was to change the dataType of the Ajax function a little bit - but basically I am sending form-encoded data, so the default type for this should be fine? </p> <p>So why does (only) the date field get escaped in a wrong manner? Is there any rather quick fix for this, before I have to write my own PHP functions for accessing the DB? </p> |
29,012,708 | 0 | Why cache read miss is faster than write miss? <p>I need to calculate an array (writeArray) using another array (readArray) but the problem is the index mapping is not the same between arrays (Value at index x of writeArray must be calculated with value at index y of readArray) so it's not very cache friendly.</p> <p>However I can either choose if the loop browses readArray sequentially or writeArray sequentially.</p> <p>So here is a simplified code :</p> <pre><code>int *readArray = new int[ARRAY_SIZE]; // Array to read int *writeArray = new int[ARRAY_SIZE]; // Array to write int *refArray = new int[ARRAY_SIZE]; // Index mapping between read and write, could be also array of pointers instead indexes // Code not showed here : Initialization of readArray with values, writeArray with zeroes and refArray with random indexes for mapping between readArray and writeArray (values of indexes between 0 and ARRAY_SIZE - 1) // Version 1: Random read (browse writeArray/refArray sequentially) for (int n = 0; n < ARRAY_SIZE; ++n) { writeArray[n] = readArray[refArray[n]]; } // Version 2: Random write (browse readArray/refArray sequentially) for (int n = 0; n < ARRAY_SIZE; ++n) { writeArray[refArray[n]] = readArray[n]; } </code></pre> <p>I was thinking that cache read misses was more slower than write misses (because CPU needs to wait before reading complete if the next instruction depends of read data but for writing it doesn't need to wait for processing the next instruction) but with profiling it's seems that version 1 is faster than version 2 (version 2 is about 50% more slower than version 1).</p> <p>I tried also this :</p> <pre><code>// Version 3: Same as version 2 but without polluting cache for (int n = 0; n < ARRAY_SIZE; ++n) { _mm_stream_si32(&writeArray[refArray[n]], readArray[n]); } </code></pre> <p>Because I don't need to read values of writeArray so there is no reason to pollute the cache with written values but this version is more more slower than other versions (6700% more slower than version 1).</p> <p>Why write miss is slower than read miss ? Why bypassing cache for writing is more slower than using it even if we don't read these written data after ?</p> |
17,049,558 | 0 | How do I convert a Web API JSON response to a data table? <p>I have a web API where if I go to a valid link, it'll display an XML.</p> <p>However, in my other application, when I call:</p> <pre><code>using (var webclient = new WebClient()) { var doc = webclient.DownloadString(url); } </code></pre> <p>It's returning JSON data.</p> <p>How do I convert this JSON to a data table? OR, should I "de-serialize" this JSON so that it becomes an XML and then I can work with the XML in order to convert it to a data table?</p> |
11,402,017 | 0 | <p>You could just use the type T directly for a simple getter and <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#cast%28java.lang.Object%29" rel="nofollow">Class.cast</a> -method for other types:</p> <pre><code>public class GenericDataTest { private static class DataTest<T> { private T value; public DataTest(T value) { this.value = value; } public T getValue() { return value; } public Object getValueAsType(Class<?> type) { return type.cast(value); } } @Test public void testGeneric() { DataTest<String> stringTest = new DataTest<String>("Test"); Assert.assertEquals("Test", stringTest.getValue()); Assert.assertEquals("Test", stringTest.getValueAsType(String.class)); DataTest<Double> doubleTest = new DataTest<Double>(1.0); Assert.assertEquals(1.0, doubleTest.getValue()); Assert.assertEquals(1.0, doubleTest.getValueAsType(Double.class)); } @Test(expected = ClassCastException.class) public void testClassCastFailure() { DataTest<String> stringTest = new DataTest<String>("Test"); Assert.assertEquals("Test", stringTest.getValueAsType(Float.class)); } } </code></pre> |
11,699,376 | 0 | Need to use asp.net mvc3 <p>I want to use ASP.net mvc3.I have VS 2010 installed and my OS is Windows XP SP3. Someone please suggest me what all things i need to install. so to run my application on VS 2010 and do i need to install Visual web developer 2010 express. Is it more useful than VS 2010. Please clarify.</p> |
23,044,966 | 0 | Program doesn't execute correctly <p>Sorry for all the long code...BUT...In order for me to work with my program and solve some issues, I need it to actually work. I'm working with a .html and .jsp files to insert data to MYSQL database. Can anybody tell me why I get this: This page cannot be display, make sure address http: //localhost:8081 is correct... ??? Please help, thanks!</p> <pre><code><!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Help Desk Ticket System</title> </head> <body> <script language ="JAVASCRIPT"> function check(form) { if(form.equipment.value =="") { alert("Please enter equipment type") form.equipment.focus() return false } if(form.problem.value =="") { alert("Please enter a description before hitting submit") form.problem.focus() return false } if(form.empid.value =="") { alert("Please enter employee ID.") form.empid.focus() return false } if(form.empfname.value =="") { alert("Please enter a first name.") form.empfname.focus() return false } if(form.emplname.value =="") { alert("Please enter a last name.") form.emplname.focus() return false } if(form.empemail.value =="") { alert("Please enter your email") form.empemail.focus() return false } if(form.empphone.value =="") { alert("Please enter a your phone number.") form.empphone.focus() return false } if(form.empcellphone.value =="") { value = "n/a" } selected = form.empdept.selectedIndex if (selected<=0) { alert("Please choose the department") form.empdept.focus() return false } selected = form.technician.selectedIndex if (selected<=0) { alert("Please choose a technician") form.technician.focus() return false } alert("Your ticket has been created.") return true } </script> <FORM method="post" action="http://localhost:8081/finalproject/help.jsp" onsubmit="return check(this)"> <h2> Please fill out the following details for your ticket </h2> <br/> Equipment: <input type="text" name="equipment" /><br/> <br/> Description of the problem: <br/> <textarea name="problem" rows="4" cols="50"></textarea><br/> <br/> <hr> <br/> Employee ID: <input type = "text" name="empid" /><br/> Employee First name: <input type = "text" name="empfname" /><br/> Employee Last name: <input type = "text" name="emplname" /><br/> Employee email: <input type = "text" name="empemail" /><br/> employee Phone: <input type = "text" name="empphone" /><br/> employee cell Phone: <input type = "text" name="empcellphone" /><br/> <br/> Employee Department: <br/> <select name = "empdept"> <option> Please select the department</option> <option>Marketing</option> <option>Human Resources</option> <option>Operations</option> <option>Legal</option> <option>Accounting</option> <option>Production</option> </select> <hr> <br/> Choose Technician: <select name ="technician"> <option value="0">Select</option> <option value="12345">Sierra: Applications </option> <option value="12344">Michael: Network</option> <option value="12343">Greg: Phones</option> <option value="12342">Aaron: Hardware</option> <option value="12341">Phil: Database </option> </select><br/> <br/> <br/> <button type="submit">Submit</button> <button type="reset" value="Clear Form">Reset</button> </form> </body> </html> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <%@ page import="java.sql.*" %> <%@ page import="java.util.Random" %> <% Connection conn = null; Statement st = null; ResultSet rs = null; //Random rand = new Random(); //int randomnumber = rand.nextInt(90000) + 10000; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://localhost/helpdesk?user=root&password=password"); st = conn.createStatement(); //String ticket = request.getParameter("ticketid"); String a = request.getParameter("equipment"); String b = request.getParameter("problem"); String c = request.getParameter("empid"); String d = request.getParameter("empfnname"); String e = request.getParameter("emplname"); String f = request.getParameter("empemail"); String g = request.getParameter("empphone"); String h = request.getParameter("empcellphone"); String i = request.getParameter("department"); String j = request.getParameter("technician"); String jointables = ("Select tech_id from technician inner join ticket on technician.tech_id = ticket.tech_id;"); String insert1 = ("insert into ticket (t_date,t_equpipment, t_descript,emp_id,tech_id)" + " values( NOW(),'"+a+"', '"+b+"', '"+c+"', '"+j+"')"); String insert2 = ("insert into employee (emp_id, emp_fname,emp_lname,emp_email, emp_phone,emp_cellphone,emp_dept)" + "values ('"+ c +"','" + d + "','" + e + "','" + f + "','" + g + "','"+ h +"','" + i + "')"); String intodatabase = insert1 + insert2; out.println("<b>Executed the following SQL statement:</b><br>"); out.println(intodatabase); //print out the actual sql statement that was generated //Execute the "insert into" sql statement st.executeUpdate(intodatabase); out.println ("<br><br><b>Successfully Added the tuple..</b>"); } catch (java.sql.SQLException ex) { out.println("<br><b>Ouch, an SQLException was thrown..</b>"); ex.printStackTrace(); } finally { if (rs != null) rs.close(); if (st != null) st.close(); if (conn != null) conn.close(); } %> </body> </html> </code></pre> |
5,003,402 | 0 | <p>As far as I see from their page, EDG do not provide a full compiler, but <a href="http://www.edg.com/index.php?location=faq_q1_whatsell" rel="nofollow">only a front-end</a>; it does not include neither an optimizer/code generator neither a standard library. You simply cannot use just EDG to produce an executable.</p> <p>You can find several free implementations of the C++ standard library (e.g. <a href="http://gcc.gnu.org/libstdc++/" rel="nofollow">libstdc++</a> from GNU, to which I suppose you should add <a href="http://www.gnu.org/s/libc/" rel="nofollow">glibc</a> for the C library subset), but without at least a code-generator backend all you can get from the front-end is the AST of the code gave in input.</p> <p>Moreover, EDG C++ it's not free, neither it is sold to individuals; EDG license only the source code and <a href="http://www.edg.com/index.php?location=faq_q2_cost" rel="nofollow">only to corporations</a> for a 40K$-250K$ price range. The links you're asking in your question would be illegal.</p> <p>If you just need a compiler for Windows, there are several great alternatives, both free and not-free, some are listed e.g. in <a href="http://stackoverflow.com/questions/1154517/c-compiler-for-windows">this question</a>.</p> |
4,291,769 | 0 | How do I notify a MATLAB object of an event in a Java object? <p>For simplicity, say I have a Java object which generates a random number at randomly spaced time intervals. I wish to have a MATLAB object notified every time one of these random numbers is generated (so that the MATLAB object can then perform some task on the data).</p> <p>How can I implement something like this? How can I have the Java object notify a MATLAB object that something has happened?</p> <p>P.S. I am a strong programmer in MATLAB but fairly new to Java.</p> |
5,738,394 | 0 | <p>As far as I understand, this attribute will give you some control over what names the elements will have in the final xml string, after the DataContractSerializer has done its work serializing your collection.</p> <p>This can be useful when you have to parse the result later manualy( in other words you will know what element to look for in that xml text, to find your collection and its parts).</p> <p>Take a look at this for examples and more info:</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa347850.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa347850.aspx</a></p> |
37,622,539 | 0 | <p>This seems to be a problem on Ubuntu (perhaps other Debian-based distros) with the Java CACerts keystore. For some reason this does not always include the full list of entries.</p> <p>To solve this, try the following:</p> <ul> <li><p>Delete the cacerts file</p> <p><code>sudo rm /etc/ssl/certs/java/cacerts</code></p></li> <li><p>Re-build the cacerts file using the dpkg postinstall script:</p> <p><code>sudo /var/lib/dpkg/info/ca-certificates-java.postinst configure</code></p></li> </ul> <p>This should re-generate the cacerts file and the problem should be resolved.</p> |
38,874,661 | 0 | How to append Json.obj into Json.arr Scala? <p>I am newbie to <strong>Scala</strong>.</p> <p>I want to append <strong>Json.obj</strong> into <strong>Json.arr</strong> during runtime in Scala. </p> <p><strong>Json Object:</strong> </p> <pre><code>var x: JsValue = Json.obj("name" -> "Fiver", "age" -> 4,"role" -> JsNull) </code></pre> <p><strong>Json Array:</strong></p> <pre><code>var y: JsValue = Json.arr(x) </code></pre> <p>Here, I am able to append single Json.obj to Json.arr but I want to add multiple Json.obj to Json.arr dynamically.</p> <p>I can do like this:</p> <pre><code>var y: JsValue = Json.arr( Json.obj("name" -> "Fiver", "age" -> 4,"role" -> JsNull), Json.obj("name" -> "Fiver", "age" -> 4,"role" -> JsNull) ) </code></pre> <p>but it is <strong>not</strong> appending in one by one. I want to append <strong>Json.Obj</strong> dynamically.</p> |
12,426,435 | 0 | <ol> <li><p>The <code>POST</code> test is used as a differentiator.</p> <p>When the view is called with <code>GET</code>, the form is rendered. The form specifies that it needs to be submitted with using <code>POST</code>, so the code assumes that a <code>POST</code> request signals the form is submitted.</p></li> <li><p>The <code>objects</code> attribute triggers the actual database query. By adding the <code>.filter()</code> call you specify a more specific database query, one where the <code>name</code> attribute contains the value of <code>f.cleaned_data['text']</code>. The result is a set of database results that match that query.</p></li> <li><p>the <code>specialPages</code> dictionary values are themselves views, and for these to work, you call them with the <code>request</code> parameter. Just like the <code>view_page</code> view callable itself.</p></li> </ol> |
14,674,078 | 0 | <ol> <li><p>It is logging the number 5 because there is 5 keys in each of your dictionaries (<code>console</code>, <code>game</code>, <code>id</code>, <code>model</code>, <code>publisher</code>). If instead of logging the <code>[consoleDictionary count]</code> you simply add one to an <code>int</code> counter each time, you would get the expected result in your counter at the end.</p></li> <li><p>You can obtain the number of objects is a much more easier way: <code>[self arrayFromJSON]</code> is an array</p></li> </ol> <p>Typically:</p> <pre><code>NSInteger nbPS3 = [[self arrayFromJSON] indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) { return [obj[@"model"] isEqualToString:@"PlayStation 3"]; }].count </code></pre> |
8,504,787 | 0 | <p>It depends what plugins you have bound to the phases up to and including compile. M2E should cope with the default plugins (maven-compiler-plugin, maven-resources-plugin) etc. Do you have some code-generation (JAXB etc.) plugins included?</p> <p><strong>EDIT</strong></p> <p>I've had no end of problems with m2e and code generation; eventually I reverted to m2eclipse which is still quite buggy.</p> <p>I recommend you move your cxf wsdl generation to a different module of the same project and then add it as a dependency. Keep that project <em>closed</em> in Eclipse (once you've <code>mvn install</code>'d it) unless you're editing it.</p> <p>Hopefully that kind of workaround will become unnecessary as m2e improves.</p> |
2,154,815 | 0 | <p>One option would be to set the page the users sees upon login and add a custom module to that page. That would get you out of writing an authentication provider.</p> |
16,235,779 | 0 | Admob Banner Ad not displaying in Android <p>Hi I have a Android game app developed using android cocos2d i need to integrate admob i have included the following code but banner ad is not displaying please help regarding this your answers will be appreciated and it would be a great help. thank you.</p> <pre><code>public class MainActivity extends Activity { private CCGLSurfaceView mGLSurfaceView; private boolean isCreated = false; public static FrameLayout m_rootLayout; AdView adView; // This is used to display Toast messages and is not necessary for your app @Override protected void onCreate(Bundle savedInstanceState) { if (!isCreated) { isCreated = true; } else { return; } super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); try{ LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams( getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight()+getWindowManager().getDefaultDisplay().getHeight()-50); adView = new AdView(this, AdSize.BANNER, "admob id"); AdRequest request = new AdRequest(); adView.loadAd(request); // Adding full screen container addContentView(adView, adParams); }catch (Exception e) { FlurryAgent.logEvent("ADMOB ERROR: "+e); } mGLSurfaceView = new CCGLSurfaceView(this); setContentView(mGLSurfaceView); CCDirector.sharedDirector().attachInView(mGLSurfaceView); getScaledCoordinate(); Global.assetManager = getAssets(); Global.context = this; Global.loadUserInfo(); CCScene scene = CCScene.node(); scene.addChild(new SplashScene(), -1); CCDirector.sharedDirector().runWithScene(scene); //-------------IAP----------------------- Log.d(TAG1, "Creating IAB helper."); mHelper = new IabHelper(this, base64EncodedPublicKey); mHelper.enableDebugLogging(true); Log.d(TAG1, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. complain("Problem setting up in-app billing: " + result); return; } // Hooray, IAB is fully set up. Now, let's get an inventory of stuff we own. Log.d(TAG, "Setup successful. Querying inventory."); mHelper.queryInventoryAsync(mGotInventoryListener); } }); Global.myActivity=this; } </code></pre> <p>manifest </p> <pre><code><?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.game.puzzlegame" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="com.android.vending.BILLING" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.game.puzzlegame.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.revmob.ads.fullscreen.FullscreenActivity" android:configChanges="keyboardHidden|orientation" > </activity> <activity android:name="com.google.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"></activity> </application> </code></pre> <p></p> |
26,327,717 | 0 | Rails 4 Devise, Pundit, Join Table ActionView::Template::Error (undefined method `task_definition_path' for #<#<Class:0x37682f95>:0x6919b2b2>): <p>Here is my use case:</p> <ol> <li>I have one user model with Devise for AuthN and I am using Pundit for AuthZ. </li> <li>I restrict access to the main application through a subdomain constraint. </li> <li>I have some pages that are for end users (will be a different LandF at some point) and I have administrative pages etc. Common story you know the drill. </li> <li>I am using a has_and_belongs_to_many utilizing a join table with :id's</li> <li>I have my controllers, view directories and migrations named as plurals, my models as singular. Example: TaskDefinition => Model, TaskDefinitions => Controller and Tables. </li> <li>The default routes are generated and i have provided the content. </li> <li>I am using partials in the view directories and this is very new issue since a port from Ruby to JRuby.</li> </ol> <p>Stack Trace:</p> <pre><code>ActionView::Template::Error (undefined method `task_definition_path' for #<#<Class:0x37682f95>:0x6919b2b2>): 10: <div class="col-md-10"> 11: <div class="panel-body"> 12: <div class="form"> 13: <%= bootstrap_form_for @task do |f| %> 14: <div class="form-group"> 15: <%= render '/admin/task_definitions/errors' %> 16: </div> app/views/admin/task_definitions/edit.html.erb:13:in`_app_views_admin_task_definitions_edit_html_erb__1276994696_33458' </code></pre> <p>Migrations:</p> <pre><code>class CreateTaskDefinitions < ActiveRecord::Migration def change create_table :task_definitions do |t| # foreign key t.integer :organization_id # attributes .... t.timestamps end # index add_index :task_definitions, :name, unique: true end end class CreateOrganizations < ActiveRecord::Migration def change create_table :organizations do |t| # for the relationship between parent orgs and child nodes t.references :parent # Used to determine Parent or Child t.string :org_type # Subdomain used for scoping site t.string :subdomain # Common fields .... t.timestamps end # index add_index :organizations, [:name, :subdomain], unique: true end end class CreateOrganizationsTaskDefinitions < ActiveRecord::Migration def change create_table :organizations_task_definitions, id: false do |t| t.integer :organization_id t.integer :task_definition_id end add_index :organizations_task_definitions, [:organization_id, :task_definition_id], name: 'index_organizations_task_definitions' end end </code></pre> <p>models:</p> <pre><code>class Organization < ActiveRecord::Base #associations has_many :users, class_name: 'User', inverse_of: :organization has_and_belongs_to_many :task_definitions, class_name: 'TaskDefinition', inverse_of: :organizations has_one :address, class_name: 'Address' has_many :children, class_name: 'Organization', foreign_key: 'parent_id' belongs_to :parent, class_name: 'Organization' accepts_nested_attributes_for :address end class TaskDefinition < ActiveRecord::Base #associations has_many :steps, class_name: 'TaskStep', inverse_of: :task_definition has_and_belongs_to_many :organizations, class_name: 'Organization', inverse_of: :task_definitions has_and_belongs_to_many :task_events, class_name: 'TaskEvent', inverse_of: :task_definitions accepts_nested_attributes_for :steps end </code></pre> <p>Controller:</p> <pre><code>class Admin::TaskDefinitionsController < ApplicationController before_filter :authenticate_user! after_action :verify_authorized ..... def edit @tasks = current_organization.task_definitions if(@tasks.size > 0 ) @task = @tasks.find(params[:id]) authorize @task # add breadcrumb add_breadcrumb @task.name, admin_task_definition_path(@task) unless current_user.org_super_admin? or current_user.finch_admin? unless @user == current_user redirect_to :back, :alert => "Access denied." end end end end end </code></pre> <p>Routes: </p> <pre><code>Rails.application.routes.draw do ...... constraints(Finch::Constraints::SubdomainRequired) do # # dashboards # resource :dash_boards, only: [:index, :show, :edit, :update, :destroy] # # orgss # resource :organizations, only: [:index, :show, :edit, :update, :destroy] # # Only Admins are allowed to access # namespace :admin do # # Workflow Data # resources :task_definitions, only: [:index, :show, :edit, :update, :destroy] resources :task_steps, only: [:show, :edit, :update, :destroy] resource :task_actions, only: [:show, :edit, :update, :destroy] resource :task_action_attributes, only: [:show, :edit, :update, :destroy] resource :task_transitions, only: [:show, :edit, :update, :destroy] end end end </code></pre> <p>view: </p> <pre><code> <div class="form"> <%= bootstrap_form_for @task do |f| %> <div class="form-group"> <%= render '/admin/task_definitions/errors' %> </div> </code></pre> <p>rake routes:</p> <pre><code> edit_organizations GET /organizations/edit(.:format) organizations#edit organizations GET /organizations(.:format) organizations#show PATCH /organizations(.:format) organizations#update PUT /organizations(.:format) organizations#update DELETE /organizations(.:format) organizations#destroy admin_task_definitions GET /admin/task_definitions(.:format) admin/task_definitions#index edit_admin_task_definition GET /admin/task_definitions/:id/edit(.:format) admin/task_definitions#edit admin_task_definition GET /admin/task_definitions/:id(.:format) admin/task_definitions#show </code></pre> |
12,828,306 | 0 | <p>You should use percent encoding to escape characters in your query string, see <a href="http://tools.ietf.org/html/rfc3986" rel="nofollow">RFC 3986</a>. This <a href="http://stackoverflow.com/questions/5366007/why-does-the-encodings-of-a-url-and-the-query-string-part-differ">previous StackOverflow post</a> contains some useful background information about URI encoding.</p> <blockquote> <p>Initially my main concern was fields that contained parentheses. I will be converting this query into a SQL server query and I need a way to ensure that I do not confuse a parentheses in a field value with one that is intended for grouping</p> </blockquote> <p>If this might be a problem then it sounds like your application will be susceptible to SQL injection. You should be escaping any external data before constructing an SQL query.</p> <blockquote> <p>/api/companies?q=(CompanyName eq Microsoft Or CompanyName eq Apple) And State eq California</p> </blockquote> <p>Based on this example you could take advantage of the URI query string to better represent your query:</p> <pre><code>/api/companies?CompanyName=Microsoft%20OR%20Apple&State=California </code></pre> |
22,646,658 | 0 | Why select_tag displays only one column? <p>I have the following <strong>select_tag</strong> in my view:</p> <pre><code> <%= select_tag :users, options_from_collection_for_select(@users, 'id','firstname' , 'lastname') %></p></br> </code></pre> <p>I want to display the firstname and lastname in the select_tag, but it always displays the first parameter after the <strong>'id'</strong> in this case the firstname. </p> <p>What I'm doing wrong?</p> |
5,759,704 | 0 | <p>You use the <a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow"><code>data</code></a> parameter in the options hash:</p> <blockquote> <p>Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).</p> </blockquote> <p>For example:</p> <pre><code>$.ajax({ url: '/pancakes/house', data: { 'where': [ 'is' ] }, // ... }); </code></pre> |
20,803,245 | 0 | How to write and read (including spaces) from text file <p>I'm using <code>fscanf</code> and <code>fprintf</code>.</p> <p>I tried to delimit the strings on each line by <code>\t</code> and to read it like so:</p> <pre><code>fscanf(fp,"%d\t%s\t%s",&t->num,&t->string1,&t->string2); </code></pre> <p>The file contents:</p> <pre><code>1[TAB]string1[TAB]some string[NEWLINE] </code></pre> <p>It does not read properly. If I <code>printf("%d %s %s",t->num,t->string1,t->string2)</code> I get:</p> <pre><code>1 string1 some </code></pre> <p>Also I get this compile warning:</p> <pre><code>warning: format specifies type 'char *' but the argument has type 'char (*)[15]' [-Wformat] </code></pre> <p>How can I fix this without using binary r/w?</p> |
7,408,363 | 0 | Difficult SQL-Query <p>i have 2 tables i.e. table 1 calls game and table 2 calls game_medias</p> <p>structure table 1 (game)</p> <pre><code>-id -genre_id -title -created </code></pre> <p>etc.</p> <p>structure table 2 (game_medias)</p> <pre><code>-id -game_id -thumb </code></pre> <p>etc</p> <p>example query:</p> <pre><code>select g.id,g.genre_id,g.title, gm.* from games g inner join game_medias as gm group by rand(g.id) limit 8; </code></pre> <p>is it possible to make a query with a extra like " where g.id = '2' " - get the genre_id from it and get into the random 8 only "items" with this genre_id ? i'm not sure if the join is the right solution - maybe someone knows a better way?</p> <p>regards</p> |
26,239,339 | 0 | Strict f77 compiler <p>I am new to fortran programming + compiling. I am trying to compile an old f77 code. I compiled it using gfortran and ran the executable but I got the following error message:</p> <pre><code>Program received signal SIGBUS: Access to an undefined portion of a memory object. Backtrace for this error: #0 0x103e40e62 #1 0x103e4162e #2 0x7fff8ace0cf9 #3 0x103a50e85 #4 0x103a54374 #5 0x103a4e095 #6 0x103a4b935 #7 0x103a4c19d Bus error: 10 </code></pre> <p>I spoke to the creator of the code and he mentioned that he used a f77 compiler. Does anyone know where I can get a f77 compiler? I am using Mac OS 10.7.5 (Lion). Or is this an error anyone recognizes? I am new to fortran compiling, so I may need detailed help. Thanks!</p> |
34,704,562 | 0 | <p>Not to be marked as correct, just expanding on the above answer. Since all phantomjs wrappers (like <a href="https://github.com/peerigon/phridge" rel="nofollow">phridge</a> and <a href="https://github.com/sgentle/phantomjs-node" rel="nofollow">phantomjs-node</a>) basically spawn a new phantomjs process, the result should be the same when run from a nodejs context.</p> <p><strong>phatomjs-webfonts.html:</strong></p> <pre><code><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PhantomJS WebFontsTest</title> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js"></script> <script> WebFont.load({ google: { families: ['Droid Sans', 'Droid Serif'] }, loading: function(){ console.log('WebFonts loading'); }, active: function(){ console.log('WebFonts active'); }, inactive: function(){ console.log('WebFonts inactive'); } }); </script> </body> </html> </code></pre> <p><strong>phantomjs-webfonts.js:</strong></p> <pre><code>var page = require('webpage').create(); page.settings.userAgent = 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36'; page.onConsoleMessage = function(msg, lineNum, sourceId) { console.log('Console: ' + msg); }; page.open('http://<server-address>/phantomjs-webfonts.html', function(status) { console.log("Loading status: " + status); }); </code></pre> <p><strong>Command:</strong></p> <pre><code>phantomjs phantomjs-webfonts.js </code></pre> <p><strong>Output</strong>:</p> <pre class="lang-none prettyprint-override"><code>Console: WebFonts loading Console: WebFonts active Loading status: success </code></pre> |
33,907,030 | 0 | <p>From the information given - assuming "Schedule.java" is just a POJO and not an activity - one way is to create a "Schedule" object in your ActivityMain class, so you can pull "Music" from the schedule array and update your text view. Make sure the schedule array has more private accessibility, or you can write getters in Schedule.java to return the relevant strings.</p> |
7,058,223 | 0 | opengl - point sprites rendering problem <p>I'm trying to render point sprites but I get points. Where is the problem ? (changing a color via glUniform3f works)</p> <p>Vertex shader:</p> <pre><code>private static String vertexShader = "#version 330" + "\n" + "layout (location = 0) in vec4 position;" + "\n" + "uniform mat4 pMatrix;" + "\n" + "uniform mat4 mMatrix;" + "\n" + "void main()" + "\n" + "{" + "\n" + "gl_Position = pMatrix * mMatrix * position;" + "\n" + "}"; </code></pre> <p>Fragment shader:</p> <pre><code>private static String fragmentShader = "#version 330" + "\n" + "out vec4 vFragColor;" + "\n" + "uniform vec3 Color;" + "\n" + "uniform vec3 lightDir;" + "\n" + "void main()" + "\n" + "{" + "\n" + "vec3 N;" + "\n" + "N.xy = gl_PointCoord* 2.0 - vec2(1.0);" + "\n" + "float mag = dot(N.xy, N.xy);" + "\n" + "if (mag > 1.0) discard;" + "\n" + "N.z = sqrt(1.0-mag);" + "\n" + "float diffuse = max(0.0, dot(lightDir, N));" + "\n" + "vFragColor = vec4(Color,1) * diffuse;" + "\n" + "}"; </code></pre> <p>Rendering:</p> <pre><code>gl.glUseProgram(shaderProgramID); gl.glUniformMatrix4fv(projectionMatrixUniform, 1, false, projectionMatrix, 0); gl.glUniformMatrix4fv(modelViewMatrixUniform, 1, false, modelViewMatrix, 0); gl.glUniform3f(colorUniform, 1.0f, 0.0f, 0.0f); gl.glUniform3f(lightDirUniform, 0.0f, 0.0f, 1.0f); gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, vbo[0]); gl.glEnableVertexAttribArray(0); gl.glVertexAttribPointer(0, 4, GL3.GL_FLOAT, false, 0, 0); gl.glDrawArrays(GL3.GL_POINTS, 0, n_particles); gl.glDisableVertexAttribArray(0); gl.glUseProgram(0); </code></pre> |
18,574,204 | 0 | <p>Use a <code>case</code>. Generally you can do</p> <pre><code>SELECT records.some_id FROM forms LEFT OUTER JOIN records ON forms.form_id = records.form_id ORDER BY case when records.some_id is not null then 1 else 2 end, records.some_id </code></pre> <p>and specifically in MySQL you can also do</p> <pre><code>SELECT records.some_id FROM forms LEFT OUTER JOIN records ON forms.form_id = records.form_id ORDER BY records.some_id is not null, records.some_id </code></pre> |
6,951,671 | 0 | <pre><code>begin ISOLATION LEVEL READ UNCOMMITTED; insert into "TB" ("Title") values ('111'); insert into "TB" ("Title") values ('111'); insert into "TB" ("Title") values ('111'); commit; </code></pre> <p>it's possible too</p> |
38,313,672 | 0 | <p>Alright we've found the answer: we had 2 credentials and apparently used the wrong one in our APK. We switched around the Signing-certificate fingerprint so that the fingerprint in the APK and in play services match and now it's working.</p> <p>The strange thing is that everything seemed to work and we've never gotten any feedback from google that something was wrong...</p> <p>Thanks for your attention to this problem!</p> |
30,888,940 | 0 | <p>Open the <a href="https://soundcloud.com/aviciiofficial/preview-avicii-vs-lenny" rel="nofollow">https://soundcloud.com/aviciiofficial/preview-avicii-vs-lenny</a> link in browser and in page there is a share button, click it and popup will load and in there click embed tab and copy the code</p> <p>use</p> <pre><code><iframe width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/41395010&amp;auto_play=false&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;visual=true"></iframe> </code></pre> |
2,108,157 | 0 | iphone and bluetooth device <p>could i connect my nokia phone to iphone using the following Object..?</p> <p>1)GKPeerPickerController 2)GKSession</p> <p>i mean (GameKit)</p> <p>note that here not two iPhone but it is one iPhone other one is only one Bluetooth device..</p> <p>thanks and regards jalju</p> |
20,855,544 | 0 | unnecessary movements in my a-star implementation <p>I've made an a-star implementation with euclidean heuristics, and it works, but makes unnecessary movements in some situations. </p> <p>Here is the screenshot: <a href="http://clip2net.com/s/6v2iU4" rel="nofollow">http://clip2net.com/s/6v2iU4</a></p> <p>Path starts on the blue circle and, in theory, cell to the right of it has less F (movement cost + heuristic cost), so a-star takes it first, but it ends up in building not the shortest path.</p> <p>How can i fix this? Or a-star is supposed to work this way and i dont need to do anything?</p> <p>My code: <a href="http://pastebin.com/02u33jY6" rel="nofollow">http://pastebin.com/02u33jY6</a> (h + cpp)</p> |
40,984,308 | 0 | <p>You used the [typescript] tag here, so I am going to assume you are using typescript.</p> <p>Make this a 1-way street. Kill off the circular dependency. I would probably move this into 1 file, but you can still split it up like this.</p> <p><strong>a.ts</strong> (just an interface)</p> <pre><code>export interface A { name: string; new (name: string); } </code></pre> <p><strong>b.ts</strong> (implementation)</p> <pre><code>import { A } from 'a'; export class B implements A { /*...*/ } </code></pre> |
15,376,218 | 0 | <p>Don't worry about it, and just specify the precision you want in your printing:</p> <pre><code>>>> print('{:.4f}'.format(34.73809999999999)) 34.7381 </code></pre> |
1,532,209 | 0 | <p>It is not possible to get the expiration date of a cookie through Javascript; only key-value pairs are exposed through <code>document.cookie</code>.</p> |
39,376,780 | 0 | <p>I'm not sure whether this code is what you wanted to get, but i hope you would find it useful anyway. Mean squared error is actually decreasing along the iterations, though I haven't tested it for making predictions, so it's up to you!</p> <pre><code>import tensorflow as tf import numpy as np from random import randint flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer('batch_size', 50, 'Batch size.') flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.') flags.DEFINE_integer('dim1', 3, 'layer size') flags.DEFINE_integer('training_epochs', 10, 'Number of passes through the main training loop') flag.DEFINE_integer('num_iters', 100, 'Number of iterations') def ezString(list): #debugging code so I can see what is going on listLength = len(list) r = '' for i in range(listLength): value = list[i] valueString = str(value) r = r + ' ' r = r + valueString return r def generateTrial(): inputs = np.zeros(2, dtype = np.float) for i in range(2): inputs[i] = randint(0, 1) unknownInput = randint(0, 1) um = 0 for j in range(2): sum = sum + inputs[j] sum = sum + unknownInput inputTensor = np.asarray(inputs) return inputTensor, sum def printTensor(tensor): sh = tensor.get_shape() print(sh) def placeholder_inputs(size): output_placeholder = tf.placeholder(tf.float32, shape=(size)) input_placeholder = tf.placeholder(tf.float32, shape=(size, 2)) return input_placeholder, output_placeholder def fill_feed_dict(inputs_pl, output_pl): inputs = [] outputs = [] for i in range(FLAGS.batch_size): input, output = generateTrial() inputs.append(input) outputs.append(output) return {inputs_pl: inputs, output_pl: outputs} def loss(y, pred): return tf.reduce_mean(tf.pow(y - pred, 2)) def NN(x, y, W1, b1, W2, b2): layer1 = tf.add(tf.matmul(x, W1), b1) layer1 = tf.nn.relu(layer1) output = tf.add(tf.matmul(layer1, W2), b2) return output, loss(y, output) def get_params(dim_hidden): with tf.variable_scope('nn_params'): return tf.Variable(tf.truncated_normal([2, dim_hidden], stddev = 0.05)), tf.Variable(0.0, (dim_hidden)),\ tf.Variable(tf.truncated_normal([dim_hidden, 1], stddev = 0.05)), tf.Variable(0.0, 1) def run_training(): input_placeholder, output_placeholder = placeholder_inputs(FLAGS.batch_size) W1, b1, W2, b2 = get_params(FLAGS.dim1) pred, loss = NN(input_placeholder, output_placeholder, W1, b1, W2, b2) optm = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(loss) init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) for iters in range(FLAGS.num_iters): l, _ = sess.run([loss, optm], feed_dict = fill_feed_dict(input_placeholder, output_placeholder)) print l, iters + 1 </code></pre> |
21,138,366 | 0 | How to create two independent branches in Mercurial? <p>We are using Mercurial to manage a project A, which links to an old version of external system.</p> <p>A new version of this external system is now available and I now want to create second version B of the same project to work with this.</p> <p>Although both versions will share much of their code, I do not want changes to one project to affect that for the other project. I want to change the code base of each independently.</p> <p>How can I deal with this please?</p> <p>One way would be to put project B in a new repository, but this would lose the history of previous code. Is there a way to retain the history?</p> <p>Though I would have preferred a single code base, it is too difficult to add conditional statements to separate these.</p> |
6,667,348 | 0 | <blockquote> <p>Is it good I a idea to use command line instead of GUI?</p> </blockquote> <p>Yes.</p> <blockquote> <p>And is it normal to compare every file I modified to the old ones with WinMerge after every time I modified them?</p> </blockquote> <p>Yes.</p> <p>Also. Buy this: <a href="http://www.syncrosvnclient.com/" rel="nofollow">http://www.syncrosvnclient.com/</a></p> |
6,977,652 | 0 | <p>both are the same, there is no difference.</p> |
40,632,428 | 0 | How to add subscribers ( my clients ) to my shiny dashboard ? <p>I am a Data Scientist. Our team is busy in making Analytics Platform based on shiny application which we shall use for commercial purpose. Our company is Analytics Product development company. The idea is, the willing client needs to sign up in our platform first time and he has to choose the subscription plan and pay. Then it is just plug and play. Whenever he wishes, he will login and use our platform.</p> <p>For this, we need to do the following things in our shiny platform:</p> <ol> <li>User Login, 2. User Registration, 3. User Profiling, 4. User Subscription, 5. Payment gateway for users & 6. Data base connectivity where we can store client's data.</li> </ol> <p>Please confirm me, whether shiny provides the above mentioned solutions.</p> |
4,041,826 | 0 | <p>You must use the Double.IsInfinity() and Double.IsNaN() methods.</p> <pre><code>if (Double.IsInfinity(SampleInterval)) { //TODO } if (Double.IsNaN(SampleInterval)) { //TODO } </code></pre> <p>Don't compare directly to Double.NaN, it will always return false.</p> |
8,292,499 | 0 | <p>Your proof isn't valid, and the reason for that is that there are many imprecise statements in your proof, and some falsehoods. For example you say that "the definition of a MST states that we must find the minimum path from a root to all verticies", whereas the definition of an MST is that it is the spanning tree of minimum weight.</p> <p>You use the fact that a "vertex that has the least edge" must be in the MST, but it's hard to see the relevance because <em>every</em> vertex appears in the MST (from the definition of spanning tree).</p> <p>The skill in writing proofs is to be extremely precise in your language, and to make logical steps that follow from things you prove (or if you're applying a well-known theorem, then a good citation). It's extremely important that you know and use the exact definitions of jargon you are using (here, perhaps, "minimal" and "spanning" and "tree").</p> <p>For this proof, as Keith says, you want to try a proof by contradiction. That is that if there is a spanning tree that doesn't contain the edge of minimal weight then you can find a spanning tree with a lower weight. Perhaps it would help to prove first how many edges a spanning tree must have, and whether every tree in the graph with that number of edges has to be a spanning tree. You should be clear what the definition of a tree is too as it will be needed in the proof: you'll take the spanning tree that doesn't contain the edge, modify it somehow, and show that it has lower weight and is still a spanning tree.</p> |
7,432,517 | 0 | <p>Jimmy is correct. Your endpoint is most likely pointing to the test instance.</p> |
19,613,180 | 0 | Apply color overlay to picture in HTML pages <p>I have a PNG picture representing a monochrome white magnifying glass with an alpha channel. This image is overlayed on the top of other pictures, with a semi-transparent background such that you still see below it:</p> <p><img src="https://i.stack.imgur.com/cbg5G.png" alt="Picture with a magnifying glass overlay"></p> <p>When you hover that picture, I would like it to change to red, as do textual links per my CSS.</p> <p>I have considered several options:</p> <ul> <li>Use a <a href="http://www.fileformat.info/info/unicode/char/1f50d/index.htm" rel="nofollow noreferrer"><code>'LEFT-POINTING MAGNIFYING GLASS' (U+1F50D)</code> character</a>. This wouldn't work for the (fewer and fewer) clients that don't support an extensive set of Unicode characters; but when it works, it's not guaranteed to produce a monochrome character (on Apple implementations, it's a full-color emoji).</li> <li>Use a mask, as <a href="http://stackoverflow.com/questions/7415872/change-color-of-png-image-via-css">described in this other similar question</a>. This only works when you don't mind an opaque background (mine is <strong>not</strong> opaque) or when you can tell what's underneath your element with great certainty (and then it's rather hackish and ugly).</li> </ul> <p>My current solution is to use a different picture to represent the white magnifying glass and the red magnifying glass that it changes for when you hover over the picture. It's an okay solution, but I was wondering if there was a way I could have just one picture of just one color, so that I don't have to go back to change the image color if I change my mind about the color.</p> <p>I'm already doing extensive use of CSS3 and HTML5, so I don't mind going deeper as long as it's supported by the latest iterations of each major browser.</p> |
17,313,558 | 1 | Form for multiple models <p>Suppose I have two models:</p> <pre><code>class Topic(models.Model): title = models.CharField() # other stuff class Post(models.Model): topic = models.ForeignKey(Topic) body = models.TextField() # other stuff </code></pre> <p>And I want to create a form contains two fields: <code>Topic.title</code> and <code>Post.body</code>. Of course, I can create the following form:</p> <pre><code>class TopicForm(Form): title = forms.CharField() body = forms.TextField() # and so on </code></pre> <p>But I don't want to duplicate code, since I already have <code>title</code> and <code>body</code> in models. I'm looking for something like this:</p> <pre><code>class TopicForm(MagicForm): class Meta: models = (Topic, Post) fields = { Topic: ('title', ), Post: ('body', ) } # and so on </code></pre> <p>Also, I want to use it in class based views. I mean, I would like to write view as:</p> <pre><code>class TopicCreate(CreateView): form_class = TopicForm # ... def form_valid(self, form): # some things before creating objects </code></pre> <p>As suggested in comments, I could use two forms. But I don't see any simple way to use two forms in my <code>TopicCreate</code> view - I should reimplement all methods belongs to getting form(at least).</p> <h2>So, my question is:</h2> <p>Is there something already implemented in Django for my requirements? Or is there a better(simpler) way?</p> <p><strong>or</strong></p> <p>Do you know a simple way with using two forms in class based view? If so, tell me, it could solve my issue too.</p> |
16,580,758 | 0 | mbstring.so and curl.so can't be loaded by PHP under Ubuntu <p>I download PHP source code to build and install it. </p> <p>But <strong>mbstring.so</strong> and <strong>curl.so</strong> can not be loaded by PHP.</p> <ol> <li>I've remove ; from php.ini</li> <li><strong>mbstring.so</strong> and <strong>curl.so</strong> exist in extension folder</li> <li>other extension files can be loaded. I've tested with <strong>gd.so</strong>. I remove ; before gd.so, it can be see in phpinfo, I add ;, gd.so is hidden in phpinfo.</li> </ol> <p>Anybody know why?</p> <p>PHP version is <strong>5.4.13</strong>.</p> |
23,800,700 | 0 | MySQL STR_TO_DATE() returns invalid date <p>Our website requires signing up. Lately it has become apparent that the signup process fails on many occasions. I implemented several logs in my PHP code to start tracking this. Including one to track outputs from mysql_last_error() when possible.</p> <p>My next step was to write a script that generates sign-up requests with random values for the different required fields. My logic was that if this yields an issue - the problem is with the back-end logic, and if it doesn't - the problem is with server loads. (BTW, was this sound logic?)</p> <p>When sending many of these (I'd say about 150) I got only three errors, and the mysql_last_error log showed this:</p> <ul> <li><p>[Wed May 21 13:20:45.000000 2014] Incorrect date value: '1964-11-31' for column 'dob' at row 1</p></li> <li><p>[Wed May 21 13:48:37.000000 2014] Incorrect date value: '1963-11-31' for column 'dob' at row 1</p></li> <li><p>[Wed May 21 13:48:37.000000 2014] Incorrect date value: '1967-02-29' for column 'dob' at row 1</p></li> </ul> <p>The request is sent in a JSON format, and its dob field is in mm/dd/yyyy format. The SQL in my PHP code subsequently looks like this:</p> <pre><code>"STR_TO_DATE('".$cleanUser['dob']."', '%m/%d/%Y')" </code></pre> <p>I tried performing this operation inside MySQL Workbench as well, to isolate it from possible bad code. but it failed there as well. I simply don't understand what's the problem, and why it occurs only on some dates.</p> <p>All help will be greatly appreciated, Thanks in Advance</p> |
37,303,993 | 0 | <p>There is mistake in the Parcelable implementation.</p> <p>First of all parcelable implementation states that: <strong>the fields passed in News(Parcel in) Constructor should be written in the same sequence in writeToParcel() method. Thats called Marshalling and Unmarshalling.</strong></p> <p><strong>Corrections:</strong></p> <ol> <li><p>Drawable cannot be passed a parameter in Parcelable.</p></li> <li><p>News Parcelable implementation.</p></li> </ol> <p>Missed some of the fields its just for your understanding.</p> <pre><code>public class News implements Parcelable { public static final String TAG = "model_news"; private JSONObject object; private int id; private String type; private String title; private Boolean comment_disabled; private String category_name; private String url; private Image images; private Date date; private Boolean is_video; protected News(Parcel in) { id = in.readInt(); type = in.readString(); title = in.readString(); category_name = in.readString(); url = in.readString(); } public static final Creator<News> CREATOR = new Creator<News>() { @Override public News createFromParcel(Parcel in) { return new News(in); } @Override public News[] newArray(int size) { return new News[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(type); dest.writeString(title); dest.writeString(category_name); dest.writeString(url); } } public class Image implements Parcelable { public static final String TAG = "model_image"; private JSONObject imageObj; private JSONObject original; private String source; private int width; private Drawable image; protected Image(Parcel in) { source = in.readString(); width = in.readInt(); } public static final Creator<Image> CREATOR = new Creator<Image>() { @Override public Image createFromParcel(Parcel in) { return new Image(in); } @Override public Image[] newArray(int size) { return new Image[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(source); dest.writeInt(width); } } </code></pre> |
39,458,263 | 0 | How to extend Laravel core class MessageBags <p>I need to extend <em>Illuminate\Support\MessageBag</em> because of add some help methods but <strong>I cant bind</strong> my own class App\Support\MyMessageBag to laravel use my class (that extends App\Support\MyMessageBag) instead of original core class.</p> <p>Do you have any ideas?</p> |