Search Results

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

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

  • A programming language that does not allow IO. Haskell is not a pure language

    - by TheIronKnuckle
    (I asked this on Stack Overflow and it got closed as off-topic, I was a bit confused until I read the FAQ, which discouraged subjective theoratical debate style questions. The FAQ here doesn't seem to have a problem with it and it sounds like this is a more appropriate place to post. If this gets closed again, forgive me, I'm not trying to troll) Are there any 100% pure languages (as I describe in the Stack Overflow post) out there already and if so, could they feasibly be used to actually do stuff? i.e. do they have an implementation? I'm not looking for raw maths on paper/Pure lambda calculus. However Pure lambda calculus with a compiler or a runtime system attached is something I'd be interested in hearing about.

    Read the article

  • Is it possible to learn maths via programming, or you should learn maths for programming?

    - by SAFAD
    I am not the best in maths, not very horrid either, but lower than the average, I've always been thinking to improve my maths, but schools and books didn't do the job because I get bored too fast. The only thing I don't get bored with is coding and gaming, so I thought what if coding a program that solves mathematical problems will help me understand maths better, most of these problems are limits (calculus), functions, Differential calculus, and some other subjects (I already said am not that good) similar to the previous noted. My question is: Am I able to achieve a better knowledge in maths if I do some specific program coding, and if possible, is physics possible that way too? Or am I wrong and Maths should be learned before programming to help improve my coding? P.S : C++ is the preferred language.

    Read the article

  • org-sort multi: date/time (?d ?t) | priority (?p) | title (?a)

    - by lawlist
    Is anyone aware of an org-sort function / modification that can refile / organize a group of TODO so that it sorts them by three (3) criteria: first sort by due date, second sort by priority, and third sort by by title of the task? EDIT: I believe that org-sort by deadline (?d) has a bug that cannot properly handle undated tasks. I am working on a workaround (i.e., moving the undated todo to a different heading before the deadline (?d) sort occurs), but perhaps the best thing to do would be to try and fix the original sorting function. Development of the workaround can be found in this thread (i.e., moving the undated tasks to a different heading in one fell swoop): How to automate org-refile for multiple todo EDIT: Apparently, the following code (ancient history) that I found on the internet was eventually modified and included as a part of org-sort-entries. Unfortunately, undated todo are not properly sorted when sorting by deadline -- i.e., they are mixed in with the dated todo. ;; multiple sort (defun org-sort-multi (&rest sort-types) "Multiple sorts on a certain level of an outline tree, or plain list items. SORT-TYPES is a list where each entry is either a character or a cons pair (BOOL . CHAR), where BOOL is whether or not to sort case-sensitively, and CHAR is one of the characters defined in `org-sort-entries-or-items'. Entries are applied in back to front order. Example: To sort first by TODO status, then by priority, then by date, then alphabetically (case-sensitive) use the following call: (org-sort-multi '(?d ?p ?t (t . ?a)))" (interactive) (dolist (x (nreverse sort-types)) (when (char-valid-p x) (setq x (cons nil x))) (condition-case nil (org-sort-entries (car x) (cdr x)) (error nil)))) ;; sort current level (defun lawlist-sort (&rest sort-types) "Sort the current org level. SORT-TYPES is a list where each entry is either a character or a cons pair (BOOL . CHAR), where BOOL is whether or not to sort case-sensitively, and CHAR is one of the characters defined in `org-sort-entries-or-items'. Entries are applied in back to front order. Defaults to \"?o ?p\" which is sorted by TODO status, then by priority" (interactive) (when (equal mode-name "Org") (let ((sort-types (or sort-types (if (or (org-entry-get nil "TODO") (org-entry-get nil "PRIORITY")) '(?d ?t ?p) ;; date, time, priority '((nil . ?a)))))) (save-excursion (outline-up-heading 1) (let ((start (point)) end) (while (and (not (bobp)) (not (eobp)) (<= (point) start)) (condition-case nil (outline-forward-same-level 1) (error (outline-up-heading 1)))) (unless (> (point) start) (goto-char (point-max))) (setq end (point)) (goto-char start) (apply 'org-sort-multi sort-types) (goto-char end) (when (eobp) (forward-line -1)) (when (looking-at "^\\s-*$") ;; (delete-line) ) (goto-char start) ;; (dotimes (x ) (org-cycle)) ))))) EDIT: Here is a more modern version of multi-sort, which is likely based upon further development of the above-code: (defun org-sort-all () (interactive) (save-excursion (goto-char (point-min)) (while (re-search-forward "^\* " nil t) (goto-char (match-beginning 0)) (condition-case err (progn (org-sort-entries t ?a) (org-sort-entries t ?p) (org-sort-entries t ?o) (forward-line)) (error nil))) (goto-char (point-min)) (while (re-search-forward "\* PROJECT " nil t) (goto-char (line-beginning-position)) (ignore-errors (org-sort-entries t ?a) (org-sort-entries t ?p) (org-sort-entries t ?o)) (forward-line)))) EDIT: The best option will be to fix sorting of deadlines (?d) so that undated todo are moved to the bottom of the outline, instead of mixed in with the dated todo. Here is an excerpt from the current org.el included within Emacs Trunk (as of July 1, 2013): (defun org-sort (with-case) "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'. Optional argument WITH-CASE means sort case-sensitively." (interactive "P") (cond ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case)) ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case)) (t (org-call-with-arg 'org-sort-entries with-case)))) (defun org-sort-remove-invisible (s) (remove-text-properties 0 (length s) org-rm-props s) (while (string-match org-bracket-link-regexp s) (setq s (replace-match (if (match-end 2) (match-string 3 s) (match-string 1 s)) t t s))) s) (defvar org-priority-regexp) ; defined later in the file (defvar org-after-sorting-entries-or-items-hook nil "Hook that is run after a bunch of entries or items have been sorted. When children are sorted, the cursor is in the parent line when this hook gets called. When a region or a plain list is sorted, the cursor will be in the first entry of the sorted region/list.") (defun org-sort-entries (&optional with-case sorting-type getkey-func compare-func property) "Sort entries on a certain level of an outline tree. If there is an active region, the entries in the region are sorted. Else, if the cursor is before the first entry, sort the top-level items. Else, the children of the entry at point are sorted. Sorting can be alphabetically, numerically, by date/time as given by a time stamp, by a property or by priority. The command prompts for the sorting type unless it has been given to the function through the SORTING-TYPE argument, which needs to be a character, \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the precise meaning of each character: n Numerically, by converting the beginning of the entry/item to a number. a Alphabetically, ignoring the TODO keyword and the priority, if any. o By order of TODO keywords. t By date/time, either the first active time stamp in the entry, or, if none exist, by the first inactive one. s By the scheduled date/time. d By deadline date/time. c By creation time, which is assumed to be the first inactive time stamp at the beginning of a line. p By priority according to the cookie. r By the value of a property. Capital letters will reverse the sort order. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be called with point at the beginning of the record. It must return either a string or a number that should serve as the sorting key for that record. Comparing entries ignores case by default. However, with an optional argument WITH-CASE, the sorting considers case as well." (interactive "P") (let ((case-func (if with-case 'identity 'downcase)) (cmstr ;; The clock marker is lost when using `sort-subr', let's ;; store the clocking string. (when (equal (marker-buffer org-clock-marker) (current-buffer)) (save-excursion (goto-char org-clock-marker) (looking-back "^.*") (match-string-no-properties 0)))) start beg end stars re re2 txt what tmp) ;; Find beginning and end of region to sort (cond ((org-region-active-p) ;; we will sort the region (setq end (region-end) what "region") (goto-char (region-beginning)) (if (not (org-at-heading-p)) (outline-next-heading)) (setq start (point))) ((or (org-at-heading-p) (condition-case nil (progn (org-back-to-heading) t) (error nil))) ;; we will sort the children of the current headline (org-back-to-heading) (setq start (point) end (progn (org-end-of-subtree t t) (or (bolp) (insert "\n")) (org-back-over-empty-lines) (point)) what "children") (goto-char start) (show-subtree) (outline-next-heading)) (t ;; we will sort the top-level entries in this file (goto-char (point-min)) (or (org-at-heading-p) (outline-next-heading)) (setq start (point)) (goto-char (point-max)) (beginning-of-line 1) (when (looking-at ".*?\\S-") ;; File ends in a non-white line (end-of-line 1) (insert "\n")) (setq end (point-max)) (setq what "top-level") (goto-char start) (show-all))) (setq beg (point)) (if (>= beg end) (error "Nothing to sort")) (looking-at "\\(\\*+\\)") (setq stars (match-string 1) re (concat "^" (regexp-quote stars) " +") re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]") txt (buffer-substring beg end)) (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n"))) (if (and (not (equal stars "*")) (string-match re2 txt)) (error "Region to sort contains a level above the first entry")) (unless sorting-type (message "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc [t]ime [s]cheduled [d]eadline [c]reated A/N/P/R/O/F/T/S/D/C means reversed:" what) (setq sorting-type (read-char-exclusive)) (and (= (downcase sorting-type) ?f) (setq getkey-func (org-icompleting-read "Sort using function: " obarray 'fboundp t nil nil)) (setq getkey-func (intern getkey-func))) (and (= (downcase sorting-type) ?r) (setq property (org-icompleting-read "Property: " (mapcar 'list (org-buffer-property-keys t)) nil t)))) (message "Sorting entries...") (save-restriction (narrow-to-region start end) (let ((dcst (downcase sorting-type)) (case-fold-search nil) (now (current-time))) (sort-subr (/= dcst sorting-type) ;; This function moves to the beginning character of the "record" to ;; be sorted. (lambda nil (if (re-search-forward re nil t) (goto-char (match-beginning 0)) (goto-char (point-max)))) ;; This function moves to the last character of the "record" being ;; sorted. (lambda nil (save-match-data (condition-case nil (outline-forward-same-level 1) (error (goto-char (point-max)))))) ;; This function returns the value that gets sorted against. (lambda nil (cond ((= dcst ?n) (if (looking-at org-complex-heading-regexp) (string-to-number (match-string 4)) nil)) ((= dcst ?a) (if (looking-at org-complex-heading-regexp) (funcall case-func (match-string 4)) nil)) ((= dcst ?t) (let ((end (save-excursion (outline-next-heading) (point)))) (if (or (re-search-forward org-ts-regexp end t) (re-search-forward org-ts-regexp-both end t)) (org-time-string-to-seconds (match-string 0)) (org-float-time now)))) ((= dcst ?c) (let ((end (save-excursion (outline-next-heading) (point)))) (if (re-search-forward (concat "^[ \t]*\\[" org-ts-regexp1 "\\]") end t) (org-time-string-to-seconds (match-string 0)) (org-float-time now)))) ((= dcst ?s) (let ((end (save-excursion (outline-next-heading) (point)))) (if (re-search-forward org-scheduled-time-regexp end t) (org-time-string-to-seconds (match-string 1)) (org-float-time now)))) ((= dcst ?d) (let ((end (save-excursion (outline-next-heading) (point)))) (if (re-search-forward org-deadline-time-regexp end t) (org-time-string-to-seconds (match-string 1)) (org-float-time now)))) ((= dcst ?p) (if (re-search-forward org-priority-regexp (point-at-eol) t) (string-to-char (match-string 2)) org-default-priority)) ((= dcst ?r) (or (org-entry-get nil property) "")) ((= dcst ?o) (if (looking-at org-complex-heading-regexp) (- 9999 (length (member (match-string 2) org-todo-keywords-1))))) ((= dcst ?f) (if getkey-func (progn (setq tmp (funcall getkey-func)) (if (stringp tmp) (setq tmp (funcall case-func tmp))) tmp) (error "Invalid key function `%s'" getkey-func))) (t (error "Invalid sorting type `%c'" sorting-type)))) nil (cond ((= dcst ?a) 'string<) ((= dcst ?f) compare-func) ((member dcst '(?p ?t ?s ?d ?c)) '<))))) (run-hooks 'org-after-sorting-entries-or-items-hook) ;; Reset the clock marker if needed (when cmstr (save-excursion (goto-char start) (search-forward cmstr nil t) (move-marker org-clock-marker (point)))) (message "Sorting entries...done"))) (defun org-do-sort (table what &optional with-case sorting-type) "Sort TABLE of WHAT according to SORTING-TYPE. The user will be prompted for the SORTING-TYPE if the call to this function does not specify it. WHAT is only for the prompt, to indicate what is being sorted. The sorting key will be extracted from the car of the elements of the table. If WITH-CASE is non-nil, the sorting will be case-sensitive." (unless sorting-type (message "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:" what) (setq sorting-type (read-char-exclusive))) (let ((dcst (downcase sorting-type)) extractfun comparefun) ;; Define the appropriate functions (cond ((= dcst ?n) (setq extractfun 'string-to-number comparefun (if (= dcst sorting-type) '< '>))) ((= dcst ?a) (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x)) (lambda(x) (downcase (org-sort-remove-invisible x)))) comparefun (if (= dcst sorting-type) 'string< (lambda (a b) (and (not (string< a b)) (not (string= a b))))))) ((= dcst ?t) (setq extractfun (lambda (x) (if (or (string-match org-ts-regexp x) (string-match org-ts-regexp-both x)) (org-float-time (org-time-string-to-time (match-string 0 x))) 0)) comparefun (if (= dcst sorting-type) '< '>))) (t (error "Invalid sorting type `%c'" sorting-type))) (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x))) table) (lambda (a b) (funcall comparefun (car a) (car b))))))

    Read the article

  • Mocking Sort With Mocha

    - by josephmate
    How can I mock an array's sort expect a lambda expression? This is a trivial example of my problem: # initializing the data l = lambda { |a,b| a <=> b } array = [ 1, 2, 3, 4, 5 ] sorted_array = [ 2, 3, 8, 9, 1] # I expect that sort will be called using the lambda as a parameter array.expects(:sort).with( l ).returns( sorted_array ) # perform the sort using the lambda expression temp = array.sort{|a,b| l.call(a,b) } Now, at first I expected that this would work; however, I got the following error: - expected exactly once, not yet invoked: [ 1, 2, 3, 4, 5 ].sort(#<Proc:0xb665eb48>) Is there a way to do what I am looking for? Cheers, Joseph

    Read the article

  • typesafe NotifyPropertyChanged using linq expressions

    - by bitbonk
    Form Build your own MVVM I have the following code that lets us have typesafe NotifyOfPropertyChange calls: public void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property) { var lambda = (LambdaExpression)property; MemberExpression memberExpression; if (lambda.Body is UnaryExpression) { var unaryExpression = (UnaryExpression)lambda.Body; memberExpression = (MemberExpression)unaryExpression.Operand; } else memberExpression = (MemberExpression)lambda.Body; NotifyOfPropertyChange(memberExpression.Member.Name); } How does this approach compare to standard simple strings approach performancewise? Sometimes I have properties that change at a very high frequency. Am I safe to use this typesafe aproach? After some first tests it does seem to make a small difference. How much CPU an memory load does this approach potentially induce?

    Read the article

  • Python del() built-in can't be used in assignment?

    - by emcee
    I noticed a problem when I was trying to use del in a lambda to thin out a list of threads to just those running: map(lambda x: del(x) if not x.isAlive() else x, self.threads) Ignore for a second that this doesn't do anything, I'm just fooling around with map, reduce, and lambda. This fails with a syntax error at del(x). With some messing around, I think the problem is del() doesn't return a value. For example, this fails with the same error: b = 5 x = del(b) This doesn't, however: def rmThis(x): del(x) Which means I'm using this workaround: map(lambda x: rmThis(x) if not x.isAlive() else x, self.threads) So is the limitation just because del() doesn't return a value? Why not? I'm using python 2.6.2

    Read the article

  • A problem with assertRaises function in Python

    - by anton.k.
    Hello,guys! I am trying to run the following test self.assertRaises(Exception,lambda: unit_test.testBasic()) where test.testBasic() is class IsPrimeTest(unittest.TestCase): def assertRaises(self,exception,callable,*args,**kwargs): print('dfdf') temp = callable super().assertRaises(exception,temp,*args,**kwargs) def testBasic_helper(self): self.failIf(is_prime(2)) self.assertTrue(is_prime(1)) where prime is a function,and but in self.assertRaises(Exception,lambda: unit_test.testBasic()) the lambda function doesnt throws an exception after the test def testBasic_helper(self): self.failIf(is_prime(2)) self.assertTrue(is_prime(1)) fails Can somebody offers a solution to the problem?

    Read the article

  • Why are closures broken within exec?

    - by Devin Jeanpierre
    In Python 2.6, >>> exec "print (lambda: a)()" in dict(a=2), {} 2 >>> exec "print (lambda: a)()" in globals(), {'a': 2} Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> File "<string>", line 1, in <lambda> NameError: global name 'a' is not defined >>> exec "print (lambda: a).__closure__" in globals(), {'a': 2} None I expected it to print 2 twice, and then print a tuple with a single cell. It is the same situation in 3.1. What's going on?

    Read the article

  • Why do all procedures have to be defined before the compiler sees them?

    - by incrediman
    For example, take a look at this code (from tspl4): (define proc1 (lambda (x y) (proc2 y x))) If I run this as my program in scheme... #!r6rs (import (rnrs)) (define proc1 (lambda (x y) (proc2 y x))) I get this error: expand: unbound identifier in module in: proc2 ...This code works fine though: #!r6rs (import (rnrs)) (define proc2 +) (define proc1 (lambda (x y) (proc2 y x))) (display (proc1 2 3)) ;output: 5

    Read the article

  • filtering elements from list of lists in Python?

    - by user248237
    I want to filter elements from a list of lists, and iterate over the elements of each element using a lambda. For example, given the list: a = [[1,2,3],[4,5,6]] suppose that I want to keep only elements where the sum of the list is greater than N. I tried writing: filter(lambda x, y, z: x + y + z >= N, a) but I get the error: <lambda>() takes exactly 3 arguments (1 given) How can I iterate while assigning values of each element to x, y, and z? Something like zip, but for arbitrarily long lists. thanks, p.s. I know I can write this using: filter(lambda x: sum(x)..., a) but that's not the point, imagine that these were not numbers but arbitrary elements and I wanted to assign their values to variable names.

    Read the article

  • How do i pass a number from a list as a parameter in scheme?

    - by wyatt
    I need to take a number from a list and convert it to a number so that i can pass it as a parameter. im trying to make a 1-bit adder in scheme. i've written the code for the or gate and the xor gate and also the half adder and now im trying to combine them all to make a full adder. im not sure if im going about it the right way. any input will be appreciated thank you. (define or-gate (lambda (a b) (if (= a 1) 1 (if (= b 1) 1 0)))) (define xor-gate (lambda (a b) (if (= a b) 0 1))) (define ha (lambda (a b) (list (xor-gate a b)(and-gate a b)))) (define fa (lambda (a b cin) (or-gate (cdr(ha cin (car (ha a b))))(cdr(ha a b))))) the issue i get when i run the program is that the half adder (ha) function outputs a list as a value and that makes the values incompatible with my other procedures because they require numbers and not lists. i feel like there is a simple solution but i dont know it.

    Read the article

  • C# Dev - I've tried Lisps, but I don't get it.

    - by Jonathan Mitchem
    After a few months of learning about and playing with lisps, both CL and a bit of Clojure, I'm still not seeing a compelling reason to write anything in it instead of C#. I would really like some compelling reasons, or for someone to point out that I'm missing something really big. The strengths of a Lisp (per my research): Compact, expressive notation - More so than C#, yes... but I seem to be able to express those ideas in C# too. Implicit support for functional programming - C# with LINQ extension methods: mapcar = .Select( lambda ) mapcan = .Select( lambda ).Aggregate( (a,b) = a.Union(b) ) car/first = .First() cdr/rest = .Skip(1) .... etc. Lambda and higher-order function support - C# has this, and the syntax is arguably simpler: "(lambda (x) ( body ))" versus "x = ( body )" "#(" with "%", "%1", "%2" is nice in Clojure Method dispatch separated from the objects - C# has this through extension methods Multimethod dispatch - C# does not have this natively, but I could implement it as a function call in a few hours Code is Data (and Macros) - Maybe I haven't "gotten" macros, but I haven't seen a single example where the idea of a macro couldn't be implemented as a function; it doesn't change the "language", but I'm not sure that's a strength DSLs - Can only do it through function composition... but it works Untyped "exploratory" programming - for structs/classes, C#'s autoproperties and "object" work quite well, and you can easily escalate into stronger typing as you go along Runs on non-Windows hardware - Yeah, so? Outside of college, I've only known one person who doesn't run Windows at home, or at least a VM of Windows on *nix/Mac. (Then again, maybe this is more important than I thought and I've just been brainwashed...) The REPL for bottom-up design - Ok, I admit this is really really nice, and I miss it in C#. Things I'm missing in a Lisp (due to a mix of C#, .NET, Visual Studio, Resharper): Namespaces. Even with static methods, I like to tie them to a "class" to categorize their context (Clojure seems to have this, CL doesn't seem to.) Great compile and design-time support the type system allows me to determine "correctness" of the datastructures I pass around anything misspelled is underlined realtime; I don't have to wait until runtime to know code improvements (such as using an FP approach instead of an imperative one) are autosuggested GUI development tools: WinForms and WPF (I know Clojure has access to the Java GUI libraries, but they're entirely foreign to me.) GUI Debugging tools: breakpoints, step-in, step-over, value inspectors (text, xml, custom), watches, debug-by-thread, conditional breakpoints, call-stack window with the ability to jump to the code at any level in the stack (To be fair, my stint with Emacs+Slime seemed to provide some of this, but I'm partial to the VS GUI-driven approach) I really like the hype surrounding Lisps and I gave it a chance. But is there anything I can do in a Lisp that I can't do as well in C#? It might be a bit more verbose in C#, but I also have autocomplete. What am I missing? Why should I use Clojure/CL?

    Read the article

  • StructureMap Autowiring with two different instances of the same interface

    - by Lambda
    For the last two days, i tried my best to learn something about StructureMap, using an old project of mine as an concrete implementation example. I tried to simplify my question as much as possible. While i will post my examples in vb.net, answers with examples in C# are also okay. The project includes an interfaces called IDatabase which connects itself to a Database. The important part looks like this. Public Interface IDatabase Function Connect(ByVal ConnectionSettings As ConnectionSettings) As Boolean ReadOnly Property ConnectionOpen As Boolean [... more functions...] End Interface Public Class MSSQLConnection Implements IDatabase Public Function Connect(ByVal ConnectionSettings As ConnectionSettings) As Boolean Implements IDatabase.Connect [... Implementation ...] End Function [... more implementations...] End Class ConnectionSettings is a structure that has all the information needed to connect to a Database. I want to open the Database Connection once and use it for every single connection in the project, so i register a instance in the ObjectFactory. dim foo = ObjectFactory.GetInstance(Of MSSQLConnection)() dim bar as ConnectionSettings foo.connect(bar) ObjectFactory.Configure(Sub(x) x.For(Of IDatabase).Use(foo)) Up until this part, everything works like a charm. Now, i get to a point where i hav e classes that need an additional instance of IDatabase because they connect to a second database. Public Class ExampleClass Public Sub New(ByVal SameOldDatabase as IDatabase, ByVal NewDatabase as IDatabase) [...] Magic happens here [...] End Sub End Class I want this second IDatabase to behave much like the first one. I want it to use a concrete, single instance and want to connect it to a different database invoking Connect with a different ConnectionSettings. The problem is: While i'm pretty sure it's somewhow possible, (my initial idea was registering ExampleClass with alternative constructor arguments), i actually want to do it without registering ExampleClass. This probably involves more configuration, but i have no idea how to do it. So, basically, it comes down to this question: How do i configurate the ObjectFactory in a way that the autowiring always invokes the constructor with object Database1 for the first IDatabase parameter and object Database2 for the second one (if there is one?)

    Read the article

  • Base64 Android encode to PHP decode make error

    - by studio lambda
    I'm a french guy, so, I'm sorry for my english... I'm developing an Android App which communicate with a PHP REST service. So, when I try to encode an image file into Base64 like this : InputStream fileInputStream = context.getContentResolver().openInputStream(uri); BufferedInputStream in = new BufferedInputStream(fileInputStream); StringWriter out = new StringWriter(); int b; while ((b = in.read()) != -1) out.write(b); out.flush(); out.close(); in.close(); String encoded = new String(android.util.Base64.encode(out.toString() .getBytes(), android.util.Base64.DEFAULT)); On server side, I make : $data=base64_decode(chunk_split($base64BinaryData)); The result is that my image file is corrupted! INFO : the image is made by an Intent to android.provider.MediaStore.ACTION_IMAGE_CAPTURE Activity in Emulator mode (avd 5554) I've already read lots of discussions about similar problem but nothing fix my bug. thanks for help Regards,

    Read the article

  • Error with python-setuptools doing "sudo easy_install python-graph-core"

    - by Dan
    Using easy_install, part of the python-setuptools, I get the following error: $ sudo easy_install python-graph-core [sudo] password for dan: Searching for python-graph-core Reading http://pypi.python.org/simple/python-graph-core/ Reading http://code.google.com/p/python-graph/ Reading http://code.google.com/p/python-graph/downloads/list?can=1 Reading http://code.google.com/p/python-graph/downloads/list Best match: python-graph-core 1.7.0 Downloading http://python-graph.googlecode.com/files/python-graph-core-1.7.0.tar.gz Processing python-graph-core-1.7.0.tar.gz Running python-graph-core-1.7.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-GwpYiM/python-graph-core-1.7.0/egg-dist-tmp-1yqbyV setup.py:8: Warning: 'as' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "/usr/bin/easy_install", line 8, in <module> load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')() File "/usr/lib/python2.5/site-packages/setuptools/command/easy_install.py", line 1671, in main with_ei_usage(lambda: File "/usr/lib/python2.5/site-packages/setuptools/command/easy_install.py", line 1659, in with_ei_usage return f() File "/usr/lib/python2.5/site-packages/setuptools/command/easy_install.py", line 1675, in <lambda> distclass=DistributionWithoutHelpCommands, **kw File "/usr/lib/python2.5/distutils/core.py", line 151, in setup dist.run_commands() File "/usr/lib/python2.5/distutils/dist.py", line 974, in run_commands self.run_command(cmd) File "/usr/lib/python2.5/distutils/dist.py", line 994, in run_command cmd_obj.run() File "/usr/lib/python2.5/site-packages/setuptools/command/easy_install.py", line 211, in run self.easy_install(spec, not self.no_deps) File "/usr/lib/python2.5/site-packages/setuptools/command/easy_install.py", line 446, in easy_install return self.install_item(spec, dist.location, tmpdir, deps) File "/usr/lib/python2.5/site-packages/setuptools/command/easy_install.py", line 476, in install_item dists = self.install_eggs(spec, download, tmpdir) File "/usr/lib/python2.5/site-packages/setuptools/command/easy_install.py", line 655, in install_eggs return self.build_and_install(setup_script, setup_base) File "/usr/lib/python2.5/site-packages/setuptools/command/easy_install.py", line 930, in build_and_install self.run_setup(setup_script, setup_base, args) File "/usr/lib/python2.5/site-packages/setuptools/command/easy_install.py", line 919, in run_setup run_setup(setup_script, args) File "/usr/lib/python2.5/site-packages/setuptools/sandbox.py", line 27, in run_setup lambda: execfile( File "/usr/lib/python2.5/site-packages/setuptools/sandbox.py", line 63, in run return func() File "/usr/lib/python2.5/site-packages/setuptools/sandbox.py", line 29, in <lambda> {'__file__':setup_script, '__name__':'__main__'} File "setup.py", line 8 except ImportError as ie: ^ SyntaxError: invalid syntax Any suggestions to what I may be doing wrong? Thanks, Dan

    Read the article

  • Functional Adaptation

    - by Charles Courchaine
    In real life and OO programming we’re often faced with using adapters, DVI to VGA, 1/4” to 1/8” audio connections, 110V to 220V, wrapping an incompatible interface with a new one, and so on.  Where the adapter pattern is generally considered for interfaces and classes a similar technique can be applied to method signatures.  To be fair, this adaptation is generally used to reduce the number of parameters but I’m sure there are other clever possibilities to be had.  As Jan questioned in the last post, how can we use a common method to execute an action if the action has a differing number of parameters, going back to the greeting example it was suggested having an AddName method that takes a first and last name as parameters.  This is exactly what we’ll address in this post. Let’s set the stage with some review and some code changes.  First, our method that handles the setup/tear-down infrastructure for our WCF service: 1: private static TResult ExecuteGreetingFunc<TResult>(Func<IGreeting, TResult> theGreetingFunc) 2: { 3: IGreeting aGreetingService = null; 4: try 5: { 6: aGreetingService = GetGreetingChannel(); 7: return theGreetingFunc(aGreetingService); 8: } 9: finally 10: { 11: CloseWCFChannel((IChannel)aGreetingService); 12: } 13: } Our original AddName method: 1: private static string AddName(string theName) 2: { 3: return ExecuteGreetingFunc<string>(theGreetingService => theGreetingService.AddName(theName)); 4: } Our new AddName method: 1: private static int AddName(string firstName, string lastName) 2: { 3: return ExecuteGreetingFunc<int>(theGreetingService => theGreetingService.AddName(firstName, lastName)); 4: } Let’s change the AddName method, just a little bit more for this example and have it take the greeting service as a parameter. 1: private static int AddName(IGreeting greetingService, string firstName, string lastName) 2: { 3: return greetingService.AddName(firstName, lastName); 4: } The new signature of AddName using the Func delegate is now Func<IGreeting, string, string, int>, which can’t be used with ExecuteGreetingFunc as is because it expects Func<IGreeting, TResult>.  Somehow we have to eliminate the two string parameters before we can use this with our existing method.  This is where we need to adapt AddName to match what ExecuteGreetingFunc expects, and we’ll do so in the following progression. 1: Func<IGreeting, string, string, int> -> Func<IGreeting, string, int> 2: Func<IGreeting, string, int> -> Func<IGreeting, int>   For the first step, we’ll create a method using the lambda syntax that will “eliminate” the last name parameter: 1: string lastNameToAdd = "Smith"; 2: //Func<IGreeting, string, string, int> -> Func<IGreeting, string, int> 3: Func<IGreeting, string, int> addName = (greetingService, firstName) => AddName(greetingService, firstName, lastNameToAdd); The new addName method gets us one step close to the signature we need.  Let’s say we’re going to call this in a loop to add several names, we’ll take the final step from Func<IGreeting, string, int> -> Func<IGreeting, int> in line as a lambda passed to ExecuteGreetingFunc like so: 1: List<string> firstNames = new List<string>() { "Bob", "John" }; 2: int aID; 3: foreach (string firstName in firstNames) 4: { 5: //Func<IGreeting, string, int> -> Func<IGreeting, int> 6: aID = ExecuteGreetingFunc<int>(greetingService => addName(greetingService, firstName)); 7: Console.WriteLine(GetGreeting(aID)); 8: } If for some reason you needed to break out the lambda on line 6 you could replace it with 1: aID = ExecuteGreetingFunc<int>(ApplyAddName(addName, firstName)); and use this method: 1: private static Func<IGreeting, int> ApplyAddName(Func<IGreeting, string, int> addName, string lastName) 2: { 3: return greetingService => addName(greetingService, lastName); 4: } Splitting out a lambda into its own method is useful both in this style of coding as well as LINQ queries to improve the debugging experience.  It is not strictly necessary to break apart the steps & functions as was shown above; the lambda in line 6 (of the foreach example) could include both the last name and first name instead of being composed of two functions.  The process demonstrated above is one of partially applying functions, this could have also been done with Currying (also see Dustin Campbell’s excellent post on Currying for the canonical curried add example).  Matthew Podwysocki also has some good posts explaining both Currying and partial application and a follow up post that further clarifies the difference between Currying and partial application.  In either technique the ultimate goal is to reduce the number of parameters passed to a function.  Currying makes it a single parameter passed at each step, where partial application allows one to use multiple parameters at a time as we’ve done here.  This technique isn’t for everyone or every problem, but can be extremely handy when you need to adapt a call to something you don’t control.

    Read the article

  • A Reusable Builder Class for Ruby Testing

    - by Liam McLennan
    My last post was about a class for building test data objects in C#. This post describes the same tool, but implemented in Ruby. The C# version was written first but I originally came up with the solution in my head using Ruby, and then I translated it to C#. The Ruby version was easier to write and is easier to use thanks to Ruby’s dynamic nature making generics unnecessary.  Here are my example domain classes: class Person attr_accessor :name, :age def initialize(name, age) @name = name @age = age end end class Property attr_accessor :street, :manager def initialize(street, manager) @street = street @manager = manager end end and the test class showing what the builder does: class Test_Builder < Test::Unit::TestCase def setup @build = Builder.new @build.configure({ Property => lambda { Property.new '127 Creek St', @build.a(Person) }, Person => lambda { Person.new 'Liam', 26 } }) end def test_create assert_not_nil @build end def test_can_get_a_person @person = @build.a(Person) assert_not_nil @person assert_equal 'Liam', @person.name assert_equal 26, @person.age end def test_can_get_a_modified_person @person = @build.a Person do |person| person.age = 999 end assert_not_nil @person assert_equal 'Liam', @person.name assert_equal 999, @person.age end def test_can_get_a_different_type_that_depends_on_a_type_that_has_not_been_configured_yet @my_place = @build.a(Property) assert_not_nil @my_place assert_equal '127 Creek St', @my_place.street assert_equal @build.a(Person).name, @my_place.manager.name end end Finally, the implementation of Builder: class Builder # defaults is a hash of Class => creation lambda def configure defaults @defaults = defaults end def a(klass) temp = @defaults[klass].call() yield temp if block_given? temp end end

    Read the article

  • We'll be at QCon San Francisco!

    - by Carlos Chang
    Oracle Technology Network is a Platinum sponsor at QCon San Francisco. Don’t miss these great developer focused sessions: Shay Shmeltzer - How we simplified Web, Mobile and Cloud development for our own developers? - the Oracle Story Over the past several years, Oracle has beendeveloping a new set of enterprise applications in what is probably one of the largest Java based development project in the world. How do you take 3000 developers and make them productive? How do you insure the delivery of cutting edge UIs for both Mobile and Web channels? How do you enable Cloud based development and deployment? Come and learn how we did it at Oracle, and see how the same technologies and methodologies can apply to your development efforts. Dan Smith - Project Lambda in Java 8 Java SE 8 will include major enhancements to the Java Programming Language and its core libraries.  This suite of new features, known as Project Lambda in the OpenJDK community, includes lambda expressions, default methods, and parallel collections (and much more!).  The result will be a next-generation Java programming experience with more flexibility and better abstractions.   This talk will introduce the new Java features and offer a behind-the-scenes view of how they evolved and why they work the way that they do. Arun Gupta - JSR 356: Building HTML5 WebSocket Applications in Java The family of HTML5 technologies has pushed the pendulum away from rich client technologies and toward ever-more-capable Web clients running on today’s browsers. In particular, WebSocket brings new opportunities for efficient peer-to-peer communication, providing the basis for a new generation of interactive and “live” Web applications. This session examines the efforts under way to support WebSocket in the Java programming model, from its base-level integration in the Java Servlet and Java EE containers to a new, easy-to-use API and toolset that are destined to become part of the standard Java platform. The complete conference schedule is here: http://qconsf.com/sf2012/schedule/wednesday.jsp But wait, there’s more! At the Oracle booth, we’ll also be covering: Oracle ADF Mobile Oracle Developer Cloud Service Oracle ADF Essentials NetBeans Project Easel Hope to see you there! 

    Read the article

  • Languages with a clear distinction between subroutines that are purely functional, mutating, state-changing, etc?

    - by CPX
    Lately I've become more and more frustrated that in most modern programming languages I've worked with (C/C++, C#, F#, Ruby, Python, JS and more) there is very little, if any, language support for determining what a subroutine will actually do. Consider the following simple pseudo-code: var x = DoSomethingWith(y); How do I determine what the call to DoSomethingWith(y) will actually do? Will it mutate y, or will it return a copy of y? Does it depend on global or local state, or is it only dependent on y? Will it change the global or local state? How does closure affect the outcome of the call? In all languages I've encountered, almost none of these questions can be answered by merely looking at the signature of the subroutine, and there is almost never any compile-time or run-time support either. Usually, the only way is to put your trust in the author of the API, and hope that the documentation and/or naming conventions reveal what the subroutine will actually do. My question is this: Does there exist any languages today that make symbolic distinctions between these types of scenarios, and places compile-time constraints on what code you can actually write? (There is of course some support for this in most modern languages, such as different levels of scope and closure, the separation between static and instance code, lambda functions, et cetera. But too often these seem to come into conflict with each other. For instance, a lambda function will usually either be purely functional, and simply return a value based on input parameters, or mutate the input parameters in some way. But it is usually possible to access static variables from a lambda function, which in turn can give you access to instance variables, and then it all breaks apart.)

    Read the article

  • Scheme Formatting Help

    - by Logan
    I've been working on a project for school that takes functions from a class file and turns them into object/classes. The assignment is all about object oriented programming in scheme. My problem however is that my code doesn't format right. The output it gives me whenever I give it a file to pass in wraps the methods of the class in a list, making it so that the class never really gets declared. I can't for the life of me figure out how to get the parenthesis wrapping the method list to remove. I would really appreciate any help. Below is the code and the class file. ;;;; PART1 --- A super-easy set of classes. Just models points and lines. Tests all of the ;; basics of class behavior without touching on anything particularly complex. (class pointInstance (parent:) (constructor_args:) (ivars: (myx 1) (myy 2)) (methods: (getx () myx) (gety () myy) (setx (x) (set! myx x)) (show () (begin (display "[") (display myx) (display ",") (display myy) (display "]"))) )) (require (lib "trace.ss")) ;; Continue reading until you hit the end of the file, all the while ;; building a list with the contents (define load-file (lambda (port) (let ((rec (read port))) (if (eof-object? rec) '() (cons rec (load-file port)))))) ;; Open a port based on a file name using open-input-file (define (load fname) (let ((fport (open-input-file fname))) (load-file fport))) ;(define lis (load "C:\\Users\\Logan\\Desktop\\simpletest.txt")) ;(define lis (load "C:\\Users\\Logan\\Desktop\\complextest.txt")) (define lis (load "C:\\Users\\Logan\\Desktop\\pointinstance.txt")) ;(display (cdaddr (cdddar lis))) (define makeMethodList (lambda (listToMake retList) ;(display listToMake) (cond [(null? listToMake) retList ;(display "The list passed in to parse was null") ] [else (makeMethodList (cdr listToMake) (append retList (list (getMethodLine listToMake)))) ] ) )) ;(trace makeMethodList) ;this works provided you just pass in the function line (define getMethodLine (lambda (functionList) `((eq? (car msg) ,(caar functionList)) ,(caddar functionList)))) (define load-classes (lambda paramList (cond [(null? paramList) (display "Your parameters are null, man.")] [(null? (car paramList))(display "Done creating class definitions.")] [(not (null? (car paramList))) (begin (let* ((className (cadaar paramList)) (classInstanceVars (cdaddr (cddaar paramList))) (classMethodList (cdr (cadddr (cddaar paramList)))) (desiredMethodList (makeMethodList classMethodList '())) ) ;(display "Classname: ") ;(display className) ;(newline)(newline) ;(display "Class Instance Vars: ") ;(display classInstanceVars) ;(newline)(newline) ;(display "Class Method List: ") ;(display classMethodList) ;(newline) ;(display "Desired Method List: ") ;(display desiredMethodList)) ;(newline)(newline) ;---------------------------------------------------- ;do not delete the below code!` `(define ,className (let ,classInstanceVars (lambda msg ;return the function list here (cond ,(makeMethodList classMethodList '()))) )) ;--------------------------------------------------- ))] ) )) (load-classes lis) ;(load-classes lis) ;(load-classes-helper lis) ;(load-classes "simpletest.txt") ;(load-classes "complextest.txt") ;method list ;(display (cdr (cadddr (cddaar <class>))))

    Read the article

  • How do I defer execution of some Ruby code until later and run it on demand in this scenario?

    - by Kyle Kaitan
    I've got some code that looks like the following. First, there's a simple Parser class for parsing command-line arguments with options. class Parser def initialize(&b); ...; end # Create new parser. def parse(args = ARGV); ...; end # Consume command-line args. def opt(...); ...; end # Declare supported option. def die(...); ...; end # Validation handler. end Then I have my own Parsers module which holds some metadata about parsers that I want to track. module Parsers ParserMap = {} def self.make_parser(kind, desc, &b) b ||= lambda {} module_eval { ParserMap[kind] = {:desc => "", :validation => lambda {} } ParserMap[kind][:desc] = desc # Create new parser identified by `<Kind>Parser`. Making a Parser is very # expensive, so we defer its creation until it's actually needed later # by wrapping it in a lambda and calling it when we actually need it. const_set(name_for_parser(kind), lambda { Parser.new(&b) }) } end # ... end Now when you want to add a new parser, you can call make_parser like so: make_parser :db, "login to database" do # Options that this parser knows how to parse. opt :verbose, "be verbose with output messages" opt :uid, "user id" opt :pwd, "password" end Cool. But there's a problem. We want to optionally associate validation with each parser, so that we can write something like: validation = lambda { |parser, opts| parser.die unless opts[:uid] && opts[:pwd] # Must provide login. } The interface contract with Parser says that we can't do any validation until after Parser#parse has been called. So, we want to do the following: Associate an optional block with every Parser we make with make_parser. We also want to be able to run this block, ideally as a new method called Parser#validate. But any on-demand method is equally suitable. How do we do that?

    Read the article

  • Using Lambdas for return values in Rhino.Mocks

    - by PSteele
    In a recent StackOverflow question, someone showed some sample code they’d like to be able to use.  The particular syntax they used isn’t supported by Rhino.Mocks, but it was an interesting idea that I thought could be easily implemented with an extension method. Background When stubbing a method return value, Rhino.Mocks supports the following syntax: dependency.Stub(s => s.GetSomething()).Return(new Order()); The method signature is generic and therefore you get compile-time type checking that the object you’re returning matches the return value defined by the “GetSomething” method. You could also have Rhino.Mocks execute arbitrary code using the “Do” method: dependency.Stub(s => s.GetSomething()).Do((Func<Order>) (() => new Order())); This requires the cast though.  It works, but isn’t as clean as the original poster wanted.  They showed a simple example of something they’d like to see: dependency.Stub(s => s.GetSomething()).Return(() => new Order()); Very clean, simple and no casting required.  While Rhino.Mocks doesn’t support this syntax, it’s easy to add it via an extension method. The Rhino.Mocks “Stub” method returns an IMethodOptions<T>.  We just need to accept a Func<T> and use that as the return value.  At first, this would seem straightforward: public static IMethodOptions<T> Return<T>(this IMethodOptions<T> opts, Func<T> factory) { opts.Return(factory()); return opts; } And this would work and would provide the syntax the user was looking for.  But the problem with this is that you loose the late-bound semantics of a lambda.  The Func<T> is executed immediately and stored as the return value.  At the point you’re setting up your mocks and stubs (the “Arrange” part of “Arrange, Act, Assert”), you may not want the lambda executing – you probably want it delayed until the method is actually executed and Rhino.Mocks plugs in your return value. So let’s make a few small tweaks: public static IMethodOptions<T> Return<T>(this IMethodOptions<T> opts, Func<T> factory) { opts.Return(default(T)); // required for Rhino.Mocks on non-void methods opts.WhenCalled(mi => mi.ReturnValue = factory()); return opts; } As you can see, we still need to set up some kind of return value or Rhino.Mocks will complain as soon as it intercepts a call to our stubbed method.  We use the “WhenCalled” method to set the return value equal to the execution of our lambda.  This gives us the delayed execution we’re looking for and a nice syntax for lambda-based return values in Rhino.Mocks. Technorati Tags: .NET,Rhino.Mocks,Mocking,Extension Methods

    Read the article

  • Help with dynamic-wind and call/cc

    - by josh
    I am having some trouble understanding the behavior of the following Scheme program: (define c (dynamic-wind (lambda () (display 'IN)(newline)) (lambda () (call/cc (lambda (k) (display 'X)(newline) k))) (lambda () (display 'OUT)(newline)))) As I understand, c will be bound to the continution created right before "(display 'X)". But using c seems to modify itself! The define above prints (as I expected) IN, X and OUT: IN X OUT And it is a procedure: #;2> c #<procedure (a9869 . results1678)> Now, I would expect that when it is called again, X would be printed, and it is not! #;3> (c) IN OUT And now c is not a procedure anymore, and a second invokation of c won't work! #;4> c ;; the REPL doesn't answer this, so there are no values returned #;5> (c) Error: call of non-procedure: #<unspecified> Call history: <syntax> (c) <eval> (c) <-- I was expecting that each invokation to (c) would do the same thing -- print IN, X, and OUT. What am I missing?

    Read the article

  • CarrierWave and nested forms saving empty image object if photo :title is included in form

    - by Wasabi Developer
    I'm after some advice in regards to handling nested form data and I would be ever so grateful for any insights. The trouble is I'm not 100% sure why I require the following code in my model accepts_nested_attributes_for :holiday_image, allow_destroy: true, :reject_if => lambda { |a| a[:title].blank? } If I don't understand why I require to tact on on my accepts_nested_attributes_for association: :reject_if => lambda { |a| a[:title].blank? } If I remove this :reject_if lambda, it will save a blank holiday photo object in the database. I presume because it takes the :title field from the form as an empty string? I guess my question is, am I doing this right or is there a better way of this this within nested forms if I want to extend my HolidayImage model to include more strings like description, notes? Sorry If I can't be more succinct. My simple holiday app. # holiday.rb class Holiday < ActiveRecord::Base has_many :holiday_image accepts_nested_attributes_for :holiday_image, allow_destroy: true, :reject_if => lambda { |a| a[:title].blank? } attr_accessible :name, :content, :holiday_image_attributes end I'm using CarrierWave for image uploads. # holiday_image.rb class HolidayImage < ActiveRecord::Base belongs_to :holiday attr_accessible :holiday_id, :image, :title mount_uploader :image, ImageUploader end Inside my _form partial there is a field_for block <h3>Photo gallery</h3> <%= f.fields_for :holiday_image do |holiday_image| %> <% if holiday_image.object.new_record? %> <%= holiday_image.label :title, "Image Title" %> <%= holiday_image.text_field :title %> <%= holiday_image.file_field :image %> <% else %> Title: <%= holiday_image.object.title %> <%= image_tag(holiday_image.object.image.url(:thumb)) %> Tick to delete: <%= holiday_image.check_box :_destroy %> <% end %> Thanks again for your patience.

    Read the article

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