Daily Archives

Articles indexed Friday June 11 2010

Page 16/114 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • How to find sum of node's value for given depth in binary tree?

    - by masato-san
    I've been scratching my head for several hours for this... problem: Binary Tree (0) depth 0 / \ 10 20 depth 1 / \ / \ 30 40 50 60 depth 2 I am trying to write a function that takes depth as argument and return the sum of values of nodes of the given depth. For instance, if I pass 2, it should return 180 (i.e. 30+40+50+60) I decided to use breath first search and when I find the node with desired depth, sum up the value, but I just can't figure out how to find out the way which node is in what depth. But with this approach I feel like going to totally wrong direction. function level_order($root, $targetDepth) { $q = new Queue(); $q->enqueue($root); while(!$q->isEmpty) { //how to determin the depth of the node??? $node = $q->dequeue(); if($currentDepth == $targetDepth) { $sum = $node->value; } if($node->left != null) { $q->enqueue($node->left); } if($node->right != null) { $q->enqueue($node->right); } //need to reset this somehow $currentDepth ++; } }

    Read the article

  • How do I search for a phrase using search logic?

    - by fivetwentysix
    Imagine case scenario, you have a list of recipes that have ingredients as a text. You want to see how many recipes contain "sesame oil". The problem with default searchlogic searching using Recipe.ingredients_like("sesame oil") is that any recipe with sesame OR oil would come up, when I'm searching for sesame+oil.

    Read the article

  • Multithreaded IOCP Client Issue

    - by Carl
    I am writing a multithreaded client that uses an IO Completion Port. I create and connect the socket that has the WSA_FLAG_OVERLAPPED attribute set. if ((m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { throw std::exception("Failed to create socket."); } if (WSAConnectByName(m_socket, L"server.com", L"80", &localAddressLength, reinterpret_cast<sockaddr*>(&localAddress), &remoteAddressLength, &remoteAddress, NULL, NULL) == FALSE) { throw std::exception("Failed to connect."); } I associate the IO Completion Port with the socket. if ((m_hIOCP = CreateIoCompletionPort(reinterpret_cast<HANDLE>(m_socket), m_hIOCP, NULL, 8)) == NULL) { throw std::exception("Failed to create IOCP object."); } All appears to go well until I try to send some data over the socket. SocketData* socketData = new SocketData; socketData->hEvent = 0; DWORD bytesSent = 0; if (WSASend(m_socket, socketData->SetBuffer(socketData->GenerateLoginRequestHeader()), 1, &bytesSent, NULL, reinterpret_cast<OVERLAPPED*>(socketData), NULL) == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING) { throw std::exception("Failed to send data."); } Instead of returning SOCKET_ERROR with the last error set to WSA_IO_PENDING, WSASend returns immediately. I need the IO to pend and for it's completion to be handled in my thread function which is also my worker thread. unsigned int __stdcall MyClass::WorkerThread(void* lpThis) { } I've done this before but I don't know what is going wrong in this case, I'd greatly appreciate any efforts in helping me fix this problem.

    Read the article

  • keywords in latex

    - by Tom
    Hi, Is there any enviroment / package to specify the keywords in a latex article? something like \begin{keywords} latex, stackoverflow, howto \end{keywords}

    Read the article

  • Java Swing: How to make the JComboxBox drop down list taller?

    - by NoozNooz42
    How to make the "dropdown" (or "popup", I don't know how it's called) of a JComboBox taller on the screen? By default, when I open my JComboBox I see, say, 7 out of 29 items, then I need to scroll. What should I do so that I can see, say, 15 out of these 32 items? (or if the dropdown is, say, 150 pixels tall, how can I make it 300 pixels tall?) I've read the Sun tutorial on JComboBox and the JavaDoc but I must have overlooked the method(s) to call.

    Read the article

  • travesersing the dom with inexact parameters

    - by rashcroft23
    Hi, I want to grab the image src on a product page in a e commerce website. I'm writing this as a bookmarklet, so I'd like the code to work universally as possible. I've noticed that there are only two reoccurring factors in the product image tag among top e-commerce websites (amazon, bestbuy ect.): border=0 and 180<width&height<400. So how could I write a selector that would give me the srcof the first img element on the page with no border and width & height between 180 and 400 px? Or is there a better way of doing this? P.S. since I'm trying to keep the bookmarklet as light as possible, I don't want to use any libraries (jquery, yui etc)

    Read the article

  • Translating profile fields. Drupal

    - by Toktik
    Hey all, I have multilanguage site, which have 3 languages. I'm using Username as field for First and Last name combined, and some Profile(core module) fields for example biography text field. So I want to translate Username and Profile fields in each language. I have tested it with i18n, it is not working with username and profile text field. So if Username problem I can use profile text fields for First and Last name. But no one module is providing localization support for Profile fields. Any suggestions? Thank you

    Read the article

  • Save as DialogBox to save textbox content to a newfile using asp.net

    - by user195114
    I want the users to type their text in the given textbox and on clicking on createNewFile Button, a SaveAs Dialogbox should popup and the users should browse through the location and save the file as desired. I have tried some thing but (1) the dialog box goes behind the application (2) when run, dialogbox opens 3 times, means it executes 3 times REPLY TO THE POST protected void btnNewFile_Click(object sender, EventArgs e) { StreamWriter sw = null; try { SaveFileDialog sdlg = new SaveFileDialog(); DialogResult result = sdlg.ShowDialog(); sdlg.InitialDirectory = @"C:\"; sdlg.AddExtension = true; sdlg.CheckPathExists = true; sdlg.CreatePrompt = false; sdlg.OverwritePrompt = true; sdlg.ValidateNames = true; sdlg.ShowHelp = true; sdlg.DefaultExt = "txt"; // sdlg.ShowDialog = Form.ActiveForm; string file = sdlg.FileName.ToString(); string data = txtNewFile.Text; if (sdlg.ShowDialog() == DialogResult.OK) { sw.WriteLine(txtNewFile.Text); sw.Close(); } if (sdlg.ShowDialog() == DialogResult.Cancel) { sw.Dispose(); } //Save(file, data); } catch { } finally { if (sw != null) { sw.Close(); } } } private void Save(string file, string data) { StreamWriter writer = new StreamWriter(file); SaveFileDialog sdlg1 = new SaveFileDialog(); try { if (sdlg1.ShowDialog() == DialogResult.OK) { writer.Write(data); writer.Close(); } else writer.Dispose(); } catch (Exception xp) { MessageBox.Show(xp.Message); } finally { if (writer != null) { writer.Close(); } } } I have tried this.

    Read the article

  • Need help with Binary Columns

    - by nusrath
    Hi, I have to query a column containing a Binary column with data like this ®â{Õ¦K!Eòû¦?;#§ø. How can i query this colmn..if I wanted something like: SELECT Name FROM Users WHERE ID = ®â{Õ¦K!Eòû¦?;#§ø THanks

    Read the article

  • iphone build error that makes me want to buy a nail gun

    - by sol
    I'm just trying to build a simple update (which I have done before) for an iphone app, but now for some reason I'm getting this error. Can anyone tell me what it means? Command/Developer/Library/Xcode/Plug-ins/CoreBuildTasks.xcplugin/Contents/Resources/copyplist failed with exit code 127 sh: plutil: command not found Here are the Build Results: CopyPNGFile /Users/me/path/build/Dist-iphoneos/MyApp.app/img_000.png images/img_000.png cd /Users/me/ setenv COPY_COMMAND /Developer/Library/PrivateFrameworks/DevToolsCore.framework/Resources/pbxcp setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/System/Library/Frameworks/JavaVM.frameworK/Versions/1.6/Home/" "/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Plug-ins/iPhoneOS Build System Support.xcplugin/Contents/Resources/copypng" -compress "" /Users/path/images/img_000.png /Users/me/path/build/Dist-iphoneos/MyApp.app/img_000.png sh: dirname: command not found CopyPlistFile /Users/me/path/build/Dist-iphoneos/MyApp.app/Entitlements.plist Entitlements.plist cd /Users/me/ setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/System/Library/Frameworks/JavaVM.frameworK/Versions/1.6/Home/" /Developer/Library/Xcode/Plug-ins/CoreBuildTasks.xcplugin/Contents/Resources/copyplist --convert binary1 Entitlements.plist --outdir /Users/me/path/build/Dist-iphoneos/MyApp.app sh: plutil: command not found

    Read the article

  • Building iPhone static library for armv6 and armv7 that includes another static library

    - by Martijn Thé
    Hi, I have an Xcode project that has a "master" static library target, that includes/links to a bunch of other static libraries from other Xcode projects. When building the master library target for "Optimized (armv6 armv7)", an error occurs in the last phase, during the CreateUniversalBinary step. For each .o file of the libraries that is included by the master library, the following error is reported (for example, the FBConnectGlobal.o file): warning for architecture: armv6 same member name (FBConnectGlobal.o) in output file used for input files: /Developer_Beta/Builds/MTToolbox/MTToolbox.build/Debug-iphoneos/MTToolbox.build/Objects-normal/armv6/libMTToolbox.a(FBConnectGlobal.o) and: /Developer_Beta/Builds/MTToolbox/MTToolbox.build/Debug-iphoneos/MTToolbox.build/Objects-normal/armv7/libMTToolbox.a(FBConnectGlobal.o) due to use of basename, truncation and blank padding In the end, Xcode tells that the build has succeeded. However, when using the final static library in an application project, it won't build because it finds duplicate symbols in one part of build (armv6) and misses symbols in the other part of the build (armv7). Any ideas how to fix this? M

    Read the article

  • How should I escape strings in JSON?

    - by Bytecode Ninja
    When creating JSON data manually, how should I escape string fields? Should I use something like Apache Commons Lang's StringEscapeUtilities.escapeHtml, StringEscapeUtilities.escapeXml, or should I use java.net.URLEncoder? The problem is that when I use SEU.escapeHtml, it doesn't escape quotes and when I wrap the whole string in a pair of 's, a malformed JSON will be generated.

    Read the article

  • Hadoop Map Reduce job never finishes

    - by rohanbk
    I am running a Hadoop Map Reduce job using a Python Mapper and Reducer script, and Hadoop Streaming. Both my Map and Reduce jobs run till they are both 100%, but the job doesn't end. I know that when things go sour, Hadoop will terminate the job, but in this case, both stages reach a 100% and just never end. Has anyone else encountered anything similar? Also, how do I debug my program to figure out where things are going wrong? If I use a smaller input file, and I just run something like: $> cat input_file | mapper.py | sort | reduce.py >> output_file everything works perfectly fine. However, when I use Hadoop, things don't work out.

    Read the article

  • How to consume PHP SOAP service using WCF

    - by mr.b
    I am new in web services so apologize me if I am making some cardinal mistake here, hehe. I have built SOAP service using PHP. Service is SOAP 1.2 compatible, and I have WSDL available. I have enabled sessions, so that I can track login status, etc. I don't need some super security here (ie message-level security), all I need is transport security (HTTPS), since this service will be used infrequently, and performances are not so much of an issue. I am having difficulties making it to work at all. C# throws some unclear exception ("Server returned an invalid SOAP Fault. Please see InnerException for more details.", which in turn says "Unbound prefix used in qualified name 'rpc:ProcedureNotPresent'."), but consuming service using PHP SOAP client behaves as expected (including session and all). So far, I have following code. note: due to amount of real code, I am posting minimal code configuration PHP SOAP server (using Zend Soap Server library), including class(es) exposed via service: <?php class Verification_LiteralDocumentProxy { protected $instance; public function __call($methodName, $args) { if ($this->instance === null) { $this->instance = new Verification(); } $result = call_user_func_array(array($this->instance, $methodName), $args[0]); return array($methodName.'Result' => $result); } } class Verification { private $guid = ''; private $hwid = ''; /** * Initialize connection * * @param string GUID * @param string HWID * @return bool */ public function Initialize($guid, $hwid) { $this->guid = $guid; $this->hwid = $hwid; return true; } /** * Closes session * * @return void */ public function Close() { // if session is working, $this->hwid and $this->guid // should contain non-empty values } } // start up session stuff $sess = Session::instance(); require_once 'Zend/Soap/Server.php'; $server = new Zend_Soap_Server('https://www.somesite.com/api?wsdl'); $server->setClass('Verification_LiteralDocumentProxy'); $server->setPersistence(SOAP_PERSISTENCE_SESSION); $server->handle(); WSDL: <definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="https://www.somesite.com/api" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap-enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" name="Verification" targetNamespace="https://www.somesite.com/api"> <types> <xsd:schema targetNamespace="https://www.somesite.com/api"> <xsd:element name="Initialize"> <xsd:complexType> <xsd:sequence> <xsd:element name="guid" type="xsd:string"/> <xsd:element name="hwid" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="InitializeResponse"> <xsd:complexType> <xsd:sequence> <xsd:element name="InitializeResult" type="xsd:boolean"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="Close"> <xsd:complexType/> </xsd:element> </xsd:schema> </types> <portType name="VerificationPort"> <operation name="Initialize"> <documentation> Initializes connection with server</documentation> <input message="tns:InitializeIn"/> <output message="tns:InitializeOut"/> </operation> <operation name="Close"> <documentation> Closes session between client and server</documentation> <input message="tns:CloseIn"/> </operation> </portType> <binding name="VerificationBinding" type="tns:VerificationPort"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="Initialize"> <soap:operation soapAction="https://www.somesite.com/api#Initialize"/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation> <operation name="Close"> <soap:operation soapAction="https://www.somesite.com/api#Close"/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation> </binding> <service name="VerificationService"> <port name="VerificationPort" binding="tns:VerificationBinding"> <soap:address location="https://www.somesite.com/api"/> </port> </service> <message name="InitializeIn"> <part name="parameters" element="tns:Initialize"/> </message> <message name="InitializeOut"> <part name="parameters" element="tns:InitializeResponse"/> </message> <message name="CloseIn"> <part name="parameters" element="tns:Close"/> </message> </definitions> And finally, WCF C# consumer code: [ServiceContract(SessionMode = SessionMode.Required)] public interface IVerification { [OperationContract(Action = "Initialize", IsInitiating = true)] bool Initialize(string guid, string hwid); [OperationContract(Action = "Close", IsInitiating = false, IsTerminating = true)] void Close(); } class Program { static void Main(string[] args) { WSHttpBinding whb = new WSHttpBinding(SecurityMode.Transport, true); ChannelFactory<IVerification> cf = new ChannelFactory<IVerification>( whb, "https://www.somesite.com/api"); IVerification client = cf.CreateChannel(); Console.WriteLine(client.Initialize("123451515", "15498518").ToString()); client.Close(); } } Any ideas? What am I doing wrong here? Thanks!

    Read the article

  • App Engine: how would you... snapshotting entities

    - by Andrew B.
    Let's say you have two kinds, Message and Contact, related by a db.ListProperty of keys on Message. A user creates a message, adds some contacts as recipients, and emails the message. Later, the user deletes one of the contact entities that was a recipient of the message. Our application should delete the appropriate Contact entity, but we want to preserve the original recipient list for the message that was sent for the user's records. In essence, we want a snapshot of the message entity at the time it was sent. If we naively delete the contact entity, though, we lose snapshot integrity; if not, we are left with an invalid key. How would you handle this situation, either in controller logic or model changes? class User(db.Model): email = db.EmailProperty(required=True) class Contact(db.Model): email = db.EmailProperty(required=True) user = db.ReferenceProperty(User, collection_name='contacts') class Message(db.Model): recipients = db.ListProperty(db.Key) # contacts sender = db.ReferenceProperty(User, collection_name='messages') body = db.TextProperty() is_emailed = db.BooleanProperty(default=False)

    Read the article

  • How to decide between using PLINQ and LINQ at runtime?

    - by Hamish Grubijan
    Or decide between a parallel and a sequential operation in general. It is hard to know without testing whether parallel or sequential implementation is best due to overhead. Obviously it will take some time to train "the decider" which method to use. I would say that this method cannot be perfect, so it is probabilistic in nature. The x,y,z do influence "the decider". I think a very naive implementation would be to give both 1/2 chance at the beginning and then start favoring them according to past performance. This disregards x,y,z, however. I suspect that this question would be better answered by academics than practitioners. Anyhow, please share your heuristic, your experience if any, your tips on this. Sample code: public interface IComputer { decimal Compute(decimal x, decimal y, decimal z); } public class SequentialComputer : IComputer { public decimal Compute( ... // sequential implementation } public class ParallelComputer : IComputer { public decimal Compute( ... // parallel implementation } public class HybridComputer : IComputer { private SequentialComputer sc; private ParallelComputer pc; private TheDecider td; // Helps to decide between the two. public HybridComputer() { sc = new SequentialComputer(); pc = new ParallelComputer(); td = TheDecider(); } public decimal Compute(decimal x, decimal y, decimal z) { decimal result; decimal time; if (td.PickOneOfTwo() == 0) { // Time this and save result into time. result = sc.Compute(...); } else { // Time this and save result into time. result = pc.Compute(); } td.Train(time); return result; } }

    Read the article

  • Prevent Windows Key from Opening Start Menu in Windows 7

    - by Jeromy Anglim
    I'd like to be able to stop the Windows Key from activating the Start Menu on Windows 7. I don't want to disable the Windows Key completely. I'd like Ctrl + Esc to still open the Start Menu. I know that you can use AutoHotKey to disable the Windows Key completely. The reason I want this functionality is that I have a lot of shortcut keys linked to the Windows key and this often results in accidentally opening the start menu.

    Read the article

  • Ruby on Rails - Create Entity with Relationship

    - by SooDesuNe
    I'm new to rails, so be nice. I'm building a "rolodex" type application, and this question is about the best way to handle creating an entity along with several relationship entities at the same time. For (a contrived) example: My application will have a Person model, which has_one Contact_Info model. On the create.html.erb page for Person it makes sense for the user of my appliction to create the person, and the contact_info at the same time. It doesn't seem right to include details for creating a contact directly in the create view/controller for person. What's the rails way to handle this?

    Read the article

  • Can't get the value of an attribute with Selenium RC using xpath??

    - by Gj
    I'm trying to get the first href attribute in a page using Selenium RC (in Python): sel.get_text("xpath=//@href") this returns an empty string. However, an identical xpath on the same page inside Firefox (using the "View XPath" extension) yields the correct value. I've tried fiddling with it, but the same happens for other attributes (eg @class) -- is there something awfully wrong with selenium or am I overlooking something trivial here?

    Read the article

  • Better way to make side-by-side DIVs in CSS

    - by JoelFan
    I have 2 DIV's that I want to be side-by-side under all circumstances. So far I am accomplishing it like this: <div style="float: left"> <table> ... </table> </div> <div style="float: right; overflow: scroll; width: 1000px"> <pre> ... </pre> </div> However, I don't like that I have to specify an absolute width in the 2nd div. I just want the 1st div to be the minimum width to display the table and 2nd div to take up the rest of the space without overflowing. Is there a better way?

    Read the article

  • Getting a table cell to become a different color on mouseover

    - by Andrei Korchagin
    Currently, when I create a table, and I mouseover a cell, that entire row is highlighted. I'm trying to make it so that it is only the immediate cell. Here's all the CSS code that pertains to tables in my stylesheet: table{margin:.5em 0 1em;} table td,table th{text-align:center;border-right:1px solid #fff;padding:.4em .8em;} table th{background-color:#5e5e5e;color:#fff;text-transform:uppercase;font-weight:bold;border- bottom:1px solid #e8e1c8;} table td{background-color:#eee;} table th a{color:#d6f325;} table th a:hover{color:#fff;} table tr.even td{background-color:#ddd;} table tr:hover td{background-color:#fff;} table.nostyle td,table.nostyle th,table.nostyle tr.even td,table.nostyle tr:hover td{border:0;background:none;background-color:transparent;} I know it's probably a simple fix but I can't find where to make it work. Everything I try just kills the mouseover effect entirely rather than making it the way I want it. Thanks in advance!

    Read the article

  • Application crashing in the iPad but working fine in iPad simulator.

    - by srikanth rongali
    Hi, I am writing a game in cocos2d. In the iPad Simulator the application is running good. While I am running the application in the iPad. But it was crashing by giving the following message in terminal. I am using 2048x2048 CCSpriteSheets in my code. I used instruments tool there is sudden increase in memory to 32MB before crashing. It is crashing at CCSpriteFrameCache . Program loaded. target remote-mobile /tmp/.XcodeGDBRemote-6258-64 Switching to remote-macosx protocol mem 0x1000 0x3fffffff cache mem 0x40000000 0xffffffff none mem 0x00000000 0x0fff none continue The program is not being run. The program is not being run. Thank you.

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >