Search Results

Search found 784 results on 32 pages for 'chars'.

Page 10/32 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • networkstream always empty!

    - by ALEX
    hey I'm writing on an Server-Client program but when my client sends something, it never reaches my server! I'm sending like this: public void Send(string s) { char[] chars = s.ToCharArray(); byte[] bytes = chars.CharToByte(); nstream.Write(bytes, 0, bytes.Length); nstream.Flush(); } and Receiving in a background thread like this void CheckIncoming(object dd) { RecievedDelegate d = (RecievedDelegate)dd; try { while (true) { List<byte> bytelist = new List<byte>(); System.Threading.Thread.Sleep(1000); int ssss; ssss = nstream.ReadByte(); if (ssss > 1) { System.Diagnostics.Debugger.Break(); } if (bytelist.Count != 0) { d.Invoke(bytelist.ToArray()); } } } catch (Exception exp) { MSGBOX("ERROR:\n" + exp.Message); } } the ssss int is never 1 whats happening here???

    Read the article

  • How to get all captures of subgroup matches with preg_match_all()?

    - by hakre
    Update/Note: I think what I'm probably looking for is to get the captures of a group in PHP. Referenced: PCRE regular expressions using named pattern subroutines. (Read carefully:) I have a string that contains a variable number of segments (simplified): $subject = 'AA BB DD '; // could be 'AA BB DD CC EE ' as well I would like now to match the segments and return them via the matches array: $pattern = '/^(([a-z]+) )+$/i'; $result = preg_match_all($pattern, $subject, $matches); This will only return the last match for the capture group 2: DD. Is there a way that I can retrieve all subpattern captures (AA, BB, DD) with one regex execution? Isn't preg_match_all suitable for this? This question is a generalization. Both the $subject and $pattern are simplified. Naturally with such the general list of AA, BB, .. is much more easy to extract with other functions (e.g. explode) or with a variation of the $pattern. But I'm specifically asking how to return all of the subgroup matches with the preg_...-family of functions. For a real life case imagine you have multiple (nested) level of a variant amount of subpattern matches. Example This is an example in pseudo code to describe a bit of the background. Imagine the following: Regular definitions of tokens: CHARS := [a-z]+ PUNCT := [.,!?] WS := [ ] $subject get's tokenized based on these. The tokenization is stored inside an array of tokens (type, offset, ...). That array is then transformed into a string, containing one character per token: CHARS -> "c" PUNCT -> "p" WS -> "s" So that it's now possible to run regular expressions based on tokens (and not character classes etc.) on the token stream string index. E.g. regex: (cs)?cp to express one or more group of chars followed by a punctuation. As I now can express self-defined tokens as regex, the next step was to build the grammar. This is only an example, this is sort of ABNF style: words = word | (word space)+ word word = CHARS+ space = WS punctuation = PUNCT If I now compile the grammar for words into a (token) regex I would like to have naturally all subgroup matches of each word. words = (CHARS+) | ( (CHARS+) WS )+ (CHARS+) # words resolved to tokens words = (c+)|((c+)s)+c+ # words resolved to regex I could code until this point. Then I ran into the problem that the sub-group matches did only contain their last match. So I have the option to either create an automata for the grammar on my own (which I would like to prevent to keep the grammar expressions generic) or to somewhat make preg_match working for me somehow so I can spare that. That's basically all. Probably now it's understandable why I simplified the question. Related: pcrepattern man page Get repeated matches with preg_match_all()

    Read the article

  • How can I map URLs to filenames with perl?

    - by eugene y
    In a simple webapp I need to map URLs to filenames or filepaths. This app has a requirement that it can depend only on modules in the core Perl ditribution (5.6.0 and later). The problem is that filename length on most filesystems is limited to 255. Another limit is about 32k subdirectories in a single folder. My solution: my $filename = $url; if (length($filename) > $MAXPATHLEN) { # if filename longer than 255 my $part1 = substr($filename, 0, $MAXPATHLEN - 13); # first 242 chars my $part2 = crypt(0, substr($filename, $MAXPATHLEN - 13)); # 13 chars hash $filename = $part1.$part2; } $filename =~ s!/!_!g; # escape directory separator Is it reliable ? How can it be improved ?

    Read the article

  • How to replace the char '[' etc with '\[' using "sed" in a file ?

    - by Abhijeet
    I have a file say "file.txt" with following contents: Capsule arr**[**0**]** in state A rate_ul/dl=**(**2000000/7000000**)** Capsule RBx**[**0**]** in state ... ... using sed operator how can i replace all occurences of '[' with '[', '(' with '(', ']' with ']' and so on. Capsule arr**\[**0**\]** in state A rate_ul/dl=**\(**2000000/7000000**\)** Capsule RBx**\[**0**\]** in state ... ... Using the substitue operator in "gvim" I am able to achieve the same result. ie. if i use ":1,$ s/\[/\\[/g" in the vi editor in command mode I see all the '[' chars replaced with '['. However if I try to use the same substitue command in a shell script using a sed command, i am not able to achieve the same result. ie If i use the following command in a shell script I am not able to achieve the desired result: sed "s/\[/\\[/g" $temp_file2 > $temp_file1 where $temp_file2 conatins the lines with '[' characters and $temp_file1 should contain the replaced '\[' chars

    Read the article

  • Database table schema design - varchar(n). Suitable choice of N

    - by morpheous
    Coming from a C background, I may be getting too anal about this and worrying unnecessarily about bits and bytes here. Still, I cant help thinking how the data is actually stored and that if I choose an N which is easily factorizable into a power of 2, the database will be more effecient in how it packs data etc. Using this "logic", I have a string field in a table which is a variable length up to 21 chars. I am tempted to use 32 instead of 21, for the reason given above - however now I am thinking that I am wasting disk space because there will be space allocated for 11 extra chars that are guaranteed to be never used. Since I envisage storing several tens of thousands of rows a day, it all adds up. Question: Mindful of all of the above, Should I declare varchar(21) or varchar(32) and why?

    Read the article

  • Applescript: cleaning a string

    - by Mike
    I have this string that has illegal chars that I want to remove but I don't know what kind of chars may be present. I built a list of chars that I want not to be filtered and I built this script (from another one I found on the web). on clean_string(TheString) --Store the current TIDs. To be polite to other scripts. set previousDelimiter to AppleScript's text item delimiters set potentialName to TheString set legalName to {} set legalCharacters to {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "?", "+", "-", "Ç", "ç", "á", "Á", "é", "É", "í", "Í", "ó", "Ó", "ú", "Ú", "â", "Â", "ã", "Ã", "ñ", "Ñ", "õ", "Õ", "à", "À", "è", "È", "ü", "Ü", "ö", "Ö", "!", "$", "%", "/", "(", ")", "&", "€", "#", "@", "=", "*", "+", "-", ",", ".", "–", "_", " ", ":", ";", ASCII character 10, ASCII character 13} --Whatever you want to eliminate. --Now iterate through the characters checking them. repeat with thisCharacter in the characters of potentialName set thisCharacter to thisCharacter as text if thisCharacter is in legalCharacters then set the end of legalName to thisCharacter log (legalName as string) end if end repeat --Make sure that you set the TIDs before making the --list of characters into a string. set AppleScript's text item delimiters to "" --Check the name's length. if length of legalName is greater than 32 then set legalName to items 1 thru 32 of legalName as text else set legalName to legalName as text end if --Restore the current TIDs. To be polite to other scripts. set AppleScript's text item delimiters to previousDelimiter return legalName end clean_string The problem is that this script is slow as hell and gives me timeout. What I am doing is checking character by character and comparing against the legalCharacters list. If the character is there, it is fine. If not, ignore. Is there a fast way to do that? something like "look at every char of TheString and remove those that are not on legalCharacters" ? thanks for any help.

    Read the article

  • Scala updating/creating value in a hashmap

    - by user1672739
    I don't understand this with Scala hasmaps: How do I create a value or update one if it does not exist? I am tryng to count the number of characters in a list of Strings. I've tried this code but it doesn't work : def times(chars: List[Char]): List[(Char, Int)] = { val map = new HashMap[Char, Int]() chars.foreach( (c : Char) => { map.update(c, map.get(c) + 1) }) } I understand the returning type isn't correct. But is my foreach loop wrong? Is there a prettier way to write it?

    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

  • Ubuntu 12.04 Asus Eee PC 1005 weird keyboard

    - by radioheads
    After upgrading to 12.04 on my netbook the keyboard got weird behaviour Before logging in to any session everything's OK (i tested the input in vt1) but as i log in with any session (unity or unity-2d) keyboard behaves as if Fn key was pressed (i got numbers and special symbols instead of normal chars. I think the problem may be in acpi support, but i don't know where to start exactly. I will appreciate any help =) P.S. Sorry for my english - I am not a native speaker =)

    Read the article

  • How does Github calculate language percentage in a repo?

    - by John Isaacks
    I have a repo with Ruby and PHP code in it. Github says my repo is 74.8% PHP and 25.2% Ruby I do not understand how this can be. When I compare the 2 languages in my project: # Count how many files: # Ruby ls | grep ".*\.rb" | wc -l # returns 10 #PHP ls | grep ".*\.php" | wc -l # returns 1 # Count how many lines, words, chars: # Ruby cat *.rb | wc # returns 229, 812, 5303 # PHP cat *.php | wc # returns 102, 473, 2760 Ruby always seems to have more. Am I missing something?

    Read the article

  • How to deal with MySQL Connector/ODBC error "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'"

    - by user12653020
    I am sure many users run into a mysterious problem when perfectly working ODBC configurations started failing with errors like: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' The above error message might be preceded with something like [nxDc[yQ]. At the same time odbc.ini specifies in its DSN different SOCKET=/tmp/mysql.sock or a TCP connection SERVER=<remote_host_or_ip>. The question is, what had happened that the ODBC driver started to ignore the DSN options? The clue lies in the corrupted string [nxDc[yQ], which actually was [UnixODBC][MySQL] with each 2nd symbol removed. This is the case of bad conversion from SQLCHAR to SQLWCHAR. The UnixODBC driver manager took a single-byte character string from the client application and tried to convert it into the wide (multi-byte) characters for the Unicode version of MyODBC driver: Initially the piece of the connection string was represented by 1-byte chars like: [S][E][R][V][E][R][=][m][y][h][o][s][t][;] after the bad conversion to wide chars (commonly 2-byte UTF-16) [SE][RV][ER][=m][yh][os][t;] instead of [S\0][E\0][R\0][V\0][E\0][R\0][=\0][m\0][y\0][h\0][o\0][s\0][t\0][;\0] Naturally, the MyODBC driver could not parse the bad string and tried to use the default connection type (SOCKET) with the default value (/var/lib/mysql/mysql.sock) Now we know what happened, but why it happened? In most cases it happened because of using ODBCManageDataSourcesQ4 utility or its older analog ODBCConfig. When registering ODBC drivers they put lots of additional options and one of these options badly affects the UnixODBC driver manager itself. The solution is simple - remove or comment out the option in odbcinst.ini file (it is empty by default) set for the driver: [MySQL ODBC 5.2.6 Driver] Description    = Driver         = /home/dbs/myodbc526/lib/libmyodbc5w.so Driver64       = /home/dbs/myodbc526/lib/libmyodbc5w.so Setup          = /home/dbs/myodbc526/lib/libmyodbc5S.so Setup64        = /home/dbs/myodbc526/lib/libmyodbc5S.so UsageCount     = 1 CPTimeout      = 0 CPTimeToLive   = 0 IconvEncoding  =  # <--------- remove this line Trace          = TraceFile      = TraceLibrary   = After applying this simple solution (remove the line with IconvEncoding = ) everything came to normal. Prior to removing that line I tried putting different encoding names there, but the result was not good, so I really don't know how to properly use it. Unfortunately, UnixODBC manuals say nothing about it. Therefore, removing this option was the only way to get things done.

    Read the article

  • iMac OSX "no route to host"

    - by jairo
    I have an issue with one of my computer on my network. It is an iMac running OS X 10.5.8. The issue is accessing certain websites. For instance, one of these websites is that the computer is unable to connect to is farmville.com. When I ping farmville.com it returns "no route to host": $ ping farmville.com PING farmville.com (50.16.253.102): 56 data bytes ping: sendto: No route to host ping: sendto: No route to host ping: sendto: No route to host When I traceroute farmville: $ traceroute farmville.com traceroute: Warning: farmville.com has multiple addresses; using 50.16.253.109 traceroute to farmville.com (50.16.253.109), 64 hops max, 40 byte packets traceroute: sendto: No route to host 1 traceroute: wrote farmville.com 40 chars, ret=-1 tracerouting the farmville ip address: 50.16.253.109 $ traceroute 50.16.253.109 traceroute to farmville.com (50.16.253.109), 64 hops max, 40 byte packets traceroute: sendto: No route to host 1 traceroute: wrote farmville.com 40 chars, ret=-1 Now the interesting part is that I on another computer (running Ubuntu 10.10) I have no issues at all accessing this website. Which tells me that it's not the internet connection. I've also disabled the firewall on the router to no avail. The /etc/hosts file in the mac is the following. The /private/etc/hosts file is empty: ## # Host Database # # localhost is used to configure the loopback interface # when the system is booting. Do not change this entry. ## 127.0.0.1 localhost #255.255.255.255 broadcasthost ::1 localhost fe80::1%lo0 localhost Any help is appreciated. Many thanks

    Read the article

  • Google Chrome doesn't respond user actions correctly

    - by Carlos A. Junior
    Recently I've changed my OS to Ubuntu 12.04 (Cinnamon, 64 bits) from Mint 13 (KDE, 64 bits) and one same bug still appears on new installation. The Google Chrome it seems that don't refresh (repaint) page based on my interactions. Example: When i'm try comment an Youtube vídeo, when i click on textarea, o cursor don't appear inside of textarea, BUT, when/if i change to another tab and return the cursor appears...OK... If i start write some text...according i'm typing the chars don't appers...again if i change to another tab and return the typed text appears on textarea. Other cases that this bug appears: Modal boxes link...don't show the modal; Forms inside modal boxes don't show typed chars; The common Discus comment plugin don't work when focused; I don't have any idea of reason of this bug. (video driver, window manager, Chrome bug ?, i don't know) Any idea to solve this ? Additional informations: Google Chrome 22.0.1229.79 (Official Build 158531) OS Linux WebKit 537.4 (@129177) JavaScript V8 3.12.19.11 Flash 11.3.31.331 User Agent Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4 Command Line /opt/google/chrome/google-chrome --flag-switches-begin --flag-switches-end Executable Path /opt/google/chrome/google-chrome Profile Path /home/carlos/.config/google-chrome/Default Kernel version: 3.2.0-31-generic-pae Ubuntu 12.04 Best regards.

    Read the article

  • Why can't I route to some sites from my MacBook Pro that I can see from my iPad?

    - by Robert Atkins
    I am on M1 Cable (residential) broadband in Singapore. I have an intermittent problem routing to some sites from my MacBook Pro—often Google-related sites (arduino.googlecode.com and ajax.googleapis.com right now, but sometimes even gmail.com.) This prevents StackExchange chat from working, for instance. Funny thing is, my iPad can route to those sites and they're on the same wireless network! I can ping the sites, but not traceroute to them which I find odd. That I can get through via the iPad implies the problem is with the MBP. In any case, calling M1 support is... not helpful. I get the same behaviour when I bypass the Airport Express entirely and plug the MBP directly into the cable modem. Can anybody explain a) how this is even possible and b) how to fix it? mella:~ ratkins$ ping ajax.googleapis.com PING googleapis.l.google.com (209.85.132.95): 56 data bytes 64 bytes from 209.85.132.95: icmp_seq=0 ttl=50 time=11.488 ms 64 bytes from 209.85.132.95: icmp_seq=1 ttl=53 time=13.012 ms 64 bytes from 209.85.132.95: icmp_seq=2 ttl=53 time=13.048 ms ^C --- googleapis.l.google.com ping statistics --- 3 packets transmitted, 3 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 11.488/12.516/13.048/0.727 ms mella:~ ratkins$ traceroute ajax.googleapis.com traceroute to googleapis.l.google.com (209.85.132.95), 64 hops max, 52 byte packets traceroute: sendto: No route to host 1 traceroute: wrote googleapis.l.google.com 52 chars, ret=-1 *traceroute: sendto: No route to host traceroute: wrote googleapis.l.google.com 52 chars, ret=-1 ^C mella:~ ratkins$ The traceroute from the iPad goes (and I'm copying this by hand): 10.0.1.1 119.56.34.1 172.20.8.222 172.31.253.11 202.65.245.1 202.65.245.142 209.85.243.156 72.14.233.145 209.85.132.82 From the MBP, I can't traceroute to any of the IPs from 172.20.8.222 onwards. [For extra flavour, not being able to access the above appears to stop me logging in to Server Fault via OpenID and formatting the above traceroutes correctly. Anyone with sufficient rep here to do so, I'd be much obliged.]

    Read the article

  • Why can't I route to some sites from my MacBook Pro that I can see from my iPad? [closed]

    - by Robert Atkins
    I am on M1 Cable (residential) broadband in Singapore. I have an intermittent problem routing to some sites from my MacBook Pro—often Google-related sites (arduino.googlecode.com and ajax.googleapis.com right now, but sometimes even gmail.com.) This prevents StackExchange chat from working, for instance. Funny thing is, my iPad can route to those sites and they're on the same wireless network! I can ping the sites, but not traceroute to them which I find odd. That I can get through via the iPad implies the problem is with the MBP. In any case, calling M1 support is... not helpful. I get the same behaviour when I bypass the Airport Express entirely and plug the MBP directly into the cable modem. Can anybody explain a) how this is even possible and b) how to fix it? mella:~ ratkins$ ping ajax.googleapis.com PING googleapis.l.google.com (209.85.132.95): 56 data bytes 64 bytes from 209.85.132.95: icmp_seq=0 ttl=50 time=11.488 ms 64 bytes from 209.85.132.95: icmp_seq=1 ttl=53 time=13.012 ms 64 bytes from 209.85.132.95: icmp_seq=2 ttl=53 time=13.048 ms ^C --- googleapis.l.google.com ping statistics --- 3 packets transmitted, 3 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 11.488/12.516/13.048/0.727 ms mella:~ ratkins$ traceroute ajax.googleapis.com traceroute to googleapis.l.google.com (209.85.132.95), 64 hops max, 52 byte packets traceroute: sendto: No route to host 1 traceroute: wrote googleapis.l.google.com 52 chars, ret=-1 *traceroute: sendto: No route to host traceroute: wrote googleapis.l.google.com 52 chars, ret=-1 ^C mella:~ ratkins$ The traceroute from the iPad goes (and I'm copying this by hand): 10.0.1.1 119.56.34.1 172.20.8.222 172.31.253.11 202.65.245.1 202.65.245.142 209.85.243.156 72.14.233.145 209.85.132.82 From the MBP, I can't traceroute to any of the IPs from 172.20.8.222 onwards. [For extra flavour, not being able to access the above appears to stop me logging in to Server Fault via OpenID and formatting the above traceroutes correctly. Anyone with sufficient rep here to do so, I'd be much obliged.]

    Read the article

  • Colorizing your terminal and shell environment?

    - by Stefan Lasiewski
    I spend most of my time working in Unix environments and using Terminal emulators. I try to use color on the commandline, because color makes the output more useful and intuitive. What are some good ways to add color to my terminal environment? What tricks do you do? What pitfals have you encountered? Unfortunately, support for color is wildly variable depending on terminal type, OS, TERM setting, utility, buggy implementations, etc. Here's what I do currently, after alot of experimentation: I tend to set 'TERM=xterm-color', which is supported on most hosts (but not all). I work on a number of different hosts, different OS versions, etc. I'm trying to keep things simple and generic, if possible. Many OSs set things like 'dircolors' and by default, and I don't want to modify this everywhere. So I try to stick with the defaults. Instead tweak my Terminal's color configuration. Use color for some unix commands (ls, grep, less, vim) and the Bash prompt. These commands seem to the standard "ANSI escape sequences" I've managed to find some settings which are widely supported, and which don't print gobbledygook characters in older environments (even FreeBSD4!) (For the most part). From my .bash_profile ### Color support # The Terminal application typically does 'export TERM=term=color' # Some terminal types will print Black, White & underlined with these settings. OS=`uname -s` case "$OS" in "SunOS" ) # Solaris9 ls doesn't allow color, so use special characters instead. LS_OPTS='-F' ;; "Linux" ) # GNU tools supports colors! See dircolors to customize colors export LS_OPTS='--color=auto' # Color support using 'less -R' alias less='less --RAW-CONTROL-CHARS' alias ls='ls ${LS_OPTS} export GREP_OPTIONS="--color=auto" ;; "Darwin"|"FreeBSD") # Most FreeBSD & Apple Darwin supports colors # LS_OPTS="-G" export CLICOLOR=true alias less='less --RAW-CONTROL-CHARS' export GREP_OPTIONS="--color=auto" ;; esac

    Read the article

  • Filtered ListView not updated

    - by Anton
    Hi! I have a ListView with a custom Adapter that extends ArrayAdapter. It's a ArrayAdapter of Type Artist. Artist is a very small class that has a name and an id. The Artist Class has toString() overridden to return just the name. I have an EditText. The EditText has an TextChangeListener where i call .getFilter().filter(chars, callback) on my adapter. In the Filter.Filterlistener().onComplete() callback i print the count and it looks really good. As i type the count decreases. So it seams everything works as advertised, but the List stays the same. I tried to call artistAdapter.notifyDataSetChanged() to force the list to redraw, but nothing happens. [see 2.)] I am tinkering around for days now! I am desperate.. Hopefully someone can have a look on my code and tell me what i am doing wrong! Thanks! Here is what i have done: 1.) Defined a ListView and an EditText like this: <EditText xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/list_search_text" android:layout_width="fill_parent" android:layout_height="35dip" android:layout_below="@id/header"> </EditText> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/list_search" android:layout_width="fill_parent" android:layout_height="fill_parent"> </ListView> 2.) Setup my ListView in the Activities onCreate(): private ListView listView = null; private ArtistAdapter artistAdapter = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_artists); artistAdapter = new ArtistAdapter(this, R.layout.row, list); // 'list' is an ArrayList<Artist> listView = (ListView) findViewById(R.id.list_search); listView.setAdapter(artistAdapter); listView.setFastScrollEnabled(true); listView.setTextFilterEnabled(true); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> av, View v, int position, long id) { // do something } }); EditText txtSearch = (EditText) findViewById(R.id.list_search_text); txtSearch.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable arg0) { } public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } public void onTextChanged(CharSequence chars, int start, int before, int count) { artistAdapter.getFilter().filter(chars, new Filter.FilterListener() { public void onFilterComplete(int count) { Log.d(Config.LOG_TAG, "filter complete! count: " + count); artistAdapter.notifyDataSetChanged(); } }); } }); } 3.) This is my ArtistAdapter in short. I added an remove() and add() method: public class ArtistAdapter extends ArrayAdapter<Artist> implements SectionIndexer { private List<Artist> items; /* other stuff like overridden getView, getPositionForSection, getSectionForPosition and so on */ @Override public void remove(Artist object) { super.remove(object); items.remove(object); } @Override public void add(Artist object) { super.add(object); items.add(object); } } 4.) My artist has also the toString() overridden: public class Artist implements Comparable<Artist> { public String uid; public String name; public Artist(String id, String name) { this.uid = id; this.name = name; } public int compareTo(Artist another) { return this.name.compareToIgnoreCase(another.name); } @Override public String toString() { return this.name; } }

    Read the article

  • Reading off a socket until end of line C#?

    - by Omar Kooheji
    I'm trying to write a service that listens to a TCP Socket on a given port until an end of line is recived and then based on the "line" that was received executes a command. I've followed a basic socket programming tutorial for c# and have come up with the following code to listen to a socket: public void StartListening() { _log.Debug("Creating Maing TCP Listen Socket"); _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, _port); _log.Debug("Binding to local IP Address"); _mainSocket.Bind(ipLocal); _log.DebugFormat("Listening to port {0}",_port); _mainSocket.Listen(10); _log.Debug("Creating Asynchronous callback for client connections"); _mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null); } public void OnClientConnect(IAsyncResult asyn) { try { _log.Debug("OnClientConnect Creating worker socket"); Socket workerSocket = _mainSocket.EndAccept(asyn); _log.Debug("Adding worker socket to list"); _workerSockets.Add(workerSocket); _log.Debug("Waiting For Data"); WaitForData(workerSocket); _log.DebugFormat("Clients Connected [{0}]", _workerSockets.Count); _mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null); } catch (ObjectDisposedException) { _log.Error("OnClientConnection: Socket has been closed\n"); } catch (SocketException se) { _log.Error("Socket Exception", se); } } public class SocketPacket { private System.Net.Sockets.Socket _currentSocket; public System.Net.Sockets.Socket CurrentSocket { get { return _currentSocket; } set { _currentSocket = value; } } private byte[] _dataBuffer = new byte[1]; public byte[] DataBuffer { get { return _dataBuffer; } set { _dataBuffer = value; } } } private void WaitForData(Socket workerSocket) { _log.Debug("Entering WaitForData"); try { lock (this) { if (_workerCallback == null) { _log.Debug("Initializing worker callback to OnDataRecieved"); _workerCallback = new AsyncCallback(OnDataRecieved); } } SocketPacket socketPacket = new SocketPacket(); socketPacket.CurrentSocket = workerSocket; workerSocket.BeginReceive(socketPacket.DataBuffer, 0, socketPacket.DataBuffer.Length, SocketFlags.None, _workerCallback, socketPacket); } catch (SocketException se) { _log.Error("Socket Exception", se); } } public void OnDataRecieved(IAsyncResult asyn) { SocketPacket socketData = (SocketPacket)asyn.AsyncState; try { int iRx = socketData.CurrentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; _log.DebugFormat("Created Char array to hold incomming data. [{0}]",iRx+1); System.Text.Decoder decoder = System.Text.Encoding.UTF8.GetDecoder(); int charLength = decoder.GetChars(socketData.DataBuffer, 0, iRx, chars, 0); _log.DebugFormat("Read [{0}] characters",charLength); String data = new String(chars); _log.DebugFormat("Read in String \"{0}\"",data); WaitForData(socketData.CurrentSocket); } catch (ObjectDisposedException) { _log.Error("OnDataReceived: Socket has been closed. Removing Socket"); _workerSockets.Remove(socketData.CurrentSocket); } catch (SocketException se) { _log.Error("SocketException:",se); _workerSockets.Remove(socketData.CurrentSocket); } } This I thought was going to be a good basis for what I wanted to do, but the code I have appended the incoming characters to a text box one by one and didn't do anything with it. Which doesn't really work for what I want to do. My main issue is the decoupling of the OnDataReceived method from the Wait for data method. which means I'm having issues building a string (I would use a string builder but I can accept multiple connections so that doesn't really work. Ideally I'd like to look while listening to a socket until I see and end of line character and then call a method with the resulting string as a parameter. What's the best way to go about doing this.

    Read the article

  • Opinions on Dual-Salt authentication for low sensitivity user accounts?

    - by Heleon
    EDIT - Might be useful for someone in the future... Looking around the bcrypt class in php a little more, I think I understand what's going on, and why bcrypt is secure. In essence, I create a random blowfish salt, which contains the number of crypt rounds to perform during the encryption step, which is then hashed using the crypt() function in php. There is no need for me to store the salt I used in the database, because it's not directly needed to decrypt, and the only way to gain a password match to an email address (without knowing the salt values or number of rounds) would be to brute force plain text passwords against the hash stored in the database using the crypt() function to verify, which, if you've got a strong password, would just be more effort than it's worth for the user information i'm storing... I am currently working on a web project requiring user accounts. The application is CodeIgniter on the server side, so I am using Ion Auth as the authentication library. I have written an authentication system before, where I used 2 salts to secure the passwords. One was a server-wide salt which sat as an environment variable in the .htaccess file, and the other was a randomly generated salt which was created at user signup. This was the method I used in that authentication system for hashing the password: $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //create a random string to be used as the random salt for the password hash $size = strlen($chars); for($i = 0; $i < 22; $i++) { $str .= $chars[rand(0, $size - 1)]; } //create the random salt to be used for the crypt $r_blowfish_salt = "$2a$12$" . $str . "$"; //grab the website salt $salt = getenv('WEBSITE_SALT'); //combine the website salt, and the password $password_to_hash = $pwd . $salt; //crypt the password string using blowfish $password = crypt($password_to_hash, $r_blowfish_salt); I have no idea whether this has holes in it or not, but regardless, I moved over to Ion Auth for a more complete set of functions to use with CI. I noticed that Ion only uses a single salt as part of its hashing mechanism (although does recommend that encryption_key is set in order to secure the database session.) The information that will be stored in my database is things like name, email address, location by country, some notes (which will be recommended that they do not contain sensitive information), and a link to a Facebook, Twitter or Flickr account. Based on this, i'm not convinced it's necessary for me to have an SSL connection on the secure pages of my site. My question is, is there a particular reason why only 1 salt is being used as part as the Ion Auth library? Is it implied that I write my own additional salting in front of the functionality it provides, or am I missing something? Furthermore, is it even worth using 2 salts, or once an attacker has the random salt and the hashed password, are all bets off anyway? (I assume not, but worth checking if i'm worrying about nothing...)

    Read the article

  • Path to background in servlet

    - by kapil chhattani
    //the below line is the element of my HTML form which renders the image sent by the servlet written further below. <img style="margin-left:91px; margin-top:-6px;" class="image" src="http://www.abcd.com/captchaServlet"> I generate a captcha code using the following code in java. public class captchaServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 150; int height = 50; int charsToPrint = 6; String elegibleChars = "ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy1234567890"; char[] chars = elegibleChars.toCharArray(); StringBuffer finalString = new StringBuffer(); for ( int i = 0; i < charsToPrint; i++ ) { double randomValue = Math.random(); int randomIndex = (int) Math.round(randomValue * (chars.length - 1)); char characterToShow = chars[randomIndex]; finalString.append(characterToShow); } System.out.println(finalString); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bufferedImage.createGraphics(); Font font = new Font("Georgia", Font.BOLD, 18); g2d.setFont(font); RenderingHints rh = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(rh); GradientPaint gp = new GradientPaint(0, 0, Color.BLUE, 0, height/2, Color.black, true); g2d.setPaint(gp); g2d.fillRect(0, 0, width, height); g2d.setColor(new Color(255, 255, 0)); Random r = new Random(); int index = Math.abs(r.nextInt()) % 5; char[] data=new String(finalString).toCharArray(); String captcha = String.copyValueOf(data); int x = 0; int y = 0; for (int i=0; i<data.length; i++) { x += 10 + (Math.abs(r.nextInt()) % 15); y = 20 + Math.abs(r.nextInt()) % 20; g2d.drawChars(data, i, 1, x, y); } g2d.dispose(); response.setContentType("image/png"); OutputStream os = response.getOutputStream(); ImageIO.write(bufferedImage, "png", os); os.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } } But in the above code background is also generated using the setPaint menthod I am guessing. I want the background to be some image from my local machine whoz URL i should be able to mention like URL url=this.getClass().getResource("Desktop/images.jpg"); BufferedImage bufferedImage = ImageIO.read(url); I am just writing the above two lines for making the reader understand better what the issue is. Dont want to use the exact same commands. All I want is the the background of the captcha code generated should be an image of my choice.

    Read the article

  • How to use a list of values in Excel as filter in a query

    - by Luca Zavarella
    It often happens that a customer provides us with a list of items for which to extract certain information. Imagine, for example, that our clients wish to have the header information of the sales orders only for certain orders. Most likely he will give us a list of items in a column in Excel, or, less probably, a simple text file with the identification code:     As long as the given values ??are at best a dozen, it costs us nothing to copy and paste those values ??in our SSMS and place them in a WHERE clause, using the IN operator, making sure to include the quotes in the case of alphanumeric elements (the database sample is AdventureWorks2008R2): SELECT * FROM Sales.SalesOrderHeader AS SOH WHERE SOH.SalesOrderNumber IN ( 'SO43667' ,'SO43709' ,'SO43726' ,'SO43746' ,'SO43782' ,'SO43796') Clearly, the need to add commas and quotes becomes an hassle when dealing with hundreds of items (which of course has happened to us!). It’d be comfortable to do a simple copy and paste, leaving the items as they are pasted, and make sure the query works fine. We can have this commodity via a User Defined Function, that returns items in a table. Simply we’ll provide the function with an input string parameter containing the pasted items. I give you directly the T-SQL code, where comments are there to clarify what was written: CREATE FUNCTION [dbo].[SplitCRLFList] (@List VARCHAR(MAX)) RETURNS @ParsedList TABLE ( --< Set the item length as your needs Item VARCHAR(255) ) AS BEGIN DECLARE --< Set the item length as your needs @Item VARCHAR(255) ,@Pos BIGINT --< Trim TABs due to indentations SET @List = REPLACE(@List, CHAR(9), '') --< Trim leading and trailing spaces, then add a CR\LF at the end of the list SET @List = LTRIM(RTRIM(@List)) + CHAR(13) + CHAR(10) --< Set the position at the first CR/LF in the list SET @Pos = CHARINDEX(CHAR(13) + CHAR(10), @List, 1) --< If exist other chars other than CR/LFs in the list then... IF REPLACE(@List, CHAR(13) + CHAR(10), '') <> '' BEGIN --< Loop while CR/LFs are over (not found = CHARINDEX returns 0) WHILE @Pos > 0 BEGIN --< Get the heading list chars from the first char to the first CR/LF and trim spaces SET @Item = LTRIM(RTRIM(LEFT(@List, @Pos - 1))) --< If the so calulated item is not empty... IF @Item <> '' BEGIN --< ...insert it in the @ParsedList temporary table INSERT INTO @ParsedList (Item) VALUES (@Item) --(CAST(@Item AS int)) --< Use the appropriate conversion if needed END --< Remove the first item from the list... SET @List = RIGHT(@List, LEN(@List) - @Pos - 1) --< ...and set the position to the next CR/LF SET @Pos = CHARINDEX(CHAR(13) + CHAR(10), @List, 1) --< Repeat this block while the upon loop condition is verified END END RETURN END At this point, having created the UDF, our query is transformed trivially in: SELECT * FROM Sales.SalesOrderHeader AS SOH WHERE SOH.SalesOrderNumber IN ( SELECT Item FROM SplitCRLFList('SO43667 SO43709 SO43726 SO43746 SO43782 SO43796') AS SCL) Convenient, isn’t it? You can find the script DBA_SplitCRLFList.sql here. Bye!!

    Read the article

  • How to find first non-repetitive character from a string?

    - by masato-san
    I've spent half day trying to figure out this and finally I got working solution. However, I feel like this can be done in simpler way. I think this code is not really readable. Problem: Find first non-repetitive character from a string. $string = "abbcabz" In this case, the function should output "c". The reason I use concatenation instead of $input[index_to_remove] = '' in order to remove character from a given string is because if I do that, it actually just leave empty cell so that my return value $input[0] does not not return the character I want to return. For instance, $str = "abc"; $str[0] = ''; echo $str; This will output "bc" But actually if I test, var_dump($str); it will give me: string(3) "bc" Here is my intention: Given: input while first char exists in substring of input { get index_to_remove input = chars left of index_to_remove . chars right of index_to_remove if dupe of first char is not found from substring remove first char from input } return first char of input Code: function find_first_non_repetitive2($input) { while(strpos(substr($input, 1), $input[0]) !== false) { $index_to_remove = strpos(substr($input,1), $input[0]) + 1; $input = substr($input, 0, $index_to_remove) . substr($input, $index_to_remove + 1); if(strpos(substr($input, 1), $input[0]) == false) { $input = substr($input, 1); } } return $input[0]; }

    Read the article

  • Vector is pointing to uninitialized bytes when used in recvfrom call

    - by Adam A.
    In a function that I am writing I am trying to return a pointer to a vector of unsigned chars. The relevant code is below. std::vector<unsigned char> *ret = new std::vector<unsigned char>(buffSize,'0'); int n = recvfrom(fd_, &((*ret)[0]) ,buffSize, &recvAddress, &sockSize); //This should work too... recvfrom(fd_, ret ,buffSize, &recvAddress, &sockSize); // display chars somehow just for testing for(std::vector<unsigned char>::iterator it=ret->begin(); it<it->end();i++) { std::cout<<*it; } std::cout<<std::endl; ... return ret; When I run this through valgrind I get errors talking about how the buffer in recvfrom is pointing to uninitialized bytes. I've narrowed this down to the vector since I swapped it out for an unsigned char array and everything works fine. Any suggestions?

    Read the article

  • Japanese text garbled while passing to a http restlet service

    - by satish-gunuputi
    Hi , I have a perl client which is calling a http restlet service (put method). Some of the parameters in this call contain japanese text. when I printed the contents of these request parameters in the restlet service I found these chars garbled ! This is my PERL client code: my %request_headers = ( 'DocumentName' => $document_name, --> This name is a JAPANESE String 'DocumentDescription' => 'Test Japanese Chars', 'content-length' => 200, 'Content-Type' => 'application/octet-stream; charset=utf-8', 'User-Agent' => "JPCharTester", ); $s-write_request('PUT', '/test-document/TEST/TEST_DOCUMENT' , %request_headers, $content); in this call both the values of $context and $document_name are JAPANESE Strings. But ONLY the document_name is received as garbled in my backend service. Here goes the Service code: String URL_ENCODING = "UTF-8"; String documentName = requestHeaders.getFirstValue("DocumentName"); System.out.println("Encoded Document Name : "+documentName+" <<<"); --> documentName is garbled here try { documentName = URLDecoder.decode(documentName, URL_ENCODING); System.out.println(>>> Decoded Document Name : "+documentName+" <<<"); --> documentName is garbled here } catch (java.io.UnsupportedEncodingException ex) { throwException(ex.getMessage(), Status.SERVER_ERROR_INTERNAL, ex); } both the above log statements printed GARBLED TEXT !! Can someone tell me what is the mistake I am doing and how to fix this ? Thanks in advance for your help. Regards, Satish.

    Read the article

  • URL Encoding using C#

    - by masfenix
    I have an application which I've developed for a friend. It sends a POST request to the VB forum software and logs someone in (with out setting cookies or anything). Once the user is logged in I create a variable that creates a path on their local machine. c:\tempfolder\date\username The problem is that some usernames are throwing "Illegal chars" exception. For example if my username was mas|fenix it would throw an exception.. Path.Combine( _ Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), _ DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username) I don't want to remove it from the string, but a folder with their username is created through FTP on a server. And this leads to my second question. If I am creating a folder on the server can I leave the "illegal chars" in? I only ask this because the server is Linux based, and I am not sure if Linux accepts it or not.. EDIT: It seems that URL encode is NOT what I want.. Here's what I want to do: old username = mas|fenix new username = mas%xxfenix Where %xx is the ASCII value or any other value that would easily identify the character.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >