Search Results

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

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

  • More FP-correct way to create an update sql query

    - by James Black
    I am working on access a database using F# and my initial attempt at creating a function to create the update query is flawed. let BuildUserUpdateQuery (oldUser:UserType) (newUser:UserType) = let buf = new System.Text.StringBuilder("UPDATE users SET "); if (oldUser.FirstName.Equals(newUser.FirstName) = false) then buf.Append("SET first_name='").Append(newUser.FirstName).Append("'" ) |> ignore if (oldUser.LastName.Equals(newUser.LastName) = false) then buf.Append("SET last_name='").Append(newUser.LastName).Append("'" ) |> ignore if (oldUser.UserName.Equals(newUser.UserName) = false) then buf.Append("SET username='").Append(newUser.UserName).Append("'" ) |> ignore buf.Append(" WHERE id=").Append(newUser.Id).ToString() This doesn't properly put a , between any update parts after the first, for example: UPDATE users SET first_name='Firstname', last_name='lastname' WHERE id=... I could put in a mutable variable to keep track when the first part of the set clause is appended, but that seems wrong. I could just create an list of tuples, where each tuple is oldtext, newtext, columnname, so that I could then loop through the list and build up the query, but it seems that I should be passing in a StringBuilder to a recursive function, returning back a boolean which is then passed as a parameter to the recursive function. Does this seem to be the best approach, or is there a better one?

    Read the article

  • using switch in strings

    - by xtemer
    guys me trying to use switch in strings by first coverting string into char and then apply switch but still didnt done it....here is my code..help me out.. import javax.swing.*; import java.io.*; class HappyBirthday { public static void main(String[] args) throws IOException { String Month; char[] Months = Month.toCharArray(); BufferedReader dataIn= new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please enter your month."); Month = JOptionPane.showInputDialog("enter month"); String month1={"January","feb"}; char[] month2 = month1.toCharArray(); // String s=month1.equals(Month); //System.out.print(month2Array[0]); switch (month2) { case 0: System.out.println("kool"); break; case 1: System.out.println("not kool"); break; default: }}} /** if (month1[1].equals(Month)) System.out.println("kool"); else if(month1[0].equals(Month)) System.out.println("kooooooooooooool"); else System.out.println("Big kooooool"); **/

    Read the article

  • Is there a better way to write this LINQ query?

    - by Raj Aththanayake
    Hi Is there a better simplified way to write this query. My logic is if collection contains customer ids and countrycodes, do the query ordey by customer id ascending. If there are no contain id in CustIDs then do the order by customer name. Is there a better way to write this query? I'm not really familiar with complex lambdas. var custIdResult = (from Customer c in CustomerCollection where (c.CustomerID.ToLower().Contains(param.ToLower()) && (countryCodeFilters.Any(item => item.Equals(c.CountryCode))) ) select c).ToList(); if (custIdResult.Count > 0) { return from Customer c in custIdResult where ( c.CustomerName.ToLower().Contains(param.ToLower()) && countryCodeFilters.Any(item => item.Equals(c.CountryCode))) orderby c.CustomerID ascending select c; } else { return from Customer c in CustomerCollection where (c.CustomerName.ToLower().Contains(param.ToLower()) && countryCodeFilters.Any(item => item.Equals(c.CountryCode))) orderby c.CustomerName descending select c; }

    Read the article

  • FileNotFoundException Java

    - by Troels Hansen
    Hi, I'm trying to make a simple highscore system for a minesweeper game. However i keep getting a file not found exception, and i've tried to use the full path for the file aswell. package minesweeper; import java.io.*; import java.util.*; public class Highscore{ public static void submitHighscore(String difficulty) throws IOException{ int easy = 99999; int normal = 99999; int hard = 99999; //int newScore = (int) MinesweeperView.getTime(); int newScore = 10; File f = new File("Highscores.dat"); if (!f.exists()){ f.createNewFile(); } Scanner input = new Scanner(f); PrintStream output = new PrintStream(f); if (input.hasNextInt()){ easy = input.nextInt(); normal = input.nextInt(); hard = input.nextInt(); } output.flush(); if(difficulty.equals("easy")){ if (easy > newScore){ easy = newScore; } }else if (difficulty.equals("normal")){ if (normal > newScore){ normal = newScore; } }else if (difficulty.equals("hard")){ if (hard > newScore){ hard = newScore; } } output.println(easy); output.println(normal); output.println(hard); } //temporary main method used for debugging public static void main(String[] args) throws IOException { submitHighscore("easy"); } }

    Read the article

  • How to create an AST with ANTLR from a hierarchical key-value syntax

    - by Brabster
    I've been looking at parsing a key-value data format with ANTLR. Pretty straightforward, but the keys represent a hierarchy. A simplified example of my input syntax: /a/b/c=2 /a/b/d/e=3 /a/b/d/f=4 In my mind, this represents a tree structured as follows: (a (b (= c 2) (d (= e 3) (= f 4)))) The nearest I can get is to use the following grammar: /* Parser Rules */ start: (component NEWLINE?)* EOF -> (component)*; component: FORWARD_SLASH ALPHA_STRING component -> ^(ALPHA_STRING component) | FORWARD_SLASH ALPHA_STRING EQUALS value -> ^(EQUALS ALPHA_STRING value); value: ALPHA_STRING; /* Lexer Rules */ NEWLINE : '\r'? '\n'; ALPHA_STRING : ('a'..'z'|'A'..'Z'|'0'..'9')+; EQUALS : '='; FORWARD_SLASH : '/'; Which produces: (a (b (= c 2))) (a (b (d (= e 3)))) (a (b (d (= f 4)))) I'm not sure whether I'm asking too much from a generic tool such as ANTLR here, and this is as close I can get with this approach. That is, from here I consume the parts of the tree and create the data structure I want by hand. So - can I produce the tree structure I want directly from a grammar? If so, how? If not, why not - is it a technical limitation in ANTLR or is it something more CS-y to do with the type of language involved?

    Read the article

  • how to rotate around each record in linq and show that in view

    - by Sadegh
    Hi, I have four tables in my database and i want to join that's and return record's and show that into searchController! My query is this: public IQueryable PerformSearch(string query) { if (!string.IsNullOrEmpty(query)) { var results = from tbl1 in context.Table1 join tbl2 in context.Table2 on tbl1.Id equals tbl2.Id join tbl3 in context.Table3 on tbl2.Id equals tbl3.Id join tbl4 in context.Table4 on tbl3.Id equals tbl4.Id where tbl1.col2.Contains(query) orderby tbl1.Count descending select new { col1 = tbl1.Col1, col1 = tbl1.Col1, col1 = tbl1.Col1, . . . }; return results.AsQueryable(); } else return null; } And this method called in SearchController as below: public class SearchController : System.Web.Mvc.Controller { public System.Web.Mvc.ActionResult Search(System.String query) { var search = new Search(); ViewData["result"] = search.PerformSearch(query); return View("Search"); } } I don't know how i can rotate around each record (plus vs intellisense feature) returned by PeformSeach method and show that in view! Also is this a good way? thanks in advance

    Read the article

  • Object equality in context of hibernate / webapp

    - by bert
    How do you handle object equality for java objects managed by hibernate? In the 'hibernate in action' book they say that one should favor business keys over surrogate keys. Most of the time, i do not have a business key. Think of addresses mapped to a person. The addresses are keeped in a Set and displayed in a Wicket RefreshingView (with a ReuseIfEquals strategy). I could either use the surrogate id or use all fields in the equals() and hashCode() functions. The problem is that those fields change during the lifetime ob the object. Either because the user entered some data or the id changes due to JPA merge() being called inside the OSIV (Open Session in View) filter. My understanding of the equals() and hashCode() contract is that those should not change during the lifetime of an object. What i have tried so far: equals() based on hashCode() which uses the database id (or super.hashCode() if id is null). Problem: new addresses start with an null id but get an id when attached to a person and this person gets merged() (re-attached) in the osiv-filter. lazy compute the hashcode when hashCode() is first called and make that hashcode @Transitional. Does not work, as merge() returns a new object and the hashcode does not get copied over. What i would need is an ID that gets assigned during object creation I think. What would be my options here? I don't want to introduce some additional persistent property. Is there a way to explicitly tell JPA to assign an ID to an object? Regards

    Read the article

  • im unable to validate a login of users ,since if im entering the wrong values my datareader is not getting executed y ?

    - by Salman_Khan
    //code private void glassButton1_Click(object sender, EventArgs e) { if (textBox1.Text == "" || textBox1.Text == "" || comboBox1.SelectedIndex == 0) { Message m = new Message(); m.ShowDialog(); } else { try { con.ConnectionString = "Data source=BLACK-PEARL;Initial Catalog=LIFELINE ;User id =sa; password=143"; con.Open(); SqlCommand cmd = new SqlCommand("Select LoginID,Password,Department from Login where LoginID=@loginID and Password=@Password and Department=@Department", con); cmd.Parameters.Add(new SqlParameter("@loginID", textBox1.Text)); cmd.Parameters.Add(new SqlParameter("@Password", textBox2.Text)); cmd.Parameters.Add(new SqlParameter("@Department", comboBox1.Text)); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { string Strname = dr[0].ToString(); string StrPass = dr[1].ToString(); string StrDept = dr[2].ToString(); if(dr[2].ToString().Equals(comboBox1.Text)&&dr[0].ToString().Equals(textBox1.Text)&&dr[1].ToString().Equals(textBox2.Text)) { MessageBox.Show("Welcome"); } else { MessageBox.Show("Please Enter correct details"); } } dr.Close(); } catch (Exception ex) { MessageBox.Show("Exception" + ex); } finally { con.Close(); } } }

    Read the article

  • Best way to unit test Collection?

    - by limc
    I'm just wondering how folks unit test and assert that the "expected" collection is the same/similar as the "actual" collection (order is not important). To perform this assertion, I wrote my simple assert API:- public void assertCollection(Collection<?> expectedCollection, Collection<?> actualCollection) { assertNotNull(expectedCollection); assertNotNull(actualCollection); assertEquals(expectedCollection.size(), actualCollection.size()); assertTrue(expectedCollection.containsAll(actualCollection)); assertTrue(actualCollection.containsAll(expectedCollection)); } Well, it works. It's pretty simple if I'm asserting just bunch of Integers or Strings. It can also be pretty painful if I'm trying to assert a collection of Hibernate domains, say for example. The collection.containsAll(..) relies on the equals(..) to perform the check, but I always override the equals(..) in my Hibernate domains to check only the business keys (which is the best practice stated in the Hibernate website) and not all the fields of that domain. Sure, it makes sense to check just against the business keys, but there are times I really want to make sure all the fields are correct, not just the business keys (for example, new data entry record). So, in this case, I can't mess around with the domain.equals(..) and it almost seems like I need to implement some comparators for just unit testing purposes instead of relying on collection.containsAll(..). Are there some testing libraries I could leverage here? How do you test your collection? Thanks.

    Read the article

  • Need help extrapolating Java code

    - by Berlioz
    If anyone familiar with Rebecca Wirfs-Brock, she has a piece of Java code found in her book titled, Object Design: Roles, Responsibilities, and Collaborations. Here is the quote Applying Double Dispatch to a Specific Problem To implement the game Rock, Paper, Scissors we need to write code that determines whether one object “beats” another. The game has nine possible outcomes based on the three kinds of objects. The number of interactions is the cross product of the kinds of objects. Case or switch statements are often governed by the type of data that is being operated on. The object-oriented language equivalent is to base its actions on the class of some other object. In Java, it looks like this Here is the piece of Java code on page 16 ' import java.util.*; import java.lang.*; public class Rock { public static void main(String args[]) { } public static boolean beats(GameObject object) { if (object.getClass.getName().equals("Rock")) { result = false; } else if (object.getClass.getName().equals("Paper")) { result = false; } else if(object.getClass.getName().equals("Scissors")) { result = true; } return result; } }' ===This is not a very good solution. First, the receiver needs to know too much about the argument. Second, there is one of these nested conditional statements in each of the three classes. If new kinds of objects could be added to the game, each of the three classes would have to be modified. Can anyone share with me how to get this "less than optimal" piece of code to work in order to see it 'working'. She proceeds to demonstrate a better way, but I will spare you. Thanks

    Read the article

  • Data layer refactoring

    - by Joey
    I've taken control of some entity framework code and am looking to refactor it. Before I do, I'd like to check my thoughts are correct and I'm not missing the entity-framework way of doing things. Example 1 - Subquery vs Join Here we have a one-to-many between As and Bs. Apart from the code below being hard to read, is it also inefficient? from a in dataContext.As where ((from b in dataContext.Bs where b.Text.StartsWith(searchText) select b.AId).Distinct()).Contains(a.Id) select a Would it be better, for example, to use the join and do something like this? from a in dataContext.As where a.Bs.Any(b => b.Text.StartsWith(searchText)) select a Example 2 - Explicit Joins vs Navigation Here we have a one-to-many between As and Bs and a one-to-many between Bs and Cs. from a in dataContext.As join b in dataContext.Bs on b.AId equals a.Id join c in dataContext.Cs on c.BId equals b.Id where c.SomeValue equals searchValue select a Is there a good reason to use explicit joins rather than navigating through the data model? For example: from a in dataContext.As where a.Bs.Any(b => b.Cs.Any(c => c.SomeValue == searchValue) select a

    Read the article

  • using threads in menu options

    - by vbNewbie
    I have an app that has a console menu with 2/3 selections. One process involves uploading a file and performing a lengthy search process on its contents, whilst another process involves SQL queries and is an interactive process with the user. I wish to use threads to allow one process to run and the menu to offer the option for the second process to run. However you cannot run the first process twice. I have created threads and corrected some compilation errors but the threading options are not working correctly. Any help appreciated. main... Dim tm As Thread = New Thread(AddressOf loadFile) Dim ts As Thread = New Thread(AddressOf reports) .... While Not response.Equals("3") Try Console.Write("Enter choice: ") response = Console.ReadLine() Console.WriteLine() If response.Equals("1") Then Console.WriteLine("Thread 1 doing work") tm.SetApartmentState(ApartmentState.STA) tm.IsBackground = True tm.Start() response = String.Empty ElseIf response.Equals("2") Then Console.WriteLine("Starting a second Thread") ts.Start() response = String.Empty End If ts.Join() tm.Join() Catch ex As Exception errormessage = ex.Message End Try End While I realize that a form based will be easier to implement with perhaps just calling different forms to handle the processes.But I really dont have that option now since the console app will be added to api later. But here are my two processes from the menu functions. Also not sure what to do with the boolean variabel again as suggested below. Private Sub LoadFile() Dim dialog As New OpenFileDialog Dim response1 As String = Nothing Dim filepath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) dialog.InitialDirectory = filepath If dialog.ShowDialog() = DialogResult.OK Then fileName = dialog.FileName ElseIf DialogResult.Cancel Then Exit Sub End If Console.ResetColor() Console.Write("Begin Search -- Discovery Search, y or n? ") response1 = Console.ReadLine() If response1 = "y" Then Search() ElseIf response1 = "n" Then Console.Clear() main() End If isRunning = False End Sub and the second one Private Shared Sub report() Dim rptGen As New SearchBlogDiscovery.rptGeneration Console.WriteLine("Tread Process started") rptGen.main() Console.WriteLine("Thread Process ended") isRunning = False End Sub

    Read the article

  • How to unselect checkbox in chrome browser

    - by hudi
    in my wicket application I have 3 checkbox in form: add(new CheckBox("1").setOutputMarkupId(true)); add(new CheckBox("2").setOutputMarkupId(true)); add(new CheckBox("3").setOutputMarkupId(true)); form also contain behavior which unselect checboxes add(new AjaxEventBehavior("onclick") { private static final long serialVersionUID = 1L; @Override protected void onEvent(AjaxRequestTarget target) { List<Component> components = new ArrayList<Component>(); if (target.getLastFocusedElementId() != null) { if (target.getLastFocusedElementId().equals("1")) { components.add(get("2")); components.add(get("3")); } else if (target.getLastFocusedElementId().equals("2")) { components.add(get("1")); } else if (target.getLastFocusedElementId().equals("3")) { components.add(get("1")); } for (Component component : components) { component.setDefaultModelObject(null); target.add(component); } } } }); this works good on mozilla browser but in chrome this doesnt work. How I can improve to work this on chrome too ? UPDATE problem is in: target.getLastFocusedElementId() in mozilla this return what I want but in chrome it always return null but I dont know wh UPDATE 2 google chrome has bug in focus element: http://code.google.com/p/chromium/issues/detail?id=1383&can=1&q=window.focus%20type%3aBug&colspec=ID%20Stars%20Pri%20Area%20Type%20Status%20Summary%20Modified%20Owner so I need to do this in other way

    Read the article

  • c# How to find if two objects are equal

    - by Simon G
    Hi, I'm needing to know the best way to compare two objects and to find out if there equal. I'm overriding both GethashCode and Equals. So a basic class looks like: public class Test { public int Value { get; set; } public string String1 { get; set; } public string String2 { get; set; } public override int GetHashCode() { return Value ^ String1.GetHashCode() ^ String2.GetHashCode(); } public override bool Equals( object obj ) { return GetHashCode() == obj.GetHashCode(); } } So for testing purposes I created two objects: Test t = new Test() { Value = 1, String1 ="One", String2 = "One" }; Test t2 = new Test() { Value = 1, String1 = "Two", String2 = "Two" }; bool areEqual = t.Equals( t2 ); In testing this areEqual returns true event though both objects are different. I realise this is because String1 and String2 are the same value in each object and thus cancels each other out when hashing. Is there a better way off hashing object that the method I have that will resolve my issue?

    Read the article

  • Works on emulator but not on device

    - by Klaus
    Hello Community, I have an inner handler class that calls the method sendMessage. sendMessige is outside the handler class, but inside the conatining Android java class. On the emulator (AVD 2.2) it works fine, but on my Android 2.2 device the method sendMessage is not called at all. Inner handler class: private Handler handler2 = new Handler() { public void handleMessage(Message msg) { if (GeoSetting.equals("s") && (inNumber.equals(definedNumber))) **SendService.this.sendMessage(definedNumber, DisplayLoc)**; if (GeoSetting.equals("a")) **SendService.this.sendMessage(inNumber, DisplayLoc)**; stopService(new Intent(getApplicationContext(), GeoService.class)); }; The method that should be called: private void sendMessage(String sendNumber, String sendText){ Toast.makeText(getApplicationContext(), "done!!!", Toast.LENGTH_LONG).show(); SmsManager sms = SmsManager.getDefault(); try { sms.sendTextMessage(sendNumber, null, sendText, null, null); if (Message == true) {Toast.makeText(getApplicationContext(), "Sending SMS to "+sendNumber+": "+sendText, Toast.LENGTH_LONG).show();} } catch (Exception exeption){ Toast.makeText(getApplicationContext(), "Something is wrong, could not send SMS!", Toast.LENGTH_LONG).show(); } Toast.makeText(getApplicationContext(), "method called!", Toast.LENGTH_LONG).show(); } Does anybody have an idea why sendMessage is not called on the real device? Thank you for the help!

    Read the article

  • Linq to Entities Joins

    - by Bob Avallone
    I have a question about joins when using Linq to Entities. According to the documentation the use on the join without a qualifier performs like a left outer join. However when I execute the code below, I get a count returned of zero. But if I comment out the three join lines I get a count of 1. That would indicate that the join are acting as inner join. I have two questions. One which is right inner or outer as the default? Second how do I do the other one i.e. inner or outer? The key words on inner and outer do not work. var nprs = (from n in db.FMCSA_NPR join u in db.FMCSA_USER on n.CREATED_BY equals u.ID join t in db.LKUP_NPR_TYPE on n.NPR_TYPE_ID equals t.ID join s in db.LKUP_AUDIT_STATUS on n.NPR_STATUS_ID equals s.ID where n.ROLE_ID == pRoleId && n.OWNER_ID == pOwnerId && n.NPR_STATUS_ID == pNPRStatusId && n.ACTIVE == pActive select n).ToList(); if (nprs.Count() == 0) return null;

    Read the article

  • Using NHibernate's HQL to make a query with multiple inner joins

    - by Abu Dhabi
    The problem here consists of translating a statement written in LINQ to SQL syntax into the equivalent for NHibernate. The LINQ to SQL code looks like so: var whatevervar = from threads in context.THREADs join threadposts in context.THREADPOSTs on threads.thread_id equals threadposts.thread_id join posts1 in context.POSTs on threadposts.post_id equals posts1.post_id join users in context.USERs on posts1.user_id equals users.user_id orderby posts1.post_time where threads.thread_id == int.Parse(id) select new { threads.thread_topic, posts1.post_time, users.user_display_name, users.user_signature, users.user_avatar, posts1.post_body, posts1.post_topic }; It's essentially trying to grab a list of posts within a given forum thread. The best I've been able to come up with (with the help of the helpful users of this site) for NHibernate is: var whatevervar = session.CreateQuery("select t.Thread_topic, p.Post_time, " + "u.User_display_name, u.User_signature, " + "u.User_avatar, p.Post_body, p.Post_topic " + "from THREADPOST tp " + "inner join tp.Thread_ as t " + "inner join tp.Post_ as p " + "inner join p.User_ as u " + "where tp.Thread_ = :what") .SetParameter<THREAD>("what", threadid) .SetResultTransformer(Transformers.AliasToBean(typeof(MyDTO))) .List<MyDTO>(); But that doesn't parse well, complaining that the aliases for the joined tables are null references. MyDTO is a custom type for the output: public class MyDTO { public string thread_topic { get; set; } public DateTime post_time { get; set; } public string user_display_name { get; set; } public string user_signature { get; set; } public string user_avatar { get; set; } public string post_topic { get; set; } public string post_body { get; set; } } I'm out of ideas, and while doing this by direct SQL query is possible, I'd like to do it properly, without defeating the purpose of using an ORM. Thanks in advance! EDIT: The database looks like this: http://i41.tinypic.com/5agciu.jpg (Can't post images yet.)

    Read the article

  • Please help!! Is there a better way to write this LINQ query

    - by Raj Aththanayake
    Hi Is there a better simplified way to write this query. My logic is if collection contains customer ids and countrycodes, do the query ordey by customer id ascending. If there are no contain id in CustIDs then do the order by customer name. Is there a better way to write this query? I'm not really familiar with complex lambdas. var custIdResult = (from Customer c in CustomerCollection where (c.CustomerID.ToLower().Contains(param.ToLower()) && (countryCodeFilters.Any(item => item.Equals(c.CountryCode))) ) select c).ToList(); if (custIdResult.Count > 0) { return from Customer c in custIdResult ( c.CustomerName.ToLower().Contains(param.ToLower()) && countryCodeFilters.Any(item => item.Equals(c.CountryCode)) ) orderby c.CustomerID ascending select c; } else { return from Customer c in CustomerCollection where ( c.CustomerName.ToLower().Contains(param.ToLower()) && countryCodeFilters.Any(item => item.Equals(c.CountryCode)) ) orderby c.CustomerName descending select c; }

    Read the article

  • Counting substring, while loop

    - by user1554786
    public class SubstringCount { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a word longer than 4 characters, and press q to quit"); int count = 0; while (scan.hasNextLine()) { System.out.println("Enter a word longer than 4 characters, and press q to quit"); String word = scan.next(); if (word.substring(0,4).equals("Stir")) { count++; System.out.println("Enter a word longer than 4 characters, and press q to quit"); scan.next(); } else if (word.equals("q")) { System.out.println("You have " + count + ("words with 'Stir' in them")); } else if (!word.substring(0,4).equals("Stir")) { System.out.println("Enter a word longer than 4 characters, and press q to quit"); scan.next(); } } } } Here I need to print how many words entered by the user contain the substring 'Stir.' However I'm not sure how to get this to work, or if I've done any of it right in the first place! Thanks for any help!

    Read the article

  • java threads don't see shared boolean changes

    - by andymur
    Here the code class Aux implements Runnable { private Boolean isOn = false; private String statusMessage; private final Object lock; public Aux(String message, Object lock) { this.lock = lock; this.statusMessage = message; } @Override public void run() { for (;;) { synchronized (lock) { if (isOn && "left".equals(this.statusMessage)) { isOn = false; System.out.println(statusMessage); } else if (!isOn && "right".equals(this.statusMessage)) { isOn = true; System.out.println(statusMessage); } if ("left".equals(this.statusMessage)) { System.out.println("left " + isOn); } } } } } public class Question { public static void main(String [] args) { Object lock = new Object(); new Thread(new Aux("left", lock)).start(); new Thread(new Aux("right", lock)).start(); } } In this code I expect to see: left, right, left right and so on, but when Thread with "left" message changes isOn to false, Thread with "right" message don't see it and I get ("right true" and "left false" console messages), left thread don't get isOn in true, but right Thread can't change it cause it always see old isOn value (true). When i add volatile modifier to isOn nothing changes, but if I change isOn to some class with boolean field and change this field then threads are see changes and it works fine Thanks in advance.

    Read the article

  • overload == (and != , of course) operator, can I bypass == to determine whether the object is null

    - by LLS
    Hello, when I try to overload operator == and != in C#, and override Equal as recommended, I found I have no way to distinguish a normal object and null. For example, I defined a class Complex. public static bool operator ==(Complex lhs, Complex rhs) { return lhs.Equals(rhs); } public static bool operator !=(Complex lhs, Complex rhs) { return !lhs.Equals(rhs); } public override bool Equals(object obj) { if (obj is Complex) { return (((Complex)obj).Real == this.Real && ((Complex)obj).Imaginary == this.Imaginary); } else { return false; } } But when I want to use if (temp == null) When temp is really null, some exception happens. And I can't use == to determine whether the lhs is null, which will cause infinite loop. What should I do in this situation. One way I can think of is to us some thing like Class.Equal(object, object) (if it exists) to bypass the == when I do the check. What is the normal way to solve the problem?

    Read the article

  • sql to linq translated code

    - by ognjenb
    SQL: SELECT o.Id, o.OrderNumber, o.Date, d.Name AS 'Distributor', d.Notes AS 'DistrNotes', -- distributer c.Name AS 'Custoer', c.Notes AS 'CustmNotes', -- customer t.Name AS 'Transporter', -- transporter o.InvoiceFile, o.Notes, o.AwbFile, o.TrackingFile, o.Status, o.DeliveryNotification, o.ServiceType, o.ValidityDate, o.DeliveryTime, o.Weight, o.CustomerId, o.CustomerOrderNumber, o.CustomerDate, o.Shipment, o.Payment, o.TransporterId, o.TotalPrice, o.Discount, o.AlreadyPaid, o.Delivered, o.Received, o.OrderEnteredBy, CONCAT(e.Name, ' ', e.Surname) AS 'IBEKO Engineer', o.Confirmed FROM `order` o LEFT JOIN person d ON o.`DistributorId` = d.`Id` LEFT JOIN person c ON o.`CustomerId` = c.Id LEFT JOIN Transporter t ON o.`TransporterId` = t.Id LEFT JOIN IbekoEngineer e ON o.OrderEnteredBy = e.Id LINQ: testEntities6 ordersEntities = new testEntities6(); var orders_query = (from o in ordersEntities.order join pd in ordersEntities.person on o.DistributorId equals pd.Id join pc in ordersEntities.person on o.CustomerId equals pc.Id join t in ordersEntities.transporter on o.TransporterId equals t.Id select new OrdersModel { Id = o.Id, OrderNumber = o.OrderNumber, Date = o.Date, Distributor_Name = pdk.Name, Distributor_Notes = pdk.Notes, Customer_Name = pc.Name, Customer_Notes = pc.Notes, Transporter_Name = t.Name, InvoiceFile = o.InvoiceFile, Notes = o.Notes, AwbFile = o.AwbFile, TrackingFile = o.TrackingFile, Status = o.Status, DeliveryNotification = o.DeliveryNotification, ServiceType = o.ServiceType, ValidityDate = o.ValidityDate, DeliveryTime = o.DeliveryTime, Weight = o.Weight, CustomerId = o.CustomerId, CustomerOrderNumber = o.CustomerOrderNumber, CustomerDate = o.CustomerDate, Shipment = o.Shipment, Payment = o.Payment, TransporterId = o.TransporterId, TotalPrice = o.TotalPrice, Discount = o.Discount, AlreadyPaid = o.AlreadyPaid, Delivered = o.Delivered, Received = o.Received, OrderEnteredBy = o.OrderEnteredBy, Confirmed = o.Confirmed }); I translated the above SQL code into linq. SQL code return data from database but LINQ not return data. Why?

    Read the article

  • Two-state script monitor not auto-resolving in SCOM

    - by DeliriumTremens
    This script runs, and if it returns 'erro' an alert is generated in SCOM. The alert is set to resolve when the monitor returns to healthy state. I have tested the script with cscript and it returns the correct values in each state. I'm baffled as to why it generates an alert on 'erro' but will not auto-resolve on 'ok': Option Explicit On Error Resume Next Dim objFSO Dim TargetFile Dim objFile Dim oAPI, oBag Dim StateDataType Dim FileSize Set oAPI = CreateObject("MOM.ScriptAPI") Set oBag = oAPI.CreatePropertyBag() TargetFile = "\\server\share\file.zip" Set objFSO = CreateObject("scripting.filesystemobject") Set objFile = objFSO.GetFile(TargetFile) FileSize = objFile.Size / 1024 If FileSize < 140000 Then Call oBag.AddValue("State", "erro") Else Call oBag.AddValue("State", "ok") End If Call oAPI.AddItem(oBag) Call oAPI.Return(oBag) Unhealthy expression: Property[@Name='State'] Equals erro Health expression: Property[@Name='State'] Equals ok If anyone can shed some light onto what I might be missing, that would be great!

    Read the article

  • Android 1.5 - 2.1 Search Activity affects Parent Lifecycle

    - by pacoder
    Behavior seems consistent in Android 1.5 to 2.1 Short version is this, it appears that when my (android search facility) search activity is fired from the android QSR due to either a suggestion or search, UNLESS my search activity in turn fires off a VISIBLE activity that is not the parent of the search, the search parents life cycle changes. It will NOT fire onDestroy until I launch a visible activity from it. If I do, onDestroy will fire fine. I need a way to get around this behavior... The long version: We have implemented a SearchSuggestion provider and a Search activity in our application. The one thing about it that is very odd is that if the SearchManager passes control to our custom Search activity, AND that activity does not create a visible Activity the Activity which parented the search does not destroy (onDestroy doesn't run) and it will not until we call a visible Activity from the parent activity. As long as our Search Activity fires off another Activity that gets focus the parent activity will fire onDestroy when I back out of it. The trick is that Activity must have a visual component. I tried to fake it out with a 'pass through' Activity so that my Search Activity could fire off another Intent and bail out but that didn't work either. I have tried setting our SearchActivity to launch singleTop and I also tried setting its noHistory attribute to true, tried setResult(RESULT_OK) in SearchACtivity prior to finish, bunch of other things, nothing is working. This is the chunk of code in our Search Activity onCreate. Couple of notes about it: If Intent is Action_Search (user typed in their own search and didn't pick a suggestion), we display a list of results as our Search Activity is a ListActivity. In this case when the item is picked, the Search Activity closes and our parent Activity does fire onDestroy() when we back out. If Intent is Action_View (user picked a suggestion) when type is "action" we fire off an Intent that creates a new visible Activity. In this case same thing, when we leave that new activity and return to the parent activity, the back key does cause the parent activity to fire onDestroy when leaving. If Intent is Action_View (user picked a suggestion) when type is "pitem" is where the problem lies. It works fine (the method call focuses an item on the parent activity), but when the back button is hit on the parent activity onDestroy is NOT called. IF after this executes I pick an option in the parent activity that fires off another activity and return to the parent then back out it will fire onDestroy() in the parent activity. Note that the "action" intent ends up running the exact same method call as "pitem", it just bring up a new visual Activity first. Also I can take out the method call from "pitem" and just finish() and the behavior is the same, the parent activity doesn't fire onDestroy() when backed out of. if (Intent.ACTION_SEARCH.equals(queryAction)) { this.setContentView(_layoutId); String searchKeywords = queryIntent.getStringExtra(SearchManager.QUERY); init(searchKeywords); } else if(Intent.ACTION_VIEW.equals(queryAction)){ Bundle bundle = queryIntent.getExtras(); String key = queryIntent.getDataString(); String userQuery = bundle.getString(SearchManager.USER_QUERY); String[] keyValues = key.split("-"); if(keyValues.length == 2) { String type = keyValues[0]; String value = keyValues[1]; if(type.equals("action")) { Intent intent = new Intent(this, EventInfoActivity.class); Long longKey = Long.parseLong(value); intent.putExtra("vo_id", longKey); startActivity(intent); finish(); } else if(type.equals("pitem")) { Integer id = Integer.parseInt(value); _application._servicesManager._mapHandlerSelector.selectInfoItem(id); finish(); } } } It just seems like something is being held onto and I can't figure out what it is, in all cases the Search Activity fires onDestroy() when finish() is called so it is definitely going away. If anyone has any suggestions I'd be most appreciative. Thanks, Sean Overby

    Read the article

  • Silverlight 3.0 Custom Cursor in Chart

    - by Wonko the Sane
    Hello All, I'm probably overlooking something that will be obvious when I see the solution, but for now... I am attempting to use a custom cursor inside the chart area of a Toolkit chart. I have created a ControlTemplate for the chart, and a grid to contain the cursors. I show/hide the cursors, and attempt to move the containing Grid, using various Mouse events. The cursor is being displayed at the correct times, but I cannot get it to move to the correct position. Here is the ControlTemplate (the funky colors are just attempts to confirm what the different pieces of the template pertain to): <dataVisTK:Title Content="{TemplateBinding Title}" Style="{TemplateBinding TitleStyle}"/> <Grid Grid.Row="1"> <!-- Remove the Legend --> <!--<dataVisTK:Legend x:Name="Legend" Title="{TemplateBinding LegendTitle}" Style="{TemplateBinding LegendStyle}" Grid.Column="1"/>--> <chartingPrimitivesTK:EdgePanel x:Name="ChartArea" Background="#EDAEAE" Style="{TemplateBinding ChartAreaStyle}" Grid.Column="0"> <Grid Canvas.ZIndex="-1" Background="#2008AE" Style="{TemplateBinding PlotAreaStyle}"> </Grid> <Border Canvas.ZIndex="1" BorderBrush="#FF250010" BorderThickness="3" /> <Grid x:Name="gridHandCursors" Canvas.ZIndex="5" Width="32" Height="32" Visibility="Collapsed"> <Image x:Name="cursorGrab" Width="32" Source="Resources/grab.png" /> <Image x:Name="cursorGrabbing" Width="32" Source="Resources/grabbing.png" Visibility="Collapsed"/> </Grid> </chartingPrimitivesTK:EdgePanel> </Grid> </Grid> </Border> and here are the mouse events (in particular, the MouseMove): void TimelineChart_Loaded(object sender, RoutedEventArgs e) { chartTimeline.UpdateLayout(); List<FrameworkElement> chartChildren = GetLogicalChildrenBreadthFirst(chartTimeline).ToList(); mChartArea = chartChildren.Where(element => element.Name.Equals("ChartArea")).FirstOrDefault() as Panel; if (mChartArea != null) { grabCursor = chartChildren.Where(element => element.Name.Equals("cursorGrab")).FirstOrDefault() as Image; grabbingCursor = chartChildren.Where(element => element.Name.Equals("cursorGrabbing")).FirstOrDefault() as Image; mGridHandCursors = chartChildren.Where(element => element.Name.Equals("gridHandCursors")).FirstOrDefault() as Grid; mChartArea.Cursor = Cursors.None; mChartArea.MouseMove += new MouseEventHandler(mChartArea_MouseMove); mChartArea.MouseLeftButtonDown += new MouseButtonEventHandler(mChartArea_MouseLeftButtonDown); mChartArea.MouseLeftButtonUp += new MouseButtonEventHandler(mChartArea_MouseLeftButtonUp); if (mGridHandCursors != null) { mChartArea.MouseEnter += (s, e2) => mGridHandCursors.Visibility = Visibility.Visible; mChartArea.MouseLeave += (s, e2) => mGridHandCursors.Visibility = Visibility.Collapsed; } } } void mChartArea_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (grabCursor != null) grabCursor.Visibility = Visibility.Visible; if (grabbingCursor != null) grabbingCursor.Visibility = Visibility.Collapsed; } void mChartArea_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (grabCursor != null) grabCursor.Visibility = Visibility.Collapsed; if (grabbingCursor != null) grabbingCursor.Visibility = Visibility.Visible; } void mChartArea_MouseMove(object sender, MouseEventArgs e) { if (mGridHandCursors != null) { Point pt = e.GetPosition(null); mGridHandCursors.SetValue(Canvas.LeftProperty, pt.X); mGridHandCursors.SetValue(Canvas.TopProperty, pt.Y); } } Any help past this roadblock would be greatly appreciated! Thanks, wTs

    Read the article

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