Search Results

Search found 720 results on 29 pages for 'tolist'.

Page 19/29 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • Linq to NHibernate wrapper issue using where statement

    - by Jacob
    I'am using wrapper to get some data from table users IQueryable<StarGuestWrapper> WhereQuery = session.Linq<User>().Where(u => u.HomeClub.Id == clubId && u.IsActive).Select( u => new StarGuestWrapper() { FullName = u.Name + " " + u.LastName, LoginTime = DateTime.Now, MonthsAsMember = 2, StarRating = 1, UserPicture = u.Photo.PhotoData, InstructorFullName = "Someone Xyz", TalkInteractionDuringSession = true, GoalInteractionDuringSession = false }); I use this without a problem as a IQueryable so I can do useful things before actually running the query. Like : WhereQuery.Skip(startRowIndex).Take(maximumRows).ToList(); and so on. The problem occurs using 'where' statement on query. For example: WhereQuery.Where(s => s.StarRating == 1) will throw an exception in runtime that 'StarRating' doesn't exist in User table - of course it doesn't it's a wrappers property. I will work if I materialize query by WhereQuery.AsEnumerable().Where(s => s.StarRating == 1) but then it loses all the sens of using IQueryable and I don't want to do this. What is strange and interesting that not all properties from wrapper throw error, all the bool values can be used in where statement. Example : WhereQuery.Where(s => s.TalkInteractionDuringSession) It works in EntityFramework , why do I get this error in NHibernate and how to get it working the way I want it to ?

    Read the article

  • Deserialize generic collections - coming up empty

    - by AC
    I've got a settings object for my app that has two collections in it. The collections are simple List generics that contain a collection of property bags. When I serialize it, everything is saved with no problem: XmlSerializer x = new XmlSerializer(settings.GetType()); TextWriter tw = new StreamWriter(@"c:\temp\settings.cpt"); x.Serialize(tw, settings); However when I deserialize it, everything is restored except for the two collections (verified by setting a breakpoint on the setters: XmlSerializer x = new XmlSerializer(typeof(CourseSettings)); XmlReader tr = XmlReader.Create(@"c:\temp\settings.cpt"); this.DataContext = (CourseSettings)x.Deserialize(tr); What would cause this? Everything is pretty vanilla... here's a snippet from the settings object... omitting most of it. The PresentationSourceDirectory works just fine, but the PresentationModules' setter isn't hit: private string _presentationSourceDirectory = string.Empty; public string PresentationSourceDirectory { get { return _presentationSourceDirectory; } set { if (_presentationSourceDirectory != value) { OnPropertyChanged("PresentationSourceDirectory"); _presentationSourceDirectory = value; } } } private List<Module> _presentationModules = new List<Module>(); public List<Module> PresentationModules { get { var sortedModules = from m in _presentationModules orderby m.ModuleOrder select m; return sortedModules.ToList<Module>(); } set { if (_presentationModules != value) { _presentationModules = value; OnPropertyChanged("PresentationModules"); } } }

    Read the article

  • How can i Write list type returning value in Linq with Entity FrameWork?

    - by programmerist
    How can i return List<personel> data type from below procedure. if i press F5 it throw me this error: Error 1 Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?) C:\Documents and Settings\yusufk\Desktop\EFTestSolutions\WebApplicationTest1\WebApplicationTest1\Default.aspx.cs 101 61 WebApplicationTest1 i think that: i should rearrange or recode "select new {. . . . " ? protected List<personel> GetPersonalsData2() { List<personel> personeller; using (FirmaEntities firmactx = new FirmaEntities()) { personeller = (from p in firmactx.Personals select new { p.ID, p.Name, p.SurName }); return personeller.ToList(); } } } public class personel { public int ID { get; set; } public string Name { get; set; } public string SurName { get; set; } }

    Read the article

  • Subsonic 3, SimpleRepository, SQL Server: How to find rows with a null field?

    - by desautelsj
    How ca I use Subsonic's Find<T> method to search for rows with a field containing the "null" value. For the sake of the discussion, let's assume I have a c# class called "Visit" which contains a nullable DateTime field called "SynchronizedOn" and also let's assume that the Subsonic migration has created the corresponding "Visits" table and the "SynchronizedOn" field. If I was to write the SQL query myself, I would write something like: SELECT * FROM Visits WHERE SynchronizedOn IS NULL When I use the following code: var visits = myRepository.Find<Visit>(x => x.SynchronizedOn == null); Subsonic turns it into the following SQL query: SELECT * FROM Visits WHERE SynchronizedOn == null which never returns any rows. I tried the following code but it throws an error: visits = repository.Find<Visit>(x => x.SynchronizedOn.HasValue); I was able to use the following syntax: var query = from v in repository.All<Visit>() where v.SynchronizedOn == null orderby v.CreatedOn select v; visits = query.ToList<Visit>(); but it's not as nice an short as using the Find<T> method. Anyone knows how I can specify the "SynchronizedOn IS NULL" condition in the Find<T> method?

    Read the article

  • Getting values from DataGridView back to XDocument (using LINQ-to-XML)

    - by Pretzel
    Learning LINQ has been a lot of fun so far, but despite reading a couple books and a bunch of online resources on the topic, I still feel like a total n00b. Recently, I just learned that if my query returns an Anonymous type, the DataGridView I'm populating will be ReadOnly (because, apparently Anonymous types are ReadOnly.) Right now, I'm trying to figure out the easiest way to: Get a subset of data from an XML file into a DataGridView, Allow the user to edit said data, Stick the changed data back into the XML file. So far I have Steps 1 and 2 figured out: public class Container { public string Id { get; set; } public string Barcode { get; set; } public float Quantity { get; set; } } // For use with the Distinct() operator public class ContainerComparer : IEqualityComparer<Container> { public bool Equals(Container x, Container y) { return x.Id == y.Id; } public int GetHashCode(Container obj) { return obj.Id.GetHashCode(); } } var barcodes = (from src in xmldoc.Descendants("Container") where src.Descendants().Count() > 0 select new Container { Id = (string)src.Element("Id"), Barcode = (string)src.Element("Barcode"), Quantity = float.Parse((string)src.Element("Quantity").Attribute("value")) }).Distinct(new ContainerComparer()); dataGridView1.DataSource = barcodes.ToList(); This works great at getting the data I want from the XML into the DataGridView so that the user has a way to manipulate the values. Upon doing a Step-thru trace of my code, I'm finding that the changes to the values made in DataGridView are not bound to the XDocument object and as such, do not propagate back. How do we take care of Step 3? (getting the data back to the XML) Is it possible to Bind the XML directly to the DataGridView? Or do I have to write another LINQ statement to get the data from the DGV back to the XDocument? Suggstions?

    Read the article

  • SpeechSynthesizer Exception - Please Help

    - by Chris
    Hi. I have the following code: private List<VoiceInfo> GetInstalledVoices(SpeechSynthesizer synthesizer) { CultureInfo currentCulture = CultureInfo.CurrentCulture; var listOfVoiceInfo = from voice in synthesizer.GetInstalledVoices(currentCulture) select voice.VoiceInfo; return listOfVoiceInfo.ToList<VoiceInfo>(); } I then call the code from the following code snippet: var synthesizer = new SpeechSynthesizer(); var installedVoices = GetInstalledVoices(synthesizer); VoiceInfo voice = null; if (installedVoices != null && installedVoices.Count > 0) { voice = installedVoices.FirstOrDefault(); } if (voice != null) { synthesizer.SelectVoice(voice.Name); } The line of code that selects the voice throws the following exception: "Cannot set voice. No matching voice is installed or the voice was disabled." This is being done from within an ASP.NET web application - running on Windows Server 2003 R2. When I run this from within Visual Studio 2008 - everything works fine. I created a simple Console app to perform the same action - then ran it from the Windows Server 2003 machine - and it worked fine. I even modified the code in the Console app to loop through each of the installed voices and select the voice. No problems. However, when doing the same from within the web application, I get the same error. I am beating my head against a wall on this one. ANY help on this would be greatly appreciated. Thanks. Chris

    Read the article

  • How to make NAnt send an email using a real account

    - by Turro
    First of all, I have already seen this post: nant mail issues but the only answer is not satisfactory (i.e.: doesn't work for me). I am using NAnt to get latest version of source, upgrade version of the libraries and application, build the application, build the setups... all the usual things, I bet. I would like NAnt to send an email to some people confirming the conclusion of the build process; I've already checked the official (pretty ugly, IMHO) documentation for the task, but the example, once copied and customized, doesn't work. This are the NAnt target and task I'm using: <target name="sendMail" > <mail from="[email protected]" tolist="[email protected];[email protected]" subject="Subject of email" mailhost="smtp.gmail.com" message="Your new release is ready!"> </mail> </target> The error message I get is: 530 5.7.0 Must issue a STARTTLS command first. It looks like that the task was designed for use by an account whose provider doesn't need authentication; but what can I do if I must use an external smtp server which requires authentication (telling my boss I need an smtp server in house is not an option)? Can anybody help/teach me? Thanks in advance...

    Read the article

  • Databinding question: DataGridView <=> XDocument (using LINQ-to-XML)

    - by Pretzel
    Learning LINQ has been a lot of fun so far, but despite reading a couple books and a bunch of online resources on the topic, I still feel like a total n00b. Recently, I just learned that if my query returns an Anonymous type, the DataGridView I'm populating will be ReadOnly (because, apparently Anonymous types are ReadOnly.) Right now, I'm trying to figure out the easiest way to: Get a subset of data from an XML file into a DataGridView, Allow the user to edit said data, Stick the changed data back into the XML file. So far I have Steps 1 and 2 figured out: public class Container { public string Id { get; set; } public string Barcode { get; set; } public float Quantity { get; set; } } // For use with the Distinct() operator public class ContainerComparer : IEqualityComparer<Container> { public bool Equals(Container x, Container y) { return x.Id == y.Id; } public int GetHashCode(Container obj) { return obj.Id.GetHashCode(); } } var barcodes = (from src in xmldoc.Descendants("Container") where src.Descendants().Count() > 0 select new Container { Id = (string)src.Element("Id"), Barcode = (string)src.Element("Barcode"), Quantity = float.Parse((string)src.Element("Quantity").Attribute("value")) }).Distinct(new ContainerComparer()); dataGridView1.DataSource = barcodes.ToList(); This works great at getting the data I want from the XML into the DataGridView so that the user has a way to manipulate the values. Upon doing a Step-thru trace of my code, I'm finding that the changes to the values made in DataGridView are not bound to the XDocument object and as such, do not propagate back. How do we take care of Step 3? (getting the data back to the XML) Is it possible to Bind the XML directly to the DataGridView? Or do I have to write another LINQ statement to get the data from the DGV back to the XDocument? Suggstions?

    Read the article

  • Fast way to get a list of group members in Active Directory with C#

    - by Jeremy
    In a web app, we're looking to display a list of sam accounts for users that are a member of a certain group. Groups could have 500 or more members in many cases and we need the page to be responsive. With a group of about 500 members it takes 7-8 seconds to get a list of sam accounts for all members of the group. Are there faster ways? I know the Active Directory Management Console does it in under a second. I've tried a few methods: 1) PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain) GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup"); List<string> lst = grp.Members.Select(g => g.SamAccountName).ToList(); 2) PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain) GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup"); PrincipalSearchResult<Principal> lstMembers = grp.GetMembers(true); List<string> lst = new List<string>(); foreach (Principal member in lstMembers ) { if (member.StructuralObjectClass.Equals("user")) { lst.Add(member .SamAccountName); } } 3) PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain) GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup"); System.DirectoryServices.DirectoryEntry de = (System.DirectoryServices.DirectoryEntry)grp.GetUnderlyingObject(); List<string> lst = new List<string>(); foreach (string sDN in de.Properties["member"]) { System.DirectoryServices.DirectoryEntry deMember = new System.DirectoryServices.DirectoryEntry("LDAP://" + sDN); lst.Add(deMember.Properties["samAccountName"].Value.ToString()); }

    Read the article

  • MVC and repository pattern data efficiency

    - by Shawn Mclean
    My project is structured as follows: DAL public IQueryable<Post> GetPosts() { var posts = from p in context.Post select p; return posts; } Service public IList<Post> GetPosts() { var posts = repository.GetPosts().ToList(); return posts; } //Returns a list of the latest feeds, restricted by the count. public IList<PostFeed> GetPostFeeds(int latestCount) { List<Post> post - GetPosts(); //CODE TO CREATE FEEDS HERE return feeds; } Lets say the GetPostFeeds(5) is supposed to return the 5 latest feeds. By going up the list, doesn't it pull down every single post from the database from GetPosts(), just to extract 5 from it? If each post is say 5kb from the database, and there is 1 million records. Wont that be 5GB of ram being used per call to GetPostFeeds()? Is this the way it happens? Should I go back to my DAL and write queries that return only what I need?

    Read the article

  • ASP.Net MVC 3 Full Name In DropDownList

    - by tgriffiths
    I am getting a bit confused with this and need a little help please. I am developing a ASP.Net MVC 3 Web application using Entity Framework 4.1. I have a DropDownList on one of my Razor Views, and I wish to display a list of Full Names, for example Tom Jones Michael Jackson James Brown In my Controller I retrieve a List of User Objects, then select the FirstName and LastName of each User, and pass the data to a SelectList. List<User> Requesters = _userService.GetAllUsersByTypeIDOrgID(46, user.organisationID.Value).ToList(); var RequesterNames = from r in Requesters let person = new { UserID = r.userID, FullName = new { r.firstName, r.lastName } } orderby person.FullName ascending select person; viewModel.RequestersList = new SelectList(RequesterNames, "UserID", "FullName"); return View(viewModel); In my Razor View I have the following @Html.DropDownListFor(model => model.requesterID, Model.RequestersList, "Select", new { @class = "inpt_a"}) @Html.ValidationMessageFor(model => model.requesterID) However, when I run the code I get the following error At least one object must implement IComparable. I feel as if I am going about this the wrong way, so could someone please help with this? Thanks.

    Read the article

  • Example with Visitor Pattern

    - by devoured elysium
    public class Song { public string Genre { get; protected set; } public string Name { get; protected set; } public string Band { get; protected set; } public Song(string name, string band, string genre) { Name = name; Genre = genre; Band = band; } } public interface IMusicVisistor { void Visit(List<Song> items); } public class MusicLibrary { List<Song> _songs = new List<Song> { ...songs ... }; public void Accept(IMusicVisitor visitor) { visitor.Visit(_songs); } } and now here's one Visitor I made: public class RockMusicVisitor : IMusicVisitor { public List<Song> Songs { get; protected set; } public void Visit(List<Song> items) { Songs = items.Where(x => x.Genre == "Rock").ToList(); } } Why is this any better than just putting a public property Songs and then letting any kind of class do with it anything that it wants to? This example comes from this post.

    Read the article

  • Entity Framework with ASP.NET MVC. Updating entity problem

    - by Kitaly
    Hi people. I'm trying to update an entity and its related entities as well. For instance, I have a class Car with a property Category and I want to change its Category. So, I have the following methods in the Controller: public ActionResult Edit(int id) { var categories = context.Categories.ToList(); ViewData["categories"] = new SelectList(categories, "Id", "Name"); var car = context.Cars.Where(c => c.Id == id).First(); return PartialView("Form", car); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Car car) { var category = context.Categories.Where(c => c.Id == car.Category.Id).First(); car.Category = category; context.UpdateCar(car); context.SaveChanges(); return RedirectToAction("Index"); } The UpdateCar method, in ObjectContext class, follows: public void UpdateCar(Car car) { var attachedCar = Cars.Where(c => c.Id == car.Id).First(); ApplyItemUpdates(attachedCar, car); } private void ApplyItemUpdates(EntityObject originalItem, EntityObject updatedItem) { try { ApplyPropertyChanges(originalItem.EntityKey.EntitySetName, updatedItem); ApplyReferencePropertyChanges(updatedItem, originalItem); } catch (InvalidOperationException ex) { Console.WriteLine(ex.ToString()); } } public void ApplyReferencePropertyChanges(IEntityWithRelationships newEntity, IEntityWithRelationships oldEntity) { foreach (var relatedEnd in oldEntity.RelationshipManager.GetAllRelatedEnds()) { var oldRef = relatedEnd as EntityReference; if (oldRef != null) { var newRef = newEntity.RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference; oldRef.EntityKey = newRef.EntityKey; } } } The problem is that when I set the Category property after the POST in my controller, the entity state changes to Added instead of remaining as Detached. How can I update one-to-one relationship with Entity Framework and ASP.NET MVC without setting all the properties, one by one like this post?

    Read the article

  • vtk glyphs 3D, indenpently color and rotation

    - by user3684219
    I try to display thanks to vtk (python wrapper) several glyphs in a scene with each their own colour and rotation. Unfortunately, just the rotation (using vtkTensorGlyph) is taken in consideration by vtk. Reversely, just color is taken in consideration when I use a vtkGlyph3D. Here is a ready to use piece of code with a vtkTensorGlyph. Each cube should have a random color but there all will be in the same color. I read and read again the doc of vtk but I found no solution. Thanks in advance for any idea #!/usr/bin/env python # -*- coding: utf-8 -*- import vtk import scipy.linalg as sc import random as ra import numpy as np import itertools points = vtk.vtk.vtkPoints() # where to locate each glyph in the scene tensors = vtk.vtkDoubleArray() # rotation for each glyph tensors.SetNumberOfComponents(9) colors = vtk.vtkUnsignedCharArray() # should be the color for each glyph colors.SetNumberOfComponents(3) # let's make 10 cubes in the scene for i in range(0, 50, 5): points.InsertNextPoint(i, i, i) # position of a glyph colors.InsertNextTuple3(ra.randint(0, 255), ra.randint(0, 255), ra.randint(0, 255) ) # pick random color rot = list(itertools.chain(*np.reshape(sc.orth(np.random.rand(3, 3)).transpose(), (1, 9)).tolist())) # random rotation matrix (row major) tensors.InsertNextTuple9(*rot) polydata = vtk.vtkPolyData() # create the polydatas polydata.SetPoints(points) polydata.GetPointData().SetTensors(tensors) polydata.GetPointData().SetScalars(colors) cubeSource = vtk.vtkCubeSource() cubeSource.Update() glyphTensor = vtk.vtkTensorGlyph() glyphTensor.SetColorModeToScalars() # is it really work ? try: glyphTensor.SetInput(polydata) except AttributeError: glyphTensor.SetInputData(polydata) glyphTensor.SetSourceConnection(cubeSource.GetOutputPort()) glyphTensor.ColorGlyphsOn() # should not color all cubes independently ? glyphTensor.ThreeGlyphsOff() glyphTensor.ExtractEigenvaluesOff() glyphTensor.Update() # next is usual vtk code mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyphTensor.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) ren = vtk.vtkRenderer() ren.SetBackground(0.2, 0.5, 0.3) ren.AddActor(actor) renwin = vtk.vtkRenderWindow() renwin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) iren.SetRenderWindow(renwin) renwin.Render() iren.Initialize() renwin.Render() iren.Start()

    Read the article

  • Jquery AutoComplete Plugin calling

    - by martinezgeovani
    When I use JQuery's autocomplete and hardcode the array values in the page it works wonderful; but what I need to do is obtain the array values from either a web service or from a public function inside a controller. I have tried various way and can't seem to make it work. The farthest I got is pulling the data in to a long string and when the auto complete results are provided it's the long string which matches, which I understand why. $("#TaskEmailNotificationList").autocomplete("http://localhost/BetterTaskList/Accounts/registeredUsersEmailList", { multiple: true, mustMatch: false, multipleSeparator: ";", autoFill: true }); has anyone encountered this? I am using C#. UPDATE: The below code is a step forward I am now getting an array returned but I think I'm processing it wrong on my page. var emailList = "http://localhost/BetterTaskList/Account/RegisteredUsersEmailList"; $("#TaskEmailNotificationList").autocomplete(emailList, { multiple: true, mustMatch: false, multipleSeparator: ";", autoFill: true }); [HttpGet] public ActionResult RegisteredUsersEmailList() { BetterTaskListDataContext db = new BetterTaskListDataContext(); var emailList = from u in db.Users select u.LoweredUserName; return Json(emailList.ToList(), JsonRequestBehavior.AllowGet); }

    Read the article

  • Problem with .Contains

    - by Rene
    Hello there, I have a little problem which i can't solve. I want to use an SQL-In-Statement in Linq. I've read in this Forum and in other Forums that I have to use the .Contains (with reverse-thinking-notation :-)). As input i have a List of Guids. I first copied them into an array and then did something like that : datatoget = (from p in objectContext.MyDataSet where ArrayToSearch.Contains(p.Subtable.Id.ToString()) select p).ToList(); datatoget is the result in which all records matching the Subtable.Id (which is a Guid) should be stored. Subtable is a Detail-Table from MyData, and the Id is a Guid-Type. I've tried several things (Convert Guid to String, and then using .Contains, etc), but I always get an Exception which says : 'Linq to Entities' doesn't recognize the Method 'Boolean Contains(System.Guid) and is not able to Translate this method into a memory expression. (Something like that, because I'm using the German Version of VS2008) I am using L2E with .NET 3.5 and am programming in C# with VS 2008. I've read several Examples, but it doesn't work. Is it perhaps because of using Guid's instead of strings ? I've also tried to write my own compare-function, but I don't know how to integrate it so that .NET calls my function for comparing.

    Read the article

  • Can someone help me refactor this C# linq business logic for efficiency?

    - by Russell
    I feel like this is not a very efficient way of using linq. I was hoping somebody on here would have a suggestion for a refactor. I realize this code is not very pretty, as I was in a complete rush. public class Workflow { public void AssignForms() { using (var cntx = new ProjectBusiness.Providers.ProjectDataContext()) { var emplist = (from e in cntx.vw_EmployeeTaskLists where e.OwnerEmployeeID == null select e).ToList(); foreach (var emp in emplist) { // if employee has a form assigned: break; if (emp.GRADE > 15 || (emp.Pay_Plan.ToLower().Contains("al") || emp.Pay_Plan.ToLower().Contains("ex"))) { //Assign278(); } else if ((emp.Series.Contains("0905") || emp.Series.Contains("0511") || emp.Series.Contains("0110") || emp.Series.Contains("1801")) || (emp.GRADE >= 12 && emp.GRADE <= 15)) { var emptask = new ProjectBusiness.Providers.EmployeeTask(); emptask.TimespanID = cntx.Timespans.SingleOrDefault(t => t.BeginDate.Year == DateTime.Today.Year & t.EndDate.Year == DateTime.Today.Year).TimespanID; var FormID = (from f in cntx.Forms where f.FormName.Contains("450") select f.FormID).FirstOrDefault(); var TaskStatusID = (from s in cntx.TaskStatus where s.StatusDescription.ToLower() == "not started" select s.TaskStatusID).FirstOrDefault(); Assign450((int)emp.EmployeeID, FormID, TaskStatusID, emptask); cntx.EmployeeTasks.InsertOnSubmit(emptask); } else { //Assign185(); } } cntx.SubmitChanges(); } } private void Assign450(int EmployeeID, int FormID, int TaskStatusID, ProjectBusiness.Providers.EmployeeTask emptask) { emptask.FormID = FormID; emptask.OwnerEmployeeID = EmployeeID; emptask.AssignedToEmployeeID = EmployeeID; emptask.TaskStatusID = TaskStatusID; emptask.DueDate = DateTime.Today; } }

    Read the article

  • Using MinHash to find similiarities between 2 images

    - by Sung Meister
    I am using MinHash algorithm to find similar images between images. I have run across this post, How can I recognize slightly modified images? which pointed me to MinHash algorithm. Being a bit mathematically challenged, I was using a C# implementation from this blog post, Set Similarity and Min Hash. But while trying to use the implementation, I have run into 2 problems. What value should I set universe value to? When passing image byte array to HashSet, it only contains distinct byte values; thus comparing values from 1 ~ 256. What is this universe in MinHash? And what can I do to improve the C# MinHash implementation? Since HashSet<byte> contains values upto 256, similarity value always come out to 1. Here is the source that uses the C# MinHash implementation from Set Similarity and Min Hash: class Program { static void Main(string[] args) { var imageSet1 = GetImageByte(@".\Images\01.JPG"); var imageSet2 = GetImageByte(@".\Images\02.TIF"); //var app = new MinHash(256); var app = new MinHash(Math.Min(imageSet1.Count, imageSet2.Count)); double imageSimilarity = app.Similarity(imageSet1, imageSet2); Console.WriteLine("similarity = {0}", imageSimilarity); } private static HashSet<byte> GetImageByte(string imagePath) { using (var fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) using (var br = new BinaryReader(fs)) { //List<int> bytes = br.ReadBytes((int)fs.Length).Cast<int>().ToList(); var bytes = new List<byte>(br.ReadBytes((int) fs.Length).ToArray()); return new HashSet<byte>(bytes); } } }

    Read the article

  • Which LINQ expression is faster

    - by Vlad Bezden
    Hi All In following code public class Person { public string Name { get; set; } public uint Age { get; set; } public Person(string name, uint age) { Name = name; Age = age; } } void Main() { var data = new List<Person>{ new Person("Bill Gates", 55), new Person("Steve Ballmer", 54), new Person("Steve Jobs", 55), new Person("Scott Gu", 35)}; // 1st approach data.Where (x => x.Age > 40).ToList().ForEach(x => x.Age++); // 2nd approach data.ForEach(x => { if (x.Age > 40) x.Age++; }); data.ForEach(x => Console.WriteLine(x)); } in my understanding 2nd approach should be faster since it iterates through each item once and first approach is running 2 times: Where clause ForEach on subset of items from where clause. However internally it might be that compiler translates 1st approach to the 2nd approach anyway and they will have the same performance. Any suggestions or ideas? I could do profiling like suggested, but I want to understand what is going on compiler level if those to lines of code are the same to the compiler, or compiler will treat it literally. Thanks in advance for your help.

    Read the article

  • ObjectContext disposed puzzle

    - by jaklucky
    Hi, I have the follwing method. public List<MyEntity> GetMyEntities(MyObjectContext objCtx) { using(MyObjectContext ctx = objCtx ?? new MyObjectContext()) { retun ctx.MyEntities.ToList(); } } The idea is, user of this method can pass in the objectcontext if they have. If not then a new objectcontext will be created. If I am passing an object context to it, then it is getting disposed after the method is done. I was expecting only "ctx" variable gets disposed. If I write a small app, to know the using and dispose mechanism. It is acting differently. class TestClass : IDisposable { public int Number { get; set; } public string Str { get; set; } public ChildClass Child { get; set; } #region IDisposable Members public void Dispose() { Console.WriteLine("Disposed is called"); } #endregion } class ChildClass : IDisposable { public string StrChild { get; set; } #region IDisposable Members public void Dispose() { Console.WriteLine("Child Disposed is called"); } #endregion } class Program { static void Main(string[] args) { TestClass test = null; test = new TestClass(); test.Child = new ChildClass(); using (TestClass test1 = test ?? new TestClass()) { test1.Number = 1; test1.Str = "hi"; test1.Child.StrChild = "Child one"; test1.Child.Dispose(); } test.Str = "hi"; test.Child.StrChild = "hi child"; Console.ReadLine(); } } In this example, "test1"gets disposed but not "test". Where as in the first case both ctx and objCtx get disposed. Any ideas what is happening here with objectContext? Thank you, Suresh

    Read the article

  • checkbox like radiobutton wpf c#

    - by rockenpeace
    i have investigated this problem but this is solved in design view and code-behind. but my problem is little difference: i try to do this as only code-behind because my checkboxes are dynamically created according to database data.In other words, number of my checkboxes is not stable. i want to check only one checkbox in group of checkboxes. when i clicked one checkbox,i want that ischecked property of other checkboxes become false.this is same property in radiobuttons. i take my checkboxes from a stackpanel in xaml side: <StackPanel Margin="4" Orientation="Vertical" Grid.Row="1" Grid.Column="1" Name="companiesContainer"> </StackPanel> my xaml.cs: using (var c = new RSPDbContext()) { var q = (from v in c.Companies select v).ToList(); foreach (var na in q) { CheckBox ch = new CheckBox(); ch.Content = na.Name; ch.Tag = na; companiesContainer.Children.Add(ch); } } foreach (object i in companiesContainer.Children) { CheckBox chk = (CheckBox)i; chk.SetBinding(ToggleButton.IsCheckedProperty, "DataItem.IsChecked"); } how can i provide this property in checkboxes in xaml.cs ? thanks in advance..

    Read the article

  • What permissions do I need to grant to run RavenDB in Server mode?

    - by dalesmithtx
    I'm reading through Rob Ashton's excellent blog post on RavenDB: http://codeofrob.com/archive/2010/05/09/ravendb-an-introduction.aspx and I'm working through the code as I read. But when I try to add an index, I get a 401 error. Here's the code: class Program { static void Main(string[] args) { using (var documentStore = new DocumentStore() { Url = "http://localhost:8080" }) { documentStore.Initialise(); documentStore.DatabaseCommands.PutIndex( "BasicEntityBySomeData", new IndexDefinition<BasicEntity, BasicEntity>() { Map = docs => from doc in docs where doc.SomeData != null select new { SomeData = doc.SomeData }, }); string entityId; using (var documentSession = documentStore.OpenSession()) { var entity = new BasicEntity() { SomeData = "Hello, World!", SomeOtherData = "This is just another property", }; documentSession.Store(entity); documentSession.SaveChanges(); entityId = entity.Id; var loadedEntity = documentSession.Load<BasicEntity>(entityId); Console.WriteLine(loadedEntity.SomeData); var docs = documentSession.Query<BasicEntity>("BasicEntityBySomeData") .Where("SomeData:Hello~") .WaitForNonStaleResults() .ToArray(); docs.ToList().ForEach(doc => Console.WriteLine(doc.SomeData)); Console.Read(); } } } It throws the 401 error when on the line that makes the PutIndex() call. Any ideas what permissions I need to apply? And where I need to apply them?

    Read the article

  • Update one-to-many EntityKey using Foreign Key

    - by User.Anonymous
    To use by the easiest way Entity Framework, I use partial class to add Foreign Key on most important Entities Model. For example, I have an Entity "CONTACT" which have "TITLE", "FUNCTION" and others. When I update a CONTACT, with this code, Foreign Key are automatically updated : public int? TitId { get { if (this.TITLE_TIT != null) return TITLE_TIT.TIT_ID; return new Nullable<int>(); } set { this.TITLE_TITReference.EntityKey = new System.Data.EntityKey("Entities.TITLE_TIT", "TIT_ID", value); } } But I have a join with ACTIVITY, that can have many CONTACT, and I don't know how to update EntityKey on setters. public IEnumerable<EntityKeyMember> ActId { get { List<EntityKeyMember> lst = new List<EntityKeyMember>(); if (this.ACT_CON2 != null) { foreach (ACT_CON2 id in this.ACT_CON2.ToList()) { EntityKeyMember key = new EntityKeyMember(id.CON_ID.ToString(),id.ACT_ID); lst.Add(key); } } return lst; } set { this.ACT_CON2.EntityKey = new System.Data.EntityKey("Entities.ACT_CON2", value); } } How set many EntityKey ? Thank you.

    Read the article

  • Binding DataTemplates (or another aproach)

    - by Bataglião
    Hi all, I'm having some troubles trying to dynamically generate content in WPF and after it bind data. I have the following scenario: TabControl - Dynamically generated TabItems through DataTemplate - inside TabItems, I have dynamic content generated by DataTemplate that I wish to bind (ListBox). The code follows: ::TabControl <TabControl Height="252" HorizontalAlignment="Left" Name="tabControl1" VerticalAlignment="Top" Width="458" Margin="12,12,12,12" ContentTemplate="{StaticResource tabItemContent}"></TabControl> ::The Template for TabControl to generate TabItems <DataTemplate x:Key="tabItemContent"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*" /> </Grid.RowDefinitions> <ListBox ItemTemplate="{StaticResource listBoxContent}" ItemsSource="{Binding}"> </ListBox> </Grid> </DataTemplate> ::The template for ListBox Inside each TabItem <DataTemplate x:Key="listBoxContent"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="22"/> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Image Grid.Column="0" Source="{Binding Path=PluginIcon}" /> <TextBlock Grid.Column="1" Text="{Binding Path=Text}" /> </Grid> </DataTemplate> So, when I try to do this on code inside a loop to create the tabitems: TabItem tabitem = tabControl1.Items[catIndex] as TabItem; tabitem.DataContext = plugins.ToList(); where 'plugins' is an Enumerable The ListBox is not bounded. I tried also to find the ListBox inside the TabItem to set the ItemSource property but no success at all. Someone have an idea on how to do that? Thanks in advance.

    Read the article

  • Castle Active Record - Working with the cache

    - by David
    Hi All, im new to the Castle Active Record Pattern and Im trying to get my head around how to effectivley use cache. So what im trying to do (or want to do) is when calling the GetAll, find out if I have called it before and check the cache, else load it, but I also want to pass a bool paramter that will force the cache to clear and requery the db. So Im just looking for the final bits. thanks public static List<Model.Resource> GetAll(bool forceReload) { List<Model.Resource> resources = new List<Model.Resource>(); //Request to force reload if (forceReload) { //need to specify to force a reload (how?) XmlConfigurationSource source = new XmlConfigurationSource("appconfig.xml"); ActiveRecordStarter.Initialize(source, typeof(Model.Resource)); resources = Model.Resource.FindAll().ToList(); } else { //Check the cache somehow and return the cache? } return resources; } public static List<Model.Resource> GetAll() { return GetAll(false); }

    Read the article

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