pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
35,730,089 | 0 | <p>Since OS X 10.10, <code>NSStatusItem</code> has <code>button</code> property, which is a regular <code>NSView</code>-based control that conforms to <code>NSAccessibility</code> protocol and which allows to change <code>accessibilityTitle</code> property directly.</p> <p>On earlier versions of OS X, you can implement a custom button that looks and behaves exactly like vanilla <code>NSStatusItem</code> and assign it to the item via <code>-[NSStatusItem setView:]</code> method, then use <code>-[NSView accessibilitySetOverrideValue:... forAttribute:NSAccessibilityTitleAttribute]</code> on your custom control to provide a voiceover title.</p> |
19,140,817 | 0 | Rails - ajax page partial update <p>I have my home.html.haml page rendering 3 partials:</p> <pre><code>%h1 Foo #foo1 = render partial: 'foo/foo', locals: {items: @foo1_items} #foo2 = render partial: 'foo/foo', locals: {items: @foo2_items} #foo3 = render partial: 'foo/foo', locals: {items: @foo3_items} </code></pre> <p>Currently, I have some remote links that refresh these parts individually firing an ajax call to to the home page:</p> <pre><code>= link_to 'refresh', home_path(mode: 'foo1'), remote:true = link_to 'refresh', home_path(mode: 'foo2'), remote:true = link_to 'refresh', home_path(mode: 'foo3'), remote:true </code></pre> <p>and I have a <strong>home.js.erb</strong> that contains something like this:</p> <pre><code><% if params[:mode] == 'foo1'%> $('#foo1').html('<%= j(render partial: 'foo/foo', locals: {items: @foo1_items}) %>') <% elsif params[:mode] == 'foo2'%> $('#foo2').html('<%= j(render partial: 'foo/foo', locals: {items: @foo2_items}) %>') <% else %> $('#foo3').html('<%= j(render partial: 'foo/foo', locals: {items: @foo3_items}) %>') <% end %> </code></pre> <p>I am wondering:</p> <ol> <li>if this is the default(suggested, best) Rails way to do a partial page refresh or generally the way to handle ajax requests?</li> <li>if it would be faster to have server respond with pure html and let the client (javascript) to do the replacing?</li> <li>how do you handle this in your application?</li> </ol> |
17,353,988 | 0 | <p>I would say that the real reason is that try-with-resources isn't so much new JVM feature as it is a compile-time language feature. In this way, it is very much analogous to the "enhanced for statement" which requires a class that has implemented the Iterable interface (you have to name an instance of the implenting class there, too). Try-with-resources requires that the resource implements the AutoCloseable interface. It is not wrong to regard the block as "syntactic sugar, introduced in 1.7". It just prevents you from having to deal with calls to the interface method yourself.</p> <p>Because the feature requires an object whose class has implemented the interface, you must give the try-with-resources block the name of that object.</p> |
37,860,516 | 0 | <p>If H:i:s is always two-digit, i.e. <code>14:05:15</code> then it will be ordered correctly.</p> <p>If it can contain one-digit in any part, i.e. <code>14:5:15</code>, then it will not be ordered correctly.</p> |
22,893,051 | 0 | <p>Like this</p> <pre><code>$(function() { $(window).on('resize', function() { $('.wrapper').css('margin-top', function() { return ($(document).height() - $(this).height()) / 2; }); }).trigger('resize'); }); </code></pre> <p><a href="http://jsfiddle.net/adeneo/sLVLt/2/" rel="nofollow"><strong>FIDDLE</strong></a></p> |
1,867,590 | 0 | <p>I've used Selector for the last couple years and found it perfectly stable. It's been at 0.8.11 for at least two years now. </p> <p>I would draw two conclusions from that: </p> <ol> <li><p>It could be basically unmaintained. If you find a bug in it or need a new feature, I wouldn't count on being able to get Luke Arno to jump up and fix it in a hurry (not saying he wouldn't, but I'm guessing that Selector isn't his main focus these days). Would you be comfortable maintaining a local fork in that case?</p></li> <li><p>It's pretty much complete. The problem that it's trying to solve is contained in scope. It's a very small library without much code. The bugs have been shaken out and there's really nothing left to do on it. I think this is the main reason it hasn't been updated in a long time. It's basically done.</p></li> </ol> <p>Open source developers, and Python developers in particular, have a long history of being very (probably overly) conservative about marking things as 1.0. The lack of unit tests can be a little off-putting, but again, it's a small library solving a problem with limited scope. The code is short and clear enough to read and convince yourself of its correctness.</p> |
6,514,430 | 0 | <p>According to <a href="http://stackoverflow.com/questions/1752701/how-to-convert-nsinteger-to-int">How to convert NSInteger to int</a>, <code>NSInteger</code> will always be at least 32 bits on every system/architecture, so yes, the answers to <a href="http://stackoverflow.com/questions/4738480/pass-two-integers-as-one-integer">Pass two integers as one integer</a> will work.</p> |
34,306,313 | 0 | <p>You are passing $request->all() directly to the create method, in which case your HTML field's name should be same as the column names in your DB</p> <pre><code><div class="form-group"> {!! Form::label('is_kids_friendly','Kids Friendly:') !!} {!! Form::radio('is_kids_friendly', 'true', null),'&nbsp', 'Yes' !!} {!! Form::radio('is_kids_friendly', 'false', null),'&nbsp','No' !!} </div> <div class="form-group"> {!! Form::label('is_kids_only','Kids Only:') !!} {!! Form::radio('is_kids_only', 'true', null),'&nbsp', 'Yes' !!} {!! Form::radio('is_kids_only', 'false', null),'&nbsp','No' !!} </div> <div class="form-group"> {!! Form::label('senior_citizen_friendly','Sineor Citizan Friendly:') !!} {!! Form::radio('senior_citizen_friendly', 'true', null),'&nbsp', 'Yes' !!} {!! Form::radio('senior_citizen_friendly', 'false', null),'&nbsp','No' !!} </div> </code></pre> |
34,686,180 | 0 | <p>The <code>finally</code> part is <em>always</em> executed before leaving the <code>try</code> block. <code>return 0</code> would leave the <code>try</code> block. So the <code>finally</code> part is executed first and returns 1.</p> <p><a href="https://docs.python.org/2/tutorial/errors.html#predefined-clean-up-actions" rel="nofollow">Documentation</a></p> |
2,993,423 | 0 | <p>You may want to trim the string first, to avoid leading and trailing hyphens.</p> <pre><code>function hyphenSpace(s){ s= (s.trim)? s.trim(): s.replace(/^\s+|\s+$/g,''); return s.split(/\s+/).join('-'); } </code></pre> |
18,673,292 | 0 | <p>Remove <code>position:absolute;</code> for the logo.</p> |
28,276,932 | 0 | <p>Yes. It is a good idea, with the correct set-up. You'll be running code as if it was a virtual machine.</p> <p>The Dockerfile configurations to create a build system is not polished and will not expand shell variables, so pre-installing applications may be a bit tedious. On the other hand after building your own image to create new users and working environment, it won't be necessary to build it again, plus you can mount your own file system with the -v parameter of the run command, so you can have the files you are going to need both in your host and container machine. It's versatile.</p> <pre><code>> sudo docker run -t -i -v /home/user_name/Workspace/project:/home/user_name/Workspace/myproject <container-ID> </code></pre> |
3,377,450 | 0 | <p>I found the solution here <a href="http://www.jamesnetherton.com/blog/2008/05/04/Converting-Unix-timestamp-values-in-ColdFusion/" rel="nofollow noreferrer">http://www.jamesnetherton.com/blog/2008/05/04/Converting-Unix-timestamp-values-in-ColdFusion/</a>. I needed to convert the start and end time in order to use in my sql query.</p> |
17,788,382 | 0 | <p>You could try something like this in PowerShell to check that the named computer is in the OU or not:</p> <p><strong>Script:</strong></p> <pre><code>import-module activedirectory $OU = @() $CheckOU = "LaptopOU" $computerName = "Laptop12345" $user = get-adcomputer $computerName -Properties * $user.DistinguishedName -split "," | %{If($_ -match "OU="){$OU += $_ -replace "OU=",""}} If($OU -match $CheckOU){ "Computer:$computerName is in the OU:$CheckOU" # Do something... } Else{ "Computer:$computerName is not in the OU:$CheckOU" # Do something else.. } </code></pre> <p>This will take a <code>$computerName</code> and get all the OU's that it's in from Active Directory and stores them in an <code>$OU</code> array. </p> <p>Then you can use that array to simply check if the computer is in the given OU (<code>$CheckOU</code>) or not by using the <code>-match</code> operator. </p> <p><strong>Note:</strong> You need to make sure that you import the <code>activedirectory</code> module. If you do not have this to import follow this link for how to get it: <a href="http://blogs.msdn.com/b/rkramesh/archive/2012/01/17/how-to-add-active-directory-module-in-powershell-in-windows-7.aspx" rel="nofollow">activedirectory module</a> </p> <p>For more Cmdlet's and syntax on the Powershell Active Directory module follow this <a href="http://technet.microsoft.com/en-us/library/ee617195.aspx" rel="nofollow">Link</a></p> |
3,097,814 | 0 | <pre><code>decltype(a->x) </code></pre> <p>This gives you the type of the member variable <code>A::x</code>, which is <code>double</code>.</p> <pre><code>decltype((a->x)) </code></pre> <p>This gives you the type of the expression <code>(a->x)</code>, which is an lvalue expression (hence why it is a const reference--<code>a</code> is a <code>const A*</code>).</p> |
36,747,045 | 0 | <p>First, you should really do</p> <pre><code>Car.prototype = Object.create(Vehicle.prototype); </code></pre> <p>The reasons are involved, but suffice to say that that's a better way to get a new object for your <code>Car</code> prototype and ensure that it inherits from the <code>Vehicle</code> prototype.</p> <p>Now, the <strong>reason</strong> you want a new object for the <code>Car</code> prototype is that if you're bothering to make a <em>subclass</em> you'll probably want specialized behaviors that <em>do</em> apply to the subclass but <em>don't</em> apply to the more general parent class. You need a new object for those new properties; otherwise, you'd be adding those behavior properties to the <code>Vehicle</code> prototype, and all Vehicles would have access.</p> <p>Finally, setting <code>Car.prototype</code> to just <code>Vehicle</code> doesn't make much sense. That would <em>work</em>, in that it would not cause an exception, but it would set the <code>Car</code> prototype to be the <code>Vehicle</code> constructor function itself.</p> |
15,826,385 | 0 | Can we query and fetch data from LIST between different subsites using CAML Query.? <p>Have LIST created under one site, can the same LIST be used to fetch data from other site using CAML Query.?</p> <p>eg:</p> <p>Consider a LIST "xxx" created under SitePages/AAA/Lists/</p> <p>Can i access the LIST "xxx" from other site i.e SitePages/BBB/</p> <p>To Summarize, Is it possible to access the LIST across parent and child sites, vice-versa.</p> <p>Thanks in advance</p> |
6,604,110 | 0 | haml display address <pre><code>album/show.html.haml #comment_list= render :partial => 'shared/comments', :locals => { :commentable => @album } shared/_comments.html.haml #comments = commentable.comments.each do |comment| = comment.content display Hello #<Comment:0x7f668f037710> </code></pre> <p>why is address displaying? How to remove it?</p> |
36,550,797 | 1 | Could not parse the remainder: '((records_list.1.key.5)' from '((records_list.1.key.5)' <p>Obligatory "I am new to Django" here...</p> <p>In my views I am creating a list, called records_list. Inside that list, I have another list in the position [0] and a dictionary in the position [1], as follows:</p> <pre><code>records_list = list() list_one = Bet.objects.order_by('-game_date') list_two = {} </code></pre> <p>Inside the "list_two", that is my dictionary, I have a key that is a date "April 2016", for ex, and a value that is a tuple: </p> <pre><code>list_two[aux_month_year] = (aux_wins, aux_losses, aux_voids, s_rate, i_rate, profit) </code></pre> <p>So I return this to my html:</p> <pre><code>records_list.append(list_one) records_list.append(list_two) return records_list </code></pre> <p>In the html, I want to create a table, and I start by checking if my profit is positive or not:</p> <pre><code>{% if records_list %} <table class="table"> <thead> <tr> <th>Date</th> <th>Wins</th> <th>Losses</th> <th>Void</th> <th>Success Rate</th> <th>Return on Investment</th> <th>Profit</th> </tr> </thead> {% for key in records_list.1 %} {% if ((records_list.1.key.5) > 0) %} <tr class="success"> <td>{{ key }}</td> <td>{{ records_list.1.key.0 }}</td> <td>{{ records_list.1.key.1 }}</td> <td>{{ records_list.1.key.2 }}</td> <td>{{ records_list.1.key.3 }}%</td> <td>{{ records_list.1.key.4 }}%</td> <td>{{ records_list.1.key.5 }}</td> </tr> </code></pre> <p>However, I am getting the following syntax error here:</p> <pre><code>{% if ((records_list.1.key.5) > 0) %} </code></pre> <p>Error:</p> <pre><code>Could not parse the remainder: '((records_list.1.key.5)' from '((records_list.1.key.5)' </code></pre> <p>If someone could help me and point me to the right direction I would appreciate! Thank you</p> |
9,103,275 | 0 | Restricting results to only rows where one value appears only once <p>I have a query that is more complex than the example here, but which needs to only return the rows where a certain field doesn't appear more than once in the data set.</p> <pre><code>ACTIVITY_SK STUDY_ACTIVITY_SK 100 200 101 201 102 200 100 203 </code></pre> <p>In this example I don't want any records with an <code>ACTIVITY_SK</code> of 100 being returned because <code>ACTIVITY_SK</code> appears twice in the data set.</p> <p>The data is a mapping table, and is used in many joins, but multiple records like this imply data quality issues and so I need to simply remove them from the results, rather than cause a bad join elsewhere.</p> <pre><code>SELECT A.ACTIVITY_SK, A.STATUS, B.STUDY_ACTIVITY_SK, B.NAME, B.PROJECT FROM ACTIVITY A, PROJECT B WHERE A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK </code></pre> <p>I had tried something like this:</p> <pre><code>SELECT A.ACTIVITY_SK, A.STATUS, B.STUDY_ACTIVITY_SK, B.NAME, B.PROJECT FROM ACTIVITY A, PROJECT B WHERE A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK WHERE A.ACTIVITY_SK NOT IN ( SELECT A.ACTIVITY_SK, COUNT(*) FROM ACTIVITY A, PROJECT B WHERE A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK GROUP BY A.ACTIVITY_SK HAVING COUNT(*) > 1 ) </code></pre> <p>But there must be a less expensive way of doing this...</p> |
28,410,479 | 0 | <p>Here is something similar with good code example.</p> <p>// Set cursor as hourglass Cursor.Current = Cursors.WaitCursor;</p> <p>// Execute your time-intensive hashing code here...</p> <p>// Set cursor as default arrow Cursor.Current = Cursors.Default;</p> <p><a href="http://stackoverflow.com/questions/1568557/how-can-i-make-the-cursor-turn-to-the-wait-cursor">How can I make the cursor turn to the wait cursor?</a></p> |
34,355,813 | 0 | <blockquote> <p>Is there any way to get a response without the target namespace?</p> </blockquote> <p>I hope not. A SOAP web service should have a well-defined, published interface and every response that it sends should conform to that interface. Usually, the interface is described by a WSDL document.</p> <blockquote> <p>And would like to get it without the target namespace</p> </blockquote> <pre><code><MyItem> <class>myClass</class> <name>MyItemName</name> </MyItem> </code></pre> <p>Being pedantic, but the absence of a namespace prefix does not mean that there is no namespace. There might be a default namespace in force. So you <em>could</em> achieve XML that looks exactly like the above and the MyItem, class and name tags might still have a non-empty namespace.</p> <blockquote> <p>I know its purpose and that it's actually quite useful.</p> </blockquote> <p>The purpose of a namespace in an XML document ( whether a web service response, or any other XML ) is to avoid polluting the global namespace. Do you really want 'name' and 'class' to have exactly one meaning in your applications? Or would it be better if each schema could define its own version of those?</p> <blockquote> <p>But it happened that it can't be processed any further by another tool with this target namespace and looks like this: </p> </blockquote> <pre><code><MyItem xmlns="http://spring.io/guides/gs-producing-web-service"> ... </code></pre> <p>That looks like valid XML, so what's the problem? Is that output produced by the 'other tool'? Or is it something that the 'other tool' cannot handle?</p> |
35,916,897 | 0 | OpenBUGS: Initializing the Model <p>I am having a problem in initializing the following model in OpenBUGS</p> <pre><code>model { #likelihood for (t in 1:n) { yisigma2[t] <- 1/exp(theta[t]); y[t] ~ dnorm(0,yisigma2[t]); } #Priors mu ~ dnorm(0,0.1); phistar ~ dbeta(20,1.5); itau2 ~ dgamma(2.5,0.025); beta <- exp(mu/2); phi <- 2*phistar-1; tau <- sqrt(1/itau2); theta0~dnorm(mu, itau2) thmean[1] <- mu + phi*(theta0-mu); theta[1] ~ dnorm(thmean[1],itau2); for (t in 2:n) { thmean[t] <- mu + phi*(theta[t-1]-mu); theta[t] ~ dnorm(thmean[t],itau2); } } </code></pre> <p>This is my data </p> <pre><code>list(y=c(-0.0383 , 0.0019 ,......-0.0094),n=945) </code></pre> <p>And this is the list of my initials </p> <pre><code>list(phistar= 0.98, mu=0, itau2=50) </code></pre> <p>The checking of model, loading of data and compilation steps are ok. When loading initials, OpenBUGS says initial values are loaded but chain contains uninitialized variables. I then tried to initialize theta0 also but the problem persists. Could someone please help me regarding this? Thanks Khalid</p> |
34,014,074 | 0 | <p>Found how to get it:</p> <pre><code>from openerp.http import request ua = request.httprequest.environ.get('HTTP_USER_AGENT', '') </code></pre> <p>Note. <code>httprequest</code> seems to be deprecated. But for now I din't find another way to get user agent.</p> |
24,134,264 | 0 | GIT and GITLAB in Debian Wheezy <p>I'm news in git and gitlab. I've installed it from the officiel installation. Trying to push some project via sourcetree for example, I've this result</p> <pre><code>`git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master Pushing to [email protected]:/home/git/repositories/root/all.git remote: GitLab: You are not allowed to access master![K remote: error: hook declined to update refs/heads/master[K </code></pre> <p>To [email protected]:/home/git/repositories/root/all.git ! [remote rejected] master -> master (hook declined)</p> <p>error: failed to push some refs to '[email protected]:/home/git/repositories/root/all.git' `</p> <p>Someone have an idea?</p> <p>Thank's</p> |
29,647,582 | 0 | Enable smilies/emoticons in UCWA Chat application <p>I have built a web application which provides simple text chatting. I have used the UCWA API provided by Microsoft to implement this Instant Messaging chat application.</p> <p>My next step is to enable usage of smilies/emoticons in the chat application. I have gone though the ucwa documentation <a href="https://ucwa.lync.com/documentation/what-is-lync-ucwa-api" rel="nofollow">https://ucwa.lync.com/documentation</a></p> <p>But i have not found a way to enable usage of smilies/emoticons.</p> <p>My query is: Does UCWA API support usage of smilies/emoticons? If yes, how do we enable in our chat application. If No, how can we add smilies/emoticons into a web application?</p> <p>Any sort of links or any clues would be really helpful. Thanks in Advance.</p> |
18,752,733 | 0 | <p>Being from a SQL Server background, I've always created a trigger on the table to basically emulate IDENTITY functionality. Once the trigger is on, the SK is automatically generated from the sequence just like identity and you don't have to worry about it.</p> |
17,810,487 | 0 | An array disappears in "for" expression, <p>There's some code, and it's not working. </p> <pre><code>window.onload = function () { var div = document.getElementById ('main'); var img = div.children; var i = 1; //console.log(img[i]); for (var i=1; i != img.length; i++) { img[i].onclick = function () { console.log(img[i]); } } } </code></pre> <p>Please, explain me Why is img[i] in <code>console.log(img[i]);</code> undefined ? How this bug can be fixed?</p> |
3,471,880 | 0 | JSF: How to refresh a page after download <p>I have a commandButton that will invoke a function to download a file (standard stuffs like <code>InputStream</code>, <code>BufferedOutputStream</code> ...) After download success, at the end of the function, I change some values of the current object and persist it into database. All of these work correctly. Now when file is done downloading, the content of the page is not updated. I have to hit refresh for me to see updated content. Please help. Below are the basic structure of my code</p> <p><code>document</code>: Managed Bean<br> <code>getDrawings()</code>: method return a list of Drawing (entity class)<br> <code>CheckedOutBy</code>: attribute of Entity <code>Drawing</code></p> <pre><code><p:dataTable id="drawing_table" value="#{document.drawings}" var="item" > <p:column> <f:facet name="header"> <h:outputText value="CheckedOutBy"/> </f:facet> <h:outputText value="#{item.checkedOutBy}"/> ... </p:dataTable> <p:commandButton ajax="false" action="#{document.Download}" value="Download" /> </code></pre> <p>Inside my Managed Bean</p> <pre><code>public void Download(){ Drawing drawing = getCurrentDrawing(); //Download drawing drawing.setCheckedOutBy("Some Text"); sBean.merge(drawing); //Update "Some Text" into CheckedOutBy field } </code></pre> |
32,701,467 | 0 | Undefined type error even with forward declaration <p>I was reading up on circular references and forward declarations. I do understand that it is not a good design practice to have implementations in a header file. However I was experimenting and could not understand this behavior.</p> <p>With the following code (containing the forward declarations) I expected it to build, however I get this error:</p> <pre><code>Error 1 error C2027: use of undefined type 'sample_ns::sample_class2' </code></pre> <p>Header.hpp</p> <pre><code>#ifndef HEADER_HPP #define HEADER_HPP #include "Header2.hpp" namespace sample_ns { class sample_class2; class sample_class{ public: int getNumber() { return sample_class2::getNumber2(); } }; } #endif </code></pre> <p>Header2.hpp</p> <pre><code>#ifndef HEADER2_HPP #define HEADER2_HPP #include "Header.hpp" namespace sample_ns { class sample_class; class sample_class2{ public: static int getNumber2() { return 5; } }; } #endif </code></pre> <p>Obviously I am missing on something. Can someone point me in the right direction as to why am I getting this error.</p> |
6,024,101 | 0 | <p>No, it's only a matter of readability. As your model grows you will probably get a very large configuration in OnModelCreating. As to make this more readable you break it up into separate configurations.</p> |
3,482,879 | 0 | Where are the functional gui users? <p>There has been a lot of research into ways of creating guis in a functional language. There is libraries for push/pull frp, arrow based frp and probably other superior research too. <a href="http://stackoverflow.com/questions/2672791/is-functional-gui-programming-possible">Many people</a> seem to agree this is the more native way yet just about everyone seems to be using imperative binding libraries such as gtk2hs and wxhaskell. Even places recommended as <a href="http://book.realworldhaskell.org/read/gui-programming-with-gtk-hs.html" rel="nofollow noreferrer">good</a> <a href="http://en.wikibooks.org/wiki/Haskell/GUI" rel="nofollow noreferrer">tutorials</a> teach binding to these plain imperative libraries. Why not guis based on FRP research?</p> |
22,385,632 | 0 | Javascript not changing background img in a span <p>I've recently tried to use some js code that i've used for ages to change a span's background colour on certain days, i'm now trying to use the js to change the background image instead but i'm having issues. The js is finding the element but rather than change to the new image, the page is just rendering the span with no image at all. Any hints would be handy as i'm not that great with js. I do have spans identified to display as block, and the current image in the span does work when the javascript is removed.</p> <p>Javascript code: (i've cut some out so only Thursday has a command)</p> <pre><code>var d = new Date(); var weekday = new Array(7); weekday[0]="Sunday"; weekday[1]="Monday"; weekday[2]="Tuesday"; weekday[3]="Wednesday"; weekday[4]="Thursday"; weekday[5]="Friday"; weekday[6]="Saturday"; var n = weekday[d.getDay()]; var thursday = document.getElementById("th"); if (n == "Thursday") { thursday.style.color="#fff"; thursday.style.backgroundImage = "url(../images/boardMiddleOn.png)"; } </code></pre> <p>CSS:</p> <pre><code>#th { background-image:url(../images/boardMiddle.png); height: 45px; line-height: 45px; } </code></pre> <p>HTML:</p> <pre><code><span id="th">Thursday: 9am - 11pm<br/></span> </code></pre> |
40,413,461 | 0 | <p>Create function to validate entered Number that return bool</p> <pre><code>bool isValidNumber = true; do{ Console.WriteLine("Enter the phone number to be added:"); string NewNumber = Console.ReadLine(); isValidNumber = isValidNumberCheck(NewNumber); }while(!isValidNumber); </code></pre> |
29,391,302 | 0 | Using custom user instead of ASP.NET IdentityUser <p>I'm new on ASP.NET Identity and trying to customize the identity which is provided while creating new MVC project.</p> <p>ASP.NET Identity automatically creates few tables for handle authentication and authorization itself.</p> <p>My main goal is just create Users table but others. I've tried following code to prevent creating these tables:</p> <pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Ignore<IdentityUserRole>(); modelBuilder.Ignore<IdentityUserClaim>(); modelBuilder.Ignore<IdentityRole>(); } </code></pre> <p>When I want to create a user, following error returning:</p> <p><em>The navigation property 'Roles' is not a declared property on type 'ApplicationUser'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.</em></p> <p>I found that built-in Identity user has following structure:</p> <pre><code>IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string> </code></pre> <p>What I need is creating a custom IdentityUser which not contains role, claim, etc. I just want the table 'Users' when I run the project.</p> <p>Any possibility to create my own IdentityUser or customize built-in one? Or any suggestion to create just 'Users' table and work with it?</p> <p>Many thanks in advice.</p> |
14,380,143 | 0 | Matching binary patterns in C <p>I'm currently developing a C program that needs to parse some bespoke data structures, fortunately I know how they are structured, however I'm not sure of how to implement my parser in C.</p> <p>Each of the structures are 32-bits in length, and each structure can be identified by it's binary signature.</p> <p>As an example, there are two particular structures that I'm interested in, and they have the following binary patterns (x means either 0 or 1)</p> <pre><code> 0000-00xx-xxxx-xxx0 0000-10xx-10xx-xxx0 </code></pre> <p>Within these structures the 'x' bits contain the actual data I need, so essentially I need a way of identifying each structure based on how the bits are written within each structure.</p> <p>So as an example in pseudo-code:</p> <pre><code>if (binaryPattern = 000010xxxxxxxxx0) { do something with it; } </code></pre> <p>I'm guessing that reading them as ints, and then performing some kind of bitmasking would be the way to go, but my knowledge of C isn't great, and maybe a simple logical OR operation would do it, but I just wanted some advice on doing this before I start.</p> <p>Thanks</p> <p>Thanks very much to everyone that has answered, very helpful!!</p> |
33,739,855 | 0 | Modify method to show success/failed Message. AngularJS <p>I´m pretty new to angularJS and I cant seem to find a good way to show a SUCCESS or ERROR message for the return of my Save method.</p> <p>Heres the html code:</p> <pre><code><form role="form"> <div class="panel-body"> <div class="panel-body"> <img src="/assets/doge.jpg" alt="Doge"> </div> <div class="container"> <div class="input-group"> <span class="input-group-addon" id="tec-nombre">Nombre del Tecnico:</span><input type="text" class="form-control" data-ng-model="tecnico.nombre" aria-describedby="tec-nombre"> <div role="alert"> <span class="error" data-ng-show="myForm.nombreTecnico.$error.required"> Required!</span> </div> </div> <div class="input-group"> <span class="input-group-addon" id="tec-legajo">Legajo del Tecnico:</span><input type="number" class="form-control" data-ng-model="tecnico.legajo" aria-describedby="tec-legajo"> <div role="alert"> <span class="error" data-ng-show="myForm.legajoTecnico.$error.required"> Required!</span> </div> </div> <div class="input-group"> <span class="input-group-addon" id="tec-email">Email del Tecnico:</span><input type="email" class="form-control" data-ng-model="tecnico.email" aria-describedby="tec-email"> <div role="alert"> <span class="error" data-ng-show="myForm.emailTecnico.$error.required"> Required!</span> </div> </div> <div class="input-group"> <span class="input-group-addon" id="tec-interno">Interno del Tecnico:</span><input type="text" class="form-control" data-ng-model="tecnico.interno" aria-describedby="tec-interno"> <div role="alert"> <span class="error" data-ng-show="myForm.nombreTecnico.$error.required"> Required!</span> </div> </div> </div> </div> <div class="form-group"> <label class="col-md-2"></label> <div class="col-md-4"> <a href="#/" class="btn">Cancel</a> <a data-ng-click="saveTecnico(tecnico);" href="#/test" class="btn btn-primary">Actualizar {{tecnico.legajo}}</a> <button data-ng-click="deleteCustomer(customer)" data-ng-show="customer._id" class="btn btn-warning">Delete</button> </div> </div> </code></pre> <p></p> <p>And heres the Angular Code:</p> <pre><code> angular.module('incidente', [ 'ngRoute' , 'ui.tree' ]) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/', { templateUrl : 'partials/home.html' }).when('/incidente/:codename', { templateUrl : 'partials/incidente.html', controller : 'IncidenteController' }).when('/incidentes', { templateUrl : 'partials/incidentes.html', controller : 'IncidentesController' }).when('/tecnicos', { templateUrl : 'partials/tecnicos.html', controller : 'TecnicosController' }).when('/tecnico/:legajo', { templateUrl : 'partials/tecnico.html', controller : 'TecnicoController' }).when('/sistema/:nombre', { templateUrl : 'partials/sistema.html', controller : 'SistemaController' }).when('/sistemas', { templateUrl : 'partials/sistemas.html', controller : 'SistemasController' }).when('/hardware/:codename', { templateUrl : 'hardware.html', controller : 'HardwareController' }).when('/hardwares', { templateUrl : 'partials/hardwares.html', controller : 'HardwaresController' }).when('/software/:codename', { templateUrl : 'partials/software.html', controller : 'SoftwareController' }).when('/softwares', { templateUrl : 'partials/softwares.html', controller : 'SoftwaresController' }).when('/readme', { templateUrl : 'partials/readme.html', controller : '' }).when('/test', { templateUrl : '/partials/tecnicos.html', controller : 'TecnicosController' }).otherwise({ redirectTo : '/' }); } ]) .controller('home', function($scope, $http) { $http.get('/resource/').success(function(data) { $scope.greeting = data; }) }) .controller( 'navigation', function($rootScope, $scope, $http, $location) { var authenticate = function(credentials, callback) { var headers = credentials ? { authorization : "Basic " + btoa(credentials.username + ":" + credentials.password) } : {}; $http.get('user', { headers : headers }).success(function(data) { if (data.name) { $rootScope.authenticated = true; } else { $rootScope.authenticated = false; } callback && callback(); }).error(function() { $rootScope.authenticated = false; callback && callback(); }); } authenticate(); $scope.credentials = {}; $scope.login = function() { authenticate($scope.credentials, function() { if ($rootScope.authenticated) { $location.path("/"); $scope.error = false; } else { $location.path("/login"); $scope.error = true; } }); }; }) .controller( 'IncidenteController', [ '$scope', '$http', '$routeParams', function($scope, $http, $routeParams) { var urlbase = "http://localhost:8080/"; var onError = function(reason) { $scope.error = "No se pudo encontrar"; }; var code = $routeParams.codename; console.log(code); var onIncidenteComplete = function(response) { try { $scope.incidente = response.data; } catch (error) { console.error(error); } }; $http.get(urlbase + "get/incidente/" + code).then( onIncidenteComplete, onError); $scope.saveIncidente = function(incidente) { console.log(incidente); return $http.post(urlbase + "set/incidente/" + incidente) }; } ]) .controller( 'IncidentesController', [ '$scope', '$http', function($scope, $http) { var urlbase = "http://localhost:8080/"; var onError = function(reason) { $scope.error = "No se pudo encontrar"; }; var onIncidenteComplete = function(response) { try { $scope.incidentes = angular .fromJson(response.data); console.log($scope.incidentes); } catch (error) { console.error(error); } }; $http.get(urlbase + "get/incidente/").then( onIncidenteComplete, onError); } ]) .controller( 'TecnicoController', [ '$scope', '$http', '$routeParams', function($scope, $http, $routeParams) { var onError = function(reason) { $scope.error = "No se pudo encontrar"; }; var urlbase = "http://localhost:8080/"; var legajo = $routeParams.legajo; var onTecnicoComplete = function(response) { try { $scope.tecnico = response.data; } catch (error) { console.error(error); } }; $http.get(urlbase + "get/tecnico/" + legajo) .then(onTecnicoComplete, onError); $scope.saveTecnico = function(tecnico) { return $http.post(urlbase + "set/tecnico/", tecnico) }; This is the function that saves the tecnico and should show the error/success message. } ]) .controller( 'TecnicosController', [ '$scope', '$http', function($scope, $http) { var onError = function(reason) { $scope.error = "No se pudo encontrar"; }; var onTecnicoComplete = function(response) { $scope.tecnicos = response.data; }; $http.get("http://localhost:8080/get/tecnico/") .then(onTecnicoComplete, onError); } ]) .controller( 'SistemasController', [ '$scope', '$http', function($scope, $http) { var urlbase = "http://localhost:8080/get/"; var onError = function(reason) { $scope.error = "No se pudo encontrar"; }; var onSistemaComplete = function(response) { $scope.sistemas = response.data; }; $http.get(urlbase + "sistema/").then( onSistemaComplete, onError); } ]); </code></pre> <p>So far is just a redirect, but I want to show a success or error message before te redirect to help the user understand what happened.</p> |
28,369,745 | 0 | <p>How do you parse JSON data? If you are using <a href="https://code.google.com/p/google-gson/" rel="nofollow">Gson</a>, you can use <a href="https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html#disableHtmlEscaping%28%29" rel="nofollow">GsonBuilder.disableHtmlEscaping()</a> method in order to display proper characters instead of their code.</p> |
28,225,138 | 0 | Not fully understanding how this closure works <p>I have an excerpt from <a href="http://stackoverflow.com/questions/111102/how-do-javascript-closures-work">How do JavaScript closures work?</a></p> <p>I am having a difficult time understanding closures. </p> <pre><code> <button type="button" id="bid">Click Me!</button> <script> var element = document.getElementById('bid'); element.onclick = (function() { // init the count to 0 var count = 0; return function(e) { // <- This function becomes the onclick handler count++; // and will retain access to the above `count` if (count === 3) { // Do something every third time alert("Third time's the charm!"); //Reset counter count = 0; } }; })(); </code></pre> <p>How is the 'count' value saved between invocations? Should not it be reset every invocation by var = 0? </p> |
31,725,967 | 0 | <p>I'm pretty sure Excel doesn't like it when there's empty CellFormats(). I suggest you try to remove these two</p> <pre><code>new CellFormat() { }, new CellFormat() { }, </code></pre> |
5,452,751 | 0 | <p>You can't do this, it's up to the user.</p> |
17,360,963 | 0 | <pre><code>#include <stdio.h> #include <string.h> //#include <stdbool.h> int main() { int m,n,t,i; char a[]="National University"; char b[]="India"; char c[100]; char d[100]; m=strlen(a); n= strlen(b); if(m>n) { t=m; // strcpy(&c,&a); for(i=0;i<n;i++) d[i]=b[i]; for(i=0;i<m-n;i++) d[n+i]=32; for(i=0;i<t;i++) { a[i]=a[i]^d[i]; d[i]=d[i]^a[i]; a[i]=a[i]^d[i]; } printf("a= %s \t b=%s" ,a,d); } else { t=n; // strcpy(&d,&b); for(i=0;i<m;i++) c[i]=a[i]; for(i=0;i<n-m;i++) c[m+i]=32; for(i=0;i<t;i++) { c[i]=c[i]^b[i]; b[i]=b[i]^c[i]; c[i]=c[i]^b[i]; } printf("c= %s \t d=%s" ,c,b); } return 0; } </code></pre> <p>This way you can do it.You just need a loop for swapping each character. EDIT: Now its dynamic. You need not to specify length manually and I am appending NULL character at the end of shorter string. Look result at :<a href="http://ideone.com/B7lsz4" rel="nofollow">http://ideone.com/B7lsz4</a></p> |
27,024,243 | 0 | <p>In my case, I was declaring a <code>const</code> in a header file, which worked fine when building and running on the device (iPhone 5), however when attempting to simulate a 4S, all of a sudden I had some 300 "duplicate symbols".</p> <p>It turns out I needed to also mark the <code>const</code> as <code>static</code> and the issue went away. Presumably it was trying to redefine the constant every time the header was referenced. The compiler isn't smart enough to just make constants static? Didn't think that would be necessary, but I guess it is.</p> <pre><code>const CGFloat kTitleAnimateDistance = 50.f; </code></pre> <p>Needed to be:</p> <pre><code>const static CGFloat kTitleAnimateDistance = 50.f; </code></pre> |
461,012 | 0 | Performance Penalty (if any) in Using the 'var' Declaration in C# 3.0+ <p>Is there any performance penalty in using the var declaration in c# 3.0+? Resharper is constantly nagging me to use it liberally, and I want to know if there is any downside to it.</p> |
30,110,401 | 0 | <p>An iOS application doesn't receive any callbacks when it is about to be uninstalled, so it's not possible to do what you want.</p> <p>See this question <a href="http://stackoverflow.com/questions/6911361/detect-ios-application-about-to-delete">Detect iOS application about to delete?</a></p> |
21,541,887 | 0 | <p>There must have been an intermittent issue. This seems to be working now.</p> |
20,434,378 | 0 | <p>I disagree with the previous post. This is not a threading issue, this is an algorithm issue. The reason matlab, R, and octave wipe the floor with C++ libraries is because their C++ libraries use more complex, better algorithms. If you read the octave page you can find out what <em>they</em> do[1]: </p> <blockquote> <p>Eigenvalues are computed in a several step process which begins with a Hessenberg decomposition, followed by a Schur decomposition, from which the eigenvalues are apparent. The eigenvectors, when desired, are computed by further manipulations of the Schur decomposition.</p> </blockquote> <p>Solving eigenvalue/eigenvector problems is non-trivial. In fact its one of the few things "Numerical Recipes in C" recommends you <em>don't</em> implement yourself. (p461). GSL is often slow, which was my initial response. ALGLIB is also slow for its standard implementation (I'm getting about 12 seconds!):</p> <pre><code>#include <iostream> #include <iomanip> #include <ctime> #include <linalg.h> using std::cout; using std::setw; using std::endl; const int VERBOSE = false; int main(int argc, char** argv) { int size = 0; if(argc != 2) { cout << "Please provide a size of input" << endl; return -1; } else { size = atoi(argv[1]); cout << "Array Size: " << size << endl; } alglib::real_2d_array mat; alglib::hqrndstate state; alglib::hqrndrandomize(state); mat.setlength(size, size); for(int rr = 0 ; rr < mat.rows(); rr++) { for(int cc = 0 ; cc < mat.cols(); cc++) { mat[rr][cc] = mat[cc][rr] = alglib::hqrndnormal(state); } } if(VERBOSE) { cout << "Matrix: " << endl; for(int rr = 0 ; rr < mat.rows(); rr++) { for(int cc = 0 ; cc < mat.cols(); cc++) { cout << setw(10) << mat[rr][cc]; } cout << endl; } cout << endl; } alglib::real_1d_array d; alglib::real_2d_array z; auto t = clock(); alglib::smatrixevd(mat, mat.rows(), 1, 0, d, z); t = clock() - t; cout << (double)t/CLOCKS_PER_SEC << "s" << endl; if(VERBOSE) { for(int cc = 0 ; cc < mat.cols(); cc++) { cout << "lambda: " << d[cc] << endl; cout << "V: "; for(int rr = 0 ; rr < mat.rows(); rr++) { cout << setw(10) << z[rr][cc]; } cout << endl; } } } </code></pre> <p>If you really need a fast library, probably need to do some real hunting. </p> <p>[1] <a href="http://www.gnu.org/software/octave/doc/interpreter/Basic-Matrix-Functions.html">http://www.gnu.org/software/octave/doc/interpreter/Basic-Matrix-Functions.html</a></p> |
19,775,676 | 0 | <p>The problem is because of this:</p> <pre><code>service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); </code></pre> <p>This is happening because your service has not stopped within your <code>timeout</code>. You should either set your timeout higher, or don't set a timeout at all.</p> |
21,800,348 | 0 | <p>You are invoking the <code>finished</code> function, instead of passing it as an argument. To pass it, use </p> <pre><code>$.when.apply($, deferred).then(finished); </code></pre> <p>Instead of </p> <pre><code>$.when.apply($, deferred).then(finished()); </code></pre> |
23,413,986 | 0 | <p>Please, try to use the frame document onready event.</p> <pre><code> printData: function(printId) { $(window.frames[printId].document).ready(function() { window.frames[printId].focus(); window.frames[printId].print(); }); } </code></pre> |
8,901,873 | 0 | <p>This should do the trick</p> <pre><code><ObjectAnimationUsingKeyFrames x:Name="animation" Duration="0" Storyboard.TargetProperty="xmlnsAlias:VisualStateUtility.InitialState" Storyboard.TargetName="ExpanderButton"> </code></pre> <p>Notice how a name is added to the animation, the parentheses are removed from the target property name, which is then prefixed with the xmlns alias from the xaml header.</p> <p>In your code behind you'll have to add this:</p> <pre><code>InitializeComponent(); Storyboard.SetTargetProperty(animation, new PropertyPath(Fully.Qualified.Namespace.VisualStateUtility.InitialState)); </code></pre> <p>Apparently this last step is required for animating custom attached properties. A real pain if you'd ask me.</p> |
34,374,236 | 0 | <p>You cannot call a trait method without specifying on which implementation you wish to call it. It doesn't matter that the method has a default implementation.</p> <p>An actual UFCS call looks like this:</p> <pre><code>trait FooPrinter { fn print() { println!("hello"); } } impl FooPrinter for () {} fn main () { <() as FooPrinter>::print(); } </code></pre> <p><a href="http://is.gd/fAyAWm" rel="nofollow">playground</a></p> <p>If you don't need polymorphism on this method, move it to a <code>struct</code> or <code>enum</code>, or make it a global function.</p> |
1,766,973 | 0 | <p>Warning: I may be totally misunderstanding you, but if all you want is a log file, why sweat?</p> <p>Put this in a bat file (change the path to your tools directory, and yourappname is of course your app's name):</p> <pre><code>cd "C:\devAndroid\Software\android-sdk-windows-1.6_r1\android-sdk-windows-1.6_r1\tools" adb logcat -v time ActivityManager:W yourappname:D *:W >"C:\devAndroid\log\yourappname.log" </code></pre> <p>Then in your code just do something similar to this:</p> <pre><code>Log.d("yourappname", "Your message"); </code></pre> <p>To create the log, connect the USB cable and run your bat file.</p> <p>Regards</p> |
10,260,710 | 0 | To rewrite a javascript to jQuery <p>I'm not a sharp jquery / javascript coder yet - so I hope that there is a kind soul out there, who can help me with rewriting a javascript into a jQuery script.</p> <p>The code looks like this:</p> <pre><code><script type="text/javascript"> function update_delivery_address() { elm_true = document.getElementById('delivery_same_as_invoice_true'); elm_false = document.getElementById('delivery_same_as_invoice_false'); if (!elm_true.checked && !elm_false.checked) { elm_true.checked = true; } if (elm_true.checked) { document.getElementById('delivery_name').value = ''; document.getElementById('delivery_att').value = ''; document.getElementById('delivery_address').value = ''; document.getElementById('delivery_zipcode').value = ''; document.getElementById('delivery_city').value = ''; document.getElementById('delivery_email').value = ''; document.getElementById('delivery_name').disabled = true; document.getElementById('delivery_att').disabled = true; document.getElementById('delivery_address').disabled = true; document.getElementById('delivery_zipcode').disabled = true; document.getElementById('delivery_city').disabled = true; document.getElementById('delivery_email').disabled = true; } else { document.getElementById('delivery_name').disabled = false; document.getElementById('delivery_att').disabled = false; document.getElementById('delivery_address').disabled = false; document.getElementById('delivery_zipcode').disabled = false; document.getElementById('delivery_city').disabled = false; document.getElementById('delivery_email').disabled = false; } } update_delivery_address(); </script> </code></pre> |
18,844,268 | 0 | how to input symbols through JQuery <p>i'm using JQuery and aJax with PHP to insert some data to database </p> <p>but I have a small problem, when i insert data contain (&) symbol .. database read the text before (&) ..</p> <p>for example .. if the title is ( Sun & Moon ) . it saves it as : (Sun) only .. how can i solve it ?</p> <p>so this is my code :</p> <pre><code><script type="text/javascript"> $(document).ready(function(){ $('#submit').click(function(){ $('#result').fadeOut("fast"); $('#wait').fadeIn("slow").delay(1000); var number = $("input#number").val(); var title = $("input#title").val(); var dataAll = 'number='+ number + '&title=' + title ; $.ajax({ url: "../insert/add_module/", type : "POST", data : dataAll, dataType :"html", success : function(msg){ $('#wait').fadeOut("fast"); $('#result').fadeIn("slow"); $('#result').html(msg) } }); }); }); </code></pre> <p></p> |
39,427,221 | 0 | Cs-Cart custom Payment button without iframe <p>I created a payment module for Cs-Cart 4, everything works well. However, loading my inline payment gateway(see paystack.com for demo) which loads a popup in an iframe is not aesthetically pleasing. </p> <p>Is there a way I can still use my custom payment button that loads a popup outside the iframe? I don't want to use the redirect to another website method, it's not nice either. </p> <p><a href="http://i.stack.imgur.com/MmdRZ.png" rel="nofollow">That's what the checkout button looks like on the page</a></p> <p><a href="http://i.stack.imgur.com/k6BLu.png" rel="nofollow">This is meant to be a fullscreen popup</a></p> <p>Current code sample for the payment module <pre><code>function fn_paystack_adjust_amount($price, $payment_currency){ $currencies = Registry::get('currencies'); if (array_key_exists($payment_currency, $currencies)) { if ($currencies[$payment_currency]['is_primary'] != 'Y') { $price = fn_format_price($price / $currencies[$payment_currency]['coefficient']); } } else { return false; } return $price; } function fn_paystack_place_order($original_order_id){ $cart = & $_SESSION['cart']; $auth = & $_SESSION['auth']; list($order_id, $process_payment) = fn_place_order($cart, $auth); $data = array ( 'order_id' => $order_id, 'type' => 'S', 'data' => TIME, ); db_query('REPLACE INTO ?:order_data ?e', $data); $data = array ( 'order_id' => $order_id, 'type' => 'E', // extra order ID 'data' => $original_order_id, ); db_query('REPLACE INTO ?:order_data ?e', $data); return $order_id; } if (!defined('BOOTSTRAP')) { die('Access denied'); } // Return from payment if (defined('PAYMENT_NOTIFICATION')) { if ($mode == 'return' && !empty($_REQUEST['merchant_order_id'])) { if (isset($view) === false){ $view = Registry::get('view'); } $view->assign('order_action', __('placing_order')); $view->display('views/orders/components/placing_order.tpl'); fn_flush(); $code = $_REQUEST['merchant_order_id']; $merchant_order_id = fn_paystack_place_order($_REQUEST['merchant_order_id']); $amount = $_REQUEST['amount']; if(!empty($merchant_order_id) and !empty($amount)){ if (fn_check_payment_script('paystack.php', $merchant_order_id, $processor_data)) { $mode = $processor_data['processor_params']['paystack_mode']; if ($mode == 'test') { $key = $processor_data['processor_params']['paystack_tsk']; }else{ $key = $processor_data['processor_params']['paystack_lsk']; } // $key_secret = $processor_data['processor_params']['key_secret']; $order_info = fn_get_order_info($merchant_order_id); $pp_response = array(); $success = false; $error = ""; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"https://api.paystack.co/transaction/verify/".$code); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $headers = [ 'Authorization: Bearer '.$key, ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); $verification = json_decode($response); if (curl_errno($ch)) { // should be 0 // curl ended with an error $cerr = curl_error($ch); curl_close($ch); throw new Exception("Curl failed with response: '" . $cerr . "'."); } curl_close ($ch); if(($verification->status===false) || (!property_exists($verification, 'data')) || ($verification->data->status !== 'success')){ $success = false; $error = ""; }else{ if ($amount == ($verification->data->amount/100)) { $success = true; }else{ $success = false; $error = "Invalid Amount"; } } if($success === true){ $pp_response['order_status'] = 'P'; $pp_response['transaction_id'] = $code; $pp_response['Status'] = 'Payment Successful'; fn_finish_payment($merchant_order_id, $pp_response); fn_order_placement_routines('route', $merchant_order_id); }else { $pp_response['order_status'] = 'O'; $pp_response['transaction_id'] = $code; $pp_response['Status'] = 'Payment Failed'; fn_finish_payment($merchant_order_id, $pp_response); fn_set_notification('E', __('error'), 'Payment Failed #'.$code); fn_order_placement_routines('checkout_redirect'); } } } else { fn_set_notification('E', __('error'), 'Payment Unsuccessful'.$_REQUEST['merchant_order_id']); fn_order_placement_routines('checkout_redirect'); } } exit; }else { $url = fn_url("payment_notification.return?payment=paystack", BOOTSTRAP, 'current'); $maintotal = $order_info['total']+$order_info['payment_surcharge']; $mode = $processor_data['processor_params']['paystack_mode']; if ($mode == 'test') { $key = $processor_data['processor_params']['paystack_tpk']; }else{ $key = $processor_data['processor_params']['paystack_lpk']; } $html = ' <form action="'.$url.'" method="POST" target="_parent"> <input type="hidden" name="paystack_payment_id" id="paystack_payment_id" /> <input type="hidden" name="merchant_order_id" id="order_id" value="'.$order_id.'"/> <input type="hidden" name="amount" value="'.$maintotal.'"/> <script src="https://js.paystack.co/v1/inline.js" data-key="'.$key.'" data-email="'.$order_info['email'].'" data-amount="'.($maintotal*100).'" data-ref="'.$order_id.'" > </script> </form>'; echo <<<EOT {$html} </body> </html> EOT; exit; } ?> </code></pre> |
14,357,137 | 0 | <p>I afraid I don't have an immediate solution. A quick search in Chrome forum showing that this issue appeared recently. You might need to wait for an upgrade of google browser.</p> <p><a href="http://code.google.com/p/chromium/issues/detail?id=116986" rel="nofollow">http://code.google.com/p/chromium/issues/detail?id=116986</a></p> |
10,630,061 | 0 | <p>Without having to increase the asset size of your app, you could create a simple UIView.</p> <pre><code>UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow]; UIView *fullscreenShadow = [[UIView alloc] initWithFrame:keyWindow.bounds]; fullscreenShadow.backgroundColor = [UIColor blackColor]; fullscreenShadow.alpha = 0.3; [keyWindow addSubview:fullscreenShadow]; </code></pre> <p>Adding it to the keyWindow will make it cover everything, except the UIStatusBar of course. I believe this will achieve your intended result. Combine it with a UIViewAnimation and bring the alpha up.</p> |
36,470,740 | 0 | <p>Unfortunately, what you are trying to achieve is inherently unsafe as far as the compiler is concerned because you are creating <em>aliases</em> to <em>mutable</em> nodes. Two possible issues that the compiler will complain about:</p> <ul> <li>there is no proof that the node will not move, so the reference you take might be invalidated</li> <li>there is no proof that the node will not be mutated, so having two aliases to it (and being able to hand over two aliases to it) create a safety hole</li> </ul> <hr> <p>Now what?</p> <p>There are various approaches. If you are sure of yourself you could use <code>unsafe</code> and raw pointers, for example. However, the simpler solutions would be:</p> <ul> <li>use a <code>Vec</code> to store the nodes, and indexes to link them</li> <li>use <code>Rc</code> and <code>Weak</code></li> </ul> <p>The former is:</p> <pre><code>struct Node<T> { data: T, next: Option<usize>, random: Option<usize>, } pub struct List<T> { store: Vec<Node<T>>, } </code></pre> <p>And the latter would be:</p> <pre><code>struct Node<T> { data: T, next: Option<Rc<Node<T>>, random: Option<Weak<Node<T>>, } pub struct List<T> { head: Option<Rc<Node<T>>, } </code></pre> <p>the latter however will not allow mutation of the internal nodes (because there is inherent aliasing) so you may need to wrap the <code>T</code> into <code>RefCell<T></code>.</p> |
32,073,948 | 0 | Jersey - Inject variable from filter as RequestScoped <p>I want to perform authentication in a filter before my resource method is called. Within this filter I would also like to retrieve the permissions of a user and pass it on through a RequestScoped @Inject annotation. </p> <pre><code>@Authenticated public class AuthenticationFilter implements ContainerRequestFilter { @NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface Authenticated {}; @Inject private ISecurityHandler handler; public AuthenticationFilter() {} @Override public void filter(ContainerRequestContext requestContext) throws IOException { // Filter out unauthorized // Retrieve user permissions this.handler.setUserPermissions(...); } } </code></pre> <p>Resource:</p> <pre><code>@Path("my-path") public class GetVisitorsDataResource { @Inject private ISecurityHandler handler; @GET @Path("resource-method") @Authenticated @Produces(MediaType.APPLICATION_JSON) public Response resource() { System.out.println(handler.getUserPermissions()); return Response.ok().build(); } } </code></pre> <p>I have registered the filter and a Factory for the injection.</p> <pre><code>public static class SecurityHandlerProvider implements Factory<ISecurityHandler> { @Override public ISecurityHandler provide() { System.out.println("PROVIDING SECURITY CONTEXT!"); return new SecurityHandlerImpl(); } @Override public void dispose(ISecurityHandler instance) { System.out.println("DISPOSING SECURITY CONTEXT!"); } } </code></pre> <p>I have also bound it.</p> <pre><code>bindFactory(SecurityHandlerProvider.class).to(ISecurityHandler.class).in(RequestScoped.class); </code></pre> <p>It is important that the object is created when a request is received and only accessible within that request. When the request is finished, the dispose method should be called. The only way I can achieve something similar is through the @Singleton annotation. However, the object is not destroyed after the request is completed and is shared across all requests.</p> <p>I have been investing too much time into this issue already, is there perhaps anybody that knows how to achieve the preferred result?</p> |
18,053,943 | 0 | Bxslider Ticker image spacing as a Wordpress plugin <p>I installed the BxSlider as a plugin for Wordpress and inserted the php script code to show above the footer on all pages.</p> <p>The images scroll perfectly across the page except I'm trying to reduce the spacing between the images to show more than one image per transition.</p> <p>To best explain the website shows as follows <a href="http://www.harvestoffalyfoodfestival.com/" rel="nofollow">http://www.harvestoffalyfoodfestival.com/</a></p> <p>How and where can I edit the html/css code to make these adjustments. The slider settings within the plugin 'Slider Margin' doesn't have any effect when entering your option amount? Thanks</p> |
2,301,346 | 0 | <p>ASP.NET web sites emit HTML, CSS and javascript (just like other technologies), and as such should be readable by ALL browsers. The technology used to host the site should have little impact on its consumption by browser clients. </p> <p>The ony real concern is when non-conforming HTML or CSS is present and the web site doesn't render properly.</p> |
28,280,193 | 0 | <p>You code compiles because it is valid code. It fails at runtime because you are asking it to do something illegal. According to <a href="https://msdn.microsoft.com/en-us/library/aa394146(v=vs.85).aspx" rel="nofollow">MSDN</a>:</p> <blockquote> <p><strong>SetSpeed</strong> Not implemented.</p> </blockquote> <p>That being the case, this line will fail:</p> <pre><code> ManagementBaseObject inParams = classInstance.GetMethodParameters("SetSpeed"); </code></pre> <p>If <code>SetSpeed</code> is <em>not implemented</em> (versus simply ignored) you will get an exception trying to retrieve params related to it. Remove the Try/Catch to verify which line it happens on.</p> <p>The manufacturer may have a utility which allows this, but it seems doubtful WMI will work. If you do find such a tool, you might want to evaluate the bool property <code>VariableSpeed</code> to see if variable speeds are even supported.</p> |
32,201,889 | 0 | <p>Your input is incorrect, it should be in the MathML namespace:</p> <pre><code><math xmlns="http://www.w3.org/1998/Math/MathML"> <apply><power></power><ci>x</ci><cn>2</cn></apply> </math> </code></pre> <p>Not directly related to your problem but there is a newer, maintained, version of the ctop.xsl stylesheet here</p> <p><a href="https://github.com/davidcarlisle/web-xslt/tree/master/ctop" rel="nofollow">https://github.com/davidcarlisle/web-xslt/tree/master/ctop</a></p> |
40,999,904 | 0 | <p>Try the below:</p> <pre><code>label.Text = dropdownlist.SelectedItem.Text; </code></pre> <p><code>SelectedItem</code> will set the label text to selected item text, example "Test".</p> <p>or this:</p> <pre><code>label.Text = dropdownlist.SelectedValue; </code></pre> <p><code>SelectedValue</code> will set the label text to selected item value, example "1".</p> |
24,466,273 | 0 | <p>Use this definition file : <a href="https://github.com/borisyankov/DefinitelyTyped/blob/master/slickgrid/SlickGrid.d.ts" rel="nofollow">https://github.com/borisyankov/DefinitelyTyped/blob/master/slickgrid/SlickGrid.d.ts</a></p> <p>And add the following in some <code>.d.ts</code> file to tell typescript about your requirejs config: </p> <pre><code>declare module 'slickgrid'{ export = Slick } </code></pre> <p>This will allow you to do: </p> <pre><code>import slickgrid = require('slickgrid'); </code></pre> |
6,634,542 | 0 | <p>The <code>:key => value</code> syntax only works for <code>=</code>, <code>IN</code>, and <code>BETWEEN</code> conditions (depending on whether <code>value</code> is atomic, an Array, or a Range). Anything else requires you to pass the SQL as a string:</p> <pre><code>Model.where("key LIKE ?", value) </code></pre> |
36,388,783 | 0 | <p>You can do like this.</p> <pre><code>public function index(Request $request) { // Handles requests such as ".../api/products?user_id=5&price=500" $products = Product::where('user_id', $request->user_id)->where('price', '<=', intval($request->price))->get(); return response()->json($products); } </code></pre> <p><strong>Or:</strong></p> <pre><code>public function index(Request $request) { // Handles requests such as ".../api/products?user_id=5&price=500" $products = Product::whereRaw("user_id=? and price<=?", [$request->user_id, $request->price])->get(); return response()->json($products); } </code></pre> <p><strong><em>Edit after @Joel Hinz comment:</em></strong></p> <p>If you want also to pass the operator of the query you can add a new parameter to the url, for example</p> <pre><code>/api/products?user_id=5&price=500&op=1 </code></pre> <p>Then switch the number in the controller.</p> <pre><code>public function index(Request $request) { // Handles requests such as ".../api/products?user_id=5&price=500&op=1" switch(intval($request->op)){ case 1: $op = "<="; break; case 2: $op = ">"; break; //and so on default: return response()->json("Wrong parameters"); break; } $products = Product::whereRaw("user_id = ? and price $op ?", [$request->user_id, $request->price])->get(); return response()->json($products); } </code></pre> |
7,643,666 | 0 | Having difficulty getting value to post from dynamic dropdown <p>G'day, I'm having a problem getting the right value to post on a form I've made. It is passing the ID but not the name. Here's my code:</p> <pre><code><td name="tech_userlogin" id="tech_userlogin" align="right" valign="top"><select name="tech_userlogin" id="tech_userlogin" class="db_field_name"> <?php $sql="SELECT techID, tech_userlogin FROM technicians"; $result=mysql_query($sql); $options=""; while ($row=mysql_fetch_array($result)) { $techID=$row["techID"]; $tech_userlogin=$row["tech_userlogin"]; $options.="<OPTION VALUE=\"$techID\">$tech_userlogin</option>"; } ?> <OPTION VALUE="">---Select--- <?php echo $options; ?> </SELECT> </code></pre> <p>The form posts to this page:</p> <pre><code><?php include 'sql_connect_R.inc.php'; $id = mysql_real_escape_string($_POST['jobID']); $equip = mysql_real_escape_string($_POST['wo_equip']); $techID = mysql_real_escape_string($_POST['techID']); $tech_login = mysql_real_escape_string($_POST['tech_userlogin']); mysql_query("UPDATE work_orders SET wo_equip = UCASE('$equip'), wo_techID = '$techID', tech_userlogin = '$tech_login' WHERE jobID = '$id'"); mysql_close($con); </code></pre> <p>I'm very new to PHP/MySQL and it took me a couple of days to get something that would put the tech_userlogin into a dropdown box. That is working, but when it posts the techID comes through on both $techID and $tech_userlogin. Could someone please help me sort this out? Any help would be greatly appreciated. Cheers, Spud</p> |
37,181,725 | 0 | How to place 2 divs next to each others with fixed position and 100% Height <p>I'm trying to create 2 <code>div</code>s, one of them is the left sidebar and the other one is the body of the page where content shows up. What I'm trying to do is:</p> <ul> <li>make the sidebar div height 100% </li> <li>the body height 100% too</li> <li>make the body's width change when sidebar width changes.</li> </ul> <p>This is the code that I've tried so far:</p> <pre><code>#Sidebar{ background-color:#F0F0F0; height: calc(100% - 80px); width: 257px; position: fixed; left: 0; bottom: 0; overflow: hidden; white-space: nowrap; } #content { margin: 0; position: fixed; height: 100%; } </code></pre> <p>when I do this, the content <code>div</code> shows IN the Sidebar!</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#Sidebar { height: calc(100% - 80px); width: 257px; position: fixed; top:0; left: 0; bottom: 0; overflow: hidden; white-space: nowrap; border:1px solid #000; } #content { margin: 0; position: fixed; height: 100%; border:1px solid tomato; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><div id="Sidebar"> Hello World!! </div> <div id="content"> Content Div </div></code></pre> </div> </div> Note that i use Jquery .Resizable to change the width. and this is a jsfiddle <a href="https://jsfiddle.net/j64r3bm1/" rel="nofollow">https://jsfiddle.net/j64r3bm1/</a></p> |
13,845,678 | 0 | <p>I'm not sure if this'll make a difference but it's worth a try...I never wrap service arguments with quotes:</p> <pre><code>arguments: [@doctrine.orm.entity_manager] </code></pre> |
14,147,534 | 0 | Can I run an app without GUI on Windows Phone 7, 7.5 and 8? <p>On WP 7 and WP 7.5 I have to develop the app on C#, nonetheless, on WP8 I can develop an app on native C++</p> <p>Assuming the corresponding programming language, I was wondering if it is possible to run a process or an app without GUI on Windows Phone 7, 7.5 and 8.</p> <p>Is it possible? How can I do it? Any example around the web?</p> |
5,444,851 | 0 | <p>I'm not sure if this would work/help, but you could specify something in your application web.xml.</p> <pre><code> <security-constraint> <display-name>Public access</display-name> <web-resource-collection> <web-resource-name>PublicPages</web-resource-name> <description>Public</description> <url-pattern>/servlet/*</url-pattern> </web-resource-collection> <user-data-constraint> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint> <security-constraint> <display-name>Secured access</display-name> <web-resource-collection> <web-resource-name>SecuredPages</web-resource-name> <description>Secured pages</description> <url-pattern>/services/*</url-pattern> </web-resource-collection> <auth-constraint> <description>General Access</description> <role-name>*</role-name> </auth-constraint> <user-data-constraint> <description>SSL not required</description> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>SecurePages</realm-name> </login-config> <security-role> <description>General Access</description> <role-name>*</role-name> </security-role> </code></pre> |
38,550,112 | 0 | <p>Currently you are applying both approach adding fragment and setting adapter remove one of them and for better use.</p> <p>Please follow <a href="https://github.com/codepath/android_guides/wiki/ViewPager-with-FragmentPagerAdapter" rel="nofollow">this</a> example to add fragment with view pager.</p> |
28,918,508 | 0 | <p>Actually, a method with signature <code>public static Image LoadImage(string path</code> isn't even an extension. It is just a static method, therefore to write this as you would like it simply change the class name:</p> <pre><code>public static class Image { public static Image LoadImage(string path) { using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path))) return Image.FromStream(ms); } } </code></pre> |
15,515,520 | 0 | Convert Word document of MS WORD 2003 To Tiff images <p>I have a word document created using MS Office 2003.Now i developed a web application using ASP.net in which i used a file upload control to upload word document files.My requirement is to convert the uploaded word document to tiff/jpg and displayed in iframe.please tell me the possible ways to achieve this.</p> |
40,935,001 | 0 | <p>I think the correct status code in this case is <code>400 Bad Request</code>. The entity you expect must always have a certain line-count, so if it doesn't have that line-count the entity is invalid.</p> <p>Generally validation problems are communicated as 400 errors.</p> |
5,530,499 | 0 | <p>Singular is a computer algebra system. Haskell is a programming language which computer algebra can be implemented within. You need to start simply and just learn basic Haskell syntax and concepts before trying to see the categorical/algebriac picture, especially since different elements can be implemented in different ways.</p> <p>But let's try something simple to establish a common language. The notes I give here should be consistent with the treatment here: <a href="http://en.wikibooks.org/wiki/Haskell/Category_theory" rel="nofollow">http://en.wikibooks.org/wiki/Haskell/Category_theory</a></p> <p>One approach is to describe the category <code>Hask</code>. The objects of <code>Hask</code> are all Haskell types. <code>Hask</code> contains function types, as well as pairs, so it is cartesian closed, and all its arrows are isomorphic to objects. In categorical terms, a hom-set is the collection of all morphisms between two objects. So the hom-set on (Int,Float) is the collection of all functions that turn an Int into a Float. </p> <p>Categorically, a functor between categories X and Y sends the objects of X to Y and the arrows of X to Y. It also therefore sends the hom-sets (collections of arrows) of X to Y.</p> <p>The class <code>Functor</code> in Haskell provides part of what you get with a categorical functor. It provides an operation <code>fmap</code> that sends arrows on objects in <code>Hask</code> to arrows on some other category (which, in our case, must also be composed of <em>some</em> objects from Hask). It can send functions on values to functions on lists of values, or functions on values to functions on pairs which contain values, etc.</p> <p>All that said, I would recommend learning Haskell without thinking about writing type classes or instances at all for some time. Stick to explicit data declarations and functions until you're more comfortable with the basic features of the language.</p> |
38,768,970 | 0 | <p>After using the GPU, you should <a href="http://www.mathworks.com/help/distcomp/reset.html" rel="nofollow">reset the gpu</a> with <code>reset</code> which will </p> <pre><code>dev = gpuDevice(gpu_id); % Do lots of stuff reset(dev) </code></pre> <p>Or you could release the device using empty (<code>[]</code>) inputs</p> <pre><code>gpuDevice([]) </code></pre> |
3,893,863 | 0 | JQuery how do I add new divs using .load? <p>This replaces the content in #message_here, each time. How do I get it to keep adding the content, by creating new divs for each message?</p> <pre><code> var last_mess_id = 1; $('#load_mess').click(function(){ $('#messages_here').load('ajax/get_message.php?last_mess_id='+last_mess_id); last_mess_id++; }) </code></pre> |
10,916,308 | 0 | <p>here is another one :)</p> <pre><code>function flow(elem){ el = $(elem); el.fadeIn('slow').delay(3000).fadeOut('slow', function(){ nextElem = el.is(':last-child') ? el.siblings(':eq(0)') : el.next(); flow(nextElem); }); } $(document).ready(function(){ flow('span:eq(0)') }) </code></pre> <p><a href="http://jsfiddle.net/acrashik/D2VtV/1/" rel="nofollow">Demo at JSFiddle</a></p> |
18,196,196 | 0 | <p>Not sure if I understand correctly, but it sounds like you're looking for <a href="http://knockoutjs.com/documentation/computedObservables.html" rel="nofollow">Computed Observables</a>:</p> <pre><code>self.AvailableItemTypes = ko.computed(function() { var selectedTypeIds = this.SelectedItemTypes().map(function(el) { return el.Id; }); return this.ItemTypes().filter(function(el) { return selectedTypeIds.indexOf(el.Id) === -1; }); }); </code></pre> |
16,511,578 | 0 | <p>It's the order of operation. In <code>p = p * 4/3</code> the compiler is doing:</p> <pre><code>p = (p * 4)/3 </code></pre> <p>However in <code>p *= 4/3</code>, the compiler is doing:</p> <pre><code>p = p * (4/3) </code></pre> <p>4/3 is 1 on the computer because of integer division, so the second example is basically multiplying by 1.</p> <p>Instead of dividing by 3 (an integer), divide by 3.0 (a double) or 3.0f (a float). Then p *= 4/3.0 and p = p * 4/3.0 are the same.</p> |
9,702,801 | 0 | <p>The easiest way to do this is the Linq using</p> <pre><code>var list = new[] { "a", "a", "b", "c", "d", "b" }; var grouped = list .GroupBy(s => s) .Select(g => new { Symbol = g.Key, Count = g.Count() }); foreach (var item in grouped) { var symbol = item.Symbol; var count = item.Count; } </code></pre> |
7,127,980 | 0 | <p>To skip lines that do not match those strings add a check:</p> <pre><code>if any(bool(x) for x in d, HD, HA, M): print ... output.write </code></pre> <p>Try running the script in a debugger:</p> <pre><code>$ python -m pdb your_script.py </code></pre> <p>and see what variables are there and what's wrong. Since PDB is not convenient, you might want to install <a href="http://pypi.python.org/pypi/ipdb" rel="nofollow"><code>ipdb</code></a> or <a href="http://pypi.python.org/pypi/pudb" rel="nofollow"><code>pudb</code></a>.</p> |
14,708,698 | 0 | <p>Keep it simple, son.</p> <pre><code>declare @date1 datetime declare @date2 datetime select @date1 = GETDATE(); select @date2 = '2013-02-02 14:05' select DATEDIFF(hh, @date2, @date1) Results ----------- 71 (1 row(s) affected) </code></pre> |
14,127,792 | 0 | <p>This must work for you</p> <pre><code>var resizeEntryHeight=function(){ $('.collectionPostContainer').each(function(){ $(this).css('height',$(this).width()+'px'); }); } $(document).ready(function(){ resizeEntryHeight(); $(window).resize(resizeEntryHeight()); }); </code></pre> |
11,862,172 | 0 | <p>Use UIDevice Macros - <a href="http://d3signerd.com/tag/uidevice/" rel="nofollow">http://d3signerd.com/tag/uidevice/</a></p> <p>Then you can write code like;</p> <pre><code>if ([DEVICE_TYPE isEqualToString:DEVICE_IPAD]) { } </code></pre> <p>or </p> <pre><code>if (IS_SIMULATOR && IS_RETINA) { } </code></pre> |
13,211,512 | 0 | Android saving images <p>this application i'm working on is suppose to allow a user to take a photo, depending on whether the GPS is enabled or not, the image should be saved into 2 different folders. However, i can't seem to change the directory.</p> <pre><code> camIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss"); String date = dateFormat.format(new Date()); photoFile = "Picture_" + date + ".jpg"; fileName = pictureDir.getPath() + File.separator + photoFile; pictureFile = new File(fileName); Uri outputFileUri = Uri.fromFile(pictureFile); camIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); startActivityForResult(camIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); </code></pre> <p>and in my onActivityResult</p> <pre><code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { if (GPSValid == 0) { pictureDir = new File(Environment .getExternalStorageDirectory().toString() + File.separator + "cameraDemoValid"); } else if (GPSValid == 1) { pictureDir = new File(Environment .getExternalStorageDirectory().toString() + File.separator + "cameraDemoInvalid"); } fileName = pictureDir.getPath() + File.separator + photoFile; pictureFile = new File(fileName); Uri outputFileUri = Uri.fromFile(pictureFile); camIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); </code></pre> <p>However, when i do this, i get a "can't write back - not read at all" error and the image is not saved and if i did include the "camIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);" in onActivityResult(), it works. Am i on the right track?</p> |
13,889,052 | 0 | <p>Use <a href="http://php.net/manual/en/reserved.variables.server.php" rel="nofollow">$_SERVER['DOCUMENT_ROOT']</a> to find the root folder.</p> <pre><code>$dir = $_SERVER['DOCUMENT_ROOT']; // will return /home/vadar/Dropbox/ENELWebsite/public_html/ if(file_exists($dir)){ //just to make sure define('APP_DIR', $dir); //home comp } else{ echo 'No include directory exists'; } </code></pre> |
4,594,046 | 0 | <p>Where i work we will never use a stringbuild becouse of the designer. We dont want the designer in the codebehind if he has to make a simple change. so keep the markup in the view and codebehind in the codebehind. </p> <p><strong>Edit</strong></p> <p>Other advantage of repeater is the change of cycle is much easier. No need to recompile and perhaps redeploy the tweak the UI, just edit the ASPX template, save and refresh.</p> |
14,190,727 | 0 | <p>When sharding you spread the data across different shards. The mongos process routes queries to shards it needs to get data from. As such you only need to look at the data a shard is holding. To quote from <a href="http://docs.mongodb.org/manual/core/sharding/#when-to-use-sharding" rel="nofollow">When to Use Sharding</a>:</p> <blockquote> <p>You should consider deploying a sharded cluster, if:</p> <ul> <li>your data set approaches or exceeds the storage capacity of a single node in your system.</li> <li>the size of your system’s active working set will soon exceed the capacity of the maximum amount of RAM for your system.</li> </ul> </blockquote> <p>Also note that the working set != whole collection. The working set is defined as:</p> <blockquote> <p>The collection of data that MongoDB uses regularly. This data is typically (or preferably) held in RAM.</p> </blockquote> <p>E.g. you have 1TB of data but typically only 50GB is used/queried. That subset is preferably held in RAM.</p> |
32,012,857 | 0 | <p>If <code>"formname"</code> is the value of the name attribute of the form and <code>"name"</code> is the value of the name attribute of the input field (as per your example):</p> <pre><code>if( document.forms["formname"].elements["name"].value == "" ){ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ document.getElementById("namef").innerHTML = "Please imput name"; return false; } </code></pre> |
29,984,885 | 0 | <p>Its better to make use of DRUPAL for your development. </p> |
25,685,544 | 0 | <p>Try replacing the categories route, as create me be taken as a category</p> <pre><code>Route::get('projects/{cat}', ['as' => 'projects.category', 'uses' => 'ProjectsController@category']); Route::get('projects/{cat}', ['as' => 'projects.category', 'uses' => 'ProjectsController@category', 'except' => ['create']]); </code></pre> |
22,383,108 | 0 | Appengine: call endpoints of another module on the same server <p>I am working on an App Engine server which has currently 2 modules. I have the default module used for endpoints and the sync module. This second module is used for syncing my server with another. So my sync module gets data from other servers and has to send it to the default module using endpoints. To do this, I generated endpoints_client_library and added the library to my sync module. I tried a lot of cases but I can't communicate my endpoints properly. Each times I got errors like "401 Unauthorized". </p> <p>So I don't know if it's the right way to use the generated endpoints client library on my server or if there is another solution, maybe simplier...</p> <p>I just want to send data from my sync module to the default.</p> <p>If you need some code, even if it is not very complete and not working at all, just say and I will.</p> <p>The URLFetch code I'm using:</p> <pre><code>AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(Collections.singleton(scope)); URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService(); FetchOptions options = FetchOptions.Builder.doNotFollowRedirects().disallowTruncate(); HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, options); HTTPHeader userAgent = new HTTPHeader("User-Agent", "AppEngine-Google; (+http://code.google.com/appengine; appid: appId)"); request.addHeader(userAgent); HTTPHeader autho = new HTTPHeader("Authorization", "OAuth "+accessToken.getAccessToken()); request.addHeader(autho); HTTPHeader contentType = new HTTPHeader("Content-Type", "application/json"); request.addHeader(contentType); HTTPResponse response = fetcher.fetch(request); int code = response.getResponseCode(); String resp = new String(response.getContent()); System.out.println(code); System.out.println(resp); </code></pre> <p>And the result: </p> <p>401</p> <pre><code>{ "error": { "errors": [ { "domain": "global", "reason": "required", "message": "{\"class\":\"com.domain.server.cloud.CloudException\",\"code\":2}", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "{\"class\":\"com.domain.server.cloud.CloudException\",\"code\":2}" } } </code></pre> |
11,868,768 | 0 | <p>Use a running total.</p> <p>Have a single variable int "calories"</p> <p>Whenever you add a food item add them to calories and display</p> <p>whenever you remove a food item remove them from calories and display</p> |
5,404,906 | 0 | <p>illegalstate exception means am thinking that <strong>thread</strong> you are using is not correctly handling.. can you post your code..so can find where the exact exception happens</p> |
5,633,371 | 0 | Using a gitosis git repository with XCode 4 <p>Hi I've been trying to access my git repository from XCode 4.</p> <p>Everything works just fine using the command line tools. I can clone my repo using:</p> <pre><code>git clone [email protected]:somerepo.git </code></pre> <p>But in XCode, when trying to use:</p> <pre><code>ssh://[email protected]:somerepo.git </code></pre> <p>It just keeps asking me for a password, which I don't want to use at all.</p> <p>The same thing happens with:</p> <pre><code>git://[email protected]:somerepo.git </code></pre> <p>Except that i also get a "Connection refused: unable to connect to a socket" error message.</p> <p>Any idea how to solve this?</p> |
13,892,367 | 0 | <p>You can change the log in the y axis with the following:</p> <pre><code>plt.gca().set_yscale('linear') </code></pre> <p>Or press the L key when the figure is in focus.</p> <p>However, your <code>hist()</code> with <code>log=True</code> does not plot a logarithmic x axis. From the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist" rel="nofollow">docs</a>:</p> <blockquote> <p>matplotlib.pyplot.hist(x, bins=10, ...)</p> <p>bins: Either an integer number of bins or a sequence giving the bins. If bins is an integer, bins + 1 bin edges will be returned, consistent with numpy.histogram() for numpy version >= 1.3, and with the new = True argument in earlier versions. <strong>Unequally spaced bins are supported if bins is a sequence.</strong></p> </blockquote> <p>So if you just set <code>bins=10</code> they will be equally spaced, which is why when you set the xscale to log they have decreasing widths. To get equally spaced bins in a log xscale you need something like:</p> <pre><code>plt.hist(x, bins=10**np.linspace(0, 1, 10)) </code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.