pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
33,602,227 | 0 | <p>Use modulus operator <code>%</code>, this makes sure character stays in range between A to Z. </p> <pre><code>char c = 'A' + shift % 26; </code></pre> <p>You can shift letters to the right, then once letter reaches Z, the next letter will be A</p> <pre><code>int main() { int row, col; for (row = 0; row < 26; row++) { for (col = 0; col < 26; col++) { char c = 'A' + (row + col) % 26; printf("%c ", c); } printf("\n"); } printf("\n"); return 0; } </code></pre> |
1,738,329 | 0 | Should I send retain or autorelease before returning objects? <p>I thought I was doing the right thing here but I get several warnings from the Build and Analyze so now I'm not so sure. My assumption is (a) that an object I get from a function (dateFromComponents: in this case) is already set for autorelease and (b) that what I return from a function should be set for autorelease. Therefore I don't need to send autorelease or retain to the result of the dateFromComponents: before I return it to the caller. Is that right?</p> <p>As a side note, if I rename my function from newTimeFromDate: to gnuTimeFromDate the analyzer does not give any warnings on this function. Is it the convention that all "new*" methods return a retained rather than autoreleased object?</p> <p>In <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH" rel="nofollow noreferrer">Memory Management Programming Guide for Cocoa</a> it says "A received object is normally guaranteed to remain valid within the method it was received" and that "That method may also safely return the object to its invoker." Which leads me to believe my code is correct. </p> <p>However, in <a href="http://oreilly.com/pub/a/mac/excerpt/Cocoa_ch04/index.html" rel="nofollow noreferrer">Memory Management in Cocoa</a> it says "Assume that objects obtained by any other method have a retain count of 1 and reside in the autorelease pool. If you want to keep it beyond the current scope of execution, then you must retain it." Which leads me to think I need to do a retain before returning the NSDate object.</p> <p>I'm developing with Xcode 3.2.1 on 10.6.2 targeting the iPhone SDK 3.1.2.</p> <p><img src="http://nextsprinter.mggm.net/Screen%20shot%202009-11-15%20at%2008.33.00.png" alt="screenshot of build/analyze output"></p> <p>Here's the code in case you have trouble reading the screen shot:</p> <pre><code>//============================================================================ // Given a date/time, returns NSDate for the specified time on that same day //============================================================================ +(NSDate*) newTimeFromDate:(NSDate*)fromDate Hour:(NSInteger)hour Minute:(NSInteger)min Second:(NSInteger)sec { NSCalendar* curCalendar = [NSCalendar currentCalendar]; const unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSDateComponents* comps = [curCalendar components:units fromDate:fromDate]; [comps setHour: hour]; [comps setMinute: min]; [comps setSecond: sec]; return [curCalendar dateFromComponents:comps]; } </code></pre> |
21,976,194 | 0 | <p>Checking for the prior existence of <code>message_id</code> seems to have solved the problem in my particular case:</p> <pre><code>after_commit on: :create do unless self.message_id if email = Mailer.email(self).deliver self.update message_id: email.message_id end end end </code></pre> <p>But I imagine there could be a scenario where I couldn't get away with that, so it'd still be good to understand why an <code>on: :create</code> callback is being called on update.</p> |
36,138,295 | 0 | <p>The classic answer to such questions is to create a SQL VIEW.</p> <p>Views are like dynamic virtual tables - in queries you use the view name instead of a table name, and the DBMS runs the query defined by the view to produce the rows for the query on the view. You therefore see rows based on the data from the tables at the time you access the view, not at the time the view was created.</p> <p>You would create this view with a statement such as</p> <pre><code>CREATE VIEW PROT_WITH_UNITS AS SELECT * FROM dna_extraction_protocols P JOIN measurement_units M ON P.volume_unit = M.id </code></pre> <p>This will give you a view with all columns of both tables, pre-joined on (what I presume to be) the required foreign key.</p> <p>If you get the definition wrong you can drop views just like tables, so you should get there eventually.</p> |
2,726,557 | 0 | <p>You could do this with a bit simpler logic using <code>KeyPress</code> instead, like this:</p> <pre><code>string buffer = ""; //buffer to store what the user typed: n, no, not, etc... void gkh_KeyPress(object sender, KeyPressEventArgs e) { buffer += e.KeyChar; //add key to the buffer, then check if we've made progress if (buffer.IndexOf("note") > -1) { this.Show(); //"notes" matched completely buffer = ""; //reset for another run } else if ("note".IndexOf(buffer) != 0) { buffer = ""; //Another key not in sequence was hit } } </code></pre> |
3,434,046 | 0 | Problem in M3G rendering in J2ME <p>I have made 3 planes and positioned them in a way that they make a corner of cube. (For some reasons I don't want to make a cube object). The 3 planes have 3 different Texture2Ds with different images. The strange problem is when I render the 3 objects and start rotating the camera, in some perspectives some parts of these 3 planes don't get rendered. For example when I look straight at the corner a hole is created which is shaped as a triangle. This is the image of the problem in a netbeans emulator: <img src="http://www.pegahan.com/m3g.jpg" alt="alt text"> I put the red lines there so you can see the cube better. The other strange thing is that the problem resolves when I set the scale of the objects to 0.5 or less. By the way the camera is in its default position and the cube's center is at (0,0,0) and each plane has a width and height of 2. Does anyone have any ideas why these objects have a conflict with each other and how could I resolve this problem.</p> <p>Thanks in advance</p> |
15,868,328 | 0 | <p>I've found what happens, and it can be usefull for others. @Mark Ormston was not so far : Cookies set with path /cas are send by IE10 to URL beginings with /cas-services</p> <p>In my case /cas and /cas-services are not in the same WebApp and each have its own JSESSIONID. Sending JSESSIONID created for /cas to /cas-services lead to the problem describe above.</p> <p>To correct, I simply rename /cas-services with /app-services (I guess that everything not beginning with /cas should work).</p> <p>JM.</p> |
32,132,528 | 0 | Akka-Http + Twitter streaming API <p>I recently got an interest into trying out some of the streaming capabilities in the Scala world. This happened while I was reading up on the Iteratee API in Play 2.</p> <p>However, people seem to think the Iteratee API is close to deprecation, and have recommended me one of the following libs:</p> <ul> <li>scalaz-stream</li> <li>akka-streams, or more specifically, akka-http</li> </ul> <p>I didn't really feel like getting into the scalaz world, so I decided to check out akka-http.</p> <p>Unfortunately, documentation seems to be very sparse on the subject of akka-http at the moment, and I'm having a lot of trouble getting everything to work.</p> <p>As per usual, I chose everyone's favourite source of streaming data to play around with: Twitter.</p> <p>Googling the subject mostly leads to either</p> <ul> <li>Matthias Nehlsens's excellent work on his <a href="http://matthiasnehlsen.com/blog/2013/09/10/birdwatch-explained/" rel="nofollow">BirdWatch project</a>. Unfortunately, he still uses the Iteratees.</li> <li>People using akka-streams with a Twitter client, but I'm not very fond of using those, as I won't be really learning much from those.</li> </ul> <p>Performing a basic GET request with akka-http seems to be structured somewhat like this:</p> <pre><code>object AkkaHttpExample extends App { implicit val system = ActorSystem("akka-http-example") implicit val materializer = ActorMaterializer() import system.dispatcher val connectionFlow: Flow[HttpRequest, HttpResponse, Future[Http.OutgoingConnection]] = Http().outgoingConnection("www.stackoverflow.com", 80) val request: HttpRequest = HttpRequest( HttpMethods.GET, uri = "/" ) val future: Future[HttpResponse] = Source.single(request) .via(connectionFlow) .runWith(Sink.head) val result: HttpResponse = Await.result(future, 5 seconds) } </code></pre> <p>The code above works (though parsing the body of the results is pretty annoying for some reason).</p> <p>When I try to do the same but pointing to the <code>/1.1/statuses/sample.json</code> endpoint (which should emit an example stream), my Future just sits there and times out. While this may seem logical given the streaming nature of the data, this should instead return a 404, because at this point I'm not even doing proper OAuth.</p> <p>For reference, this is my code so far at this point:</p> <pre><code>object AkkaHttpExample extends App { implicit val system = ActorSystem("akka-http-example") implicit val materializer = ActorMaterializer() import system.dispatcher val connectionFlow: Flow[HttpRequest, HttpResponse, Future[Http.OutgoingConnection]] = Http().outgoingConnection("stream.twitter.com", 80) val request: HttpRequest = HttpRequest( HttpMethods.GET, uri = "/1.1/statuses/sample.json" ) val future: Future[HttpResponse] = Source.single(request) .via(connectionFlow) .runWith(Sink.head) val result: HttpResponse = Await.result(future, 50 seconds) } </code></pre> <p>Like I said, I figured that maybe the streaming nature of this might be causing the problem regardless, so I tried to change my code to handle the chunks one by one based on the only examples I could find, as shown here:</p> <pre><code>object AkkaHttpExample extends App { implicit val system = ActorSystem("akka-http-example") implicit val materializer = ActorMaterializer() import system.dispatcher val connectionFlow: Flow[HttpRequest, HttpResponse, Future[Http.OutgoingConnection]] = Http().outgoingConnection("stream.twitter.com", 80) val request: HttpRequest = HttpRequest( HttpMethods.GET, uri = "/1.1/statuses/sample.json" ) Source.single(request) .via(connectionFlow) .map(_.entity.dataBytes) .flatten(FlattenStrategy.concat) .map(_.decodeString("UTF-8")) .runForeach(println _) .onComplete(_ => system.terminate()) } </code></pre> <p>This causes the application to terminate immediately. Remove the <code>.onComplete</code> clause keeps the ActorSystem and the application running, but nothing seems to actually happen :'(</p> <p>Does anyone have any experience with this? The library has been one huge headache so far. Should I go back to Play + WS + Iteratees?</p> |
8,669,640 | 0 | <p>Debugging itself is the process of finding and exterminating bugs, nothing more and nothing less. So unless you're a perfect programmer who never makes any mistakes, you've done it.</p> <p>A <em>debugger</em>, on the other hand, is a tool which assists in debugging. You can still debug without a debugger, but using a debugger gives you more options, and ways to go about it.</p> <p>Without you mentioning specifically which debugger you're talking about (Visual Studio one, or gdb, or...) we can't really tell you how to use it, but, in a nutshell:</p> <p>A debugger will let you execute the code one instruction at a time, or one line at a time. It will let you run your code until a place you're interested in, then stop. While the code is stopped, you can inspect the values of the variables to make sure things are in order, and in some cases even modify things on the run to test various scenarios.</p> <p>Some of the techniques of debugging without using a debugger are:</p> <ul> <li>print insertion, where you litter your code with printing commands that will allow you to track the state of your code while it is running,</li> <li>code reading, where you read the code and try to find the places where your intention differs from what is actually written</li> <li>mug conversations, where you try to explain your code to your friend (or a mug, or a penguin doll on your desk), and in the process see where your logic goes wrong</li> <li>binary cut search, where you delete chunks of your code at a time and see if the error is still present</li> </ul> <p>and many more.</p> |
11,572,205 | 0 | Attribute not accessible via Rspec <p>Models:</p> <pre><code>class User < ActiveRecord:Base has_many :roles has_many :networks, :through => :roles end class Network < ActiveRecord:Base has_many :roles has_many :network, :through => :roles end class Role < ActiveRecord:Base attr_accesible :user_id, :network_id, :position belongs_to :user belongs_to :network end </code></pre> <p>The default for role is "member"</p> <p>In the console I can type:</p> <pre><code>> @role = Role.find(1) > @role.position => "member" </code></pre> <p>But in my Rspec tests, I use FactoryGirl to create a user, network, and role. And I have the test <code>@role.should respond_to(:position)</code> I have also tried just assigning it <code>@role.position = "admin"</code>. And no matter what, I get an error like:</p> <pre><code>Failure/Error: @role.should respond_to(:position) expected [#<Role id:1, user_id: 1, position: "member", created_at...updated_at...>] to respond to :position </code></pre> <p>Am I missing something very basic?</p> <p>EDIT:</p> <p>factories.rb</p> <pre><code>FactoryGirl.define do factory :user do name "Example User" sequence(:email) {|n| "email#{n}@program.com"} end factory :network do sequence(:name) {|n| "Example Network #{n}"} location "Anywhere, USA" description "Lorem Ipsum" end factory :role do association :user association :network position "member" end end </code></pre> <p>network_controller_spec</p> <pre><code>... before(:each) do @user = test_sign_in(FactoryGirl.create(:user) @network = FactoryGirl.create(:network) @role = FactoryGirl.create(:role, :user_id => @user.id, :network_id = @network.id) #I have also tried without using (_id) I have tried not setting the position in the factories as well. end it "should respond to position" do get :show, :id => @network # This may not be the best or even correct way to find this. But there should only be one, and this method works in the console. @role = Role.where(:user_id => @user.id, :network_id => @network.id) @role.should respond_to(:position) end </code></pre> |
23,324,249 | 0 | <p>I found this solution that works for me</p> <p>map.addMarker(markerIndex, {coords: [(e.offsetX / map.scale) - map.transX, (e.offsetY / map.scale) - map.transY]});</p> <p>No matter if zooming in or not, the positioning is compensated.</p> <p>Lorenzo</p> |
6,948,643 | 0 | Curious about the implementation of Control.Invoke() <p>What exactly does Control.Invoke(Delegate) do to get the delegate to run on the GUI thread? Furthermore, Its my understanding that invoke will block until the invoked function its done. How does it achieve this?</p> <p>I would like some good gritty details. I'm hoping to learn something interesting.</p> |
22,238,011 | 0 | <p>You should set the new image to the <code>ImageView</code> like this:</p> <pre><code>imagem = (ImageView)findViewById(R.id.imageBody); imagem.setImageResource(R.drawable.my_image); </code></pre> <p>Also note that method <code>rgsexo.getCheckedRadioButtonId()</code> doesn't give you an id from R class, but the id you need to set to the button via <code>setId(int id)</code> method before, i.e. in xml layout file. Maybe it's better to differ your two buttons in group via index as follows:</p> <pre><code>int radioButtonID = radioButtonGroup.getCheckedRadioButtonId(); View radioButton = radioButtonGroup.findViewById(radioButtonID); int idx = radioButtonGroup.indexOfChild(radioButton); </code></pre> <p>So the whole method would be:</p> <pre><code>private String interpretIMC(float imcValue) { imagem = (ImageView)findViewById(R.id.imageBody); rgsexo = (RadioGroup)findViewById(R.id.rgSexo); int selectedId = rgsexo.getCheckedRadioButtonId(); // get the id View radioButton = radioButtonGroup.findViewById(radioButtonID); int idx = radioButtonGroup.indexOfChild(radioButton); switch (idx) // switch on the button selected { case 0: if (imcValue < 20) { imagem.setImageResource(R.drawable.slim); return "Abaixo do Peso"; } else if (imcValue < 24.9) { imagem.setImageResource(R.drawable.normal); return "Peso Normal"; } else if (imcValue < 29.9) { imagem.setImageResource(R.drawable.fat); return "Acima do Peso"; } else if (imcValue < 39.9) { imagem.setImageResource(R.drawable.fat); return "Obesidade Moderada"; } else { imagem.setImageResource(R.drawable.fat); return "Obesidade Mórbida"; } break; case 1: if (imcValue < 19) { return "Abaixo do Peso"; } else if (imcValue < 23.9) { return "Peso Normal"; } else if (imcValue < 28.9) { return "Acima do Peso"; } else if (imcValue < 38.9) { return "Obesidade Moderada"; } else { return "Obesidade Mórbida"; } break; } } </code></pre> |
40,188,059 | 0 | <p>This is due to Anaconda's virtual environments'. The "Root" kernel that you see is from Anaconda's environment that is created upon installation. In order to install other kernels for various versions of python see <a href="http://ipython.readthedocs.io/en/stable/install/kernel_install.html" rel="nofollow">http://ipython.readthedocs.io/en/stable/install/kernel_install.html</a>.</p> |
13,219,164 | 0 | changing a typed dataset field type <p>I have a project, within which I have two classes, one is an enumeration, that descends from Byte.This class is called Status. The other class , is a TypedDataSet. It is in the same namespace of the enumeration class. I try to change the type of one field of this typed dataset, that by now is Byte, to Status. But I get the following error from VIsual Studio( 2008):" Field type changing Column requires a valid DataType". I have done this operation in other project, so I don't understand this error, besides Status enumeration members are byte too.. this is the code: @Hogan. Here is the enumeration Status:</p> <pre><code>namespace LinQToDataset { public enum Status : byte { Created, Accepted, Fixed, Reopened, Closed, } } </code></pre> <p>And here is the field of the typed dataset whose type I want to change to Status(instead of byte). The field is called Status as well: </p> <pre><code>[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public byte Status { get { return ((byte)[this.tableDefect.StatusColumn])); } set { this[this.tableDefect.StatusColumn] = value; } } </code></pre> <p>an anyone help me please?</p> |
16,340,714 | 0 | Wordpress Plugin for Soundcloud giving "Track currently not available" <p>So I am using wordpress to build a website with the soundcloud plugin. The shortcode for 3 out of 4 songs is working fine but the fourth just shows up as "Track currently not available". The track is playable on soundcloud just fine.</p> <p>Here is the webpage where its happening:</p> <p><a href="http://lostintheholler.com/epk/?page_id=13" rel="nofollow">http://lostintheholler.com/epk/?page_id=13</a></p> <p>and here is the track on soundcloud:</p> <p><a href="https://soundcloud.com/lostintheholler/07-take-it-and-go" rel="nofollow">https://soundcloud.com/lostintheholler/07-take-it-and-go</a></p> <p>The wordpress embed code from soundcloud works fine too but it doesn't have the look you get from using the plugin. </p> <p>Thanks!</p> |
17,059,858 | 0 | <p>The active selector doesn't work with in page jump anchors, only with external anchors. With in page jump anchors, active selector will apply style to all in page anchors. It will work with external links, for example when you have a webpage with a menu apering on every page, active selector can be used to evidentiate in the menu the page you are currently on.</p> <p>In your case, you can try to use focus selector instead.</p> |
21,091,313 | 0 | <p>The specific addresses returned by malloc are selected by the implementation and not always optimal for the using code. You already know that the speed of moving memory around depends greatly on cache and page effects.</p> <p>Here, the specific pointers malloced are not known. You could print them out using <code>printf("%p", ptr)</code>. What is known however, is that using just one malloc for two blocks surely avoids page and cache waste between the two blocks. That may already be the reason for the speed difference.</p> |
39,281,702 | 0 | <p>Anand S Kumar's answer doesn't round to the nearest quarter hour, it cuts off the minutes to the nearest 15 minutes below it. </p> <p>Actually, in your example <code>2015-07-18 13:53:33.280</code> should round to <code>2015-07-18 14:00:00.000</code> since <code>53:33.280</code> is closer to 60 minutes than 45 minutes.</p> <p>I found an more robust answer for rounding in <a href="http://stackoverflow.com/questions/3463930/how-to-round-the-minute-of-a-datetime-object-python">this post</a>.</p> <p>For your situation this should work:</p> <pre><code>import datetime def round_time(time, round_to): """roundTo is the number of minutes to round to""" rounded = time + datetime.timedelta(minutes=round_to/2.) rounded -= datetime.timedelta(minutes=rounded.minute % round_to, seconds=rounded.second, microseconds=rounded.microsecond) return rounded dt['dtcolumn'] = df['dtcolumn'].apply(lambda x: round_time(x)) </code></pre> |
14,404,991 | 0 | <p>It is only with borders. When you see arrows like this, the developer most likely used pseudo elements to create them. Basically what happens is you create a transparent box without content, and since there is nothing there, all you see is the one corner of the border. This conveniently looks just like an arrow.</p> <p>How to do it:</p> <pre><code>.foo:before { content: ' '; height: 0; position: absolute; width: 0; border: 10px solid transparent; border-left-color: #333; } </code></pre> <p><a href="http://jsfiddle.net/fGSZx/">http://jsfiddle.net/fGSZx/</a></p> <p>Here are some resources to help:</p> <p><a href="http://css-tricks.com/snippets/css/css-triangle/">CSS Triangle from CSS-Tricks</a> (this should clear everything up)</p> <p><a href="http://coding.smashingmagazine.com/2011/07/13/learning-to-use-the-before-and-after-pseudo-elements-in-css/">Smashing Mag article about :before and :after</a></p> |
20,643,311 | 0 | <p>You can use the <code>collect_max</code> UDF from Brickhouse ( <a href="http://github.com/klout/brickhouse" rel="nofollow">http://github.com/klout/brickhouse</a> ) to solve this problem, passing in a value of 1, meaning that you only want the single max value.</p> <pre><code>select array_index( map_keys( collect_max( carrier_id, meandelay, 1) ), 0 ) from flightinfo; </code></pre> <p>Also, I've read somewhere that the Hive <code>max</code> UDF does allow you to access other fields on the row, but I think its easier just to use <code>collect_max</code>.</p> |
7,340,309 | 0 | Throw Exception inside a Task - "await" vs Wait() <pre><code>static async void Main(string[] args) { Task t = new Task(() => { throw new Exception(); }); try { t.Start(); t.Wait(); } catch (AggregateException e) { // When waiting on the task, an AggregateException is thrown. } try { t.Start(); await t; } catch (Exception e) { // When awating on the task, the exception itself is thrown. // in this case a regular Exception. } } </code></pre> <p>In TPL, When throwing an exception inside a Task, it's wrapped with an AggregateException.<br> But the same is not happening when using the <strong>await</strong> keyword.<br> What is the explanation for that behavior ?</p> |
16,391,288 | 0 | <p>As the compiler is trying to tell you, you can't use <code>==</code> to compare a string with a character. The <code>==</code> operator works differently for primitives (such as a <code>char</code>) and reference types (such as a <code>String</code>) so conditions like <code>if(encrypt == 'U')</code> are nonsensical.</p> |
35,875,343 | 0 | How to make method that turns number grades into letter grades in Java <p>I am trying to write a method in Java that turns number grades into letter grades, but there is an error with the returns that I do not understand why. Any input would be appreciated.</p> <pre><code>import java.util.*; import static java.lang.System.out; public class Lab26 { public static void main(String[] args) { } public static String letterGrade(double grade) { String a = "A"; String b = "B"; String c = "C"; String d = "D"; String f = "F"; if (grade <= 100 && grade >= 90) { return a; } else if (grade < 90 && grade >= 80) { return b; } else if (grade < 80 && grade >= 70) { return c; } else if (grade < 70 && grade >= 60) { return d; } else if (grade < 60) { return f; } } } </code></pre> |
18,677,388 | 0 | <p>Try using a content script, injected into the web page, instead of a background script. Use this in your manifest.json:</p> <pre><code>"content_scripts" : [{ "js" : ["myScript.js"] }] "permissions": [ "tabs", "http://*/*", "https://*/*" ] </code></pre> <p>However, chrome extensions are sandboxed from other scripts in the page. However, you do have access to the DOM and you can inject your own tags. So, create a new <code><script></code> tag and append it to the DOM, and the new script (script.js) it references can include the event listeners you want.</p> <p>background.js:</p> <pre><code>chrome.runtime.onConnect.addListener(function(port) { port.onMessage.addListener(function(msg) { enableEXT = msg.enableEXT; }); }); chrome.webRequest.onHeadersReceived.addListener(function(details) { for (var i = 0; i < details.responseHeaders.length; ++i) { if (details.responseHeaders[i].name.toLowerCase() == 'content-type' && !enableEXT) details.responseHeaders[i].value = 'application/xyz'; } return {responseHeaders: details.responseHeaders}; }, {urls: ["<all_urls>"]}, ['blocking', 'responseHeaders']); </code></pre> <p>myScript.js:</p> <pre><code>//to inject into the page var s = document.createElement('script'); s.src = chrome.extension.getURL("script.js"); s.onload = function() { this.parentNode.removeChild(this); }; (document.head||document.documentElement).appendChild(s); //to communicate with our background var port = chrome.runtime.connect(); window.addEventListener("message", function(event) { // We only accept messages from ourselves if (event.source != window) return; if (event.data.type && (event.data.type == "FROM_PAGE")) { port.postMessage(event.data); } }, false); </code></pre> <p>script.js:</p> <pre><code>window.onkeydown = function() { if (event.keyCode == 70) window.postMessage({ enableEXT: true, "*"); }; window.onkeyup = function() { window.postMessage({ enableEXT: false, "*"); }; </code></pre> <p>To communicate between your injected code, your content script, and your background page is a very awkward situation, but can be dealt with, with all the postMessage APIs...</p> |
31,597,500 | 0 | Update some json items in existing file <p>i'm trying to do a simple script to manipulate some json, so i decode the json file , create a foreach to make some ifs looking for information with live games, live.json file:</p> <pre><code>{ Match: [ { Id: "348324", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Joinville", HomeTeam_Id: "1208", HomeGoals: "1", AwayTeam: "Ponte Preta", AwayTeam_Id: "745", AwayGoals: "1", Time: "67", Location: "Arena Joinville", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } }, { Id: "348319", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Cruzeiro", HomeTeam_Id: "749", HomeGoals: "1", AwayTeam: "Avai FC", AwayTeam_Id: "1203", AwayGoals: "1", Time: "Finished", Location: "Mineirão", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } } </code></pre> <p>Check the comments in the code i specify what i want in each part.</p> <pre><code> <?php $json_url = "http://domain.com/live.json"; // the file comes with live games $json = file_get_contents($json_url); $links = json_decode($json, TRUE); foreach($links["Match"] as $key=>$val) { if($val['Id'] == "live games id") // i want to live.json games ids match with the games with the same id in file.json // i only want to update the items below, and { $links["Match"][$key]['Time'] = ['Time']; // in the end i just want to get the item Time to update file.json in item time for the game with the same id $links["Match"][$key]['HomeGoals'] = ['HomeGoals']; // similar to what i want with Time $links["Match"][$key]['AwayGoals'] = ['AwayGoals']; } } $fp = fopen( "file.json","w+"); // this file have the list of all games including the ones that came from live.json, the structure are exactly the same. fwrite($fp,json_encode($links)); fclose($fp); ?> </code></pre> <p>The content of new file.json</p> <pre><code>{ Match: [ { Id: "348324", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Joinville", HomeTeam_Id: "1208", HomeGoals: "1", AwayTeam: "Ponte Preta", AwayTeam_Id: "745", AwayGoals: "1", Time: "69", Location: "Arena Joinville", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } }, { Id: "348319", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Cruzeiro", HomeTeam_Id: "749", HomeGoals: "1", AwayTeam: "Avai FC", AwayTeam_Id: "1203", AwayGoals: "1", Time: "Finished", Location: "Mineirão", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } } </code></pre> <p>Somebody can help ? What is the best approach to do this ?</p> |
13,039,570 | 0 | onmouseover transition effect without jQuery <p>I use onmouseover for hover effects of the main site logo on my dev site <a href="http://www.new.ianroyal.co" rel="nofollow">http://www.new.ianroyal.co</a>. </p> <p>onmouseover changes the site logo image instantaneously, I was wondering if I could apply a transition effect (fade in, or just generally slow down the transition speed) without using jQuery. </p> <p>Here is my code</p> <blockquote> <blockquote> <blockquote> <blockquote> <p><code><a href="<?php echo esc_url( home_url( '/' ) ); ?>" ONMOUSEOVER='ian.src="http://new.ianroyal.co/wp-content/themes/twentytwelve/images/IN-Logo.png" '<br> ONMOUSEOUT='ian.src="http://new.ianroyal.co/wp-content/themes/twentytwelve/images/IN-Logo1.png" '><img src="http://new.ianroyal.co/wp-content/themes/twentytwelve/images/IN-Logo1.png" NAME="ian" class="header-image" alt="Ian Nelson"/></a></code></p> </blockquote> </blockquote> </blockquote> </blockquote> <p>I've searched and searched but it seems the only solultions are with jQuery which I don't have a good enough grasp of yet. </p> <p>Thank you</p> |
27,265,129 | 0 | <blockquote> <pre><code>can't instantiate class com.example.mealplan.MainActivity </code></pre> </blockquote> <p>Abstract classes cannot be instantiated. Remove the <code>abstract</code> from your class declaration.</p> |
3,734,371 | 0 | How to avoid cyclic behaviour with Castle Windsor's CollectionResolver? <p>I am using Castle Windsor 2.5 in my application. I have a service which is a composite that acts as a distributor for objects that implement the same interface.</p> <pre><code>public interface IService { void DoStuff(string someArg); } public class ConcreteService1 : IService { public void DoStuff(string someArg) { } } public class ConcreteService2 : IService { public void DoStuff(string someArg) { } } public class CompositeService : List<IService>, IService { private readonly IService[] decoratedServices; CompositeService(params IService[] decoratedServices) { this.decoratedServices = decoratedServices; } public void DoStuff(string someArg) { foreach (var service in decoratedServices) { service.DoStuff(someArg); } } } </code></pre> <p>The problem I have is that using config such as that shown below causes Windsor to report that "A cycle was detected when trying to resolve a dependency."</p> <pre><code>windsor.Register( Component .For<IService>() .ImplementedBy<CompositeService>(), Component .For<IService>() .ImplementedBy<ConcreteService1>(), Component .For<IService>() .ImplementedBy<ConcreteService2>() ); </code></pre> <p>This cyclic behaviour seems to be at odds with the standard (non-collection based) behaviour that can be used to implenent the decorator pattern, where the component being resolved is ignored and the next registered component that implements the same interface is used instead.</p> <p>So what I'd like to know is whether or not there is a way to make Windsor exclude the <code>CompositeService</code> component when it's resolving the <code>IService</code> services for the <code>decoratedServices</code> property. The <code>decoratedServices</code> property should contain two items: an instance of <code>ConcreteService1</code>, and an instance of <code>ConcreteService2</code>. I'd like to do this without explicitly specifying the dependencies.</p> |
9,234,566 | 0 | <p>Use <code>'body'</code> instead of <code>page</code>. <code>page</code> is not a defined variable.</p> <pre><code>$(document).ready(function() { var Side = $('body').text(); alert( Side ); }); </code></pre> <p>Other options are <code>document</code> or <code>html</code>, but these would also include non-body text, such as the contents of the <code><title></code> tags.</p> <p>If you want to strip out the JavaScript, you can use:</p> <pre><code>var Side = $('body').clone(); Side.find('script').remove(); // Remove <script> elements, etc. Side = Side.text(); </code></pre> <p>If you really want to strip all invisible items, use:</p> <pre><code>Side.find(':hidden').remove(); // instead of the second line </code></pre> |
18,490,825 | 0 | <p>Yes, you can just use <code>+-</code> operators if you want to add or subtract two numbers.</p> <p>If you want to truncate the result back to 16 bits, just assign the result to a 16 bit wire/register, and it will automatically drop the upper bits and just assign the lower 16 bits to <code>out</code>. In some cases this may create a lint warning, so you may want to assign the result to an intermediate variable first, and then do an explicit part select.</p> <pre><code>wire [15:0] out; wire [15:0] A; wire [31:0] A_rotate; A_rotate = {A,A} << N; out = A_rotate[15:0]; </code></pre> |
21,231,328 | 0 | keeping control with the same handle between form loads <p>I got a form with a control i draw on with another application. The other application loads to slow to start it each time i show my window. So i load the secondary application in advance. I use a control handle as argument, telling the application wich handle to draw on. This works fine the first time. When i close my dialog (clicking the ok button, setting the dialog result to ok) and open it again, the control handle changed.</p> <p>How can i keep my control handle the same between two loads of the dialog?</p> <pre><code>public partial class ListForm : Form { FilterDialog filterDialog; public ListForm() { InitializeComponent(); filterDialog = new FilterDialog(); //this is where i load my second form, wich i draw in } </code></pre> <p>the Dialog i draw in</p> <pre><code>public FilterDialog() { InitializeComponent(); string applicationlocation = @"..."; //set the argument string hexvalue = btnImage.Handle.ToInt32().ToString("X8"); process.StartInfo.Arguments = "0x" + hexvalue; process.StartInfo.FileName = applicationlocation; process.StartInfo.UseShellExecute = false; process.Start(); } private void FilterDialog_Load(object sender, EventArgs e) { if (this.filter != string.Empty) txtFilter.Text = filter; } </code></pre> |
15,837,751 | 0 | <blockquote> <p>Can an aggregates invariant include a rule based on information from elsewhere?</p> </blockquote> <p>Aggregates can always use the informations in their own states and the argument that their <a href="http://epic.tesio.it/doc/manual/command_query_separation.html" rel="nofollow">commands</a> recieves.</p> <p>Someone use to access applicative services via singletons, service locators and so on, but IMO, that's a smell of tightly coupled applications. They forget that methods' arguments are effective dependency injectors! :-)</p> <blockquote> <p>In DDD can an aggregates invariant include a rule based on information in a another aggregate?</p> </blockquote> <p>No.<br> Except if the second aggregate is provided via commands' arguments, of course. </p> <p><strong>WARNING ! ! !</strong></p> <blockquote> <p>I have an entity called Asset (equipment)...<br> ... (and a) second aggregate called AssetType...</p> </blockquote> <p>The last time that I had to cope with a similar structure, it was a pain.</p> <p>Chances are that you are choosing the wrong abstractions.</p> <blockquote> <p>have I got my invariant wrong?</p> </blockquote> <p>Probably... Did you asked to the <strong>domain expert</strong>? Does <strong>he</strong> talks about "TagTypes"?</p> <p><a href="http://epic.tesio.it/doc/manual/solid_principles.html#about_liskov_substitution" rel="nofollow">You should never abstract on your own</a>.</p> <p>Entities of type <code>X</code> holding a reference to an instance of an <code>X-Type</code> are almost always a smell of over-abstraction, that in the hope of reuse, makes the model rigid and inflexible to business evolution.</p> <p><strong>ANSWER</strong></p> <p>If <em>(and only if)</em> the domain expert actually described the model in these terms, a possible approach is the following:</p> <ol> <li>you can create an <code>AssetType</code> class with a factory method that turns an <code>IEnumerable<Tag></code> into a <code>TagSet</code> <a href="http://epic.tesio.it/2013/03/04/exceptions-are-terms-ot-the-ubiquitous-language.html" rel="nofollow">and throws</a> either <code>MissingMandatoryTagException</code> or <code>UnexpectedTagException</code> if some of the tag is missing or unexpected. </li> <li>in the <code>Asset</code> class, a command <code>RegisterTags</code> would accept an <code>AssetType</code> and an <code>IEnumerable<Tag></code>, throwing the <code>MissingMandatoryTagException</code> and <code>WrongAssetTypeException</code> (note how important are exceptions to ensure invariants).</li> </ol> <p><strong>edit</strong><br> something like this, but much more documented:</p> <pre class="lang-cs prettyprint-override"><code>public class AssetType { private readonly Dictionary<TagType, bool> _tagTypes = new Dictionary<TagType, bool>(); public AssetType(AssetTypeName name) { // validation here... Name = name; } /// <summary> /// Enable a tag type to be assigned to asset of this type. /// </summary> /// <param name="type"></param> public void EnableTagType(TagType type) { // validation here... _tagTypes[type] = false; } /// <summary> /// Requires that a tag type is defined for any asset of this type. /// </summary> /// <param name="type"></param> public void RequireTagType(TagType type) { // validation here... _tagTypes[type] = false; } public AssetTypeName Name { get; private set; } /// <summary> /// Builds the tag set. /// </summary> /// <param name="tags">The tags.</param> /// <returns>A set of tags for the current asset type.</returns> /// <exception cref="ArgumentNullException"><paramref name="tags"/> is <c>null</c> or empty.</exception> /// <exception cref="MissingMandatoryTagException">At least one of tags required /// by the current asset type is missing in <paramref name="tags"/>.</exception> /// <exception cref="UnexpectedTagException">At least one of the <paramref name="tags"/> /// is not allowed for the current asset type.</exception> /// <seealso cref="RequireTagType"/> public TagSet BuildTagSet(IEnumerable<Tag> tags) { if (null == tags || tags.Count() == 0) throw new ArgumentNullException("tags"); TagSet tagSet = new TagSet(); foreach (Tag tag in tags) { if(!_tagTypes.ContainsKey(tag.Key)) { string message = string.Format("Cannot use tag {0} in asset type {1}.", tag.Key, Name); throw new UnexpectedTagException("tags", tag.Key, message); } tagSet.Add(tag); } foreach (TagType tagType in _tagTypes.Where(kvp => kvp.Value == true).Select(kvp => kvp.Key)) { if(!tagSet.Any(t => t.Key.Equals(tagType))) { string message = string.Format("You must provide the tag {0} to asset of type {1}.", tagType, Name); throw new MissingMandatoryTagException("tags", tagType, message); } } return tagSet; } } public class Asset { public Asset(AssetName name, AssetTypeName type) { // validation here... Name = name; Type = type; } public TagSet Tags { get; private set; } public AssetName Name { get; private set; } public AssetTypeName Type { get; private set; } /// <summary> /// Registers the tags. /// </summary> /// <param name="tagType">Type of the tag.</param> /// <param name="tags">The tags.</param> /// <exception cref="ArgumentNullException"><paramref name="tagType"/> is <c>null</c> or /// <paramref name="tags"/> is either <c>null</c> or empty.</exception> /// <exception cref="WrongAssetTypeException"><paramref name="tagType"/> does not match /// the <see cref="Type"/> of the current asset.</exception> /// <exception cref="MissingMandatoryTagException">At least one of tags required /// by the current asset type is missing in <paramref name="tags"/>.</exception> /// <exception cref="UnexpectedTagException">At least one of the <paramref name="tags"/> /// is not allowed for the current asset type.</exception> public void RegisterTags(AssetType tagType, IEnumerable<Tag> tags) { if (null == tagType) throw new ArgumentNullException("tagType"); if (!tagType.Name.Equals(Type)) { string message = string.Format("The asset {0} has type {1}, thus it can not handle tags defined for assets of type {2}.", Name, Type, tagType.Name); throw new WrongAssetTypeException("tagType", tagType, message); } Tags = tagType.BuildTagSet(tags); } } </code></pre> |
32,453,071 | 0 | Nested JSON PHP decode <p>I have the following Json file </p> <pre><code>{ "username”: “userabc”, “locations”: [ { “locationId": "2123", “locationName": "Test Site", “setupDate”: "0000-00-00", “dataType”: { “book”: [ { “bookId": “1257245", “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" }, { “bookId": “4257245", “information”: “Infotag 11”, “addedDate": "0000-00-00 00:00:00" }, { “bookId": “2227242”, “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" } ], “tape”: [ { “tapeId": “1220”, “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" }, { “tapeId": “1320”, “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" } ], “record”: [ { “recordId": “a21322”, “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" }, { “recordId": “b213222”, “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" } ], "virtual": [ { “virtId": "2123", “information”: "57235", “addedDate”: "0000-00-00 00:00:00", } ] } } ] } </code></pre> <p>I'm currently trying to access the nested part of (to count the number of bookIDs). I have done the following, can print the locationName but I am unable to print the bookId, I'm not sure where I'm going wrong.</p> <pre><code>$obj = json_decode($json,true); foreach($obj['locations'] as $chunk) { $locName = $chunk['locationName']; echo $locName; } </code></pre> <p>This is the part I am having problems with, I am not able to see any results?</p> <pre><code>foreach($obj['locations']['book'] as $chunk) { $bkId = $chunk['bookId']; echo $bkId; } </code></pre> |
4,373,138 | 0 | Read string in Objective-C console application? <p>What is the best way to read string input from a simple Objective-C console application?</p> <p>I would just like to store the input as an NSString variable.</p> <p>I've seen multiple people post about <code>scanf</code>, <code>gets</code> and others, but they everyone seems to say that they're "unreliable", or "open to attack".</p> <p>I can see how this could be true for <code>gets</code> but I'm looking for the best possible way to do this.</p> <p>Thanks!</p> |
27,998,642 | 0 | Laravel assertions full list <p>PHP Laravel framework provides assertion methods like <code>->assertTrue()</code>, <code>->assertFalse()</code> for unit testing. However, I cannot find a full list of them. Are they documented somewhere? If not, where can I find them in Laravel source?</p> |
29,047,409 | 0 | <p>the answer is YES and NO. it depends on the processed data dynamic range</p> <ul> <li>if you are processing numbers/signal in specified range then YES</li> <li>but if the numbers/signal has very high dynamic range then NO</li> </ul> <p>you should use more fixed point formats for different stage of signal processing</p> <ul> <li>for example ADC gives you values in exact defined range</li> <li>so you have to use fixed format such that does not loss precision and have not many unused bits</li> <li>after that you apply some filter or what ever the range changes</li> <li>so you need to get bound of possible number ranges per stage and use the best suited fixed point format you have at disposal</li> </ul> <p>This means you need some number of fixed point formats</p> <ul> <li>and also the operations between them</li> <li>you can have fixed number of bits and just change the position of decimal point...</li> </ul> <p>To be more specific then you need add the block diagram of your processing pipeline</p> <ul> <li>with the number ranges included</li> <li>and list of used operations</li> <li>matrix operations and integrals/sums are tricky because they can change the dynamic range considerably</li> </ul> <p>The real question always stays if such implementation is faster then floating point ...</p> <ul> <li>because sometimes the transition between different fixed point stages can be slower then direct floating point implementation ...</li> </ul> |
29,703,312 | 0 | <p>The most seems like your binary is just not executed. Try to execute explicitly:</p> <pre><code>php vendor/bin/propel </code></pre> |
7,407,668 | 0 | adding unique class for new div <p>I want add a unique class for each new div after input, how is it in my code?</p> <p>Add class for this: <code><div class="thing"></div></code></p> <p><strong>DEMO:</strong> <a href="http://jsfiddle.net/wAwyR/2/" rel="nofollow">http://jsfiddle.net/wAwyR/2/</a> => please in here(field) typing a number for adding new input.</p> <pre><code>function unique() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < 5; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } $('input').live("keyup", function () { $('.lee').empty(); var $val = $(this).val(); for (var i = 0; i < $val; i++) { $('.lee').append('<input type="text" name="hi" class="">div class="thing"></div>'); $('input[hi]').next('div').attr('class', unique()) } }); </code></pre> |
36,616,691 | 0 | how to use both angularJS and knockoutJS on same page <p>my application developed with AngularJS but now i'm going to implement 'Mosaico Email Template Editor' (which is developed with KnockoutJS).. so How Can i Use both Angular and Knockout On Same Page.. any one can explain with sample code.. ?? tanx in advance</p> <p>my sample code : </p> <pre><code><script type="text/javascript" src="js/core/controller/knockout.js"></script> <script src="dist/vendor/jquery.min.js"></script> <script type="text/javascript" src="js/core/controller/controller.js"></script> <div data-bind="foreach: templates"> <div class="template template-xx" style="" data-bind="attr: { class: 'template template-'+name }"> <div class="description" style="padding-bottom:5px"><b data-bind="text: name">xx</b>: <span data-bind="text: desc">xx</span></div> <a href="#" data-bind="click: $root.newEdit.bind(undefined, name), attr: { href: 'editor.html#templates/'+name+'/template-'+name+'.html' }"> <img src="/images/full.png" width="100%" alt="xx" data-bind="attr: { src: 'templates/'+name+'/edres/_full.png' }"> </a> </div> </div> *[and JS file below - controller.js][1]* var viewModel = { templates: [ { name: 'versafix-1', desc: 'The versatile template' }, { name: 'tedc15', desc: 'The TEDC15 template' } ] }; document.addEventListener('DOMContentLoaded',function(){ ko.applyBindings(viewModel); }); </code></pre> <p>First two image - what i expect but i get now right side one...i think knockout binding not working properly in my page:</p> <p><img src="https://i.stack.imgur.com/tojhW.png" alt="First two image - what i expect but i get now right side one...i think knockout binding not working properly in my page"></p> |
33,442,426 | 0 | Autocomplete inpud is not detected by $watch angularjs <p>I have a form of addresses which has one input autocomplete from googleMaps. When I select an address, the rest of inputs aumatically is filled. Two of this form are latitude and longitude.</p> <p>I want that when I put an address, the service $watch detect this values and refresh the map.</p> <p>Note: The services $watch detect values if I write in that field, but I want to write address and take this values.</p> <p>My code form addresses:</p> <pre><code> <input vs-google-autocomplete="{ types: ['address'] }" vs-autocomplete-validator="vs-street-address" ng-model="streetNumber[a.count].name" vs-place="streetNumber[a.count].place" vs-place-id="streetNumber[a.count].components.placeId" vs-street-number="streetNumber[a.count].components.streetNumber" vs-street="streetNumber[a.count].components.street" vs-city="streetNumber[a.count].components.city" vs-state="streetNumber[a.count].components.state" vs-country-short="streetNumber[a.count].components.countryCode" vs-country="streetNumber[a.count].components.country" vs-post-code="streetNumber[a.count].components.postCode" vs-latitude="streetNumber[a.count].components.location.lat" vs-longitude="streetNumber[a.count].components.location.long" type="text" name="streetNumber" id="streetNumber" class="form-control" placeholder="Enter full address (street number, street, ...)"> <input type="text" id="user_address_{{ ::address.count }}_latitude" name="user[address][{{ ::address.count }}][latitude]" value="{{streetNumber[a.count].components.location.lat}}" ng-model="latitude" class="form-control"> <input type="text" id="user_address_{{ ::address.count }}_longitude" name="user[address][{{ ::address.count }}][longitude]" ng-model="longitude" value="{{streetNumber[a.count].components.location.long}}" class="form-control"> <ui-gmap-google-map center='map.center' zoom='map.zoom'></ui-gmap-google-map> </code></pre> <p>AngularJS:</p> <pre><code>app.controller("testCtrl",function ($scope) { $scope.map = { center: { latitude: 40.37464, longitude: -3.7319700000000466 }, zoom: 16 }; $scope.address = { count: -1 }; $scope.$watch('longitude', function(newLongitude) { alert('newLongitude'); }, true); $scope.$watch('latitude', function(newLatitude) { if (!angular.isUndefined(newLatitude)){ $scope.map['center']['latitude'] = newLatitude; } }, true); }); </code></pre> |
22,182,892 | 0 | best way to determine proximity to location with a list of latlng with Google Map API <p>I'm under a 2-day crunch deadline (my own undoing, I know), and I need to implement a function in Wordpress that searches through a bunch of posts with custom content containing locations in a known field in wp_postmeta, (NOT geocoded) and shows a list of them based on proximity (i.e., within 20 miles) to a specific geocode. </p> <p>I have no problem with the WP query - I'm just a little new to Google Map API, and the docs aren't terribly straightforward with regards to geocoding, which I ASSUME I have to do to determine proximity. </p> <p>Additionally, I assume I'll just have to iterate through the list of each post and determine one at a time if they meet the proximity requirement. </p> <p>I'm not asking for someone to do this for me, unless you w3ant to be paid to do it for me - I just need to be pointed in the right direction quickly. I can;t find ANYONE who knows how to do this - and I have some budget for it...</p> |
10,807,302 | 0 | <p>You should first introduce the "UserName" to your Session by using </p> <pre><code>HttpContext.Current.Session.Add("UserName", value) </code></pre> <p>in your setter.</p> <pre><code>public class CurrentUser { public static string UserName { get { if (HttpContext.Current.Session["UserName"] != null) return (string)HttpContext.Current.Session["UserName"]; else return null; } set { if (HttpContext.Current.Session["UserName"] == null) HttpContext.Current.Session.Add("UserName", value); else HttpContext.Current.Session["UserName"] = value; } } } </code></pre> <p>After doing that it should work as you wrote.</p> |
33,220,187 | 0 | <p>I would recommend using Spark for this kind of bulk migration. It's also a useful tool for general maintenance of C*. </p> <p><a href="https://github.com/datastax/spark-cassandra-connector" rel="nofollow">https://github.com/datastax/spark-cassandra-connector</a></p> <p>With spark the command</p> <pre><code>sc.cassandraTable("ks1","table").saveToCassandra("ks2","table") </code></pre> <p>you would move your tables. </p> <p>If you aren't interested in Spark I think a custom java program or Brian Hess's Bulkloader tool would be useful</p> <p><a href="https://github.com/brianmhess/cassandra-loader" rel="nofollow">https://github.com/brianmhess/cassandra-loader</a></p> |
37,165,164 | 0 | <p>I find out the solution for this</p> <pre><code>$form['field_first_name']['und']['0']['value']['#value'] = 'XXXXX'; $form['field_first_name']['und']['0']['value']['#attributes'] = array('readonly' => 'readonly'); </code></pre> <p>Try this. Suggest me Ok.</p> |
19,857,210 | 0 | <p>I found a solution!</p> <pre><code>5 = TEXT 5 { value = hier typolink { parameter.field = pid title.cObject = TEXT title.cObject { data.dataWrap = DB:pages:{field:pid}:title } } } </code></pre> |
6,592,976 | 0 | Difference between Thread and Threadpool <p>Can any one guide me with example about Thread and ThreadPool what is difference between them? which is best to use...? what are the drawback on its</p> |
5,914,626 | 0 | Extracting html tables from website <p>I am trying to use XML, RCurl package to read some html tables of the following URL <a href="http://www.nse-india.com/marketinfo/equities/cmquote.jsp?key=SBINEQN&symbol=SBIN&flag=0&series=EQ#" rel="nofollow">http://www.nse-india.com/marketinfo/equities/cmquote.jsp?key=SBINEQN&symbol=SBIN&flag=0&series=EQ#</a></p> <p>Here is the code I am using </p> <pre><code>library(RCurl) library(XML) options(RCurlOptions = list(useragent = "R")) url <- "http://www.nse-india.com/marketinfo/equities/cmquote.jsp?key=SBINEQN&symbol=SBIN&flag=0&series=EQ#" wp <- getURLContent(url) doc <- htmlParse(wp, asText = TRUE) docName(doc) <- url tmp <- readHTMLTable(doc) ## Required tables tmp[[13]] tmp[[14]] </code></pre> <p>If you look at the tables it has not been able to parse the values from the webpage. I guess this due to some javascipt evaluation happening on the fly. Now if I use "save page as" option in google chrome(it does not work in mozilla) and save the page and then use the above code i am able to read in the values.</p> <p>But is there a work around so that I can read the table of the fly ? It will be great if you can help.</p> <p>Regards,</p> |
38,948,619 | 0 | angular 2 location.go vs window.location.href <p>I understand that location.go will simply change the browser url without reloading the page while window.location.href will reload the page.</p> <p>What I don't understand is there impact on SEO. My site url scheme is defined in a way that parts of url can be in different order for the exact same page. We dont want to have this as google will penalize it assuming it to be duplicate content. I have two approaches to handle this problem - </p> <p>location.go approach is more desirable from user experience point. I can load the page and find the correct url in parallel and simply change the url in browser. But I do not know if search engines also take the input from location.go.</p> <p>Please note that my logic for building unique url is bit complex and require me to go all the way to database. So it makes a considerable difference in performance if I choose location.go vs window.location.href to change the url.</p> |
32,584,318 | 0 | <p>The Sitecore <code>LinkManager</code> is indeed not so clever. We also experienced this issue with a mix of proxy servers and load balancers. To remove the ports, we have created a custom <code>LinkProvider</code> which removes the port if needed (untested code sample):</p> <pre><code>public class LinkProvider : Sitecore.Links.LinkProvider { public override string GetItemUrl(Item item, UrlOptions options) { var url = base.GetItemUrl(item, options); if (url.StartsWith("https://")) { url = url.Replace(":443", string.Empty); } return url; } } </code></pre> <p>And configure the new <code>LinkProvider</code>:</p> <pre><code><configuration xmlns:set="http://www.sitecore.net/xmlconfig/set/"> <sitecore> <linkManager defaultProvider="sitecore"> <providers> <add name="sitecore" set:type="Website.LinkProvider, Website" /> </providers> </linkManager> </sitecore> </configuration> </code></pre> |
8,694,330 | 0 | <p>You can simplify to:</p> <pre><code>SELECT expire_date - (expire_date - now()) - interval '1 month' FROM "License" WHERE license_id = 10 </code></pre> <p>This is valid without <em>additional</em> brackets because subtractions are evaluated from left to right.<br> <sub>In my first version the one necessary pair of brackets was missing, though.</sub></p> <p>This form of the query also prevents an error in the case that <code>license</code> should not be unique. You would get multiple rows instead. In that case, and if you should need it, add <code>LIMIT 1</code> guarantee a single value.</p> <hr> <p>@Milen diagnosed the cause of the error correctly. Experiment with these statements to see:</p> <pre><code>SELECT interval (interval '1 month'); -- error SELECT (interval '1 month')::interval; -- no error </code></pre> <p>However, the cure is simpler. Just don't add another cast, it is redundant.</p> |
23,737,780 | 0 | <p>the map-canvas or its parents must have a decent height. Try </p> <pre><code> <div id="map-canvas" style="height:100px;"></div> </code></pre> <p>note the <code>px</code> instead of <code>%</code></p> |
23,629,056 | 0 | WinForms and WebService in 1 solution <p>How to have a <code>WinForms</code> app that has a <code>ASP.NET</code> WebSite as part of the <code>Solution</code>.</p> <p>What I would like to do is as my WinForms app start the <code>ASP.NET</code> Service also starts.</p> <p>When the Winforms app closes, I want to shutdown the <code>ASP.NET</code> Service.</p> <p><strong>Main Objective</strong></p> <p>Essentially my objective is to be able to view a Silverlight XAP file in my WinForms BrowserControl.</p> <p>The XAP will not function correctly because of security issues, and it needs to access files (images/videos) from the filesystem.</p> |
39,891,494 | 0 | <p>If you check PHP Documentation for <code>eval()</code>, this is the description:</p> <blockquote> <p>eval — Evaluate a string as PHP code</p> </blockquote> <p>However, PHP Documentation, itself says that <code>eval</code> is a <em>dangerous</em> construct: Caution</p> <blockquote> <p>The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.</p> </blockquote> <p>So, be careful when using <code>eval</code>, very careful. Now back to your question.</p> <p>I think what you need here is a tool that can help you with Syntax checking to detect violations of a defined coding standard. I use ESLint to check violations in Javascript code. For PHP I use both PHPStorm and Sublime Text, and I use PHP Lint and PHPCS. Instead doing eval, I suggest you use one of these OR combination of these tools to achieve you objective.</p> <p>If you are using Jetbrains PHPStorm, you can find these plugins here:</p> <ul> <li><a href="https://www.jetbrains.com/help/phpstorm/2016.2/using-php-code-sniffer-tool.html" rel="nofollow">https://www.jetbrains.com/help/phpstorm/2016.2/using-php-code-sniffer-tool.html</a></li> <li><a href="https://plugins.jetbrains.com/plugin/7887?pr=phpStorm" rel="nofollow">https://plugins.jetbrains.com/plugin/7887?pr=phpStorm</a> I personally prefer to use PHPStorm, it is really among the best PHP IDE out there.</li> </ul> <p>If you prefer to use Sublime, here are the plugins for you: </p> <ul> <li><a href="https://github.com/SublimeLinter/SublimeLinter-php" rel="nofollow">https://github.com/SublimeLinter/SublimeLinter-php</a></li> <li><a href="https://github.com/SublimeLinter/SublimeLinter-phplint" rel="nofollow">https://github.com/SublimeLinter/SublimeLinter-phplint</a></li> <li><a href="https://github.com/benmatselby/sublime-phpcs" rel="nofollow">https://github.com/benmatselby/sublime-phpcs</a></li> </ul> <p>My point is, a good combination of these tools should be enough to ensure sanity of your code.</p> <p>-Thanks</p> |
18,910,280 | 0 | <p>Try</p> <pre><code>include_once 'simple_html_dom.php'; $oHtml = str_get_html($url); $Title = array_shift($oHtml->find('title'))->innertext; $Description = array_shift($oHtml->find("meta[name='description']"))->content; $keywords = array_shift($oHtml->find("meta[name='keywords']"))->content; echo $title; echo $Description; echo $keywords; </code></pre> |
34,358,625 | 0 | <p>Correct way to solve this issue is as follows:</p> <pre><code>Template.DoPolls.helpers({ polls: function() { var user = Meteor.userId() return Polls.find({voters: {$ne: user}}); } }); </code></pre> <p>where $ne look over the voters array and if it finds the userId then doesn't show that poll.</p> <p>To achieve the opposite (so only polls where the user has voted the helper would be:</p> <pre><code>Template.PollsDone.helpers({ polls: function() { var user = Meteor.userId() return Polls.find({voters: {$in: [ user ] }}); } }); </code></pre> |
7,115,448 | 0 | Descendant of sibling jquery <p>I have recently switched from using XPath to using jQuery selectors. I am having trouble with a particular XPath selector I would use:</p> <p>//h1[contains(.,'Some Title')]//following::a[1]</p> <p>Basically I get the first link element from a descendant of a sibling.</p> <p>From what I understand jQuery selects descendants as "ancestor descedant" and selects siblings as "sibling + sibling".</p> <p>How do I combine these when I don't care/know what the sibling tag is? (In other words "h1 + ul a" works but I want to leave out the ul if possible"</p> |
35,712,705 | 0 | Unable to hear any output from Text to Speech <p>I am creating my own Codenameone application that uses the Text to Speech functionality in IOS 8. My application uses the same native IOS code as given in the DrSbaitso demo. I can build my application and deploy it to my IPhone successfully, however I am never able to hear any output from the Text to Speech. I have verified that the native interface is getting called, but I cannot hear any sound. Is there something else that needs to be implemented than just the native interface that will call the IOS text to speech functionality? Is there perhaps something I need to enable on my IPhone to use the Text to Speech API? I have listed my native implementation code that I am using.</p> <p>Header:</p> <pre><code>#import <Foundation/Foundation.h> @interface com_testapp_demos_TTSImpl: NSObject { } -(void)say:(NSString*)param; -(BOOL)isSupported; @end </code></pre> <p>Source:</p> <pre><code>#import "com_testapp_demos_TTSImpl.h" #import <AVFoundation/AVFoundation.h> @implementation com_testapp_demos_TTSImpl -(void)say:(NSString*)param{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-GB"]; AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:param]; AVSpeechSynthesizer *syn = [[[AVSpeechSynthesizer alloc] init]autorelease]; utterance.rate = 0; utterance.voice = voice; [syn speakUtterance:utterance]; [pool release]; } -(BOOL)isSupported{ return YES; } @end </code></pre> |
17,922,582 | 0 | MKMapRectMake how to zoom out after setup <p>I use <code>MKMapRectMake</code> to mark north east and south west to display a region. Here's how I do that:</p> <pre><code>routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y, northEastPoint.x - southWestPoint.x, northEastPoint.y - southWestPoint.y); [self.mapView setVisibleMapRect:routeRect]; </code></pre> <p>After I set up this display region, how can I zoom out the map a little? What is the best way to do this?</p> <h2>UPDATE</h2> <p>This is code that I use to get <code>rect</code> for <code>setVisibleMapRect</code> function:</p> <pre><code>for(Path* p in ar) { self.routeLine = nil; self.routeLineView = nil; // while we create the route points, we will also be calculating the bounding box of our route // so we can easily zoom in on it. MKMapPoint northEastPoint; MKMapPoint southWestPoint; // create a c array of points. MKMapPoint* pointArr = malloc(sizeof(CLLocationCoordinate2D) * ar.count); for(int idx = 0; idx < ar.count; idx++) { Path *m_p = [ar objectAtIndex:idx]; [NSCharacterSet characterSetWithCharactersInString:@","]]; CLLocationDegrees latitude = m_p.Latitude; CLLocationDegrees longitude = m_p.Longitude; // create our coordinate and add it to the correct spot in the array CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude); MKMapPoint point = MKMapPointForCoordinate(coordinate); // adjust the bounding box // if it is the first point, just use them, since we have nothing to compare to yet. if (idx == 0) { northEastPoint = point; southWestPoint = point; } else { if (point.x > northEastPoint.x) northEastPoint.x = point.x; if(point.y > northEastPoint.y) northEastPoint.y = point.y; if (point.x < southWestPoint.x) southWestPoint.x = point.x; if (point.y < southWestPoint.y) southWestPoint.y = point.y; } pointArr[idx] = point; } // create the polyline based on the array of points. self.routeLine = [MKPolyline polylineWithPoints:pointArr count:ar.count]; _routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y, northEastPoint.x - southWestPoint.x, northEastPoint.y - southWestPoint.y); // clear the memory allocated earlier for the points free(pointArr); [self.mapView removeOverlays: self.mapView.overlays]; // add the overlay to the map if (nil != self.routeLine) { [self.mapView addOverlay:self.routeLine]; } // zoom in on the route. [self zoomInOnRoute]; } </code></pre> |
34,978,554 | 0 | Use of Node JS for Frontend <p>I have heard about Node.js being used in the frontend side of the application as opposed to the backend side, but I cannot find any use cases for which it can be used. Can somebody explain the use cases for which Node.js is used in the frontend.</p> <p>Also for a fairly complex system such as a CMS(Content Management System) for an e-commerce site, would Node.js be the right choice?</p> <p>Thanks in advance</p> |
29,470,470 | 0 | alert 2 arrays in same line javascript <p>I have a problem alerting out 2 arrays on same line in Javascript. The user should write Movie name and movie rating(1-5) 5 times, and <code>printMovies()</code> function should print out users (movie)name and (movie)rating in a single line something like this:</p> <pre><code>Movie Rating Star Wars 5 Lord of the Rings 4 Casino 4 Movie4 3 Movie5 2 </code></pre> <p>How do I alert out all of five inputs in a single line (movie + rating) per line, AFTER they have got input from user?</p> <p>//CODE</p> <pre><code>var title; var rating; var a = []; var movies = []; var ratings = []; function buttonAddMovie()//Button onclick { addMovie(title, rating) addMovie(title, rating) addMovie(title, rating) addMovie(title, rating) addMovie(title, rating) } function addMovie(title, rating) { do{ title = prompt("Enter movie: "); } while (title == ""); do { rating = parseInt(prompt("Enter rating 1-5 on movie " + (title))); } while (rating > 5 || rating < 1); movies.push(title);//Pushing title to movies a.push(movies);//Pushing movies to a array ratings.push(rating);//Pushing rating to ratings a.push(ratings);//Pushing ratings to a array printMovies() } function printMovies() { for (var i = 0; i < a.length; i++) { alert(a[0][0] + " " + a[0][1]);//Here is my biggest problem! } } </code></pre> |
23,569,833 | 0 | <pre><code>$("#output1 > ins,#output1 del").first() </code></pre> <p><a href="http://jsfiddle.net/a6dLH/" rel="nofollow">http://jsfiddle.net/a6dLH/</a></p> |
31,069,895 | 0 | <p>Modify your reqList select:</p> <pre><code>var reqList = (from p in db.RequestDetail group new { p.PropertyID, p.UnitID , p.Value , p.PropertiesValueID } by p.RequestID into reqG select new RequestDetailViewModel{ PropertyID = reqG.PropertyID, UnitID = reqG.UnitID , Value = reqG.Value , PropertiesValueID = reqG.PropertiesValueID }); </code></pre> <p>Will return <code>List<RequestDetailViewModel></code></p> <p>Implement <code>IComparable</code> for your <code>RequestDetailViewModel</code> class then use <code>SequenceEqual</code> to compare two lists</p> |
10,965,542 | 0 | Adding one character to string <p>In C++:</p> <p>If I want to add <code>0x01</code> to the string text I would do: <code>text += (char)0x01</code>;</p> <p>If I want to add <code>0x02</code> to the string text I would do: <code>text += (char)0x02</code>;</p> <p>If I want to add <code>0x0i</code> (were <code>i</code> is an unsinged <code>int</code> between 0 and 9), what could I do?</p> <p>EDIT: I probably wasn't quite clear. So by 0x01, I mean the character given in Hex as 01. So in the above if i is the integer (in decimal) say 3, then I would want to add 0x03 (so this is not the character given in decimal as 48 + 3).</p> |
27,055,820 | 0 | Calculating datatable input text value and showing result in a outputtextbox <p>I am new to primefaces. I have a problem and the issue is , i have a inputtextbox inside a datatable and if i enter any value inside a textbox the count should display in a outputTextbox called total. I am not finding any solution. my code is</p> <pre><code><p:dataTable id="venueNames" var="test" value="#{issueAdmitCardBean.venueNames}" paginator="false" rows="10" styleClass="dataTable" rowIndexVar="index"> <p:column headerText="Id"> <h:outputText value="#{test.id}" /> </p:column> <p:column headerText="Name Of Venue"> <h:outputText value="#{test.name}" /> </p:column> <p:column headerText="Maximum Capacity"> <h:outputText value="#{test.capacity}" /> </p:column> <p:column headerText="Allot No. of Candidates" > <h:inputText value="#{issueAdmitCardBean.venueNames[index].allotCandaidate}" style="width:50px;" onkeyup="doWork(#{test.capacity}, this.value);" required="true"/> </p:column> <p:column headerText="Exam Date"> <p:calendar value="issueAdmitCardBean.examDate" pattern="dd-MM-yyyy" navigator="true" style="width:10px;"/> </p:column> </p:dataTable> </code></pre> <p>I want to display the total right after the datatable . please give any suggestion and help me.Thanks in advance </p> |
35,016,805 | 0 | <p>Since an empty predicate is true, my favorite implementation of true and false is:</p> <pre><code>pred true {} pred false { not true } </code></pre> |
9,902,604 | 0 | <blockquote> <p>Should I implement IDisposable? </p> </blockquote> <p>Yes</p> <blockquote> <p>But What happens if the user of my class forgets to call Dispose?</p> </blockquote> <p>you should follow the Disposable pattern as defined here: <a href="http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx</a></p> |
1,518,973 | 0 | <p>When returning the file to the browser, set the mime-type to be "application/x-unknown" - this will cause the browser to ask you to download as it won't know how to handle it.</p> <p>There is the possibility the browser will read the file extension and try and be clever, but there's nothing you can do about this.</p> |
6,081,137 | 0 | <p>If C# (and C and java, and probably C++), you need to declare <code>_shouldStop</code> and <code>Grab</code> as <code>volatile</code>.</p> |
33,966,107 | 0 | <p>Just to let you know, Linux is just a kernel, <strong><em>NOT</em></strong> a full operating system. If you expect it to be a full operating system, you will need to also include other things like the GNU Coreutils. Otherwise you'll be left with something almost useless to use and impossible to install on its own.</p> <p>To compile the kernel, you'll need to have an existing install of some flavor of Linux (Ubuntu, Fedora, Arch, etc).</p> <p>Basically, in essence, you get a copy of the Linux code, then you simply run <code>make</code>.</p> <p>This is how Arch Linux builds the Linux kernel: <a href="https://projects.archlinux.org/svntogit/packages.git/tree/trunk/PKGBUILD?h=packages/linux" rel="nofollow">https://projects.archlinux.org/svntogit/packages.git/tree/trunk/PKGBUILD?h=packages/linux</a></p> |
3,116,556 | 0 | <p>Try copying the form definition code from views/users/login.ctp to your FAQ view. Make sure that the form is named properly so that it points at the Users controller. If you're not sure, look in the book.</p> <p>Then you'll need to redirect to the FAQ page after successful login. If necessary you can define a specific login action for this style of login (say, signin) so that the standard way remains unaltered WRT to login redirect. Include a condition to display the form only when you are not logged in.</p> |
28,757,170 | 0 | How does ejabberd handle really high number of requests <p>How does ejabberd handle really high number of requests. For eg.</p> <ul> <li>I have only 1 instance running.</li> </ul> <p><strong>I am assuming:</strong></p> <ul> <li>Lets take mod_offline.erl for example</li> <li>This module gets started by ejabberd_admin when server is started</li> <li>Using gen_server callbacks.</li> </ul> <p>-- Is there only a single instance of this module running or are there multiple instances of the module running at the same time -- If multiple then how many such instances?</p> <p>I was also curious what needs to be done to write a custom module to be able to handle high number of requests simultaneously.</p> <p>Could you please provide some pointers?</p> <p>I am very new to erlang and ejabberd. Please help me understand how does ejabberd take care of high requests.</p> <p>Best Regards,</p> |
18,324,044 | 0 | <p>Check out Google Analytics Report Automation using Magic Script - <a href="https://developers.google.com/analytics/solutions/report-automation-magic" rel="nofollow">https://developers.google.com/analytics/solutions/report-automation-magic</a>. As long as you have permission to both accounts you want to pull data from, you can make a dashboard using Google Spreadsheets.</p> |
34,566,973 | 0 | <p>It means literally in the shape of the Greek letter rho, which is "ρ". The idea is that if you map the values out as a graph, the visual representation forms this shape. You could also think of it as "d" shaped or "p" shaped. But look carefully at the font and notice that the line or stem extends slightly past the loop, while it doesn't on a rho. Rho is a better description of the shape because the loop never exits; i.e., there shouldn't be any lines leading out of the loop. That and mathematicians love Greek letters.</p> <p>You have some number of values which do not repeat; these form a line or the "stem" of the "letter". The values then enter a loop or cycle, forming a circle or the "loop" of the "letter".</p> <p>For example, consider the <a href="https://en.wikipedia.org/wiki/Repeating_decimal" rel="nofollow">repeating decimals</a> 7/12 (0.5833333...) and 3227/55 (5.81441441444...). If you make your sequence the digits in the number, then you can graph these out to form a rho shape. Let's look at 3227/55.</p> <ul> <li>x0 = 5</li> <li>x1 = 8</li> <li>x2 = 1</li> <li>x3 = 4</li> <li>x4 = 4</li> <li>x5 = 1 = x2</li> <li>x6 = 4 = x3</li> <li>x7 = 4 = x4</li> <li>...</li> </ul> <p>You can graph it like so:</p> <pre><code>5 -> 8 -> 1 ^ \ / v 4 <- 4 </code></pre> <p>You can see this forms a "ρ" shape.</p> |
25,645,039 | 1 | Readline() in a loop is not working in python <p>I have a file called <code>file</code> with this text:</p> <pre><code>Hello I am not a bot I am a human Do you believe me? I know you won't Yes I am a bot Yes you thought it right </code></pre> <p>This code prints out all the lines of the text:</p> <pre><code>with open(file) as f: for i in f: print(i,end="") </code></pre> <p>But this code does not, and I don't understand why.</p> <pre><code>with open(file) as f: for i in f: print(f.readline(),end="") </code></pre> <p>This prints out:</p> <pre><code>I am not a bot Do you believe me? Yes I am a bot </code></pre> <p>What I understand is as the loop goes over the lines in the file, it will read that line and return that as a string which is then printed. If I replace the for loop with <code>for i in range(9)</code>, it works.</p> |
38,978,542 | 0 | I am getting a segmentation error in PRIME1 on spoj. How should I eradicate it? <p>My answer to problem <a href="http://www.spoj.com/problems/PRIME1/" rel="nofollow">PRIME1</a> please explain me where am I wrong. I am receiving a segmentation error.</p> <p>here it is:</p> <pre><code> #include<cstdlib> #include<iostream> using namespace std; int main(int argc, char** argv) { int t=0,i=0,m=0,n=0; cin>>t; while(t--&&t<=10) { cin>>m>>n; if(m>=1&&n-m<=100000) { int prime[n]; for(i=0;i<n;i++) prime[i]=1; for (int i=2; i*i<=n; i++) { if (prime[i] == true) { for (int j=i*2; j<=n; j += i) prime[j] = false; } } for (int k=m+1; k<n; k++) if (prime[k]) cout <<k<<endl; } } return 0; } </code></pre> |
38,221,453 | 0 | Managing a nested resource in Jax-RS/Jersey that sometimes should behave as a non-nested resource <p>I am developing simple APIs with Jax-RS Jersey. Let's say I am considering the domain of items sold by stores in some country.</p> <p>My design includes these two calls :</p> <ul> <li>/webapi/items</li> <li>/webapi/store/1/items</li> </ul> <p>Both of them should return a list of items, the first one should return all the items sold in that country, the second one should return only the items sold by store number 1.</p> <p>I have of course two resources, an ItemResource which handles all the requests regarding items, and a StoreResource which handles all requests regarding stores.</p> <pre><code>@Path("items") class ItemResource { @GET public List<Item> getAllItems(){ } </code></pre> <p>.</p> <pre><code>@Path("stores") class StoreResource @GET @Path("/{storeId}/items") public List<Item> getItemsSoldByStore(@PathParam("storeId") long storeId) { } </code></pre> <p>What I would like to do is to pass the second request to the ItemResource, in order to avoid coupling between <code>StoreResource</code> and model class <code>Item</code> or database interfaces (like DAOs) specifically created to manage Items. I know I can consider ItemResource like a sub-resource, or a nested resource of StoreResource, but the point is that this is not always true, since sometimes I would like to call ItemResource without passing a store id, to get all items (this is the case of the first request <a href="http://foo.com/webapi/items" rel="nofollow">http://foo.com/webapi/items</a> ). I'd like to keep the <code>@Path("items")</code> annotation on the <code>ItemResource</code> so it handles every request to /items endpoint. </p> <p>What is the correct design in this situation? Thanks for any help.</p> |
19,963,428 | 0 | <p>Use Inversion Of Control (IOC) and the Service Locator pattern to create a shared data service they both talk too. I notice your mvvm-light tag; I know a default Mvvm-light project uses a ViewModelLocator class and SimpleIOC so you can register a data service like below.</p> <pre><code>public class ViewModelLocator { static ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); SimpleIoc.Default.Register<IDataService, DataService>(); } } </code></pre> <p>An interface is used so we can swap out the DataService at will and even have a different one for design time. So you will create an interface that defines methods you will use and just make sure your DataService implements them. It is in your DataService implementation you will use the shared context / source.</p> <pre><code>public class DataService: IDataService { //USE SAME SOURCE (example EF) private SharedSourceEntities context; (blah blah)... } </code></pre> <p>After you can inject it into both view models either in the constructor or calling the service locator.</p> <p><strong>Dependency Injection:</strong></p> <pre><code>public class ViewModelOne: ViewModelBase { private readonly IDataService dataService; public ViewModelOne(IDataService dataService) { this.dataService = dataService; } } public class ViewModelTwo: ViewModelBase { private readonly IDataService dataService; public ViewModelTwo(IDataService dataService) { this.dataService = dataService; } } </code></pre> <p><strong>Service location:</strong></p> <pre><code>SimpleIoc.Default.GetInstance<IDataService>(); </code></pre> |
25,311,985 | 0 | trying to run a function within a class <p>I am trying to call a function within my class. But when i try to call it errors out and says "Fatal error: Call to undefined function" even though its defined within my class.</p> <pre><code> function checkArray($day, $array){ foreach ($array as $key => $value) { if (array_search($day, $value)) return $key; } return false; } </code></pre> <p>And i try to call it like this within another function of the class</p> <pre><code>if(checkArray($i,$events)){ echo $events[checkArray($i,$events)]["short"]; } </code></pre> <p>if i test this code without using a class, it works perfect. But within a class it seems like it doesn't let me call a function that is within a class. I'm kind of new to OOP so i know it might seem like a dumb question.</p> |
37,966,320 | 0 | <p>1st try/test, changed it into:</p> <pre><code>def purgeOld(): XvbmcEntries = setupXvbmcEntries() for entry in XvbmcEntries: xvbmcaddons = xbmc.translatePath(entry.path) if os.path.exists(xvbmcaddons)==True: for root, dirs, files in os.walk(xvbmcaddons): file_count = 0 file_count += len(files) if file_count > 0: for f in files: try: os.unlink(os.path.join(root, f)) except: pass for d in dirs: try: shutil.rmtree(os.path.join(root, d), ignore_errors=True) except: pass try: shutil.rmtree(xbmc.translatePath(os.path.join('special://home/addons/repository.Blaaat1')), ignore_errors=True) shutil.rmtree(xbmc.translatePath(os.path.join('special://home/addons/repository.Blaaat2')), ignore_errors=True) shutil.rmtree(xbmc.translatePath(os.path.join('special://home/addons/repository.Blaaat3')), ignore_errors=True) dialog.ok("TEST-PURGE", 'we found some orphaned dependencies...','', 'NOTE: a REBOOT is highly recommended!') xbmc.executebuiltin("UpdateLocalAddons") except: pass else: #dialog.ok("Purge test dialog2", "Crap cleaner all done...") pass else: #dialog.ok("Purge test dialog3", "Crap cleaner all done...") pass dialog.ok("Purge dialog DONE!", "everything is as clean as a whistle...") # return </code></pre> <p>This does remove all the folders, but now I have to specify 'what to remove' twice, this does seem a little redundant? (entries are specified in setupXvbmcEntries earlier, now again/extra under try: etc), I assume this can be done prettier, invoke 'xvbmcaddons' again somehowe perhaps?</p> |
32,168,039 | 0 | what is exact difference between Spark Transform in DStream and map.? <p>I am trying to understand transform on Spark DStream in Spark Streaming.</p> <p>I knew that transform in much superlative compared to map, but Can some one give me some real time example or clear example that can differentiate transform and map.? </p> |
33,066,794 | 0 | How to make vim use buffer instead of stdout by default? <p>I searched all over the internet, but didn't find an answer.</p> <p>I found plugin "AsyncCommand", but I don't want to type :AsyncCommand everytime. I just want vim to pipe stdout to a buffer by default.</p> <p>Is it even possible? Do you know any plugin that can do this?</p> |
9,536,120 | 0 | <p>You can just use</p> <pre><code>var myArrayInJs = <?php echo json_encode($myArray); ?>; </code></pre> |
10,699,434 | 0 | <ol> <li>Derive from both <code>std::exception</code> and <code>boost::exception</code> <em>virtually</em>: <code>struct ConfigurationException : virtual std::exception, virtual boost::exception</code>.</li> <li>Catch by const reference: <code>catch (const std::exception& e)</code>.</li> <li>Don't put GUI logic in an exception constructor. Put it in an exception handler (i.e. <code>catch</code> block).</li> <li>Consider using <code>error_info</code> to attach additional information (like your title and message).</li> </ol> <p>And in general, be careful when mixing Qt with exceptions.</p> |
40,779,154 | 0 | <p>We can do same Springboard behavior using UICollectionView and for that we need to write code for custom layout.</p> <p>I have achieved it with my custom layout class implementation with <strong>"SMCollectionViewFillLayout"</strong> </p> <p><strong>Output as below:</strong></p> <p><strong>1.png</strong></p> <p><a href="https://i.stack.imgur.com/Pzb5E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pzb5E.png" alt="First.png"></a></p> <p><strong>2_Code_H-Scroll_V-Fill.png</strong></p> <p><a href="https://i.stack.imgur.com/WdBZn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WdBZn.png" alt="enter image description here"></a></p> <p><strong>3_Output_H-Scroll_V-Fill.png</strong> <a href="https://i.stack.imgur.com/bfind.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bfind.png" alt="enter image description here"></a></p> <p><strong>4_Code_H-Scroll_H-Fill.png</strong> <a href="https://i.stack.imgur.com/mxwSH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mxwSH.png" alt="enter image description here"></a></p> <p><strong>5_Output_H-Scroll_H-Fill.png</strong> <a href="https://i.stack.imgur.com/cwWqq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cwWqq.png" alt="enter image description here"></a></p> |
2,851,664 | 0 | <p>I got it all sorted out now. My hook_theme is this:</p> <pre><code>function cssswitch_theme() { return array( 'cssswitch_display' => array( 'arguments' => array('node'), ), 'cssswitch_node_form' => array( 'arguments' => array('form' => NULL), 'template' => 'cssswitch-node-form.tpl.php', ), ); } </code></pre> <p>I created the file themes/garland/cssswitch-node-form.tpl.php Then I can have control over where to put any form elements like this:</p> <pre><code><style> #edit-hour-start-wrapper, #edit-minute-start-wrapper, #edit-ampm-start-wrapper, #edit-hour-end-wrapper, #edit-minute-end-wrapper, #edit-ampm-end-wrapper { float:left; margin-right:25px; } </style> <div id="regform1"> <?php print drupal_render($form['title']); ?> <?php print drupal_render($form['cssfilename']); ?> <fieldset class="group-account-basics collapsible"> <legend>Time Start</legend> <?php print drupal_render($form['hour_start']); ?> <?php print drupal_render($form['minute_start']); ?> <?php print drupal_render($form['ampm_start']); ?> </fieldset> <fieldset class="group-account-basics collapsible"><legend>Time end</legend> <?php print drupal_render($form['hour_end']); ?> <?php print drupal_render($form['minute_end']); ?> <?php print drupal_render($form['ampm_end']); ?> </fieldset> </div> <?php print drupal_render($form['options']); ?> <?php print drupal_render($form['author']); ?> <?php print drupal_render($form['revision_information']); ?> <?php print drupal_render($form['path']); ?> <?php print drupal_render($form['attachments']); ?> <?php print drupal_render($form['comment_settings']); ?> <?php print drupal_render($form); ?> </code></pre> |
19,806,495 | 0 | how to iterate through the selectors with jquery? <p>Suppose, I have multiple selectors used </p> <pre><code>$('.some, .next, .any, .way, .myname, .something') </code></pre> <p>and now if I would like to change each background when one background is changed, so I'm wondering how can I iterate all selectors using likely to this: <code>$(this).each()</code> but I know this will not work coz this will take currently selected each elements but I would like to do all the selectors in my selectors used.</p> |
34,768,606 | 0 | Pass array and string from one script to another script <p>Hi have two script one in calling the another. from one script I m trying to pass two parameters a string and an array. How can i receive it on another script. Script 1 :</p> <pre><code> $admin_script_path/aggregation_checklist_hdfs.sh "${aggregation_hdfs_folder}" "${incrementalArray[@]}" </code></pre> <p>Script 2 :</p> <pre><code>path="$1" echo "$path" specificAggregationArray=( "$@" ) </code></pre> <p>but these are not working.</p> |
1,918,230 | 0 | <p>Try:</p> <pre><code>SELECT * FROM table WHERE column NOT LIKE 'pdd%' </code></pre> |
7,352,347 | 0 | maven-android-plugin passing build properties <p>I have a property file in asset folder, i want to override the values in this property file at project build time. like mvn clean install -Durl=<a href="https://xyx.xom" rel="nofollow">https://xyx.xom</a>?</p> <p>EX: assets/my_prop.properties </p> <pre><code># my_server_url=http://www.test.com/ change to my_server_url=${url} </code></pre> <p>i want to replace the my_server_url value at the build time what i did: mvn clean install -Durl=<a href="http://xys.com" rel="nofollow">http://xys.com</a></p> <p>but it's not replacing,how can i replace the my_server_url when doing the buid</p> |
40,623,405 | 0 | If var statement for existing var <p>I know there is the <code>if var</code> statement, but is there a way for it modify an existing var?</p> <pre><code>let number1: Int? = 1 ... var number2: Int = 2 if var number2 = number1 { //if number1 is not nil, number2 will be set to number1 which is 1 } </code></pre> |
25,950,183 | 0 | EditText with "text" inputType not hiding error popup when text is changed <p>Here is my XML</p> <pre><code><EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/barcode" android:id="@+id/barcode" android:inputType="number" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/name" android:id="@+id/name" android:inputType="text" /> </code></pre> <p>I set error to both fields:</p> <pre><code>((TextView) findViewById(R.id.barcode)).setError(getString(R.string.at_least_one_field)); ((TextView) findViewById(R.id.name)).setError(getString(R.string.at_least_one_field)); </code></pre> <p>When i run the app and change content in <code>barcode</code> field it's error popup is hiding. And when i change content in <code>name</code> field it's error popup is not hiding. It's hiding only when i tap on Finish button on the keyboard.</p> <p>Why <code>number</code> and <code>text</code> fields have different behaviour?</p> |
21,669,432 | 0 | OAuth 2.0 authentication for mobile client <p>I am developing an app using node.js which will also have an mobile client. I am looking to make the authentication using OAuth 2.0. I have my own external server which will do client validation and generate tokens. Please help me know as to how can i achieve this using OAuth2orize or any other really good module.</p> |
17,506,399 | 0 | <p>Ok, I found out the answer and it's particularly simple. (Finally for days)</p> <p>All I gotta do is just remove the collection, as well change the filter into checked. I also changed the <code>additional_toppings</code> into <code>additional_topping_ids</code> to return the array and I also add the <code>accessible</code> attribute.</p> <p>Here are the codes:</p> <pre><code>f.input :additional_toppings, as: :check_boxes, checked: food.additional_topping_ids </code></pre> <hr> <pre><code>attr_accessible :name, :price, :quantity, :picture, :category_id, :info , :favourite, :weekly, :unlimited, :toppings, :tag_list, :additional_topping_ids has_many :categorizations has_many :additional_toppings, :through => :categorizations </code></pre> |
24,795,894 | 0 | How to stop random effect in javascript <p>hey guys i am using <a href="http://codecanyon.net/item/magicwall-responsive-image-grid/full_screen_preview/7391534" rel="nofollow">Codecanyon</a> for my image gallery. Right now it is animating images with random effect. i want to remove random effect. any suggestion how can i do this. below is the functions of animation.</p> <pre><code>parseAnimationOptions: function (t) { var i, o = this, n = ["flipX", "flipY", "rollInX", "rollInY", "rollOutX", "rollOutY", "slideX", "slideY", "slideRow", "slideColumn", "fade"]; return t.animation ? i = t.animation : "*" == o.options.animations ? (i = o.excludeAnimations(n), i = (Math.random() < .5 ? "" : "-") + i[Math.floor(Math.random() * i.length)]) : (o.selectedAnimations && o.selectedAnimations.length || (o.selectedAnimations = o.options.animations.split(":")), i = o.excludeAnimations("*" == o.selectedAnimations[0] ? n : o.selectedAnimations[0].split(",")), i = i[Math.floor(Math.random() * i.length)], o.selectedAnimations.splice(0, 1)), -1 == n.indexOf(i.replace("-", "")) && (i = "fade"), e.extend(!0, t, { animation: i, type: i.replace(/[XY-]/g, ""), dir: 0 == i.indexOf("-", 0) ? -1 : 1, axis: i.replace(/[^XY]/g, ""), duration: t.duration || o.options[i.replace("-", "") + "Duration"] || o.options.duration, easing: t.easing || o.options[i.replace("-", "") + "Easing"] || o.options.easing }) } </code></pre> <p>and this code is on the page</p> <pre><code>$(".magicwall").magicWall({ maxItemWidth: 300, maxItemHeight: 240, animations: "rollOutY", flipXDuration: 500, }); </code></pre> |
30,504,517 | 0 | <p>Use <code>group by</code> and <code>join</code>:</p> <pre><code>SELECT s.lot_number, s.prod_code, s.date_received, s.expiry_date, s.quantity FROM scheme.stquem s JOIN (SELECT lot_number, min(date_received) as mindr FROM scheme.stquem WHERE prod_code = '001' AND lot_number <> '' //removes blanks GROUP BY lot_number ) sl ON sl.lot_number = s.lot_number and sl.mindr = s.date_received WHERE prod_code = '001' ORDER BY s.lot_number; </code></pre> |
30,388,510 | 0 | <p>You can have a single click handler for all the radio buttons with name <code>cureway</code></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('input[name="cureway"]').click(function() { if (this.id == 'first') { alert('first') } else if (this.id == 'second') { alert('second') } });</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> <input type="radio" name="cureway" id="first" class="checker" />first <input type="radio" name="cureway" id="second" class="checker" />second <input type="radio" name="cureway" id="third" class="checker" />third <input type="radio" name="cureway" id="forth" class="checker" />forth <input type="radio" name="cureway" id="five" class="checker" />five</code></pre> </div> </div> </p> |
33,882,647 | 0 | Universal Deep Links with Mandrill sub domain <p>I have Universal Deep Links working for my iOS app, Neighbourly (associated with neighbourly.co.nz)</p> <p>We send out emails to our users and use Mandrill to track clicks. The email links go to a subdomain clicks.neighbourly.co.nz/path which points to mandrillapp.com/path and the links redirect to neighbourly.co.nz/newpath</p> <p>Ive added applinks:clicks.neighbourly.co.nz to the apps associated domains.</p> <p>My apple-app-site-association file's paths is a wildcard: ["*"]</p> <p>But, while links to neighbourly.co.nz launch the app correctly, links to clicks.neighbourly.co.nz launch in Safari. What am I missing?</p> <p>I can't find any info online about setting up subdomains for deep links</p> <p>Does my apple-app-site-association file need to be hosted at mandrillapp.com?</p> |
4,849,077 | 0 | Unable to understand correctness of Peterson Algorithm <p>I have a scenario to discuss here for Peterson Algorithm:</p> <pre><code>flag[0] = 0; flag[1] = 0; turn; P0: flag[0] = 1; turn = 1; while (flag[1] == 1 && turn == 1) { // busy wait } // critical section ... // end of critical section flag[0] = 0; P1: flag[1] = 1; turn = 0; while (flag[0] == 1 && turn == 0) { // busy wait } // critical section ... // end of critical section flag[1] = 0; </code></pre> <p>Suppose both process start executing concurrently .P0 sets flag[0]=1 and die. Then P1 starts. Its while condition will be satisfied as flag[0]=1 ( set by P0 and turn =0) and it will stuck in this loop forever which is a dead lock.<br> So does Peterson Algorithm doesn't account for this case ?<br> In case if dying of process in not to be considered while analyzing such algorithms then in Operating System Book by William Stalling, appendix A contain a series of algorithm for concurrency, starting with 4 incorrect algorithm for demonstration. It proves them incorrect by considering the case of dying of a process ( in addition to other cases) before completion but then claims Peterson Algorithm to be correct. I came across <a href="http://stackoverflow.com/questions/4033738/does-petersons-algorithm-satisfy-starvation">this</a> thread which give me clue that there is a problem when considering N process( n>2) but for two process this algorithm works fine.<br> So is there a problem in the analysis of the algorithm(suggested by one of my classmate and i fully second him) as discussed above or Peterson Algorithm doesn't claim deadlock with 2 process too?</p> <hr> <p>In this paper <a href="http://portal.acm.org/citation.cfm?id=945527">Some myths about famous mutual exclusion algorithms</a>, the author concluded <strong>Peterson has never claimed that his algorithm assures bounded bypass.</strong><br> Can unbounded bypass be thought of as reaching infinity as in case of deadlock ? Well in that case we can have less trouble in accepting that Peterson Algorithm can lead to deadlock.</p> |
14,750,020 | 0 | Does check style 80 character rule still making sense today? <p>I have recently started doing some Java and one of the Maven checkstyle plugin is pissing me off, specially the 80 chars per line rule ! </p> <pre><code>"Line is longer than 80 characters!" </code></pre> <p>I have managed to fix most of the checkstyle "compile error" generated by the Maven plugin automatically via a Eclipse checkstyle plugin but many of the the 80 chars error still needs manual fix despite I have fiddled with the formatter for quite a while....</p> <p>What makes it worse is it makes the code looks ugly, breaking function deceleration,class deceleration, assignment into 2/3 line, </p> <p>Some of the checkstyle is good which helps us get the code clean but some rules just looks stupid and total waste of time !</p> <p>This makes me wondering does the 80 chars checkstyle still making any sense in the modern computer age ? I just failed to understand why java team still use it, it has been causing more trouble than helping us get the code clean & in a good style...</p> |
Subsets and Splits