Search Results

Search found 36172 results on 1447 pages for 'unicode string'.

Page 63/1447 | < Previous Page | 59 60 61 62 63 64 65 66 67 68 69 70  | Next Page >

  • How to read and write a STL C++ string?

    - by cambr
    #include<string> ... string in; //How do I store a string from stdin to in? // //gets(in) - 16 cannot convert `std::string' to `char*' for argument `1' to //char* gets (char*)' // //scanf("%s",in) also gives some weird error Similarly, how do I write out in to stdout or to a file??

    Read the article

  • How can I determine if a composite format string is invalid?

    - by Tinister
    Per the documentation, String.Format will throw a FormatException if either (A) the format string is invalid or (B) the format string contains an index that cannot be found in the args array. I want to be able to determine which (if either) of those conditions fail on any arbitrary string and array of arguments. Is there anything that can do that for me? Thanks!

    Read the article

  • ASP.NET MVC2 Implementing Custom RoleManager problem

    - by ile
    To create a custom membership provider I followed these instructions: http://stackoverflow.com/questions/2771094/asp-net-mvc2-custom-membership and these: http://mattwrock.com/post/2009/10/14/Implementing-custom-Membership-Provider-and-Role-Provider-for-Authinticating-ASPNET-MVC-Applications.aspx So far, I've managed to implement custom membership provider and that part works fine. RoleManager still needs some modifications... Project structure: SAMembershipProvider.cs: public class SAMembershipProvider : MembershipProvider { #region - Properties - private int NewPasswordLength { get; set; } private string ConnectionString { get; set; } public bool enablePasswordReset { get; set; } public bool enablePasswordRetrieval { get; set; } public bool requiresQuestionAndAnswer { get; set; } public bool requiresUniqueEmail { get; set; } public int maxInvalidPasswordAttempts { get; set; } public int passwordAttemptWindow { get; set; } public MembershipPasswordFormat passwordFormat { get; set; } public int minRequiredNonAlphanumericCharacters { get; set; } public int minRequiredPasswordLength { get; set; } public string passwordStrengthRegularExpression { get; set; } public override string ApplicationName { get; set; } public override bool EnablePasswordRetrieval { get { return enablePasswordRetrieval; } } public override bool EnablePasswordReset { get { return enablePasswordReset; } } public override bool RequiresQuestionAndAnswer { get { return requiresQuestionAndAnswer; } } public override int MaxInvalidPasswordAttempts { get { return maxInvalidPasswordAttempts; } } public override int PasswordAttemptWindow { get { return passwordAttemptWindow; } } public override bool RequiresUniqueEmail { get { return requiresUniqueEmail; } } public override MembershipPasswordFormat PasswordFormat { get { return passwordFormat; } } public override int MinRequiredPasswordLength { get { return minRequiredPasswordLength; } } public override int MinRequiredNonAlphanumericCharacters { get { return minRequiredNonAlphanumericCharacters; } } public override string PasswordStrengthRegularExpression { get { return passwordStrengthRegularExpression; } } #endregion #region - Methods - public override void Initialize(string name, NameValueCollection config) { throw new NotImplementedException(); } public override bool ChangePassword(string username, string oldPassword, string newPassword) { throw new NotImplementedException(); } public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new NotImplementedException(); } public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { throw new NotImplementedException(); } public override bool DeleteUser(string username, bool deleteAllRelatedData) { throw new NotImplementedException(); } public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { throw new NotImplementedException(); } public override int GetNumberOfUsersOnline() { throw new NotImplementedException(); } public override string GetPassword(string username, string answer) { throw new NotImplementedException(); } public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { throw new NotImplementedException(); } public override MembershipUser GetUser(string username, bool userIsOnline) { throw new NotImplementedException(); } public override string GetUserNameByEmail(string email) { throw new NotImplementedException(); } protected override void OnValidatingPassword(ValidatePasswordEventArgs e) { base.OnValidatingPassword(e); } public override string ResetPassword(string username, string answer) { throw new NotImplementedException(); } public override bool UnlockUser(string userName) { throw new NotImplementedException(); } public override void UpdateUser(MembershipUser user) { throw new NotImplementedException(); } public override bool ValidateUser(string username, string password) { AccountRepository accountRepository = new AccountRepository(); var user = accountRepository.GetUser(username); if (string.IsNullOrEmpty(password.Trim())) return false; if (user == null) return false; //string hash = EncryptPassword(password); var email = user.Email; var pass = user.Password; if (user == null) return false; if (pass == password) { //User = user; return true; } return false; } #endregion protected string EncryptPassword(string password) { //we use codepage 1252 because that is what sql server uses byte[] pwdBytes = Encoding.GetEncoding(1252).GetBytes(password); byte[] hashBytes = System.Security.Cryptography.MD5.Create().ComputeHash(pwdBytes); return Encoding.GetEncoding(1252).GetString(hashBytes); } } SARoleProvider.cs public class SARoleProvider : RoleProvider { AccountRepository accountRepository = new AccountRepository(); public override bool IsUserInRole(string username, string roleName) { return true; } public override string ApplicationName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override void CreateRole(string roleName) { throw new NotImplementedException(); } public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotImplementedException(); } public override bool RoleExists(string roleName) { throw new NotImplementedException(); } public override string[] GetRolesForUser(string username) { int rolesCount = 0; IQueryable<RoleViewModel> rolesNames; try { // get roles for this user from DB... rolesNames = accountRepository.GetRolesForUser(username); rolesCount = rolesNames.Count(); } catch (Exception ex) { throw ex; } string[] roles = new string[rolesCount]; int counter = 0; foreach (var item in rolesNames) { roles[counter] = item.RoleName.ToString(); counter++; } return roles; } public override string[] GetUsersInRole(string roleName) { throw new NotImplementedException(); } public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotImplementedException(); } public override string[] GetAllRoles() { throw new NotImplementedException(); } } AccountRepository.cs public class RoleViewModel { public string RoleName { get; set; } } public class AccountRepository { private DB db = new DB(); public User GetUser(string email) { return db.Users.SingleOrDefault(d => d.Email == email); } public IQueryable<RoleViewModel> GetRolesForUser(string email) { var result = ( from role in db.Roles join user in db.Users on role.RoleID equals user.RoleID where user.Email == email select new RoleViewModel { RoleName = role.Name }); return result; } } webconfig <membership defaultProvider="SAMembershipProvider" userIsOnlineTimeWindow="15"> <providers> <clear/> <add name="SAMembershipProvider" type="SA_Contacts.Membership.SAMembershipProvider, SA_Contacts" connectionStringName ="ShinyAntConnectionString" /> </providers> </membership> <roleManager defaultProvider="SARoleProvider" enabled="true" cacheRolesInCookie="true"> <providers> <clear/> <add name="SARoleProvider" type="SA_Contacts.Membership.SARoleProvider" connectionStringName ="ShinyAntConnectionString" /> </providers> </roleManager> AccountController.cs: public class AccountController : Controller { SAMembershipProvider provider = new SAMembershipProvider(); AccountRepository accountRepository = new AccountRepository(); public AccountController() { } public ActionResult LogOn() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult LogOn(string userName, string password, string returnUrl) { if (!ValidateLogOn(userName, password)) { return View(); } var user = accountRepository.GetUser(userName); var userFullName = user.FirstName + " " + user.LastName; FormsAuthentication.SetAuthCookie(userFullName, false); if (!String.IsNullOrEmpty(returnUrl) && returnUrl != "/") { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } private bool ValidateLogOn(string userName, string password) { if (String.IsNullOrEmpty(userName)) { ModelState.AddModelError("username", "You must specify a username."); } if (String.IsNullOrEmpty(password)) { ModelState.AddModelError("password", "You must specify a password."); } if (!provider.ValidateUser(userName, password)) { ModelState.AddModelError("_FORM", "The username or password provided is incorrect."); } return ModelState.IsValid; } } In some testing controller I have following: [Authorize] public class ContactsController : Controller { SAMembershipProvider saMembershipProvider = new SAMembershipProvider(); SARoleProvider saRoleProvider = new SARoleProvider(); // // GET: /Contact/ public ActionResult Index() { string[] roleNames = Roles.GetRolesForUser("[email protected]"); // Outputs admin ViewData["r1"] = roleNames[0].ToString(); // Outputs True // I'm not even sure if this method is the same as the one below ViewData["r2"] = Roles.IsUserInRole("[email protected]", roleNames[0].ToString()); // Outputs True ViewData["r3"] = saRoleProvider.IsUserInRole("[email protected]", "admin"); return View(); } If I use attribute [Authorize] then everything works ok, but if I use [Authorize(Roles="admin")] then user is always rejected, like he is not in role. Any idea of what could be wrong here? Thanks in advance, Ile

    Read the article

  • Compatibility of Enum Vs. string constants

    - by Yosi
    I was recently told that using Enum: public enum TaskEndState { Error, Completed, Running } may have compatibility/serialization issues, and thus sometimes it's better to use const string: public const string TASK_END_STATE = "END_STATE"; public const string TASK_END_STATE_ERROR = "TASK_END_STATE_ERROR"; public const string TASK_END_STATE_COMPLETE = "TASK_END_STATE_COMPLETE"; public const string TASK_END_STATE_RUNNING = "TASK_END_STATE_RUNNING"; Can you find practical use case where it may happen, is there any guidelines where Enum's should be avoided? Edit: My production environment has multiple WFC services (different versions of the same product). A later version may/or may not include some new properties as Task end state (this is just an example). If we try to deserialize a new Enum value in an older version of a specific service, it may not work.

    Read the article

  • Removing the last digits in string [migrated]

    - by Ruriko
    I have a string that looks like this: [APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834 I want to remove the digits at the end of the string, basically the 16 digits at the end of the string. In the end it should look like this: [APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC) This is my code that I have written so far var str="[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834"; var n=str.substr(1,74); document.write(n); The problem is the string will be different so each will have different amount of characters. So how I remove the digits at the end of the string in javascript?

    Read the article

  • Sorting a string array in C++ no matter of A or a and with å, ä ö?

    - by Chris_45
    How do you sort an array of strings in C++ that will make this happen in this order: mr Anka Mr broWn mr Ceaser mR donK mr ålish Mr Ätt mr önD //following not the way to get that order regardeless upper or lowercase and å, ä, ö //in forloop... string handle; point1 = array1[j].find_first_of(' '); string forename1(array1[j].substr(0, (point1))); string aftername1(array1[j].substr(point1 + 1)); point2 = array1[j+1].find_first_of(' '); string forename2(array1[j+1].substr(0, (point2))); string aftername2(array1[j+1].substr(point2 + 1)); if(aftername1 > aftername2){ handle = array1[j]; array1[j] = array1[j+1]; array1[j+1] = handle;//swapping } if(aftername1 == aftername2){ if(forname1 > forname2){ handle = array1[j]; array1[j] = array1[j+1]; array1[j+1] = handle; } }

    Read the article

  • how to split string with some seperator but without removing that seperator in Java?

    - by sag
    Hi, I m facing problem in splitting string. Actually i want to split a string with some seperator but without loosing that seperator. when we use somestring.split(String seperator) method in java it splits the string but removes the seperator part from string.It should not happen. I want result like below: Example::string1="Ram-sita-laxman"; seperator="-"; string1.split(seperator); output : [Ram, sita, laxman] but i want the result like :[Ram, -sita, -laxman] is there a way to get output like this?

    Read the article

  • How do I convert a number (as a String) to an array of bytes in Java?

    - by user1795595
    I'm creating a method specific method for a java project i'm working on. The UML given specifies the return type to be of static byte[] that accepts the arguments (String, byte) So far, looks like this: public static byte[] convertNumToDigitArray(String number, byte numDigits) { } This method is supposed to convert a number (as a String) to an array of bytes. The ordering must go from most to least significant digits. For example, if the number String is “732” then index 0 of the array should contain 7. The last argument (numDigits) should match the length of the string passed in. How do I do this?

    Read the article

  • PHP get values from SimpleXMLElement array

    - by seanp2k
    I have this: [1]=> object(SimpleXMLElement)#6 (1) { ["@attributes"]=> array(14) { ["name"]=> string(5) "MySQL" ["acknowledged"]=> string(1) "1" ["comments"]=> string(1) "1" ["current_check_attempt"]=> string(1) "1" ["downtime"]=> string(1) "0" ["last_check"]=> string(19) "2010-05-01 17:57:00" ["markdown_filter"]=> string(1) "0" ["max_check_attempts"]=> string(1) "3" ["output"]=> string(42) "CRITICAL - Socket timeout after 10 seconds" ["perfdata_available"]=> string(1) "1" ["service_object_id"]=> string(3) "580" ["state"]=> string(8) "critical" ["state_duration"]=> string(6) "759439" ["unhandled"]=> string(1) "0" } } (I used var_dump($child) to generate that) How do I get the 'name' attribute out of there as a string? Here is my code: $xml = simplexml_load_string($results); foreach($xml->data->list as $child) { var_dump($child); echo $child->getName() . ": " . $child->name . "<br />"; }

    Read the article

  • help me with xor encryption in c#

    - by x86shadow
    I wrote this code in c# to encrypt a text with a key : using System; using System.Linq; using System.Collections.Generic; using System.Text; namespace ENCRYPT { class XORENC { private static int Bin2Dec(string num) { int _num = 0; for (int i = 0; i < num.Length; i++) { _num += (int)Math.Pow(2, num.Length - i - 1) * int.Parse(num[i].ToString()); } return _num; } private static string Dec2Bin(int num) { if (num < 2) return num.ToString(); return Dec2Bin(num / 2) + (num % 2).ToString(); } public static string StrXor(string str, string key) { string _str = ""; string _key = ""; string _dec = ""; string _temp = ""; for (int i = 0; i < str.Length; i++) { _temp = Dec2Bin(str[i]); for (int j = 0; j < 8 - _temp.Length + 1; j++) { _temp = '0' + _temp; } _str += _temp; } for (int i = 0; i < key.Length; i++) { _temp = Dec2Bin(key[i]); for (int j = 0; j < 8 - _temp.Length + 1; j++) { _temp = '0' + _temp; } _key += _temp; } while (_key.Length < _str.Length) { _key += _key; } if (_key.Length > _str.Length) _key = _key.Substring(0, _str.Length); for (int i = 0; i < _str.Length; i++) { if (_str[i] == _key[i]) { _dec += '0'; } else { _dec += '1'; } } _str = ""; for (int i = 0; i < _dec.Length; i = i + 8) { char _chr = (char)0; _chr = (char)Bin2Dec(_dec.Substring(i, 8)); _str += _chr; } return _str; } } } the problem is that I always get error when I want to decrypt an encryted text with this code. see the example below for more info : string enc_text = ENCRYPT.XORENC("abc","a"); //enc_text = " ??" string dec_text = ENCRYPT.XORENC(enc_text,"a"); //ERROR any one can help ?

    Read the article

  • Retrieve the full ASP.NET Form Buffer as a String

    - by Rick Strahl
    Did it again today: For logging purposes I needed to capture the full Request.Form data as a string and while it’s pretty easy to retrieve the buffer it always takes me a few minutes to remember how to do it. So I finally wrote a small helper function to accomplish this since this comes up rather frequently especially in debugging scenarios or in the immediate window. Here’s the quick function to get the form buffer as string: /// <summary> /// Returns the content of the POST buffer as string /// </summary> /// <returns></returns> public static string FormBufferToString() { HttpRequest Request = HttpContext.Current.Request; if (Request.TotalBytes > 0) return Encoding.Default.GetString(Request.BinaryRead(Request.TotalBytes)); return string.Empty; } Clearly a simple task, but handy to have in your library for reuse. You probably don’t want to call this if you have a massive inbound form buffer, or if the data you’re retrieving is binary. It’s probably a good idea to check the inbound content type before calling this function with something like this: var formBuffer = string.Empty; if (Request.ContentType.StartsWith("text/") || Request.ContentType == "application/x-www-form-urlencoded") ) { formBuffer = FormBufferToString(); } to ensure you’re working only on content types you can actually view as text. Now if I can only remember the name of this function in my library – it’s part of the static WebUtils class in the West Wind Web Toolkit if you want to check out a number of other useful Web helper functions.© Rick Strahl, West Wind Technologies, 2005-2011Posted in ASP.NET  

    Read the article

  • String Conversion to Char for Java Game

    - by Jen
    Is there someone who could help me achieve the following points on this problems? I can't seem to get it. I tried using toCharArray and Scanner to achieve this, but it doesn't work, nor do I know how to make this things possible for my word game. :( · Get a popular name of person, place, verse, saying or event from the user. This may have a single or multiple words in it. · Create a copy of this string to an array where each letter is replaced with a hyphen (-) and each space is replaced with an underscore (_). Symbols and numbers will remain shown. · The program then asks a letter from the user. If the letter is in the inputted string, then it should be shown on the array at the same position it is shown in the string. Meaning, the letter replaces the hyphen (-) at the correct position of the array. · The program again prompts for a letter from the user and replaces the hyphen (-) of the array if it exists on the inputted string. This will be repeatedly done until such time each hyphen (-) is replaced with the correct letter. · If the user inputs an invalid letter, that is, a letter that does not exist on the inputted string, then the program should inform the user. If this happens 3 times while there is still at least one hyphen on the array, then the program should inform the user that he lost the game and showing him the whole correct string. · If the user completes the game, meaning, all hyphens have been replaced with the correct letters; then the program should congratulate the user for a job well done.

    Read the article

  • Using a random string to authenticate HMAC?

    - by mrwooster
    I am designing a simple webservice and want to use HMAC for authentication to the service. For the purpose of this question we have: a web service at example.com a secret key shared between a user and the server [K] a consumer ID which is known to the user and the server (but is not necessarily secret) [D] a message which we wish to send to the server [M] The standard HMAC implementation would involve using the secret key [K] and the message [M] to create the hash [H], but I am running into issues with this. The message [M] can be quite long and tends to be read from a file. I have found its very difficult to produce a correct hash consistently across multiple operating systems and programming languages because of hidden characters which make it into various file formats. This is of course bad implementation on the client side (100%), but I would like this webservice to be easily accessible and not have trouble with different file formats. I was thinking of an alternative, which would allow the use a short (5-10 char) random string [R] rather than the message for autentication, e.g. H = HMAC(K,R) The user then passes the random string to the server and the server checks the HMAC server side (using random string + shared secret). As far as I can see, this produces the following issues: There is no message integrity - this is ok message integrity is not important for this service A user could re-use the hash with a different message - I can see 2 ways around this Combine the random string with a timestamp so the hash is only valid for a set period of time Only allow each random string to be used once Since the client is in control of the random string, it is easier to look for collisions I should point out that the principle reason for authentication is to implement rate limiting on the API service. There is zero need for message integrity, and its not a big deal if someone can forge a single request (but it is if they can forge a very large number very quickly). I know that the correct answer is to make sure the message [M] is the same on all platforms/languages before hashing it. But, taking that out of the equation, is the above proposal an acceptable 2nd best?

    Read the article

  • Parsing with BeautifulSoup, error message TypeError: coercing to Unicode: need string or buffer, NoneType found

    - by Samsun Knight
    so I'm trying to scrape an Amazon page for data, and I'm getting an error when I try to parse for where the seller is located. Here's my code: #getting the html request = urllib2.Request('http://www.amazon.com/gp/offer-listing/0393934241/') opener = urllib2.build_opener() #hiding that I'm a webscraper request.add_header('User-Agent', 'Mozilla/5 (Solaris 10) Gecko') #opening it up, putting into soup form html = opener.open(request).read() soup = BeautifulSoup(html, "html5lib") #parsing for the seller info sellers = soup.findAll('div', {'class' : 'a-row a-spacing-medium olpOffer'}) for eachseller in sellers: #parsing for price price = eachseller.find('span', {'class' : 'a-size-large a-color-price olpOfferPrice a-text-bold'}) #parsing for shipping costs shippingprice = eachseller.find('span' , {'class' : 'olpShippingPrice'}) #parsing for condition condition = eachseller.find('span', {'class' : 'a-size-medium'}) #parsing for seller name sellername = eachseller.find('b') #parsing for seller location location = eachseller.find('div', {'class' : 'olpAvailability'}) #printing it all out print "price, " + price.string + ", shipping price, " + shippingprice.string + ", condition," + condition.string + ", seller name, " + sellername.string + ", location, " + location.string I get the error message, pertaining to the 'print' command at the end, "TypeError: coercing to Unicode: need string or buffer, NoneType found" I know that it's coming from this line - location = eachseller.find('div', {'class' : 'olpAvailability'}) - because the code works fine without that line, and I know that I'm getting NoneType because the line isn't finding anything. Here's the html from the section I'm looking to parse: <*div class="olpAvailability"> In Stock. Ships from WI, United States. <*br/><*a href="/gp/aag/details/ref=olp_merch_ship_9/175-0430757-3801038?ie=UTF8&amp;asin=0393934241&amp;seller=A1W2IX7T37FAMZ&amp;sshmPath=shipping-rates#aag_shipping">Domestic shipping rates</a> and <*a href="/gp/aag/details/ref=olp_merch_return_9/175-0430757-3801038?ie=UTF8&amp;asin=0393934241&amp;seller=A1W2IX7T37FAMZ&amp;sshmPath=returns#aag_returns">return policy</a>. <*/div> (but without the stars - just making sure the HTML doesn't compile out of code form) I don't see what's the problem with the 'location' line of code, or why it's not pulling the data I want. Help?

    Read the article

  • Regex to check if exact string exists

    - by Jayrox
    I am looking for a way to check if an exact string match exists in another string using Regex or any better method suggested. I understand that you tell regex to match a space or any other non-word character at the beginning or end of a string. However, I don't know exactly how to set it up. Search String: t String 1: Hello World, Nice to see you! t String 2: Hello World, Nice to see you! String 3: T Hello World, Nice to see you! I would like to use the search string and compare it to String 1, String 2 and String 3 and only get a positive match from String 1 and String 3 but not from String 2. Requirements: Search String may be at any character position in the Subject. There may or may not be a white-space character before or after it. I do not want it to match if it is part of another string; such as part of a word. For the sake of this question: I think I would do this using this pattern: /\bt\b/gi /\b{$search_string}\b/gi Does this look right? Can it be made better? Any situations where this pattern wouldn't work? Additional info: this will be used in PHP 5

    Read the article

  • (Java) Get value of string loaded into dynamic-type object?

    - by Michael
    I'm very new to Java (~10 days), so my code is probably pretty bad, but here's what I've got: ArgsDataHolder argsData = new ArgsDataHolder(); // a class that holds two // ArrayList's where each element // representing key/value args Class thisArgClass; String thisArgString; Object thisArg; for(int i=2; i< argsString.length; i++) { thisToken = argsString[i]; thisArgClassString = getClassStringFromToken(thisToken).toLowerCase(); System.out.println("thisArgClassString: " + thisArgClassString); thisArgClass = getClassFromClassString(thisArgClassString); // find closing tag; concatenate middle Integer j = new Integer(i+1); thisArgString = getArgValue(argsString, j, "</" + thisArgClassString + ">"); thisArg = thisArgClass.newInstance(); thisArg = thisArgClass.valueOf(thisArgString); argsData.append(thisArg, thisArgClass); } The user basically has to input a set of key/value arguments into the command prompt in this format: <class>value</class>, e.g. <int>62</int>. Using this example, thisArgClass would be equal to Integer.class, thisArgString would be a string that read "62", and thisArg would be an instance of Integer that is equal to 62. I tried thisArg.valueOf(thisArgString), but I guess valueOf(<String>) is only a method of certain subclasses of Object. For whatever reason, I can't seem to be able to cast thisArg to thisArgClass (like so: thisArg = (thisArgClass)thisArgClass.newInstance();, at which point valueOf(<String>) should become accessible. There's got to be a nice, clean way of doing this, but it is beyond my abilities at this point. How can I get the value of the string loaded into a dynamically-typed object (Integer, Long, Float, Double, String, Character, Boolean, etc.)? Or am I just overthinking this, and Java will do the conversion for me? :confused:

    Read the article

  • Should UTF-16 be considered harmful?

    - by Artyom
    I'm going to ask what is probably quite a controversial question: "Should one of the most popular encodings, UTF-16, be considered harmful?" Why do I ask this question? How many programmers are aware of the fact that UTF-16 is actually a variable length encoding? By this I mean that there are code points that, represented as surrogate pairs, take more then one element. I know; lots of applications, frameworks and APIs use UTF-16, such as Java's String, C#'s String, Win32 APIs, Qt GUI libraries, the ICU Unicode library, etc. However, with all of that, there are lots of basic bugs in the processing of characters out of BMP (characters that should be encoded using two UTF-16 elements). For example, try to edit one of these characters: 𝄞 𝕥 𝟶 𠂊 You may miss some, depending on what fonts you have installed. These characters are all outside of the BMP (Basic Multilingual Plane). If you cannot see these characters, you can also try looking at them in the Unicode Character reference. For example, try to create file names in Windows that include these characters; try to delete these characters with a "backspace" to see how they behave in different applications that use UTF-16. I did some tests and the results are quite bad: Opera has problem with editing them Notepad can't deal with them correctly (delete for example) File names editing in Window dialogs in broken All QT3 applications can't deal with them. StackOverflow seems to remove these characters if edited directly in as Unicode characters, and only seems to allow them as HTML Unicode escapes. So... This was very simple test. Do you think that UTF-16 should be considered harmful?

    Read the article

  • PHP PCRE differences on testing and hosting servers

    - by Gary Pearman
    Hi all, I've got the following regular expression that works fine on my testing server, but just returns an empty string on my hosted server. $text = preg_replace('~[^\\pL\d]+~u', $use, $text); Now I'm pretty sure this comes down to the hosting server version of PCRE not being compiled with Unicode property support enabled. The differences in the two versions are as follows: My server: PCRE version 7.8 2008-09-05 Compiled with UTF-8 support Unicode properties support Newline sequence is LF \R matches all Unicode newlines Internal link size = 2 POSIX malloc threshold = 10 Default match limit = 10000000 Default recursion depth limit = 10000000 Match recursion uses stack Hosting server: PCRE version 4.5 01-December-2003 Compiled with UTF-8 support Newline character is LF Internal link size = 2 POSIX malloc threshold = 10 Default match limit = 10000000 Match recursion uses stack Also note that the version on the hosting server (the same version PHP is compiled against) is pretty old. What confuses me though, is that pcretest fails on both servers from the command line with re> ~[^\\pL\d]+~u ** Unknown option 'u' although this regexp works fine when run from PHP on my server. So, I guess my questions are does the regular expression fail on the hosting server because of the lack of Unicode properties? Or is there something else that I'm missing? Thanks all, Gaz.

    Read the article

  • SHGetFolderPath returns path with question marks in it

    - by Colen
    Hi, Our application calls ShGetFolderPath when it runs, to get the My Documents folder. This normally works great. However, for three users - ???????, Jörg and Jörgen (see if you can spot the pattern!) - the call returns some very strange results. For example, for ???????, the call returns: c:\Users\???????\Documents I assume there's some sort of character encoding shenanigan going on here, possibly related to Unicode, but I don't have any experience with that sort of thing. How can I get a useful path to the folder (and other related folders) out of windows, without grovelling through registry keys for the information? In an email to me, ??????? ("Dmitry"), told me his "my documents" folder was actually located here: C:\Users\43D6~1\Documents So I know there's a way to get a "normal" version of the path out of Windows, I just don't know what it is. Background: Our application is not unicode-aware, and uses standard "char *" strings. How can we get the "normal" path? I'm not opposed to calling the "unicode" version of the function, then converting it to "normal" text, if that's possible. Converting the application entirely to use unicode is not an option here (we don't have the time). Thanks.

    Read the article

  • What is the correct JNA mapping for UniChar on Mac OS X?

    - by Trejkaz
    I have a C struct like this: struct HFSUniStr255 { UInt16 length; UniChar unicode[255]; }; I have mapped this in the expected way: public class HFSUniStr255 extends Structure { public UInt16 length; // UInt16 is just an IntegerType with length 2 for convenience. public /*UniChar*/ char[] unicode = new char[255]; //public /*UniChar*/ byte[] unicode = new byte[255*2]; //public /*UniChar*/ UInt16[] unicode = new UInt16[255]; public HFSUniStr255() { } public HFSUniStr255(Pointer pointer) { super(pointer); } } If I use this version, I get every second character of the string into my char[] ("aits D" for "Macintosh HD".) I am assuming that this is something to do with being on a 64-bit platform and JNA mapping the value to a 32-bit wchar_t but then chopping off the high 16 bits on each wchar_t on copying them back. If I use the byte[] version, I get data which decodes correctly using the UTF-16LE charset. If I use the UInt16[] version, I get the right code point for each character but it is then inconvenient to convert them back into a string. Is there some way I can define my type as char[], and yet have it convert correctly?

    Read the article

  • How can I create a Base64-Encoded string from an GDI+ Image in C++?

    - by Schnapple
    I asked a question recently, How can I create an Image in GDI+ from a Base64-Encoded string in C++?, which got a response that led me to the answer. Now I need to do the opposite - I have an Image in GDI+ whose image data I need to turn into a Base64-Encoded string. Due to its nature, it's not straightforward. The crux of the issue is that an Image in GDI+ can save out its data to either a file or an IStream*. I don't want to save to a file, so I need to use the resulting stream. Problem is, this is where my knowledge breaks down. This first part is what I figured out in the other question // Initialize GDI+. GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); // I have this decode function from elsewhere std::string decodedImage = base64_decode(Base64EncodedImage); // Allocate the space for the stream DWORD imageSize = decodedImage.length(); HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, imageSize); LPVOID pImage = ::GlobalLock(hMem); memcpy(pImage, decodedImage.c_str(), imageSize); // Create the stream IStream* pStream = NULL; ::CreateStreamOnHGlobal(hMem, FALSE, &pStream); // Create the image from the stream Image image(pStream); // Cleanup pStream->Release(); GlobalUnlock(hMem); GlobalFree(hMem); (Base64 code) And now I'm going to perform an operation on the resulting image, in this case rotating it, and now I want the Base64-equivalent string when I'm done. // Perform operation (rotate) image.RotateFlip(Gdiplus::Rotate180FlipNone); IStream* oStream = NULL; CLSID tiffClsid; GetEncoderClsid(L"image/tiff", &tiffClsid); // Function defined elsewhere image.Save(oStream, &tiffClsid); // And here's where I'm stumped. (GetEncoderClsid) So what I wind up with at the end is an IStream* object. But here's where both my knowledge and Google break down for me. IStream shouldn't be an object itself, it's an interface for other types of streams. I'd go down the road from getting string-Image in reverse, but I don't know how to determine the size of the stream, which appears to be key to that route. How can I go from an IStream* to a string (which I will then Base64-Encode)? Or is there a much better way to go from a GDI+ Image to a string?

    Read the article

  • SQL: empty string vs NULL value

    - by Jacek Prucia
    I know this subject is a bit controversial and there are a lot of various articles/opinions floating around the internet. Unfortunatelly, most of them assume the person doesn't know what the difference between NULL and empty string is. So they tell stories about surprising results with joins/aggregates and generally do a bit more advanced SQL lessons. By doing this, they absolutely miss the whole point and are therefore useless for me. So hopefully this question and all answers will move subject a bit forward. Let's suppose I have a table with personal information (name, birth, etc) where one of the columns is an email address with varchar type. We assume that for some reason some people might not want to provide an email address. When inserting such data (without email) into the table, there are two available choices: set cell to NULL or set it to empty string (''). Let's assume that I'm aware of all the technical implications of choosing one solution over another and I can create correct SQL queries for either scenario. The problem is even when both values differ on the technical level, they are exactly the same on logical level. After looking at NULL and '' I came to a single conclusion: I don't know email address of the guy. Also no matter how hard i tried, I was not able to sent an e-mail using either NULL or empty string, so apparently most SMTP servers out there agree with my logic. So i tend to use NULL where i don't know the value and consider empty string a bad thing. After some intense discussions with colleagues i came with two questions: am I right in assuming that using empty string for an unknown value is causing a database to "lie" about the facts? To be more precise: using SQL's idea of what is value and what is not, I might come to conclusion: we have e-mail address, just by finding out it is not null. But then later on, when trying to send e-mail I'll come to contradictory conclusion: no, we don't have e-mail address, that @!#$ Database must have been lying! Is there any logical scenario in which an empty string '' could be such a good carrier of important information (besides value and no value), which would be troublesome/inefficient to store by any other way (like additional column). I've seen many posts claiming that sometimes it's good to use empty string along with real values and NULLs, but so far haven't seen a scenario that would be logical (in terms of SQL/DB design). P.S. Some people will be tempted to answer, that it is just a matter of personal taste. I don't agree. To me it is a design decision with important consequences. So i'd like to see answers where opion about this is backed by some logical and/or technical reasons.

    Read the article

  • php turn unicode http link into clickable

    - by newinjs
    Hello, i have unicode link needed to be turn into links. Is it possible to change unicode into clickable? Currently i'm using this piece of code to turn link into clickable function clickable_link($text) { $ret = ' ' . $text; $ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a class=\"hrefLink\" href=\"\\2\" target=\"_blank\">\\2</a>", $ret); $ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a class=\"hrefLink\" href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret); $ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret); $ret = substr($ret, 1); return $ret; } Any help would be deeply appreciated.

    Read the article

< Previous Page | 59 60 61 62 63 64 65 66 67 68 69 70  | Next Page >