Search Results

Search found 24043 results on 962 pages for 'private methods'.

Page 71/962 | < Previous Page | 67 68 69 70 71 72 73 74 75 76 77 78  | Next Page >

  • Why is my program freezing when I use a method? (Java)

    - by user2915567
    When I use a boolean method in the Main body, my program freezes and stops working. I've tried putting the method at different places but the exact same thing happens - it freezes. The method is really simple and well-written, I'm not sure what's causing the problem. P.S. The method is on the bottom of the code. Thanks for your help! Edit: That was a dumb question now that I look at it. Thanks again everyone! public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int stringNumber = 0; String[] stringArray = new String[10]; for (int i = 0; i <= stringArray.length; i++) { boolean itemExists = false; boolean AddItem = AddItem(); if (AddItem == true) { out.println("\nEnter a string"); String input = keyboard.next(); if (i > 0) { for (int j = 0; j < stringArray.length; j++) { if (input.equalsIgnoreCase(stringArray[j])) { itemExists = true; out.println("Item \"" + input + "\" already exists."); break; } } } if (itemExists == false) { stringArray[stringNumber] = input; out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.\n"); } else { out.println("Try again."); i--; } PrintArray(stringArray); stringNumber++; } } } // This is the method I was talking about // public static boolean AddItem() { Scanner keyboard = new Scanner(System.in); int input = keyboard.nextInt(); out.println("If you want to add an item, Press 1"); if (input == 1) { return true; } else { out.println("Invalid input."); return false; } }

    Read the article

  • Creating a Ruby method that pads an Array

    - by CJ Johnson
    I'm working on creating a method that pads an array, and accepts 1. a desired value and 2. an optional string/integer value. Desired_size reflects the desired number of elements in the array. If a string/integer is passed in as the second value, this value is used to pad the array with extra elements. I understand there is a 'fill' method that can shortcut this - but that would be cheating for the homework I'm doing. The issue: no matter what I do, only the original array is returned. I started here: class Array def pad(desired_size, value = nil) desired_size >= self.length ? return self : (desired_size - self.length).times.do { |x| self << value } end end test_array = [1, 2, 3] test_array.pad(5) From what I researched the issue seemed to be around trying to alter self's array, so I learned about .inject and gave that a whirl: class Array def pad(desired_size, value = nil) if desired_size >= self.length return self else (desired_size - self.length).times.inject { |array, x| array << value } return array end end end test_array = [1, 2, 3] test_array.pad(5) The interwebs tell me the problem might be with any reference to self so I wiped that out altogether: class Array def pad(desired_size, value = nil) array = [] self.each { |x| array << x } if desired_size >= array.length return array else (desired_size - array.length).times.inject { |array, x| array << value } return array end end end test_array = [1, 2, 3] test_array.pad(5) I'm very new to classes and still trying to learn about them. Maybe I'm not even testing them the right way with my test_array? Otherwise, I think the issue is I get the method to recognize the desired_size value that's being passed in. I don't know where to go next. Any advice would be appreciated. Thanks in advance for your time.

    Read the article

  • Multiple generic parameters on a html helper extension method

    - by WestDiscGolf
    What I'm trying to do is create an extension method for the HtmlHelper to create a specific output and associated details like TextBoxFor<. What I want to do is specify the property from the model class as per TextBoxFor<, then an associated controller action and other parameters. So far the signature of the method looks like: public static MvcHtmlString Create<TModel, TProperty, TController>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Expression<Action<TController>> action, object htmlAttributes) where TController : Controller where TModel : class The issue occurs when I go to call it. In my view if I call it as per the TextBoxFor without specifying the Model type I am able to specify the lambda expression to set the property which it's for, but when I go to specify the action I am unable to. However, when I specify the controller type Html.Create<HomeController>( ... ) I am unable to specify the model property that the control is to be created for. I want to be able to call it like <%= Html.Create(x => x.Title, controller => controller.action, null) %> I've been hitting my head for a few hours now on this issue over the past day, can anyone point me in the right direction?

    Read the article

  • Creating a method that is simultaneously an instance and class method

    - by Mike Axiak
    In Python, I'd like to be able to create a function that behaves both as a class function and an instance method, but with the ability to change behaviors. The use case for this is for a set of serializable objects and types. As an example: >>> class Thing(object): #... >>> Thing.to_json() 'A' >>> Thing().to_json() 'B' I know that given the definition of classmethod() in funcobject.c in the Python source, this looks like it'd be simple with a C module. Is there a way to do this from within python? Thanks!

    Read the article

  • Cocos2d: is it good practice to use a shared GameScene when having various levels?

    - by mm24
    In my code (based on the ShootEmUp example in this book, which I highly reccomend, source code in chapter 8 available here) I often use the trick of accessing the GameScene via: +(GameScene*) sharedGameScene; which returns a reference to the static instance of GameScene. Is a static instance of GameScene as in the book still a valid pattern in case I want a MainMenu calling GameScene initialized with different level data each time (e.g. different enemies)? (I have created a sceneWithId:(int) method where I load different level data each time. Or should I pheraps create a GameScene class and then sublcass it? E.g. FirstGameScene : GameScene

    Read the article

  • Codeigniter: Library function--I'm stuck

    - by Kevin Brown
    I have a library function that sets up my forms, and submits data. They're long, and they work, so I'll spare you reading my code. :) I simply need a way for my functions to determine how to handle the data. Until now, the function did one thing: Submit a report for the current user. NOW, the client has requested that an administrator also be able to complete a form--this means that the form would be filled out, and it would CREATE a user at the same time, whereas the current function EDITS and is accessed by an EXISTING user. Do I need a separate function to do essentially the same thing? How do I make one function perform two tasks? One to update a user, and if there is no user, create one. Current controller: function survey() { $id = $this->session->userdata('id'); $data['member'] = $this->home_model->getUser($id); //Convert the db Object to a row array $data['manager'] = $data['member']->row(); $manager_id = $data['manager']->manager_id; $data['manager'] = $this->home_model->getUser($manager_id); $data['manager'] = $data['manager']->row(); $data['header'] = "Home"; $this->survey_form_processing->survey_form($this->_container,$data, $method); } Current Library: function survey_form($container) { //Lots of validation stuff $this->CI->validation->set_rules($rules); if ( $this->CI->validation->run() === FALSE ) { // Output any errors $this->CI->validation->output_errors(); } else { // Submit form $this->_submit(); } $this->CI->load->view($container,$data); The submit function is huge too. Basically says, "Update table with data where user_id=current user" I hope this wasn't too confusing. I'll create two functions if need be, but I'd like to keep redundancy down! }

    Read the article

  • Will my LinqToSql execution be deffered if i filter with IEnumerable<T> instead of IQueryable<T>?

    - by cottsak
    I have been using these common EntityObjectFilters as a "pipes and filters" way to query from a collection a particular item with an ID: public static class EntityObjectFilters { public static T WithID<T>(this IQueryable<T> qry, int ID) where T : IEntityObject { return qry.SingleOrDefault<T>(item => item.ID == ID); } public static T WithID<T>(this IList<T> list, int ID) where T : IEntityObject { return list.SingleOrDefault<T>(item => item.ID == ID); } } ..but i wondered to myself: "can i make this simpler by just creating an extension for all IEnumerable<T> types"? So i came up with this: public static class EntityObjectFilters { public static T WithID<T>(this IEnumerable<T> qry, int ID) where T : IEntityObject { return qry.SingleOrDefault<T>(item => item.ID == ID); } } Now while this appears to yield the same result, i want to know that when applied to IQueryable<T>s will the expression tree be passed to LinqToSql for evaluating as SQL code or will my qry be evaluated in it's entirety first, then iterated with Funcs? I'm suspecting that (as per Richard's answer) the latter will be true which is obviously what i don't want. I want the same result, but the added benefit of the delayed SQL execution for IQueryable<T>s. Can someone confirm for me what will actually happen and provide simple explanation as to how it would work?

    Read the article

  • PHP Class Question

    - by Jerry
    Hi all I am trying to build a PHP class to check the username and password in MySql. I am getting "mysql_query(): supplied argument is not a valid MySQL-Link resource in D:\2010Portfolio\football\main.php on line 38" database has errors:" message. When I move my userQuery code out of my Class, it works fine. Only if it is inside my Class. I am not sure if the problem is that I don't build the connection to mysql inside my Class or not. Thanks for any helps!! Here is my code <?php $userName=$_POST['userName']; $userPw=$_POST['password']; class checkUsers { public $userName; public $userPw; function checkUsers($userName='', $userPw=''){ $this->userName=$userName; $this->userPw=$userPw; } function check1(){ if (empty($this->userName) || empty($this->userPw)){ $message="<strong>Please Enter Username and Password</strong>"; }else{ //line 38 is next line $userQuery=mysql_query("SELECT userName, userPw FROM user WHERE userName='$this->userName' and userPw='$this->userPw'", $connection); if (!$userQuery){ die("database has errors: ". mysql_error()); } if(mysql_num_rows($userQuery)==0){ $message="Please enter valid username and password"; } }//end empty check return $message; }//end check1 method }//end Class $checkUser=new checkUsers($userName, $userPw); echo $checkUser->check1(); ?> I appreciate any helps!!!!

    Read the article

  • How to retrieve the file icons and file previews used by windows explorer?

    - by user193655
    I am developing a Delphi documents management application, so somehow I am giving the user some functionality similar to windows explorer. Currently I am using imagelists where I manually maintain the icons (like one for pdf, one for xls, ...) and when I need to display an icon for a filetype that I don't explicitly support I have a generic icon. Is there a way to retrieve the icon used by windows, like MyTImage := GiveMeDefaultIconForExtension('pdf'); In Vista and Seven this should be an icon with multiple resolutions I think. Moreover I would like to know if there is a way to get the preview used by windows explorer. For example windows explorer creates a small thumbnail for a pdf document for example, and displays it when the user chooses to view "big icons". Is there a way to retrieve that preview? MyTImage := GiveMePreviewForFile('C:\Test\File.pdf');

    Read the article

  • Facebook iOS SDK Share Dialog - Sharing on a Friend's Wall

    - by JPK
    Is it possible to use the Facebook iOS SDK Share Dialog to share on a Friend's Wall? I know that it is possible to do this using the Feed Dialog, but that provides the user with a less than optimal experience, and seems to be discouraged by Facebook. It would be fantastic if we could configure the Share Dialog to share with one particular friend. Additionally, is there a way to share with a friend privately (such that it would be sent to Messages)? I have researched pretty extensively and it seems like there is not a way to do either of these things using the iOS SDK - I would just like to confirm that I am not missing something.

    Read the article

  • Call a dynamically generated method on a ILGenerator on the same type

    - by Thiado de Arruda
    Normally, when I want to call a dynamic method in another ILGenerator object that is writing a method on the same type I do the following : generator.Emit(OpCodes.Ldarg_0); // reference to the current object generator.Emit(OpCodes.Ldstr, "someArgument"); generator.Emit(OpCodes.Call, methodBuilder); //this methodbuilder is also defined on this dynamic type. However, I faced the following problem: I cant have a reference to the methodbuilder of the method I want to call, because it is generated by another framework(I only get a reference to the current TypeBuilder). This method is defined as protected virtual(and overriden on the methodbuilder I cant get a reference to) in the base class of the current dynamic type and I can get a reference to it by doing this : generator.Emit(OpCodes.Ldarg_0); // reference to the current object generator.Emit(OpCodes.Ldstr, "someArgument"); generator.Emit(OpCodes.Call, baseType.GetMethod("SomeMethodDefinedInBaseClassThatWasOverridenInThisDynamicType")); The problem is that this calls the method on the base type and not the overriden method. Is there any way I can get a reference to a methodbuilder only having a reference to the typebuilder that defined it? Or is there a way to call a method using ILGenerator without having to pass the 'MethodInfo' object to it?

    Read the article

  • Find a base case for a recursive void method

    - by Evan S
    I am doing homework. I would like to build a base case for a recursion where ordering given numbers (list2) in ascending order. Purpose of writing this codes is that when all numbers are in ascending order then should stop calling a method called ascending(list2, list1); and all values in list2 should be shipped to list1. For instance, list2 = 6,5,4,3,2,1 then list2 becomes empty and list1 should be 1,2,3,4,5,6. I am trying to compare result with previous one and if matches then stop. But I can't find the base case to stop it. In addition, Both ascending() and fixedPoint() are void method. Anybody has idea? lol Took me 3 days... When I run my code then 6,5,4,3,2,1 5,6,4,3,2,1 4,5,6,3,2,1 3,4,5,6,2,1 2,3,4,5,6,1 1,2,3,4,5,6 1,2,3,4,5,6 1,2,3,4,5,6 1,2,3,4,5,6 1,2,3,4,5,6 infinite............. public class Flipper { public static void main(String[] args) { Flipper aFlipper = new Flipper(); List<Integer> content = Arrays.asList(6,5,4,3,2,1); ArrayList<Integer> l1 = new ArrayList<Integer>(content); ArrayList<Integer> l2 = new ArrayList<Integer>(); // empty list aFlipper.fixedPoint(l2,l1); System.out.println("fix l1 is "+l1); System.out.println("fix l2 is "+l2); } public void fixedPoint(ArrayList<Integer> list1, ArrayList<Integer> list2) { // data is in list2 ArrayList<Integer> temp1 = new ArrayList<Integer>(); // empty list if (temp1.equals(list2)) { System.out.println("found!!!"); } else { ascending(list2, list1); // data, null temp1 = list1; // store processed value System.out.println("st list1 is "+list1); System.out.println("st list2 is "+list2); } fixedPoint(list2, list1); // null, processed data }

    Read the article

  • How to retrieve the file previews used by windows explorer in Windows vista and seven?

    - by user193655
    I am developing a Delphi documents management application, so somehow I am giving the user some functionality similar to windows explorer. I would like to know if there is a way to get the preview used by windows explorer. For example windows explorer creates a small thumbnail for a pdf document for example, and displays it when the user chooses to view "big icons". Is there a way to retrieve that preview? MyTImage := GiveMePreviewForFile('C:\Test\File.pdf');

    Read the article

  • Create Generic Class Instance from Static Method in a Derived Class

    - by user343547
    I have a class in C# with a template and static method similar to class BClass<T> { public static BClass<T> Create() { return new BClass<T>(); } } From this I derive a class and specify a template parameter to the base class class DClass : BClass<int> { } A problem occurs when I try to use the static method to create an instance of D class Program { static void Main(string[] args) { DClass d = DClass.Create(); } } Gives a compiler error "Cannot implicitly convert type 'Test.BClass<int ' to 'Test.DClass'." Adding the below cast leads to a runtime casting exception. DClass d = (DClass)DClass.Create(); Is there any succint way to allow the static method to create instances of the derived class? Ideally I would like the equivalent of a c++ typedef and I don't want the below syntax (which does work). BClass<int> d = DClass.Create();

    Read the article

  • Extension method question. Why do I need to use someObj = someObj.somemethod();

    - by Kettenbach
    Hi All, I have a simple extension method that I would like to use to add an item to an array of items. public static T[] addElement<T>(this T[] array, T elementToAdd) { var list = new List<T>(array) {elementToAdd}; return list.ToArray(); } this works ok, but when I use it, I am having to set the array equal to the return value. I see that I am returning an Array. I likely want this method to be void, but I would like the item added. Does anyone have any ideas on what I need to do , to make this work the way I am wanting? Instead of someArray = someArray.addElement(item), I just want to do someArray.addElement(item) and then someArray be ready to go. What am I missing here? Thanks, ~ck in San Diego

    Read the article

  • ControlCollection extension method optimization

    - by Johan Leino
    Hi, got question regarding an extension method that I have written that looks like this: public static IEnumerable<T> FindControlsOfType<T>(this ControlCollection instance) where T : class { T control; foreach (Control ctrl in instance) { if ((control = ctrl as T) != null) { yield return control; } foreach (T child in FindControlsOfType<T>(ctrl.Controls)) { yield return child; } } } public static IEnumerable<T> FindControlsOfType<T>(this ControlCollection instance, Func<T, bool> match) where T : class { return FindControlsOfType<T>(instance).Where(match); } The idea here is to find all controls that match a specifc criteria (hence the Func<..) in the controls collection. My question is: Does the second method (that has the Func) first call the first method to find all the controls of type T and then performs the where condition or does the "runtime" optimize the call to perform the where condition on the "whole" enumeration (if you get what I mean). secondly, are there any other optimizations that I can do to the code to perform better. An example can look like this: var checkbox = this.Controls.FindControlsOfType<MyCustomCheckBox>( ctrl => ctrl.CustomProperty == "Test" ) .FirstOrDefault();

    Read the article

  • How to call another class's method from my app delegate

    - by Jared
    I have an application that utilizes UILocalNotifications to pop-up UIAlertViews. When the notification fires, the user chooses to go into the app, and this method is called from my app delegate: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {...} Where I can handle it and where I also prompt another alertview for more information. So when the app launches, it is displaying view A, and then the alertview pops up and prompts for input. This alertview, however, is originating from my app delegate. I need to be able to reload view A when the user hits Yes/No on the alertview. How can I do that from within my app delegate? Any help is appreciated!!

    Read the article

  • Process every pair in a sequence

    - by Henry Jackson
    I'm looking for a concise way to process every (unordered) pair of elements in a sequence in .NET. I know I can do it with nested foreach loops, but I was looking for something a little more readable. I was imagining something like a modified Any() extension method: IEnumerable<Transaction> transactions = ... if (transactions.AnyPair( (first, second) => first.UniqueID == second.UniqueID)) throw ... Or maybe a foreach-style one: IEnumerable<JigsawPiece> pieces = ... pieces.ForEachPair( (first, second) => { TryFit(first, second); }); This question has been asked for other languages (e.g. see http://stackoverflow.com/questions/942543/operation-on-every-pair-of-element-in-a-list), but I'm looking for a .NET solution.

    Read the article

  • sending and receiving with sockets in java?

    - by Darksole
    I am working on sending and receiving from clients and servers in java, and am stumped at the moment. the client socket is to contact a server at “localhost” port 4321. The client will receive a string from the server and alternate spelling the contents of this string with the server. For example, given the string “Bye Bye”, the client (which always begins sending the first letter) sends “B”, receives “y”, sends “e”, receives “ ”, sends “B”, receives “y”, sends “e”, and receives “done!”, which is the string that either client or server will send after the last letter from the original string is received. After “done!” is transmitted, both client and server close their communications. How would i go about getting the first string and then going back and forth sending and reciving letters that make the string, and when finished either send or get done!? import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class Program2 { public static void goClient() throws UnknownHostException, IOException{ String server = "localhost"; int port = 4321; Socket socket = new Socket(server, port); InputStream inStream = socket.getInputStream(); OutputStream outStream = socket.getOutputStream(); Scanner in = new Scanner(inStream); PrintWriter out = new PrintWriter(outStream, true); String rec = ""; if(in.hasNext()){ rec = in.nextLine(); } char[] array = new char[rec.length()]; for(int i = 0; i < rec.length(); i++){ array[i] = rec.charAt(i); } while(in.hasNext()){ for(int x = 0; x < array.length + 1; x+=2){ String str = in.nextLine(); str = Character.toString(array[x]); out.println(str); } in.close(); socket.close(); } } }

    Read the article

  • Java Method declaration

    - by user1701604
    I'm trying to declare a method for my program that takes only a 5 digit integer and for each digit of the integer, reads a value from the program and prints it out. I understand this isn't very clear but im having trouble relaying what I mean. I understand it will be some sort of for loop to read each digit of the integer individually until something reaches 5. Something like the charAt() string method but works for digits.

    Read the article

  • LINQ .Cast() extension method fails but (type)object works.

    - by Ben Robinson
    To convert between some LINQ to SQL objects and DTOs we have created explicit cast operators on the DTOs. That way we can do the following: DTOType MyDTO = (LinqToSQLType)MyLinq2SQLObj; This works well. However when you try to cast using the LINQ .Cast() extension method it trows an invalid cast exception saying cannot cast type Linq2SQLType to type DTOType. i.e. the below does not work List<DTO.Name> Names = dbContact.tNames.Cast<DTO.Name>() .ToList(); But the below works fine: DAL.tName MyDalName = new DAL.tName(); DTO.Name MyDTOName = (DTO.Name)MyDalName; and the below also works fine List<DTO.Name> Names = dbContact.tNames.Select(name => (DTO.Name)name) .ToList(); Why does the .Cast() extension method throw an invalid cast exception? I have used the .Cast() extension method in this way many times in the past and when you are casting something like a base type to a derived type it works fine, but falls over when the object has an explicit cast operator.

    Read the article

  • Python: Hack to call a method on an object that isn't of its class

    - by cool-RR
    Assume you define a class, which has a method which does some complicated processing: class A(object): def my_method(self): # Some complicated processing is done here return self And now you want to use that method on some object from another class entirely. Like, you want to do A.my_method(7). This is what you'd get: TypeError: unbound method my_method() must be called with A instance as first argument (got int instance instead). Now, is there any possibility to hack things so you could call that method on 7? I'd want to avoid moving the function or rewriting it. (Note that the method's logic does depend on self.) One note: I know that some people will want to say, "You're doing it wrong! You're abusing Python! You shouldn't do it!" So yes, I know, this is a terrible terrible thing I want to do. I'm asking if someone knows how to do it, not how to preach to me that I shouldn't do it.

    Read the article

  • How do I avoid boxing/unboxing when extending System.Object?

    - by Robert H.
    I'm working on an extension method that's only applicable to reference types. I think, however, it's currently boxing and unboxing the the value. How can I avoid this? namespace System { public static class SystemExtensions { public static TResult GetOrDefaultIfNull<T, TResult>(this T obj, Func<T, TResult> getValue, TResult defaultValue) { if (obj == null) return defaultValue; return getValue(obj); } } } Example usage: public class Foo { public int Bar { get; set; } } In some method: Foo aFooObject = new Foo { Bar = 1 }; Foo nullReference = null; Console.WriteLine(aFooObject.GetOrDefaultIfNull((o) => o.Bar, 0)); // results: 1 Console.WriteLine(nullReference.GetOrDefaultIfNull((o) => o.Bar, 0)); // results: 0

    Read the article

  • Using ms: xpath functions inside XPathExpression

    - by Filini
    I am trying to use Microsoft XPath Extension Functions (such as ms:string-compare http://msdn.microsoft.com/en-us/library/ms256114.aspx) inside an XPathExpression object. These functions are extensions inside the MSXML library, and if I use them in an XslCompiledTransform (simply adding the "ms" namespace) they work like a charm: var xsl = @" <?xml version=""1.0"" encoding=""UTF-8""?> <xsl:stylesheet version=""2.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:fn=""http://www.w3.org/2005/xpath-functions"" xmlns:ms=""urn:schemas-microsoft-com:xslt""> <xsl:output method=""xml"" version=""1.0"" encoding=""UTF-8"" indent=""yes""/> <xsl:template match=""/Data""> <xsl:element name=""Result""> <xsl:value-of select=""ms:string-compare(@timeout1, @timeout2)""/> </xsl:element> </xsl:template> </xsl:stylesheet>"; var xslDocument = new XmlDocument(); xslDocument.LoadXml(xsl); var transform = new XslCompiledTransform(); transform.Load(xslDocument); Then I tried using them in an XPathExpression: XPathNavigator nav = document.DocumentElement.CreateNavigator(); XPathExpression expr = nav.Compile("ms:string-compare(/Data/@timeout1, /Data/@timeout2)"); XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable); manager.AddNamespace("ms", "urn:schemas-microsoft-com:xslt"); expr.SetContext(manager); nav.Evaluate(expr); But I get an exception "XsltContext is needed for this query because of an unknown function". XsltContext is a specific XmlNamespaceManager, but I don't know if it's possible to instantiate it without an actual XslCompiledTransform (it's abstract) and use it as my expression context. Is there any way to do this (or any other way to use ms: extensions inside an XPathExpression)?

    Read the article

< Previous Page | 67 68 69 70 71 72 73 74 75 76 77 78  | Next Page >