Search Results

Search found 1816 results on 73 pages for 'equals'.

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

  • catDog string problem at Codingbat.com [closed]

    - by stanny110
    public boolean catDog(String str) { int catAnswer = 0; int dogAnswer = 0; int cat_Count = 0; int dog_Count = 0; for (int i=0; i< str.length()-1; i++) { String sub = str.substring(i, i+2); if ((sub.equals("cat"))) cat_Count++; if ((sub.equals("dog"))) dog_Count++; catAnswer = cat_Count; dogAnswer = dog_Count; } //end for if(dogAnswer == catAnswer ) {return true;} // else return (dogAnswer != catAnswer) ;

    Read the article

  • Refactor java code

    - by Alfred
    I would like to refactor code which looks something like this: String input; // input from client socket. if (input.equals(x) { doX(); } else if (input.equals(y) { doY(); } else { unknown_command(); } It is code which checks input from socket to perform some action, but I don't like the if else construction because every time a new command is added to the server (code) a new if else has to be added which is ugly. Also when deleting a command the if else has to be modified.

    Read the article

  • How do I implement a remove by index method for a singly linked list in Java?

    - by Lars Flyger
    Hi, I'm a student in a programming class, and I need some help with this code I've written. So far I've written an entire linked list class (seen below), yet for some reason the "removeByIndex" method won't work. I can't seem to figure out why, the logic seems sound to me. Is there some problem I don't know about? public class List<T> { //private sub-class Link private class Link { private T value; private Link next; //constructors of Link: public Link (T val) { this.value = val; this.next = null; } public Link (T val, Link next) { this.value = val; this.next = next; } @SuppressWarnings("unused") public T getValue() { return value; } } private static final Exception NoSuchElementException = null; private static final Exception IndexOutOfBoundsException = null; private Link chain = null; //constructors of List: public List() { this.chain = null; } //methods of List: /** * Preconditions: none * Postconditions: returns true if list is empty */ public boolean isEmpty() { return this.chain == null; } /** * Preconditions: none * Postconditions: A new Link is added via add-aux * @param element */ public void add(T element) { this.add_aux(element, this.chain); } /** * Preconditions: none * Postconditions: A new Link is added to the current chain * @param element * @param chain */ private void add_aux(T element, Link chain) { if (chain == null) { //if chain is null set chain to a new Link with a value of //element this.chain = new Link(element); } else if (chain.next != null) { //if chain.next is not null, go to next item in chain and //try //to add element add_aux(element, chain.next); } else { //if chain.next is null, set chain.next equal to a new Link //with value of element. chain.next = new Link(element); } } /** * Preconditions: none * Postconditions: returns the link at the defined index via nthlink_aux * @param index * @return */ private Link nthLink (int index) { return nthLink_aux(index, this.chain); } /** * Preconditions: none * Postconditions: returns the link at the defined index in the specified *chain * @param i * @param c * @return */ private Link nthLink_aux (int i, Link c) { if (i == 0) { return c; } else return nthLink_aux(i-1, c.next); } /** * Preconditions: the specified element is present in the list * Postconditions: the specified element is removed from the list * @param element * @throws Exception */ public void removeElement(T element) throws Exception { if (chain == null) { throw NoSuchElementException; } //while chain's next is not null and the value of chain.next is not //equal to element, //set chain equal to chain.next //use this iteration to go through the linked list. else while ((chain.next != null) && !(chain.next.value.equals(element))){ Link testlink = chain.next; if (testlink.next.value.equals(element)) { //if chain.next is equal to element, bypass the //element. chain.next.next = chain.next.next.next; } else if (testlink.next == null) { throw NoSuchElementException; } } } /** * Preconditions: none * Postsconditions: the Link at the specified index is removed * @param index * @throws Exception */ public void removeByIndex(int index) throws Exception { if (index == 0) { //if index is 0, set chain equal to chain.next chain = chain.next; } else if (index > 0) { Link target = nthLink(index); while (target != null) { if (target.next != null) { target = target.next; } //if target.next is null, set target to null else { target = null; } } return; } else throw IndexOutOfBoundsException; } /** * Preconditions: none * Postconditions: the specified link's value is printed * @param link */ public void printLink (Link link) { if(link != null) { System.out.println(link.value.toString()); } } /** * Preconditions: none * Postconditions: all of the links' values in the list are printed. */ public void print() { //copy chain to a new variable Link head = this.chain; //while head is not null while (!(head == null)) { //print the current link this.printLink(head); //set head equal to the next link head = head.next; } } /** * Preconditions: none * Postconditions: The chain is set to null */ public void clear() { this.chain = null; } /** * Preconditions: none * Postconditions: Places the defined link at the defined index of the list * @param index * @param val */ public void splice(int index, T val) { //create a new link with value equal to val Link spliced = new Link(val); if (index <= 0) { //copy chain Link copy = chain; //set chain equal to spliced chain = spliced; //set chain.next equal to copy chain.next = copy; } else if (index > 0) { //create a target link equal to the link before the index Link target = nthLink(index - 1); //set the target's next equal to a new link with a next //equal to the target's old next target.next = new Link(val, target.next); } } /** * Preconditions: none * Postconditions: Check to see if element is in the list, returns true * if it is and false if it isn't * @param element * @return */ public boolean Search(T element) { if (chain == null) { //return false if chain is null return false; } //while chain's next is not null and the value of chain.next is not //equal to element, //set chain equal to chain.next //use this iteration to go through the linked list. else while ((chain.next != null) && !(chain.next.value.equals(element))) { Link testlink = chain.next; if (testlink.next.value.equals(element)) { //if chain.next is equal to element, return true return true; } else if (testlink.next == null) { return false; } } return false; } /** * Preconditions: none * Postconditions: order of the links in the list is reversed. */ public void reverse() { //copy chain Link current = chain; //set chain equal to null chain = null; while (current != null) { Link save = current; current = current.next; save.next = chain; chain = save; } } }'

    Read the article

  • Subsonic 3.0 Query limit with MySQL c#.net LinQ

    - by omegawkd
    Hello, a quick question which may or may not be easily answered. Currently, in order to return a limited result set of data to my calling reference using SubSonic I use a similar function as below: _DataSet = from CatSet in t2_aspnet_shopping_item_category.All() join CatProdAssignedLink in t2_aspnet_shopping_link_categoryproduct.All() on CatSet.CategoryID equals CatProdAssignedLink.CategoryID join ProdSet in t2_aspnet_shopping_item_product.All() on CatProdAssignedLink.ProductID equals ProdSet.ProductID where ProdSet.ProductID == __ProductID orderby CatProdAssignedLink.LinkID ascending select CatSet; and select the first item from the data set. Is there a way to limit the lookup initially to a certain amount of rows? I'm using MySQL as the base database.

    Read the article

  • Web Sockets: Browser won't receive the message, complains about it not starting with 0x00 (byte)

    - by giggsey
    Here is my code: import java.net.*; import java.io.*; import java.util.*; import org.jibble.pircbot.*; public class WebSocket { public static int port = 12345; public static ArrayList<WebSocketClient> clients = new ArrayList<WebSocketClient>(); public static ArrayList<Boolean> handshakes = new ArrayList<Boolean>(); public static ArrayList<String> nicknames = new ArrayList<String>(); public static ArrayList<String> channels = new ArrayList<String>(); public static int indexNum; public static void main(String args[]) { try { ServerSocket ss = new ServerSocket(WebSocket.port); WebSocket.console("Created socket on port " + WebSocket.port); while (true) { Socket s = ss.accept(); WebSocket.console("New Client connecting..."); WebSocket.handshakes.add(WebSocket.indexNum,false); WebSocket.nicknames.add(WebSocket.indexNum,""); WebSocket.channels.add(WebSocket.indexNum,""); WebSocketClient p = new WebSocketClient(s,WebSocket.indexNum); Thread t = new Thread( p); WebSocket.clients.add(WebSocket.indexNum,p); indexNum++; t.start(); } } catch (Exception e) { WebSocket.console("ERROR - " + e.toString()); } } public static void console(String msg) { Date date = new Date(); System.out.println("[" + date.toString() + "] " + msg); } } class WebSocketClient implements Runnable { private Socket s; private int iAm; private String socket_res = ""; private String socket_host = ""; private String socket_origin = ""; protected String nick = ""; protected String ircChan = ""; WebSocketClient(Socket socket, int mynum) { s = socket; iAm = mynum; } public void run() { String client = s.getInetAddress().toString(); WebSocket.console("Connection from " + client); IRCclient irc = new IRCclient(iAm); Thread t = new Thread( irc ); try { Scanner in = new Scanner(s.getInputStream()); PrintWriter out = new PrintWriter(s.getOutputStream(),true); while (true) { if (! in.hasNextLine()) continue; String input = in.nextLine().trim(); if (input.isEmpty()) continue; // Lets work out what's wrong with our input if (input.length() > 3 && input.charAt(0) == 65533) { input = input.substring(2); } WebSocket.console("< " + input); // Lets work out if they authenticate... if (WebSocket.handshakes.get(iAm) == false) { checkForHandShake(input); continue; } // Lets check for NICK: if (input.length() > 6 && input.substring(0,6).equals("NICK: ")) { nick = input.substring(6); Random generator = new Random(); int rand = generator.nextInt(); WebSocket.console("I am known as " + nick); WebSocket.nicknames.set(iAm, "bo-" + nick + rand); } if (input.length() > 9 && input.substring(0,9).equals("CHANNEL: ")) { ircChan = "bo-" + input.substring(9); WebSocket.console("We will be joining " + ircChan); WebSocket.channels.set(iAm, ircChan); } if (! ircChan.isEmpty() && ! nick.isEmpty() && irc.started == false) { irc.chan = ircChan; irc.nick = WebSocket.nicknames.get(iAm); t.start(); continue; } else { irc.msg(input); } } } catch (Exception e) { WebSocket.console(e.toString()); e.printStackTrace(); } t.stop(); WebSocket.channels.remove(iAm); WebSocket.clients.remove(iAm); WebSocket.handshakes.remove(iAm); WebSocket.nicknames.remove(iAm); WebSocket.console("Closing connection from " + client); } private void checkForHandShake(String input) { // Check for HTML5 Socket getHeaders(input); if (! socket_res.isEmpty() && ! socket_host.isEmpty() && ! socket_origin.isEmpty()) { send("HTTP/1.1 101 Web Socket Protocol Handshake\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "WebSocket-Origin: " + socket_origin + "\r\n" + "WebSocket-Location: ws://" + socket_host + "/\r\n\r\n",false); WebSocket.handshakes.set(iAm,true); } return; } private void getHeaders(String input) { if (input.length() >= 8 && input.substring(0,8).equals("Origin: ")) { socket_origin = input.substring(8); return; } if (input.length() >= 6 && input.substring(0,6).equals("Host: ")) { socket_host = input.substring(6); return; } if (input.length() >= 7 && input.substring(0,7).equals("Cookie:")) { socket_res = "."; } /*input = input.substring(4); socket_res = input.substring(0,input.indexOf(" HTTP")); input = input.substring(input.indexOf("Host:") + 6); socket_host = input.substring(0,input.indexOf("\r\n")); input = input.substring(input.indexOf("Origin:") + 8); socket_origin = input.substring(0,input.indexOf("\r\n"));*/ return; } protected void send(String msg, boolean newline) { byte c0 = 0x00; byte c255 = (byte) 0xff; try { PrintWriter out = new PrintWriter(s.getOutputStream(),true); WebSocket.console("> " + msg); if (newline == true) msg = msg + "\n"; out.print(msg + c255); out.flush(); } catch (Exception e) { WebSocket.console(e.toString()); } } protected void send(String msg) { try { WebSocket.console(">> " + msg); byte[] message = msg.getBytes(); byte[] newmsg = new byte[message.length + 2]; newmsg[0] = (byte)0x00; for (int i = 1; i <= message.length; i++) { newmsg[i] = message[i - 1]; } newmsg[message.length + 1] = (byte)0xff; // This prints correctly..., apparently... System.out.println(Arrays.toString(newmsg)); OutputStream socketOutputStream = s.getOutputStream(); socketOutputStream.write(newmsg); } catch (Exception e) { WebSocket.console(e.toString()); } } protected void send(String msg, boolean one, boolean two) { try { WebSocket.console(">> " + msg); byte[] message = msg.getBytes(); byte[] newmsg = new byte[message.length+1]; for (int i = 0; i < message.length; i++) { newmsg[i] = message[i]; } newmsg[message.length] = (byte)0xff; // This prints correctly..., apparently... System.out.println(Arrays.toString(newmsg)); OutputStream socketOutputStream = s.getOutputStream(); socketOutputStream.write(newmsg); } catch (Exception e) { e.printStackTrace(); } } } class IRCclient implements Runnable { protected String nick; protected String chan; protected int iAm; boolean started = false; IRCUser irc; IRCclient(int me) { iAm = me; irc = new IRCUser(iAm); } public void run() { WebSocket.console("Connecting to IRC..."); started = true; irc.setNick(nick); irc.setVerbose(false); irc.connectToIRC(chan); } void msg(String input) { irc.sendMessage("#" + chan, input); } } class IRCUser extends PircBot { int iAm; IRCUser(int me) { iAm = me; } public void setNick(String nick) { this.setName(nick); } public void connectToIRC(String chan) { try { this.connect("irc.appliedirc.com"); this.joinChannel("#" + chan); } catch (Exception e) { WebSocket.console(e.toString()); } } public void onMessage(String channel, String sender,String login, String hostname, String message) { // Lets send this message to me WebSocket.clients.get(iAm).send(message); } } Whenever I try to send the message to the browser (via Web Sockets), it complains that it doesn't start with 0x00 (which is a byte). Any ideas? Edit 19/02 - Added the entire code. I know it's real messy and not neat, but I want to get it functioning first. Spend last two days trying to fix.

    Read the article

  • linq Except and custom IEqualityComparer

    - by Joe
    I'm trying to implement a custom comparer on two lists of strings and use the .Except() linq method to get those that aren't one one of the lists. The reason I'm doing a custom comparer is because I need to do a "fuzzy" compare, i.e. one string on one list could be embedded inside a string on the other list. I've made the following comparer ` public class ItemFuzzyMatchComparer : IEqualityComparer { bool IEqualityComparer<string>.Equals(string x, string y) { return (x.Contains(y) || y.Contains(x)); } int IEqualityComparer<string>.GetHashCode(string obj) { if (Object.ReferenceEquals(obj, null)) return 0; return obj.GetHashCode(); } } ` When I debug, the only breakpoint that hits is in the GetHashCode() method. The Equals() never gets touched. Any ideas?

    Read the article

  • LINQ to SQL join when there aren't results

    - by Boarder2
    Given the following database structure I'm trying to write a LINQ query that will return images grouped by tags it's associated with. So far I've got this: var images = from img in db.Images join imgTags in db.ImageTags on img.idImage equals imgTags.idImage join t in db.Tags on imgTags.idTag equals t.idTag where img.OCRData.Contains(searchText.Text) group img by new { t.TagName } into aGroup select new { GroupName = aGroup.Key.TagName, Items = from x in aGroup select new ImageFragment() { ImageID = x.idImage, ScanDate = x.ScanTime } }; Which works great. However, I also want to return Images that do not have any tags associated with them in a group of "(Untagged)" or something. I can't wrap my head around how I would do this without inserting a default tag for every image and that seems like generally not a very good solution.

    Read the article

  • how can I translate a NSString to NSData? And the data has the same content as the string

    - by someonemaybe
    NSString * theString=@"e88d"; NSData * data; // something I should implement NSLog(@"%@", theString); NSLog(@"%@",[data description]); I want the results of the two printings are the same. AES encryption and decryption: (1).The server: if the plaintext is :@"abcd"; the AES encrypted data(NSData data type) is :"d882830c dc892036 4345839f 13c7516a"; (2).in my local app, my code is : NSData*data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://..."]]; NSString * mystring= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; However, to decrypt data successfully, I must got a data(NSData date type) which equals to "d882830c dc892036 4345839f 13c7516a".But it is the mystring (NSString data type) not the data(NSData data type) that equals to the right value. the encryption and decryption function both need a data(NSData data type) as input datas. (NSData*)AES128EncryptWithKey:(NSString*)key; (NSData*)AES128DecryptWithKey:(NSString*)key;

    Read the article

  • What calendar appears to count days since december 28, 1800?

    - by Sander Marechal
    Hello, I have been tasked to read in some data from some weird old system. The system contains many dates but they are all oddly formatted. They are integer numbers ranging from approximately 55,000 to 80,000. I know two dates for certain: 58,112 equals February 2, 1960 61,439 equals March 16, 1969 It appears to me that those integer numbers are the number of days elapsed since December 28, 1800. But I think that's a very strange date to start a calendar on. There is probably going something on with leap years and what-not that is doing to bite me in the ass later on. Does anyone recognise this calendar? Can anyone tell me what the proper way is to convert those integers to human readable dates? Thanks in advance!

    Read the article

  • Comparing two List<MyClass> in C#

    - by Matt
    I have a class called MyClass This class inherits IEquatable and implements equals the way I need it to. (Meaning: when I compare two MyClass tyupe objects individually in code, it works) I then create two List: var ListA = new List<MyClass>(); var ListB = new List<MyClass>(); // Add distinct objects that are equal to one another to // ListA and ListB in such a way that they are not added in the same order. When I go to compare ListA and ListB, should I get true? ListA.Equals(ListB)==true; //???

    Read the article

  • How to access drop down list from EditItemTemplate of FormView

    - by IrfanRaza
    Hello friends, I have a formview on my aspx page containing various controls arranged using table. There is a DDL "cboClients" which i need to enable or disabled depending upon role within Edit mode. The problem here is that i am not able to get that control using FindControl() method. I have tried following code - DropDownList ddl = null; if (FormView1.Row != null) { ddl = (DropDownList)FormView1.Row.FindControl("cboClients"); ddl.Enabled=false; } Even I ave used the DataBound event of the same control - protected void cboClients_DataBound(object sender, EventArgs e) { if (FormView1.CurrentMode == FormViewMode.Edit) { if ((Session["RoleName"].ToString().Equals("Clients")) || (Session["RoleName"].ToString().Equals("Suppliers"))) { DropDownList ddl = (DropDownList)sender; ddl.Enabled = false; } } } But this databound event occurs only once, but not when formview mode is changed. Can anyone provide me proper solution? Thanks for sharing your time.

    Read the article

  • Using android gesture on top of menu buttons

    - by chriacua
    What I want is to have an options menu where the user can choose to navigate the menu between: 1) touching a button and then pressing down on the trackball to select it, and 2) drawing predefined gestures from Gestures Builder As it stands now, I have created my buttons with OnClickListener and the gestures with GestureOverlayView. Then I select starting a new Activity depending on whether the using pressed a button or executed a gesture. However, when I attempt to draw a gesture, it is not picked up. Only pressing the buttons is recognized. The following is my code: public class Menu extends Activity implements OnClickListener, OnGesturePerformedListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //create TextToSpeech myTTS = new TextToSpeech(this, this); myTTS.setLanguage(Locale.US); //create Gestures mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures); if (!mLibrary.load()) { finish(); } // Set up click listeners for all the buttons. View playButton = findViewById(R.id.play_button); playButton.setOnClickListener(this); View instructionsButton = findViewById(R.id.instructions_button); instructionsButton.setOnClickListener(this); View modeButton = findViewById(R.id.mode_button); modeButton.setOnClickListener(this); View statsButton = findViewById(R.id.stats_button); statsButton.setOnClickListener(this); View exitButton = findViewById(R.id.exit_button); exitButton.setOnClickListener(this); GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures); gestures.addOnGesturePerformedListener(this); } public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) { ArrayList<Prediction> predictions = mLibrary.recognize(gesture); // We want at least one prediction if (predictions.size() > 0) { Prediction prediction = predictions.get(0); // We want at least some confidence in the result if (prediction.score > 1.0) { // Show the gesture Toast.makeText(this, prediction.name, Toast.LENGTH_SHORT).show(); //User drew symbol for PLAY if (prediction.name.equals("Play")) { myTTS.shutdown(); //connect to game // User drew symbol for INSTRUCTIONS } else if (prediction.name.equals("Instructions")) { myTTS.shutdown(); startActivity(new Intent(this, Instructions.class)); // User drew symbol for MODE } else if (prediction.name.equals("Mode")){ myTTS.shutdown(); startActivity(new Intent(this, Mode.class)); // User drew symbol to QUIT } else { finish(); } } } } @Override public void onClick(View v) { switch (v.getId()){ case R.id.instructions_button: startActivity(new Intent(this, Instructions.class)); break; case R.id.mode_button: startActivity(new Intent(this, Mode.class)); break; case R.id.exit_button: finish(); break; } } Any suggestions would be greatly appreciated!

    Read the article

  • c# login Screen Error

    - by Kumu
    The type or namespace name 'Login' could not be found (are you missing a using directive or an assembly reference?) This error displays according to the MainMenu of my system. The following code describes the MainMenu source code of my system. Login login; is the error place which system shows, using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace FootballLeague { public partial class MainMenu : Form { FootballLeagueDatabase footballLeagueDatabase; Game game; Team team; **Login login;** public MainMenu() { InitializeComponent(); changePanel(1); } public MainMenu(FootballLeagueDatabase footballLeagueDatabaseIn) { InitializeComponent(); footballLeagueDatabase = footballLeagueDatabaseIn; } //FootballLeagueDatabase footballLeagueDatabase = new FootballLeagueDatabase(); private void Form_Loaded(object sender, EventArgs e) { } private void gameButton_Click(object sender, EventArgs e) { int option = 0; changePanel(option); } private void scoreboardButton_Click(object sender, EventArgs e) { int option = 1; changePanel(option); } private void changePanel(int optionIn) { gamePanel.Hide(); scoreboardPanel.Hide(); string title = "Football League System"; switch (optionIn) { case 0: gamePanel.Show(); this.Text = title + " - Game Menu"; break; case 1: scoreboardPanel.Show(); this.Text = title + " - Display Menu"; break; } } private void logoutButton_Click(object sender, EventArgs e) { login = new Login(); login.Show(); this.Hide(); } and I have the Form class called Login.cs and the following code displays that class. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace FootballLeagueSystem { public partial class Login : Form { MainMenu menu; public Login() { InitializeComponent(); } private void administratorLoginButton_Click(object sender, EventArgs e) { string username1 = "08247739"; string password1 = "08247739"; if ((userNameTxt.Text.Length) == 0) MessageBox.Show("Please enter your username!"); else if ((passwordTxt.Text.Length) == 0) MessageBox.Show("Please enter your password!"); else if (userNameTxt.Text.Equals("") || passwordTxt.Text.Equals("")) MessageBox.Show("Invalid Username or Password!"); else { if (this.userNameTxt.Text == username1 && this.passwordTxt.Text == password1) MessageBox.Show("Welcome Administrator!", "Administrator Login"); menu = new MainMenu(); menu.Show(); this.Hide(); } } private void managerLoginButton_Click(object sender, EventArgs e) { { string username2 = "1111"; string password2 = "1111"; if ((userNameTxt.Text.Length) == 0) MessageBox.Show("Please enter your username!"); else if ((passwordTxt.Text.Length) == 0) MessageBox.Show("Please enter your password!"); else if (userNameTxt.Text.Equals("") && passwordTxt.Text.Equals("")) MessageBox.Show("Invalid Username or Password!"); //menu = new MainMenu(); //menu.Hide(); //this.Close(); else { if (this.userNameTxt.Text == username2 && this.passwordTxt.Text == password2) MessageBox.Show("Welcome Manager!", "Manager Login"); menu = new MainMenu(); menu.Show(); //menu.HideTab(); this.Hide(); } } } private void cancelButton_Click(object sender, EventArgs e) { this.Close(); } } } Please can you someone explain me where is the error is?

    Read the article

  • Problem storing text to a String[] and then storing the array to a Vector.

    - by hatboysam
    OK so for background I've only been using Java for a little more than a week and I am making a basic GUI "Recipe Book" application just to test out some of the techniques I've learned. Currently I'm working on the "Add New Recipe" page that allows the user to make a new recipe by adding ingredients one at a time. The ingredients have 3 attributes: Name, amount, and unit (like cups, oz, etc) that come from two text fields and a combo box respectively. The 3 values are stores as strings to a String array that represents the ingredient, then the arrays are stored in a vector that holds all of the ingredients for one recipe. When an ingredient is added, the user first types in the 3 necessary values into empty boxes/combo box dropdown and then clicks "Add Ingredient". Here is my code for when the button is clicked: public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source == addIngredientButton) { //make sure 3 ingredient fields are not blank if (!ingredientNameField.getText().equals("") && !ingredientAmountField.getText().equals("") && !ingredientUnitDropdown.getSelectedItem().equals("")) { tempIngredientsArray[0] = ingredientNameField.getText(); //set ingredient name to first position in array tempIngredientsArray[1] = ingredientAmountField.getText(); //set ingredient amount to second position in array tempIngredientsArray[2] = (String) ingredientUnitDropdown.getSelectedItem(); //set ingredient unit to third position in array int ingredientsVectorSize = tempRecipe.ingredientsVector.size(); tempRecipe.ingredientsVector.add(this.tempIngredientsArray); //why would it matter if this and previous statement were switched for (int k = 0; k < ingredientsVectorSize + 1; k++ ) { liveIngredientsListArea.append("\n" + tempRecipe.makeIngredientSentence(k)); System.out.println(Arrays.toString(tempIngredientsArray)); //shows that tempIngredientsArray gets messed up each time } } Now here's the really strange problem I've been having. The first time the user adds an ingredient everything works fine. The second time, the String[] for that ingredient seems to be duplicated, and the third time it's triplicated. Aka the first time it runs the System.out.println might return "{Sugar, 3, Cups}" and the second time it will return "{Flour, 2, Oz.} {Flour, 2, Oz.}" etc. What's causing this strange problem? All help greatly appreciated, let me know if you need any clarification.

    Read the article

  • Converting "is null" into a linq to sql statement

    - by Darryl Braaten
    I am having trouble replicating the following sql as a LINQ statement select TableA.* from TableA left outer join TableAinTableB on TableA.Id = TableAId where TableBId is null The following returns no lines from TableA in db.TableA join AinB in db.TableAinTableB on TableA.Id equals TableAId where AinB.TableBId == null select TableA Also tried and a few other things that didn't work. from TableA in db.TableA join AinB in db.TableAinTableB on TableA.Id equals TableAId where AinB == null select TableA TableAinTableB is a many to many table. The query I want will pull all the records from TableA that have no records in the middle table. My sql does what I want but I have no idea how to convert it to LINQ to SQL. I ended up working around it by just doing a db.ExecuteQuery("working sql"); But I would like to know if the query is possible in LINQ and how to write it, or a pointer to a document that covers this scenario. My searching did not uncover anything I found useful.

    Read the article

  • Avoiding Mixup of Language Details

    - by DarenW
    Today someone asked me what was wrong with their source code. It was obvious. "Use double equals in place of that single equal in that if statement. Um, i think..." As i remember some languages actually take a single equals for comparison. Since i sometimes forget or mix up the syntax details among the several languages i use, i stepped over to my laptop to try a quickie experiment... It costs a bit of time and is a break in the flow to try "quick" experiments (though maybe the practice is good for memory.) What tips do you have for keeping straight in your mind the syntax (and other) details of multiple languages? (And nowadays, this applies just as well to the many wiki-like markups!)

    Read the article

  • How to stop a WPF binding from ignoring the PropertyChanged event that it caused?

    - by Jacob Stanley
    I have a TextBox bound to a ViewModel's Text property with the following setup: Xaml <TextBox Text="{Binding Text}"/> C# public class ViewModel : INotifyPropertyChanged { public string Text { get { return m_Text; } set { if (String.Equals(m_Text, value)) { return; } m_Text = value.ToLower(); RaisePropertyChanged("Text"); } } // Snip } When I type some stuff in to the TextBox it successfully sets the Text property on the ViewModel. The problem is that WPF ignores the property changed event that is raised by it's own update. This results in the user not seeing the text they typed converted to lowercase. How can I change this behaviour so that the TextBox updates with lowercase text? Note: this is just an example I have used to illustrate the problem of WPF ignoring events. I'm not really interested in converting strings to lowercase or any issues with String.Equals(string, string).

    Read the article

  • Bind multiple request parameters to one object in Spring 3

    - by Max
    Hi, I can't figure out a way to bind several arguments and headers to one request parameter using annotations in Spring 3. For example, let's say I'm getting this request: Headers: Content-type: text/plain; POST Body: Name: Max Now I want it all to mysteriously bind to this object: class NameInfo { String name; } Using some code like this: String getName() { if ("text/plain".equals(headers.get("content-type"))) { return body.get("name"); } else if ("xml".equals(headers.get("content-type")) { return parseXml(body).get("name"); } else ... } So that in the end I would be able to use: @RequestMapping(method = RequestMethod.POST) void processName(@RequestAttribute NameInfo name) { ... } Is there a way to achieve something similar to what I need? Thanks in advance.

    Read the article

  • Selecting MediaTray in Java printing

    - by Rocket Surgeon
    I am trying to programmatically select a different media tray using Java Printing API. However, my document always gets printed to the default (TOP) media tray. I checked if the MediaTray attributes are supported using "isAttributeValueSupported()" method on javax.print.PrintService interface and I am getting the result as "true" for each MediaTray I pass. Here is my code: public void print( String printerName, com.company.services.document.transferobject.MediaTray tray, byte[] document) { String methodName = "print: "; logger.sendEvent(CLASS_NAME + methodName + "Start", EventType.INFO, this); if (printerName == null || "none".equals(printerName) || "?".equals(printerName) || "null".equals(printerName)) { logger.sendEvent("Please supply printer name, currently printerName is "+printerName, EventType.INFO, this); return; } DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE; AttributeSet attributeSet = new HashAttributeSet(); attributeSet.add(new PrinterName(printerName, null)); javax.print.PrintService service = getService(printerName); if (service.isAttributeValueSupported(MediaTray.TOP, flavor, null)) { System.out.println("---------->>>>>>>>>Yes TOP" + " : Value : " + MediaTray.TOP.getValue()); } else { System.out.println("---------->>>>>>>>>Nope"); } if (service.isAttributeValueSupported(MediaTray.BOTTOM, flavor, null)) { System.out.println("---------->>>>>>>>>Yes BOTTOM" + " : Value : " + MediaTray.BOTTOM.getValue()); } else { System.out.println("---------->>>>>>>>>Nope"); } if (service.isAttributeValueSupported(MediaTray.MIDDLE, flavor, null)) { System.out.println("---------->>>>>>>>>Yes MIDDLE" + " : Value : " + MediaTray.MIDDLE.getValue()); } else { System.out.println("---------->>>>>>>>>Nope"); } if (service.isAttributeValueSupported(MediaTray.MANUAL, flavor, null)) { System.out.println("---------->>>>>>>>>Yes MANUAL" + " : Value : " + MediaTray.MANUAL.getValue()); } else { System.out.println("---------->>>>>>>>>Nope"); } if (service.isAttributeValueSupported(MediaTray.SIDE, flavor, null)) { System.out.println("---------->>>>>>>>>Yes SIDE" + " : Value : " + MediaTray.SIDE.getValue()); } else { System.out.println("---------->>>>>>>>>Nope"); } DocPrintJob printJob = service.createPrintJob(); try { byte[] textStream = document; PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); pras.add(DocumentServiceConstant. DEFAULT_ONE_PRINT_COPY); pras.add(Sides.ONE_SIDED); Media standardTray= toStandardTray(tray); if (null != standardTray) { pras.add(standardTray); } Doc myDoc = new SimpleDoc(textStream, flavor, null); printJob.print(myDoc, pras); logger.sendEvent( " successfully printed ............ ", EventType.INFO, this); } catch (Throwable th) { logger.sendEvent(" Throwable : "+th.getLocalizedMessage(), EventType.INFO, this); ExceptionUtility .determineExceptionForServiceClient(th); } logger.sendEvent(CLASS_NAME + methodName + "END: ", EventType.INFO, this); } Any help will be greatly appreciated!

    Read the article

  • How to parse app.config using ConfigurationManager?

    - by Amokrane
    I was using a certain method for parsing my app.config file. Then I was told that using ConfigurationManager is better and simpler. But the thing is I don't know how to do it with ConfigurationManager. My original code looked like this: XmlNode xmlProvidersNode; XmlNodeList xmlProvidersList; XmlNodeList xmlTaskFactoriesList; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("app.config"); xmlProvidersNode = xmlDoc.DocumentElement.SelectSingleNode("TaskProviders"); xmlProvidersList = xmlProvidersNode.SelectNodes("TaskProvider"); foreach (XmlNode xmlProviderElement in xmlProvidersList) { if (xmlProviderElement.Attributes.GetNamedItem("Name").Value.Equals(_taskProvider)) { xmlTaskFactoriesList = xmlProviderElement.SelectNodes("TaskTypeFactory"); foreach (XmlNode xmlTaskFactoryElement in xmlTaskFactoriesList) { if (xmlTaskFactoryElement.Attributes.GetNamedItem("TaskType").Value.Equals(_taskType)) { taskTypeFactory = xmlTaskFactoryElement.Attributes.GetNamedItem("Class").Value; } } } } What would be the equivalent using ConfigurationManager? (Because all I can see is how to get keys not nodes..) Thanks

    Read the article

  • Alert show when extension of FileUpLoads are not allowed

    - by Vy Clarks
    I have a asp FileUpload control in my aspx page. And the code behind to check file's extension and then insert them into database: private string Write(HttpPostedFile file, string table) { string fileNameMain = Path.GetFileName(file.FileName); // check for the valid file extension string fileExtension = Path.GetExtension(fileNameMain).ToLower(); if (fileExtension.Equals(".pdf") || fileExtension.Equals(".doc")) { ...insert fileupload into database } else { LabelError.Text = "Extension of files are not allowed."; return null; } } With the code above, it checks the extension and then show the message "Extension of files are not allowed." in a LabelError if the fileupload is not allowed. Now, I'm required to do the "check-extension" in the other way: at the moment the client click and choose FileUpload, an alert show "Extension of files are not allowed.". I need a way to make an alert show at the momment the FileUpload choosed in browser. Help!!!!

    Read the article

  • Join Query Help

    - by John
    Hello, The query below works well. It pulls data from two MySQL tables, "submission" and "login." I would like to also pull data from a third table called "comment" in the same database. The table "comment" has the following fields: commentid, loginid, submissionid, comment, datecommented Two of the fields in the table "login" are called "loginid" and "username." In the query below, I would like to count all "commentid" in "comment" where "loginid" equals the "loginid" in "login" where "username" equals "$profile." How can I do this? Thanks in advance, John $sqlStr1 = "SELECT l.username, l.loginid, s.loginid, s.submissionid, s.title, s.url, s.datesubmitted, s.displayurl, l.created, count(s.submissionid) countSubmissions FROM submission AS s INNER JOIN login AS l ON s.loginid = l.loginid WHERE l.username = '$profile'";

    Read the article

  • Removing a result from Queryset

    - by Enrico
    Is there a simple way to discard/remove the last result in a queryset without affecting the db? I am trying to paginate results in Django, but don't know the total number of objects for a given query. I was planning on using next/previous or older/newer links, so I only need to know if this is the first and/or last page. First is easy to check. To check for the last page I can compare the number of results with the pagesize or make a second query. The first method fails to detect the last page when the number of results in the last set equals the pagesize (ie 100 records get broken into 10 pages with the last page containing exactly 10 results) and I would like to avoid making a second query. My current thought is that I should fetch pagesize + 1 results from the db. If the queryset length equals 11, I know this is not the last page and I want to discard the last result in the queryset before passing the queryset to the template.

    Read the article

  • Can .NET load and parse a properties file equivalent to Java Properties class?

    - by Tai Squared
    Is there an easy way in C# to read a properties file that has each property on a separate line followed by an equals sign and the value, such as the following: ServerName=prod-srv1 Port=8888 CustomProperty=Any value In Java, the Properties class handles this parsing easily: Properties myProperties=new Properties(); FileInputStream fis = new FileInputStream (new File("CustomProps.properties")); myProperties.load(fis); System.out.println(myProperties.getProperty("ServerName")); System.out.println(myProperties.getProperty("CustomProperty")); I can easily load the file in C# and parse each line, but is there a built in way to easily get a property without having to parse out the key name and equals sign myself? The C# information I have found seems to always favor XML, but this is an existing file that I don't control and I would prefer to keep it in the existing format as it will require more time to get another team to change it to XML than parsing the existing file.

    Read the article

  • Java - strange problem storing text to a String[] and then storing the array to a Vector. Help plea

    - by hatboysam
    OK so for background I've only been using Java for a little more than a week and I am making a basic GUI "Recipe Book" application just to test out some of the techniques I've learned. Currently I'm working on the "Add New Recipe" page that allows the user to make a new recipe by adding ingredients one at a time. The ingredients have 3 attributes: Name, amount, and unit (like cups, oz, etc) that come from two text fields and a combo box respectively. The 3 values are stores as strings to a String array that represents the ingredient, then the arrays are stored in a vector that holds all of the ingredients for one recipe. When an ingredient is added, the user first types in the 3 necessary values into empty boxes/combo box dropdown and then clicks "Add Ingredient". Here is my code for when the button is clicked: public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source == addIngredientButton) { //make sure 3 ingredient fields are not blank if (!ingredientNameField.getText().equals("") && !ingredientAmountField.getText().equals("") && !ingredientUnitDropdown.getSelectedItem().equals("")) { tempIngredientsArray[0] = ingredientNameField.getText(); //set ingredient name to first position in array tempIngredientsArray[1] = ingredientAmountField.getText(); //set ingredient amount to second position in array tempIngredientsArray[2] = (String) ingredientUnitDropdown.getSelectedItem(); //set ingredient unit to third position in array int ingredientsVectorSize = tempRecipe.ingredientsVector.size(); tempRecipe.ingredientsVector.add(this.tempIngredientsArray); //why would it matter if this and previous statement were switched for (int k = 0; k < ingredientsVectorSize + 1; k++ ) { liveIngredientsListArea.append("\n" + tempRecipe.makeIngredientSentence(k)); System.out.println(Arrays.toString(tempIngredientsArray)); //shows that tempIngredientsArray gets messed up each time } } Now here's the really strange problem I've been having. The first time the user adds an ingredient everything works fine. The second time, the String[] for that ingredient seems to be duplicated, and the third time it's triplicated. Aka the first time it runs the System.out.println might return "{Sugar, 3, Cups}" and the second time it will return "{Flour, 2, Oz.} {Flour, 2, Oz.}" etc. What's causing this strange problem? All help greatly appreciated, let me know if you need any clarification.

    Read the article

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