Search Results

Search found 990 results on 40 pages for 'readline'.

Page 4/40 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • saxon java xpath exception :

    - by changed
    Hi I am trying to read XPath queries from a file and run it against a xml data file. I am doing it through Saxon Xpath processor. But i keep getting this error. Code i am using is from sample code provided with the library. Error i am getting is : Exception in thread "main" javax.xml.xpath.XPathExpressionException: Supplied node must be built using the same or a compatible Configuration at net.sf.saxon.xpath.XPathExpressionImpl.evaluate(XPathExpressionImpl.java:283) at net.sf.saxon.xpath.XPathExpressionImpl.evaluate(XPathExpressionImpl.java:375) at edu.xml.XPathExample.go(XPathExample.java:81) at edu.xml.XPathExample.main(XPathExample.java:42) - public void go(String filename) throws Exception { XPathExpression findLine = null; String readLine = null; Object document = new XPathEvaluator().setSource(new StreamSource(new File(dataPath))); System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON, "net.sf.saxon.xpath.XPathFactoryImpl"); XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON); XPath xpe = xpf.newXPath(); if (filename != null) { this.queryPath = filename; } try { fileReader = new BufferedReader(new FileReader(queryPath)); } catch (FileNotFoundException ex) { System.out.println("File not found: " + ex.getMessage()); } xpe.setXPathVariableResolver(this); while (true) { try { readLine = fileReader.readLine(); } catch (IOException ex) { System.out.println("Error while reading file: " + ex.getMessage()); } if (readLine == null) { break; } findLine = xpe.compile(readLine); String resultString = findLine.evaluate(document); System.out.println("<output>"); System.out.println("String Value => " + resultString); System.out.println("</output>"); } }

    Read the article

  • C# Windows Service

    - by Goober
    Scenario I've created a windows service, but whenever I start it, it stops immediately. The service was concieved from a console application that used to subscribe to an event and watch processes on a server. If anything happened to process (i.e. It was killed), then the event would trigger the process to be restarted. The reason I'm telling you this is because the original code used to look like this: Original Console App Code: static void Main(string[] args) { StartProcess sp = new StartProcess(); //Note the readline that means the application sits here waiting for an event! Console.ReadLine(); } Now that this code has been turned into a Windows Service, it is essentially EXACTLY THE SAME. However, the service does not sit there waiting, even with the readline, it just ends..... New Windows Service Code: protected override void OnStart(string[] args) { ProcessMonitor pm = new ProcessMonitor(); Console.ReadLine(); } Thoughts Since the functionality is entirely encapsulated within this single class (It quite literally starts, sets up some events and waits) - How can I get the service to actually sit there and just wait? It seems to be ignoring the readline. However this works perfectly as a console application, it is just far more convenient to have it as a service.

    Read the article

  • graphviz segmentation fault

    - by LucaB
    Hi I'm building a graph with many nodes, around 3000. I wrote a simple python program to do the trick with graphviz, but it gives me segmentation fault and I don't know why, if the graph is too big or if i'm missing something. The code is: #!/usr/bin/env python # Import graphviz import sys sys.path.append('..') sys.path.append('/usr/lib/graphviz') import gv # Import pygraph from pygraph.classes.graph import graph from pygraph.classes.digraph import digraph from pygraph.algorithms.searching import breadth_first_search from pygraph.readwrite.dot import write # Graph creation gr = graph() file = open('nodes.dat', 'r') line = file.readline() while line: gr.add_nodes([line[0:-1]]) line = file.readline() file.close() print 'nodes finished, beginning edges' edges = open('edges_ok.dat', 'r') edge = edges.readline() while edge: gr.add_edge((edge.split()[0], edge.split()[1])) edge = edges.readline() edges.close() print 'edges finished' print 'Drawing' # Draw as PNG dot = write(gr) gvv = gv.readstring(dot) gv.layout(gvv,'dot') gv.render(gvv,'svg','graph.svg') and it crashes at the gv.layout() call. The files are somthing like: nodes: node1 node2 node3 edges_ok: node1 node2 node2 node3

    Read the article

  • Not receiving all message via TCP in Java?

    - by javatcp
    I have a tcp socket sending three lines like this out2.println("message1\n"); out2.println("message2\n"); out2.println("message3\n"); and another tco socket receiving and displaying these messages like this System.out.println(in.readLine()); System.out.println(in.readLine()); System.out.println(in.readLine()); but only the first message is recieved and displayed, anything I send after that is not.

    Read the article

  • Problem in arranging contents of Class in JAVA

    - by LuckySlevin
    Hi, I have some classes and I'm trying to fill the objects of this class. Here is what i've tried. (Question is at the below) public class Team { private String clubName; private String preName; private ArrayList<String> branches; public Team(String clubName, String preName) { this.clubName = clubName; this.preName = preName; branches = new ArrayList<String>(); } public Team() { // TODO Auto-generated constructor stub } public String getClubName() { return clubName; } public String getPreName() { return preName; } public ArrayList<String> getBranches() { return branches; } public void setClubName(String clubName) { this.clubName = clubName; } public void setPreName(String preName) { this.preName = preName; } public void setBranches(ArrayList<String> branches) { this.branches = branches; } } public class Branch { private ArrayList<Player> players = new ArrayList<Player>(); String brName; public Branch() {} public void setBr(String brName){this.brName = brName;} public String getBr(){return brName;} public ArrayList<Player> getPlayers() { return players; } public void setPlayers(ArrayList<Player> players) { this.players = players; } } //TEST CLASS public class test { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { String a,b,c; String q = "q"; int brCount = 0, tCount = 0; BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); Team[] teams = new Team[30]; Branch[] myBranch = new Branch[30]; for(int z = 0 ; z <30 ;z++) { teams[z] = new Team(); myBranch[z] = new Branch(); } ArrayList<String> tmp = new ArrayList<String>(); int k = 0; int secim = Integer.parseInt(input.readLine()); while(secim != 0) { if(k!=0) secim = Integer.parseInt(input.readLine()); k++; switch(secim) { case 1 : brCount = 0; a = input.readLine(); teams[tCount].setClubName(a); b= input.readLine(); teams[tCount].setPreName(b); c = input.readLine(); while(c.equals(q) == false) { if(brCount != 0) {c = input.readLine();} if(c.equals(q)== false){ myBranch[brCount].brName = c; tmp.add(myBranch[brCount].brName); brCount++; } System.out.println(brCount); } teams[tCount].setBranches(tmp); for(int i=0;i<=tCount;i++ ){ System.out.print("a :" + teams[i].getClubName()+ " " + teams[i].getPreName()+ " "); System.out.println(teams[i].getBranches());} tCount++; break; case 2: String src = input.readLine();//LATERRRRRRRr } } } } The problem is one of my class elements. I have an arraylist as an element of a class. When i enter: AAA as preName BBB as clubName c d e as Branches Then as a second element www as preName GGG as clubName a b as branches The result is coming like: AAA BBB c,d,e,a,b GGG www c,d,e,a,b Which means ArrayList part of the class is putting it on and on. I tried to use clear() method but caused problems. Any ideas.

    Read the article

  • Regex vs. string:find() for simple word boundary

    - by user576267
    Say I only need to find out whether a line read from a file contains a word from a finite set of words. One way of doing this is to use a regex like this: .*\y(good|better|best)\y.* Another way of accomplishing this is using a pseudo code like this: if ( (readLine.find("good") != string::npos) || (readLine.find("better") != string::npos) || (readLine.find("best") != string::npos) ) { // line contains a word from a finite set of words. } Which way will have better performance? (i.e. speed and CPU utilization)

    Read the article

  • How LINQ to Object statements work

    - by rajbk
    This post goes into detail as to now LINQ statements work when querying a collection of objects. This topic assumes you have an understanding of how generics, delegates, implicitly typed variables, lambda expressions, object/collection initializers, extension methods and the yield statement work. I would also recommend you read my previous two posts: Using Delegates in C# Part 1 Using Delegates in C# Part 2 We will start by writing some methods to filter a collection of data. Assume we have an Employee class like so: 1: public class Employee { 2: public int ID { get; set;} 3: public string FirstName { get; set;} 4: public string LastName {get; set;} 5: public string Country { get; set; } 6: } and a collection of employees like so: 1: var employees = new List<Employee> { 2: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 3: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 4: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 5: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }, 6: }; Filtering We wish to  find all employees that have an even ID. We could start off by writing a method that takes in a list of employees and returns a filtered list of employees with an even ID. 1: static List<Employee> GetEmployeesWithEvenID(List<Employee> employees) { 2: var filteredEmployees = new List<Employee>(); 3: foreach (Employee emp in employees) { 4: if (emp.ID % 2 == 0) { 5: filteredEmployees.Add(emp); 6: } 7: } 8: return filteredEmployees; 9: } The method can be rewritten to return an IEnumerable<Employee> using the yield return keyword. 1: static IEnumerable<Employee> GetEmployeesWithEvenID(IEnumerable<Employee> employees) { 2: foreach (Employee emp in employees) { 3: if (emp.ID % 2 == 0) { 4: yield return emp; 5: } 6: } 7: } We put these together in a console application. 1: using System; 2: using System.Collections.Generic; 3: //No System.Linq 4:  5: public class Program 6: { 7: [STAThread] 8: static void Main(string[] args) 9: { 10: var employees = new List<Employee> { 11: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 12: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 13: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 14: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }, 15: }; 16: var filteredEmployees = GetEmployeesWithEvenID(employees); 17:  18: foreach (Employee emp in filteredEmployees) { 19: Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 20: emp.ID, emp.FirstName, emp.LastName, emp.Country); 21: } 22:  23: Console.ReadLine(); 24: } 25: 26: static IEnumerable<Employee> GetEmployeesWithEvenID(IEnumerable<Employee> employees) { 27: foreach (Employee emp in employees) { 28: if (emp.ID % 2 == 0) { 29: yield return emp; 30: } 31: } 32: } 33: } 34:  35: public class Employee { 36: public int ID { get; set;} 37: public string FirstName { get; set;} 38: public string LastName {get; set;} 39: public string Country { get; set; } 40: } Output: ID 2 First_Name Jim Last_Name Ashlock Country UK ID 4 First_Name Jill Last_Name Anderson Country AUS Our filtering method is too specific. Let us change it so that it is capable of doing different types of filtering and lets give our method the name Where ;-) We will add another parameter to our Where method. This additional parameter will be a delegate with the following declaration. public delegate bool Filter(Employee emp); The idea is that the delegate parameter in our Where method will point to a method that contains the logic to do our filtering thereby freeing our Where method from any dependency. The method is shown below: 1: static IEnumerable<Employee> Where(IEnumerable<Employee> employees, Filter filter) { 2: foreach (Employee emp in employees) { 3: if (filter(emp)) { 4: yield return emp; 5: } 6: } 7: } Making the change to our app, we create a new instance of the Filter delegate on line 14 with a target set to the method EmployeeHasEvenId. Running the code will produce the same output. 1: public delegate bool Filter(Employee emp); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: var employees = new List<Employee> { 9: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 10: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 11: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 12: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 13: }; 14: var filterDelegate = new Filter(EmployeeHasEvenId); 15: var filteredEmployees = Where(employees, filterDelegate); 16:  17: foreach (Employee emp in filteredEmployees) { 18: Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 19: emp.ID, emp.FirstName, emp.LastName, emp.Country); 20: } 21: Console.ReadLine(); 22: } 23: 24: static bool EmployeeHasEvenId(Employee emp) { 25: return emp.ID % 2 == 0; 26: } 27: 28: static IEnumerable<Employee> Where(IEnumerable<Employee> employees, Filter filter) { 29: foreach (Employee emp in employees) { 30: if (filter(emp)) { 31: yield return emp; 32: } 33: } 34: } 35: } 36:  37: public class Employee { 38: public int ID { get; set;} 39: public string FirstName { get; set;} 40: public string LastName {get; set;} 41: public string Country { get; set; } 42: } Lets use lambda expressions to inline the contents of the EmployeeHasEvenId method in place of the method. The next code snippet shows this change (see line 15).  For brevity, the Employee class declaration has been skipped. 1: public delegate bool Filter(Employee emp); 2:  3: public class Program 4: { 5: [STAThread] 6: static void Main(string[] args) 7: { 8: var employees = new List<Employee> { 9: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 10: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 11: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 12: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 13: }; 14: var filterDelegate = new Filter(EmployeeHasEvenId); 15: var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0); 16:  17: foreach (Employee emp in filteredEmployees) { 18: Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 19: emp.ID, emp.FirstName, emp.LastName, emp.Country); 20: } 21: Console.ReadLine(); 22: } 23: 24: static bool EmployeeHasEvenId(Employee emp) { 25: return emp.ID % 2 == 0; 26: } 27: 28: static IEnumerable<Employee> Where(IEnumerable<Employee> employees, Filter filter) { 29: foreach (Employee emp in employees) { 30: if (filter(emp)) { 31: yield return emp; 32: } 33: } 34: } 35: } 36:  The output displays the same two employees.  Our Where method is too restricted since it works with a collection of Employees only. Lets change it so that it works with any IEnumerable<T>. In addition, you may recall from my previous post,  that .NET 3.5 comes with a lot of predefined delegates including public delegate TResult Func<T, TResult>(T arg); We will get rid of our Filter delegate and use the one above instead. We apply these two changes to our code. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: var employees = new List<Employee> { 7: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 8: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 9: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 10: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 11: }; 12:  13: var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0); 14:  15: foreach (Employee emp in filteredEmployees) { 16: Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 17: emp.ID, emp.FirstName, emp.LastName, emp.Country); 18: } 19: Console.ReadLine(); 20: } 21: 22: static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> filter) { 23: foreach (var x in source) { 24: if (filter(x)) { 25: yield return x; 26: } 27: } 28: } 29: } We have successfully implemented a way to filter any IEnumerable<T> based on a  filter criteria. Projection Now lets enumerate on the items in the IEnumerable<Employee> we got from the Where method and copy them into a new IEnumerable<EmployeeFormatted>. The EmployeeFormatted class will only have a FullName and ID property. 1: public class EmployeeFormatted { 2: public int ID { get; set; } 3: public string FullName {get; set;} 4: } We could “project” our existing IEnumerable<Employee> into a new collection of IEnumerable<EmployeeFormatted> with the help of a new method. We will call this method Select ;-) 1: static IEnumerable<EmployeeFormatted> Select(IEnumerable<Employee> employees) { 2: foreach (var emp in employees) { 3: yield return new EmployeeFormatted { 4: ID = emp.ID, 5: FullName = emp.LastName + ", " + emp.FirstName 6: }; 7: } 8: } The changes are applied to our app. 1: public class Program 2: { 3: [STAThread] 4: static void Main(string[] args) 5: { 6: var employees = new List<Employee> { 7: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 8: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 9: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 10: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 11: }; 12:  13: var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0); 14: var formattedEmployees = Select(filteredEmployees); 15:  16: foreach (EmployeeFormatted emp in formattedEmployees) { 17: Console.WriteLine("ID {0} Full_Name {1}", 18: emp.ID, emp.FullName); 19: } 20: Console.ReadLine(); 21: } 22:  23: static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> filter) { 24: foreach (var x in source) { 25: if (filter(x)) { 26: yield return x; 27: } 28: } 29: } 30: 31: static IEnumerable<EmployeeFormatted> Select(IEnumerable<Employee> employees) { 32: foreach (var emp in employees) { 33: yield return new EmployeeFormatted { 34: ID = emp.ID, 35: FullName = emp.LastName + ", " + emp.FirstName 36: }; 37: } 38: } 39: } 40:  41: public class Employee { 42: public int ID { get; set;} 43: public string FirstName { get; set;} 44: public string LastName {get; set;} 45: public string Country { get; set; } 46: } 47:  48: public class EmployeeFormatted { 49: public int ID { get; set; } 50: public string FullName {get; set;} 51: } Output: ID 2 Full_Name Ashlock, Jim ID 4 Full_Name Anderson, Jill We have successfully selected employees who have an even ID and then shaped our data with the help of the Select method so that the final result is an IEnumerable<EmployeeFormatted>.  Lets make our Select method more generic so that the user is given the freedom to shape what the output would look like. We can do this, like before, with lambda expressions. Our Select method is changed to accept a delegate as shown below. TSource will be the type of data that comes in and TResult will be the type the user chooses (shape of data) as returned from the selector delegate. 1:  2: static IEnumerable<TResult> Select<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, TResult> selector) { 3: foreach (var x in source) { 4: yield return selector(x); 5: } 6: } We see the new changes to our app. On line 15, we use lambda expression to specify the shape of the data. In this case the shape will be of type EmployeeFormatted. 1:  2: public class Program 3: { 4: [STAThread] 5: static void Main(string[] args) 6: { 7: var employees = new List<Employee> { 8: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 9: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 10: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 11: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 12: }; 13:  14: var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0); 15: var formattedEmployees = Select(filteredEmployees, (emp) => 16: new EmployeeFormatted { 17: ID = emp.ID, 18: FullName = emp.LastName + ", " + emp.FirstName 19: }); 20:  21: foreach (EmployeeFormatted emp in formattedEmployees) { 22: Console.WriteLine("ID {0} Full_Name {1}", 23: emp.ID, emp.FullName); 24: } 25: Console.ReadLine(); 26: } 27: 28: static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> filter) { 29: foreach (var x in source) { 30: if (filter(x)) { 31: yield return x; 32: } 33: } 34: } 35: 36: static IEnumerable<TResult> Select<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, TResult> selector) { 37: foreach (var x in source) { 38: yield return selector(x); 39: } 40: } 41: } The code outputs the same result as before. On line 14 we filter our data and on line 15 we project our data. What if we wanted to be more expressive and concise? We could combine both line 14 and 15 into one line as shown below. Assuming you had to perform several operations like this on our collection, you would end up with some very unreadable code! 1: var formattedEmployees = Select(Where(employees, emp => emp.ID % 2 == 0), (emp) => 2: new EmployeeFormatted { 3: ID = emp.ID, 4: FullName = emp.LastName + ", " + emp.FirstName 5: }); A cleaner way to write this would be to give the appearance that the Select and Where methods were part of the IEnumerable<T>. This is exactly what extension methods give us. Extension methods have to be defined in a static class. Let us make the Select and Where extension methods on IEnumerable<T> 1: public static class MyExtensionMethods { 2: static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> filter) { 3: foreach (var x in source) { 4: if (filter(x)) { 5: yield return x; 6: } 7: } 8: } 9: 10: static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) { 11: foreach (var x in source) { 12: yield return selector(x); 13: } 14: } 15: } The creation of the extension method makes the syntax much cleaner as shown below. We can write as many extension methods as we want and keep on chaining them using this technique. 1: var formattedEmployees = employees 2: .Where(emp => emp.ID % 2 == 0) 3: .Select (emp => new EmployeeFormatted { ID = emp.ID, FullName = emp.LastName + ", " + emp.FirstName }); Making these changes and running our code produces the same result. 1: using System; 2: using System.Collections.Generic; 3:  4: public class Program 5: { 6: [STAThread] 7: static void Main(string[] args) 8: { 9: var employees = new List<Employee> { 10: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 11: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 12: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 13: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 14: }; 15:  16: var formattedEmployees = employees 17: .Where(emp => emp.ID % 2 == 0) 18: .Select (emp => 19: new EmployeeFormatted { 20: ID = emp.ID, 21: FullName = emp.LastName + ", " + emp.FirstName 22: } 23: ); 24:  25: foreach (EmployeeFormatted emp in formattedEmployees) { 26: Console.WriteLine("ID {0} Full_Name {1}", 27: emp.ID, emp.FullName); 28: } 29: Console.ReadLine(); 30: } 31: } 32:  33: public static class MyExtensionMethods { 34: static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> filter) { 35: foreach (var x in source) { 36: if (filter(x)) { 37: yield return x; 38: } 39: } 40: } 41: 42: static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) { 43: foreach (var x in source) { 44: yield return selector(x); 45: } 46: } 47: } 48:  49: public class Employee { 50: public int ID { get; set;} 51: public string FirstName { get; set;} 52: public string LastName {get; set;} 53: public string Country { get; set; } 54: } 55:  56: public class EmployeeFormatted { 57: public int ID { get; set; } 58: public string FullName {get; set;} 59: } Let’s change our code to return a collection of anonymous types and get rid of the EmployeeFormatted type. We see that the code produces the same output. 1: using System; 2: using System.Collections.Generic; 3:  4: public class Program 5: { 6: [STAThread] 7: static void Main(string[] args) 8: { 9: var employees = new List<Employee> { 10: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 11: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 12: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 13: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 14: }; 15:  16: var formattedEmployees = employees 17: .Where(emp => emp.ID % 2 == 0) 18: .Select (emp => 19: new { 20: ID = emp.ID, 21: FullName = emp.LastName + ", " + emp.FirstName 22: } 23: ); 24:  25: foreach (var emp in formattedEmployees) { 26: Console.WriteLine("ID {0} Full_Name {1}", 27: emp.ID, emp.FullName); 28: } 29: Console.ReadLine(); 30: } 31: } 32:  33: public static class MyExtensionMethods { 34: public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> filter) { 35: foreach (var x in source) { 36: if (filter(x)) { 37: yield return x; 38: } 39: } 40: } 41: 42: public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) { 43: foreach (var x in source) { 44: yield return selector(x); 45: } 46: } 47: } 48:  49: public class Employee { 50: public int ID { get; set;} 51: public string FirstName { get; set;} 52: public string LastName {get; set;} 53: public string Country { get; set; } 54: } To be more expressive, C# allows us to write our extension method calls as a query expression. Line 16 can be rewritten a query expression like so: 1: var formattedEmployees = from emp in employees 2: where emp.ID % 2 == 0 3: select new { 4: ID = emp.ID, 5: FullName = emp.LastName + ", " + emp.FirstName 6: }; When the compiler encounters an expression like the above, it simply rewrites it as calls to our extension methods.  So far we have been using our extension methods. The System.Linq namespace contains several extension methods for objects that implement the IEnumerable<T>. You can see a listing of these methods in the Enumerable class in the System.Linq namespace. Let’s get rid of our extension methods (which I purposefully wrote to be of the same signature as the ones in the Enumerable class) and use the ones provided in the Enumerable class. Our final code is shown below: 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; //Added 4:  5: public class Program 6: { 7: [STAThread] 8: static void Main(string[] args) 9: { 10: var employees = new List<Employee> { 11: new Employee { ID = 1, FirstName = "John", LastName = "Wright", Country = "USA" }, 12: new Employee { ID = 2, FirstName = "Jim", LastName = "Ashlock", Country = "UK" }, 13: new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson", Country = "CHE" }, 14: new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" } 15: }; 16:  17: var formattedEmployees = from emp in employees 18: where emp.ID % 2 == 0 19: select new { 20: ID = emp.ID, 21: FullName = emp.LastName + ", " + emp.FirstName 22: }; 23:  24: foreach (var emp in formattedEmployees) { 25: Console.WriteLine("ID {0} Full_Name {1}", 26: emp.ID, emp.FullName); 27: } 28: Console.ReadLine(); 29: } 30: } 31:  32: public class Employee { 33: public int ID { get; set;} 34: public string FirstName { get; set;} 35: public string LastName {get; set;} 36: public string Country { get; set; } 37: } 38:  39: public class EmployeeFormatted { 40: public int ID { get; set; } 41: public string FullName {get; set;} 42: } This post has shown you a basic overview of LINQ to Objects work by showning you how an expression is converted to a sequence of calls to extension methods when working directly with objects. It gets more interesting when working with LINQ to SQL where an expression tree is constructed – an in memory data representation of the expression. The C# compiler compiles these expressions into code that builds an expression tree at runtime. The provider can then traverse the expression tree and generate the appropriate SQL query. You can read more about expression trees in this MSDN article.

    Read the article

  • Looping in Python and keeping current line after sub routine [migrated]

    - by Brendan
    I've been trying to nut out an issue when looping in python 3. When returning from sub routine the "line" variable has not incremented. How do I get the script to return the latest readline from the subsroutine? Code below def getData(line): #print(line) #while line in sTSDP_data: while "/service/content/test" not in line: line = sTSDP_data.readline() import os, sys sFileTSDP = "d:/ess/redo/Test.log" sTSDP_data = open(sFileTSDP, "r") for line in sTSDP_data: if "MOBITV" in line: getData(line) #call sub routine print(line)

    Read the article

  • Lambda&rsquo;s for .NET made easy&hellip;

    - by mbcrump
    The purpose of my blog is to explain things for a beginner to intermediate c# programmer. I’ve seen several blog post that use lambda expressions always assuming the audience is familiar with them. The purpose of this post is to make them simple and easily understood. Let’s begin with a definition. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. So anonymous function… delegates or expression tree types? I don’t get it??? Confused yet?   Lets break this into a few definitions and jump right into the code. anonymous function – is an "inline" statement or expression that can be used wherever a delegate type is expected. delegate - is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value. Expression trees - represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.   Don’t worry if this still sounds confusing, lets jump right into the code with a simple 3 line program. We are going to use a Function Delegate (all you need to remember is that this delegate returns a value.) Lambda expressions are used most commonly with the Func and Action delegates, so you will see an example of both of these. Lambda Expression 3 lines. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {             Func<int, int> myfunc = x => x *x;             Console.WriteLine(myfunc(6).ToString());             Console.ReadLine();         }       } } Is equivalent to Old way of doing it. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {               Console.WriteLine(myFunc(6).ToString());             Console.ReadLine();         }            static int myFunc(int x)          {              return x * x;            }       } } In the example, there is a single parameter, x, and the expression is x*x. I’m going to stop here to make sure you are still with me. A lambda expression is an unnamed method written in place of a delegate instance. In other words, the compiler converts the lambda expression to either a : A delegate instance An expression tree All lambda have the following form: (parameters) => expression or statement block Now look back to the ones we have created. It should start to sink in. Don’t get stuck on the => form, use it as an identifier of a lambda. A Lamba expression can also be written in the following form: Lambda Expression. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {             Func<int, int> myFunc = x =>             {                 return x * x;             };               Console.WriteLine(myFunc(6).ToString());             Console.ReadLine();         }       } } This form may be easier to read but consumes more space. Lets try an Action delegate – this delegate does not return a value. Action Delegate example. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {             Action<string> myAction = (string x) => { Console.WriteLine(x); };             myAction("michael has made this so easy");                                   Console.ReadLine();         }       } } Lambdas can also capture outer variables (such as the example below) A lambda expression can reference the local variables and parameters of the method in which it’s defined. Outer variables referenced by a lambda expression are called captured variables. Capturing Outer Variables using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {             string mike = "Michael";             Action<string> myAction = (string x) => {                 Console.WriteLine("{0}{1}", mike, x);          };             myAction(" has made this so easy");                                   Console.ReadLine();         }       } } Lamba’s can also with a strongly typed list to loop through a collection.   Used w a strongly typed list. using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace ConsoleApplication7 {     class Program     {          static void Main(string[] args)         {             List<string> list = new List<string>() { "1", "2", "3", "4" };             list.ForEach(s => Console.WriteLine(s));             Console.ReadLine();         }       } } Outputs: 1 2 3 4 I think this will get you started with Lambda’s, as always consult the MSDN documentation for more information. Still confused? Hopefully you are not.

    Read the article

  • Encapsulating code in F# (Part 1)

    - by MarkPearl
    I have been looking at F# for a while now and seem a few really interesting samples and snippets on howto’s. This has been great to see the basic outline of the language and the possibilities, however a nagging question in the back of my mind has been what does an F# project look like? How do I code group code in F# so that it can be modularized and brought in and out of a project easily? My Expert F# book has an entire chapter (7) dedicated to this and after browsing the other chapters of the book I decided that this topic was something I really wanted to know more about now! Because of my C# background I keep trying to think in F# of objects. So to try and get a clearer idea of how to do things the F# way I am first going to take a very simplified C# example and try to “translate” it. using System; namespace ConsoleApplication1 { namespace ExampleOfEncapsulationInCSharp { class Program { static void EncapsulatedVariableInAMethod() { int count = 10; Console.WriteLine(count); } static void Main(string[] args) { EncapsulatedVariableInAMethod(); Console.ReadLine(); } } } } From the above example the count integer is encapsulated within EncapsulatedVariableInAMethod method. You couldn’t access the count variable from outside the scope of its parent method but have full access to it within the method. Lets look at my F# equivalent… open System let EncapsulatedVariableInAMethod = let count = 10 Console.WriteLine(count) () EncapsulatedVariableInAMethod Console.ReadLine()   Now, when I first attempted to write the F# code I got stuck… I didn’t have the Console.WriteLine calls but had the following… open System let EncapsulatedVariableInAMethod = let count = 10 EncapsulatedVariableInAMethod Console.ReadLine()   The compiler didn’t like the let before the count = 10. This is because every F# expression must evaluate to a value. If I did not want to make the Console call, I would still need to evaluate the expression to something – and for this reason the Unit Type is provided. I could have done something like…. open System let EncapsulatedVariableInAMethod = let count = 10 () EncapsulatedVariableInAMethod Console.ReadLine()   Which the compiler would be happy with…

    Read the article

  • The sign of a true manager is delegation (C# style)

    - by MarkPearl
    Today I thought I would write a bit about delegates in C#. Up till recently I have managed to side step any real understanding of what delegates do and why they are useful – I mean, I know roughly what they do and have used them a lot, but I have never really got down dirty with them and mucked about. Recently however with my renewed interest in Silverlight delegates came up again as a possible solution to a particular problem, and suddenly I found myself opening a bland little console application to just see exactly how far I could take delegates with my limited knowledge. So, let’s first look at the MSDN definition of delegates… A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure. Well, don’t you love MSDN for such a useful definition. I must give it credit though… later on it really explains it a bit better by saying “A delegate lets you pass a function as a parameter. The type safety of delegates requires the function you pass as a delegate to have the same signature as the delegate declaration.” A little more reading up on delegates mentions that delegates are similar to interfaces in that they enable the separation of specification and implementation. A delegate declares a single method, while an interface declares a group of methods. So enough reading - lets look at some code and see a basic example of a delegate… Let’s assume we have a console application with a simple delegate declared called AdjustValue like below… class Program { private delegate int AdjustValue(int val); static void Main(string[] args) { } } In a sense, all we have said is that we will be creating one or more methods that follow the same pattern as AdjustValue – i.e. they will take one input value of type int and return an integer. We could then expand our code to have various methods that match the structure of our delegate AdjustValue (remember the structure is int xxx (int xxx)) class Program { private delegate int AdjustValue(int val); private static int Dbl(int val) { return val * 2; } private static int AlwaysOne(int val) { return 1; } static void Main(string[] args) { } }  Above I have expanded my project to have two methods, one called Dbl and the other AlwaysOne. Dbl always returns double the input val and AlwaysOne always returns 1. I could now declare a variable and assign it to be one of those functions, like the following… class Program { private delegate int AdjustValue(int val); private static int Dbl(int val) { return val * 2; } private static int AlwaysOne(int val) { return 1; } static void Main(string[] args) { AdjustValue myDelegate; myDelegate = Dbl; Console.WriteLine(myDelegate(1).ToString()); Console.ReadLine(); } } In this instance I have declared an instance of the AdjustValue delegate called myDelegate; I have then told myDelegate to point to the method Dbl, and then called myDelegate(1). What would the result be? Yes, in this instance it would be exactly the same as me calling the following code… static void Main(string[] args) { Console.WriteLine(Dbl(1).ToString()); Console.ReadLine(); }   So why all the extra work for delegates when we could just do what we did above and call the method directly? Well… that separation of specification to implementation comes to mind. So, this all seems pretty simple. Let’s take a slightly more complicated variation to the console application. Assume that my project is the same as the one previously except that my main method is adjusted as follows… static void Main(string[] args) { AdjustValue myDelegate; myDelegate = Dbl; myDelegate = AlwaysOne; Console.WriteLine(myDelegate(1).ToString()); Console.ReadLine(); } What would happen in this scenario? Quite simply “1” would be written to the console, the reason being that myDelegate was last pointing to the AlwaysOne method before it was called. Make sense? In a way, the myDelegate is a variable method that can be swapped and changed when needed. Let’s make the code a little more confusing by using a delegate in the declaration of another delegate as shown below… class Program { private delegate int AdjustValue(InputValue val); private delegate int InputValue(); private static int Dbl(InputValue val) { return val()*2; } private static int GetInputVal() { Console.WriteLine("Enter a whole number : "); return Convert.ToInt32(Console.ReadLine()); } static void Main(string[] args) { AdjustValue myDelegate; myDelegate = Dbl; Console.WriteLine(myDelegate(GetInputVal).ToString()); Console.ReadLine(); } }   Now it gets really interesting because it looks like we have passed a method into a function in the main method by declaring… Console.WriteLine(myDelegate(GetInputVal).ToString()); So, what it the output? Well, try take a guess on what will happen – then copy the code and see if you got it right. Well that brings me to the end of this short explanation of Delegates. Hopefully it made sense!

    Read the article

  • Nashorn ?? JDBC ? Oracle DB ?????·?? 3

    - by Homma
    ???? Nashorn ?? JavaScript ??????? JDBC ? Oracle DB ???????????????????? Oracle DB ????? SQL ??????????????? ???????????????????????????????? ????????? URL ? https://blogs.oracle.com/nashorn_ja/entry/nashorn_jdbc_3 ??? JDBC ??????????????? JDBC ????????????????? Nashorn ????? JavaScript ????????????? ???????? JDBC OCI ???????????????????????????????? ????? ?? Java ??????????????? Nashorn ? JavaScript ???????????????? // Invoke jjs with -scripting option. /* * This sample can be used to check the JDBC installation. * Just run it and provide the connect information. It will select * "Hello World" from the database. */ var OracleDataSource = Java.type("oracle.jdbc.pool.OracleDataSource"); function main() { // Prompt the user for connect information print("Please enter information to test connection to the database"); var user, password, database; user = readLine("user: "); slash_index = user.indexOf('/'); if (slash_index != -1) { password = user.substring(slash_index + 1) user = user.substring(0, slash_index); } else password = readLine("password: "); database = readLine("database(a TNSNAME entry): "); java.lang.System.out.print("Connecting to the database..."); java.lang.System.out.flush(); print("Connecting..."); // Open an OracleDataSource and get a connection var ods = new OracleDataSource(); ods.setURL("jdbc:oracle:oci:@" + database); ods.setUser(user); ods.setPassword(password); var conn = ods.getConnection(); print("connected."); // Create a statement var stmt = conn.createStatement(); // Do the SQL "Hello World" thing var rset = stmt.executeQuery("select 'Hello World' from dual"); while (rset.next()) print(rset.getString(1)); // close the result set, the statement and the connection rset.close(); stmt.close(); conn.close(); print("Your JDBC installation is correct."); } main(); oracle.jdbc.pool.OracleDataSource ? Java.type() ?????Nashorn ??????????????????????????? Java ? System.out.println() ? System.out.flush() ? java.lang. ???????????????? Java ?????????? readEntry() ????? Nashorn ? readLine() ???????????? Java ????????????????????????JavaScript ?????????????????? ?? Java ??????????????????????????? Java ???????????????? JavaScript ?????????????????? ???????? JDBC OCI ???????????????? LD_LIBRARY_PATH ????????????????? ???Nashorn ? readLine() ??????????jjs ????? -scripting ????????????????? $ export LD_LIBRARY_PATH=${ORACLE_HOME}/lib $ jjs -scripting -cp ${ORACLE_HOME}/jdbc/lib/ojdbc6.jar JdbcCheckup.js Please enter information to test connection to the database user: test password: test database(a TNSNAME entry): orcl Connecting to the database...Connecting... connected. Hello World Your JDBC installation is correct. JDBC OCI ????????????????? "select 'Hello World' from dual" ??? SQL ?????????????? ?????????????????database ???? :: ??????????? ??? ??? Oracle DB ????? SQL ???????????????? Java ? JDBC ??????????????????????????? Nashorn ??????????????????????????????????

    Read the article

  • Reading a user input (character or string of letters) into ggplot command inside a switch statement or a nested ifelse (with functions in it)

    - by statisticalbeginner
    I have code like AA <- as.integer(readline("Select any number")) switch(AA, 1={ num <-as.integer(readline("Select any one of the options \n")) print('You have selected option 1') #reading user data var <- readline("enter the variable name \n") #aggregating the data based on required condition gg1 <- aggregate(cbind(get(var))~Mi+hours,a, FUN=mean) #Ploting ggplot(gg1, aes(x = hours, y = get(var), group = Mi, fill = Mi, color = Mi)) + geom_point() + geom_smooth(stat="smooth", alpha = I(0.01)) }, 2={ print('bar') }, { print('default') } ) The dataset is [dataset][1] I have loaded the dataset into object list a <- read.table(file.choose(), header=FALSE,col.names= c("Ei","Mi","hours","Nphy","Cphy","CHLphy","Nhet","Chet","Ndet","Cdet","DON","DOC","DIN","DIC","AT","dCCHO","TEPC","Ncocco","Ccocco","CHLcocco","PICcocco","par","Temp","Sal","co2atm","u10","dicfl","co2ppm","co2mol","pH")) I am getting error like source ("switch_statement_check.R") Select any one of the options 1 [1] "You have selected option 1" enter the variable name Nphy Error in eval(expr, envir, enclos) : (list) object cannot be coerced to type 'double' > gg1 is getting data that is fine. I dont know what to do to make the variable entered by user to work in that ggplot command. Please suggest any solution for this. The dput output structure(list(Ei = c(1L, 1L, 1L, 1L, 1L, 1L), Mi = c(1L, 1L, 1L, 1L, 1L, 1L), hours = 1:6, Nphy = c(0.1023488, 0.104524, 0.1064772, 0.1081702, 0.1095905, 0.110759), Cphy = c(0.6534707, 0.6448216, 0.6369597, 0.6299084, 0.6239005, 0.6191941), CHLphy = c(0.1053458, 0.110325, 0.1148174, 0.1187672, 0.122146, 0.1249877), Nhet = c(0.04994161, 0.04988347, 0.04982555, 0.04976784, 0.04971029, 0.04965285), Chet = c(0.3308593, 0.3304699, 0.3300819, 0.3296952, 0.3293089, 0.3289243), Ndet = c(0.04991916, 0.04984045, 0.04976363, 0.0496884, 0.04961446, 0.04954156), Cdet = c(0.3307085, 0.3301691, 0.3296314, 0.3290949, 0.3285598, 0.3280252), DON = c(0.05042275, 0.05085697, 0.05130091, 0.05175249, 0.05220978, 0.05267118 ), DOC = c(49.76304, 49.52745, 49.29323, 49.06034, 48.82878, 48.59851), DIN = c(14.9933, 14.98729, 14.98221, 14.9781, 14.97485, 14.97225), DIC = c(2050.132, 2050.264, 2050.396, 2050.524, 2050.641, 2050.758), AT = c(2150.007, 2150.007, 2150.007, 2150.007, 2150.007, 2150.007), dCCHO = c(0.964222, 0.930869, 0.8997098, 0.870544, 0.843196, 0.8175117), TEPC = c(0.1339044, 0.1652179, 0.1941872, 0.2210289, 0.2459341, 0.2690721), Ncocco = c(0.1040715, 0.1076058, 0.1104229, 0.1125141, 0.1140222, 0.1151228), Ccocco = c(0.6500288, 0.6386706, 0.6291149, 0.6213265, 0.6152447, 0.6108502), CHLcocco = c(0.1087667, 0.1164099, 0.1225822, 0.1273103, 0.1308843, 0.1336465), PICcocco = c(0.1000664, 0.1001396, 0.1007908, 0.101836, 0.1034179, 0.1055634), par = c(0, 0, 0.8695131, 1.551317, 2.777707, 4.814341), Temp = c(9.9, 9.9, 9.9, 9.9, 9.9, 9.9), Sal = c(31.31, 31.31, 31.31, 31.31, 31.31, 31.31), co2atm = c(370, 370, 370, 370, 370, 370), u10 = c(0.01, 0.01, 0.01, 0.01, 0.01, 0.01), dicfl = c(-2.963256, -2.971632, -2.980446, -2.989259, -2.997877, -3.005702), co2ppm = c(565.1855, 565.7373, 566.3179, 566.8983, 567.466, 567.9814), co2mol = c(0.02562326, 0.02564828, 0.0256746, 0.02570091, 0.02572665, 0.02575002 ), pH = c(7.879427, 7.879042, 7.878636, 7.878231, 7.877835, 7.877475)), .Names = c("Ei", "Mi", "hours", "Nphy", "Cphy", "CHLphy", "Nhet", "Chet", "Ndet", "Cdet", "DON", "DOC", "DIN", "DIC", "AT", "dCCHO", "TEPC", "Ncocco", "Ccocco", "CHLcocco", "PICcocco", "par", "Temp", "Sal", "co2atm", "u10", "dicfl", "co2ppm", "co2mol", "pH"), row.names = c(NA, 6L), class = "data.frame") As per the below suggestions I have tried a lot but it is not working. Summarizing I will say: var <- readline("enter a variable name") I cant use get(var) inside any command but not inside ggplot, it wont work. gg1$var it also doesnt work, even after changing the column names. Does it have a solution or should I just choose to import from an excel sheet, thats better? Tried with if else and functions fun1 <- function() { print('You have selected option 1') my <- as.character((readline("enter the variable name \n"))) gg1 <- aggregate(cbind(get(my))~Mi+hours,a, FUN=mean) names(gg1)[3] <- my #print(names(gg1)) ggplot (gg1,aes_string(x="hours",y=(my),group="Mi",color="Mi")) + geom_point() } my <- as.integer(readline("enter a number")) ifelse(my == 1,fun1(),"") ifelse(my == 2,print ("its 2"),"") ifelse(my == 3,print ("its 3"),"") ifelse(my != (1 || 2|| 3) ,print("wrong number"),"") Not working either...:(

    Read the article

  • Session management error: None of the authentication protocols specified are supported

    - by JBWhitmore
    The title is the first error that has sent me on a mission to fix things. Motivation: I was trying to install the new Enthought Python Distribution -- when the error above first showed up. The install finished -- and looked like there were a few more times it flagged dcopserver problems: Please check that "dcopserver" program is running! Could not read network connection list: ~/home/user/.DCOPserver_host__0 When running ipython from the distribution, it claims that readline (the ability to up arrow in history or tab-complete) is not available for my system. It is though -- if I run the ipython that's sitting in /usr/bin/ipython all readline features work perfectly. So, I tried to fix the install by trying to fix what I thought could be causing the problems. Bad things that are happening that I want to be fixed: When restarting I get the error: Could not update ICEauthority file /home/username/.ICEauthority. ipython readline doesn't work with Enthought's ipython Things I have tried: changed the owner of my ~/.ICEauthority to be me. changed the owner of home directory (and all nested files and folders) to be me double checked that /var/lib/gdm was owned by Gnome (yep) attempted to reinstall DCOP, kbuildsycoca stuff (fail) I've removed nautilus; rebooted; reinstalled; rebooted; removed ubuntu-desktop; rebooted; reinstalled; rebooted. Any suggestions on how to fix the Bad Things that are happening would be greatly appreciated! Computer: Ubuntu 10.04 x86

    Read the article

  • No Thank You &ndash; Yours Truly &ndash; F#

    - by MarkPearl
    I am plodding along with my F# book. I have reached the part where I know enough about the syntax of the language to understand something if I read it – but not enough about the language to be productive and write something useful. A bit of a frustrating place to be. Needless to say when you are in this state of mind – you end up paging mindlessly through chapters of my F# book with no real incentive to learn anything until you hit “Exceptions”. Raising an exception explicitly So lets look at raising an exception explicitly – in C# we would throw the exception, F# is a lot more polite instead of throwing the exception it raises it, … (raise (System.InvalidOperationException("no thank you"))) quite simple… Catching an Exception So I would expect to be able to catch an exception as well – lets look at some C# code first… try { Console.WriteLine("Raise Exception"); throw new InvalidOperationException("no thank you"); } catch { Console.WriteLine("Catch Exception and Carry on.."); } Console.WriteLine("Carry on..."); Console.ReadLine();   The F# equivalent would go as follows… open System; try Console.WriteLine("Raise Exception") raise (System.InvalidOperationException("no thank you")) with | _ -> Console.WriteLine("Catch Exception and Carry on..") Console.WriteLine("Carry on...") Console.ReadLine();   In F# there is a “try, with” and a “try finally” Finally… In F# there is a finally block however the “with” and “finally” can’t be combined. open System; try Console.WriteLine("Raise Exception") raise (System.InvalidOperationException("no thank you")) finally Console.WriteLine("Finally carry on...") Console.ReadLine()

    Read the article

  • adjacency list creation , out of Memory error

    - by p1
    Hello , I am trying to create an adjacency list to store a graph.The implementation works fine while storing 100,000 records. However,when I tried to store around 1million records I ran into OutofMemory Error : Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOfRange(Arrays.java:3209) at java.lang.String.(String.java:215) at java.io.BufferedReader.readLine(BufferedReader.java:331) at java.io.BufferedReader.readLine(BufferedReader.java:362) at liarliar.main(liarliar.java:39) Following is my implementation HashMap<String,ArrayList<String>> adj = new HashMap<String,ArrayList<String>>(num); while ((str = in.readLine()) != null) { StringTokenizer Tok = new StringTokenizer(str); name = (String) Tok.nextElement(); cnt = Integer.valueOf(Tok.nextToken()); ArrayList<String> templist = new ArrayList<String>(cnt); while(cnt>0) { templist.add(in.readLine()); cnt--; } adj.put(name,templist); } //done creating a adjacency list I am wondering, if there is any better way to implement the adjacency list. Also, I know number of nodes right in the begining and , in the future I flatten the list as I visit nodes. Any suggestions ? Thanks

    Read the article

  • Using StringBuilder to process csv files to save heap space

    - by portoalet
    I am reading a csv file that has about has about 50,000 lines and 1.1MiB in size (and can grow larger). In Code1, I use String to process the csv, while in Code2 I use StringBuilder (only one thread executes the code, so no concurrency issues) Using StringBuilder makes the code a little bit harder to read that using normal String class. Am I prematurely optimizing things with StringBuilder in Code2 to save a bit of heap space and memory? Code1 fr = new FileReader(file); BufferedReader reader = new BufferedReader(fr); String line = reader.readLine(); while ( line != null ) { int separator = line.indexOf(','); String symbol = line.substring(0, seperator); int begin = separator; separator = line.indexOf(',', begin+1); String price = line.substring(begin+1, seperator); // Publish this update publisher.publishQuote(symbol, price); // Read the next line of fake update data line = reader.readLine(); } Code2 fr = new FileReader(file); StringBuilder stringBuilder = new StringBuilder(reader.readLine()); while( stringBuilder.toString() != null ) { int separator = stringBuilder.toString().indexOf(','); String symbol = stringBuilder.toString().substring(0, separator); int begin = separator; separator = stringBuilder.toString().indexOf(',', begin+1); String price = stringBuilder.toString().substring(begin+1, separator); publisher.publishQuote(symbol, price); stringBuilder.replace(0, stringBuilder.length(), reader.readLine()); }

    Read the article

  • c++ Mixing printf with wprintf (or cout with wcout)

    - by Bo Jensen
    I know you should not mix printing with printf,cout and wprintf,wcout, but have a hard time finding a good answer why and if it is possible to get round it. The problem is I use a external library that prints with printf and my own uses wcout. If I do a simple example it works fine, but from my full application it simply does not print the printf statements. If this is really a limitation, then there would be many libraries out there which can not work together with wide printing applications. Any insight on this is more than welcome. Update : I boiled it down to : #include <stdio.h> #include <stdlib.h> #include <iostream> #include <readline/readline.h> #include <readline/history.h> int main() { char *buf; std::wcout << std::endl; /* ADDING THIS LINE MAKES PRINTF VANISH!!! */ rl_bind_key('\t',rl_abort);//disable auto-complete while((buf = readline("my-command : "))!=NULL) { if (strcmp(buf,"quit")==0) break; std::wcout<<buf<< std::endl; if (buf[0]!=0) add_history(buf); } free(buf); return 0; } So I guess it might be a flushing problem, but it still looks strange to me, I have to check up on it.

    Read the article

  • Should java try blocks be scoped as tightly as possible?

    - by isme
    I've been told that there is some overhead in using the Java try-catch mechanism. So, while it is necessary to put methods that throw checked exception within a try block to handle the possible exception, it is good practice performance-wise to limit the size of the try block to contain only those operations that could throw exceptions. I'm not so sure that this is a sensible conclusion. Consider the two implementations below of a function that processes a specified text file. Even if it is true that the first one incurs some unnecessary overhead, I find it much easier to follow. It is less clear where exactly the exceptions come from just from looking at statements, but the comments clearly show which statements are responsible. The second one is much longer and complicated than the first. In particular, the nice line-reading idiom of the first has to be mangled to fit the readLine call into a try block. What is the best practice for handling exceptions in a funcion where multiple exceptions could be thrown in its definition? This one contains all the processing code within the try block: void processFile(File f) { try { // construction of FileReader can throw FileNotFoundException BufferedReader in = new BufferedReader(new FileReader(f)); // call of readLine can throw IOException String line; while ((line = in.readLine()) != null) { process(line); } } catch (FileNotFoundException ex) { handle(ex); } catch (IOException ex) { handle(ex); } } This one contains only the methods that throw exceptions within try blocks: void processFile(File f) { FileReader reader; try { reader = new FileReader(f); } catch (FileNotFoundException ex) { handle(ex); return; } BufferedReader in = new BufferedReader(reader); String line; while (true) { try { line = in.readLine(); } catch (IOException ex) { handle(ex); break; } if (line == null) { break; } process(line); } }

    Read the article

  • while loop in c#

    - by Nave Tseva
    I have this code: using System; namespace _121119_zionAVGfilter { class Program { static void Main(string[] args) { int cnt = 0, zion, sum = 0; double avg; Console.Write("Enter first zion \n"); zion = int.Parse(Console.ReadLine()); while (zion != -1) { while (zion < -1 || zion > 100) { Console.Write("zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n"); zion = int.Parse(Console.ReadLine()); } cnt++; sum = sum + zion; Console.Write("Enter next zion, if you want to exit tap -1 \n"); zion = int.Parse(Console.ReadLine()); if (cnt != 0){} } if (cnt == 0) { Console.WriteLine("something doesn't make sence"); } else { avg = (double)sum / cnt; Console.Write("the AVG is {0}", avg); } Console.ReadLine(); } } } The problem here is that if in the beginning I enter a negative or bigger than hundred number, I will get this message: "zion can be between 0 to 100 only! \nyou can rewrite the zion here, or Press -1 to see the avg\n". If I then meenter -1, this what that shows up instead of the AVG: "Enter next zion, if you want to exit tap -1 \n." How can I solve this problem so when the number is negative or bigger than hundred and than tap -1 I will see the AVG an not another message?

    Read the article

  • how to load files in python

    - by Alvaro
    I'm fairly new to python and would like some help on properly loading separate files. My codes purpose is to open a given file, search for customers of that file by the state or state abbreviation. However, i have a separate function to open a separate file where i have (name of state):(state abbreviation) Thanks. def file_state_search(fileid, state): z=0 indx = 0 while z<25: line=fileid.readline() data_list = ("Name:", "Address:", "City:", "State:", "Zipcode:") line_split = line.split(":") if state in line: while indx<5: print data_list[indx], line_split[indx] indx = indx + 1 elif state not in line: z = z + 1 def state_convert(fileid, state): line2=in_file2.readline() while state in line2: print line2 x=1 while x==1: print "Choose an option:" print print "Option '1': Search Record By State" print option = raw_input("Enter an option:") print if option == "1": state = raw_input("Enter A State:") in_file = open("AdrData.txt", 'r') line=in_file.readline() print in_file2 = open("States.txt", 'r') line2=in_file2.readline() converted_state = state_convert(in_file2, state) print converted_state state_find = file_state_search(in_file, state) print state_find x=raw_input("Enter '1' to continue, Enter '2' to stop: ") x=int(x) By the way, my first import statement works, for whatever reason my second one doesn't. Edit: My question is, what am i doing wrong in my state_convert function.

    Read the article

  • C#: An object reference is required for the non-static field, method, or Property

    - by Omin
    I feel bad for asking this when there are so many questions that are related but I was not able to find/understand the answer I am looking for. // 2. Develop a program to convert currency X to currency Y and visa versa. using System; class Problem2 { static void Main (string[] args) { while (true) { Console.WriteLine ("1. Currency Conversion from CAD to Won"); Console.WriteLine ("2. Currency Conversion from Won to Cad"); Console.Write ("Choose from the Following: (1 or 2)? "); int option = int.Parse( Console.ReadLine() ); //double x; if (option == 1) { Console.WriteLine ("Type in the amount you would like to Convert CAD to Won: "); //double y =double.Parse( Console.ReadLine()); //Console.WriteLine( cadToWon( y ) ); Console.WriteLine( cadToWon( double.Parse( Console.ReadLine() ) )); } if (option == 2) { Console.WriteLine ("Type in the amount you would like to Convert Won to CAD: "); Console.WriteLine( wonToCad (double.Parse( Console.ReadLine()))); } } } double cadToWon( double x ) { return x * 1113.26; } double wonToCad( double x) { return x / 1113.26; } } This give me the Error messgae "An object reference is required for the non-static field, method, or property 'Problem2..." I know that I'll be able to run the program if I add static infront of the methods but I'm wondering why I need it (I think it's because Main is static?) and what do I need to change in order to use these methods without adding static to them? Thank you

    Read the article

  • Foreach loop and tasks.

    - by Scott Chamberlain
    I know from the codeing guidlines that I have read you should not do for (int i = 0; i < 5; i++) { Task.Factory.StartNew(() => Console.WriteLine(i)); } Console.ReadLine(); as it will write 5 5's, I understand that and I think i understand why it is happening. I know the solution is just to do for (int i = 0; i < 5; i++) { int localI = i; Task.Factory.StartNew(() => Console.WriteLine(localI)); } Console.ReadLine(); However is something like this ok to do? foreach (MyClass myClass in myClassList) { Task.Factory.StartNew(() => myClass.DoAction()); } Console.ReadLine(); Or do I need to do the same thing I did in the for loop. foreach (MyClass myClass in myClassList) { MyClass localMyClass = myClass; Task.Factory.StartNew(() => localMyClass.DoAction()); } Console.ReadLine();

    Read the article

  • Error In VB.Net code

    - by Michael
    I am getting the error "Format Exception was unhandled at "Do While objectReader.Peek < -1 " and after. any help would be wonderful. 'Date: Class 03/20/2010 'Program Purpose: When code is executed data will be pulled from a text file 'that contains the named storms to find the average number of storms during the time 'period chosen by the user and to find the most active year. between the range of 'years 1990 and 2008 Option Strict On Public Class frmHurricane Private _intNumberOfHuricanes As Integer = 5 Public Shared _intSizeOfArray As Integer = 7 Public Shared _strHuricaneList(_intSizeOfArray) As String Private _strID(_intSizeOfArray) As String Private _decYears(_intSizeOfArray) As Decimal Private _decFinal(_intSizeOfArray) As Decimal Private _intNumber(_intSizeOfArray) As Integer Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'The frmHurricane load event reads the Hurricane text file and 'fill the combotBox object with the data. 'Initialize an instance of the StreamReader Object and declare variable page 675 on the book Dim objectReader As IO.StreamReader Dim strLocationAndNameOfFile As String = "C:\huricanes.txt" Dim intCount As Integer = 0 Dim intFill As Integer Dim strFileError As String = "The file is not available. Please restart application when available" 'This is where we code the file if it exist. If IO.File.Exists(strLocationAndNameOfFile) Then objectReader = IO.File.OpenText(strLocationAndNameOfFile) 'Read the file line by line until the file is complete Do While objectReader.Peek <> -1 **_strHuricaneList(intCount) = objectReader.ReadLine() _strID(intCount) = objectReader.ReadLine() _decYears(intCount) = Convert.ToDecimal(objectReader.ReadLine()) _intNumber(intCount) = Convert.ToInt32(objectReader.ReadLine()) intCount += 1** Loop objectReader.Close() 'With any luck the data will go to the Data Box For intFill = 0 To (_strID.Length - 1) Me.cboByYear.Items.Add(_strID(intFill)) Next Else MsgBox(strFileError, , "Error") Me.Close() End If End Sub

    Read the article

  • Using AES encryption in .NET - CryptographicException saying the padding is invalid and cannot be removed

    - by Jake Petroules
    I wrote some AES encryption code in C# and I am having trouble getting it to encrypt and decrypt properly. If I enter "test" as the passphrase and "This data must be kept secret from everyone!" I receive the following exception: System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed. at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.CryptoStream.FlushFinalBlock() at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at System.IO.Stream.Dispose() ... And if I enter something less than 16 characters I get no output. I believe I need some special handling in the encryption since AES is a block cipher, but I'm not sure exactly what that is, and I wasn't able to find any examples on the web showing how. Here is my code: using System; using System.IO; using System.Security.Cryptography; using System.Text; public static class DatabaseCrypto { public static EncryptedData Encrypt(string password, string data) { return DatabaseCrypto.Transform(true, password, data, null, null) as EncryptedData; } public static string Decrypt(string password, EncryptedData data) { return DatabaseCrypto.Transform(false, password, data.DataString, data.SaltString, data.MACString) as string; } private static object Transform(bool encrypt, string password, string data, string saltString, string macString) { using (AesManaged aes = new AesManaged()) { aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; int key_len = aes.KeySize / 8; int iv_len = aes.BlockSize / 8; const int salt_size = 8; const int iterations = 8192; byte[] salt = encrypt ? new Rfc2898DeriveBytes(string.Empty, salt_size).Salt : Convert.FromBase64String(saltString); byte[] bc_key = new Rfc2898DeriveBytes("BLK" + password, salt, iterations).GetBytes(key_len); byte[] iv = new Rfc2898DeriveBytes("IV" + password, salt, iterations).GetBytes(iv_len); byte[] mac_key = new Rfc2898DeriveBytes("MAC" + password, salt, iterations).GetBytes(16); aes.Key = bc_key; aes.IV = iv; byte[] rawData = encrypt ? Encoding.UTF8.GetBytes(data) : Convert.FromBase64String(data); using (ICryptoTransform transform = encrypt ? aes.CreateEncryptor() : aes.CreateDecryptor()) using (MemoryStream memoryStream = encrypt ? new MemoryStream() : new MemoryStream(rawData)) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, encrypt ? CryptoStreamMode.Write : CryptoStreamMode.Read)) { if (encrypt) { cryptoStream.Write(rawData, 0, rawData.Length); return new EncryptedData(salt, mac_key, memoryStream.ToArray()); } else { byte[] originalData = new byte[rawData.Length]; int count = cryptoStream.Read(originalData, 0, originalData.Length); return Encoding.UTF8.GetString(originalData, 0, count); } } } } } public class EncryptedData { public EncryptedData() { } public EncryptedData(byte[] salt, byte[] mac, byte[] data) { this.Salt = salt; this.MAC = mac; this.Data = data; } public EncryptedData(string salt, string mac, string data) { this.SaltString = salt; this.MACString = mac; this.DataString = data; } public byte[] Salt { get; set; } public string SaltString { get { return Convert.ToBase64String(this.Salt); } set { this.Salt = Convert.FromBase64String(value); } } public byte[] MAC { get; set; } public string MACString { get { return Convert.ToBase64String(this.MAC); } set { this.MAC = Convert.FromBase64String(value); } } public byte[] Data { get; set; } public string DataString { get { return Convert.ToBase64String(this.Data); } set { this.Data = Convert.FromBase64String(value); } } } static void ReadTest() { Console.WriteLine("Enter password: "); string password = Console.ReadLine(); using (StreamReader reader = new StreamReader("aes.cs.txt")) { EncryptedData enc = new EncryptedData(); enc.SaltString = reader.ReadLine(); enc.MACString = reader.ReadLine(); enc.DataString = reader.ReadLine(); Console.WriteLine("The decrypted data was: " + DatabaseCrypto.Decrypt(password, enc)); } } static void WriteTest() { Console.WriteLine("Enter data: "); string data = Console.ReadLine(); Console.WriteLine("Enter password: "); string password = Console.ReadLine(); EncryptedData enc = DatabaseCrypto.Encrypt(password, data); using (StreamWriter stream = new StreamWriter("aes.cs.txt")) { stream.WriteLine(enc.SaltString); stream.WriteLine(enc.MACString); stream.WriteLine(enc.DataString); Console.WriteLine("The encrypted data was: " + enc.DataString); } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >