Search Results

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

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

  • convert integer to a string in a given numeric base in python

    - by Mark Borgerding
    Python allows easy creation of an integer from a string of a given base via int(str,base). I want to perform the inverse: creation of a string from an integer. i.e. I want some function int2base(num,base) such that: int( int2base( X , BASE ) , BASE ) == X the function name/argument order is unimportant For any number X and base BASE that int() will accept. This is an easy function to write -- in fact easier than describing it in this question -- however, I feel like I must be missing something. I know about the functions bin,oct,hex; but I cannot use them for a few reasons: Those functions are not available on older versions of python with which I need compatibility (2.2) I want a general solution that can be called the same way for different bases I want to allow bases other than 2,8,16 Related Python elegant inverse function of int(string,base) Interger to base-x system using recursion in python Base 62 conversion in Python How to convert an integer to the shortest url-safe string in Python?

    Read the article

  • C# .NET : Is using the .NET Image Conversion enough?

    - by contactmatt
    I've seen a lot of people try to code their own image conversion techniques. It often seems to be very complicated, and ends up using GDI+ funciton calls, and manipulating bits of the image. This has got me wondering if I am missing something in the simplicity of .NET's image conversion call when saving an image. Here's the code I have Bitmap tempBmp = new Bitmap("c:\temp\img.jpg"); Bitmap bmp = new Bitmap(tempBmp, 800, 600); bmp.Save(c:\temp\img.bmp, //extension depends on format ImageFormat.Bmp) //These are all the ImageFormats I allow conversion to within the program. Ignore the syntax for a second ;) ImageFormat.Gif) //or ImageFormat.Jpeg) //or ImageFormat.Png) //or ImageFormat.Tiff) //or ImageFormat.Wmf) //or ImageFormat.Bmp)//or ); This is all I'm doing in my image conversion. Just setting the location of where the image should be saved, and passing it an ImageFormat type. I've tested it the best I can, but I'm wondering if I am missing anything in this simple format conversion, or if this is suffice?

    Read the article

  • Scala 2.8.1 implicitly convert to java.util.List<java.util.Map<String, Object>>

    - by Ralph
    I have a Scala data structure created with the following: List(Map[String, Anyref]("a" -> someFoo, "b" -> someBar)) I would like to implicitly convert it (using scala.collection.JavaConversions or scala.collection.JavaConverters) to a java.util.List<java.util.Map<String, Object>> to be passed the a Java method that expects the latter. Is this possible? I have already created the following method that does it, but was wondering if it can be done automatically by the compiler? import scala.collection.JavaConversions._ def convertToJava(listOfMaps: List[Map[String, AnyRef]]): java.util.List[java.util.Map[String, Object]] = { asJavaList(listOfMaps.map(asJavaMap(_))) }

    Read the article

  • Python elegant inverse function of int(string,base)

    - by random guy
    python allows conversions from string to integer using any base in the range [2,36] using: int(string,base) im looking for an elegant inverse function that takes an integer and a base and returns a string for example >>> str_base(224,15) 'ee' i have the following solution: def digit_to_char(digit): if digit < 10: return chr(ord('0') + digit) else: return chr(ord('a') + digit - 10) def str_base(number,base): if number < 0: return '-' + str_base(-number,base) else: (d,m) = divmod(number,base) if d: return str_base(d,base) + digit_to_char(m) else: return digit_to_char(m) note: digit_to_char() works for bases <= 169 arbitrarily using ascii characters after 'z' as digits for bases above 36 is there a python builtin, library function, or a more elegant inverse function of int(string,base) ?

    Read the article

  • AES Key encoded byte[] to String and back to byte[]

    - by Tom Brito
    In the similar question "Conversion of byte[] into a String and then back to a byte[]" is said to not to do the byte[] to String and back conversion, what looks like apply to most cases, mainly when you don't know the encoding used. But, in my case I'm trying to save to a DB the javax.crypto.SecretKey data, and recoverd it after. The interface provide a method getEncoded() which returns the key data encoded as byte[], and with another class I can use this byte[] to recover the key. So, the question is, how do I write the key bytes as String, and later get back the byte[] to regenerate the key?

    Read the article

  • .Net Round-trip Types

    - by Fujiy
    I making a method that generate a unique string key for some parameters. But the same key if call with same values. I just accept primitive types, string, DateTime, Guid, and Nullable(since I append types together, I can distinguish who is int and who is int?), because I can convert all to string without lost values or precision.(for float and double a use ToString("R"), to DateTime ToString("O")). Exists a easy way to know which types I can transform in strings without conflict? And how do this transform(how I said before, float, double and datetime have specific ways) Thanks

    Read the article

  • Using Generics to return a literal string or from Dictionary<string, object>

    - by Mike
    I think I outsmarted myself this time. Feel free to edit the title also I could not think of a good one. I am reading from a file and then in that file will be a string because its like an xml file. But in the file will be a literal value or a "command" to get the value from the workContainer so <Email>[email protected]</Email> or <Email>[? MyEmail ?]</Email> What I wanted to do instead of writing ifs all over the place to put it in a generic function so logic is If Container command grab from container else grab string and convert to desired type Its up to the user to ensure the file is ok and the type is correct so another example is so <Answer>3</Answer> or <Answer>[? NumberOfSales ?]</Answer> This is the procedure I started to work on public class WorkContainer:Dictionary<string, object> { public T GetKeyValue<T>(string Parameter) { if (Parameter.StartsWith("[? ")) { string key = Parameter.Replace("[? ", "").Replace(" ?]", ""); if (this.ContainsKey(key)) { return (T)this[key]; } else { // may throw error for value types return default(T); } } else { // Does not Compile if (typeof(T) is string) { return Parameter } // OR return (T)Parameter } } } The Call would be mail.To = container.GetKeyValue<string>("[email protected]"); or mail.To = container.GetKeyValue<string>("[? MyEmail ?]"); int answer = container.GetKeyValue<int>("3"); or answer = container.GetKeyValue<int>("[? NumberOfSales ?]"); But it does not compile?

    Read the article

  • python3: removing several chars from a string with a long chain of .replace().replace().replace()

    - by MadSc13ntist
    I found this example on stack overflow. I understand it, but seems like a bit much for such a simple method concept... removing several chars from a string. import string exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude) is there a builtin string method in python 3.1 to do something to the tune of: s = "a,b,c,d,e,f,g,h,i" s = s.strip([",", "d", "h"]) instead of: s = s.replace(",", "").replace("d", "").replace("h", "")

    Read the article

  • example of a utf-8 format octet string

    - by erik
    I'm working w/ a function that expects a string formatted as a utf-8 encoded octet string. Can someone give me an example of what a utf-8 encoded octet string would look like? Put another way, if I convert 'foo' to bytes, I get 112, 111, 111. What would these char codes look like as a utf-8 encoded octet string? Would it be "0x70 0x6f 0x6f"? Thanks

    Read the article

  • Help with function in string

    - by draice
    I have a variable, emailBody, which is set to a string stored in a database emailBody = DLookup("emailBody", "listAdditions", "Id = " & itemType) The string icludes an IIf function (which includes a dlookup function). ?emailBody The new commodity is" & Iif(dlookup("IsVague", "CommodityType", "Description= " & newItem)="1", "vague.", "not vague.") How do I properly format the string so that the function will be evaluated and the result stored in the string?

    Read the article

  • how do you convert a directoryInfo file to string

    - by steve
    Problem is that i cant convert to string Dim path As String = "..\..\..\Tier1 downloads\CourseVB\" If countNumberOfFolders > 0 Then 'if there is a folder then ' make a reference to a directory Dim di As New IO.DirectoryInfo(path) Dim diar1 As IO.DirectoryInfo() = di.GetDirectories() Dim dra As IO.DirectoryInfo 'list the names of all files in the specified directory For Each dra In diar1 Dim lessonDirectoryName() As Lesson lessonDirectoryName(0).lessonName = dra Next 'the the lesson is an object, and lessonName is the property of type string. How do i convert the directoryInfo to string?

    Read the article

  • How to split a string of words and add to an array - Objective C

    - by user1412469
    Let's say I have this: NSString *str = @"This is a sample string"; How will I split the string in a way that each word will be added into a NSMutableArray? In VB.net you can do this: Dim str As String Dim strArr() As String Dim count As Integer str = "vb.net split test" strArr = str.Split(" ") For count = 0 To strArr.Length - 1 MsgBox(strArr(count)) Next So how to do this in Objective-C? Thanks

    Read the article

  • vb.net one dimensional string array manipulation difficulty

    - by Luay
    Hi, I am having some problems with manipulating a one dimensional string array in vb.net and would like your assistance please. My objective is to get 4 variables (if possible) from a file path. these variables are: myCountry, myCity, myStreet, Filename. All declared as string. The file location is also declared as string. so I have: Dim filePath As String to illustrate my problem and what I am trying to do I have the following examples: 1- C:\my\location\is\UK\Birmingham\Summer Road\this house.txt. In this example myCountry would be= UK. myCity= Birmingham. myStreet=Summer Road. Filename=this house.txt 2- C:\my Location\is\France\Lyon\that house.txt. here myCountry=France. myCity=Lyon. There is no street. Filename=that house.txt 3- C:\my Location is\Germany\the other house.txt Here myCountry=Germany. No city. No street. Filename=the other house.txt What I am trying to say is I have no idea before hand about the lenght of the string or the position of the variables I want. I also don't know if I am going to find/get a city or street name in the path. However I do now that i will get myCountry and it will be one of 5 options: UK, France, Germany, Spain, Italy. To tackle my problem, the first thing I did was Dim pathArr() As String = filePath.Split("\") to get the FileName I did: FileName = pathArr.Last To get myCountry I did: If filePath.Contains("UK") Then myCountry = "UK" ElseIf filePath.Contains("France") Then myCountry = "France" ElseIf filePath.Contains("Germany") Then myCountry = "Germany" ElseIf filePath.Contains("Spain") Then myCountry = "Spain" ElseIf filePath.Contains("Italy") Then myCountry = "Italy" End If in trying to figure out myCity and myStreet (and whether they exist in the string in the first place) I started with: Dim ind As Integer = Array.IndexOf(pathArr, myCountry) to get the index of the myCountry string. I thought I could make my way from there but I am stuck and don't know what to do next. Any help will be appreciated. Thanks

    Read the article

  • find string in DataGridView

    - by LCountee
    I'm using a foreach loop to populate each row in a DataGridView with a string. I need to search the DataGridView to make sure that I don't add a string that is already there. What is the best way to do this? Here is my code so far: foreach (String file in openFileDialog.FileNames) { // todo: make sure file string does not already exist in DataGridView dataGridView1.Rows.Add(); dataGridView1.Rows[i].Cells[1].Value = file; i++; }

    Read the article

  • Assembly GDB Print String

    - by Ken
    So in assembly I declare the following String: Sample db "This is a sample string",0 In GDB I type "p Sample" (without quotes) and it spits out 0x73696854. I want the actual String to print out. So I tried "printf "%s", Sample" (again, without quotes) and it spits out "Cannot access memory at address 0x73696854." Short version: How do I print a string in GDB?

    Read the article

  • Count the number of times a string appears within a string...

    - by onekidney
    I simply have a string that looks something like this: "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false" All I want to do is to count how many times the string "true" appears in that string. I'm feeling like the answer is something like String.CountAllTheTimesThisStringAppearsInThatString() but for some reason I just can't figure it out. Help?

    Read the article

  • Java String object creation

    - by Ajay
    Hi, 1) What is difference in thers two statements: String s1 = "abc"; and String s1 = new String("abc") 2) as i am not using new in first statement, how string object will be created Thanks

    Read the article

  • Make a String text Bold in Java Android

    - by meskh
    I want to make Habit Number: bold , I tried the HTML tag but it didn't work. I did some research but couldn't find any. Hope someone is able to help me. Thanks! String habitnumber = "Habit Number: " + String.valueOf(habitcounter); String Title = habit.getTitle(); String description = habit.getDescription(); //Set text for the row tv.setText(habitnumber+ "\n" + Title + " \n" + description + "\n --------------------");

    Read the article

  • c++ std::ostringstream vs std::string::append

    - by NickSoft
    In all examples that use some kind of buffering I see they use stream instead of string. How is std::ostringstream and << operator different than using string.append. Which one is faster and which one uses less resourses (memory). One difference I know is that you can output different types into output stream (like integer) rather than the limited types that string::append accepts. Here is an example: std::ostringstream os; os << "Content-Type: " << contentType << ";charset=" << charset << "\r\n"; std::string header = os.str(); vs std::string header("Content-Type: "); header.append(contentType); header.append(";charset="); header.append(charset); header.append("\r\n"); Obviously using stream is shorter, but I think append returns reference to the string so it can be written like this: std::string header("Content-Type: "); header.append(contentType) .append(";charset=") .append(charset) .append("\r\n"); And with output stream you can do: std::string content; ... os << "Content-Length: " << content.length() << "\r\n"; But what about memory usage and speed? Especially when used in a big loop. Update: To be more clear the question is: Which one should I use and why? Is there situations when one is preferred or the other? For performance and memory ... well I think benchmark is the only way since every implementation could be different. Update 2: Well I don't get clear idea what should I use from the answers which means that any of them will do the job, plus vector. Cubbi did nice benchmark with the addition of Dietmar Kühl that the biggest difference is construction of those objects. If you are looking for an answer you should check that too. I'll wait a bit more for other answers (look previous update) and if I don't get one I think I'll accept Tolga's answer because his suggestion to use vector is already done before which means vector should be less resource hungry.

    Read the article

  • Conversion of BizTalk Projects to Use the New WCF-SAP Adaptor

    - by Geordie
    We are in the process of upgrading our BizTalk Environment from BizTalk 2006 R2 to BizTalk 2010. The SAP adaptor in BizTalk 2010 is an all new and more powerful WCF-SAP adaptor. When my colleagues tested out the new adaptor they discovered that the format of the data extracted from SAP was not identical to the old adaptor. This is not a big deal if the structure of the messages from SAP is simple. In this case we were receiving the delivery and invoice iDocs. Both these structures are complex especially the delivery document. Over the past few years I have tweaked the delivery mapping to remove bugs from original mapping. The idea of redoing these maps did not appeal and due to the current work load was not even an option. I opted for a rather crude alternative of pulling in the iDoc in the new typed format and then adding a static map at the start of the orchestration to convert the data to the old schema.  Note WCF-SAP data formats (on the binding tab of the configuration dialog box is the ‘RecieiveIdocFormat’ field): Typed:  Returns a XML document with the hierarchy represented in XML and all fields being represented by XML tags. RFC: Returns an XML document with the hierarchy represented in XML but the iDoc lines in flat file format. String: This returns the iDoc in a format that is closest to the original flat file format but is still wrapped with some top level XML tags. The files also contained some strange characters at the end of each line. I started with the invoice document and it was quite straight forward to add the mapping but this is where my problems started. The orchestrations for these documents are dynamic and so require the identity of the partner to be able to correctly configure the orchestration. The partner identity is in the EDI_DC40 segment of the iDoc. In the old project the RECPRN node of the segment was promoted. The code to set a variable to the partner ID was now failing. After lot of head scratching I discovered the problem was due to the addition of Namespaces to the fields in the EDI_DC40 segment. To overcome this I needed to use an xPath query with a Namespace Manager. This had to be done in custom code. I now tried to repeat the process with the delivery document. Unfortunately when we tried to get sample typed data from SAP an exception was thrown. The adapter "WCF-SAP" raised an error message. Details "Microsoft.ServiceModel.Channels.Common.XmlReaderGenerationException: The segment or group definition E2EDKA1001 was not found in the IDoc metadata. The UniqueId of the IDoc type is: IDOCTYP/3/DESADV01/ZASNEXT1/640. For Receive operations, the SAP adapter does not support unreleased segments.   Our guess is that when the WCF-SAP adaptor tries to down load the data it retrieves a data schema from SAP. For some reason the schema does not match the data. This may be due to the version of SAP we are running or due to a customization. Either way resolving this problem did not look easy. When doing some research on this problem I found an article showing me how to get the data from SAP using the WCF-SAP adaptor without any XML tags. http://blogs.msdn.com/b/adapters/archive/2007/10/05/receiving-idocs-getting-the-raw-idoc-data.aspx Reproduction of Mustansir blog: Since the WCF based SAP Adapter is ... well, WCF based, all data flowing in and out of the adapter is encapsulated within a SOAP message. Which means there are those pesky xml tags all over the place. If you want to receive an Idoc from SAP, you can receive it in "Typed" format (in which case each column in each segment of the idoc appears within its own xml tag), or you can receive it in "String" format (in which case there are just 2 xml tags at the top, the raw xml data in string/flat file format, and the 2 closing xml tags). In "String" format, an incoming idoc (for ORDERS05, containing 5 data records) would look like: <ReceiveIdoc ><idocData>EDI_DC40 8000000000001064985620 E2EDK01005 800000000000106498500000100000001 E2EDK14 8000000000001064985000002000000020111000 E2EDK14 8000000000001064985000003000000020081000 E2EDK14 80000000000010649850000040000000200710 E2EDK14 80000000000010649850000050000000200600</idocData></ReceiveIdoc> (I have trimmed part of the control record so that it fits cleanly here on one line). Now, you're only interested in the IDOC data, and don't care much for the XML tags. It isn't that difficult to write your own pipeline component, or even some logic in the orchestration to remove the tags, right? Well, you don't need to write any extra code at all - the WCF Adapter can help you here! During the configuration of your one-way Receive Location using WCF-Custom, navigate to the Messages tab. Under the section "Inbound BizTalk Messge Body", select the "Path" radio button, and: (a) Enter the body path expression as: /*[local-name()='ReceiveIdoc']/*[local-name()='idocData'] (b) Choose "String" for the Node Encoding. What we've done is, used an XPATH to pull out the value of the "idocData" node from the XML. Your Receive Location will now emit text containing only the idoc data. You can at this point, for example, put the Flat File Pipeline component to convert the flat text into a different xml format based on some other schema you already have, and receive your version of the xml formatted message in your orchestration.   This was potentially a much easier solution than adding the static maps to the orchestrations and overcame the issue with ‘Typed’ delivery documents. Not quite so fast… Note: When I followed Mustansir’s blog the characters at the end of each line disappeared. After configuring the adaptor and passing the iDoc data into the original flat file receive pipelines I was receiving exceptions. There was a failure executing the receive pipeline: "PAPINETPipelines.DeliveryFlatFileReceive, CustomerIntegration2.PAPINET.Pipelines, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4ca3635fbf092bbb" Source: "Pipeline " Receive Port: "recSAP_Delivery" URI: "D:\CustomerIntegration2\SAP\Delivery\*.xml" Reason: An error occurred when parsing the incoming document: "Unexpected data found while looking for: 'Z2EDPZ7' The current definition being parsed is E2EDP07GRP. The stream offset where the error occured is 8859. The line number where the error occured is 23. The column where the error occured is 0.". Although the new flat file looked the same as the old one there was a differences. In the original file all lines in the document were exactly 1064 character long. In the new file all lines were truncated to the last alphanumeric character. The final piece of the puzzle was to add a custom pipeline component to pad all the lines to 1064 characters. This component was added to the decode node of the custom delivery and invoice flat file disassembler pipelines. Execute method of the custom pipeline component: public IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg) { //Convert Stream to a string Stream s = null; IBaseMessagePart bodyPart = inmsg.BodyPart;   // NOTE inmsg.BodyPart.Data is implemented only as a setter in the http adapter API and a //getter and setter for the file adapter. Use GetOriginalDataStream to get data instead. if (bodyPart != null) s = bodyPart.GetOriginalDataStream();   string newMsg = string.Empty; string strLine; try { StreamReader sr = new StreamReader(s); strLine = sr.ReadLine(); while (strLine != null) { //Execute padding code if (strLine != null) strLine = strLine.PadRight(1064, ' ') + "\r\n"; newMsg += strLine; strLine = sr.ReadLine(); } sr.Close(); } catch (IOException ex) { throw new Exception("Error occured trying to pad the message to 1064 charactors"); }   //Convert back to stream and set to Data property inmsg.BodyPart.Data = new MemoryStream(Encoding.UTF8.GetBytes(newMsg)); ; //reset the position of the stream to zero inmsg.BodyPart.Data.Position = 0; return inmsg; }

    Read the article

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