Search Results

Search found 1014 results on 41 pages for 'trim'.

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

  • Execution Plan Optimization when where clause is removed then added back

    - by nmushov
    I have a stored procedure that uses a table valued function which executes in 9 seconds. If I alter the table valued function and remove the where clause, the stored procedure executes in 3 seconds. If I add the where clause back, the query still executes in 3 seconds. I took a look at the execution plans and it appears that after I remove the where clause, the execution plan includes parallelism and the scan count for 2 of my tables drops for 50000 and 65000 down to 5 and 3. After I add the where clause back, the optimized execution plan still runs unless I run DBCC FREEPROCCACHE. Questions 1. Why would SQL Server start using the optimized execution plan for both queries only when I first remove the where clause? Is there a way to force SQL Server to use this execution plan? Also, this is a paramaterized all-in-one query that uses the (Parameter is null or Parameter) in the where clause, which I believe is bad for performance. RETURNS TABLE AS RETURN ( SELECT TOP (@PageNumber * @PageSize) CASE WHEN @SortOrder = 'Expensive' THEN ROW_NUMBER() OVER (ORDER BY SellingPrice DESC) WHEN @SortOrder = 'Inexpensive' THEN ROW_NUMBER() OVER (ORDER BY SellingPrice ASC) WHEN @SortOrder = 'LowMiles' THEN ROW_NUMBER() OVER (ORDER BY Mileage ASC) WHEN @SortOrder = 'HighMiles' THEN ROW_NUMBER() OVER (ORDER BY Mileage DESC) WHEN @SortOrder = 'Closest' THEN ROW_NUMBER() OVER (ORDER BY P1.Distance ASC) WHEN @SortOrder = 'Newest' THEN ROW_NUMBER() OVER (ORDER BY [Year] DESC) WHEN @SortOrder = 'Oldest' THEN ROW_NUMBER() OVER (ORDER BY [Year] ASC) ELSE ROW_NUMBER() OVER (ORDER BY InventoryID ASC) END as rn, P1.InventoryID, P1.SellingPrice, P1.Distance, P1.Mileage, Count(*) OVER () RESULT_COUNT, dimCarStatus.[year] FROM (SELECT InventoryID, SellingPrice, Zip.Distance, Mileage, ColorKey, CarStatusKey, CarKey FROM facInventory JOIN @ZipCodes Zip ON Zip.DealerKey = facInventory.DealerKey) as P1 JOIN dimColor ON dimColor.ColorKey = P1.ColorKey JOIN dimCarStatus ON dimCarStatus.CarStatusKey = P1.CarStatusKey JOIN dimCar ON dimCar.CarKey = P1.CarKey WHERE (@ExteriorColor is NULL OR dimColor.ExteriorColor like @ExteriorColor) AND (@InteriorColor is NULL OR dimColor.InteriorColor like @InteriorColor) AND (@Condition is NULL OR dimCarStatus.Condition like @Condition) AND (@Year is NULL OR dimCarStatus.[Year] like @Year) AND (@Certified is NULL OR dimCarStatus.Certified like @Certified) AND (@Make is NULL OR dimCar.Make like @Make) AND (@ModelCategory is NULL OR dimCar.ModelCategory like @ModelCategory) AND (@Model is NULL OR dimCar.Model like @Model) AND (@Trim is NULL OR dimCar.Trim like @Trim) AND (@BodyType is NULL OR dimCar.BodyType like @BodyType) AND (@VehicleTypeCode is NULL OR dimCar.VehicleTypeCode like @VehicleTypeCode) AND (@MinPrice is NULL OR P1.SellingPrice >= @MinPrice) AND (@MaxPrice is NULL OR P1.SellingPrice < @MaxPrice) AND (@Mileage is NULL OR P1.Mileage < @Mileage) ORDER BY CASE WHEN @SortOrder = 'Expensive' THEN -SellingPrice WHEN @SortOrder = 'Inexpensive' THEN SellingPrice WHEN @SortOrder = 'LowMiles' THEN Mileage WHEN @SortOrder = 'HighMiles' THEN -Mileage WHEN @SortOrder = 'Closest' THEN P1.Distance WHEN @SortOrder = 'Newest' THEN -[YEAR] WHEN @SortOrder = 'Oldest' THEN [YEAR] ELSE InventoryID END )

    Read the article

  • How can I await the first completed async task of a list in .Net?

    - by Eyal
    My input is a long list of files located on an Amazon S3 server. I'd like to download the metadata of the files, compute the hashes of the local files, and compare the metadata hash with the local files' hash. Currently, I use a loop to start all the metadata downloads asynchronously, then as each completes, compute MD5 on the local file if needed and compare. Here's the code (just the relevant lines): Dim s3client As New AmazonS3Client(KeyId.Text, keySecret.Text) Dim responseTasks As New List(Of System.Tuple(Of ListViewItem, Task(Of GetObjectMetadataResponse))) For Each lvi As ListViewItem In lvStatus.Items Dim gomr As New Amazon.S3.Model.GetObjectMetadataRequest gomr.BucketName = S3FileDialog.GetBucketName(lvi.SubItems(2).Text) gomr.Key = S3FileDialog.GetPrefix(lvi.SubItems(2).Text) responseTasks.Add(New System.Tuple(Of ListViewItem, Task(Of GetObjectMetadataResponse))(lvi, s3client.GetObjectMetadataAsync(gomr))) Next For Each t As System.Tuple(Of ListViewItem, Task(Of GetObjectMetadataResponse)) In responseTasks Dim response As GetObjectMetadataResponse = Await t.Item2 If response.ETag.Trim(""""c) = MD5CalcFile(lvi.SubItems(1).Text) Then lvi.SubItems(3).Text = "Match" UpdateLvi(lvi) End If Next I've got two problems: I'm awaiting the reponses in the order that I made them. I'd rather process them in the order that they complete so that I get them faster. The MD5 calculation is long and synchronous. I tried making it async but the process locked up. I think that the MD5 task was added to the end of .Net's task list and it didn't get to run until all the downloads completed. Ideally, I process the response as they arrive, not in order, and the MD5 is asynchronous but gets a chance to run. Edit: Incorporating WhenAll, it looks like this now: Dim s3client As New Amazon.S3.AmazonS3Client(KeyId.Text, keySecret.Text) Dim responseTasks As New Dictionary(Of Task(Of GetObjectMetadataResponse), ListViewItem) For Each lvi As ListViewItem In lvStatus.Items Dim gomr As New Amazon.S3.Model.GetObjectMetadataRequest gomr.BucketName = S3FileDialog.GetBucketName(lvi.SubItems(2).Text) gomr.Key = S3FileDialog.GetPrefix(lvi.SubItems(2).Text) responseTasks.Add(s3client.GetObjectMetadataAsync(gomr), lvi) Next Dim startTime As DateTimeOffset = DateTimeOffset.Now Do While responseTasks.Count > 0 Dim currentTask As Task(Of GetObjectMetadataResponse) = Await Task.WhenAny(responseTasks.Keys) Dim response As GetObjectMetadataResponse = Await currentTask If response.ETag.Trim(""""c) = MD5CalcFile(lvi.SubItems(1).Text) Then lvi.SubItems(3).Text = "Match" UpdateLvi(lvi) End If Loop MsgBox((DateTimeOffset.Now - startTime).ToString) The UI locks up momentarily whenever MDSCalcFile is done. The whole loop takes about 45s and the first file's MD5 result happens within 1s of starting. If I change the line to: If response.ETag.Trim(""""c) = Await Task.Run(Function () MD5CalcFile(lvi.SubItems(1).Text)) Then The UI doesn't lock up when MD5CalcFile is done. The whole loop takes about 75s, up from 45s, and the first file's MD5 result happens after 40s of waiting.

    Read the article

  • CodeIgniter: json_decode array issues

    - by thedp
    On my client side I'm sending an ajax request with jQuery in the following matter: $.post(script.php, { "var1":"something", "var2":"[1,2,3]" }, function(data) { }, "json"); On the server side, in the CodeIgniter's controller I'm receiving the values like so: $var1 = trim($this->input->post('var1')); $var2 = trim($this->input->post('var2')); My question is how do I convert the string in $var2 into a PHP array. I tried using json_decode($var2, true) but it returns a null since "[1,2,3]" is not a legal JSON string by itself. Also, if you believe there is a better way for me to read the values on the server-side please show me how. Thank you.

    Read the article

  • php: remove <p>, </p>, <br> and <br /> from beginning and end of string

    - by andufo
    $chars = " \t\n\r\0\x0B"; $pattern = '('.implode('|',array_map('preg_quote',array('<p>','</p>','<br />','<br>'))).')'."\b"; $data = trim(preg_replace('~'.$pattern.'$~i','',preg_replace('~^'.$pattern.'~i','',trim($data,$chars))),$chars); That code is set to remove all <p>,</p>,<br> and <br /> from the beginning and end of a html string. But it is no working. Any ideas?

    Read the article

  • linq NullReferenceException while checking for null reference

    - by Odrade
    I have the following LINQ query: List<FileInputItem> inputList = GetInputList(); var results = from FileInputItem f in inputList where ( Path.GetDirectoryName(f.Folder).ToLower().Trim() == somePath || Path.GetDirectoryName(f.Folder).ToLower().Trim() == someOtherPath ) && f.Expression == null select f; Every time this query is executed, it generates a NullReferenceException. If I remove the condition f.Expression == null or change it to f.Expression != null, the query executes normally (giving the wrong results, of course). The relevant bits of FileInputItem look like this: [Serializable] public class FileInputItem { [XmlElement("Folder")] public string Folder { get; set; } [XmlElement("Expression")] public string Expression { get; set; } /*SNIP. Irrelevant properties */ } I'm new to LINQ to objects, so I'm probably missing something fundamental here. What's the deal?

    Read the article

  • c# - Object reference not set to an instance of an object.

    - by tom
    Line 30: sUsername.Trim(); Line 31: sPassword.Trim(); Line 32: string ConnectionString = WebConfigurationManager.ConnectionStrings["dbnameConnectionString"].ConnectionString; Line 33: SqlConnection myConnection = new SqlConnection(ConnectionString); Line 34: try Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Any ideas? I don't understand the error.

    Read the article

  • Option Value Changed - ODBC Error 2169

    - by fredrick-ughimi
    Hello Edgar, Thank you for your response. I am using Powerbasic (www.powerbasic.com) as my compiler and SQLTools as a third party tool to access ADS through ODBC. I must stat that this error also appers when I take other actions like Update, Delete, Find, etc. But I don't get this error when I am using MS Access. Here is my save routine: [Code] Local sUsername As String Local sPassword As String Local sStatus As String Local sSQLStatement1 As String sUsername = VD_GetText (nCbHndl, %ID_FRMUPDATEUSERS_TXTUSERNAME) If Trim$(sUsername) = "" Then MsgBox "Please, enter Username", %MB_ICONINFORMATION Or %MB_TASKMODAL, VD_App.Title Control Set Focus nCbHndl, %ID_FRMUPDATEUSERS_TXTUSERNAME Exit Function End If sPassword = VD_GetText (nCbHndl, %ID_FRMUPDATEUSERS_TXTPASSWORD) If Trim$(sPassword) = "" Then MsgBox "Please, enter Password", %MB_ICONINFORMATION Or %MB_TASKMODAL, VD_App.Title Control Set Focus nCbHndl, %ID_FRMUPDATEUSERS_TXTPASSWORD Exit Function End If sStatus = VD_GetText (nCbHndl, %ID_FRMUPDATEUSERS_CBOSTATUS) sSQLStatement1 = "INSERT INTO [tblUsers] (Username, Password, Status) " + _ "VALUES ('" + sUsername + "','" + sPassword + "','" + sStatus +"')" 'Submit the SQL Statement to the database SQL_Stmt %SQL_STMT_IMMEDIATE, sSQLStatement1 'Check for errors If SQL_ErrorPending Then SQL_MsgBox SQL_ErrorQuickAll, %MSGBOX_OK End If [/code] Best regards,

    Read the article

  • PHP form post, automatically mapping to an object (model binding)

    - by Pete Nelson
    I do a lot of ASP.NET MVC 2 development, but I'm tackling a small project at work and it needs to be done in PHP. Is there anything built-in to PHP to do model binding, mapping form post fields to a class? Some of my PHP code currently looks like this: class EntryForm { public $FirstName = ""; public $LastName = ""; } $EntryForm = new EntryForm(); if ($_POST && $_POST["Submit"] == "Submit") { $EntryForm->FirstName = trim($_POST["FirstName"]); $EntryForm->LastName = trim($_POST["LastName"]); } Is there anything built-in to a typical PHP install that would do such mapping like you'd find in ASP.NET MVC, or does it require an additional framework?

    Read the article

  • How can I modify input before model binding in asp.net mvc?

    - by David G
    How can I intercept submitted form input and modify it before it is bound to my model? For example, if I wanted to trim the whitespace from all text. I have tried creating a custom model binder like so: public class CustomBinder : DefaultModelBinder { protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) { string newValue = ((string)value).Trim(); //example code to create new value but could be anything base.SetProperty(controllerContext, bindingContext, propertyDescriptor, newValue); } } but this doesn't seem to be invoked. Is there a better place to modify the input value? Note: I need to modify the value before it is bound and validated.

    Read the article

  • TextBoxWatermarkExtender and Custom validator problem

    - by Mac
    i have two textboxes one for phone and one for email for phone textbox i have used textbox watermark extender and a filtered textbox extender provided in ajax extension toolkit as a water mark extender text iam displaying only numbers are allowed. the problem is that on client side validation of two textboxes by custom validator iam checking function ValidatePhoneEmail(source, args) { var txtEmail = $('#<%= txtEmail.ClientID %'); var txtPhone = $('#<%= txtPhone.ClientID %>'); if (txtEmail.focus().val().trim() != '' || txtPhone.focus().val().trim() != '') { args.isValid = true; } else { args.isValid = false; } } and the problem is phone textbox is not empty as it contains text "Only Numbers" so it always return false what to do..?

    Read the article

  • How can i have different LINQ to XML quries based on two different condition?

    - by Subhen
    Hi , We want the query result should be assigned with two results based on some condition like following: var vAudioData = (from xAudioinfo in xResponse.Descendants(ns + "DIDL-Lite").Elements(ns + "item") if((xAudioinfo.Element(upnp + "artist")!=null) { select new RMSMedia { strAudioTitle = ((string)xAudioinfo.Element(dc + "title")).Trim() }; } else select new RMSMedia { strGen = ((string)xAudioinfo.Element(dc + "Gen")).Trim() }; The VarAudioData should contain both if and else condition values. I have added the if condition just to project , what is my needs, m quite sure though that we can not use if and else. Please help if there are any other approach to accomplish this. Thanks, Subhen

    Read the article

  • Why does my array initialization code cause a StackOverflowException to be thrown?

    - by MCS
    The following line of code in my class constructor is throwing a StackOverflowException: myList = new string[]{}; // myList is a property of type string[] Why is that happening? And what's the proper way to initialize an empty array? UPDATE: The cause was in the set method, in which I was attempting to trim all values. What's wrong with this code: set { for (int i = 0; i < myList.Length; i++) { if (myList[i] != null) myList[i] = myList[i].Trim(); } }

    Read the article

  • Panel is not displaying in JFrame

    - by mallikarjun
    I created a chat panel and added to Jframe but the panel is not displaying. But my sop in the chat panel are displaying in the console. Any one please let me know what could be the problem My Frame public class MyFrame extends JFrame { MyPanel chatClient; String input; public MyFrame() { input = (String)JOptionPane.showInputDialog(null, "Name:", "Connect to chat server", JOptionPane.QUESTION_MESSAGE, null,null, "Test"); input=input.trim(); chatClient = new MyPanel("localhost",input); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(chatClient); } public static void main(String...args){ new MyFrame(); } } MyPanel: public class MyPanel extends JPanel{ ChatClient chatClient; public MyPanel(String host, String uid) { chatClient= new ChatClient(host,uid); add(chatClient.getChatPanel()); this.setVisible(true); } } chat panel: public class ChatClient { Client client; String name; ChatPanel chatPanel; String hostid; public ChatClient(String host,String uid){ client = new Client(); client.start(); System.out.println("in constructor"); Network.register(client); client.addListener(new Listener(){ public void connected(Connection connection){ System.out.println("in client connected method"); Network.RegisterName registerName = new Network.RegisterName(); registerName.name=name; client.sendTCP(registerName); } public void received(Connection connection,Object object){ System.out.println("in client received method"); if (object instanceof Network.UpdateNames) { Network.UpdateNames updateNames = (Network.UpdateNames)object; //chatFrame.setNames(updateNames.names); System.out.println("got it message"); return; } if (object instanceof Network.ChatMessage) { Network.ChatMessage chatMessage = (Network.ChatMessage)object; //chatFrame.addMessage(chatMessage.text); System.out.println("send it message"); return; } } }); // end of listner name=uid.trim(); hostid=host.trim(); chatPanel = new ChatPanel(hostid,name); chatPanel.setSendListener(new Runnable(){ public void run(){ Network.ChatMessage chatMessage = new Network.ChatMessage(); chatMessage.chatMessage=chatPanel.getSendText(); client.sendTCP(chatMessage); } }); new Thread("connect"){ public void run(){ try{ client.connect(5000, hostid,Network.port); }catch(IOException e){ e.printStackTrace(); } } }.start(); }//end of constructor static public class ChatPanel extends JPanel{ CardLayout cardLayout; JList messageList,nameList; JTextField sendText; JButton sendButton; JPanel topPanel,bottomPanel,panel; public ChatPanel(String host,String user){ setSize(600, 200); this.setVisible(true); System.out.println("Chat panel "+host+"user: "+user); { panel = new JPanel(new BorderLayout()); { topPanel = new JPanel(new GridLayout(1,2)); panel.add(topPanel); { topPanel.add(new JScrollPane(messageList=new JList())); messageList.setModel(new DefaultListModel()); } { topPanel.add(new JScrollPane(nameList=new JList())); nameList.setModel(new DefaultListModel()); } DefaultListSelectionModel disableSelections = new DefaultListSelectionModel() { public void setSelectionInterval (int index0, int index1) { } }; messageList.setSelectionModel(disableSelections); nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } { bottomPanel = new JPanel(new GridBagLayout()); panel.add(bottomPanel,BorderLayout.SOUTH); bottomPanel.add(sendText=new JTextField(),new GridBagConstraints(0,0,1,1,1,0,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,0,0),0,0)); bottomPanel.add(sendButton=new JButton(),new GridBagConstraints(1,0,1,1,0,0,GridBagConstraints.CENTER,0,new Insets(0,0,0,0),0,0)); } } sendText.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ sendButton.doClick(); } }); } public void setSendListener (final Runnable listener) { sendButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent evt) { if (getSendText().length() == 0) return; listener.run(); sendText.setText(""); sendText.requestFocus(); } }); } public String getSendText () { return sendText.getText().trim(); } public void setNames (final String[] names) { EventQueue.invokeLater(new Runnable(){ public void run(){ DefaultListModel model = (DefaultListModel)nameList.getModel(); model.removeAllElements(); for(String name:names) model.addElement(name); } }); } public void addMessage (final String message) { EventQueue.invokeLater(new Runnable() { public void run () { DefaultListModel model = (DefaultListModel)messageList.getModel(); model.addElement(message); messageList.ensureIndexIsVisible(model.size() - 1); } }); } } public JPanel getChatPanel(){ return chatPanel; } }

    Read the article

  • having trouble with a mysql query

    - by chuck akers
    this keeps saying Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in directory here the error is near the login_query variable, can someone help me fix it. <?php if (isset($_POST['login_username'], $_POST['login_password'])) { $login_username = trim(mysql_real_escape_string(htmlentities($_POST['login_username']))); $login_password = md5(trim(mysql_real_escape_string(htmlentities($_POST['login_password'])))); if (!empty($login_username) && !empty($login_password)) { $login_query = mysql_query("SELECT user_id FROM username WHERE username='".$login_username."' AND password='".$login_password."'"); if (mysql_num_rows($login_query)==1) { $user_id = mysql_result($login_query, 0, 'user_id'); $_SESSION['user_id'] = $user_id; header('Location: index.php'); die(); } }} ?

    Read the article

  • Trimming a vector of strings

    - by dreamlax
    I have an std::vector of std::strings containing data similar to this: [0] = "" [1] = "Abc" [2] = "Def" [3] = "" [4] = "Ghi" [5] = "" [6] = "" How can I get a vector containing the 4 strings from 1 to 4? (i.e. I want to trim all blank strings from the start and end of the vector): [0] = "Abc" [1] = "Def" [2] = "" [3] = "Ghi" Currently, I am using a forward iterator to make my way up to "Abc" and a reverse iterator to make my way back to "Ghi", and then constructing a new vector using those iterators. This method works, but I want to know if there is an easier way to trim these elements. P.S. I'm a C++ noob. Edit Also, I should mention that the vector may be composed entirely of blank strings, in which case a 0-sized vector would be the desired result.

    Read the article

  • what are the best practices to prevent sql injections

    - by s2xi
    Hi, I have done some research and still confused, This is my outcome of that research. Can someone please comment and advise to how I can make these better or if there is a rock solid implementation already out there I can use? Method 1: array_map('trim', $_GET); array_map('stripslashes', $_GET); array_map('mysql_real_escape_string', $_GET); Method 2: function filter($data) { $data = trim(htmlentities(strip_tags($data))); if (get_magic_quotes_gpc()) $data = stripslashes($data); $data = mysql_real_escape_string($data); return $data; } foreach($_GET as $key => $value) { $data[$key] = filter($value); }

    Read the article

  • Form validation with optional File Upload field callback

    - by MotiveKyle
    I have a form with some input fields and a file upload field in the same form. I am trying to include a callback into the form validation to check for file upload errors. Here is the controller for adding and the callback: public function add() { if ($this->ion_auth->logged_in()): //validate form input $this->form_validation->set_rules('title', 'title', 'trim|required|max_length[66]|min_length[2]'); // link url $this->form_validation->set_rules('link', 'link', 'trim|required|max_length[255]|min_length[2]'); // optional content $this->form_validation->set_rules('content', 'content', 'trim|min_length[2]'); $this->form_validation->set_rules('userfile', 'image', 'callback_validate_upload'); $this->form_validation->set_error_delimiters('<small class="error">', '</small>'); // if form was submitted, process form if ($this->form_validation->run()) { // add pin $pin_id = $this->pin_model->create(); $slug = strtolower(url_title($this->input->post('title'), TRUE)); // path to pin folder $file_path = './uploads/' . $pin_id . '/'; // if folder doesn't exist, create it if (!is_dir($file_path)) { mkdir($file_path); } // file upload config variables $config['upload_path'] = $file_path; $config['allowed_types'] = 'jpg|png'; $config['max_size'] = '2048'; $config['max_width'] = '1920'; $config['max_height'] = '1080'; $config['encrypt_name'] = TRUE; $this->load->library('upload', $config); // upload image file if ($this->upload->do_upload()) { $this->load->model('file_model'); $image_id = $this->file_model->insert_image_to_db($pin_id); $this->file_model->add_image_id_to_pin($pin_id, $image_id); } } // build page else: // User not logged in redirect("login", 'refresh'); endif; } The callback: function validate_upload() { if ($_FILES AND $_FILES['userfile']['name']): if ($this->upload->do_upload()): return true; else: $this->form_validation->set_message('validate_upload', $this->upload->display_errors()); return false; endif; else: return true; endif; } I am getting the error Fatal error: Call to a member function do_upload() on a non-object on line 92 when I try to run this. Line 92 is the if ($this->upload->do_upload()): line in the validate_upload callback. Am I going about this the right way? What's triggering this error?

    Read the article

  • Using module include in OCaml

    - by Geoff
    In OCaml 3.11, I want to "extend" an existing module using the include directive, like so: module MyString = struct include String let trim s = ... end No problem. But now I want to expose this module's type explicitly (i.e. in a .mli file). I want something like this: module MyString : sig include String val trim : string -> string end But the include syntax is not correct because String refers to a module, not a module type (and the compiler does indeed barf). How can I refer to the module type for String here (without having write it out explicitly in a sig expression)? Thanks!

    Read the article

  • How can I clear the Android app cache?

    - by Srao
    I am writing a app which can programatically clear application cache of all the third party apps installed on the device. Following is the code snippet for Android 2.2 public static void trimCache(Context myAppctx) { Context context = myAppctx.createPackageContext("com.thirdparty.game", Context.CONTEXT_INCLUDE_CO|Context.CONTEXT_IGNORE_SECURITY); File cachDir = context.getCacheDir(); Log.v("Trim", "dir " + cachDir.getPath()); if (cachDir!= null && cachDir.isDirectory()) { Log.v("Trim", "can read " + cachDir.canRead()); String[] fileNames = cachDir.list(); //Iterate for the fileName and delete } } My manifest has following permissions: android.permission.CLEAR_APP_CACHE android.permission.DELETE_CACHE_FILES Now the problem is that the name of the cache directory is printed but the list of files cachDir.list() always returns null. I am not able to delete the cache directory since the file list is always null. Is there any other way to clear the application cache?

    Read the article

  • PHP - Can you help change this function slightly?

    - by Joe
    I have the following function I modified based off someone elses function: function showCombinations($string, $nameString, $linkParts, $i){ $wordDivider = "/"; //the divider between the words/values if ($i >= count($linkParts)){ echo "<a href='".trim($string)."'>".trim($nameString)."</a>, "; } else { foreach ($linkParts[$i] as $currentTrait){ if ($currentTrait['name']=="urltext"){ $currentNameStringName=""; //ignore } else { $currentNameStringName=$currentTrait['name']; } if ($nameString!=""){ $currentNameString=$nameString." - ".$currentNameStringName; } else { $currentNameString=$nameString.$currentNameStringName; } showCombinations($string.$currentTrait['value'].$wordDivider, $currentNameString, $linkParts, $i + 1); } } } showCombinations('', '', $linkParts, 0); All I need to change this to do is, instead of "ECHO", I want it to build up the combination and so I can do: $result = showCombinations('', '', $linkParts, 0); echo $result; I need it this way because I have to modify that $result, not just echo it.

    Read the article

  • Writing an optimised and efficient search engine with mySQL and ColdFusion

    - by Mel
    I have a search page with the following scenarios listed below. I was told there was a better way to do it, but not how, and that I am using too many if statements, and that it's prone to causing an error through url manipulation: Search.cfm will processes a search made from a search bar present on all pages, with one search input (titleName). If search.cfm is accessed manually (through URL not through using the simple search bar on all pages) it displays an advanced search form with three inputs (titleName, genreID, platformID) or it evaluates searchResponse variable and decides what to do. If simple search query is blank, has no results, or less than 3 characters it displays an error If advanced search query is blank, has no results, or less than 3 characters it displays an error If any successful search returns results, they come back normally. The top-of-page logic is as follows: <!---SET DEFAULT VARIABLE---> <cfparam name="variables.searchResponse" default=""> <!---CHECK TO SEE IF SIMPLE SEARCH A FORM WAS SUBMITTED AND EXECUTE SEARCH IF IT WAS---> <cfif IsDefined("Form.simpleSearch") AND Len(Trim(Form.titleName)) LTE 2> <cfset variables.searchResponse = "invalidString"> <cfelseif IsDefined("Form.simpleSearch") AND Len(Trim(Form.titleName)) GTE 3> <!---EXECUTE METHOD AND GET DATA---> <cfinvoke component="myComponent" method="simpleSearch" searchString="#Form.titleName#" returnvariable="simpleSearchResult"> <cfset variables.searchResponse = "simpleSearchResult"> </cfif> <!---CHECK IF ANY RECORDS WERE FOUND---> <cfif IsDefined("variables.simpleSearchResult") AND simpleSearchResult.RecordCount IS 0> <cfset variables.searchResponse = "noResult"> </cfif> <!---CHECK IF ADVANCED SEARCH FORM WAS SUBMITTED---> <cfif IsDefined("Form.AdvancedSearch") AND Len(Trim(Form.titleName)) LTE 2> <cfset variables.searchResponse = "invalidString"> <cfelseif IsDefined("Form.advancedSearch") AND Len(Trim(Form.titleName)) GTE 2> <!---EXECUTE METHOD AND GET DATA---> <cfinvoke component="myComponent" method="advancedSearch" returnvariable="advancedSearchResult" titleName="#Form.titleName#" genreID="#Form.genreID#" platformID="#Form.platformID#"> <cfset variables.searchResponse = "advancedSearchResult"> </cfif> <!---CHECK IF ANY RECORDS WERE FOUND---> <cfif IsDefined("variables.advancedSearchResult") AND advancedSearchResult.RecordCount IS 0> <cfset variables.searchResponse = "noResult"> </cfif> I'm using the searchResponse variable to decide what the the page displays, based on the following scenarios: <!---ALWAYS DISPLAY SIMPLE SEARCH BAR AS IT'S PART OF THE HEADER---> <form name="simpleSearch" action="search.cfm" method="post"> <input type="hidden" name="simpleSearch" /> <input type="text" name="titleName" /> <input type="button" value="Search" onclick="form.submit()" /> </form> <!---IF NO SEARCH WAS SUBMITTED DISPLAY DEFAULT FORM---> <cfif searchResponse IS ""> <h1>Advanced Search</h1> <!---DISPLAY FORM---> <form name="advancedSearch" action="search.cfm" method="post"> <input type="hidden" name="advancedSearch" /> <input type="text" name="titleName" /> <input type="text" name="genreID" /> <input type="text" name="platformID" /> <input type="button" value="Search" onclick="form.submit()" /> </form> </cfif> <!---IF SEARCH IS BLANK OR LESS THAN 3 CHARACTERS DISPLAY ERROR MESSAGE---> <cfif searchResponse IS "invalidString"> <cfoutput> <h1>INVALID SEARCH</h1> </cfoutput> </cfif> <!---IF SEARCH WAS MADE BUT NO RESULTS WERE FOUND---> <cfif searchResponse IS "noResult"> <cfoutput> <h1>NO RESULT FOUND</h1> </cfoutput> </cfif> <!---IF SIMPLE SEARCH WAS MADE A RESULT WAS FOUND---> <cfif searchResponse IS "simpleSearchResult"> <cfoutput> <h1>Search Results</h1> </cfoutput> <cfoutput query="simpleSearchResult"> <!---DISPLAY QUERY DATA---> </cfoutput> </cfif> <!---IF ADVANCED SEARCH WAS MADE A RESULT WAS FOUND---> <cfif searchResponse IS "advancedSearchResult"> <cfoutput> <h1>Search Results</h1> <p>Your search for "#Form.titleName#" returned #advancedSearchResult.RecordCount# result(s).</p> </cfoutput> <cfoutput query="advancedSearchResult"> <!---DISPLAY QUERY DATA---> </cfoutput> </cfif> Is my logic a) not efficient because my if statements/is there a better way to do this? And b) Can you see any scenarios where my code can break? I've tested it but I have not been able to find any issues with it. And I have no way of measuring performance. Any thoughts and ideas would be greatly appreciated. Many thanks

    Read the article

  • Write file at a specific value and line

    - by user2828891
    I want to write data at a specified value in a text file from a text box. Here is a example: item_begin etcitem 3344 item_type=etcitem is first line and item_begin weapon 3343 item_type=weapon is second. Well i want to replace item_type=weapon at second line with item_type=armor. Here is code so far: var data2 = File.WriteAllLines("itemdata.txt") .Where(x => x.Contains("3343")) .Take(1) .SelectMany(x => x.Split('\t')) .Select(x => x.Split('=')) .Where(x => x.Length > 1) .ToDictionary(x => x[0].Trim(), x => x[1]); But returns error at WriteAllLines. Here is the readline part code: var data = File.ReadLines("itemdata.txt") .Where(x => x.Contains("3343")) .Take(1) .SelectMany(x => x.Split('\t')) .Select(x => x.Split('=')) .Where(x => x.Length > 1) .ToDictionary(x => x[0].Trim(), x => x[1]); //call values textitem_type.Text = data["item_type"]; And want to write the same value I change on textitem_type.Text after read. I used this to reaplace but replaces all values with same name from line and returns me in text only 1 line. Code: private void button2_Click(object sender, EventArgs e) { var data = File .ReadLines("itemdata.txt") .Where(x => x.Contains(itemSrchtxt.Text)) .Take(1) .SelectMany(x => x.Split('\t')) .Select(x => x.Split('=')) .Where(x => x.Length > 1) .ToDictionary(x => x[0].Trim(), x => x[1]); StreamReader reader = new StreamReader(Directory.GetCurrentDirectory() + @"\itemdata.txt"); string content = reader.ReadLine(); reader.Close(); content = Regex.Replace(content, data["item_type"], textitem_type.Text); StreamWriter write = new StreamWriter(Directory.GetCurrentDirectory() + @"\itemdata.txt"); write.WriteLine(content); write.Close(); }

    Read the article

  • result set using two different views (from an if statement)

    - by mailman1979
    Hi All, I have a bit of code that works with a result set called "result" (original I know) but depending on the incoming variable I'd like to fire the specific query depending. I have the below in an if statement but that just makes the "result" recordset gets those nasty red lines and it doesn't work. I'm sure this is easy to work out. if (area == "dashboard") { IQueryable<ViewGetNavigationMainItem> result = (from m in _entities.ViewGetNavigationMainItems where m.area.Trim() == area.Trim() where m.state == "Online" where m.parentID == parentID orderby m.sequence ascending select m); } else { //Get the Content Items IQueryable<ViewGetNavigationContentItem> result = (from m in _entities.ViewGetNavigationContentItems where m.navID == navID where m.parentID == parentID orderby m.contentOrder ascending select m); } maxRecords = result.Count(); foreach (var item in result) { etc etc etc

    Read the article

  • Given a document select a relevant snippet.

    - by BCS
    When I ask a question here, the tool tips for the question returned by the auto search given the first little bit of the question, but a decent percentage of them don't give any text that is any more useful for understanding the question than the title. Does anyone have an idea about how to make a filter to trim out useless bits of a question? My first idea is to trim any leading sentences that contain only words in some list (for instance, stop words, plus words from the title, plus words from the SO corpus that have very weak correlation with tags, that is that are equally likely to occur in any question regardless of it's tags)

    Read the article

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