Search Results

Search found 214 results on 9 pages for 'tuples'.

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

  • Search for string within text column in MySQL

    - by user94154
    I have mysql table that has a column that stores xml as a string. I need to find all tuples where the xml column contains a given string of 6 characters. Nothing else matters--all I need to know is if this 6 character string is there or not. So it probably doesn't matter that the text is formatted as xml. Question: how can I search within mysql? ie SELECT * FROM items WHERE items.xml [contains the text '123456'] Is there a way I can use the LIKE operator to do this? Thanks

    Read the article

  • C++11 initialize array with uniform value in constexpr function

    - by marack
    I have a class template which builds a simple array based on the template parameters as one of its members. I need to be able to initialize every element in the array to a single value in one of the constructors. Unfortunately this constructor must be constexpr. The relevant part boils down to: template <typename T, size_t N> class foo { T data[N]; constexpr foo(T val) { // initialize data with N copies of val } }; Using std::fill or a loop is incompatible with the constexpr requirement. Initializing with : data{val} only sets the first element of the array and zero-initializes the remainder. How can this be achieved? I feel like there should be a solution with variadic templates and tuples etc...

    Read the article

  • Python point lookup (coordinate binning?)

    - by Rince
    Greetings, I am trying to bin an array of points (x, y) into an array of boxes [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] (tuples are the corner points) So far I have the following routine: def isInside(self, point, x0, x1, y0, y1): pr1 = getProduct(point, (x0, y0), (x1, y0)) if pr1 >= 0: pr2 = getProduct(point, (x1, y0), (x1, y1)) if pr2 >= 0: pr3 = getProduct(point, (x1, y1), (x0, y1)) if pr3 >= 0: pr4 = getProduct(point, (x0, y1), (x0, y0)) if pr4 >= 0: return True return False def getProduct(origin, pointA, pointB): product = (pointA[0] - origin[0])*(pointB[1] - origin[1]) - (pointB[0] - origin[0])*(pointA[1] - origin[1]) return product Is there any better way then point-by-point lookup? Maybe some not-obvious numpy routine? Thank you!

    Read the article

  • Partially fattening a list

    - by alj
    This is probably a really silly question but, given the example code at the bottom, how would I get a single list that retain the tuples? (I've looked at the itertools but it flattens everything) What I currently get is: ('id', 20, 'integer') ('companyname', 50, 'text') [('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, 'text'), ('puma', 30, 'text')] ('contact', 50, 'text') ('email', 50, 'text') what I would like is a single level list like: ('id', 20, 'integer') ('companyname', 50, 'text') ('focus', 30, 'text') ('fiesta', 30, 'text') ('mondeo', 30, 'text') ('puma', 30, 'text') ('contact', 50, 'text') ('email', 50, 'text') def getproducts(): temp_list=[] product_list=['focus','fiesta','mondeo','puma'] #usually this would come from a db for p in product_list: temp_list.append((p,30,'text')) return temp_list def createlist(): column_title_list = ( ("id",20,"integer"), ("companyname",50,"text"), getproducts(), ("contact",50,"text"), ("email",50,"text"), ) return column_title_list for item in createlist(): print item Thanks ALJ

    Read the article

  • Should I be put off a junior role that uses an online development test?

    - by Ninefingers
    I've applied for a junior development role, or rather been found by a recruiter looking for a developer. In order to get to a telephone interview stage I've been asked to sit one of those online coding assessments. This wasn't quite what I expected. I consider myself a fairly good developer for my age and experience, but I've no illusions about being Don Knuth or anything. The test was a series of incredibly obtuse questions asking about the results of various obscure evaluations. About 30 minutes in I was thinking to myself I hadn't intended to enter an obfuscated code contest/code golf exercise. After my last telephone interview I was asked to build something. I did. That seemed fair. Go away and work this out is more my in office experience of programming than "please evaluate this combination of lambdas, filters, maps, lists, tuples etc". So I'm a little put off, to be honest. I never claimed to know the language inside out or all the little corner cases. My questions, then: Should I be put off? Why? Why not? Are these kinds of tests what I should be expecting for junior roles? Should I learn stuff exam style? That seems to be the objective of these tests, for which you are timed and not supposed to use references or books? Normally, in the course of development I have a fairly good idea of basic types, rules, flow control and whatever. Occasionally I'll come up on something I need to use a regex for and have to go and remind myself of the exact piece of syntax I need if trying what I think should work doesn't. Or I'll come up against a module I've not used before and go and look it up. For example, if I wanted to write a server using sockets in C right now, I'd probably check the last piece of code I wrote doing that (and or the various books I have) and work from there. Chances are I probably couldn't do it exactly from scratch and from memory, although I can tell you you'd need a socket(), bind(), listen() and accept() call and you might also want select() depending on whether you intend to pthread_create or not. So I know what the calls are, but not their specific parameter list. What are your experiences if you are a recruiting manager? Are you after programmers who can quote you the API or do you not mind if your programmers have a few books on their desk and google function calls every so often?

    Read the article

  • Disco/MapReduce: Using results of previous iteration as input to new iteration

    - by muckabout
    Currently am implementing PageRank on Disco. As an iterative algorithm, the results of one iteration are used as input to the next iteration. I have a large file which represents all the links, with each row representing a page and the values in the row representing the pages to which it links. For Disco, I break this file into N chunks, then run MapReduce for one round. As a result, I get a set of (page, rank) tuples. I'd like to feed this rank to the next iteration. However, now my mapper needs two inputs: the graph file, and the pageranks. I would like to "zip" together the graph file and the page ranks, such that each line represents a page, it's rank, and it's out links. Since this graph file is separated into N chunks, I need to split the pagerank vector into N parallel chunks, and zip the regions of the pagerank vectors to the graph chunks This all seems more complicated than necessary, and as a pretty straightforward operation (with the quintessential mapreduce algorithm), it seems I'm missing something about Disco that could really simplify the approach. Any thoughts?

    Read the article

  • Asp.net mvc 2 .net 4.0 error when View model type is Tuple with more than 4 items

    - by Bojan
    When I create strongly typed View in Asp.net mvc 2, .net 4.0 with model type Tuple I get error when Tuple have more than 4 items example 1: type of view is Tuple<string, string, string, string> (4-tuple) and everything works fine view: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/WebUI.Master" Inherits="System.Web.Mvc.ViewPage<Tuple<string, string, string, string>>" %> controller: var tuple = Tuple.Create("a", "b", "c", "d"); return View(tuple); example 2: type of view is Tuple<string, string, string, string, string> (5-tuple) and I have this error: Compiler Error Message: CS1003: Syntax error, '>' expected view: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/WebUI.Master" Inherits="System.Web.Mvc.ViewPage<Tuple<string, string, string, string, string>>" %> controller: var tuple = Tuple.Create("a", "b", "c", "d", "e"); return View(tuple); example 3 if my view model is of type dynamic I can use both 4-tuple and 5-tuple and there is no error on page view: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/WebUI.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> controller: dynamic model = new ExpandoObject(); model.tuple = Tuple.Create("a", "b", "c", "d"); return View(model); or view: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/WebUI.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> controller: dynamic model = new ExpandoObject(); model.tuple = Tuple.Create("a", "b", "c", "d", "e"); return View(model); Even if I have something like Tuple<string, Tuple<string, string, string>, string> 3-tuple and one of the items is also a tuple and sum of items in all tuples is more than 4 I get the same error, Tuple<string, Tuple<string, string>, string> works fine

    Read the article

  • Find unique vertices from a 'triangle-soup'

    - by sum1stolemyname
    I am building a CAD-file converter on top of two libraries (Opencascade and DWF Toolkit). However, my question is plattform agnostic: Given: I have generated a mesh as a list of triangular faces form a model constructed through my application. Each Triangle is defined through three vertexes, which consist of three floats (x, y & z coordinate). Since the triangles form a mesh, most of the vertices are shared by more then one triangle. Goal: I need to find the list of unique vertices, and to generate an array of faces consisting of tuples of three indices in this list. What i want to do is this: //step 1: build a list of unique vertices for each triangle for each vertex in triangle if not vertex in listOfVertices Add vertex to listOfVertices //step 2: build a list of faces for each triangle for each vertex in triangle Get Vertex Index From listOfvertices AddToMap(vertex Index, triangle) While I do have an implementation which does this, step1 (the generation of the list of unique vertices) is really slow in the order of O(n!), since each vertex is compared to all vertices already in the list. I thought "Hey, lets build a hashmap of my vertices' components using std::map, that ought to speed things up!", only to find that generating a unique key from three floating point values is not a trivial task. Here, the experts of stackoverflow come into play: I need some kind of hash-function which works on 3 floats, or any other function generating a unique value from a 3d-vertex position.

    Read the article

  • How do I process a nested list?

    - by ddbeck
    Suppose I have a bulleted list like this: * list item 1 * list item 2 (a parent) ** list item 3 (a child of list item 2) ** list item 4 (a child of list item 2 as well) *** list item 5 (a child of list item 4 and a grand-child of list item 2) * list item 6 I'd like to parse that into a nested list or some other data structure which makes the parent-child relationship between elements explicit (rather than depending on their contents and relative position). For example, here's a list of tuples containing an item and a list of its children (and so forth): [('list item 1',), ('list item 2', [('list item 3',), [('list item 4', [('list item 5'),]] ('list item 6',)] I've attempted to do this with plain Python and some experimentation with Pyparsing, but I'm not making progress. I'm left with two major questions: What's the strategy I need to employ to make this work? I know recursion is part of the solution, but I'm having a hard time making the connection between this and, say, a Fibonacci sequence. I'm certain I'm not the first person to have done this, but I don't know the terminology of the problem to make fruitful searches for more information on this topic. What problems are related to this so that I can learn more about solving these kinds of problems in general?

    Read the article

  • Python: Networked IDLE/Redo IDLE front-end while using the same back-end?

    - by Rosarch
    Is there any existing web app that lets multiple users work with an interactive IDLE type session at once? Something like: IDLE 2.6.4 Morgan: >>> letters = list("abcdefg") Morgan: >>> # now, how would you iterate over letters? Jack: >>> for char in letters: print "char %s" % char char a char b char c char d char e char f char g Morgan: >>> # nice nice If not, I would like to create one. Is there some module I can use that simulates an interactive session? I'd want an interface like this: def class InteractiveSession(): ''' An interactive Python session ''' def putLine(line): ''' Evaluates line ''' pass def outputLines(): ''' A list of all lines that have been output by the session ''' pass def currentVars(): ''' A dictionary of currently defined variables and their values ''' pass (Although that last function would be more of an extra feature.) To formulate my problem another way: I'd like to create a new front end for IDLE. How can I do this? UPDATE: Or maybe I can simulate IDLE through eval()? UPDATE 2: What if I did something like this: I already have a simple GAE Python chat app set up, that allows users to sign in, make chat rooms, and chat with each other. Instead of just saving incoming messages to the datastore, I could do something like this: def putLine(line, user, chat_room): ''' Evaluates line for the session used by chat_room ''' # get the interactive session for this chat room curr_vars = InteractiveSession.objects.where("chatRoom = %s" % chat_room).get() result = eval(prepared_line, curr_vars.state, {}) curr_vars.state = curr_globals curr_vars.lines.append((user, line)) if result: curr_vars.lines.append(('SELF', result.__str__())) curr_vars.put() The InteractiveSession model: def class InteractiveSession(db.Model): # a dictionary mapping variables to values # it looks like GAE doesn't actually have a dictionary field, so what would be best to use here? state = db.DictionaryProperty() # a transcript of the session # # a list of tuples of the form (user, line_entered) # # looks something like: # # [('Morgan', '# hello'), # ('Jack', 'x = []'), # ('Morgan', 'x.append(1)'), # ('Jack', 'x'), # ('SELF', '[1]')] lines = db.ListProperty() Could this work, or am I way off/this approach is infeasible/I'm duplicating work when I should use something already built?

    Read the article

  • Pair-wise iteration in C# or sliding window enumerator

    - by f3lix
    If I have an IEnumerable like: string[] items = new string[] { "a", "b", "c", "d" }; I would like to loop thru all the pairs of consecutive items (sliding window of size 2). Which would be ("a","b"), ("b", "c"), ("c", "d") My solution was is this public static IEnumerable<Pair<T, T>> Pairs(IEnumerable<T> enumerable) { IEnumerator<T> e = enumerable.GetEnumerator(); e.MoveNext(); T current = e.Current; while ( e.MoveNext() ) { T next = e.Current; yield return new Pair<T, T>(current, next); current = next; } } // used like this : foreach (Pair<String,String> pair in IterTools<String>.Pairs(items)) { System.Out.PrintLine("{0}, {1}", pair.First, pair.Second) } When I wrote this code, I wondered if there are already functions in the .NET framework that do the same thing and do it not just for pairs but for any size tuples. IMHO there should be a nice way to do this kind of sliding window operations. I use C# 2.0 and I can imagine that with C# 3.0 (w/ LINQ) there are more (and nicer) ways to do this, but I'm primarily interested in C# 2.0 solutions. Though, I will also appreciate C# 3.0 solutions.

    Read the article

  • How can I remove an "ALMOST" Duplicate using LINQ? ( OR SQL? )

    - by Atomiton
    This should be and easy one for the LINQ gurus out there. I'm doing a complex Query using UNIONS and CONTAINSTABLE in my database to return ranked results to my application. I'm getting duplicates in my returned data. This is expected. I'm using CONTAINSTABLE and CONTAINS to get all the results I need. CONTAINSTABLE is ranked by SQL and CONTAINS (which is run only on the Keywords field ) is hard-code-ranked by me. ( Sorry if that doesn't make sense ) Anyway, because the tuples aren't identical ( their rank is different ) a duplicate is returned. I figure the best way to deal with this is use LINQ. I know I'll be using the Distinct() extension method, but do I have to implement the IEqualityComparer interface? I'm a little fuzzy on how to do this. For argument's sake, say my resultset is structured like this class: class Content { ContentID int //KEY Rank int Description String } If I have a List<Content> how would I write the Distinct() method to exclude Rank? Ideally I'd like to keep the Content's highest Rank. SO, if one Content's RAnk is 112 and the other is 76. I'd like to keep the 112 rank. Hopefully I've given enough information.

    Read the article

  • Discover periodic patterns in a large data-set

    - by Miner
    I have a large sequence of tuples on disk in the form (t1, k1) (t2, k2) ... (tn, kn) ti is a monotonically increasing timestamp and ki is a key (assume a fixed length string if needed). Neither ti nor ki are guaranteed to be unique. However, the number of unique tis and kis is huge (millions). n itself is very large (100 Million+) and the size of k (approx 500 bytes) makes it impossible to store everything in memory. I would like to find out periodic occurrences of keys in this sequence. For example, if I have the sequence (1, a) (2, b) (3, c) (4, b) (5, a) (6, b) (7, d) (8, b) (9, a) (10, b) The algorithm should emit (a, 4) and (b, 2). That is a occurs with a period of 4 and b occurs with a period of 2. If I build a hash of all keys and store the average of the difference between consecutive timestamps of each key and a std deviation of the same, I might be able to make a pass, and report only the ones that have an acceptable std deviation(ideally, 0). However, it requires one bucket per unique key, whereas in practice, I might have very few really periodic patterns. Any better ways?

    Read the article

  • SQL with Regular Expressions vs Indexes with Logical Merging Functions

    - by geeko
    Hello Lads, I am trying to develop a complex textual search engine. I have thousands of textual pages from many books. I need to search pages that contain specified complex logical criterias. These criterias can contain virtually any compination of the following: A: Full words. B: Word roots (semilar to stems; i.e. all words with certain key letters). C: Word templates (in some languages are filled in certain templates to form various part of speech such as adjactives, past/present verbs...). D: Logical connectives: AND/OR/XOR/NOT/IF/IFF and parentheses to state priorities. Now, would it be faster to have the pages' full text in database (not indexed) and search though them all using SQL and Regular Expressions ? Or would it be better to construct indexes of word/root/template-page-location tuples. Hence, we can boost searching for individual words/roots/templates. However, it gets tricky as we interdouce logical connectives into our query. I thought of doing the following steps in such cases: 1: Seperately search for each individual words/roots/templates in the specified query. 2: On priority bases, we merge two result lists (from step 1) at a time depedning on the logical connective For example, if we are searching for "he AND (is OR was)": 1: We shall search for "he", "is" and "was" seperately and get result lists for each word. 2: Merge the result lists of "is" and "was" using the merging function OR-MERGE 3: Merge the merged result list from the OR-MERGE function with the one of "he" using the merging function AND-MERGE The result of step 3 is then returned as the result of the specified query. What do you think gurues ? Which is faster ? Any better ideas ? Thank you all in advance.

    Read the article

  • More FP-correct way to create an update sql query

    - by James Black
    I am working on access a database using F# and my initial attempt at creating a function to create the update query is flawed. let BuildUserUpdateQuery (oldUser:UserType) (newUser:UserType) = let buf = new System.Text.StringBuilder("UPDATE users SET "); if (oldUser.FirstName.Equals(newUser.FirstName) = false) then buf.Append("SET first_name='").Append(newUser.FirstName).Append("'" ) |> ignore if (oldUser.LastName.Equals(newUser.LastName) = false) then buf.Append("SET last_name='").Append(newUser.LastName).Append("'" ) |> ignore if (oldUser.UserName.Equals(newUser.UserName) = false) then buf.Append("SET username='").Append(newUser.UserName).Append("'" ) |> ignore buf.Append(" WHERE id=").Append(newUser.Id).ToString() This doesn't properly put a , between any update parts after the first, for example: UPDATE users SET first_name='Firstname', last_name='lastname' WHERE id=... I could put in a mutable variable to keep track when the first part of the set clause is appended, but that seems wrong. I could just create an list of tuples, where each tuple is oldtext, newtext, columnname, so that I could then loop through the list and build up the query, but it seems that I should be passing in a StringBuilder to a recursive function, returning back a boolean which is then passed as a parameter to the recursive function. Does this seem to be the best approach, or is there a better one?

    Read the article

  • Insert MANY key value pairs fast into berkeley db with hash access

    - by Kungi
    Hi, i'm trying to build a hash with berkeley db, which shall contain many tuples (approx 18GB of key value pairs), but in all my tests the performance of the insert operations degrades drastically over time. I've written this script to test the performance: #include<iostream> #include<db_cxx.h> #include<ctime> #define MILLION 1000000 int main () { long long a = 0; long long b = 0; int passes = 0; int i = 0; u_int32_t flags = DB_CREATE; Db* dbp = new Db(NULL,0); dbp->set_cachesize( 0, 1024 * 1024 * 1024, 1 ); int ret = dbp->open( NULL, "test.db", NULL, DB_HASH, flags, 0); time_t time1 = time(NULL); while ( passes < 100 ) { while( i < MILLION ) { Dbt key( &a, sizeof(long long) ); Dbt data( &b, sizeof(long long) ); dbp->put( NULL, &key, &data, 0); a++; b++; i++; } DbEnv* dbep = dbp->get_env(); int tmp; dbep->memp_trickle( 50, &tmp ); i=0; passes++; std::cout << "Inserted one million --> pass: " << passes << " took: " << time(NULL) - time1 << "sec" << std::endl; time1 = time(NULL); } } Perhaps you can tell me why after some time the "put" operation takes increasingly longer and maybe how to fix this. Thanks for your help, Andreas

    Read the article

  • N-gram split function for string similarity comparison

    - by Michael
    As part of excersise to better understand F# which I am currently learning , I wrote function to split given string into n-grams. 1) I would like to receive feedback about my function : can this be written simpler or in more efficient way? 2) My overall goal is to write function that returns string similarity (on 0.0 .. 1.0 scale) based on n-gram similarity; Does this approach works well for short strings comparisons , or can this method reliably be used to compare large strings (like articles for example). 3) I am aware of the fact that n-gram comparisons ignore context of two strings. What method would you suggest to accomplish my goal? //s:string - target string to split into n-grams //n:int - n-gram size to split string into let ngram_split (s:string, n:int) = let ngram_count = s.Length - (s.Length % n) let ngram_list = List.init ngram_count (fun i -> if( i + n >= s.Length ) then s.Substring(i,s.Length - i) + String.init ((i + n) - s.Length) (fun i -> "#") else s.Substring(i,n) ) let ngram_array_unique = ngram_list |> Seq.ofList |> Seq.distinct |> Array.ofSeq //produce tuples of ngrams (ngram string,how much occurrences in original string) Seq.init ngram_array_unique.Length (fun i -> (ngram_array_unique.[i], ngram_list |> List.filter(fun item -> item = ngram_array_unique.[i]) |> List.length) )

    Read the article

  • page.insert_html not rendering partial correctly

    - by mathee
    The following is in the text_field. = f.text_field :title, :size => 50, :onchange => remote_function(:update => :suggestions, :url => {:action => :display_question_search_results}) The following is in display_questions_search_results.rjs. page.insert_html :bottom, 'suggestions', :partial => 'suggestions' Whenever the user types, I'd like to search the database for any tuples that match the keywords in the text field. Then, display those results. But, at the moment, _suggestions.haml only contains the word "suggestions!!". But, instead of seeing "suggestions!!" in the suggestions div tag, I get: try { Element.insert("suggestions", { bottom: "suggestions!!" }); } catch (e) { alert('RJS error:\n\n' + e.toString()); alert('Element.insert(\"suggestions\", { bottom: \"suggestions!!\" });'); throw e } I've been trying to find out why this is being done, but the previously asked questions I found seem more complicated than what I'm doing...

    Read the article

  • How do I implement configurations and settings?

    - by Malvolio
    I'm writing a system that is deployed in several places and each site needs its own configurations and settings. A "configuration" is a named value that is necessary to a particular site (e.g., the database URL, S3 bucket name); every configuration is necessary, there is not usually a default, and it's typically string-valued. A setting is a named value but it just tweaks the behavior of the system; it's often numeric or Boolean, and there's usually some default. So far, I've been using property files or thing like them, but it's a terrible solution. Several times, a developer has added a requirement for a configuration but not added the value to file for the live configuration, so the new release passed all the tests, then failed when released to live. Better, of course, for every file to be compiled — so if there's a missing configuration, or one of the wrong type, it won't get past the compiler — and inject the site-specific class into the build for each site. As a bones, a Scala file can easy model more complex values, especially lists, but also maps and tuples. The downside is, the files are sometimes maintained by people who aren't developers, so it has to be pretty self-explanatory, which was the advantage of property files. (Someone explain XML configurations to me: all the complexity of a compilable file but the run-time risk of a property file.) What I'm looking for is an easy pattern for defining a group required names and allowable values. Any suggestions?

    Read the article

  • Why there is no scoped locks for multiple mutexes in C++0x or Boost.Thread?

    - by Vicente Botet Escriba
    C++0x thread library or Boost.thread define non-member variadic template function that lock all lock avoiding dead lock. template <class L1, class L2, class... L3> void lock(L1&, L2&, L3&...); While this function avoid help to deadlock, the standard do not includes the associated scoped lock to write exception safe code. { std::lock(l1,l2); // do some thing // unlock li l2 exception safe } That means that we need to use other mechanism as try-catch block to make exception safe code or define our own scoped lock on multiple mutexes ourselves or even do that { std::lock(l1,l2); std::unique_lock lk1(l1, std::adopted); std::unique_lock lk2(l2, std::adopted); // do some thing // unlock li l2 on destruction of lk1 lk2 } Why the standard doesn't includes a scoped lock on multiple mutexes of the same type, as for example { std::array_unique_lock<std::mutex> lk(l1,l2); // do some thing // unlock l1 l2 on destruction of lk } or tuples of mutexes { std::tuple_unique_lock<std::mutex, std::recursive_mutex> lk(l1,l2); // do some thing // unlock l1 l2 on destruction of lk } Is there something wrong on the design?

    Read the article

  • parsing of mathematical expressions

    - by gcc
    (in c90) (linux) input: sqrt(2 - sin(3*A/B)^2.5) + 0.5*(C*~(D) + 3.11 +B) a b /*there are values for a,b,c,d */ c d input: cos(2 - asin(3*A/B)^2.5) +cos(0.5*(C*~(D)) + 3.11 +B) a b /*there are values for a,b,c,d */ c d input: sqrt(2 - sin(3*A/B)^2.5)/(0.5*(C*~(D)) + sin(3.11) +ln(B)) /*max lenght of formula is 250 characters*/ a b /*there are values for a,b,c,d */ c /*each variable with set of floating numbers*/ d As you can see infix formula in the input depends on user. My program will take a formula and n-tuples value. Then it calculate the results for each value of a,b,c and d. If you wonder I am saying ;outcome of program is graph. /sometimes,I think i will take input and store in string. then another idea is arise " I should store formula in the struct" but i don't know how I can construct the code on the base of structure./ really, I don't know way how to store the formula in program code so that I can do my job. can you show me? /* a,b,c,d is letters cos,sin,sqrt,ln is function*/

    Read the article

  • F# How to tokenise user input: separating numbers, units, words?

    - by David White
    I am fairly new to F#, but have spent the last few weeks reading reference materials. I wish to process a user-supplied input string, identifying and separating the constituent elements. For example, for this input: XYZ Hotel: 6 nights at 220EUR / night plus 17.5% tax the output should resemble something like a list of tuples: [ ("XYZ", Word); ("Hotel:", Word); ("6", Number); ("nights", Word); ("at", Operator); ("220", Number); ("EUR", CurrencyCode); ("/", Operator); ("night", Word); ("plus", Operator); ("17.5", Number); ("%", PerCent); ("tax", Word) ] Since I'm dealing with user input, it could be anything. Thus, expecting users to comply with a grammar is out of the question. I want to identify the numbers (could be integers, floats, negative...), the units of measure (optional, but could include SI or Imperial physical units, currency codes, counts such as "night/s" in my example), mathematical operators (as math symbols or as words including "at" "per", "of", "discount", etc), and all other words. I have the impression that I should use active pattern matching -- is that correct? -- but I'm not exactly sure how to start. Any pointers to appropriate reference material or similar examples would be great.

    Read the article

  • Beginner having difficulty with SQL query

    - by Vulcanizer
    Hi, I've been studying SQL for 2 weeks now and I'm preparing for an SQL test. Anyway I'm trying to do this question: For the table: 1 create table data { 2 id int, 3 n1 int not null, 4 n2 int not null, 5 n3 int not null, 6 n4 int not null, 7 primary key (id) 8 } I need to return the relation with tuples (n1, n2, n3) where all the corresponding values for n4 are 0. The problem asks me to solve it WITHOUT using subqueries(nested selects/views) It also gives me an example table and the expected output from my query: 01 insert into data (id, n1, n2, n3, n4) 02 values (1, 2,4,7,0), 03 (2, 2,4,7,0), 04 (3, 3,6,9,8), 05 (4, 1,1,2,1), 06 (5, 1,1,2,0), 07 (6, 1,1,2,0), 08 (7, 5,3,8,0), 09 (8, 5,3,8,0), 10 (9, 5,3,8,0); expects (2,4,7) (5,3,8) and not (1,1,2) since that has a 1 in n4 in one of the cases. The best I could come up with was: 1 SELECT DISTINCT n1, n2, n3 2 FROM data a, data b 3 WHERE a.ID <> b.ID 4 AND a.n1 = b.n1 5 AND a.n2 = b.n2 6 AND a.n3 = b.n3 7 AND a.n4 = b.n4 8 AND a.n4 = 0 but I found out that also prints (1,1,2) since in the example (1,1,2,0) happens twice from IDs 5 and 6. Any suggestions would be really appreciated.

    Read the article

  • method works fine, until it is called in a function, then UnboundLocalError

    - by user1776100
    I define a method called dist, to calculate the distance between two points which I does it correctly when directly using the method. However, when I get a function to call it to calculate the distance between two points, I get UnboundLocalError: local variable 'minkowski_distance' referenced before assignment edit sorry, I just realised, this function does work. However I have another method calling it that doesn't. I put the last method at the bottom This is the method: class MinkowskiDistance(Distance): def __init__(self, dist_funct_name_str = 'Minkowski distance', p=2): self.p = p def dist(self, obj_a, obj_b): distance_to_power_p=0 p=self.p for i in range(len(obj_a)): distance_to_power_p += abs((obj_a[i]-obj_b[i]))**(p) minkowski_distance = (distance_to_power_p)**(1/p) return minkowski_distance and this is the function: (it basically splits the tuples x and y into their number and string components and calculates the distance between the numeric part of x and y and then the distance between the string parts, then adds them. def total_dist(x, y, p=2, q=2): jacard = QGramDistance(q=q) minkowski = MinkowskiDistance(p=p) x_num = [] x_str = [] y_num = [] y_str = [] #I am spliting each vector into its numerical parts and its string parts so that the distances #of each part can be found, then summed together. for i in range(len(x)): if type(x[i]) == float or type(x[i]) == int: x_num.append(x[i]) y_num.append(y[i]) else: x_str.append(x[i]) y_str.append(y[i]) num_dist = minkowski.dist(x_num,y_num) str_dist = I find using some more steps #I am simply adding the two types of distance to get the total distance: return num_dist + str_dist class NearestNeighbourClustering(Clustering): def __init__(self, data_file, clust_algo_name_str='', strip_header = "no", remove = -1): self.data_file= data_file self.header_strip = strip_header self.remove_column = remove def run_clustering(self, max_dist, p=2, q=2): K = {} #dictionary of clusters data_points = self.read_data_file() K[0]=[data_points[0]] k=0 #I added the first point in the data to the 0th cluster #k = number of clusters minus 1 n = len(data_points) for i in range(1,n): data_point_in_a_cluster = "no" for c in range(k+1): distances_from_i = [total_dist(data_points[i],K[c][j], p=p, q=q) for j in range(len(K[c]))] d = min(distances_from_i) if d <= max_dist: K[c].append(data_points[i]) data_point_in_a_cluster = "yes" if data_point_in_a_cluster == "no": k += 1 K[k]=[data_points[i]] return K

    Read the article

  • How can I change how OS X's 'say' command pronounces a word?

    - by jwhitlock
    OS X's say command is useful for some tasks (such as Skype's 'notify me when a contact comes online), but it is pronouncing some names incorrectly. Is there a way to teach say to pronounce a word differently? For example, try: say "Hi, Joel Spolsky" The 'ol' sounds like 'ball' rather than 'old'. I'd like to add an exception that say "Pronounce Spolsky like this", rather than try to teach new linguistic rules. I bet there is a way since it can pronounce "iphone" as Apple wants. Update - After some research, here's what I've learned: Text-to-speech is split between turning the text to phonemes, and then the phonemes are turned into audio using a voice. Changing the voice doesn't effect the phonemes. The Speech Synthesis Manager has some functions for turning text to phonemes, and a method for registering a speech dictionary that will add new text-phoneme maps. However, Apple's speech dictionary must be in a binary form - I didn't find any plist XML. Using dtrace while running say, I found some interesting files opened in /System/Library/PrivateFrameworks/SpeechDictionary.framework/Resources. This is probably the speech dictionary, but they are all binary, except for Homophones, which is XML. Adding entries to Homophones does nothing - it is probably used in speech-to-text. They are also code signed by Apple - changing them may prevent some programs from working. PrefixDictionary CartNames CartLite SymbolDictionary Homophones There are ways to add text versions of application interface elements so VoiceOver works, a lot of which a developer gets for free, but there are tricky bits. The standard here appears to be to use a phonetic spelling as needed. My guesses are: say is a light layer of code on top of the Speech Synthesis Manager. It would be easy for the Apple devs to add a command line option to take the path to a speech dictionary plist for alternate phoneme mapping, but they didn't. It may be a useful open-source project to write a better say. Skype probably uses Speech Synthesis Manager directly, leaving no hooks to change the way my friend's names are pronounced, other than spelling them phonetically, which is silly. The easiest way to make a command line version of say is how JRobert suggested. Here's my quick implementation, using Doug Harris's spelling suggestion: #!/bin/sh echo $@ | tr '[A-Z]' '[a-z]' | sed "s/spolsky/spowlsky/g" | /usr/bin/say Finally, some fun command line stuff: # Apple is weird sqlite3 /System/Library/PrivateFrameworks/SpeechDictionary.framework/Resources/Tuples .dump # Get too much information about what files are being opened sudo dtrace -n 'syscall::open*:entry { printf("%s %s",execname,copyinstr(arg0)); }' # Just fun say -v bad "Joel Spolsky Spolsky Spolsky Spolsky Spolsky, Joel Spolsky Spolsky Spolsky Spolsky Spolsky" echo "scale=1000; 4*a(1)" | bc -l | say

    Read the article

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