Search Results

Search found 1037 results on 42 pages for 'lambda calculus'.

Page 11/42 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Setting a property from one collection to another collection

    - by ooo
    I have two colluections List<Application> myApps; List<Application> yourApps; These lists have overlapping overlapping data but they are coming from different sources and each source has some missing field data. Application object has a property called Description Both collections have a unique field called Key i want to see if there is a LINQ solution to: Loop through all applications in myApps and look at the key and see if that existing in yourApps. If it does, i want to take the description property from that application in yourApps and set the description property on the application on myApps to that same value i wanted to see if there was any slick way using lambda expressions (instead of having to have loops and a number of if statements.)

    Read the article

  • Need help programming with Mclauren series and Taylor series!

    - by user352258
    Ok so here's what i have so far: #include <stdio.h> #include <math.h> //#define PI 3.14159 int factorial(int n){ if(n <= 1) return(1); else return(n * factorial(n-1)); } void McLaurin(float pi){ int factorial(int); float x = 42*pi/180; int i, val=0, sign; for(i=1, sign=-1; i<11; i+=2){ sign *= -1; // alternate sign of cos(0) which is 1 val += (sign*(pow(x, i)) / factorial(i)); } printf("\nMcLaurin of 42 = %d\n", val); } void Taylor(float pi){ int factorial(int); float x; int i; float val=0.00, sign; float a = pi/3; printf("Enter x in degrees:\n"); scanf("%f", &x); x=x*pi/180.0; printf("%f",x); for(i=0, sign=-1.0; i<2; i++){ if(i%2==1) sign *= -1.0; // alternate sign of cos(0) which is 1 printf("%f",sign); if(i%2==1) val += (sign*sin(a)*(pow(x-a, i)) / factorial(i)); else val += (sign*cos(a)*(pow(x-a, i)) / factorial(i)); printf("%d",factorial(i)); } printf("\nTaylor of sin(%g degrees) = %d\n", (x*180.0)/pi, val); } main(){ float pi=3.14159; void McLaurin(float); void Taylor(float); McLaurin(pi); Taylor(pi); } and here's the output: McLaurin of 42 = 0 Enter x in degrees: 42 0.733038-1.00000011.0000001 Taylor of sin(42 degrees) = -1073741824 I suspect the reason for these outrageous numbers goes with the fact that I mixed up my floats and ints? But i just cant figure it out...!! Maybe its a math thing, but its never been a strength of mine let alone program with calculus. Also the Mclaurin fails, how does it equal zero? WTF! Please help correct my noobish code. I am still a beginner...

    Read the article

  • When is LINQ (to objects) Overused?

    - by Mystagogue
    My career started as a hard-core functional-paradigm developer (LISP), and now I'm a hard-care .net/C# developer. Of course I'm enamored with LINQ. However, I also believe in (1) using the right tool for the job and (2) preserving the KISS principle: of the 60+ engineers I work with, perhaps only 20% have hours of LINQ / functional paradigm experience, and 5% have 6 to 12 months of such experience. In short, I feel compelled to stay away from LINQ unless I'm hampered in achieving a goal without it (wherein replacing 3 lines of O-O code with one line of LINQ is not a "goal"). But now one of the engineers, having 12 months LINQ / functional-paradigm experience, is using LINQ to objects, or at least lambda expressions anyway, in every conceivable location in production code. My various appeals to the KISS principle have not yielded any results. Therefore... What published studies can I next appeal to? What "coding standard" guideline have others concocted with some success? Are there published LINQ performance issues I could point out? In short, I'm trying to achieve my first goal - KISS - by indirect persuasion. Of course this problem could be extended to countless other areas (such as overuse of extension methods). Perhaps there is an "uber" guide, highly regarded (e.g. published studies, etc), that takes a broader swing at this. Anything?

    Read the article

  • Lambdas within Extension methods: Possible memory leak?

    - by Oliver
    I just gave an answer to a quite simple question by using an extension method. But after writing it down i remembered that you can't unsubscribe a lambda from an event handler. So far no big problem. But how does all this behave within an extension method?? Below is my code snipped again. So can anyone enlighten me, if this will lead to myriads of timers hanging around in memory if you call this extension method multiple times? I would say no, cause the scope of the timer is limited within this function. So after leaving it no one else has a reference to this object. I'm just a little unsure, cause we're here within a static function in a static class. public static class LabelExtensions { public static Label BlinkText(this Label label, int duration) { Timer timer = new Timer(); timer.Interval = duration; timer.Tick += (sender, e) => { timer.Stop(); label.Font = new Font(label.Font, label.Font.Style ^ FontStyle.Bold); }; label.Font = new Font(label.Font, label.Font.Style | FontStyle.Bold); timer.Start(); return label; } }

    Read the article

  • Delegate within a delegate in VB.NET.

    - by Topdown
    I am trying to write a VB.NET alternative to a C# anonymous function. I wish to call Threading.SynchronizationContext.Current.Send which expects a delegate of type Threading.SendOrPostCallback to be passed to it. The background is here, but because I wish to both pass in a string to MessageBox.Show and also capture the DialogResult I need to define another delegate within. I am struggling with the VB.NET syntax, both from the traditional delegate style, and lambda functions. My go at the traditional syntax is below, but I have gut feeling it should be much simpler than this: Private Sub CollectMesssageBoxResultFromUserAsDelegate(ByVal messageToShow As String, ByRef wasCanceled As Boolean) wasCanceled = False If Windows.Forms.MessageBox.Show(String.Format("{0}{1}Please press [OK] to ignore this error and continue, or [Cancel] to stop here.", messageToShow), "Continue", Windows.Forms.MessageBoxButtons.OKCancel, Windows.Forms.MessageBoxIcon.Exclamation) = Windows.Forms.DialogResult.Cancel Then wasCanceled = True End If End Sub Private Delegate Sub ShowMessageBox(ByVal messageToShow As String, ByRef canceled As Boolean) Private Sub AskUserWhetherToCancel(ByVal message As String, ByVal args As CancelEventArgs) If args Is Nothing Then args = New System.ComponentModel.CancelEventArgs With {.Cancel = False} Dim wasCancelClicked As Boolean Dim firstDelegate As New ShowMessageBox(AddressOf CollectMesssageBoxResultFromUserAsDelegate) '…. Now what?? 'I can’t declare SendOrPostCallback as below: 'Dim myDelegate As New Threading.SendOrPostCallback(AddressOf firstDelegate) End Sub

    Read the article

  • linq-to-sql combine child expressions

    - by VictorS
    I need to create and combine several expressions for child entity into one to use it on "Any" operator of a parent. Code now looks like this: Expresion<Child, bool> startDateExpression = t => t.start_date >= startDate; Expression<Child, bool> endDateExpression = t => t.end_date <= endDate; .... ParameterExpression param = startDateExpression.Parameters[0]; Expression<Func<T, bool>> Combined = Expression.Lambda<Func<Child, bool>>( Expression.AndAlso(startDateExpression.Body, startDateExpression.Body), param); //but now I am trying to use combined expression on parent //this line fails just to give an idea on what I am trying to do: //filter type is IQueryable<Parent>; var filter = filter.Where(p =>p.Children.Any(Combined)); How can I do that? Is there better(more elegant way way of doing it?

    Read the article

  • How can I get this dynamic WHERE statement in my LINQ-to-XML to work?

    - by Edward Tanguay
    In this question Jon Skeet offered a very interesting solution to making a LINQ-to-XML statement dynamic, but my knowledge of lambdas and delegates is not yet advanced enough to implement it: I've got it this far, but of course I get the error "smartForm does not exist in the current context": private void LoadWithId(int id) { XDocument xmlDoc = null; try { xmlDoc = XDocument.Load(FullXmlDataStorePathAndFileName); } catch (Exception ex) { throw new Exception(String.Format("Cannot load XML file: {0}", ex.Message)); } Func<XElement, bool> whereClause = (int)smartForm.Element("id") == id"; var smartForms = xmlDoc.Descendants("smartForm") .Where(whereClause) .Select(smartForm => new SmartForm { Id = (int)smartForm.Element("id"), WhenCreated = (DateTime)smartForm.Element("whenCreated"), ItemOwner = smartForm.Element("itemOwner").Value, PublishStatus = smartForm.Element("publishStatus").Value, CorrectionOfId = (int)smartForm.Element("correctionOfId"), IdCode = smartForm.Element("idCode").Value, Title = smartForm.Element("title").Value, Description = smartForm.Element("description").Value, LabelWidth = (int)smartForm.Element("labelWidth") }); foreach (SmartForm smartForm in smartForms) { _collection.Add(smartForm); } } Ideally I want to be able to just say: var smartForms = GetSmartForms(smartForm=> (int) smartForm.Element("DisplayOrder").Value > 50); I've got it this far, but I'm just not grokking the lambda magic, how do I do this? public List<SmartForm> GetSmartForms(XDocument xmlDoc, XElement whereClause) { var smartForms = xmlDoc.Descendants("smartForm") .Where(whereClause) .Select(smartForm => new SmartForm { Id = (int)smartForm.Element("id"), WhenCreated = (DateTime)smartForm.Element("whenCreated"), ItemOwner = smartForm.Element("itemOwner").Value, PublishStatus = smartForm.Element("publishStatus").Value, CorrectionOfId = (int)smartForm.Element("correctionOfId"), IdCode = smartForm.Element("idCode").Value, Title = smartForm.Element("title").Value, Description = smartForm.Element("description").Value, LabelWidth = (int)smartForm.Element("labelWidth") }); }

    Read the article

  • List<object>.RemoveAll - How to create an appropriate Predicate

    - by CJM
    This is a bit of noob question - I'm still fairly new to C# and generics and completely new to predicates, delegates and lamda expressions... I have a class 'Enquiries' which contains a generic list of another class called 'Vehicles'. I'm building up the code to add/edit/delete Vehicles from the parent Enquiry. And at the moment, I'm specifically looking at deletions. From what I've read so far, it appears that I can use Vehicles.RemoveAll() to delete an item with a particular VehicleID or all items with a particular EnquiryID. My problem is understanding how to feed .RemoveAll the right predicate - the examples I have seen are too simplistic (or perhaps I am too simplistic given my lack of knowledge of predicates, delegates and lambda expressions). So if I had a List<Of Vehicle> Vehicles where each Vehicle had an EnquiryID, how would I use Vehicles.RemoveAll() to remove all vehicles for a given EnquiryID? I understand there are several approaches to this so I'd be keen to hear the differences between approaches - as much as I need to get something working, this is also a learning exercise. As an supplementary question, is a Generic list the best repository for these objects? My first inclination was towards a Collection, but it appears I am out of date. Certainly Generics seem to be preferred, but I'm curious as to other alternatives. Thanks

    Read the article

  • PHP: passing a function with parameters as parameter

    - by Oden
    Hey, I'm not sure that silly question, but I ask: So, if there is an anonymous function I can give it as another anonymous functions parameter, if it has been already stored a variable. But, whats in that case, if I have stored only one function in a variable, and add the second directly as a parameter into it? Can I add parameters to the non-stored function? Fist example (thats what i understand :) ): $func = function($str){ return $str; }; $func2 = function($str){ return $str; }; $var = $func($func2('asd')); var_dump($var); // prints out string(3) "asd" That makes sense for me, but what is with the following one? $func = function($str){ return $str; }; $var = $func(function($str = "asd"){ return $str; }); var_dump($var); /** This prints out: object(Closure)#1 (1) { ["parameter"]=> array(1) { ["$str"]=> string(10) "" } } But why? */ And at the end, can someone recommend me a book or an article, from what i can learn this lambda coding feature of php? Thank you in advance for your answers :)

    Read the article

  • Are function-local typedefs visible inside C++0x lambdas?

    - by GMan - Save the Unicorns
    I've run into a strange problem. The following simplified code reproduces the problem in MSVC 2010 Beta 2: template <typename T> struct dummy { static T foo(void) { return T(); } }; int main(void) { typedef dummy<bool> dummy_type; auto x = [](void){ bool b = dummy_type::foo(); }; // auto x = [](void){ bool b = dummy<bool>::foo(); }; // works } The typedef I created locally in the function doesn't seem to be visible in the lambda. If I replace the typedef with the actual type, it works as expected. Here are some other test cases: // crashes the compiler, credit to Tarydon int main(void) { struct dummy {}; auto x = [](void){ dummy d; }; } // works as expected int main(void) { typedef int integer; auto x = [](void){ integer i = 0; }; } I don't have g++ 4.5 available to test it, right now. Is this some strange rule in C++0x, or just a bug in the compiler? From the results above, I'm leaning towards bug. Though the crash is definitely a bug. For now, I have filed two bug reports. All code snippets above should compile. The error has to do with using the scope resolution on locally defined scopes. (Spotted by dvide.) And the crash bug has to do with... who knows. :) Update According to the bug reports, they have both been fixed for the next release of Visual Studio 2010.

    Read the article

  • WPF DataGrid populating blank rows on TreeView's SelectedItemChanged

    - by jes9582
    When my DataGrid populates on the TreeView's SelectedItemChanged event it finds the objects and creates the rows accordingly but the rows populate with no text or are just blank. So I know it is finding my objects but it is not displaying them properly. Does anyone see where I made an error or suggest any changes or fixes? Thank you in advance! Here is the CSharp code that is setting the DataGrid's ItemsSource (I am using .dbml and LINQ with Lambda expressions): dgSystemSettings.ItemsSource = (tvSystemConfiguration.SelectedItem as SYSTEM_SETTINGS_GROUP).SYSTEM_SETTINGS_NAMEs.Join(ssdc.SYSTEM_SETTINGS_VALUEs, x => x.SSN_ID, y => y.SSV_SSN_ID, (x, y) => new { SYSTEM_SETTINGS_NAME = x, SYSTEM_SETTINGS_VALUE = y }); And here is the .xaml: <DataGrid Name="dgSystemSettings" AutoGenerateColumns="False" Height="447" Width="513" DockPanel.Dock="Right" ItemsSource="{Binding}" VerticalAlignment="Top" Margin="10,10,0,0"> <DataGrid.Columns> <DataGridTextColumn x:Name="colDisplayName" Header="Name" Binding="{Binding SSN_DISPLAY_NAME}"></DataGridTextColumn> <DataGridTextColumn x:Name="colValue" Header="Value" Binding="{Binding SSV_VALUE}"></DataGridTextColumn> </DataGrid.Columns> </DataGrid>

    Read the article

  • Rails scalar query

    - by Craig
    I need to display a UI element (e.g. a star or checkmark) for employees that are 'favorites' of the current user (another employee). The Employee model has the following relationship defined to support this: has_and_belongs_to_many :favorites, :class_name => "Employee", :join_table => "favorites", :association_foreign_key => "favorite_id", :foreign_key => "employee_id" The favorites has two fields: employee_id, favorite_id. If I were to write SQL, the following query would give me the results that I want: SELECT id, account, IF( ( SELECT favorite_id FROM favorites WHERE favorite_id=p.id AND employee_id = ? ) IS NULL, FALSE, TRUE) isFavorite FROM employees Where the '?' would be replaced by the session[:user_id]. How do I represent the isFavorite scalar query in Rails? Another approach would use a query like this: SELECT id, account, IF(favorite_id IS NULL, FALSE, TRUE) isFavorite FROM employees e LEFT OUTER JOIN favorites f ON e.id=f.favorite_id AND employee_id = ? Again, the '?' is replaced by the session[:user_id] value. I've had some success writing this in Rails: ee=Employee.find(:all, :joins=>"LEFT OUTER JOIN favorites ON employees.id=favorites.favorite_id AND favorites.employee_id=1", :select=>"employees.*,favorites.favorite_id") Unfortunately, when I try to make this query 'dynamic' by replacing the '1' with a '?', I get errors. ee=Employee.find(:all, :joins=>["LEFT OUTER JOIN favorites ON employees.id=favorites.favorite_id AND favorites.employee_id=?",1], :select=>"employees.*,favorites.favorite_id") Obviously, I have the syntax wrong, but can :joins expressions be 'dynamic'? Is this a case for a Lambda expression? I do hope to add other filters to this query and use it with will_paginate and acts_as_taggable_on, if that makes a difference. edit errors from trying to make :joins dynamic: ActiveRecord::ConfigurationError: Association named 'LEFT OUTER JOIN favorites ON employees.id=favorites.favorite_id AND favorites.employee_id=?' was not found; perhaps you misspelled it? from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1906:in `build' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1911:in `build' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1910:in `each' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1910:in `build' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1830:in `initialize' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1789:in `new' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1789:in `add_joins!' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1686:in `construct_finder_sql' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1548:in `find_every' from /Users/craibuc/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:615:in `find'

    Read the article

  • Get the property, as a string, from an Expression<Func<TModel,TProperty>>

    - by Jaxidian
    I use some strongly-typed expressions that get serialized to allow my UI code to have strongly-typed sorting and searching expressions. These are of type Expression<Func<TModel,TProperty>> and are used as such: SortOption.Field = (p => p.FirstName);. I've gotten this working perfectly for this simple case. The code that I'm using for parsing the "FirstName" property out of there is actually reusing some existing functionality in a third-party product that we use and it works great, until we start working with deeply-nested properties(SortOption.Field = (p => p.Address.State.Abbreviation);). This code has some very different assumptions in the need to support deeply-nested properties. As for what this code does, I don't really understand it and rather than changing that code, I figured I should just write from scratch this functionality. However, I don't know of a good way to do this. I suspect we can do something better than doing a ToString() and performing string parsing. So what's a good way to do this to handle the trivial and deeply-nested cases? Requirements: Given the expression p => p.FirstName I need a string of "FirstName". Given the expression p => p.Address.State.Abbreviation I need a string of "Address.State.Abbreviation" While it's not important for an answer to my question, I suspect my serialization/deserialization code could be useful to somebody else who finds this question in the future, so it is below. Again, this code is not important to the question - I just thought it might help somebody. Note that DynamicExpression.ParseLambda comes from the Dynamic LINQ stuff and Property.PropertyToString() is what this question is about. /// <summary> /// This defines a framework to pass, across serialized tiers, sorting logic to be performed. /// </summary> /// <typeparam name="TModel">This is the object type that you are filtering.</typeparam> /// <typeparam name="TProperty">This is the property on the object that you are filtering.</typeparam> [Serializable] public class SortOption<TModel, TProperty> : ISerializable where TModel : class { /// <summary> /// Convenience constructor. /// </summary> /// <param name="property">The property to sort.</param> /// <param name="isAscending">Indicates if the sorting should be ascending or descending</param> /// <param name="priority">Indicates the sorting priority where 0 is a higher priority than 10.</param> public SortOption(Expression<Func<TModel, TProperty>> property, bool isAscending = true, int priority = 0) { Property = property; IsAscending = isAscending; Priority = priority; } /// <summary> /// Default Constructor. /// </summary> public SortOption() : this(null) { } /// <summary> /// This is the field on the object to filter. /// </summary> public Expression<Func<TModel, TProperty>> Property { get; set; } /// <summary> /// This indicates if the sorting should be ascending or descending. /// </summary> public bool IsAscending { get; set; } /// <summary> /// This indicates the sorting priority where 0 is a higher priority than 10. /// </summary> public int Priority { get; set; } #region Implementation of ISerializable /// <summary> /// This is the constructor called when deserializing a SortOption. /// </summary> protected SortOption(SerializationInfo info, StreamingContext context) { IsAscending = info.GetBoolean("IsAscending"); Priority = info.GetInt32("Priority"); // We just persisted this by the PropertyName. So let's rebuild the Lambda Expression from that. Property = DynamicExpression.ParseLambda<TModel, TProperty>(info.GetString("Property"), default(TModel), default(TProperty)); } /// <summary> /// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> to populate with data. </param> /// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for this serialization. </param> public void GetObjectData(SerializationInfo info, StreamingContext context) { // Just stick the property name in there. We'll rebuild the expression based on that on the other end. info.AddValue("Property", Property.PropertyToString()); info.AddValue("IsAscending", IsAscending); info.AddValue("Priority", Priority); } #endregion }

    Read the article

  • Using Lambda Expressions trees with IEnumerable

    - by Loathian
    I've been trying to learn more about using Lamba expression trees and so I created a simple example. Here is the code, this works in LINQPad if pasted in as a C# program. void Main() { IEnumerable<User> list = GetUsers().Where(NameContains("a")); list.Dump("Users"); } // Methods public IEnumerable<User> GetUsers() { yield return new User{Name = "andrew"}; yield return new User{Name = "rob"}; yield return new User{Name = "chris"}; yield return new User{Name = "ryan"}; } public Expression<Func<User, bool>> NameContains(string namePart) { return u => u.Name.Contains(namePart); } // Classes public class User { public string Name { get; set; } } This results in the following error: The type arguments for method 'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. However if I just substitute the first line in main with this: IEnumerable<User> list = GetUsers().Where(u => u.Name.Contains("a")); It works fine. Can tell me what I'm doing wrong, please?

    Read the article

  • Can't pass a single parameter to lambda function in MVVM Light Toolkit's RelayCommand

    - by Dave
    I don't know if there's a difference between Josh Smith's and Laurent Bugnion's implementations of RelayCommand or not, but everywhere I've looked, it sounds like the Execute portion of RelayCommand can take 0 or 1 parameters. I've only been able to get it to work with 0. When I try something like: public class Test { public RelayCommand MyCommand { get; set; } public Test() { MyCommand = new RelayCommand((param) => SomeFunc(param)); } private void SomeFunc( object param) { } } I get the error: Delegate 'System.Action' does not take '1' arguments. Just to make sure I am not insane, I went to the definition of RelayCommand to make sure I didn't have some rogue implementation in my solution somewhere, but sure enough, it was just Action, and not Action<. What on earth am I missing here?

    Read the article

  • Precompile Lambda Expression Tree conversions as constants?

    - by Nathan
    It is fairly common to take an Expression tree, and convert it to some other form, such as a string representation (for example this question and this question, and I suspect Linq2Sql does something similar). In many cases, perhaps even most cases, the Expression tree conversion will always be the same, i.e. if I have a function public string GenerateSomeSql(Expression<Func<TResult, TProperty>> expression) then any call with the same argument will always return the same result for example: GenerateSomeSql(x => x.Age) //suppose this will always return "select Age from Person" GenerateSomeSql(x => x.Ssn) //suppose this will always return "select Ssn from Person" So, in essence, the function call with a particular argument is really just a constant, except time is wasted at runtime re-computing it continuously. Assuming, for the sake of argument, that the conversion was sufficiently complex to cause a noticeable performance hit, is there any way to pre-compile the function call into an actual constant?

    Read the article

  • javascript scope problem when lambda function refers to a variable in enclosing loop

    - by Stefan Blixt
    First question on stackoverflow :) Hope I won't embarrass myself... I have a javascript function that loads a list of albums and then it creates a list item for each album. The list item should be clickable, so I call jQuery's click() with a function that does stuff. I do this in a loop. My problem is that all items seem to get the same click function, even though I try to make a new one that does different stuff in each iteration. Another possibility is that the iteration variable is global somehow, and the function refers to it. Code below. debug() is just an encapsulation of Firebug's console.debug(). function processAlbumList(data, c) { for (var album in data) { var newAlbum = $('<li class="albumLoader">' + data[album].title + '</li>').clone(); var clickAlbum = function() { debug("contents: " + album); }; debug("Album: " + album + "/" + data[album].title); $('.albumlist').append(newAlbum); $(newAlbum).click(clickAlbum); } } Here is a transcript of what it prints when the above function runs, after that are some debug lines caused by me clicking on different items. It always prints "10", which is the last value that the album variable takes (there are 10 albums). Album: 0/Live on radio.electro-music.com Album: 1/Doodles Album: 2/Misc Stuff Album: 3/Drawer Collection Album: 4/Misc Electronic Stuff Album: 5/Odds & Ends Album: 6/Tumbler Album: 7/Bakelit 32 Album: 8/Film Album: 9/Bakelit Album: 10/Slow Zoom/Atomic Heart contents: 10 contents: 10 contents: 10 contents: 10 contents: 10 Any ideas? Driving me up the wall, this is. :) /Stefan

    Read the article

  • Linq Queries converting to lambda expressions ?

    - by Freshblood
    Hello from item in range where item % 2 ==0 select i ; is converting to lamda expressions as below range.where(item % 2 ==0).select(x=>x). I feel that first way of linq is translating next one and if it is ,so is there any optimization like this range.where(item & 2 == 0) instead of other one ?

    Read the article

  • Pattern matching for lambda expressions

    - by alphomega
    21 --Primitive recursion constructor 22 pr :: ([Int] -> Int) -> ([Int] -> Int) -> ([Int] -> Int) 23 pr f g = \xs 0 -> f xs 24 pr f g = \xs (y+1) -> g xs y ((pr f g) xs y) I want the function this function creates to act differently on different inputs, so that it can create a recursive function. As expected, the above code doesn't work. How do I do something like pattern matching, but for the function it creates? Thanks

    Read the article

  • Creating Delegates With Lambda Expressions in F#

    - by Matt H
    Why does... type IntDelegate = delegate of int -> unit type ListHelper = static member ApplyDelegate (l : int list) (d : IntDelegate) = l |> List.iter (fun x -> d.Invoke x) ListHelper.ApplyDelegate [1..10] (fun x -> printfn "%d" x) not compile, when: type IntDelegate = delegate of int -> unit type ListHelper = static member ApplyDelegate (l : int list, d : IntDelegate) = l |> List.iter (fun x -> d.Invoke x) ListHelper.ApplyDelegate ([1..10], (fun x -> printfn "%d" x)) does? The only difference that is that in the second one, ApplyDelegate takes its parameters as a tuple. Error 1 This function takes too many arguments, or is used in a context where a function is not expected

    Read the article

  • How optimize by lambda expression

    - by simply denis
    I have a very similar function is only one previous report and the other future, how can I optimize and write beautiful? public bool AnyPreviousReportByGroup(int groupID) { if(this.GroupID == groupID) { return true; } else { return PreviousReport.AnyPreviousReportByGroup(groupID); } } public bool AnyNextReportByGroup(int groupID) { if (this.GroupID == groupID) { return true; } else { return NextReport.AnyNextReportByGroup(groupID); } }

    Read the article

  • Cannot we use break statement in a lambda(C#3.0)

    - by Newbie
    Consider this List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6 }; int j = 0; intList.ForEach(i => { if (i.Equals(1)) { j = i; break; } } ); Throwing error: No enclosing loop out of which to break or continue But the below works foreach(int i in intList) { j = i; break; } Why so. Am I making any mistake. Thanks

    Read the article

  • How to use objetcs as modules/functors in Scala?

    - by Jeff
    Hi. I want to use object instances as modules/functors, more or less as shown below: abstract class Lattice[E] extends Set[E] { val minimum: E val maximum: E def meet(x: E, y: E): E def join(x: E, y: E): E def neg(x: E): E } class Calculus[E](val lat: Lattice[E]) { abstract class Expr case class Var(name: String) extends Expr {...} case class Val(value: E) extends Expr {...} case class Neg(e1: Expr) extends Expr {...} case class Cnj(e1: Expr, e2: Expr) extends Expr {...} case class Dsj(e1: Expr, e2: Expr) extends Expr {...} } So that I can create a different calculus instance for each lattice (the operations I will perform need the information of which are the maximum and minimum values of the lattice). I want to be able to mix expressions of the same calculus but not be allowed to mix expressions of different ones. So far, so good. I can create my calculus instances, but problem is that I can not write functions in other classes that manipulate them. For example, I am trying to create a parser to read expressions from a file and return them; I also was trying to write an random expression generator to use in my tests with ScalaCheck. Turns out that every time a function generates an Expr object I can't use it outside the function. Even if I create the Calculus instance and pass it as an argument to the function that will in turn generate the Expr objects, the return of the function is not recognized as being of the same type of the objects created outside the function. Maybe my english is not clear enough, let me try a toy example of what I would like to do (not the real ScalaCheck generator, but close enough). def genRndExpr[E](c: Calculus[E], level: Int): Calculus[E]#Expr = { if (level > MAX_LEVEL) { val select = util.Random.nextInt(2) select match { case 0 => genRndVar(c) case 1 => genRndVal(c) } } else { val select = util.Random.nextInt(3) select match { case 0 => new c.Neg(genRndExpr(c, level+1)) case 1 => new c.Dsj(genRndExpr(c, level+1), genRndExpr(c, level+1)) case 2 => new c.Cnj(genRndExpr(c, level+1), genRndExpr(c, level+1)) } } } Now, if I try to compile the above code I get lots of error: type mismatch; found : plg.mvfml.Calculus[E]#Expr required: c.Expr case 0 = new c.Neg(genRndExpr(c, level+1)) And the same happens if I try to do something like: val boolCalc = new Calculus(Bool) val e1: boolCalc.Expr = genRndExpr(boolCalc) Please note that the generator itself is not of concern, but I will need to do similar things (i.e. create and manipulate calculus instance expressions) a lot on the rest of the system. Am I doing something wrong? Is it possible to do what I want to do? Help on this matter is highly needed and appreciated. Thanks a lot in advance.

    Read the article

  • parallel_for_each from amp.h – part 1

    - by Daniel Moth
    This posts assumes that you've read my other C++ AMP posts on index<N> and extent<N>, as well as about the restrict modifier. It also assumes you are familiar with C++ lambdas (if not, follow my links to C++ documentation). Basic structure and parameters Now we are ready for part 1 of the description of the new overload for the concurrency::parallel_for_each function. The basic new parallel_for_each method signature returns void and accepts two parameters: a grid<N> (think of it as an alias to extent) a restrict(direct3d) lambda, whose signature is such that it returns void and accepts an index of the same rank as the grid So it looks something like this (with generous returns for more palatable formatting) assuming we are dealing with a 2-dimensional space: // some_code_A parallel_for_each( g, // g is of type grid<2> [ ](index<2> idx) restrict(direct3d) { // kernel code } ); // some_code_B The parallel_for_each will execute the body of the lambda (which must have the restrict modifier), on the GPU. We also call the lambda body the "kernel". The kernel will be executed multiple times, once per scheduled GPU thread. The only difference in each execution is the value of the index object (aka as the GPU thread ID in this context) that gets passed to your kernel code. The number of GPU threads (and the values of each index) is determined by the grid object you pass, as described next. You know that grid is simply a wrapper on extent. In this context, one way to think about it is that the extent generates a number of index objects. So for the example above, if your grid was setup by some_code_A as follows: extent<2> e(2,3); grid<2> g(e); ...then given that: e.size()==6, e[0]==2, and e[1]=3 ...the six index<2> objects it generates (and hence the values that your lambda would receive) are:    (0,0) (1,0) (0,1) (1,1) (0,2) (1,2) So what the above means is that the lambda body with the algorithm that you wrote will get executed 6 times and the index<2> object you receive each time will have one of the values just listed above (of course, each one will only appear once, the order is indeterminate, and they are likely to call your code at the same exact time). Obviously, in real GPU programming, you'd typically be scheduling thousands if not millions of threads, not just 6. If you've been following along you should be thinking: "that is all fine and makes sense, but what can I do in the kernel since I passed nothing else meaningful to it, and it is not returning any values out to me?" Passing data in and out It is a good question, and in data parallel algorithms indeed you typically want to pass some data in, perform some operation, and then typically return some results out. The way you pass data into the kernel, is by capturing variables in the lambda (again, if you are not familiar with them, follow the links about C++ lambdas), and the way you use data after the kernel is done executing is simply by using those same variables. In the example above, the lambda was written in a fairly useless way with an empty capture list: [ ](index<2> idx) restrict(direct3d), where the empty square brackets means that no variables were captured. If instead I write it like this [&](index<2> idx) restrict(direct3d), then all variables in the some_code_A region are made available to the lambda by reference, but as soon as I try to use any of those variables in the lambda, I will receive a compiler error. This has to do with one of the direct3d restrictions, where only one type can be capture by reference: objects of the new concurrency::array class that I'll introduce in the next post (suffice for now to think of it as a container of data). If I write the lambda line like this [=](index<2> idx) restrict(direct3d), all variables in the some_code_A region are made available to the lambda by value. This works for some types (e.g. an integer), but not for all, as per the restrictions for direct3d. In particular, no useful data classes work except for one new type we introduce with C++ AMP: objects of the new concurrency::array_view class, that I'll introduce in the post after next. Also note that if you capture some variable by value, you could use it as input to your algorithm, but you wouldn’t be able to observe changes to it after the parallel_for_each call (e.g. in some_code_B region since it was passed by value) – the exception to this rule is the array_view since (as we'll see in a future post) it is a wrapper for data, not a container. Finally, for completeness, you can write your lambda, e.g. like this [av, &ar](index<2> idx) restrict(direct3d) where av is a variable of type array_view and ar is a variable of type array - the point being you can be very specific about what variables you capture and how. So it looks like from a large data perspective you can only capture array and array_view objects in the lambda (that is how you pass data to your kernel) and then use the many threads that call your code (each with a unique index) to perform some operation. You can also capture some limited types by value, as input only. When the last thread completes execution of your lambda, the data in the array_view or array are ready to be used in the some_code_B region. We'll talk more about all this in future posts… (a)synchronous Please note that the parallel_for_each executes as if synchronous to the calling code, but in reality, it is asynchronous. I.e. once the parallel_for_each call is made and the kernel has been passed to the runtime, the some_code_B region continues to execute immediately by the CPU thread, while in parallel the kernel is executed by the GPU threads. However, if you try to access the (array or array_view) data that you captured in the lambda in the some_code_B region, your code will block until the results become available. Hence the correct statement: the parallel_for_each is as-if synchronous in terms of visible side-effects, but asynchronous in reality.   That's all for now, we'll revisit the parallel_for_each description, once we introduce properly array and array_view – coming next. Comments about this post by Daniel Moth welcome at the original blog.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >