Search Results

Search found 218 results on 9 pages for 'closures'.

Page 8/9 | < Previous Page | 4 5 6 7 8 9  | Next Page >

  • Converting ObjC Blocks to C# Lambas

    - by Sam
    I need some help converting an Objective-C block to C#. Here is the source ObjC: NSDate* addYear = [_calendar dateByAddingComponents:((^{ NSDateComponents* components = [NSDateComponents new]; components.month = 12; return components; })()) toDate:now options:0]; Now I tried the following in C#: NSDate date = _calendar.DateByAddingComponents((() => { NSDateComponents components = new NSDateComponents(); components.Month = 12; return components; })(), now, NSCalendarOptions.None); To which I get the following compiler error: Expression denotes a 'anonymous method' where a 'method group' was expected. Removing the parentheses around the lambda yields Cannot convert 'lambda expression' to non-delegate type 'MonoTouch.Foundation.NSDateComponents'. What is the correct C# syntax? I need to retain the closures as there are a lot more in the code base that I am porting.

    Read the article

  • Javascript: Access the right scope "under" apply(...)

    - by Chau
    This is a very old problem, but I cannot seem to get my head around the other solutions presented here. I have an object function ObjA() { var a = 1; this.methodA = function() { alert(a); } } which is instantiated like var myObjA = new ObjA(); Later on, I assign my methodA as a handler function in an external Javascript Framework, which invokes it using the apply(...) method. When the external framework executes my methodA, this belongs to the framework function invoking my method. Since I cannot change how my method is called, how do I regain access to the private variable a? My research tells me, that closures might be what I'm looking for.

    Read the article

  • What are the new features in Java 7

    - by T.K.
    What is the most official Java 7 feature list? I find very little useful information regarding this on the official JDK 7 site. Apart from that I can only find blogs with people summarizing "some" of the new features. However, some of these blog entries are old and some of them claim that these features "may or may not" be included in Java 7. Can anyone provide a list of features that will definitely be included in Java 7? I would also very much like to know the estimated release date. Will it be backwards compatible with my existing Java EE 6 stuff. That is, will I be able to switch seamlessly using EJBs, JPA2, Glassfish 3 and so on. The feature I am mostly interested in is Closures, so I'll happily switch to Java 7 as soon as a stable release comes out. Thanks!

    Read the article

  • Clojure for a lisp illiterate

    - by dbyrne
    I am a lifelong object-oriented programmer. My job is primarily java development, but I have experience in a number of languages. Ruby gave me my first real taste of functional programming. I loved the features Ruby borrowed from the functional paradigm such as closures and continuations. Eventually, I graduated to Scala. This has been a great way to gradually learn to approach non-trivial problems in a functional manner. Now I am interested in Clojure. I know all the sexy features that make it enticing (software transactional memory, macros, etc.), but I just can't get used to "thinking in lisp". I've seen Rich Hickey's screencasts aimed at java programmers, but they are geared towards explaining language features and not approaching real world problems. I am looking for any advice or resources which have made this transition easier for others.

    Read the article

  • What is the difference between an object's scope and it's context in javascript?

    - by DKinzer
    In the vernacular, scope and context have a lot in common. Which is why I get confused when I read references to both, such as in the quote below from an article on closures: Scope refers to where variables and functions are accessible, and in what context it is being executed. (@robertnyman) As far as I can tell, context is just a reference to an object. Can someone please explain what exactly is context, as used, for instance, in the jQuery syntax, $(selector, context). And is an object's scope the same at it's context?

    Read the article

  • Return a function from the anonymous wrapper?

    - by sabithpocker
    I am trying to undrstand the code for(var i = 0; i < 10; i++) { setTimeout((function(e) { return function() { console.log(e); } })(i), 1000) } from here http://bonsaiden.github.com/JavaScript-Garden/#function.closures I understood this method : for(var i = 0; i < 10; i++) { (function(e) { setTimeout(function() { console.log(e); }, 1000); })(i); } Can anyone please help me by explaining the first one?

    Read the article

  • how could I pass closure problems in order to increment a global var

    - by hyptos
    I have a simple goal, I would like to increment a variable but I'm facing the closure problem. I've read why this s happening here How do JavaScript closures work? But I can't find the solution to my problem :/ let's assume this part of code I took from the link. function say667() { // Local variable that ends up within closure var num = 666; var sayAlert = function() { alert(num); //incrementation } num++; return sayAlert; } I would like to increment num within the function and to keep the changes to num. How could I do that ? Here is the JsFiddle where I have my problem, I can't figure out how to increment my totalSize and keep it. http://jsfiddle.net/knLbv/2/ I don't want a local variable that ends up with closure.

    Read the article

  • Can I put google map functions into a closure?

    - by Joe
    I am trying to write some google map functionlity and playing around with javascript closures with an aim to try organise and structure my code better. I have the following code: var gmapFn ={ init : function(){ if (GBrowserIsCompatible()) { this.mapObj = new GMap2($("#map_canvas")); this.mapObj.setCenter(new google.maps.LatLng(51.512880,-0.134334),16); } } } Then I call it later in a jquery doc ready: $(document).ready(function() { gmapFn.init(); }) I have set up the google map keys and but I get an error on the main.js : uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://maps.gstatic.com/intl/en_ALL/mapfiles/193c/maps2.api/main.js :: ig :: line 170" data: no] QO() THe error seems to be thrown at the GBrowserIsCompatible() test which I beieve is down to me using this closure, is there a way to keep it in an closure and get init() working?

    Read the article

  • Are function arguments stored in a closure?

    - by Nick Lowman
    I was reading this great article about closures here and the example below outputs 'item3 undefined' three times. I understand why it outputs 'item3' three times as the functions inside buildList() all use the same single closure but why can't it access the 'list' argument? Why is it undefined? Is it because the argument is passed in after the closure has been created? function buildList(list) { var result = []; for (var i = 0; i < list.length; i++) { var item = 'item' + list[i]; result.push( function() {console.log(item + ' ' + list[i])} ); } return result; } function testList() { var fnlist = buildList([1,2,3]); // using j only to help prevent confusion - could use i for (var j = 0; j < fnlist.length; j++) { fnlist[j](); } }

    Read the article

  • Will my self-taught code be fine, or should I take it to the professional level?

    - by G1i1ch
    Lately I've been getting professional work, hanging out with other programmers, and making friends in the industry. The only thing is I'm 100% self-taught. It's caused my style to extremely deviate from the style of those that are properly trained. It's the techniques and organization of my code that's different. It's a mixture of several things I do. I tend to blend several programming paradigms together. Like Functional and OO. I lean to the Functional side more than OO, but I see the use of OO when something would make more sense as an abstract entity. Like a game object. Next I also go the simple route when doing something. When in contrast, it seems like sometimes the code I see from professional programmers is complicated for the sake of it! I use lots of closures. And lastly, I'm not the best commenter. I find it easier just to read through my code than reading the comment. And most cases I just end up reading the code even if there are comments. Plus I've been told that, because of how simply I write my code, it's very easy to read it. I hear professionally trained programmers go on and on about things like unit tests. Something I've never used before so I haven't even the faintest idea of what they are or how they work. Lots and lots of underscores "_", which aren't really my taste. Most of the techniques I use are straight from me, or a few books I've read. Don't know anything about MVC, I've heard a lot about it though with things like backbone.js. I think it's a way to organize an application. It just confuses me though because by now I've made my own organizational structures. It's a bit of a pain. I can't use template applications at all when learning something new like with Ubuntu's Quickly. I have trouble understanding code that I can tell is from someone trained. Complete OO programming really leaves a bad taste in my mouth, yet that seems to be what EVERYONE else is strictly using. It's left me not that confident in the look of my code, or wondering whether I'll cause sparks when joining a company or maybe contributing to open source projects. In fact I'm rather scared of the fact that people will eventually be checking out my code. Is this just something normal any programmer goes through or should I really look to change up my techniques?

    Read the article

  • How can a solo programmer become a good team player?

    - by Nick
    I've been programming (obsessively) since I was 12. I am fairly knowledgeable across the spectrum of languages out there, from assembly, to C++, to Javascript, to Haskell, Lisp, and Qi. But all of my projects have been by myself. I got my degree in chemical engineering, not CS or computer engineering, but for the first time this fall I'll be working on a large programming project with other people, and I have no clue how to prepare. I've been using Windows all of my life, but this project is going to be very unix-y, so I purchased a Mac recently in the hopes of familiarizing myself with the environment. I was fortunate to participate in a hackathon with some friends this past year -- both CS majors -- and excitingly enough, we won. But I realized as I worked with them that their workflow was very different from mine. They used Git for version control. I had never used it at the time, but I've since learned all that I can about it. They also used a lot of frameworks and libraries. I had to learn what Rails was pretty much overnight for the hackathon (on the other hand, they didn't know what lexical scoping or closures were). All of our code worked well, but they didn't understand mine, and I didn't understand theirs. I hear references to things that real programmers do on a daily basis -- unit testing, code reviews, but I only have the vaguest sense of what these are. I normally don't have many bugs in my little projects, so I have never needed a bug tracking system or tests for them. And the last thing is that it takes me a long time to understand other people's code. Variable naming conventions (that vary with each new language) are difficult (__mzkwpSomRidicAbbrev), and I find the loose coupling difficult. That's not to say I don't loosely couple things -- I think I'm quite good at it for my own work, but when I download something like the Linux kernel or the Chromium source code to look at it, I spend hours trying to figure out how all of these oddly named directories and files connect. It's a programming sin to reinvent the wheel, but I often find it's just quicker to write up the functionality myself than to spend hours dissecting some library. Obviously, people who do this for a living don't have these problems, and I'll need to get to that point myself. Question: What are some steps that I can take to begin "integrating" with everyone else? Thanks!

    Read the article

  • How to become a good team player?

    - by Nick
    I've been programming (obsessively) since I was 12. I am fairly knowledgeable across the spectrum of languages out there, from assembly, to C++, to Javascript, to Haskell, Lisp, and Qi. But all of my projects have been by myself. I got my degree in chemical engineering, not CS or computer engineering, but for the first time this fall I'll be working on a large programming project with other people, and I have no clue how to prepare. I've been using Windows all of my life, but this project is going to be very unix-y, so I purchased a Mac recently in the hopes of familiarizing myself with the environment. I was fortunate to participate in a hackathon with some friends this past year -- both CS majors -- and excitingly enough, we won. But I realized as I worked with them that their workflow was very different from mine. They used Git for version control. I had never used it at the time, but I've since learned all that I can about it. They also used a lot of frameworks and libraries. I had to learn what Rails was pretty much overnight for the hackathon (on the other hand, they didn't know what lexical scoping or closures were). All of our code worked well, but they didn't understand mine, and I didn't understand theirs. I hear references to things that real programmers do on a daily basis -- unit testing, code reviews, but I only have the vaguest sense of what these are. I normally don't have many bugs in my little projects, so I have never needed a bug tracking system or tests for them. And the last thing is that it takes me a long time to understand other people's code. Variable naming conventions (that vary with each new language) are difficult (__mzkwpSomRidicAbbrev), and I find the loose coupling difficult. That's not to say I don't loosely couple things -- I think I'm quite good at it for my own work, but when I download something like the Linux kernel or the Chromium source code to look at it, I spend hours trying to figure out how all of these oddly named directories and files connect. It's a programming sin to reinvent the wheel, but I often find it's just quicker to write up the functionality myself than to spend hours dissecting some library. Obviously, people who do this for a living don't have these problems, and I'll need to get to that point myself. Question: What are some steps that I can take to begin "integrating" with everyone else? Thanks!

    Read the article

  • Should i continue my self-taught coding practice or learn how to do coding professionally?

    - by G1i1ch
    Lately I've been getting professional work, hanging out with other programmers, and making friends in the industry. The only thing is I'm 100% self-taught. It's caused my style to extremely deviate from the style of those that are properly trained. It's the techniques and organization of my code that's different. It's a mixture of several things I do. I tend to blend several programming paradigms together. Like Functional and OO. I lean to the Functional side more than OO, but I see the use of OO when something would make more sense as an abstract entity. Like a game object. Next I also go the simple route when doing something. When in contrast, it seems like sometimes the code I see from professional programmers is complicated for the sake of it! I use lots of closures. And lastly, I'm not the best commenter. I find it easier just to read through my code than reading the comment. And most cases I just end up reading the code even if there are comments. Plus I've been told that, because of how simply I write my code, it's very easy to read it. I hear professionally trained programmers go on and on about things like unit tests. Something I've never used before so I haven't even the faintest idea of what they are or how they work. Lots and lots of underscores "_", which aren't really my taste. Most of the techniques I use are straight from me, or a few books I've read. Don't know anything about MVC, I've heard a lot about it though with things like backbone.js. I think it's a way to organize an application. It just confuses me though because by now I've made my own organizational structures. It's a bit of a pain. I can't use template applications at all when learning something new like with Ubuntu's Quickly. I have trouble understanding code that I can tell is from someone trained. Complete OO programming really leaves a bad taste in my mouth, yet that seems to be what EVERYONE else is strictly using. It's left me not that confident in the look of my code, or wondering whether I'll cause sparks when joining a company or maybe contributing to open source projects. In fact I'm rather scared of the fact that people will eventually be checking out my code. Is this just something normal any programmer goes through or should I really look to change up my techniques?

    Read the article

  • Evaluating Solutions to Manage Product Compliance? Don’t Wait Much Longer

    - by Evelyn Neumayr
    By Kerrie Foy, Director PLM Product Marketing, Oracle Depending on severity, product compliance issues can cause various problems from run-away budgets to business closures. But effective policies and safeguards can create a strong foundation for innovation, productivity, market penetration and competitive advantage. If you’ve been putting off a systematic approach to product compliance, it is time to reconsider that decision. Why now?  No matter what industry, companies face a litany of worldwide and regional regulations that require proof of product compliance and environmental friendliness for market access.  For example, Restriction of Hazardous Substances (RoHS), a regulation that restricts the use of six dangerous materials used in the manufacture of electronic and electrical equipment, was originally adopted by the European Union in 2003 for implementation in 2006 and has evolved over time through various regional versions for North America, China, Japan, Korea, Norway and Turkey. In addition, the RoHS directive allowed for material exemptions used in Medical Devices, but that exemption ends in 2014. Additional regulations worth watching are the Battery Directive, Waste Electrical and Electronic Equipment (WEEE), and Registration, Evaluation, Authorization and Restriction of Chemicals (REACH) directives. Additional regulations are expected from organizations such as the Food and Drug Administration in the US and similar organizations elsewhere. Meeting compliance requirements and also successfully investing in eco-friendly designs can be a major challenge. It may involve transforming business models, go-to-market strategies, supply networks, quality assurance policies and compliance processes.  Without a single source of truth for product data and without proper processes in place, ensuring product compliance burgeons into a crushing task that is cost-prohibitive and overwhelming.  However, the risk to consumer goodwill and satisfaction, revenue, business continuity, and market potential is too great not to solve the compliance challenge. Companies are beginning to adapt and thrive by implementing systematic approaches to product compliance that are more than functional bandages, they are revenue-generating engines. Consider working with Oracle to help you address your compliance needs. Many of the world’s most innovative leaders and pioneers are leveraging Oracle’s Agile Product Lifecycle Management (PLM) portfolio of enterprise applications to manage the product value chain, centralize product data, automate processes, and launch more eco-friendly products to market faster.   Particularly, the Agile Product Governance & Compliance (PG&C) solution provides out-of-the-box functionality to integrate actionable regulatory information into the enterprise product record from the ideation to the disposal/recycling phase.  Agile PG&C is a comprehensive solution that makes product compliance per corporate initiatives and regulations more reliable and efficient. Throughout product lifecycles, use the solution to support full material disclosures, gain rapid visibility into non-compliance issues, efficiently manage declarations with your suppliers, feed compliance data into a corrective action if a product must be changed, and swiftly satisfy audits by showing all due diligence tracked in one solution. Given the compounding regulation and consumer focus on urgent environmental issues, now is the time to act. Implementing an enterprise-wide systematic approach to product compliance is a competitive investment. From the start, Agile PG&C enables companies to confidently design for compliance and sustainability, reduce the cost of compliance, minimize the risk of business interruption, deliver responsible products, and inspire new innovation.  Don’t wait any longer! To find out more about Agile Product Governance & Compliance download the data sheet, contact your sales representative, or call Oracle at 1-800-633-0738.

    Read the article

  • Recover Lost Form Data in Firefox

    - by Asian Angel
    Have you ever filled in a text area or form in a webpage and something happens before you can finish it? If you like the idea of recovering that lost data then you will want to have a look at the Lazarus: Form Recovery extension for Firefox. Lazarus: Form Recovery in Action For our first example we chose the comment text box area for one of the articles here at the website. As you can see we were not finished typing in the whole comment yet… Notice the “Lazarus Icon” in the lower right corner. Note: We simulated accidental tab closures for our two examples. After getting our webpage opened up again all of our text was gone. Right clicking within the text area showed two options available…”Recover Text & Recover Form”. Notice that our lost text was listed as a “sub menu”…this could be extremely useful in matching up the appropriate text to the correct webpage if you had multiple tabs open before something happened. Click on the correct text listing to insert it. So easy to finish writing our comment without having to start from zero again. In our second example we chose the sign-up form page for the website. As before we were not finished filling in the form… Getting the webpage opened back up showed the same problem as before…all the entered text was lost. This time we right clicked in the browser window area and there was that wonderful “Recover Form Command” waiting to be used. One click and… All of our lost form data was back and we were able to finish filling in the form. For those who may be interested you can disable Lazarus: Form Recovery on individual websites using the “Context Menu” for the “Status Bar Icon” Options There are three sections in the options and you should take a quick look through them to make any desired modifications in how Lazarus: Form Recovery functions. The first “Options Area” focuses on display/access for the extension. The second “Options Area” allows you to expand the type of data retained, enable removal of data within a given time frame, set up a password, disable search indexing, and enable form data retention while in “Private Browsing Mode”. The third “Options Area” focuses on the Lazarus database itself. Conclusion If you have ever lost text area or form data before then you know how much time could be lost in starting over. Lazarus: Form Recovery helps provide a nice backup solution to get you up and running once again with a minimum of effort. Links Download the Lazarus: Form Recovery extension (Mozilla Add-ons) Download the Lazarus: Form Recovery extension (Extension Homepage) Similar Articles Productive Geek Tips Quick Tip: Resize Any Textbox or Textarea in FirefoxWhy Doesn’t AutoComplete Always Work in Firefox?Pass Variables between Windows Forms Windows without ShowDialog()Using Secure Login in FirefoxAdd Search Forms to the Firefox Search Bar TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips DVDFab 6 Revo Uninstaller Pro Registry Mechanic 9 for Windows PC Tools Internet Security Suite 2010 Looking for Good Windows Media Player 12 Plug-ins? Find Out the Celebrity You Resemble With FaceDouble Whoa ! Use Printflush to Solve Printing Problems Icelandic Volcano Webcams Open Multiple Links At One Go

    Read the article

  • Why were namespaces removed from ECMAScript consideration?

    - by Bob
    Namespaces were once a consideration for ECMAScript (the old ECMAScript 4) but were taken out. As Brendan Eich says in this message: One of the use-cases for namespaces in ES4 was early binding (use namespace intrinsic), both for performance and for programmer comprehension -- no chance of runtime name binding disagreeing with any earlier binding. But early binding in any dynamic code loading scenario like the web requires a prioritization or reservation mechanism to avoid early versus late binding conflicts. Plus, as some JS implementors have noted with concern, multiple open namespaces impose runtime cost unless an implementation works significantly harder. For these reasons, namespaces and early binding (like packages before them, this past April) must go. But I'm not sure I understand all of that. What exactly is a prioritization or reservation mechanism and why would either of those be needed? Also, must early binding and namespaces go hand-in-hand? For some reason I can't wrap my head around the issues involved. Can anyone attempt a more fleshed out explanation? Also, why would namespaces impose runtime costs? In my mind I can't help but see little difference in concept between a namespace and a function using closures. For instance, Yahoo and Google both have YAHOO and google objects that "act like" namespaces in that they contain all of their public and private variables, functions, and objects within a single access point. So why, then, would a namespace be so significantly different in implementation? Maybe I just have a misconception as to what a namespace is exactly.

    Read the article

  • Relation between [[Prototype]] and prototype in JavaScript

    - by Claudiu
    From http://www.jibbering.com/faq/faq_notes/closures.html : Note: ECMAScript defines an internal [[prototype]] property of the internal Object type. This property is not directly accessible with scripts, but it is the chain of objects referred to with the internal [[prototype]] property that is used in property accessor resolution; the object's prototype chain. A public prototype property exists to allow the assignment, definition and manipulation of prototypes in association with the internal [[prototype]] property. The details of the relationship between to two are described in ECMA 262 (3rd edition) and are beyond the scope of this discussion. What are the details of the relationship between the two? I've browsed through ECMA 262 and all I've read there is stuff like: The constructor’s associated prototype can be referenced by the program expression constructor.prototype, Native ECMAScript objects have an internal property called [[Prototype]]. The value of this property is either null or an object and is used for implementing inheritance. Every built-in function and every built-in constructor has the Function prototype object, which is the initial value of the expression Function.prototype Every built-in prototype object has the Object prototype object, which is the initial value of the expression Object.prototype (15.3.2.1), as the value of its internal [[Prototype]] property, except the Object prototype object itself. From this all I gather is that the [[Prototype]] property is equivalent to the prototype property for pretty much any object. Am I mistaken?

    Read the article

  • InvalidOperationException (Lambda parameter not in scope) when trying to Compile a Lambda Expression

    - by Moshe Levi
    Hello, I'm writing an Expression Parser to make my API more refactor friendly and less error prone. basicaly, I want the user to write code like that: repository.Get(entity => entity.Id == 10); instead of: repository.Get<Entity>("Id", 10); Extracting the member name from the left side of the binary expression was straight forward. The problems began when I tried to extract the value from the right side of the expression. The above snippet demonstrates the simplest possible case which involves a constant value but it can be much more complex involving closures and what not. After playing with that for some time I gave up on trying to cover all the possible cases myself and decided to use the framework to do all the heavy lifting for me by compiling and executing the right side of the expression. the relevant part of the code looks like that: public static KeyValuePair<string, object> Parse<T>(Expression<Func<T, bool>> expression) { var binaryExpression = (BinaryExpression)expression.Body; string memberName = ParseMemberName(binaryExpression.Left); object value = ParseValue(binaryExpression.Right); return new KeyValuePair<string, object>(memberName, value); } private static object ParseValue(Expression expression) { Expression conversionExpression = Expression.Convert(expression, typeof(object)); var lambdaExpression = Expression.Lambda<Func<object>>(conversionExpression); Func<object> accessor = lambdaExpression.Compile(); return accessor(); } Now, I get an InvalidOperationException (Lambda parameter not in scope) in the Compile line. when I googled for the solution I came up with similar questions that involved building an expression by hand and not supplying all the pieces, or trying to rely on parameters having the same name and not the same reference. I don't think that this is the case here because I'm reusing the given expression. I would appreciate if someone will give me some pointers on this. Thank you.

    Read the article

  • C# and F# lambda expressions code generation

    - by ControlFlow
    Let's look at the code, generated by F# for simple function: let map_add valueToAdd xs = xs |> Seq.map (fun x -> x + valueToAdd) The generated code for lambda expression (instance of F# functional value) will looks like this: [Serializable] internal class map_add@3 : FSharpFunc<int, int> { public int valueToAdd; internal map_add@3(int valueToAdd) { this.valueToAdd = valueToAdd; } public override int Invoke(int x) { return (x + this.valueToAdd); } } And look at nearly the same C# code: using System.Collections.Generic; using System.Linq; static class Program { static IEnumerable<int> SelectAdd(IEnumerable<int> source, int valueToAdd) { return source.Select(x => x + valueToAdd); } } And the generated code for the C# lambda expression: [CompilerGenerated] private sealed class <>c__DisplayClass1 { public int valueToAdd; public int <SelectAdd>b__0(int x) { return (x + this.valueToAdd); } } So I have some questions: Why does F#-generated class is not marked as sealed? Why does F#-generated class contains public fields since F# doesn't allows mutable closures? Why does F# generated class has the constructor? It may be perfectly initialized with the public fields... Why does C#-generated class is not marked as [Serializable]? Also classes generated for F# sequence expressions are also became [Serializable] and classes for C# iterators are not.

    Read the article

  • Wrapping FUSE from Go

    - by Matt Joiner
    I'm playing around with wrapping FUSE with Go. However I've come stuck with how to deal with struct fuse_operations. I can't seem to expose the operations struct by declaring type Operations C.struct_fuse_operations as the members are lower case, and my pure-Go sources would have to use C-hackery to set the members anyway. My first error in this case is "can't set getattr" in what looks to be the Go equivalent of a default copy constructor. My next attempt is to expose an interface that expects GetAttr, ReadLink etc, and then generate C.struct_fuse_operations and bind the function pointers to closures that call the given interface. This is what I've got (explanation continues after code): package fuse // #include <fuse.h> // #include <stdlib.h> import "C" import ( //"fmt" "os" "unsafe" ) type Operations interface { GetAttr(string, *os.FileInfo) int } func Main(args []string, ops Operations) int { argv := make([]*C.char, len(args) + 1) for i, s := range args { p := C.CString(s) defer C.free(unsafe.Pointer(p)) argv[i] = p } cop := new(C.struct_fuse_operations) cop.getattr = func(*C.char, *C.struct_stat) int {} argc := C.int(len(args)) return int(C.fuse_main_real(argc, &argv[0], cop, C.size_t(unsafe.Sizeof(cop)), nil)) } package main import ( "fmt" "fuse" "os" ) type CpfsOps struct { a int } func (me *CpfsOps) GetAttr(string, *os.FileInfo) int { return -1; } func main() { fmt.Println(os.Args) ops := &CpfsOps{} fmt.Println("fuse main returned", fuse.Main(os.Args, ops)) } This gives the following error: fuse.go:21[fuse.cgo1.go:23]: cannot use func literal (type func(*_Ctype_char, *_Ctype_struct_stat) int) as type *[0]uint8 in assignment I'm not sure what to pass to these members of C.struct_fuse_operations, and I've seen mention in a few places it's not possible to call from C back into Go code. If it is possible, what should I do? How can I provide the "default" values for interface functions that acts as though the corresponding C.struct_fuse_operations member is set to NULL?

    Read the article

  • Java SWT: wrapping syncExec and asyncExec to clean up code

    - by jonescb
    I have a Java Application using SWT as the toolkit, and I'm getting tired of all the ugly boiler plate code it takes to update a GUI element. Just to set a disabled button to be enabled I have to go through something like this: shell.getDisplay().asyncExec(new Runnable() { public void run() { buttonOk.setEnabled(true); } }); I prefer keeping my source code as flat as I possibly can, but I need a whopping 3 indentation levels just to do something simple. Is there some way I can wrap it? I would like a class like: public class UIUpdater { public static void updateUI(Shell shell, *function_ptr*) { shell.getDisplay().asyncExec(new Runnable() { public void run() { //Execute function_ptr } }); } } And can be used like so: UIUpdater.updateUI(shell, buttonOk.setEnabled(true)); Something like this would be great for hiding that horrible mess SWT seems to think is necessary to do anything. As I understand it, Java cannot do functions pointers. But Java 7 will have something called Closures which should be what I want. But in the meantime is there anything at all I can do to pass a function pointer or callback to another function to be executed? As an aside, I'm starting to think it'd be worth the effort to redo this application in Swing, and I don't have to put up with this ugly crap and non-cross-platformyness of SWT.

    Read the article

  • Should I define a single "DataContext" and pass references to it around or define muliple "DataConte

    - by Nate Bross
    I have a Silverlight application that consists of a MainWindow and several classes which update and draw images on the MainWindow. I'm now expanding this to keep track of everything in a database. Without going into specifics, lets say I have a structure like this: MainWindow Drawing-Surface Class1 -- Supports Drawing DataContext + DataServiceCollection<T> w/events Class2 -- Manages "transactions" (add/delete objects from drawing) Class3 Each "Class" is passed a reference to the Drawing Surface so they can interact with it independently. I'm starting to use WCF Data Services in Class1 and its working well; however, the other classes are also going to need access to the WCF Data Services. (Should I define my "DataContext" in MainWindow and pass a reference to each child class?) Class1 will need READ access to the "transactions" data, and Class2 will need READ access to some of the drawing data. So my question is, where does it make the most sense to define my DataContext? Does it make sense to: Define a "global" WCF Data Service "Context" object and pass references to that in all of my subsequent classes? Define an instance of the "Context" for each Class1, Class2, etc Have each method that requires access to data define its own instance of the "Context" and use closures handle the async load/complete events? Would a structure like this make more sense? Is there any danger in keeping an active "DataContext" open for an extended period of time? Typical usecase of this application could range from 1 minute to 40+ minutes. MainWindow Drawing-Surface DataContext Class1 -- Supports Drawing DataServiceCollection<DrawingType> w/events Class2 -- Manages "transactions" (add/delete objects from drawing) DataServiceCollection<TransactionType> w/events Class3 DataServiceCollection<T> w/events

    Read the article

  • jquery callback functions failing to finish execution

    - by calumbrodie
    I'm testing a jquery app i've written and have come across some unexpected behaviour $('button.clickme').live('click',function(){ //do x (takes 2 seconds) //do y (takes 4 seconds) //do z (takes 0.5 seconds) }) The event can be triggered by a number of buttons. What I'm finding is that when I click each button slowly (allowing 10 seconds between clicks) - my callback function executes correctly (actions x, y & z complete). However If I rapidly click buttons on my page it appears that the function sometimes only completes up to step x or y before terminating. My question: Is it the case that if this function is fired by a clicking second DOM element, while the first callback function is completing - will jQuery terminate the first callback and start over again? Do I have to write my callback function explicitly outside the event handler and then call it?? function doStuff() { //do x //do y //do z ( } $('button.clickme).live('click',doStuff()) If this is the case can someone explain why this is happening or give me a link to some advice on best practice on closures etc - I'd like to know the BEST way to write jQuery to improve performance etc. Thanks

    Read the article

  • Comparison of Java and .NET technologies/frameworks

    - by Paul Sasik
    I work in a shop that is a mix of mostly Java and .NET technologists. When discussing new solutions and architectures we often encounter impedance in trying to compare the various technologies, frameworks, APIs etc. in use between the two camps. It seems that each camp knows little about the other and we end up comparing apples to oranges and forgetting about the bushels. While researching the topic I found this: Java -- .Net rough equivalents It's a nice list but it's not quite exhaustive and is missing the key .NET 3.0 technologies and a few other tidbits. To complete that list: what are the near/rough equivalents (or a combination of technologies) in Java to the following in .NET? WCF WPF Silverlight = JavaFx WF = jBMP (Java Business Process Management) Generics Lambda expressions = lambdaJ project or Closures Linq (not Linq-to-SQL) ...have i missed anything else? Note that I omitted technologies that are already covered in the linked article. I would also like to hear feedback on whether the linked article is accurate. Thanks. (Will CW if requested.)

    Read the article

  • Is it possible to wrap an asynchronous event and its callback in a function that returns a boolean?

    - by Rob Flaherty
    I'm trying to write a simple test that creates an image element, checks the image attributes, and then returns true/false. The problem is that using the onload event makes the test asynchronous. On it own this isn't a problem (using a callback as I've done in the code below is easy), but what I can't figure out is how to encapsulate this into a single function that returns a boolean. I've tried various combinations of closures, recursion, and self-executing functions but have had no luck. So my question: am I being dense and overlooking something simple, or is this in fact not possible, because, no matter what, I'm still trying to wrap an asynchronous function in synchronous expectations? Here's the code: var supportsImage = function(callback) { var img = new Image(); img.onload = function() { //Check attributes and pass true or false to callback callback(true); }; img.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='; }; supportsImage(function(status){ console.log(status); }); To be clear, what I want is to be able to wrap this in something such that it can be used like: if (supportsImage) { //Do some crazy stuff } Thanks! (Btw, I know there are a ton of SO questions regarding confusion about synchronous vs. asynchronous. Apologies if this can be reduced to something previously answered.)

    Read the article

< Previous Page | 4 5 6 7 8 9  | Next Page >