Search Results

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

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

  • NHibernate IUserType convert nullable DateTime to DB not-null value

    - by barakbbn
    I have legacy DB that store dates that means no-date as 9999-21-31, The column Till_Date is of type DateTime not-null="true". in the application i want to build persisted class that represent no-date as null, So i used nullable DateTime in C# //public DateTime? TillDate {get; set; } I created IUserType that knows to convert the entity null value to DB 9999-12-31 but it seems that NHibernate doesn't call SafeNullGet, SafeNullSet on my IUserType when the entity value is null, and report a null is used for not-null column. I tried to by-pass it by mapping the column as not-null="false" (changed only the mapping file, not the DB) but it still didn't help, only now it tries to insert the null value to the DB and get ADOException. Any knowledge if NHibernate doesn't support IUseType that convert null to not-null values? Thanks //Implementation public class NullableDateTimeToNotNullUserType : IUserType { private static readonly DateTime MaxDate = new DateTime(9999, 12, 31); public new bool Equals(object x, object y) { //This didn't work as well if (ReferenceEquals(x, y)) return true; //if(x == null && y == null) return false; if (x == null || y == null) return false; return x.Equals(y); } public int GetHashCode(object x) { return x == null ? 0 : x.GetHashCode(); } public object NullSafeGet(IDataReader rs, string[] names, object owner) { var value = rs.GetDateTime(rs.GetOrdinal(names[0])); return (value == MaxDate)? null : value; } public void NullSafeSet(IDbCommand cmd, object value, int index) { var dateValue = (DateTime?)value; var dbValue = (dateValue.HasValue) ? dateValue.Value : MaxDate; ((IDataParameter)cmd.Parameters[index]).Value = dbValue; } public object DeepCopy(object value) { return value; } public object Replace(object original, object target, object owner) { return original; } public object Assemble(object cached, object owner) { return cached; } public object Disassemble(object value) { return value; } public SqlType[] SqlTypes { get { return new[] { NHibernateUtil.DateTime.SqlType }; } } public Type ReturnedType { get { return typeof(DateTime?); } } public bool IsMutable { get { return false; } } } } //Final Implementation with fixes. make the column mapping in hbm.xml not-null="false" public class NullableDateTimeToNotNullUserType : IUserType { private static readonly DateTime MaxDate = new DateTime(9999, 12, 31); public new bool Equals(object x, object y) { //This didn't work as well if (ReferenceEquals(x, y)) return true; //if(x == null && y == null) return false; if (x == null || y == null) return false; return x.Equals(y); } public int GetHashCode(object x) { return x == null ? 0 : x.GetHashCode(); } public object NullSafeGet(IDataReader rs, string[] names, object owner) { var value = NHibernateUtil.Date.NullSafeGet(rs, names[0]); return (value == MaxDate)? default(DateTime?) : value; } public void NullSafeSet(IDbCommand cmd, object value, int index) { var dateValue = (DateTime?)value; var dbValue = (dateValue.HasValue) ? dateValue.Value : MaxDate; NHibernateUtil.Date.NullSafeSet(cmd, valueToSet, index); } public object DeepCopy(object value) { return value; } public object Replace(object original, object target, object owner) { return original; } public object Assemble(object cached, object owner) { return cached; } public object Disassemble(object value) { return value; } public SqlType[] SqlTypes { get { return new[] { NHibernateUtil.DateTime.SqlType }; } } public Type ReturnedType { get { return typeof(DateTime?); } } public bool IsMutable { get { return false; } } } }

    Read the article

  • Trying to sentinel loop this program.

    - by roger34
    Okay, I spent all this time making this for class but I have one thing that I can't quite get: I need this to sentinel loop continuously (exiting upon entering x) so that the System.out.println("What type of Employee? Enter 'o' for Office " + "Clerical, 'f' for Factory, or 's' for Saleperson. Enter 'x' to exit." ); line comes back up after they enter the first round of information. Also, I can't leave this up long on the (very) off chance a classmate might see this and steal the code. Full code following: import java.util.Scanner; public class Project1 { public static void main (String args[]){ Scanner inp = new Scanner( System.in ); double totalPay; System.out.println("What type of Employee? Enter 'o' for Office " + "Clerical, 'f' for Factory, or 's' for Saleperson. Enter 'x' to exit." ); String response= inp.nextLine(); while (!response.toLowerCase().equals("o")&&!response.toLowerCase().equals("f") &&!response.toLowerCase().equals("s")&&!response.toLowerCase().equals("x")){ System.out.print("\nInvalid selection,please enter your choice again:\n"); response=inp.nextLine(); } char choice = response.toLowerCase().charAt( 0 ); switch (choice){ case 'o': System.out.println("Enter your hourly rate:"); double officeRate=inp.nextDouble(); System.out.println("Enter the number of hours worked:"); double officeHours=inp.nextDouble(); totalPay = officeCalc(officeRate,officeHours); taxCalc(totalPay); break; case 'f': System.out.println("How many Widgets did you produce during the week?"); double widgets=inp.nextDouble(); totalPay=factoryCalc(widgets); taxCalc(totalPay); break; case 's': System.out.println("What were your total sales for the week?"); double totalSales=inp.nextDouble(); totalPay=salesCalc(totalSales); taxCalc(totalPay); break; } } public static double taxCalc(double totalPay){ double federal=totalPay*.22; double state =totalPay*.055; double netPay = totalPay - federal - state; federal =federal*Math.pow(10,2); federal =Math.round(federal); federal= federal/Math.pow(10,2); state =state*Math.pow(10,2); state =Math.round(state); state= state/Math.pow(10,2); totalPay =totalPay*Math.pow(10,2); totalPay =Math.round(totalPay); totalPay= totalPay/Math.pow(10,2); netPay =netPay*Math.pow(10,2); netPay =Math.round(netPay); netPay= netPay/Math.pow(10,2); System.out.printf("\nTotal Pay \t: %1$.2f.\n", totalPay); System.out.printf("State W/H \t: %1$.2f.\n", state); System.out.printf("Federal W/H : %1$.2f.\n", federal); System.out.printf("Net Pay \t: %1$.2f.\n", netPay); return totalPay; } public static double officeCalc(double officeRate,double officeHours){ double overtime=0; if (officeHours>=40) overtime = officeHours-40; else overtime = 0; if (officeHours >= 40) officeHours = 40; double otRate = officeRate * 1.5; double totalPay= (officeRate * officeHours) + (otRate*overtime); return totalPay; } public static double factoryCalc(double widgets){ double totalPay=widgets*.35 +300; return totalPay; } public static double salesCalc(double totalSales){ double totalPay = totalSales * .05 + 500; return totalPay; } }

    Read the article

  • Invoke a SOAP method with namespace prefixes

    - by mvladic
    My C# web service client sends following soap message to Java-based web service: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <getData> <request> <requestParameters xmlns="http://b..."> <equals> ... </equals> </requestParameters> </request> </getData> </soap:Body> </soap:Envelope> and Java-based web service returns error: 500 Internal Server Error ... Cannot find dispatch method for {}getData ... Client written in Java, which works, sends the following message: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <ns2:getData xmlns:ns2="http://a..."> <ns2:request> <ns3:requestParameters xmlns:ns3="http://b..."> <ns3:equals> ... </ns3:equals> </ns3:requestParameters> </ns2:request> </ns2:getData> </soap:Body> </soap:Envelope> Is there an easy way in C# to send SOAP messages the same way Java client sends: with namespace prefixes? Following is C# code that sends message: // class MyService is auto-generated using wsdl.exe tool MyService service = new MyService(); RequestMessage request = new RequestMessage(); ... ResponseMessage response = service.getData(request); ... UPDATE: RequestMessage class looks like this: /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.2152")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://uri.etsi.org/02657/v1.5.1#/RetainedData")] public partial class RequestMessage { private byte[] requestPriorityField; private RequestConstraints requestParametersField; private string deliveryPointHIBField; private string maxHitsField; private NationalRequestParameters nationalRequestParametersField; private System.Xml.XmlElement anyField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(DataType="hexBinary", Order=0)] public byte[] requestPriority { get { return this.requestPriorityField; } set { this.requestPriorityField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Order=1)] public RequestConstraints requestParameters { get { return this.requestParametersField; } set { this.requestParametersField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Order=2)] public string deliveryPointHIB { get { return this.deliveryPointHIBField; } set { this.deliveryPointHIBField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(DataType="integer", Order=3)] public string maxHits { get { return this.maxHitsField; } set { this.maxHitsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Order=4)] public NationalRequestParameters nationalRequestParameters { get { return this.nationalRequestParametersField; } set { this.nationalRequestParametersField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAnyElementAttribute(Order=5)] public System.Xml.XmlElement Any { get { return this.anyField; } set { this.anyField = value; } } }

    Read the article

  • The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

    - by Kumu
    I get the following error when I try to compile my C# program: The type or namespace name 'Login' could not be found (are you missing a using directive or an assembly reference?) 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; //Error here public MainMenu() { InitializeComponent(); changePanel(1); } public MainMenu(FootballLeagueDatabase footballLeagueDatabaseIn) { InitializeComponent(); footballLeagueDatabase = footballLeagueDatabaseIn; } 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(); } Login.cs 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!"); else { if (this.userNameTxt.Text == username2 && this.passwordTxt.Text == password2) MessageBox.Show("Welcome Manager!", "Manager Login"); menu = new MainMenu(); menu.Show(); this.Hide(); } } } private void cancelButton_Click(object sender, EventArgs e) { this.Close(); } } } Where is the error? What am I doing wrong?

    Read the article

  • Trying to sentinel loop this program. [java]

    - by roger34
    Okay, I spent all this time making this for class but I have one thing that I can't quite get: I need this to sentinel loop continuously (exiting upon entering x) so that the System.out.println("What type of Employee? Enter 'o' for Office " + "Clerical, 'f' for Factory, or 's' for Saleperson. Enter 'x' to exit." ); line comes back up after they enter the first round of information. Also, I can't leave this up long on the (very) off chance a classmate might see this and steal the code. Full code following: import java.util.Scanner; public class Project1 { public static void main (String args[]){ Scanner inp = new Scanner( System.in ); double totalPay; System.out.println("What type of Employee? Enter 'o' for Office " + "Clerical, 'f' for Factory, or 's' for Saleperson. Enter 'x' to exit." ); String response= inp.nextLine(); while (!response.toLowerCase().equals("o")&&!response.toLowerCase().equals("f") &&!response.toLowerCase().equals("s")&&!response.toLowerCase().equals("x")){ System.out.print("\nInvalid selection,please enter your choice again:\n"); response=inp.nextLine(); } char choice = response.toLowerCase().charAt( 0 ); switch (choice){ case 'o': System.out.println("Enter your hourly rate:"); double officeRate=inp.nextDouble(); System.out.println("Enter the number of hours worked:"); double officeHours=inp.nextDouble(); totalPay = officeCalc(officeRate,officeHours); taxCalc(totalPay); break; case 'f': System.out.println("How many Widgets did you produce during the week?"); double widgets=inp.nextDouble(); totalPay=factoryCalc(widgets); taxCalc(totalPay); break; case 's': System.out.println("What were your total sales for the week?"); double totalSales=inp.nextDouble(); totalPay=salesCalc(totalSales); taxCalc(totalPay); break; } } public static double taxCalc(double totalPay){ double federal=totalPay*.22; double state =totalPay*.055; double netPay = totalPay - federal - state; federal =federal*Math.pow(10,2); federal =Math.round(federal); federal= federal/Math.pow(10,2); state =state*Math.pow(10,2); state =Math.round(state); state= state/Math.pow(10,2); totalPay =totalPay*Math.pow(10,2); totalPay =Math.round(totalPay); totalPay= totalPay/Math.pow(10,2); netPay =netPay*Math.pow(10,2); netPay =Math.round(netPay); netPay= netPay/Math.pow(10,2); System.out.printf("\nTotal Pay \t: %1$.2f.\n", totalPay); System.out.printf("State W/H \t: %1$.2f.\n", state); System.out.printf("Federal W/H : %1$.2f.\n", federal); System.out.printf("Net Pay \t: %1$.2f.\n", netPay); return totalPay; } public static double officeCalc(double officeRate,double officeHours){ double overtime=0; if (officeHours>=40) overtime = officeHours-40; else overtime = 0; if (officeHours >= 40) officeHours = 40; double otRate = officeRate * 1.5; double totalPay= (officeRate * officeHours) + (otRate*overtime); return totalPay; } public static double factoryCalc(double widgets){ double totalPay=widgets*.35 +300; return totalPay; } public static double salesCalc(double totalSales){ double totalPay = totalSales * .05 + 500; return totalPay; } }

    Read the article

  • Hibernate - strange order of native SQL parameters

    - by Xorty
    Hello, I am trying to use native MySQL's MD5 crypto func, so I defined custom insert in my mapping file. <hibernate-mapping package="tutorial"> <class name="com.xorty.mailclient.client.domain.User" table="user"> <id name="login" type="string" column="login"></id> <property name="password"> <column name="password" /> </property> <sql-insert>INSERT INTO user (login,password) VALUES ( ?, MD5(?) )</sql-insert> </class> </hibernate-mapping> Then I create User (pretty simple POJO with just 2 Strings - login and password) and try to persist it. session.beginTransaction(); // we have no such user in here yet User junitUser = (User) session.load(User.class, "junit_user"); assert (null == junitUser); // insert new user junitUser = new User(); junitUser.setLogin("junit_user"); junitUser.setPassword("junitpass"); session.save(junitUser); session.getTransaction().commit(); What actually happens? User is created, but with reversed parameters order. He has login "junitpass" and "junit_user" is MD5 encrypted and stored as password. What did I wrong? Thanks EDIT: ADDING POJO class package com.xorty.mailclient.client.domain; import java.io.Serializable; /** * POJO class representing user. * @author MisoV * @version 0.1 */ public class User implements Serializable { /** * Generated UID */ private static final long serialVersionUID = -969127095912324468L; private String login; private String password; /** * @return login */ public String getLogin() { return login; } /** * @return password */ public String getPassword() { return password; } /** * @param login the login to set */ public void setLogin(String login) { this.login = login; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @see java.lang.Object#toString() * @return login */ @Override public String toString() { return login; } /** * Creates new User. * @param login User's login. * @param password User's password. */ public User(String login, String password) { setLogin(login); setPassword(password); } /** * Default constructor */ public User() { } /** * @return hashCode * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((null == login) ? 0 : login.hashCode()); result = prime * result + ((null == password) ? 0 : password.hashCode()); return result; } /** * @param obj Compared object * @return True, if objects are same. Else false. * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof User)) { return false; } User other = (User) obj; if (login == null) { if (other.login != null) { return false; } } else if (!login.equals(other.login)) { return false; } if (password == null) { if (other.password != null) { return false; } } else if (!password.equals(other.password)) { return false; } return true; } }

    Read the article

  • When I try to redefine a variable, I get an index out of bounds error

    - by user2770254
    I'm building a program to act as a calculator with memory, so you can give variables and their values. Whenever I'm trying to redefine a variable, a = 5, to a = 6, I get an index out of bounds error. public static void main(String args[]) { LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>(); Scanner scan = new Scanner(System.in); ArrayList<Integer> values = new ArrayList<>(); ArrayList<String> variables = new ArrayList<>(); while(scan.hasNextLine()) { String line = scan.nextLine(); String[] tokens = line.split(" "); if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var")) { int value = 0; for(int i=0; i<tokens.length; i++) { if(tokens.length==3) { value = Integer.parseInt(tokens[2]); System.out.printf("%5d\n",value); if(map.containsKey(tokens[0])) { values.set(values.indexOf(tokens[0]), value); variables.set(variables.indexOf(tokens[0]), tokens[0]); } else { values.add(value); } break; } else if(tokens[i].charAt(0) == '+') { value = addition(tokens, value); System.out.printf("%5d\n",value); variables.add(tokens[0]); if(map.containsKey(tokens[0])) { values.set(values.indexOf(tokens[0]), value); variables.set(variables.indexOf(tokens[0]), tokens[0]); } else { values.add(value); } break; } else if(i==tokens.length-1 && tokens.length != 3) { System.out.println("No operation"); break; } } map.put(tokens[0], value); } if(Character.isDigit(tokens[0].charAt(0))) { int value = 0; if(tokens.length==1) { System.out.printf("%5s\n", tokens[0]); } else { value = addition(tokens, value); System.out.printf("%5d\n", value); } } if(line.equals("clear")) { clear(map); } if(line.equals("var")) { variableList(variables, values); } } } public static int addition(String[] a, int b) { for(String item : a) { if(Character.isDigit(item.charAt(0))) { int add = Integer.parseInt(item); b = b + add; } } return b; } public static void clear(LinkedHashMap<String,Integer> b) { b.clear(); } public static void variableList(ArrayList<String> a, ArrayList<Integer> b) { for(int i=0; i<a.size(); i++) { System.out.printf("%5s: %d\n", a.get(i), b.get(i)); } } I included the whole code because I'm not sure where the error is arising from.

    Read the article

  • Overriding GetHashCode in a mutable struct - What NOT to do?

    - by Kyle Baran
    I am using the XNA Framework to make a learning project. It has a Point struct which exposes an X and Y value; for the purpose of optimization, it breaks the rules for proper struct design, since its a mutable struct. As Marc Gravell, John Skeet, and Eric Lippert point out in their respective posts about GetHashCode() (which Point overrides), this is a rather bad thing, since if an object's values change while its contained in a hashmap (ie, LINQ queries), it can become "lost". However, I am making my own Point3D struct, following the design of Point as a guideline. Thus, it too is a mutable struct which overrides GetHashCode(). The only difference is that mine exposes and int for X, Y, and Z values, but is fundamentally the same. The signatures are below: public struct Point3D : IEquatable<Point3D> { public int X; public int Y; public int Z; public static bool operator !=(Point3D a, Point3D b) { } public static bool operator ==(Point3D a, Point3D b) { } public Point3D Zero { get; } public override int GetHashCode() { } public override bool Equals(object obj) { } public bool Equals(Point3D other) { } public override string ToString() { } } I have tried to break my struct in the way they describe, namely by storing it in a List<Point3D>, as well as changing the value via a method using ref, but I did not encounter they behavior they warn about (maybe a pointer might allow me to break it?). Am I being too cautious in my approach, or should I be okay to use it as is?

    Read the article

  • Should I make the Cells in a Tiledmap as null when my player hits it

    - by Vishal Kumar
    I am making a Tile Based game using Libgdx. I took the idea from SuperKoalio platformer demo by Mario Zencher. When I wanted to implement Collectables in my game , I simply draw the coins using Tiled Map Editor. When my player hits that, I use to set that cell as null. Someday on this site suggested me not to do so... never use null. I agreed. What can be any other way. If I am using layer.setCell(x,y) to set the cell to any other cell... even if an transparent one .. my player seems to be stopped by an invisible object/hurdle. This is my code: for (Rectangle tile : tiles) { if (koalaRect.overlaps(tile)) { TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(1); try{ type = layer.getCell((int) tile.x, (int) tile.y).getTile().getProperties().get("tileType").toString(); } catch(Exception e){ System.out.print("Exception in Tiles Property"+e); type="nonbreakable"; } //Let us destroy this cell if(("award".equals(type))){ layer.setCell((int) tile.x, (int) tile.y, null); listener.coin(); score+=100; test = ""+layer.getCell(0, 0).getTile().getProperties().get("tileType"); } //DOING THIS GIVES A BAD EFFECT if(("killer".equals(type))){ //player.health--; //layer.setCell((int) tile.x, (int) tile.y, layer.getCell(20,0)); } // we actually reset the player y-position here // so it is just below/above the tile we collided with // this removes bouncing :) if (player.velocity.y > 0) { player.position.y = (tile.y - Player.height); } Is this a right approach? OR I should create separate Sprite Class called Coin.

    Read the article

  • my application did not show toast mesage when network is not available [closed]

    - by Smart Guy
    my application did no show toast message when network is disable if (position == 2) { final ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connMgr .getActiveNetworkInfo(); android.net.NetworkInfo mobile1 = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (activeNetworkInfo == null) { Toast.makeText(LoginScreen.this, "No Active Network",Toast.LENGTH_LONG).show(); } else { if (activeNetworkInfo.isConnected()) { btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View view) { String pinemptycheck = pin.getText().toString(); String mobileemptycheck = mobile.getText().toString(); if (pinemptycheck.trim().equals("")||(mobileemptycheck.trim().equals(""))) { Toast.makeText(getApplicationContext(), "Please Enter Correct Information", Toast.LENGTH_LONG).show(); } else { showProgress(); postLoginData(); } } }); } else if (activeNetworkInfo.isConnectedOrConnecting()) { Toast.makeText(LoginScreen.this, "network is Connecting", Toast.LENGTH_LONG) .show(); else if (mobile1.isAvailable()) { btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View view) { showProgress(); postLoginData(); } }); } else if (!mobile1.isAvailable()) { Toast.makeText(LoginScreen.this,"No other Connection Found ",Toast.LENGTH_LONG).show(); btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View v) { Toast.makeText(LoginScreen.this," No other Connection Found", Toast.LENGTH_LONG).show(); } }); }}}

    Read the article

  • How to Implement Project Type "Copy", "Move", "Rename", and "Delete"

    - by Geertjan
    You've followed the NetBeans Project Type Tutorial and now you'd like to let the user copy, move, rename, and delete the projects conforming to your project type. When they right-click a project, they should see the relevant menu items and those menu items should provide dialogs for user interaction, followed by event handling code to deal with the current operation. Right now, at the end of the tutorial, the "Copy" and "Delete" menu items are present but disabled, while the "Move" and "Rename" menu items are absent: The NetBeans Project API provides a built-in mechanism out of the box that you can leverage for project-level "Copy", "Move", "Rename", and "Delete" actions. All the functionality is there for you to use, while all that you need to do is a bit of enablement and configuration, which is described below. To get started, read the following from the NetBeans Project API: http://bits.netbeans.org/dev/javadoc/org-netbeans-modules-projectapi/org/netbeans/spi/project/ActionProvider.html http://bits.netbeans.org/dev/javadoc/org-netbeans-modules-projectapi/org/netbeans/spi/project/CopyOperationImplementation.html http://bits.netbeans.org/dev/javadoc/org-netbeans-modules-projectapi/org/netbeans/spi/project/MoveOrRenameOperationImplementation.html http://bits.netbeans.org/dev/javadoc/org-netbeans-modules-projectapi/org/netbeans/spi/project/DeleteOperationImplementation.html Now, let's do some work. For each of the menu items we're interested in, we need to do the following: Provide enablement and invocation handling in an ActionProvider implementation. Provide appropriate OperationImplementation classes. Add the new classes to the Project Lookup. Make the Actions visible on the Project Node. Run the application and verify the Actions work as you'd like. Here we go: Create an ActionProvider. Here you specify the Actions that should be supported, the conditions under which they should be enabled, and what should happen when they're invoked, using lots of default code that lets you reuse the functionality provided by the NetBeans Project API: class CustomerActionProvider implements ActionProvider { @Override public String[] getSupportedActions() { return new String[]{ ActionProvider.COMMAND_RENAME, ActionProvider.COMMAND_MOVE, ActionProvider.COMMAND_COPY, ActionProvider.COMMAND_DELETE }; } @Override public void invokeAction(String string, Lookup lkp) throws IllegalArgumentException { if (string.equalsIgnoreCase(ActionProvider.COMMAND_RENAME)) { DefaultProjectOperations.performDefaultRenameOperation( CustomerProject.this, ""); } if (string.equalsIgnoreCase(ActionProvider.COMMAND_MOVE)) { DefaultProjectOperations.performDefaultMoveOperation( CustomerProject.this); } if (string.equalsIgnoreCase(ActionProvider.COMMAND_COPY)) { DefaultProjectOperations.performDefaultCopyOperation( CustomerProject.this); } if (string.equalsIgnoreCase(ActionProvider.COMMAND_DELETE)) { DefaultProjectOperations.performDefaultDeleteOperation( CustomerProject.this); } } @Override public boolean isActionEnabled(String command, Lookup lookup) throws IllegalArgumentException { if ((command.equals(ActionProvider.COMMAND_RENAME))) { return true; } else if ((command.equals(ActionProvider.COMMAND_MOVE))) { return true; } else if ((command.equals(ActionProvider.COMMAND_COPY))) { return true; } else if ((command.equals(ActionProvider.COMMAND_DELETE))) { return true; } return false; } } Importantly, to round off this step, add "new CustomerActionProvider()" to the "getLookup" method of the project. If you were to run the application right now, all the Actions we're interested in would be enabled (if they are visible, as described in step 4 below) but when you invoke any of them you'd get an error message because each of the DefaultProjectOperations above looks in the Lookup of the Project for the presence of an implementation of a class for handling the operation. That's what we're going to do in the next step. Provide Implementations of Project Operations. For each of our operations, the NetBeans Project API lets you implement classes to handle the operation. The dialogs for interacting with the project are provided by the NetBeans project system, but what happens with the folders and files during the operation can be influenced via the operations. Below are the simplest possible implementations, i.e., here we assume we want nothing special to happen. Each of the below needs to be in the Lookup of the Project in order for the operation invocation to succeed. private final class CustomerProjectMoveOrRenameOperation implements MoveOrRenameOperationImplementation { @Override public List<FileObject> getMetadataFiles() { return new ArrayList<FileObject>(); } @Override public List<FileObject> getDataFiles() { return new ArrayList<FileObject>(); } @Override public void notifyRenaming() throws IOException { } @Override public void notifyRenamed(String nueName) throws IOException { } @Override public void notifyMoving() throws IOException { } @Override public void notifyMoved(Project original, File originalPath, String nueName) throws IOException { } } private final class CustomerProjectCopyOperation implements CopyOperationImplementation { @Override public List<FileObject> getMetadataFiles() { return new ArrayList<FileObject>(); } @Override public List<FileObject> getDataFiles() { return new ArrayList<FileObject>(); } @Override public void notifyCopying() throws IOException { } @Override public void notifyCopied(Project prjct, File file, String string) throws IOException { } } private final class CustomerProjectDeleteOperation implements DeleteOperationImplementation { @Override public List<FileObject> getMetadataFiles() { return new ArrayList<FileObject>(); } @Override public List<FileObject> getDataFiles() { return new ArrayList<FileObject>(); } @Override public void notifyDeleting() throws IOException { } @Override public void notifyDeleted() throws IOException { } } Also make sure to put the above methods into the Project Lookup. Check the Lookup of the Project. The "getLookup()" method of the project should now include the classes you created above, as shown in bold below: @Override public Lookup getLookup() { if (lkp == null) { lkp = Lookups.fixed(new Object[]{ this, new Info(), new CustomerProjectLogicalView(this), new CustomerCustomizerProvider(this), new CustomerActionProvider(), new CustomerProjectMoveOrRenameOperation(), new CustomerProjectCopyOperation(), new CustomerProjectDeleteOperation(), new ReportsSubprojectProvider(this), }); } return lkp; } Make Actions Visible on the Project Node. The NetBeans Project API gives you a number of CommonProjectActions, including for the actions we're dealing with. Make sure the items in bold below are in the "getActions" method of the project node: @Override public Action[] getActions(boolean arg0) { return new Action[]{ CommonProjectActions.newFileAction(), CommonProjectActions.copyProjectAction(), CommonProjectActions.moveProjectAction(), CommonProjectActions.renameProjectAction(), CommonProjectActions.deleteProjectAction(), CommonProjectActions.customizeProjectAction(), CommonProjectActions.closeProjectAction() }; } Run the Application. When you run the application, you should see this: Let's now try out the various actions: Copy. When you invoke the Copy action, you'll see the dialog below. Provide a new project name and location and then the copy action is performed when the Copy button is clicked below: The message you see above, in red, might not be relevant to your project type. When you right-click the application and choose Branding, you can find the string in the Resource Bundles tab, as shown below: However, note that the message will be shown in red, no matter what the text is, hence you can really only put something like a warning message there. If you have no text at all, it will also look odd.If the project has subprojects, the copy operation will not automatically copy the subprojects. Take a look here and here for similar more complex scenarios. Move. When you invoke the Move action, the dialog below is shown: Rename. The Rename Project dialog below is shown when you invoke the Rename action: I tried it and both the display name and the folder on disk are changed. Delete. When you invoke the Delete action, you'll see this dialog: The checkbox is not checkable, in the default scenario, and when the dialog above is confirmed, the project is simply closed, i.e., the node hierarchy is removed from the application. However, if you truly want to let the user delete the project on disk, pass the Project to the DeleteOperationImplementation and then add the children of the Project you want to delete to the getDataFiles method: private final class CustomerProjectDeleteOperation implements DeleteOperationImplementation { private final CustomerProject project; private CustomerProjectDeleteOperation(CustomerProject project) { this.project = project; } @Override public List<FileObject> getDataFiles() { List<FileObject> files = new ArrayList<FileObject>(); FileObject[] projectChildren = project.getProjectDirectory().getChildren(); for (FileObject fileObject : projectChildren) { addFile(project.getProjectDirectory(), fileObject.getNameExt(), files); } return files; } private void addFile(FileObject projectDirectory, String fileName, List<FileObject> result) { FileObject file = projectDirectory.getFileObject(fileName); if (file != null) { result.add(file); } } @Override public List<FileObject> getMetadataFiles() { return new ArrayList<FileObject>(); } @Override public void notifyDeleting() throws IOException { } @Override public void notifyDeleted() throws IOException { } } Now the user will be able to check the checkbox, causing the method above to be called in the DeleteOperationImplementation: Hope this answers some questions or at least gets the discussion started. Before asking questions about this topic, please take the steps above and only then attempt to apply them to your own scenario. Useful implementations to look at: http://kickjava.com/src/org/netbeans/modules/j2ee/clientproject/AppClientProjectOperations.java.htm https://kenai.com/projects/nbandroid/sources/mercurial/content/project/src/org/netbeans/modules/android/project/AndroidProjectOperations.java

    Read the article

  • Java Program help [migrated]

    - by georgetheevilman
    Okay I have a really annoying error. Its coming from my retainAll method. The problem is that I am outputting 1,3,5 in ints at the end, but I need 1,3,5,7,9. Here is the code below for the MySet and driver classes public class MySetTester { public static void main(String[]args) { MySet<String> strings = new MySet<String>(); strings.add("Hey!"); strings.add("Hey!"); strings.add("Hey!"); strings.add("Hey!"); strings.add("Hey!"); strings.add("Listen!"); strings.add("Listen!"); strings.add("Sorry, I couldn't resist."); strings.add("Sorry, I couldn't resist."); strings.add("(you know you would if you could)"); System.out.println("Testing add:\n"); System.out.println("Your size: " + strings.size() + ", contains(Sorry): " + strings.contains("Sorry, I couldn't resist.")); System.out.println("Exp. size: 4, contains(Sorry): true\n"); MySet<String> moreStrings = new MySet<String>(); moreStrings.add("Sorry, I couldn't resist."); moreStrings.add("(you know you would if you could)"); strings.removeAll(moreStrings); System.out.println("Testing remove and removeAll:\n"); System.out.println("Your size: " + strings.size() + ", contains(Sorry): " + strings.contains("Sorry, I couldn't resist.")); System.out.println("Exp. size: 2, contains(Sorry): false\n"); MySet<Integer> ints = new MySet<Integer>(); for (int i = 0; i < 100; i++) { ints.add(i); } System.out.println("Your size: " + ints.size()); System.out.println("Exp. size: 100\n"); for (int i = 0; i < 100; i += 2) { ints.remove(i); } System.out.println("Your size: " + ints.size()); System.out.println("Exp. size: 50\n"); MySet<Integer> zeroThroughNine = new MySet<Integer>(); for (int i = 0; i < 10; i++) { zeroThroughNine.add(i); } ints.retainAll(zeroThroughNine); System.out.println("ints should now only retain odd numbers" + " 0 through 10\n"); System.out.println("Testing your iterator:\n"); for (Integer i : ints) { System.out.println(i); } System.out.println("\nExpected: \n\n1 \n3 \n5 \n7 \n9\n"); System.out.println("Yours:"); for (String s : strings) { System.out.println(s); } System.out.println("\nExpected: \nHey! \nListen!"); strings.clear(); System.out.println("\nClearing your set...\n"); System.out.println("Your set is empty: " + strings.isEmpty()); System.out.println("Exp. set is empty: true"); } } And here is the main code. But still read the top part because that's where my examples are. import java.util.Set; import java.util.Collection; import java.lang.Iterable; import java.util.Iterator; import java.util.Arrays; import java.lang.reflect.Array; public class MySet implements Set, Iterable { // instance variables - replace the example below with your own private E[] backingArray; private int numElements; /** * Constructor for objects of class MySet */ public MySet() { backingArray=(E[]) new Object[5]; numElements=0; } public boolean add(E e){ for(Object elem:backingArray){ if (elem==null ? e==null : elem.equals(e)){ return false; } } if(numElements==backingArray.length){ E[] newArray=Arrays.copyOf(backingArray,backingArray.length*2); newArray[numElements]=e; numElements=numElements+1; backingArray=newArray; return true; } else{ backingArray[numElements]=e; numElements=numElements+1; return true; } } public boolean addAll(Collection<? extends E> c){ for(E elem:c){ this.add(elem); } return true; } public void clear(){ E[] newArray=(E[])new Object[backingArray.length]; numElements=0; backingArray=newArray; } public boolean equals(Object o){ if(o instanceof Set &&(((Set)o).size()==numElements)){ for(E elem:(Set<E>)o){ if (this.contains(o)==false){ return false; } return true; } } return false; } public boolean contains(Object o){ for(E backingElem:backingArray){ if (o!=null && o.equals(backingElem)){ return true; } } return false; } public boolean containsAll(Collection<?> c){ for(E elem:(Set<E>)c){ if(!(this.contains(elem))){ return false; } } return true; } public int hashCode(){ int sum=0; for(E elem:backingArray){ if(elem!=null){ sum=sum+elem.hashCode(); } } return sum; } public boolean isEmpty(){ if(numElements==0){ return true; } else{ return false; } } public boolean remove(Object o){ int i=0; for(Object elem:backingArray){ if(o!=null && o.equals(elem)){ backingArray[i]=null; numElements=numElements-1; E[] newArray=Arrays.copyOf(backingArray,backingArray.length-1); return true; } i=i+1; } return false; } public boolean removeAll(Collection<?> c){ for(Object elem:c){ this.remove(elem); } return true; } public boolean retainAll(Collection<?> c){ MySet<E> removalArray=new MySet<E>(); for(E arrayElem:backingArray){ if(arrayElem!= null && !(c.contains(arrayElem))){ this.remove(arrayElem); } } return false; } public int size(){ return numElements; } public <T> T[] toArray(T[] a) throws ArrayStoreException,NullPointerException{ for(int i=0;i<numElements;i++){ a[i]=(T)backingArray[i]; } for(int j=numElements;j<a.length;j++){ a[j]=null; } return a; } public Object[] toArray(){ Object[] newArray=new Object[numElements]; for(int i=0;i<numElements;i++){ newArray[i]=backingArray[i]; } return newArray; } public Iterator<E> iterator(){ setIterator iterator=new setIterator(); return iterator; } private class setIterator implements Iterator<E>{ private int currIndex; private E lastElement; public setIterator(){ currIndex=0; lastElement=null; } public boolean hasNext(){ while(currIndex<=numElements && backingArray[currIndex]==null){ currIndex=currIndex+1; } if (currIndex<=numElements){ return true; } return false; } public E next(){ E element=backingArray[currIndex]; currIndex=currIndex+1; lastElement=element; return element; } public void remove() throws UnsupportedOperationException,IllegalStateException{ if(lastElement!=null){ MySet.this.remove((Object)lastElement); numElements=numElements-1; } else{ throw new IllegalStateException(); } } } } I've been able to reduce the problems, but otherwise this thing is still causing problems.

    Read the article

  • How to swap or move 2 string in Array? [on hold]

    - by Wisnu Khazefa
    I have a need to convert .csv file to .dat file. In my problem, there are value pairs, with a name attribute (called Fund) and corresponding numeric value. If the input file has a pair whose value is 0, then that pair (Fund and value) is dropped. The output file should have only those pairs (Fund and value) where the value is non-zero. Here is the prototype of my code. public static void Check_Fund(){ String header = "Text1,Text2,Text3,FUND_UALFND_1,FUND_UALPRC_1,FUND_UALFND_2," +"FUND_UALPRC_2,FUND_UALFND_3,FUND_UALPRC_3,FUND_UALFND_4,FUND_UALPRC_4,FUND_UALFND_5,FUND_UALPRC_5,Text4,Text5,Text6,Text7"; String text = "ABC;CDE;EFG;PRMF;0;PRFF;50;PREF;0;PRCF;0;PRMP;50;TAHU;;BAKWAN;SINGKONG"; String[] head; String[] value; String showText = ""; head = header.split(","); value = text.split(";"); String regex = "\\d+"; String[] fund = {"PREF","PRMF","PRFF","PRCF","PRMP","PDFF","PSEF","PSCB","PSMF","PRGC","PREP"}; for(int i = 0; i < value.length; i++){ for(int j=0;j < fund.length; j++){ if(value[i].equals(fund[j]) && value[i+1].matches(regex)){ if(value[i+1].equals("0")){ value[i] = ""; value[i+1] = ""; } } } showText = showText + head[i] +":" + value[i] + System.lineSeparator(); } System.out.println(showText ); } Expected Result Input: FUND_UALFND_1:PRMF FUND_UALPRC_1:0 FUND_UALFND_2:PRFF FUND_UALPRC_2:50 FUND_UALFND_3:PREF FUND_UALPRC_3:0 FUND_UALFND_4:PRCF FUND_UALPRC_4:0 FUND_UALFND_5:PRMP FUND_UALPRC_5:50 Output: FUND_UALFND_1:PRFF FUND_UALPRC_1:50 FUND_UALFND_2:PRMP FUND_UALPRC_2:50 FUND_UALFND_0: FUND_UALPRC_0: FUND_UALFND_0: FUND_UALPRC_0: FUND_UALFND_0: FUND_UALPRC_0:

    Read the article

  • Scala parser combinator runs out of memory

    - by user3217013
    I wrote the following parser in Scala using the parser combinators: import scala.util.parsing.combinator._ import scala.collection.Map import scala.io.StdIn object Keywords { val Define = "define" val True = "true" val False = "false" val If = "if" val Then = "then" val Else = "else" val Return = "return" val Pass = "pass" val Conj = ";" val OpenParen = "(" val CloseParen = ")" val OpenBrack = "{" val CloseBrack = "}" val Comma = "," val Plus = "+" val Minus = "-" val Times = "*" val Divide = "/" val Pow = "**" val And = "&&" val Or = "||" val Xor = "^^" val Not = "!" val Equals = "==" val NotEquals = "!=" val Assignment = "=" } //--------------------------------------------------------------------------------- sealed abstract class Op case object Plus extends Op case object Minus extends Op case object Times extends Op case object Divide extends Op case object Pow extends Op case object And extends Op case object Or extends Op case object Xor extends Op case object Not extends Op case object Equals extends Op case object NotEquals extends Op case object Assignment extends Op //--------------------------------------------------------------------------------- sealed abstract class Term case object TrueTerm extends Term case object FalseTerm extends Term case class FloatTerm(value : Float) extends Term case class StringTerm(value : String) extends Term case class Identifier(name : String) extends Term //--------------------------------------------------------------------------------- sealed abstract class Expression case class TermExp(term : Term) extends Expression case class UnaryOp(op : Op, exp : Expression) extends Expression case class BinaryOp(op : Op, left : Expression, right : Expression) extends Expression case class FuncApp(funcName : Term, args : List[Expression]) extends Expression //--------------------------------------------------------------------------------- sealed abstract class Statement case class ExpressionStatement(exp : Expression) extends Statement case class Pass() extends Statement case class Return(value : Expression) extends Statement case class AssignmentVar(variable : Term, exp : Expression) extends Statement case class IfThenElse(testBody : Expression, thenBody : Statement, elseBody : Statement) extends Statement case class Conjunction(left : Statement, right : Statement) extends Statement case class AssignmentFunc(functionName : Term, args : List[Term], body : Statement) extends Statement //--------------------------------------------------------------------------------- class myParser extends JavaTokenParsers { val keywordMap : Map[String, Op] = Map( Keywords.Plus -> Plus, Keywords.Minus -> Minus, Keywords.Times -> Times, Keywords.Divide -> Divide, Keywords.Pow -> Pow, Keywords.And -> And, Keywords.Or -> Or, Keywords.Xor -> Xor, Keywords.Not -> Not, Keywords.Equals -> Equals, Keywords.NotEquals -> NotEquals, Keywords.Assignment -> Assignment ) def floatTerm : Parser[Term] = decimalNumber ^^ { case x => FloatTerm( x.toFloat ) } def stringTerm : Parser[Term] = stringLiteral ^^ { case str => StringTerm(str) } def identifier : Parser[Term] = ident ^^ { case value => Identifier(value) } def boolTerm : Parser[Term] = (Keywords.True | Keywords.False) ^^ { case Keywords.True => TrueTerm case Keywords.False => FalseTerm } def simpleTerm : Parser[Expression] = (boolTerm | floatTerm | stringTerm) ^^ { case term => TermExp(term) } def argument = expression def arguments_aux : Parser[List[Expression]] = (argument <~ Keywords.Comma) ~ arguments ^^ { case arg ~ argList => arg :: argList } def arguments = arguments_aux | { argument ^^ { case arg => List(arg) } } def funcAppArgs : Parser[List[Expression]] = funcEmptyArgs | ( Keywords.OpenParen ~> arguments <~ Keywords.CloseParen ^^ { case args => args.foldRight(List[Expression]()) ( (a,b) => a :: b ) } ) def funcApp = identifier ~ funcAppArgs ^^ { case funcName ~ argList => FuncApp(funcName, argList) } def variableTerm : Parser[Expression] = identifier ^^ { case name => TermExp(name) } def atomic_expression = simpleTerm | funcApp | variableTerm def paren_expression : Parser[Expression] = Keywords.OpenParen ~> expression <~ Keywords.CloseParen def unary_operation : Parser[String] = Keywords.Not def unary_expression : Parser[Expression] = operation(0) ~ expression(0) ^^ { case op ~ exp => UnaryOp(keywordMap(op), exp) } def operation(precedence : Int) : Parser[String] = precedence match { case 0 => Keywords.Not case 1 => Keywords.Pow case 2 => Keywords.Times | Keywords.Divide | Keywords.And case 3 => Keywords.Plus | Keywords.Minus | Keywords.Or | Keywords.Xor case 4 => Keywords.Equals | Keywords.NotEquals case _ => throw new Exception("No operations with this precedence.") } def binary_expression(precedence : Int) : Parser[Expression] = precedence match { case 0 => throw new Exception("No operation with zero precedence.") case n => (expression (n-1)) ~ operation(n) ~ (expression (n)) ^^ { case left ~ op ~ right => BinaryOp(keywordMap(op), left, right) } } def expression(precedence : Int) : Parser[Expression] = precedence match { case 0 => unary_expression | paren_expression | atomic_expression case n => binary_expression(n) | expression(n-1) } def expression : Parser[Expression] = expression(4) def expressionStmt : Parser[Statement] = expression ^^ { case exp => ExpressionStatement(exp) } def assignment : Parser[Statement] = (identifier <~ Keywords.Assignment) ~ expression ^^ { case varName ~ exp => AssignmentVar(varName, exp) } def ifthen : Parser[Statement] = ((Keywords.If ~ Keywords.OpenParen) ~> expression <~ Keywords.CloseParen) ~ ((Keywords.Then ~ Keywords.OpenBrack) ~> statements <~ Keywords.CloseBrack) ^^ { case ifBody ~ thenBody => IfThenElse(ifBody, thenBody, Pass()) } def ifthenelse : Parser[Statement] = ((Keywords.If ~ Keywords.OpenParen) ~> expression <~ Keywords.CloseParen) ~ ((Keywords.Then ~ Keywords.OpenBrack) ~> statements <~ Keywords.CloseBrack) ~ ((Keywords.Else ~ Keywords.OpenBrack) ~> statements <~ Keywords.CloseBrack) ^^ { case ifBody ~ thenBody ~ elseBody => IfThenElse(ifBody, thenBody, elseBody) } def pass : Parser[Statement] = Keywords.Pass ^^^ { Pass() } def returnStmt : Parser[Statement] = Keywords.Return ~> expression ^^ { case exp => Return(exp) } def statement : Parser[Statement] = ((pass | returnStmt | assignment | expressionStmt) <~ Keywords.Conj) | ifthenelse | ifthen def statements_aux : Parser[Statement] = statement ~ statements ^^ { case st ~ sts => Conjunction(st, sts) } def statements : Parser[Statement] = statements_aux | statement def funcDefBody : Parser[Statement] = Keywords.OpenBrack ~> statements <~ Keywords.CloseBrack def funcEmptyArgs = Keywords.OpenParen ~ Keywords.CloseParen ^^^ { List() } def funcDefArgs : Parser[List[Term]] = funcEmptyArgs | Keywords.OpenParen ~> repsep(identifier, Keywords.Comma) <~ Keywords.CloseParen ^^ { case args => args.foldRight(List[Term]()) ( (a,b) => a :: b ) } def funcDef : Parser[Statement] = (Keywords.Define ~> identifier) ~ funcDefArgs ~ funcDefBody ^^ { case funcName ~ funcArgs ~ body => AssignmentFunc(funcName, funcArgs, body) } def funcDefAndStatement : Parser[Statement] = funcDef | statement def funcDefAndStatements_aux : Parser[Statement] = funcDefAndStatement ~ funcDefAndStatements ^^ { case stmt ~ stmts => Conjunction(stmt, stmts) } def funcDefAndStatements : Parser[Statement] = funcDefAndStatements_aux | funcDefAndStatement def parseProgram : Parser[Statement] = funcDefAndStatements def eval(input : String) = { parseAll(parseProgram, input) match { case Success(result, _) => result case Failure(m, _) => println(m) case _ => println("") } } } object Parser { def main(args : Array[String]) { val x : myParser = new myParser() println(args(0)) val lines = scala.io.Source.fromFile(args(0)).mkString println(x.eval(lines)) } } The problem is, when I run the parser on the following example it works fine: define foo(a) { if (!h(IM) && a) then { return 0; } if (a() && !h()) then { return 0; } } But when I add threes characters in the first if statement, it runs out of memory. This is absolutely blowing my mind. Can anyone help? (I suspect it has to do with repsep, but I am not sure.) define foo(a) { if (!h(IM) && a(1)) then { return 0; } if (a() && !h()) then { return 0; } } EDIT: Any constructive comments about my Scala style is also appreciated.

    Read the article

  • Sorting in Hash Maps in Java

    - by Crystal
    I'm trying to get familiar with Collections. I have a String which is my key, email address, and a Person object (firstName, lastName, telephone, email). I read in the Java collections chapter on Sun's webpages that if you had a HashMap and wanted it sorted, you could use a TreeMap. How does this sort work? Is it based on the compareTo() method you have in your Person class? I overrode the compareTo() method in my Person class to sort by lastName. But it isn't working properly and was wondering if I have the right idea or not. getSortedListByLastName at the bottom of this code is where I try to convert to a TreeMap. Also, if this is the correct way to do it, or one of the correct ways to do it, how do I then sort by firstName since my compareTo() is comparing by lastName. import java.util.*; public class OrganizeThis { /** Add a person to the organizer @param p A person object */ public void add(Person p) { staff.put(p.getEmail(), p); //System.out.println("Person " + p + "added"); } /** * Remove a Person from the organizer. * * @param email The email of the person to be removed. */ public void remove(String email) { staff.remove(email); } /** * Remove all contacts from the organizer. * */ public void empty() { staff.clear(); } /** * Find the person stored in the organizer with the email address. * Note, each person will have a unique email address. * * @param email The person email address you are looking for. * */ public Person findByEmail(String email) { Person aPerson = staff.get(email); return aPerson; } /** * Find all persons stored in the organizer with the same last name. * Note, there can be multiple persons with the same last name. * * @param lastName The last name of the persons your are looking for. * */ public Person[] find(String lastName) { ArrayList<Person> names = new ArrayList<Person>(); for (Person s : staff.values()) { if (s.getLastName() == lastName) { names.add(s); } } // Convert ArrayList back to Array Person nameArray[] = new Person[names.size()]; names.toArray(nameArray); return nameArray; } /** * Return all the contact from the orgnizer in * an array sorted by last name. * * @return An array of Person objects. * */ public Person[] getSortedListByLastName() { Map<String, Person> sorted = new TreeMap<String, Person>(staff); ArrayList<Person> sortedArrayList = new ArrayList<Person>(); for (Person s: sorted.values()) { sortedArrayList.add(s); } Person sortedArray[] = new Person[sortedArrayList.size()]; sortedArrayList.toArray(sortedArray); return sortedArray; } private Map<String, Person> staff = new HashMap<String, Person>(); public static void main(String[] args) { OrganizeThis testObj = new OrganizeThis(); Person person1 = new Person("J", "W", "111-222-3333", "[email protected]"); Person person2 = new Person("K", "W", "345-678-9999", "[email protected]"); Person person3 = new Person("Phoebe", "Wang", "322-111-3333", "[email protected]"); Person person4 = new Person("Nermal", "Johnson", "322-342-5555", "[email protected]"); Person person5 = new Person("Apple", "Banana", "123-456-1111", "[email protected]"); testObj.add(person1); testObj.add(person2); testObj.add(person3); testObj.add(person4); testObj.add(person5); System.out.println(testObj.findByEmail("[email protected]")); System.out.println("------------" + '\n'); Person a[] = testObj.find("W"); for (Person p : a) System.out.println(p); System.out.println("------------" + '\n'); a = testObj.find("W"); for (Person p : a) System.out.println(p); System.out.println("SORTED" + '\n'); a = testObj.getSortedListByLastName(); for (Person b : a) { System.out.println(b); } } } Person class: public class Person implements Comparable { String firstName; String lastName; String telephone; String email; public Person() { firstName = ""; lastName = ""; telephone = ""; email = ""; } public Person(String firstName) { this.firstName = firstName; } public Person(String firstName, String lastName, String telephone, String email) { this.firstName = firstName; this.lastName = lastName; this.telephone = telephone; this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int compareTo(Object o) { String s1 = this.lastName + this.firstName; String s2 = ((Person) o).lastName + ((Person) o).firstName; return s1.compareTo(s2); } public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) { return true; } // must return false if the explicit parameter is null if (otherObject == null) { return false; } if (!(otherObject instanceof Person)) { return false; } Person other = (Person) otherObject; return firstName.equals(other.firstName) && lastName.equals(other.lastName) && telephone.equals(other.telephone) && email.equals(other.email); } public int hashCode() { return this.email.toLowerCase().hashCode(); } public String toString() { return getClass().getName() + "[firstName = " + firstName + '\n' + "lastName = " + lastName + '\n' + "telephone = " + telephone + '\n' + "email = " + email + "]"; } }

    Read the article

  • Custom language - FOR loop in a clojure interpeter?

    - by Mark
    I have a basic interpreter in clojure. Now i need to implement for (initialisation; finish-test; loop-update) { statements } Implement a similar for-loop for the interpreted language. The pattern will be: (for variable-declarations end-test loop-update do statement) The variable-declarations will set up initial values for variables.The end-test returns a boolean, and the loop will end if end-test returns false. The statement is interpreted followed by the loop-update for each pass of the loop. Examples of use are: (run ’(for ((i 0)) (< i 10) (set i (+ 1 i)) do (println i))) (run ’(for ((i 0) (j 0)) (< i 10) (seq (set i (+ 1 i)) (set j (+ j (* 2 i)))) do (println j))) inside my interpreter. I will attach my interpreter code I got so far. Any help is appreciated. Interpreter (declare interpret make-env) ;; needed as language terms call out to 'interpret' (def do-trace false) ;; change to 'true' to show calls to 'interpret' ;; simple utilities (def third ; return third item in a list (fn [a-list] (second (rest a-list)))) (def fourth ; return fourth item in a list (fn [a-list] (third (rest a-list)))) (def run ; make it easy to test the interpreter (fn [e] (println "Processing: " e) (println "=> " (interpret e (make-env))))) ;; for the environment (def make-env (fn [] '())) (def add-var (fn [env var val] (cons (list var val) env))) (def lookup-var (fn [env var] (cond (empty? env) 'error (= (first (first env)) var) (second (first env)) :else (lookup-var (rest env) var)))) ;; for terms in language ;; -- define numbers (def is-number? (fn [expn] (number? expn))) (def interpret-number (fn [expn env] expn)) ;; -- define symbols (def is-symbol? (fn [expn] (symbol? expn))) (def interpret-symbol (fn [expn env] (lookup-var env expn))) ;; -- define boolean (def is-boolean? (fn [expn] (or (= expn 'true) (= expn 'false)))) (def interpret-boolean (fn [expn env] expn)) ;; -- define functions (def is-function? (fn [expn] (and (list? expn) (= 3 (count expn)) (= 'lambda (first expn))))) (def interpret-function ; keep function definitions as they are written (fn [expn env] expn)) ;; -- define addition (def is-plus? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '+ (first expn))))) (def interpret-plus (fn [expn env] (+ (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define subtraction (def is-minus? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '- (first expn))))) (def interpret-minus (fn [expn env] (- (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define multiplication (def is-times? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '* (first expn))))) (def interpret-times (fn [expn env] (* (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define division (def is-divides? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '/ (first expn))))) (def interpret-divides (fn [expn env] (/ (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define equals test (def is-equals? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '= (first expn))))) (def interpret-equals (fn [expn env] (= (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define greater-than test (def is-greater-than? (fn [expn] (and (list? expn) (= 3 (count expn)) (= '> (first expn))))) (def interpret-greater-than (fn [expn env] (> (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define not (def is-not? (fn [expn] (and (list? expn) (= 2 (count expn)) (= 'not (first expn))))) (def interpret-not (fn [expn env] (not (interpret (second expn) env)))) ;; -- define or (def is-or? (fn [expn] (and (list? expn) (= 3 (count expn)) (= 'or (first expn))))) (def interpret-or (fn [expn env] (or (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define and (def is-and? (fn [expn] (and (list? expn) (= 3 (count expn)) (= 'and (first expn))))) (def interpret-and (fn [expn env] (and (interpret (second expn) env) (interpret (third expn) env)))) ;; -- define print (def is-print? (fn [expn] (and (list? expn) (= 2 (count expn)) (= 'println (first expn))))) (def interpret-print (fn [expn env] (println (interpret (second expn) env)))) ;; -- define with (def is-with? (fn [expn] (and (list? expn) (= 3 (count expn)) (= 'with (first expn))))) (def interpret-with (fn [expn env] (interpret (third expn) (add-var env (first (second expn)) (interpret (second (second expn)) env))))) ;; -- define if (def is-if? (fn [expn] (and (list? expn) (= 4 (count expn)) (= 'if (first expn))))) (def interpret-if (fn [expn env] (cond (interpret (second expn) env) (interpret (third expn) env) :else (interpret (fourth expn) env)))) ;; -- define function-application (def is-function-application? (fn [expn env] (and (list? expn) (= 2 (count expn)) (is-function? (interpret (first expn) env))))) (def interpret-function-application (fn [expn env] (let [function (interpret (first expn) env)] (interpret (third function) (add-var env (first (second function)) (interpret (second expn) env)))))) ;; the interpreter itself (def interpret (fn [expn env] (cond do-trace (println "Interpret is processing: " expn)) (cond ; basic values (is-number? expn) (interpret-number expn env) (is-symbol? expn) (interpret-symbol expn env) (is-boolean? expn) (interpret-boolean expn env) (is-function? expn) (interpret-function expn env) ; built-in functions (is-plus? expn) (interpret-plus expn env) (is-minus? expn) (interpret-minus expn env) (is-times? expn) (interpret-times expn env) (is-divides? expn) (interpret-divides expn env) (is-equals? expn) (interpret-equals expn env) (is-greater-than? expn) (interpret-greater-than expn env) (is-not? expn) (interpret-not expn env) (is-or? expn) (interpret-or expn env) (is-and? expn) (interpret-and expn env) (is-print? expn) (interpret-print expn env) ; special syntax (is-with? expn) (interpret-with expn env) (is-if? expn) (interpret-if expn env) ; functions (is-function-application? expn env) (interpret-function-application expn env) :else 'error))) ;; tests of using environment (println "Environment tests:") (println (add-var (make-env) 'x 1)) (println (add-var (add-var (add-var (make-env) 'x 1) 'y 2) 'x 3)) (println (lookup-var '() 'x)) (println (lookup-var '((x 1)) 'x)) (println (lookup-var '((x 1) (y 2)) 'x)) (println (lookup-var '((x 1) (y 2)) 'y)) (println (lookup-var '((x 3) (y 2) (x 1)) 'x)) ;; examples of using interpreter (println "Interpreter examples:") (run '1) (run '2) (run '(+ 1 2)) (run '(/ (* (+ 4 5) (- 2 4)) 2)) (run '(with (x 1) x)) (run '(with (x 1) (with (y 2) (+ x y)))) (run '(with (x (+ 2 4)) x)) (run 'false) (run '(not false)) (run '(with (x true) (with (y false) (or x y)))) (run '(or (= 3 4) (> 4 3))) (run '(with (x 1) (if (= x 1) 2 3))) (run '(with (x 2) (if (= x 1) 2 3))) (run '((lambda (n) (* 2 n)) 4)) (run '(with (double (lambda (n) (* 2 n))) (double 4))) (run '(with (sum-to (lambda (n) (if (= n 0) 0 (+ n (sum-to (- n 1)))))) (sum-to 100))) (run '(with (x 1) (with (f (lambda (n) (+ n x))) (with (x 2) (println (f 3))))))

    Read the article

  • How to save/retrieve words to/from SQlite database?

    - by user998032
    Sorry if I repeat my question but I have still had no clues of what to do and how to deal with the question. My app is a dictionary. I assume that users will need to add words that they want to memorise to a Favourite list. Thus, I created a Favorite button that works on two phases: short-click to save the currently-view word into the Favourite list; and long-click to view the Favourite list so that users can click on any words to look them up again. I go for using a SQlite database to store the favourite words but I wonder how I can do this task. Specifically, my questions are: Should I use the current dictionary SQLite database or create a new SQLite database to favorite words? In each case, what codes do I have to write to cope with the mentioned task? Could anyone there kindly help? Here is the dictionary code: package mydict.app; import java.util.ArrayList; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.util.Log; public class DictionaryEngine { static final private String SQL_TAG = "[MyAppName - DictionaryEngine]"; private SQLiteDatabase mDB = null; private String mDBName; private String mDBPath; //private String mDBExtension; public ArrayList<String> lstCurrentWord = null; public ArrayList<String> lstCurrentContent = null; //public ArrayAdapter<String> adapter = null; public DictionaryEngine() { lstCurrentContent = new ArrayList<String>(); lstCurrentWord = new ArrayList<String>(); } public DictionaryEngine(String basePath, String dbName, String dbExtension) { //mDBExtension = getResources().getString(R.string.dbExtension); //mDBExtension = dbExtension; lstCurrentContent = new ArrayList<String>(); lstCurrentWord = new ArrayList<String>(); this.setDatabaseFile(basePath, dbName, dbExtension); } public boolean setDatabaseFile(String basePath, String dbName, String dbExtension) { if (mDB != null) { if (mDB.isOpen() == true) // Database is already opened { if (basePath.equals(mDBPath) && dbName.equals(mDBName)) // the opened database has the same name and path -> do nothing { Log.i(SQL_TAG, "Database is already opened!"); return true; } else { mDB.close(); } } } String fullDbPath=""; try { fullDbPath = basePath + dbName + "/" + dbName + dbExtension; mDB = SQLiteDatabase.openDatabase(fullDbPath, null, SQLiteDatabase.OPEN_READWRITE|SQLiteDatabase.NO_LOCALIZED_COLLATORS); } catch (SQLiteException ex) { ex.printStackTrace(); Log.i(SQL_TAG, "There is no valid dictionary database " + dbName +" at path " + basePath); return false; } if (mDB == null) { return false; } this.mDBName = dbName; this.mDBPath = basePath; Log.i(SQL_TAG,"Database " + dbName + " is opened!"); return true; } public void getWordList(String word) { String query; // encode input String wordEncode = Utility.encodeContent(word); if (word.equals("") || word == null) { query = "SELECT id,word FROM " + mDBName + " LIMIT 0,15" ; } else { query = "SELECT id,word FROM " + mDBName + " WHERE word >= '"+wordEncode+"' LIMIT 0,15"; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); int indexWordColumn = result.getColumnIndex("Word"); int indexContentColumn = result.getColumnIndex("Content"); if (result != null) { int countRow=result.getCount(); Log.i(SQL_TAG, "countRow = " + countRow); lstCurrentWord.clear(); lstCurrentContent.clear(); if (countRow >= 1) { result.moveToFirst(); String strWord = Utility.decodeContent(result.getString(indexWordColumn)); String strContent = Utility.decodeContent(result.getString(indexContentColumn)); lstCurrentWord.add(0,strWord); lstCurrentContent.add(0,strContent); int i = 0; while (result.moveToNext()) { strWord = Utility.decodeContent(result.getString(indexWordColumn)); strContent = Utility.decodeContent(result.getString(indexContentColumn)); lstCurrentWord.add(i,strWord); lstCurrentContent.add(i,strContent); i++; } } result.close(); } } public Cursor getCursorWordList(String word) { String query; // encode input String wordEncode = Utility.encodeContent(word); if (word.equals("") || word == null) { query = "SELECT id,word FROM " + mDBName + " LIMIT 0,15" ; } else { query = "SELECT id,content,word FROM " + mDBName + " WHERE word >= '"+wordEncode+"' LIMIT 0,15"; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); return result; } public Cursor getCursorContentFromId(int wordId) { String query; // encode input if (wordId <= 0) { return null; } else { query = "SELECT id,content,word FROM " + mDBName + " WHERE Id = " + wordId ; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); return result; } public Cursor getCursorContentFromWord(String word) { String query; // encode input if (word == null || word.equals("")) { return null; } else { query = "SELECT id,content,word FROM " + mDBName + " WHERE word = '" + word + "' LIMIT 0,1"; } //Log.i(SQL_TAG, "query = " + query); Cursor result = mDB.rawQuery(query,null); return result; } public void closeDatabase() { mDB.close(); } public boolean isOpen() { return mDB.isOpen(); } public boolean isReadOnly() { return mDB.isReadOnly(); } } And here is the code below the Favourite button to save to and load the Favourite list: btnAddFavourite = (ImageButton) findViewById(R.id.btnAddFavourite); btnAddFavourite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Add code here to save the favourite, e.g. in the db. Toast toast = Toast.makeText(ContentView.this, R.string.messageWordAddedToFarvourite, Toast.LENGTH_SHORT); toast.show(); } }); btnAddFavourite.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // Open the favourite Activity, which in turn will fetch the saved favourites, to show them. Intent intent = new Intent(getApplicationContext(), FavViewFavourite.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplicationContext().startActivity(intent); return false; } }); }

    Read the article

  • Using a Predicate as a key to a Dictionary

    - by Tom Hines
    I really love Linq and Lambda Expressions in C#.  I also love certain community forums and programming websites like DaniWeb. A user on DaniWeb posted a question about comparing the results of a game that is like poker (5-card stud), but is played with dice. The question stemmed around determining what was the winning hand.  I looked at the question and issued some comments and suggestions toward a potential answer, but I thought it was a neat homework exercise. [A little explanation] I eventually realized not only could I compare the results of the hands (by name) with a certain construct – I could also compare the values of the individual dice with the same construct. That piece of code eventually became a Dictionary with the KEY as a Predicate<int> and the Value a Func<T> that returns a string from the another structure that contains the mapping of an ENUM to a string.  In one instance, that string is the name of the hand and in another instance, it is a string (CSV) representation of of the digits in the hand. An added benefit is that the digits re returned in the order they would be for a proper poker hand.  For instance the hand 1,2,5,3,1 would be returned as ONE_PAIR (1,1,5,3,2). [Getting to the point] 1: using System; 2: using System.Collections.Generic; 3:   4: namespace DicePoker 5: { 6: using KVP_E2S = KeyValuePair<CDicePoker.E_DICE_POKER_HAND_VAL, string>; 7: public partial class CDicePoker 8: { 9: /// <summary> 10: /// Magical construction to determine the winner of given hand Key/Value. 11: /// </summary> 12: private static Dictionary<Predicate<int>, Func<List<KVP_E2S>, string>> 13: map_prd2fn = new Dictionary<Predicate<int>, Func<List<KVP_E2S>, string>> 14: { 15: {new Predicate<int>(i => i.Equals(0)), PlayerTie},//first tie 16:   17: {new Predicate<int>(i => i > 0), 18: (m => string.Format("Player One wins\n1={0}({1})\n2={2}({3})", 19: m[0].Key, m[0].Value, m[1].Key, m[1].Value))}, 20:   21: {new Predicate<int>(i => i < 0), 22: (m => string.Format("Player Two wins\n2={2}({3})\n1={0}({1})", 23: m[0].Key, m[0].Value, m[1].Key, m[1].Value))}, 24:   25: {new Predicate<int>(i => i.Equals(0)), 26: (m => string.Format("Tie({0}) \n1={1}\n2={2}", 27: m[0].Key, m[0].Value, m[1].Value))} 28: }; 29: } 30: } When this is called, the code calls the Invoke method of the predicate to return a bool.  The first on matching true will have its value invoked. 1: private static Func<DICE_HAND, E_DICE_POKER_HAND_VAL> GetHandEval = dh => 2: map_dph2fn[map_dph2fn.Keys.Where(enm2fn => enm2fn(dh)).First()]; After coming up with this process, I realized (with a little modification) it could be called to evaluate the individual values in the dice hand in the event of a tie. 1: private static Func<List<KVP_E2S>, string> PlayerTie = lst_kvp => 2: map_prd2fn.Skip(1) 3: .Where(x => x.Key.Invoke(RenderDigits(dhPlayerOne).CompareTo(RenderDigits(dhPlayerTwo)))) 4: .Select(s => s.Value) 5: .First().Invoke(lst_kvp); After that, I realized I could now create a program completely without “if” statements or “for” loops! 1: static void Main(string[] args) 2: { 3: Dictionary<Predicate<int>, Action<Action<string>>> main = new Dictionary<Predicate<int>, Action<Action<string>>> 4: { 5: {(i => i.Equals(0)), PlayGame}, 6: {(i => true), Usage} 7: }; 8:   9: main[main.Keys.Where(m => m.Invoke(args.Length)).First()].Invoke(Display); 10: } …and there you have it. :) ZIPPED Project

    Read the article

  • Remove duplicates from DataTable and custom IEqualityComparer<DataRow>

    - by abatishchev
    How have I to implement IEqualityComparer<DataRow> to remove duplicates rows from a DataTable with next structure: ID primary key, col_1, col_2, col_3, col_4 The default comparer doesn't work because each row has it's own, unique primary key. How to implement IEqualityComparer<DataRow> that will skip primary key and compare only data remained. I have something like this: public class DataRowComparer : IEqualityComparer<DataRow> { public bool Equals(DataRow x, DataRow y) { return x.ItemArray.Except(new object[] { x[x.Table.PrimaryKey[0].ColumnName] }) == y.ItemArray.Except(new object[] { y[y.Table.PrimaryKey[0].ColumnName] }); } public int GetHashCode(DataRow obj) { return obj.ToString().GetHashCode(); } } and public static DataTable RemoveDuplicates(this DataTable table) { return (table.Rows.Count > 0) ? table.AsEnumerable().Distinct(new DataRowComparer()).CopyToDataTable() : table; } but it calls only GetHashCode() and doesn't call Equals()

    Read the article

  • Update a list from another list

    - by Langali
    I have a list of users in local store that I need to update from a remote list of users every once in a while. Basically: If a remote user already exists locally, update its fields. If a remote user doesn't already exist locally, add the user. If a local user doesn't appear in the remote list, deactivate or delete. If a local user also appears in the remote list, update its fields. Just a simple case of syncing the local list. Is there a better way to do this in pure Java than the following? I feel gross looking at my own code. public class User { Integer id; String email; boolean active; //Getters and Setters....... public User(Integer id, String email, boolean active) { this.id = id; this.email = email; this.active = active; } @Override public boolean equals(Object other) { boolean result = false; if (other instanceof User) { User that = (User) other; result = (this.getId() == that.getId()); } return result; } } public static void main(String[] args) { //From 3rd party List<User> remoteUsers = getRemoteUsers(); //From Local store List<User> localUsers =getLocalUsers(); for (User remoteUser : remoteUsers) { boolean found = false; for (User localUser : localUsers) { if (remoteUser.equals(localUser)) { found = true; localUser.setActive(remoteUser.isActive()); localUser.setEmail(remoteUser.getEmail()); //update } break; } if (!found) { User user = new User(remoteUser.getId(), remoteUser.getEmail(), remoteUser.isActive()); //Save } } for(User localUser : localUsers ) { boolean found = false; for(User remoteUser : remoteUsers) { if(localUser.equals(remoteUser)) { found = true; localUser.setActive(remoteUser.isActive()); localUser.setEmail(remoteUser.getEmail()); //Update } break; } if(!found) { localUser.setActive(false); // Deactivate } } }

    Read the article

  • Outer Join is not working in Linq Query: The method 'Join' cannot follow the method 'SelectMany' or is not supported

    - by Scorpion
    I am writing the Linq query as below: But on run its throwing the following error: The method 'Join' cannot follow the method 'SelectMany' or is not supported. Try writing the query in terms of supported methods or call the 'AsEnumerable' or 'ToList' method before calling unsupported methods. LINQ from a in AccountSet join sm in new_schoolMemberSet on a.AccountId equals sm.new_OrganisationId.Id into ps from suboc in ps.DefaultIfEmpty() join sr in new_schoolRoleSet on suboc.new_SchoolRoleId.Id equals sr.new_schoolRoleId where sr.new_name == "Manager" where a.new_OrganisationType.Value == 430870007 select new { a.AccountId, a.new_OrganisationType.Value } I am expecting the result as below: I never used the Outer join in Linq before. So please correct me if I am doing it wrong. Thanks

    Read the article

  • General advice and guidelines on how to properly override object.GetHashCode()

    - by Svish
    According to MSDN, a hash function must have the following properties: If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values. The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again. For the best performance, a hash function must generate a random distribution for all input. I keep finding myself in the following scenario: I have created a class, implemented IEquatable<T> and overridden object.Equals(object). MSDN states that: Types that override Equals must also override GetHashCode ; otherwise, Hashtable might not work correctly. And then it usually stops up a bit for me. Because, how do you properly override object.GetHashCode()? Never really know where to start, and it seems to be a lot of pitfalls. Here at StackOverflow, there are quite a few questions related to GetHashCode overriding, but most of them seems to be on quite particular cases and specific issues. So, therefore I would like to get a good compilation here. An overview with general advice and guidelines. What to do, what not to do, common pitfalls, where to start, etc. I would like it to be especially directed at C#, but I would think it will work kind of the same way for other .NET languages as well(?). I think maybe the best way is to create one answer per topic with a quick and short answer first (close to one-liner if at all possible), then maybe some more information and end with related questions, discussions, blog posts, etc., if there are any. I can then create one post as the accepted answer (to get it on top) with just a "table of contents". Try to keep it short and concise. And don't just link to other questions and blog posts. Try to take the essence of them and then rather link to source (especially since the source could disappear. Also, please try to edit and improve answers instead of created lots of very similar ones. I am not a very good technical writer, but I will at least try to format answers so they look alike, create the table of contents, etc. I will also try to search up some of the related questions here at SO that answers parts of these and maybe pull out the essence of the ones I can manage. But since I am not very stable on this topic, I will try to stay away for the most part :p

    Read the article

  • Can I query DOM Document with xpath expression from multiple threads safely?

    - by Dan
    I plan to use dom4j DOM Document as a static cache in an application where multiples threads can query the document. Taking into the account that the document itself will never change, is it safe to query it from multiple threads? I wrote the following code to test it, but I am not sure that it actually does prove that operation is safe? package test.concurrent_dom; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; /** * Hello world! * */ public class App extends Thread { private static final String xml = "<Session>" + "<child1 attribute1=\"attribute1value\" attribute2=\"attribute2value\">" + "ChildText1</child1>" + "<child2 attribute1=\"attribute1value\" attribute2=\"attribute2value\">" + "ChildText2</child2>" + "<child3 attribute1=\"attribute1value\" attribute2=\"attribute2value\">" + "ChildText3</child3>" + "</Session>"; private static Document document; private static Element root; public static void main( String[] args ) throws DocumentException { document = DocumentHelper.parseText(xml); root = document.getRootElement(); Thread t1 = new Thread(){ public void run(){ while(true){ try { sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } Node n1 = root.selectSingleNode("/Session/child1"); if(!n1.getText().equals("ChildText1")){ System.out.println("WRONG!"); } } } }; Thread t2 = new Thread(){ public void run(){ while(true){ try { sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } Node n1 = root.selectSingleNode("/Session/child2"); if(!n1.getText().equals("ChildText2")){ System.out.println("WRONG!"); } } } }; Thread t3 = new Thread(){ public void run(){ while(true){ try { sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } Node n1 = root.selectSingleNode("/Session/child3"); if(!n1.getText().equals("ChildText3")){ System.out.println("WRONG!"); } } } }; t1.start(); t2.start(); t3.start(); System.out.println( "Hello World!" ); } }

    Read the article

  • linq query - The method or operation is not implemented.

    - by Dejan.S
    I'm doing the Rob Conery mvc storefront and at one place I'm suppose to get categories but I get an error with this linq query and I can not get why. It's exactly the same as his. var culturedName = from ct in ReadOnlyContext.CategoryCultureDetails where ct.Culture.LanguageCode == System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName select new { ct.CategoryName, ct.CategoryId }; return from c in ReadOnlyContext.Categories join cn in culturedName on c.CategoryId equals cn.CategoryId select new Core.Model.Category { Id = c.CategoryId, Name = cn.CategoryName, ParentId = c.ParentId ?? 0, Products = new LazyList<Core.Model.Product>(from p in GetProducts() join cp in ReadOnlyContext.Categories_Products on p.Id equals cp.ProductId where cp.CategoryId == c.CategoryId select p) }; its the return query that mess things up. I have checked and the culturename actually gets data from the database. Appricate your help

    Read the article

  • Hibernate MappingException

    - by Marcus
    I'm getting this Hibernate error: org.hibernate.MappingException: Could not determine type for: a.b.c.Results$BusinessDate, for columns: [org.hibernate.mapping.Column(businessDate)] The class is below. Does anyone know why I'm getting this error?? @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "businessDate" }) @XmlRootElement(name = "Results") @Entity(name = "Results") @Table(name = "RESULT") @Inheritance(strategy = InheritanceType.JOINED) @Cache(usage = CacheConcurrencyStrategy.READ_ONLY) public class Results implements Equals, HashCode { @XmlElement(name = "BusinessDate", required = true) protected Results.BusinessDate businessDate; public Results.BusinessDate getBusinessDate() { return businessDate; } public void setBusinessDate(Results.BusinessDate value) { this.businessDate = value; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "raw", "display" }) @Entity(name = "Results$BusinessDate") @Table(name = "BUSINESSDATE") @Inheritance(strategy = InheritanceType.JOINED) public static class BusinessDate implements Equals, HashCode { ....

    Read the article

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