Search Results

Search found 49435 results on 1978 pages for 'query string'.

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

  • How do I truncate a .NET string?

    - by Steve Guidi
    I apologize for such a question that likely has a trivial solution, but I strangely could not find a concise API for this problem. Essentially, I would like to truncate a string such that it its length is not longer than a given value. I am writing to a database table and want to ensure that the values I write meet the constraint of the column's datatype. For instance, it would be nice if I could write the following: string NormalizeLength(string value, int maxLength) { return value.Substring(0, maxLength); } Unfortunately, this raises an exception because maxLength exceeds the string boundaries. Of course, I could write a function like the following, but I was hoping that something like this already exists. string NormalizeLength(string value, int maxLength) { return value.Length <= maxLength ? value : value.Substring(0, maxLength); } Where is the elusive API that performs this task? Is there one?

    Read the article

  • string manipulation without alloc mem in c

    - by Mike
    I'm wondering if there is another way of getting a sub string without allocating memory. To be more specific, I have a string as: const char *str = "9|0\" 940 Hello"; Currently I'm getting the 940, which is the sub-string I want as, char *a = strstr(str,"9|0\" "); char *b = substr(a+5, 0, 3); // gives me the 940 Where substr is my sub string procedure. The thing is that I don't want to allocate memory for this by calling the sub string procedure. Is there a much easier way?, perhaps by doing some string manipulation and not alloc mem. I'll appreciate any feedback.

    Read the article

  • MySQL query optimization - distinct, order by and limit

    - by Manuel Darveau
    I am trying to optimize the following query: select distinct this_.id as y0_ from Rental this_ left outer join RentalRequest rentalrequ1_ on this_.id=rentalrequ1_.rental_id left outer join RentalSegment rentalsegm2_ on rentalrequ1_.id=rentalsegm2_.rentalRequest_id where this_.DTYPE='B' and this_.id<=1848978 and this_.billingStatus=1 and rentalsegm2_.endDate between 1273631699529 and 1274927699529 order by rentalsegm2_.id asc limit 0, 100; This query is done multiple time in a row for paginated processing of records (with a different limit each time). It returns the ids I need in the processing. My problem is that this query take more than 3 seconds. I have about 2 million rows in each of the three tables. Explain gives: +----+-------------+--------------+--------+-----------------------------------------------------+---------------+---------+--------------------------------------------+--------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+--------------+--------+-----------------------------------------------------+---------------+---------+--------------------------------------------+--------+----------------------------------------------+ | 1 | SIMPLE | rentalsegm2_ | range | index_endDate,fk_rentalRequest_id_BikeRentalSegment | index_endDate | 9 | NULL | 449904 | Using where; Using temporary; Using filesort | | 1 | SIMPLE | rentalrequ1_ | eq_ref | PRIMARY,fk_rental_id_BikeRentalRequest | PRIMARY | 8 | solscsm_main.rentalsegm2_.rentalRequest_id | 1 | Using where | | 1 | SIMPLE | this_ | eq_ref | PRIMARY,index_billingStatus | PRIMARY | 8 | solscsm_main.rentalrequ1_.rental_id | 1 | Using where | +----+-------------+--------------+--------+-----------------------------------------------------+---------------+---------+--------------------------------------------+--------+----------------------------------------------+ I tried to remove the distinct and the query ran three times faster. explain without the query gives: +----+-------------+--------------+--------+-----------------------------------------------------+---------------+---------+--------------------------------------------+--------+-----------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+--------------+--------+-----------------------------------------------------+---------------+---------+--------------------------------------------+--------+-----------------------------+ | 1 | SIMPLE | rentalsegm2_ | range | index_endDate,fk_rentalRequest_id_BikeRentalSegment | index_endDate | 9 | NULL | 451972 | Using where; Using filesort | | 1 | SIMPLE | rentalrequ1_ | eq_ref | PRIMARY,fk_rental_id_BikeRentalRequest | PRIMARY | 8 | solscsm_main.rentalsegm2_.rentalRequest_id | 1 | Using where | | 1 | SIMPLE | this_ | eq_ref | PRIMARY,index_billingStatus | PRIMARY | 8 | solscsm_main.rentalrequ1_.rental_id | 1 | Using where | +----+-------------+--------------+--------+-----------------------------------------------------+---------------+---------+--------------------------------------------+--------+-----------------------------+ As you can see, the Using temporary is added when using distinct. I already have an index on all fields used in the where clause. Is there anything I can do to optimize this query? Thank you very much!

    Read the article

  • Lucene Query Syntax

    - by Don
    Hi, I'm trying to use Lucene to query a domain that has the following structure Student 1-------* Attendance *---------1 Course The data in the domain is summarised below Course.name Attendance.mandatory Student.name ------------------------------------------------- cooking N Bob art Y Bob If I execute the query "courseName:cooking AND mandatory:Y" it returns Bob, because Bob is attending the cooking course, and Bob is also attending a mandatory course. However, what I really want to query for is "students attending a mandatory cooking course", which in this case would return nobody. Is it possible to formulate this as a Lucene query? I'm actually using Compass, rather than Lucene directly, so I can use either CompassQueryBuilder or Lucene's query language. For the sake of completeness, the domain classes themselves are shown below. These classes are Grails domain classes, but I'm using the standard Compass annotations and Lucene query syntax. @Searchable class Student { @SearchableProperty(accessor = 'property') String name static hasMany = [attendances: Attendance] @SearchableId(accessor = 'property') Long id @SearchableComponent Set<Attendance> getAttendances() { return attendances } } @Searchable(root = false) class Attendance { static belongsTo = [student: Student, course: Course] @SearchableProperty(accessor = 'property') String mandatory = "Y" @SearchableId(accessor = 'property') Long id @SearchableComponent Course getCourse() { return course } } @Searchable(root = false) class Course { @SearchableProperty(accessor = 'property', name = "courseName") String name @SearchableId(accessor = 'property') Long id }

    Read the article

  • insert array to mysql db function

    - by ganjan
    Hi. I have an array where the keys represent each column in my database. Now I want a function that makes a mysql update query. Something like $db['money'] = $money_input + $money_db; $db['location'] = $location $query = 'UPDATE tbl_user SET '; for($x = 0; $x < count($db); $x++ ){ $query .= $db something ".=." $db something } $query .= "WHERE username=".$username." ";

    Read the article

  • C++ String manipulation isn't making sense to me...

    - by Andrew Bolster
    I am trying some of the Stanford SEE courses online to learn some new languages; this particular assignment has to do with removing substrings from strings. What I've got so far is below, but if text = "hello hello" and remove ="el", it gets stuck in a loop, but if i change text to text = "hello hllo", it works, making me think I'm doing something obviously stupid. There is a stipulation in the assignment not to modify the incoming strings, and instead to return a new string. string CensorString1(string text, string remove){ string returned; size_t found=0, lastfound=0; found = (text.substr(lastfound,text.size())).find(remove); while (string::npos != found ){ returned += text.substr(lastfound,found); lastfound = found + remove.size(); found = (text.substr(lastfound,text.size())).find(remove); } returned += text.substr(lastfound,found); return returned; } Guidance would be appreciated :-) Thanks

    Read the article

  • PHP: MySQL query duplicating update for no reason

    - by ThinkingInBits
    The code below is first the client code, then the class file. For some reason the 'deductTokens()' method is calling twice, thus charging an account double. I've been programming all night, so I may just need a second pair of eyes: if ($action == 'place_order') { if ($_REQUEST['unlimited'] == 200) { $license = 'extended'; } else { $license = 'standard'; } if ($photograph->isValidPhotographSize($photograph_id, $_REQUEST['size_radio'])) { $token_cost = $photograph->getTokenCost($_REQUEST['size_radio'], $_REQUEST['unlimited']); $order = new ImageOrder($_SESSION['user']['id'], $_REQUEST['size_radio'], $license, $token_cost); $order->saveOrder(); $order->deductTokens(); header('location: account.php'); } else { die("Please go back and select a valid photograph size"); } } ######CLASS CODE####### <?php include_once('database_classes.php'); class Order { protected $account_id; protected $cost; protected $license; public function __construct($account_id, $license, $cost) { $this->account_id = $account_id; $this->cost = $cost; $this->license = $license; } } class ImageOrder extends Order { protected $size; public function __construct($account_id, $size, $license, $cost) { $this->size = $size; parent::__construct($account_id, $license, $cost); } public function saveOrder() { //$db = Connect::connect(); //$account_id = $db->real_escape_string($this->account_id); //$size = $db->real_escape_string($this->size); //$license = $db->real_escape_string($this->license); //$cost = $db->real_escape_string($this->cost); } public function deductTokens() { $db = Connect::connect(); $account_id = $db->real_escape_string($this->account_id); $cost = $db->real_escape_string($this->cost); $query = "UPDATE accounts set tokens=tokens-$cost WHERE id=$account_id"; $result = $db->query($query); } } ?> When I die("$query"); directly after the query, it's printing the proper statement, and when I run that query within MySQL it works perfectly.

    Read the article

  • About the String#substring() method

    - by alain.janinm
    If we take a look at the String#substring method implementation : new String(offset + beginIndex, endIndex - beginIndex, value); We see that a new String is created with the same original content (parameter char [] value). So the workaround is to use new String(toto.substring(...)) to drop the reference to the original char[] value and make it eligible for GC (if no more references exist). I would like to know if there is a special reason that explain this implementation. Why the method doesn't create herself the new shorter String and why she keeps the full original value instead? The other related question is : should we always use new String(...) when dealing with substring?

    Read the article

  • String intern puzzles

    - by Yob
    On this blog I found interesting String puzzles: --- Quote --- String te = "te", st = "st"; //"test".length(); String username = te + st; username.intern(); System.out.println("String object the same is: " + (username == "test")); prints String object the same is: true but uncomment the "test".length(); line and it prints String object the same is: false --- EoQ --- Being honest I don't understand why the outputs are different. Could you please explain me what's the cause of such behaviour?

    Read the article

  • Making uppercase of std::string

    - by Daniel K.
    Which implementation do you think is better? std::string ToUpper( const std::string& source ) { std::string result; result.reserve( source.length() ); std::transform( source.begin(), source.end(), result.begin(), std::ptr_fun<int, int>( std::toupper ) ); return result; } and... std::string ToUpper( const std::string& source ) { std::string result( source.length(), '\0' ); std::transform( source.begin(), source.end(), result.begin(), std::ptr_fun<int, int>( std::toupper ) ); return result; } Difference is that the first one uses reserve method after the default constructor, but the second one uses the constructor accepting the number of characters.

    Read the article

  • string manipulations in C

    - by Vivek27
    Following are some basic questions that I have with respect to strings in C. If string literals are stored in read-only data segment and cannot be changed after initialisation, then what is the difference between the following two initialisations. char *string = "Hello world"; const char *string = "Hello world"; When we dynamically allocate memory for strings, I see the following allocation is capable enough to hold a string of arbitary length.Though this allocation work, I undersand/beleive that it is always good practice to allocate the actual size of actual string rather than the size of data type.Please guide on proper usage of dynamic allocation for strings. char *string = (char *)malloc(sizeof(char));

    Read the article

  • Why is Java String indexOf failing?

    - by Binaryrespawn
    Hi all, this must be quite simple but I am having great difficulty. You see I am trying to find a string within another string as follows. e = input.indexOf("-->"); s = input.indexOf("<!--"); input = input.replace(input.substring(s, e + 3), " "); The integers e and s are returning -1 in that it was not found and this is causing the replace method to fail. The test string I am using is "Chartered Certified<!--lol--> Accountants (ACCA)". I tried to creat a new string object and pass in the string as an argument as follows e=input.indexOf(new String("<!--")); This yielded the same result. Any ideas ?

    Read the article

  • c# creating a database query METHOD

    - by Sinaesthetic
    I'm not sure if im delluded but what I would like to do is create a method that will return the results of a query, so that i can reuse the connection code. As i understand it, a query returns an object but how do i pass that object back? I want to send the query into the method as a string argument, and have it return the results so that I can use them. Here's what i have which was a stab in the dark, it obviously doesn't work. This example is me trying to populate a listbox with the results of a query; the sheet name is Employees and the field/column is name. The error i get is "Complex DataBinding accepts as a data source either an IList or an IListSource.". any ideas? public Form1() { InitializeComponent(); openFileDialog1.ShowDialog(); openedFile = openFileDialog1.FileName; lbxEmployeeNames.DataSource = Query("Select [name] FROM [Employees$]"); } public object Query(string sql) { System.Data.OleDb.OleDbConnection MyConnection; System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand(); string connectionPath; //build connection string connectionPath = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openedFile + "';Extended Properties=Excel 8.0;"; MyConnection = new System.Data.OleDb.OleDbConnection(connectionPath); MyConnection.Open(); myCommand.Connection = MyConnection; myCommand.CommandText = sql; return myCommand.ExecuteNonQuery(); }

    Read the article

  • .NET Format a string with fixed spaces

    - by treant
    Does the .NET String.Format method allow placement of a string at a fixed position within a fixed length string. " String Goes Here" " String Goes Here " "String Goes Here " How is this done using .NET? Edit - I have tried Format/PadLeft/PadRight to death. They do not work. I don't know why. I ended up writing my own function to do this. Edit - I made a mistake and used a colon instead of a comma in the format specifier. Should be "{0,20}". Thanks for all of the excellent and correct answers.

    Read the article

  • Question about the String.replaceAll() and String.replaceFirst() method.

    - by Java Doe
    I need to do a simple string replace operation on a segment of string. I ran into the following issue and hope to get some advice. In the original string I got, I can replace the string such as to something else. BUT, in the same original string, if I want to replace a much long string such as the following, it won’t work. Nothing gets replaced after the call. <div class="more"><a href="http://SERVER_name/profiles/atom/mv/theboard/entries/related.do?email=xyz.com&ps=20&since=1273518953218&sinceEntryId=abc-def-123-456">More...</a></div> I tried these two methods: originalString.replaceFirst(moreTag, newContent); originalString.replaceAll(moreTag, newContent); Thanks in advance.

    Read the article

  • Simple UPDATE query with (sometime) long query times

    - by Eric
    I run a dedicated MySQL server (2 cores, 16GB RAM) serving 100-200 requests per second. It is getting sluggish during peak traffic and I have a hard time optimizing the server. So I'm looking for some ideas now that I have done lots of Innodb fine-tuning with the "TUNING PRIMER" The query that now generates most slow queries is the following (see result from mysqldumpslow): Count: 433 Time=3.40s (1470s) Lock=0.00s (0s) Rows=0.0 (0), UPDATE user_sessions SET tid='S' WHERE idsession='S' I am very surprised to have so many long queries for such a simple query with no locking. Fyi, the table is InnoDB and has 14000 rows. It contains all active sessions on the site with approx 10 UPDATE and SELECT hits per second. Here is its structure: CREATE TABLE `user_sessions` ( `personid` mediumint(9) NOT NULL DEFAULT '0', `ip` varchar(18) COLLATE utf8_unicode_ci NOT NULL, `idsession` varchar(32) COLLATE utf8_unicode_ci NOT NULL, `datum` date NOT NULL DEFAULT '0000-00-00', `tid` time NOT NULL DEFAULT '00:00:00', `status` tinyint(4) NOT NULL DEFAULT '0', KEY `personid` (`personid`), KEY `idsession` (`idsession`), KEY `datum` (`datum`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci Any ideas?

    Read the article

  • Excel equivilant of java's String.contains(String otherString)

    - by corsiKa
    I have a cell that has a fairly archaic String. (It's the mana cost of a Magic: the Gathering spell.) Examples are 3g, 2gg, 3ur, and bg. There are 5 possible letters (g w u b r). I have 5 columns and would like to count at the bottom how many of each it contains. So my spreadsheet might look like this A B C D E F G +-------------------------------------------- 1|Name Cost G W U B R 2|Centaur Healer 1gw 1 1 0 0 0 3|Sunspire Griffin 1ww 0 1 0 0 0 // just 1, even though 1ww 4|Rakdos Shred-Freak {br}{br} 0 0 0 1 1 Basically, I want something that looks like =if(contains($A2,C$1),1,0) and I can drag it across all 5 columns and down all 270 some cards. (Those are actual data, by the way. It's not mocked :-) .) In Java I would do this: String[] colors = { "B", "G", "R", "W", "U" }; for(String color : colors) { System.out.print(cost.toUpperCase().contains(color) ? 1 : 0); System.out.print("\t"); } Is there something like this in using Excel 2010. I tried using find() and search() and they work great if the color exists. But if the color doesn't exist, it returns #value - so I get 1 1 #value #value #value instead of 1 1 0 0 0 for, example, Centaur Healer (row 2). The formula used was if(find($A2,C$1) > 0, 1, 0).

    Read the article

  • Converting List<String> to String[] in Java

    - by Christian
    How do I convert a list into an array? The following code returns an error. public static void main(String[] args) { List<String> strlist = new ArrayList<String>(); strlist.add("sdfs1"); strlist.add("sdfs2"); String[] strarray = (String[]) strlist.toArray(); System.out.println(strarray); }

    Read the article

  • i want to return List<DictionaryClass<string,string>> from web service but getting error for IDictio

    - by girish
    [WebMethod] public List<DictionaryClass<string,string>> GetDataByModuleDictionary(string ModuleName) { return BAL_GeneralService.GetDataByModuleDictionary(ModuleName); } here i m getting the following error... The type DictionaryClass`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary.

    Read the article

  • MS SQL Query Sum of subquery

    - by San
    Hello , I need a help i getting following output from the query . SELECT ARG_CONSUMER, cast(ARG_TOTALAMT as float)/100 AS 'Total', (SELECT SUM(cast(DAMT as float))/100 FROM DEBT WHERE DDATE >= ARG.ARG_ORIGDATE AND DDATE <= ARG.ARG_LASTPAYDATE AND DTYPE IN ('CSH','CNTP','DDR','NBP') AND DCONSUMER = ARG.ARG_CONSUMER ) AS 'Paid' FROM ARGMASTER ARG WHERE ARG_STATUS = '1' Current output is a list of all records... But what i want to achieve here is count of arg consumers Total of ARG_TOTALAMT total of that subquery PAID difference between PAID & Total amount. I am able to achieve first two i.e. count of consumers & total of ARG _ TOTALAMT... but i am confused about sum of of ...i.e. sum (SELECT SUM(cast(DAMT as float))/100 FROM DEBT WHERE DDATE >= ARG.ARG_ORIGDATE AND DDATE <= ARG.ARG_LASTPAYDATE AND DTYPE IN ('CSH','CNTP','DDR','NBP') AND DCONSUMER = ARG.ARG_CONSUMER) AS 'Paid' Please advice

    Read the article

  • Best way to split a string by word (SQL Batch separator)

    - by Paul Kohler
    I have a class I use to "split" a string of SQL commands by a batch separator - e.g. "GO" - into a list of SQL commands that are run in turn etc. ... private static IEnumerable<string> SplitByBatchIndecator(string script, string batchIndicator) { string pattern = string.Concat("^\\s*", batchIndicator, "\\s*$"); RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline; foreach (string batch in Regex.Split(script, pattern, options)) { yield return batch.Trim(); } } My current implementation uses a Regex with yield but I am not sure if it's the "best" way. It should be quick It should handle large strings (I have some scripts that are 10mb in size for example) The hardest part (that the above code currently does not do) is to take quoted text into account Currently the following SQL will incorrectly get split: var batch = QueryBatch.Parse(@"-- issue... insert into table (name, desc) values('foo', 'if the go is on a line by itself we have a problem...')"); Assert.That(batch.Queries.Count, Is.EqualTo(1), "This fails for now..."); I have thought about a token based parser that tracks the state of the open closed quotes but am not sure if Regex will do it. Any ideas!?

    Read the article

  • Returning the element number of the longest string in an array

    - by JohnRoberts
    I'm trying to get the longestS method to take the user-inputted array of strings, then return the element number of the longest string in that array. I got it to the point where I was able to return the number of chars in the longest string, but I don't believe that will work for what I need. My problem is that I keep getting incompatible type errors when trying to figure this out. I don't understand the whole data type thing with strings yet. It's confusing me how I go about return a number of the array yet the array is of strings. The main method is fine, I got stuck on the ???? part. { public static void main(String [] args) { Scanner inp = new Scanner( System.in ); String [] responseArr= new String[4]; for (int i=0; i<4; i++) { System.out.println("Enter string "+(i+1)); responseArr[i] = inp.nextLine(); } int highest=longestS(responseArr); } public static int longestS(String[] values) { int largest=0 for( int i = 1; i < values.length; i++ ) { if ( ????? ) } return largest; } }

    Read the article

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