Search Results

Search found 37183 results on 1488 pages for 'string conversion'.

Page 112/1488 | < Previous Page | 108 109 110 111 112 113 114 115 116 117 118 119  | Next Page >

  • Algorithm detect repeating/similiar strings in a corpus of data -- say email subjects, in Python

    - by RizwanK
    I'm downloading a long list of my email subject lines , with the intent of finding email lists that I was a member of years ago, and would want to purge them from my Gmail account (which is getting pretty slow.) I'm specifically thinking of newsletters that often come from the same address, and repeat the product/service/group's name in the subject. I'm aware that I could search/sort by the common occurrence of items from a particular email address (and I intend to), but I'd like to correlate that data with repeating subject lines.... Now, many subject lines would fail a string match, but "Google Friends : Our latest news" "Google Friends : What we're doing today" are more similar to each other than a random subject line, as is: "Virgin Airlines has a great sale today" "Take a flight with Virgin Airlines" So -- how can I start to automagically extract trends/examples of strings that may be more similar. Approaches I've considered and discarded ('because there must be some better way'): Extracting all the possible substrings and ordering them by how often they show up, and manually selecting relevant ones Stripping off the first word or two and then count the occurrence of each sub string Comparing Levenshtein distance between entries Some sort of string similarity index ... Most of these were rejected for massive inefficiency or likelyhood of a vast amount of manual intervention required. I guess I need some sort of fuzzy string matching..? In the end, I can think of kludgy ways of doing this, but I'm looking for something more generic so I've added to my set of tools rather than special casing for this data set. After this, I'd be matching the occurring of particular subject strings with 'From' addresses - I'm not sure if there's a good way of building a data structure that represents how likely/not two messages are part of the 'same email list' or by filtering all my email subjects/from addresses into pools of likely 'related' emails and not -- but that's a problem to solve after this one. Any guidance would be appreciated.

    Read the article

  • Null-free "maps": Is a callback solution slower than tryGet()?

    - by David Moles
    In comments to "How to implement List, Set, and Map in null free design?", Steven Sudit and I got into a discussion about using a callback, with handlers for "found" and "not found" situations, vs. a tryGet() method, taking an out parameter and returning a boolean indicating whether the out parameter had been populated. Steven maintained that the callback approach was more complex and almost certain to be slower; I maintained that the complexity was no greater and the performance at worst the same. But code speaks louder than words, so I thought I'd implement both and see what I got. The original question was fairly theoretical with regard to language ("And for argument sake, let's say this language don't even have null") -- I've used Java here because that's what I've got handy. Java doesn't have out parameters, but it doesn't have first-class functions either, so style-wise, it should suck equally for both approaches. (Digression: As far as complexity goes: I like the callback design because it inherently forces the user of the API to handle both cases, whereas the tryGet() design requires callers to perform their own boilerplate conditional check, which they could forget or get wrong. But having now implemented both, I can see why the tryGet() design looks simpler, at least in the short term.) First, the callback example: class CallbackMap<K, V> { private final Map<K, V> backingMap; public CallbackMap(Map<K, V> backingMap) { this.backingMap = backingMap; } void lookup(K key, Callback<K, V> handler) { V val = backingMap.get(key); if (val == null) { handler.handleMissing(key); } else { handler.handleFound(key, val); } } } interface Callback<K, V> { void handleFound(K key, V value); void handleMissing(K key); } class CallbackExample { private final Map<String, String> map; private final List<String> found; private final List<String> missing; private Callback<String, String> handler; public CallbackExample(Map<String, String> map) { this.map = map; found = new ArrayList<String>(map.size()); missing = new ArrayList<String>(map.size()); handler = new Callback<String, String>() { public void handleFound(String key, String value) { found.add(key + ": " + value); } public void handleMissing(String key) { missing.add(key); } }; } void test() { CallbackMap<String, String> cbMap = new CallbackMap<String, String>(map); for (int i = 0, count = map.size(); i < count; i++) { String key = "key" + i; cbMap.lookup(key, handler); } System.out.println(found.size() + " found"); System.out.println(missing.size() + " missing"); } } Now, the tryGet() example -- as best I understand the pattern (and I might well be wrong): class TryGetMap<K, V> { private final Map<K, V> backingMap; public TryGetMap(Map<K, V> backingMap) { this.backingMap = backingMap; } boolean tryGet(K key, OutParameter<V> valueParam) { V val = backingMap.get(key); if (val == null) { return false; } valueParam.value = val; return true; } } class OutParameter<V> { V value; } class TryGetExample { private final Map<String, String> map; private final List<String> found; private final List<String> missing; public TryGetExample(Map<String, String> map) { this.map = map; found = new ArrayList<String>(map.size()); missing = new ArrayList<String>(map.size()); } void test() { TryGetMap<String, String> tgMap = new TryGetMap<String, String>(map); for (int i = 0, count = map.size(); i < count; i++) { String key = "key" + i; OutParameter<String> out = new OutParameter<String>(); if (tgMap.tryGet(key, out)) { found.add(key + ": " + out.value); } else { missing.add(key); } } System.out.println(found.size() + " found"); System.out.println(missing.size() + " missing"); } } And finally, the performance test code: public static void main(String[] args) { int size = 200000; Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < size; i++) { String val = (i % 5 == 0) ? null : "value" + i; map.put("key" + i, val); } long totalCallback = 0; long totalTryGet = 0; int iterations = 20; for (int i = 0; i < iterations; i++) { { TryGetExample tryGet = new TryGetExample(map); long tryGetStart = System.currentTimeMillis(); tryGet.test(); totalTryGet += (System.currentTimeMillis() - tryGetStart); } System.gc(); { CallbackExample callback = new CallbackExample(map); long callbackStart = System.currentTimeMillis(); callback.test(); totalCallback += (System.currentTimeMillis() - callbackStart); } System.gc(); } System.out.println("Avg. callback: " + (totalCallback / iterations)); System.out.println("Avg. tryGet(): " + (totalTryGet / iterations)); } On my first attempt, I got 50% worse performance for callback than for tryGet(), which really surprised me. But, on a hunch, I added some garbage collection, and the performance penalty vanished. This fits with my instinct, which is that we're basically talking about taking the same number of method calls, conditional checks, etc. and rearranging them. But then, I wrote the code, so I might well have written a suboptimal or subconsicously penalized tryGet() implementation. Thoughts?

    Read the article

  • finding common prefix of array of strings

    - by bumperbox
    I have an array like this $sports = array( 'Softball - Counties', 'Softball - Eastern', 'Softball - North Harbour', 'Softball - South', 'Softball - Western' ); and i would like to find the longest common part of the string so in this instance, it would be 'Softball - '; I am thinking that I would follow the this process $i = 1; // loop to the length of the first string while ($i < strlen($sports[0]) { // grab the left most part up to i in length $match = substr($sports[0], 0, $i); // loop through all the values in array, and compare if they match foreach ($sports as $sport) { if ($match != substr($sport, 0, $i) { // didn't match, return the part that did match return substr($sport, 0, $i-1); } } // foreach // increase string length $i++; } // while // if you got to here, then all of them must be identical Questions is there a built in function or much simpler way of doing this ? for my 5 line array that is probably fine, but if i were to do several thousand line arrays, there would be a lot of overhead, so i would have to be move calculated with my starting values of $i, eg $i = halfway of string, if it fails, then $i/2 until it works, then increment $i by 1 until we succeed. so that we are doing the least number of comparisons to get a result If there a formula/algorithm out already out there for this kind of problem ? thanks alex

    Read the article

  • Python finding substring between certain characters using regex and replace()

    - by jCuga
    Suppose I have a string with lots of random stuff in it like the following: strJunk ="asdf2adsf29Value=five&lakl23ljk43asdldl" And I'm interested in obtaining the substring sitting between 'Value=' and '&', which in this example would be 'five'. I can use a regex like the following: match = re.search(r'Value=?([^&>]+)', strJunk) >>> print match.group(0) Value=five >>> print match.group(1) five How come match.group(0) is the whole thing 'Value=five' and group(1) is just 'five'? And is there a way for me to just get 'five' as the only result? (This question stems from me only having a tenuous grasp of regex) I am also going to have to make a substitution in this string such such as the following: val1 = match.group(1) strJunk.replace(val1, "six", 1) Which yields: 'asdf2adsf29Value=six&lakl23ljk43asdldl' Considering that I plan on performing the above two tasks (finding the string between 'Value=' and '&', as well as replacing that value) over and over, I was wondering if there are any other more efficient ways of looking for the substring and replacing it in the original string. I'm fine sticking with what I've got but I just want to make sure that I'm not taking up more time than I have to be if better methods are out there.

    Read the article

  • java phone number validation....

    - by user69514
    Here is my problem: Create a constructor for a telephone number given a string in the form xxx-xxx-xxxx or xxx-xxxx for a local number. Throw an exception if the format is not valid. So I was thinking to validate it using a regular expression, but I don't know if I'm doing it correctly. Also what kind of exception would I have to throw? Do I need to create my own exception? public TelephoneNumber(String aString){ if(isPhoneNumberValid(aString)==true){ StringTokenizer tokens = new StringTokenizer("-"); if(tokens.countTokens()==3){ areaCode = Integer.parseInt(tokens.nextToken()); exchangeCode = Integer.parseInt(tokens.nextToken()); number = Integer.parseInt(tokens.nextToken()); } else if(tokens.countTokens()==2){ exchangeCode = Integer.parseInt(tokens.nextToken()); number = Integer.parseInt(tokens.nextToken()); } else{ //throw an excemption here } } } public static boolean isPhoneNumberValid(String phoneNumber){ boolean isValid = false; //Initialize reg ex for phone number. String expression = "(\\d{3})(\\[-])(\\d{4})$"; CharSequence inputStr = phoneNumber; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()){ isValid = true; } return isValid; } Hi sorry, yes this is homework. For this assignments the only valid format are xxx-xxx-xxxx and xxx-xxxx, all other formats (xxx)xxx-xxxx or xxxxxxxxxx are invalid in this case. I would like to know if my regular expression is correct

    Read the article

  • Output error in comparing characters from two strings

    - by Andrew Martin
    I'm stuck with my a piece of code I'm creating. My IDE is Eclipse and when I use its debugging feature, to trace what's happening on each line, it outputs perfectly. However, when I click the "run" project, it just outputs a blank screen: public static void compareInterests(Client[] clientDetails) { int interests = 0; for (int p = 0; p < numberOfClients; p++) { for (int q = 0; q < numberOfClients; q++) { String a = clientDetails[p].getClientInterests(); String b = clientDetails[q].getClientInterests(); int count = 0; while (count < a.length()) { if (a.charAt(count) == b.charAt(count)) interests++; count++; } if ((interests >= 3) && (clientDetails[p].getClientName() != clientDetails[q].getClientName())) System.out.print (clientDetails[p].getClientName() + " is compatible with " + clientDetails[q].getClientName()); interests = 0; } } } The code is designed to import an object array which contains information on a client's name and a client's interests. The client's interests are stored in the format "01010", where each 1 means they are interested in that activity, each 0 means they are not. My code compares each character of every client's string with every other client's string and outputs the results for all client's that don't have the same name and have three or more interests in common. When I run this code through Java's debugger, it outputs fine - but when I click run project or compile, I just get a blank screen. Any ideas?

    Read the article

  • Generate regular expression to match strings from the list A, but not from list B

    - by Vlad
    I have two lists of strings ListA and ListB. I need to generate a regular expression that will match all strings in ListA and will not match any string in ListB. The strings could contain any combination of characters, numbers and punctuation. If a string appears on ListA it is guaranteed that it will not be in the ListB. If a string is not in either of these two lists I don't care what the result of the matching should be. The lists typically contain thousands of strings, and strings are fairly similar to each other. I know the trivial answer to this question, which is just generate a regular expression of the form (Str1)|(Str2)|(Str3) where StrN is the string from ListA. But I am looking for a more efficient way to do this. Ideal solution would be some sort of tool that will take two lists and generate a Java regular expression for this. Update 1: By "efficient", I mean to generate expression that is shorter than trivial solution. The ideal algorithm would generate the shorted possible expression. Here are some examples. ListA = { C10 , C15, C195 } ListB = { Bob, Billy } The ideal expression would be /^C1.+$/ Another example, note the third element of ListB ListA = { C10 , C15, C195 } ListB = { Bob, Billy, C25 } The ideal expression is /^C[^2]{1}.+$/ The last example ListA = { A , D ,E , F , H } ListB = { B , C , G , I } The ideal expression is the same as trivial solution which is /^(A|D|E|F|H)$/ Also, I am not looking for the ideal solution, anything better than trivial would help. I was thinking along the lines of generating the list of trivial solutions, and then try to merge the common substrings while watching that we don't wander into ListB territory. *Update 2: I am not particularly worried about the time it takes to generate the RegEx, anything under 10 minutes on the modern machine is acceptable

    Read the article

  • Error Handling in T-SQL Scalar Function

    - by hydroparadise
    Ok.. this question could easily take multiple paths, so I will hit the more specific path first. While working with SQL Server 2005, I'm trying to create a scalar funtion that acts as a 'TryCast' from varchar to int. Where I encounter a problem is when I add a TRY block in the function; CREATE FUNCTION u_TryCastInt ( @Value as VARCHAR(MAX) ) RETURNS Int AS BEGIN DECLARE @Output AS Int BEGIN TRY SET @Output = CONVERT(Int, @Value) END TRY BEGIN CATCH SET @Output = 0 END CATCH RETURN @Output END Turns out theres all sorts of things wrong with this statement including "Invalid use of side-effecting or time-dependent operator in 'BEGIN TRY' within a function" and "Invalid use of side-effecting or time-dependent operator in 'END TRY' within a function". I can't seem to find any examples of using try statements within a scalar function, which got me thinking, is error handling in a function is possible? The goal here is to make a robust version of the Convert or Cast functions to allow a SELECT statement carry through depsite conversion errors. For example, take the following; CREATE TABLE tblTest ( f1 VARCHAR(50) ) GO INSERT INTO tblTest(f1) VALUES('1') INSERT INTO tblTest(f1) VALUES('2') INSERT INTO tblTest(f1) VALUES('3') INSERT INTO tblTest(f1) VALUES('f') INSERT INTO tblTest(f1) VALUES('5') INSERT INTO tblTest(f1) VALUES('1.1') SELECT CONVERT(int,f1) AS f1_num FROM tblTest DROP TABLE tblTest It never reaches point of dropping the table because the execution gets hung on trying to convert 'f' to an integer. I want to be able to do something like this; SELECT u_TryCastInt(f1) AS f1_num FROM tblTest fi_num __________ 1 2 3 0 5 0 Any thoughts on this? Is there anything that exists that handles this? Also, I would like to try and expand the conversation to support SQL Server 2000 since Try blocks are not an option in that scenario. Thanks in advance.

    Read the article

  • Convert RGB value to HSV

    - by marionmaiden
    I've found a method on the Internet to convert RGB values to HSV values. Unfortunately, when the values are R=G=B, I'm getting a NaN, because of the 0/0 operation. Do you know if there is an implemented method for this conversion in Java, or what do I have to do when I get the 0/0 division to get the right value of the HSV? Here comes my method, adapted from some code on the Internet: public static double[] RGBtoHSV(double r, double g, double b){ double h, s, v; double min, max, delta; min = Math.min(Math.min(r, g), b); max = Math.max(Math.max(r, g), b); // V v = max; delta = max - min; // S if( max != 0 ) s = delta / max; else { s = 0; h = -1; return new double[]{h,s,v}; } // H if( r == max ) h = ( g - b ) / delta; // between yellow & magenta else if( g == max ) h = 2 + ( b - r ) / delta; // between cyan & yellow else h = 4 + ( r - g ) / delta; // between magenta & cyan h *= 60; // degrees if( h < 0 ) h += 360; return new double[]{h,s,v}; }

    Read the article

  • TypeConverter prevents ApplyPropertyChanges in EntityFramework

    - by Felix
    I ran into an interesting problem (hopefully, interesting not just for me :) I am running Entity Framework 1 (.NET 3.5) and ASP.NET MVC 2. I have a Customer class that has many-to-one relationship with Country class (in other words, Country is a lookup table for customers - I described more in this post: http://stackoverflow.com/questions/2404801/explicit-casting-doesnt-work-in-default-model-binding ) I got TypeConverter to work; so I am getting a perfect object into controller's Post method. Create works fine; however, in Edit I am getting the following error when I call ApplyPropertyChanges: The existing object in the ObjectContext is in the Added state. Changes can only be applied when the existing object is in an unchanged or modified state. The controller code is fairly trivial: public ActionResult Edit(Customer customerToEdit) { if (ModelState.IsValid) { Customer cust = (Customer)context.GetObjectByKey( new EntityKey("BAEntities.Customers", "CustomerID", customerToEdit.CustomerID)); context.ApplyPropertyChanges(cust.EntityKey.EntitySetName, customerToEdit); context.SaveChanges(); } return View(...); } If I remove country from the form, it works fine; and if I assign dropdown value to EntityReference "manually" - it works as well. TypeConverter code is also fairly simple, but I've never used TypeConverter before, so I may be missing something here: public override object ConvertFrom(ITypeDescriptorContext typeContext, CultureInfo culture, object value) { if (value is string) { int countryID = Int16.Parse((string)value); Country country = (Country)context.GetObjectByKey( new EntityKey("BAEntities.Countries", "CountryID", countryID)); return country; } return base.ConvertFrom(typeContext, culture, value); }

    Read the article

  • Java SortedMap to Scala TreeMap

    - by Dave
    I'm having trouble converting a java SortedMap into a scala TreeMap. The SortedMap comes from deserialization and needs to be converted into a scala structure before being used. Some background, for the curious, is that the serialized structure is written through XStream and on desializing I register a converter that says anything that can be assigned to SortedMap[Comparable[_],_] should be given to me. So my convert method gets called and is given an Object that I can safely cast because I know it's of type SortedMap[Comparable[_],_]. That's where it gets interesting. Here's some sample code that might help explain it. // a conversion from comparable to ordering scala> implicit def comparable2ordering[A <: Comparable[A]](x: A): Ordering[A] = new Ordering[A] { | def compare(x: A, y: A) = x.compareTo(y) | } comparable2ordering: [A <: java.lang.Comparable[A]](x: A)Ordering[A] // jm is how I see the map in the converter. Just as an object. I know the key // is of type Comparable[_] scala> val jm : Object = new java.util.TreeMap[Comparable[_], String]() jm: java.lang.Object = {} // It's safe to cast as the converter only gets called for SortedMap[Comparable[_],_] scala> val b = jm.asInstanceOf[java.util.SortedMap[Comparable[_],_]] b: java.util.SortedMap[java.lang.Comparable[_], _] = {} // Now I want to convert this to a tree map scala> collection.immutable.TreeMap() ++ (for(k <- b.keySet) yield { (k, b.get(k)) }) <console>:15: error: diverging implicit expansion for type Ordering[A] starting with method Tuple9 in object Ordering collection.immutable.TreeMap() ++ (for(k <- b.keySet) yield { (k, b.get(k)) })

    Read the article

  • Image File In Text Editor - What Are The Characters? What's the Process?

    - by TheDarkIn1978
    i'm currently in the process of conceptualizing an art piece for a gallery show next year, so this bizarre question of mine is more than just simple curiosity. if i open up an image file (a .PNG) with Text Edit or Note Pad, the file is presented in textual characters. something like this except: æº"í=™?0Ù:Ã,ÏI8^?K¯pmDHƒÃ?;wÔlD DDF›ä™èÜE[E˜ƒê?¯ƒºäeèçã?'ów+æ1ï‡ê0òHõñ?ò$úîù¥{WÎn}2*Ÿ!y(Ö!%2e9U2µ i4Õ(?=ù(›7}:É?##„G¶VfcVñ[÷D6gvrˆvéZN›=Ù=ó{púp…p?Ók‹oÃvŒÛ»{ùœóüôøW†W–VH\P?P$VTPt^lQ‹_B_S=Q™\Z[Ü)s/{]Œ_û]~¯¿¯Awu˜ùä’JÖ Í*tï[’ÎáÔ=<Æ6?~ZCWSÛpVµ?±ØŒ?nÆ^¨æ??™¡?a¥ë£1µÒÁ#?Gè)G<^mRl™m?jˆj~€"“R–Úª’?u?çO-•m˜â?ìéväˆàˆOä5ùXùûù”]¬]?]›V›œ{X{Óˆ|Ô’Èm{J?4‰Èáæõ}??~Á?óºYáœåüuRFÆ>W|^3Ñ5‰94=,<ú?|1b=2< >ö:?sÃ`¨{úf<f|ÛÖ?ãÊ íâ–âè/_÷O¬}Â?Í›§Ãd’kÃkØ?sSíS? ??øy;-6]ˆ?÷ÌÌÙåËLÈ,l÷uvzNtÆt6Ô6?O ?P?_t_|°N¸]Ÿ{ƒ{è˜3KK> ?x~ò[ñ\ÆXA?x?Ãî?X? ?…°”¸™‘jÂzÕkm~]jObµ·p1°Y‚s?&b”}s?ãËóí-»ñ”÷‰?‡v?ˆ˜WõØ£??æe~;¸n?Ooáa'aÁÎÌ-ª$ª!ª~ ?¨‹CÏpÏO/Á›œ/?80<Ë<§8 can anyone explain what is happening here? are the characters some form translation of pixel data by the text editor? maybe it is completely meaningless / an error? if not, is there a name for this type of data conversion or process?

    Read the article

  • Convert float to decimal in Informix

    - by prabhu
    I have a table with a column of type decimal. There is a ESQL/C structure that represents the table. It has a member of type decimal. I also have a normal C structure for equivalent for the same table. The type of the above mentioned field is a float. Since we use memcpy to copy data to and from ESQL/C structure to C structure, there is an issue with decimal to float conversion. When I searched the Informix ESQL/C Programmer's manual, I couldn't find any function that can do this. Google search led me to the deccvflt() function. This function converts from a float to a decimal type. Though I couldn't find this function listed in the manual, I see the declarations in decimal.h. Are these functions still recommended to be used? Alternatively, I was also thinking about using the decimal type in the C structure also, as it happens to be a C structure. This way, I can still use the memcpy right? Please share your thoughts. IBM Informix Dynamic Server Version 11.50.FC3 Thanks, prabhu

    Read the article

  • How to scan convert right edges and slopes less than one?

    - by Zachary
    I'm writing a program which will use scan conversion on triangles to fill in the pixels contained within the triangle. One thing that has me confused is how to determine the x increment for the right edge of the triangle, or for slopes less than or equal to one. Here is the code I have to handle left edges with a slope greater than one (obtained from Computer Graphics: Principles and Practice second edition): for(y=ymin;y<=ymax;y++) { edge.increment+=edge.numerator; if(edge.increment>edge.denominator) { edge.x++; edge.increment -= edge.denominator; } } The numerator is set from (xMax-xMin), and the denominator is set from (yMax-yMin)...which makes sense as it represents the slope of the line. As you move up the scan lines (represented by the y values). X is incremented by 1/(denomniator/numerator) ...which results in x having a whole part and a fractional part. If the fractional part is greater than one, then the x value has to be incremented by 1 (as shown in edge.incrementedge.denominator). This works fine for any left handed lines with a slope greater than one, but I'm having trouble generalizing it for any edge, and google-ing has proved fruitless. Does anyone know the algorithm for that?

    Read the article

  • Should I go vor Arrays or Objects in PHP in a CouchDB/Ajax app?

    - by karlthorwald
    I find myself converting between array and object all the time in PHP application that uses couchDB and Ajax. Of course I am also converting objects to JSON and back (for sometimes couchdb but mostly Ajax), but this is not so much disturbing my workflow. At the present I have php objects that are returned by the CouchDB modules I use and on the other hand I have the old habbit to return arrays like array("error"="not found","data"=$dataObj) from my functions. This leads to a mixed occurence of real php objects and nested arrays and I cast with (object) or (array) if necessary. The worst thing is that I know more or less by heart what a function returns, but not what type (array or object), so I often run into type errors. My plan is now to always cast arrays to objects before returning from a function. Of course this implies a lot of refactoring. Is this the right way to go? What about the conversion overhead? Other ideas or tips? Edit: Kenaniah's answer suggests I should go the other way, this would mean I'd cast everything to arrays. And for all the Ajax / JSON stuff and also for CouchDB I would use $myarray = json_decode($json_data,$assoc = false) Even more work to change all the CouchDB and Ajax functions but in the end I have better code.

    Read the article

  • Cannot convert object, recieved from ajax call, into a long

    - by Matt
    I'm using Asp.Net-Mvc, I have this method in my controller: [AcceptVerbs(HttpVerbs.Post)] public ActionResult LinkAccount(string site, object id) { return this.Json(id); } Here's the ajax method that calls it: $.post("/Account/LinkAccount", { site: "Facebook", id: FB.Facebook.apiClient.get_session().uid }, function(result) { alert(result); }, "json" ); returning this.Json(id); makes the alert work... it alerts 7128383 (something similar to that). but if I change this.Json(id) to this.Json(Conver.ToInt64(id)); the alert does not fire... Any idea of why I can't convert an object received from an object to a long? I already know changing the LinkAccount method to accept a long instead works just fine. It's just I need it as an object because some other sites I'm linking up have strings for id's rather than longs. UPDATE: I tried running the code on localhost so I could set a breakpoint. First I changed the line return this.Json(Convert.ToInt64(id)); to long idAsLong = Convert.ToInt64(id));. Here's what the debugger is telling me: When I hover over id it says: "id | {string[1]}" and when I press the plus button is shows: "[0] | '7128383'" When I hover over idAsLong, it says: "idAsLong | 0" Why isn't it converting it properly?

    Read the article

  • How to convert source code to a xml based representation of the ast?

    - by autobiographer
    i wanna get a xml representation of the ast of java and c code. 3 months ago, i asked this question yet but the solutions weren't comfortable for me srcml seems to be a good solution for this problem but it does not support line numbers and columns but i need that feature. about elsa: cite: "There is ongoing effort to export the Elsa AST as an XML document; we expect to be able to advertise this in the next public release." dms... didn't understand that. especially for java, there is javaml which supports line numbers. but the sourceforge page doesn't list any files. question: there's software available which supports conversion of ast into xml which supports line numbers (and columns) [especially for java and c/c++]? is there an alternative to javaml and srcml? ps: i don't wanne have parser generators. i hope to find a tool which can be used on the console typing: ./my-xml-generator Test.java [or something like that]... or a java implementation would be great too.

    Read the article

  • Convert UCS-2 characters to UTF-8 Using C#

    - by quanticle
    I'm pulling some internationalized text from a MS SQL Server 2005 database. As per the defaults for that DB, the characters are stored as UCS-2. However, I need to output the data in UTF-8 format, as I'm sending it out over the web. Currently, I have the following code to convert: SqlString dbString = resultReader.GetSqlString(0); byte[] dbBytes = dbString.GetUnicodeBytes(); byte[] utf8Bytes = System.Text.Encoding.Convert(System.Text.Encoding.Unicode, System.Text.Encoding.UTF8, dbBytes); System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); string outputString = encoder.GetString(utf8Bytes); However, when I examine the output in the browser, it appears to be garbage, no matter what I set the encoding to. What am I missing? EDIT: In response to the answers below, the reason I thought I had to perform a conversion is because I can output literal multibyte strings just fine. For example: OutputControl.Text = "????????????????????????????????????????????????????????????????"; works. Here, OutputControl is an ASP.Net Literal. However, OutputControl.Text = outputString; //Output from above snippet results in mangled output as described above. My hypothesis was that the database's output was somehow getting mangled by ASP.Net. If that's not the case, then what are some other possibilities?

    Read the article

  • Should I go for Arrays or Objects in PHP in a CouchDB/Ajax app?

    - by karlthorwald
    I find myself converting between array and object all the time in PHP application that uses couchDB and Ajax. Of course I am also converting objects to JSON and back (for sometimes couchdb but mostly Ajax), but this is not so much disturbing my workflow. At the present I have php objects that are returned by the CouchDB modules I use and on the other hand I have the old habbit to return arrays like array("error"="not found","data"=$dataObj) from my functions. This leads to a mixed occurence of real php objects and nested arrays and I cast with (object) or (array) if necessary. The worst thing is that I know more or less by heart what a function returns, but not what type (array or object), so I often run into type errors. My plan is now to always cast arrays to objects before returning from a function. Of course this implies a lot of refactoring. Is this the right way to go? What about the conversion overhead? Other ideas or tips? Edit: Kenaniah's answer suggests I should go the other way, this would mean I'd cast everything to arrays. And for all the Ajax / JSON stuff and also for CouchDB I would use $myarray = json_decode($json_data,$assoc = true); //EDIT: changed to true, whcih is what I really meant Even more work to change all the CouchDB and Ajax functions but in the end I have better code.

    Read the article

  • Converting ntext to nvcharmax(max) - Getting around size limitation

    - by Overflew
    Hi all, I'm trying to change an existing SQL NText column to nvcharmax(max), and encountering an error on the size limit. There's a large amount of existing data, some of which is more than the 8k limit, I believe. We're looking to convert this, so that the field is searchable in LINQ. The 2x SQL statements I've tried are: update Table set dataNVarChar = convert(nvarchar(max), dataNtext) where dataNtext is not null update Table set dataNVarChar = cast(dataNtext as nvarchar(max)) where dataNtext is not null And the error I get is: Cannot create a row of size 8086 which is greater than the allowable maximum row size of 8060. This is using SQL Server 2008. Any help appreciated, Thanks. Update / Solution: The marked answer below is correct, and SQL 2008 can change the column to the correct data type in my situation, and there are no dramas with the LINQ-utilising application we use on top of it: alter table [TBL] alter column [COL] nvarchar(max) I've also been advised to follow it up with: update [TBL] set [COL] = [COL] Which completes the conversion by moving the data from the lob structure to the table (if the length in less than 8k), which improves performance / keeps things proper.

    Read the article

  • Type result with Ternary operator in C#

    - by Vaccano
    I am trying to use the ternary operator, but I am getting hung up on the type it thinks the result should be. Below is an example that I have contrived to show the issue I am having: class Program { public static void OutputDateTime(DateTime? datetime) { Console.WriteLine(datetime); } public static bool IsDateTimeHappy(DateTime datetime) { if (DateTime.Compare(datetime, DateTime.Parse("1/1")) == 0) return true; return false; } static void Main(string[] args) { DateTime myDateTime = DateTime.Now; OutputDateTime(IsDateTimeHappy(myDateTime) ? null : myDateTime); Console.ReadLine(); ^ } | } | // This line has the compile issue ---------------+ On the line indicated above, I get the following compile error: Type of conditional expression cannot be determined because there is no implicit conversion between '< null ' and 'System.DateTime' I am confused because the parameter is a nullable type (DateTime?). Why does it need to convert at all? If it is null then use that, if it is a date time then use that. I was under the impression that: condition ? first_expression : second_expression; was the same as: if (condition) first_expression; else second_expression; Clearly this is not the case. What is the reasoning behind this? (NOTE: I know that if I make "myDateTime" a nullable DateTime then it will work. But why does it need it? As I stated earlier this is a contrived example. In my real example "myDateTime" is a data mapped value that cannot be made nullable.)

    Read the article

  • Converting "A* Search" code from C++ to Java [on hold]

    - by mr5
    Updated! I get this code from this site It's A* Search Algorithm(finding shortest path with heuristics) I modify most of variable names and some if conditions from the original version to satisfy my syntactic taste. It works in C++ (as I can't see any trouble with it) but fails in Java version. Java Code: String findPath(int startX, int startY, int finishX, int finishY) { @SuppressWarnings("unchecked") LinkedList<Node>[] nodeList = (LinkedList<Node>[]) new LinkedList<?>[2]; nodeList[0] = new LinkedList<Node>(); nodeList[1] = new LinkedList<Node>(); Node n0; Node m0; int nlIndex = 0; // queueList index // reset the node maps for(int y = 0;y < ROW_COUNT; ++y) { for(int x = 0;x < COL_COUNT; ++x) { close_nodes_map[y][x] = 0; open_nodes_map[y][x] = 0; } } // create the start node and push into list of open nodes n0 = new Node( startX, startY, 0, 0 ); n0.updatePriority( finishX, finishY ); nodeList[nlIndex].push( n0 ); open_nodes_map[startY][startX] = n0.getPriority(); // mark it on the open nodes map // A* search while( !nodeList[nlIndex].isEmpty() ) { LinkedList<Node> pq = nodeList[nlIndex]; // get the current node w/ the highest priority // from the list of open nodes n0 = new Node( pq.peek().getX(), pq.peek().getY(), pq.peek().getIterCount(), pq.peek().getPriority()); int x = n0.getX(); int y = n0.getY(); nodeList[nlIndex].pop(); // remove the node from the open list open_nodes_map[y][x] = 0; // mark it on the closed nodes map close_nodes_map[y][x] = 1; // quit searching when the goal state is reached //if((*n0).estimate(finishX, finishY) == 0) if( x == finishX && y == finishY ) { // generate the path from finish to start // by following the directions String path = ""; while( !( x == startX && y == startY) ) { int j = dir_map[y][x]; int c = '0' + ( j + Node.DIRECTION_COUNT / 2 ) % Node.DIRECTION_COUNT; path = (char)c + path; x += DIR_X[j]; y += DIR_Y[j]; } return path; } // generate moves (child nodes) in all possible directions for(int i = 0; i < Node.DIRECTION_COUNT; ++i) { int xdx = x + DIR_X[i]; int ydy = y + DIR_Y[i]; // boundary check if (!(xdx >= 0 && xdx < COL_COUNT && ydy >= 0 && ydy < ROW_COUNT)) continue; if ( ( gridMap.getData( ydy, xdx ) == GridMap.WALKABLE || gridMap.getData( ydy, xdx ) == GridMap.FINISH) && close_nodes_map[ydy][xdx] != 1 ) { // generate a child node m0 = new Node( xdx, ydy, n0.getIterCount(), n0.getPriority() ); m0.nextLevel( i ); m0.updatePriority( finishX, finishY ); // if it is not in the open list then add into that if( open_nodes_map[ydy][xdx] == 0 ) { open_nodes_map[ydy][xdx] = m0.getPriority(); nodeList[nlIndex].push( m0 ); // mark its parent node direction dir_map[ydy][xdx] = ( i + Node.DIRECTION_COUNT / 2 ) % Node.DIRECTION_COUNT; } else if( open_nodes_map[ydy][xdx] > m0.getPriority() ) { // update the priority info open_nodes_map[ydy][xdx] = m0.getPriority(); // update the parent direction info dir_map[ydy][xdx] = ( i + Node.DIRECTION_COUNT / 2 ) % Node.DIRECTION_COUNT; // replace the node // by emptying one queueList to the other one // except the node to be replaced will be ignored // and the new node will be pushed in instead while( !(nodeList[nlIndex].peek().getX() == xdx && nodeList[nlIndex].peek().getY() == ydy ) ) { nodeList[1 - nlIndex].push( nodeList[nlIndex].pop() ); } nodeList[nlIndex].pop(); // remove the wanted node // empty the larger size queueList to the smaller one if( nodeList[nlIndex].size() > nodeList[ 1 - nlIndex ].size() ) nlIndex = 1 - nlIndex; while( !nodeList[nlIndex].isEmpty() ) { nodeList[1 - nlIndex].push( nodeList[nlIndex].pop() ); } nlIndex = 1 - nlIndex; nodeList[nlIndex].push( m0 ); // add the better node instead } } } } return ""; // no route found } Output1: Legends . = PATH ? = START X = FINISH 3,2,1 = OBSTACLES (Misleading path) Output2: Changing these lines: n0 = new Node( a, b, c, d ); m0 = new Node( e, f, g, h ); to n0.set( a, b, c, d ); m0.set( e, f, g, h ); I get (I'm really confused) C++ Code: std::string A_Star::findPath(int startX, int startY, int finishX, int finishY) { typedef std::queue<Node> List_Container; List_Container nodeList[2]; // list of open (not-yet-tried) nodes Node n0; Node m0; int pqIndex = 0; // nodeList index // reset the node maps for(int y = 0;y < ROW_COUNT; ++y) { for(int x = 0;x < COL_COUNT; ++x) { close_nodes_map[y][x] = 0; open_nodes_map[y][x] = 0; } } // create the start node and push into list of open nodes n0 = Node( startX, startY, 0, 0 ); n0.updatePriority( finishX, finishY ); nodeList[pqIndex].push( n0 ); open_nodes_map[startY][startX] = n0.getPriority(); // mark it on the open nodes map // A* search while( !nodeList[pqIndex].empty() ) { List_Container &pq = nodeList[pqIndex]; // get the current node w/ the highest priority // from the list of open nodes n0 = Node( pq.front().getX(), pq.front().getY(), pq.front().getIterCount(), pq.front().getPriority()); int x = n0.getX(); int y = n0.getY(); nodeList[pqIndex].pop(); // remove the node from the open list open_nodes_map[y][x] = 0; // mark it on the closed nodes map close_nodes_map[y][x] = 1; // quit searching when the goal state is reached //if((*n0).estimate(finishX, finishY) == 0) if( x == finishX && y == finishY ) { // generate the path from finish to start // by following the directions std::string path = ""; while( !( x == startX && y == startY) ) { int j = dir_map[y][x]; char c = '0' + ( j + DIRECTION_COUNT / 2 ) % DIRECTION_COUNT; path = c + path; x += DIR_X[j]; y += DIR_Y[j]; } return path; } // generate moves (child nodes) in all possible directions for(int i = 0; i < DIRECTION_COUNT; ++i) { int xdx = x + DIR_X[i]; int ydy = y + DIR_Y[i]; // boundary check if (!( xdx >= 0 && xdx < COL_COUNT && ydy >= 0 && ydy < ROW_COUNT)) continue; if ( ( pGrid->getData(ydy,xdx) == WALKABLE || pGrid->getData(ydy, xdx) == FINISH) && close_nodes_map[ydy][xdx] != 1 ) { // generate a child node m0 = Node( xdx, ydy, n0.getIterCount(), n0.getPriority() ); m0.nextLevel( i ); m0.updatePriority( finishX, finishY ); // if it is not in the open list then add into that if( open_nodes_map[ydy][xdx] == 0 ) { open_nodes_map[ydy][xdx] = m0.getPriority(); nodeList[pqIndex].push( m0 ); // mark its parent node direction dir_map[ydy][xdx] = ( i + DIRECTION_COUNT / 2 ) % DIRECTION_COUNT; } else if( open_nodes_map[ydy][xdx] > m0.getPriority() ) { // update the priority info open_nodes_map[ydy][xdx] = m0.getPriority(); // update the parent direction info dir_map[ydy][xdx] = ( i + DIRECTION_COUNT / 2 ) % DIRECTION_COUNT; // replace the node // by emptying one nodeList to the other one // except the node to be replaced will be ignored // and the new node will be pushed in instead while ( !( nodeList[pqIndex].front().getX() == xdx && nodeList[pqIndex].front().getY() == ydy ) ) { nodeList[1 - pqIndex].push( nodeList[pqIndex].front() ); nodeList[pqIndex].pop(); } nodeList[pqIndex].pop(); // remove the wanted node // empty the larger size nodeList to the smaller one if( nodeList[pqIndex].size() > nodeList[ 1 - pqIndex ].size() ) pqIndex = 1 - pqIndex; while( !nodeList[pqIndex].empty() ) { nodeList[1-pqIndex].push(nodeList[pqIndex].front()); nodeList[pqIndex].pop(); } pqIndex = 1 - pqIndex; nodeList[pqIndex].push( m0 ); // add the better node instead } } } } return ""; // no route found } Output: Legends . = PATH ? = START X = FINISH 3,2,1 = OBSTACLES (Just right) From what I read about Java's documentation, I came up with the conclusion: C++'s std::queue<T>::front() == Java's LinkedList<T>.peek() Java's LinkedList<T>.pop() == C++'s std::queue<T>::front() + std::queue<T>::pop() What might I be missing in my Java version? In what way does it became different algorithmically from the C++ version?

    Read the article

  • Helper method to Replace/Remove characters that do not match the Regular Expression

    - by Michael Freidgeim
    I have a few fields, that use regEx for validation. In case if provided field has unaccepted characters, I don't want to reject the whole field, as most of validators do, but just remove invalid characters. I am expecting to keep only Character Classes for allowed characters and created a helper method to strip unaccepted characters. The allowed pattern should be in Regex format, expect them wrapped in square brackets. function will insert a tilde after opening squere bracket , according to http://stackoverflow.com/questions/4460290/replace-chars-if-not-match.  [^ ] at the start of a character class negates it - it matches characters not in the class.I anticipate that it could work not for all RegEx describing valid characters sets,but it works for relatively simple sets, that we are using.         /// <summary>               /// Replaces  not expected characters.               /// </summary>               /// <param name="text"> The text.</param>               /// <param name="allowedPattern"> The allowed pattern in Regex format, expect them wrapped in brackets</param>               /// <param name="replacement"> The replacement.</param>               /// <returns></returns>               /// //        http://stackoverflow.com/questions/4460290/replace-chars-if-not-match.               //http://stackoverflow.com/questions/6154426/replace-remove-characters-that-do-not-match-the-regular-expression-net               //[^ ] at the start of a character class negates it - it matches characters not in the class.               //Replace/Remove characters that do not match the Regular Expression               static public string ReplaceNotExpectedCharacters( this string text, string allowedPattern,string replacement )              {                     allowedPattern = allowedPattern.StripBrackets( "[", "]" );                      //[^ ] at the start of a character class negates it - it matches characters not in the class.                      var result = Regex .Replace(text, @"[^" + allowedPattern + "]", replacement);                      return result;              }static public string RemoveNonAlphanumericCharacters( this string text)              {                      var result = text.ReplaceNotExpectedCharacters(NonAlphaNumericCharacters, "" );                      return result;              }        public const string NonAlphaNumericCharacters = "[a-zA-Z0-9]";There are a couple of functions from my StringHelper class  http://geekswithblogs.net/mnf/archive/2006/07/13/84942.aspx , that are used here.    //                           /// <summary>               /// 'StripBrackets checks that starts from sStart and ends with sEnd (case sensitive).               ///           'If yes, than removes sStart and sEnd.               ///           'Otherwise returns full string unchanges               ///           'See also MidBetween               /// </summary>               /// <param name="str"></param>               /// <param name="sStart"></param>               /// <param name="sEnd"></param>               /// <returns></returns>               public static string StripBrackets( this string str, string sStart, string sEnd)              {                      if (CheckBrackets(str, sStart, sEnd))                     {                           str = str.Substring(sStart.Length, (str.Length - sStart.Length) - sEnd.Length);                     }                      return str;              }               public static bool CheckBrackets( string str, string sStart, string sEnd)              {                      bool flag1 = (str != null ) && (str.StartsWith(sStart) && str.EndsWith(sEnd));                      return flag1;              }               public static string WrapBrackets( string str, string sStartBracket, string sEndBracket)              {                      StringBuilder builder1 = new StringBuilder(sStartBracket);                     builder1.Append(str);                     builder1.Append(sEndBracket);                      return builder1.ToString();              }v

    Read the article

  • How to use DoDirect/Paypal Pro in asp.net?

    - by ptahiliani
    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Net;using System.IO;using System.Collections;public partial class Default2 : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {    }    protected void Button1_Click(object sender, EventArgs e)    {        //API Credentials (3-token)        string strUsername = "<<enter your sandbox username here>>";        string strPassword = "<<enter your sandbox password here>>";        string strSignature = "<<enter your signature here>>";        string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature;        string strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";        string strAPIVersion = "2.3";        string strNVP = strCredentials + "&METHOD=DoDirectPayment" +        "&CREDITCARDTYPE=" + "Visa" +        "&ACCT=" + "4710496235600346" +        "&EXPDATE=" + "10" + "2017" +        "&CVV2=" + "123" +        "&AMT=" + "12.34" +        "&FIRSTNAME=" + "Demo" +        "&LASTNAME=" + "User" +        "&IPADDRESS=192.168.2.236" +        "&STREET=" + "Lorem-1" +        "&CITY=" + "Lipsum-1" +        "&STATE=" + "Lorem" +        "&COUNTRY=" + "INDIA" +        "&ZIP=" + "302004" +        "&COUNTRYCODE=IN" +        "&PAYMENTACTION=Sale" +        "&VERSION=" + strAPIVersion;        try        {            //Create web request and web response objects, make sure you using the correct server (sandbox/live)            HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVPSandboxServer);            wrWebRequest.Method = "POST";            StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());            requestWriter.Write(strNVP);            requestWriter.Close();            // Get the response.            HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();            StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());            //and read the response            string responseData = responseReader.ReadToEnd();            responseReader.Close();            string result = Server.UrlDecode(responseData);            string[] arrResult = result.Split('&');            Hashtable htResponse = new Hashtable();            string[] responseItemArray;            foreach (string responseItem in arrResult)            {                responseItemArray = responseItem.Split('=');                htResponse.Add(responseItemArray[0], responseItemArray[1]);            }            string strAck = htResponse["ACK"].ToString();            if (strAck == "Success" || strAck == "SuccessWithWarning")            {                string strAmt = htResponse["AMT"].ToString();                string strCcy = htResponse["CURRENCYCODE"].ToString();                string strTransactionID = htResponse["TRANSACTIONID"].ToString();                //ordersDataSource.InsertParameters["TransactionID"].DefaultValue = strTransactionID;                string strSuccess = "Thank you, your order for: $" + strAmt + " " + strCcy + " has been processed.";                //successLabel.Text = strSuccess;                Response.Write(strSuccess.ToString());            }            else            {                string strErr = "Error: " + htResponse["L_LONGMESSAGE0"].ToString();                string strErrcode = "Error code: " + htResponse["L_ERRORCODE0"].ToString();                //errLabel.Text = strErr;                //errcodeLabel.Text = strErrcode;                Response.Write(strErr.ToString() + "<br/>" + strErrcode.ToString());                return;            }        }        catch (Exception ex)        {            // do something to catch the error, like write to a log file.            Response.Write("error processing");        }    }}

    Read the article

  • How to remove illegal characters from path and filenames?

    - by Gary Willoughby
    I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am i missing? using System; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?"; illegal = illegal.Trim(Path.GetInvalidFileNameChars()); illegal = illegal.Trim(Path.GetInvalidPathChars()); Console.WriteLine(illegal); Console.ReadLine(); } } }

    Read the article

< Previous Page | 108 109 110 111 112 113 114 115 116 117 118 119  | Next Page >