Search Results

Search found 13450 results on 538 pages for 'recent items'.

Page 87/538 | < Previous Page | 83 84 85 86 87 88 89 90 91 92 93 94  | Next Page >

  • Limit CPU usage of a process

    - by jb
    I have a service running which periodically checks a folder for a file and then processes it. (Reads it, extracts the data, stores it in sql) So I ran it on a test box and it took a little longer thaan expected. The file had 1.6 million rows, and it was still running after 6 hours (then I went home). The problem is the box it is running on is now absolutely crippled - remote desktop was timing out so I cant even get on it to stop the process, or attach a debugger to see how far through etc. It's solidly using 90%+ CPU, and all other running services or apps are suffering. The code is (from memory, may not compile): List<ItemDTO> items = new List<ItemDTO>(); using (StreamReader sr = fileInfo.OpenText()) { while (!sr.EndOfFile) { string line = sr.ReadLine() try { string s = line.Substring(0,8); double y = Double.Parse(line.Substring(8,7)); //If the item isnt already in the collection, add it. if (items.Find(delegate(ItemDTO i) { return (i.Item == s); }) == null) items.Add(new ItemDTO(s,y)); } catch { /*Crash*/ } } return items; } - So I am working on improving the code (any tips appreciated). But it still could be a slow affair, which is fine, I've no problems with it taking a long time as long as its not killing my server. So what I want from you fine people is: 1) Is my code hideously un-optimized? 2) Can I limit the amount of CPU my code block may use? Cheers all

    Read the article

  • How to optimize shopping carts for minimal prices?

    - by tangens
    I have a list of items I want to buy. The items are offered by different shops and different prices. The shops have individual delivery costs. I'm looking for an optimal shopping strategy (and a java library supporting it) to purchase all of the items with a minimal total price. Example: Item1 is offered at Shop1 for $100, at Shop2 for $111. Item2 is offered at Shop1 for $90, at Shop2 for $85. Delivery cost of Shop1: $10 if total order < $150; $0 otherwise Delivery cost of Shop2: $5 if total order < $50; $0 otherwise If I buy Item1 and Item2 at Shop1 the total cost is $100 + $90 +$0 = $190. If I buy Item1 and Item2 at Shop2 the total cost is $111 + $85 +$0 = $196. If I buy Item1 at Shop1 and Item2 at Shop2 the total cost is $100 + $10 + $85 + $0 = 195. I get the minimal price if I order Item1 at Shop1 and Item2 at Shop2: $195 Question I need some hints which algorithms may help me to solve optimization problems of this kind for number of items about 100 and number of shops about 20. I already looked at apache-math and its optimization package, but I have no idea what algorithm to look for.

    Read the article

  • IE AJAX/Jquery issue - redirecting to new page instead of loading it into a div

    - by phx-zs
    I have a page like this: <form class="ajax" method="post" action="add_item.php"> [text input] [submit button] </form> [list any items the user has in a div here called #items] When the user clicks the submit button, a function like this is called: $("form.ajax").live('submit', function(event) { params = $(this).serialize(); $.post($(this).attr("action"), params, function(data){ json = $.parseJSON(data); // do stuff based on the json results if(json.success.action == 'replace'){ $(json.success.container).html(json.success.message); } else{ $(json.success.container).prepend(json.success.message); $(json.success.container).find(".item:first").slideDown(); } }); event.returnValue = false; return false; }); This is supposed to load add_item.php into the #items div, and it works fine in FF, Chrome, Safari, just not IE. In IE (tested 7 and 8) when I click Submit it redirects the page to add_item.php rather than loading it into the #items div. I tried adding event.preventDefault(); to the end of the function but that didn't work. Any ideas?

    Read the article

  • MySQL managing catalogue views

    - by Mark Lawrence
    A friend of mine has a catalogue that currently holds about 500 rows or 500 items. We are looking at ways that we can provide reports on the catalogue inclduing the number of times an item was viewed, and dates for when its viewed. His site is averaging around 25,000 page impressions per month and if we assumed for a minute that half of these were catalogue items then we'd assume roughly 12,000 catalogue items viewed each month. My question is the best way to manage item views in the database. First option is to insert the catalogue ID into a table and then increment the number of times its viewed. The advantage of this is its compact nature. There will only ever be as many rows in the table as there are catalogue items. `catalogue_id`, `views` The disadvantage is that no date information is being held, short of maintaining the last time an item was viewed. The second option is to insert a new row each time an item is viewed. `catalogue_id`, `timestamp` If we continue with the assumed figure of 12,000 item views that means adding 12,000 rows to the table each month, or 144,000 rows each year. The advantage of this is we know the number of times the item is viewed, and also the dates for when its viewed. The disadvantage is the size of the table. Is a table with 144,000 rows becoming too large for MySQL? Interested to hear any thoughts or suggestions on how to achieve this. Thanks.

    Read the article

  • Array to Array pushing in Zend Session object

    - by kate-koopy
    Hello! I have some example of pushing array to array in session object: class someClass extends someOtherOne { ...////// some other code here that starts session and creates namespace public function __add2Session($a,$b) { $namespc = $this -> __getnewNameSpace(); //returns a Zend Session Namesapce (object) if (!isset($namespc -> {$a})) { $namespc -> {$a} = array(); } array_push($namespc -> {$a}, $b); } } ...///////////// $item=array(1=>"one",2=>"two",3=>"three",4=>"four",5=>"five",6=>"six",7=>"seven"); $k = new someClass(); $cart = new Zend_Session_Namespace('Cart'); $k -> __add2Session("items",$item); The result is when I reload the page several times - the value of $cart -> items in the session gets overwritten and not populated. Can somebody explain why it occurs and how do I fix this? I want to have $cart -> items to be an "array in array" like: $cart -> items = array(array(1=>"one",2=>"two"), array(1=>"two",2=>"three"));

    Read the article

  • Cross Thread problem C#

    - by Frederik Witte
    Hello people - I got this code (lg_log is a listbox, and i want it to log the start_server.bat) Here is the code i got: public void bt_play_Click(object sender, EventArgs e) { lg_log.Items.Add("Starting Mineme server .."); string directory = Directory.GetCurrentDirectory(); var info = new ProcessStartInfo(directory + @"\start_base.bat") {UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true, WorkingDirectory = directory + @"\Servers\Base"}; var proc = new Process { StartInfo = info, EnableRaisingEvents = true }; proc.OutputDataReceived += (obj, args) => { if (args.Data != null) { lg_log.Items.Add(args.Data); } }; proc.Start(); proc.BeginOutputReadLine(); lg_log.Items.Add("Server is now running!"); proc.WaitForExit(); } When i run this, i'll get an error .. Anybody can help me? I'll rate the answer up! :D Edit: The error i get is this: System.InvalidOperationException Hope it helps :) The error comes at the lg_log.Items.Add(args.Data); code line

    Read the article

  • Unknown ListView Behavior

    - by st0le
    I'm currently making a SMS Application in Android, the following is a code snippet from Inbox Listactivity, I have requested a cursor from the contentresolver and used a custom adapter to add custom views into the list. Now, in the custom view i've got 2 TextViews (tvFullBody,*tvBody*)... tvFullBody contains the Full SMS Text while tvBody contains a short preview (35 characters) The tvFullBody Visibility is by default set to GONE. My idea is, when the user clicks on a list item, the tvBody should dissappear(GONE) and the tvFullBody should become visible (VISIBLE). On Clicking again, it should revert back to its original state. //isExpanded is a BitSet of the size = no of list items...keeps track of which items are expanded and which are not @Override protected void onListItemClick(ListView l, View v, int position, long id) { if(isExpanded.get(position)) { v.findViewById(R.id.tvFullBody).setVisibility(View.GONE); v.findViewById(R.id.tvBody).setVisibility(View.VISIBLE); }else { v.findViewById(R.id.tvFullBody).setVisibility(View.VISIBLE); v.findViewById(R.id.tvBody).setVisibility(View.GONE); } isExpanded.flip(position); super.onListItemClick(l, v, position, id); } The Code works as it is supposed to :) except for an undesired sideeffect.... Every 10th (or so) List Item also gets "toggled". eg. If i Expand the 1st, then the 11th, 21th list items are also expanded...Although they remain off screen, but on scrolling you get to see the undesired "expansion". By my novice analysis, i'm guessing Listview keeps track of 10 list items that are currently visible, upon scrolling, it "reuses" those same variables, which is causing this problem...(i didn't check the android source code yet.) I'd be gratefull for any suggestion, on how i should tackle this! :) I'm open to alternative methods aswell....Thanks in advance! :)

    Read the article

  • SQL left join with multiple rows into one row

    - by beardedd
    Basically, I have two tables, Table A contains the actual items that I care to get out, and Table B is used for language translations. So, for example, Table A contains the actual content. Anytime text is used within the table, instead of storing actual varchar values, ids are stored that relate back to text stored in Table B. This allows me to by adding a languageID column to Table B, have multiple translations for the same row in the database. Example: Table A Title (int) Description (int) Other Data.... Table B TextID (int) - This is the column whose value is stored in other tables LanguageID (int) Text (varchar) My question is more a call for suggestions on how to best handle this. Ideally I want a query that I can use to select from the table, and get the text as opposed to the ids of the text out of the table. Currently when I have two text items in the table this is what I do: SELECT C.ID, C.Title, D.Text AS Description FROM (SELECT A.ID, A.Description, B.Text AS Title FROM TableA A, TranslationsTable B WHERE A.Title = B.TextID AND B.LanguaugeID = 1) C LEFT JOIN TranslationsTable D ON C.Description = D.TextID AND D.LanguaugeID = 1 This query gives me the row from Table A I am looking for (using where statements in the inner select statement) with the actual text based on the language ID used instead of the text ids. This works fine when I am only using one or two text items that need to be translated, but adding a third item or more, it starts to get really messy - essentially another left join on top of the example. Any suggestions on a better query, or at least a good way to handle 3 or more text items in a single row?

    Read the article

  • Programmatically Update UITableView in Response to Button Press

    - by Kyle Begeman
    I have a completely custom view that holds a UITableView and a Custom Tab Bar (basically a UIView that contains 6 UIButtons). I am loading data from a plist file, and then I am sorting the data into multiple arrays based on categories (an array for misc items, and array for mail items, etc.) Each button in the tab bar represents a category, and when I press the button I call the custom function "miscSelected" and so on. How can I have the table view completely reload and then display the tableview based on the array selected (select the misc category and the tableview clears itself and loads the misc array data, same for any other category)? The method I have experimented with is created and NSString named "selection" and then in each button function I set selected to equal whatever section I am selecting. In my cellForRoxAtIndexPath method I have this: if ([self.selection isEqualToString:@"All Items"]) { NSArray *mainDataArray = [NSArray arrayWithContentsOfFile:self.plistFile]; NSSortDescriptor *brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:brandDescriptor]; self.sortedData = [mainDataArray sortedArrayUsingDescriptors:sortDescriptors]; } else if ([self.selection isEqualToString:@"Misc Items"]){ self.sortedData = [NSArray arrayWithContentsOfFile:self.plistFile]; } cell.itemTitle.text = [[self.sortedData objectAtIndex:indexPath.row] objectForKey:@"name"]; For the sake of example and testing I am simply displaying the same data, just one button displays it in alphabetical order and the other does not. This code works only when I start to scroll down and back up, but it does not actually update on button press. Calling myTable reloadData does not do anything either. Any help would be great, thanks!

    Read the article

  • html/js: Refresh 'Select' options

    - by framara
    Hi, There's a class 'Car' with brand and model as properties. I have a list of items of this class List<Car> myCars. I need to represent in a JSP website 2 ComboBox, one for brand and another for model, that when you select the brand, in the model list only appear the ones from that brand. I don't know how to do this in a dynamic way. Any suggestion where to start? Thanks Update Ok, what I do now is send in the request a list with all the brand names, and a list of the items. The JSP code is like: <select name="manufacturer" id="id_manufacturer" onchange="return getManufacturer();"> <option value=""></option> <c:forEach items="${manufacturers}" var="man"> <option value="${man}" >${man}</option> </c:forEach> </select> <select name="model" id="id_model"> <c:forEach items="${mycars}" var="car"> <c:if test="${car.manufacturer eq man_selected}"> <option value="${car.id}">${car.model}</option> </c:if> </c:forEach> </select> <script> function getManufacturer() { man_selected = document.getElementById('id_manufacturer').value; } </script> How do I do to refresh the 'model' select options according to the selected 'man_selected' ?

    Read the article

  • Listening Port Permanently. if file is on my stream, Get file. How to?

    - by Phsika
    i writed 2 client and server program. client dend file also server listen port and than get file.But i need My server App must listen on 51124 port permanently. if any file on my stream, show my message "there is a file on your stream" and than show me savefile dialog. But my server app in "Infinite loop". 1) listen 51124 port every time 2) do i have a file on my stream, show me a messagebox. private void Form1_Load(object sender, EventArgs e) { TcpListener Dinle = new TcpListener(51124); try { Dinle.Start(); Socket Baglanti = Dinle.AcceptSocket(); if (!Baglanti.Connected) { MessageBox.Show("No Connection!"); } else { while (true) { byte[] Dizi = new byte[250000]; Baglanti.Receive(Dizi, Dizi.Length, 0); string Yol; saveFileDialog1.Title = "Save File"; saveFileDialog1.ShowDialog(); Yol = saveFileDialog1.FileName; FileStream Dosya = new FileStream(Yol, FileMode.Create); Dosya.Write(Dizi, 0, Dizi.Length - 20); Dosya.Close(); listBox1.Items.Add("dosya indirildi"); listBox1.Items.Add("Dosya Boyutu=" + Dizi.Length.ToString()); listBox1.Items.Add("Indirilme Tarihi=" + DateTime.Now); listBox1.Items.Add("--------------------------------"); } } } catch (Exception) { throw; } } My Algorithm: if(AnyFileonStream()==true) { GetFile() //Also continue to listening 51124 port... } How can i do that?

    Read the article

  • Extensions methods and forward compatibilty of source code.

    - by TcKs
    Hi, I would like solve the problem (now hypothetical but propably real in future) of using extension methods and maginification of class interface in future development. Example: /* the code written in 17. March 2010 */ public class MySpecialList : IList<MySpecialClass> { // ... implementation } // ... somewhere elsewhere ... MySpecialList list = GetMySpecialList(); // returns list of special classes var reversedList = list.Reverse().ToList(); // .Reverse() is extension method /* now the "list" is unchanged and "reveresedList" has same items in reversed order */ /* --- in future the interface of MySpecialList will be changed because of reason XYZ*/ /* the code written in some future */ public class MySpecialList : IList<MySpecialClass> { // ... implementation public MySpecialList Reverse() { // reverse order of items in this collection return this; } } // ... somewhere elsewhere ... MySpecialList list = GetMySpecialList(); // returns list of special classes var reversedList = list.Reverse().ToList(); // .Reverse() was extension method but now is instance method and do something else ! /* now the "list" is reversed order of items and "reveresedList" has same items lake in "list" */ My question is: Is there some way how to prevent this case (I didn't find them)? If is now way how to prevent it, is there some way how to find possible issues like this? If is now way how to find possible issues, should I forbid usage of extension methods? Thanks.

    Read the article

  • Getting the current item number or index when using will_paginate in rails app

    - by Rich
    I have a rails app that stores movies watched, books read, etc. The index page for each type lists paged collections of all its items, using will_paginate to bring back 50 items per page. When I output the items I want to display a number to indicate what item in the total collection it is. The numbering should be reversed as the collection is displayed with most recent first. This might not relate to will_paginate but rather some other method of calculation. I will be using the same ordering in multiple types so it will need to be reusable. As an example, say I have 51 movies. The first item of the first page should display: Fight Club - Watched: 30th Dec 2010 Whilst the last item on the page should display: The Matrix - Watched: 3rd Jan 2010 The paged collection is available as an instance variable e.g. @movies, and @movies.count will display the number of items in the paged collection. So if we're on page 1, movies.count == 50, whilst on page 2 @movies.count == 1. Using Movie.count would give 51. If the page number and page size can be accessed the number could be calculated so how can they be returned? Though I'm hopeful there is something that already exists to handle this calculation!

    Read the article

  • c# How to implement a collection of generics

    - by Amy
    I have a worker class that does stuff with a collection of objects. I need each of those objects to have two properties, one has an unknown type and one has to be a number. I wanted to use an interface so that I could have multiple item classes that allowed for other properties but were forced to have the PropA and PropB that the worker class requires. This is the code I have so far, which seemed to be OK until I tried to use it. A list of MyItem is not allowed to be passed as a list of IItem even though MyItem implements IItem. This is where I got confused. Also, if possible, it would be great if when instantiating the worker class I don't need to pass in the T, instead it would know what T is based on the type of PropA. Can someone help get me sorted out? Thanks! public interface IItem<T> { T PropA { get; set; } decimal PropB { get; set; } } public class MyItem : IItem<string> { public string PropA { get; set; } public decimal PropB { get; set; } } public class WorkerClass<T> { private List<T> _list; public WorkerClass(IEnumerable<IItem<T>> items) { doStuff(items); } public T ReturnAnItem() { return _list[0]; } private void doStuff(IEnumerable<IItem<T>> items) { foreach (IItem<T> item in items) { _list.Add(item.PropA); } } } public void usage() { IEnumerable<MyItem> list= GetItems(); var worker = new WorkerClass<string>(list);//Not Allowed }

    Read the article

  • Why can't I pass an object of type T to a method on an object of type <? extends T>?

    - by Matt
    In Java, assume I have the following class Container that contains a list of class Items: public class Container<T> { private List<Item<? extends T>> items; private T value; public Container(T value) { this.value = value; } public void addItem(Item item) { items.add(item); } public void doActions() { for (Item item : items) { item.doAction(value); } } } public abstract class Item<T> { public abstract void doAction(T item); } Eclipse gives the error: The method doAction(capture#1-of ? extends T) in the type Item is not applicable for the arguments (T) I've been reading generics examples and various postings around, but I still can't figure out why this isn't allowed. Eclipse also doesn't give any helpful tips in its proposed fix, either. The variable value is of type T, why wouldn't it be applicable for ? extends T?.

    Read the article

  • Scroll to item in listview in Silverlight 3.

    - by the empirical programmer
    I have a silverlight 3 app with a textbox on the main window and a childwindow that has a list of all the potential textbox values. When I open that childwindow I want it to scroll to the correct one in the list. I'm trying to do this with the code below...using the ScrollIntoView. It was not working at all until I add the UpdateLayerout(). However it does not seem to work all the time. At times it scrolls but not all the way to the item, it is a few items higher than it should be. The listbox is in an Accordion and the list items use a ItemTemplate\DataTemplate, not sure if that effects anything but thought I'd mention it. Any ideas what I'm missing in the code below? What I would like is to scroll the item to the top of the list ....any ideas how to that? (Or any other suggestions on how to code this better) Thanks! for (int index = 0; index < myList.Items.Count; index++) { object obj = myList.Items[index]; var listItem= obj as listItemObject; if (listItemObj != null) { if (string.Compare(listItemObj.id, _PastedInId, StringComparison.InvariantCultureIgnoreCase) == 0) { selectThisIndex = index; scrollToThisItem = obj; } } } myList.SelectedIndex = selectThisIndex; if (scrollToThisItem != null){ myList.UpdateLayout(); myList.ScrollIntoView(scrollToThisItem); }

    Read the article

  • Trouble defining method for Javascript class definition.

    - by btoverdrive
    I'm somewhat new to object oriented programming in Javascript and I'm trying to build a handler object and library for a list of items I get back from an API call. Ideally, I'd like the library functions to be members of the handler class. I'm having trouble getting my class method to work however. I defined as part of the class bcObject the method getModifiedDateTime, but when I try to echo the result of the objects call to this method, I get this error: Error on line 44 position 26: Expected ';' this.getModifiedDateTime: function(epochtime) { which leads me to believe that I simply have a syntax issue with my method definition but I can't figure out where. response( { "items": [ {"id":711,"name":"Shuttle","lastModifiedDate":"1268426336727"}, {"id":754,"name":"Formula1","lastModifiedDate":"1270121717721"} ], "extraListItemsAttr1":"blah", "extraListItemsAttr2":"blah2" }); function response(MyObject) { bcObject = new bcObject(MyObject); thing = bcObject.getModifiedDateTime(bcObject.videoItem[0].lastModifiedDate); SOSE.Echo(thing); } function bcObject(listObject) { // define class members this.responseList = {}; this.videoCount = 0; this.videoItem = []; this.responseListError = ""; // instantiate members this.responseList = listObject; this.videoCount = listObject.items.length; // populate videoItem array for (i=0;i<this.videoCount;i++) { this.videoItem[i] = listObject.items[i]; } this.getModifiedDateTime: function(epochtime) { var dateStringOutput = ""; var myDate = new Date(epochtime); dateStringOutput = myDate.toLocaleString(); return dateStringOutput; }; }

    Read the article

  • EventKitUI view and edit problem!

    - by Alish
    I try to to find a solution to do View and Edit of a the item from a tablview. My application base on UITabBarController. Each of the Bar items contain a class with a a couple of UIViews. This is the first items of UITabBarController. I done Add event from Apple sample code: SimpleEKDemo. Add Event working without any problem. I tried to add View and Edit part to the code. I would able to select an items from tableView to edit the selected item. But after I tried to add code from SimpleEKDemo to my code, I realized I have to add UINavigationController to the implement. So I did. After I add that it's came to the items of UITabBarController. Also I even the Add Event didn't worked very well (I couldn't insert event name and location. but edit was working. So I need to know: 1- Is it possible to implement Edit/View without using UINavigationController. If yes please let me know a sample code. 2- If I must use UINavigationController. Because I don't need UINavigationController to become it the first page and I don't need any bar added to my application. Is it possible it's appear in the application when I choose a item of tableView but appear alike that! Snapshots: https://public.me.com/alish (pict.zip)

    Read the article

  • How do I implement IEnumerable?

    - by Stacey
    I have a class that contains a static number of objects. This class needs to be frequently 'compared' to other classes that will be simple List objects. public partial class Sheet { public Item X{ get; set; } public Item Y{ get; set; } public Item Z{ get; set; } } the items are obviously not going to be "X" "Y" "Z", those are just generic names for example. The problem is that due to the nature of what needs to be done, a List won't work; even though everything in here is going to be of type Item. It is like a checklist of very specific things that has to be tested against in both code and runtime. This works all fine and well; it isn't my issue. My issue is iterating it. For instance I want to do the following... List<Item> UncheckedItems = // Repository Logic Here. UncheckedItems contains all available items; and the CheckedItems is the Sheet class instance. CheckedItems will contain items that were moved from Unchecked to Checked; however due to the nature of the storage system, items moved to Checked CANNOT be REMOVED from Unchecked. I simply want to iterate through "Checked" and remove anything from the list in Unchecked that is already in "Checked". So naturally, that would go like this with a normal list. foreach(Item item in Unchecked) { if( Checked.Contains(item) ) Unchecked.Remove( item ); } But since "Sheet" is not a 'List', I cannot do that. So I wanted to implement IEnumerable so that I could. Any suggestions? I've never implemented IEnumerable directly before and I'm pretty confused as to where to begin.

    Read the article

  • CakePHP pagination with HABTM models

    - by nickf
    I'm having some problems with creating pagination with a HABTM relationship. First, the tables and relationships: requests (id, to_location_id, from_location_id) locations (id, name) items_locations (id, item_id, location_id) items (id, name) So, a Request has a Location the request is coming from and a Location the Request is going to. For this question, I'm only concerned about the "to" location. Request --belongsTo--> Location* --hasAndBelongsToMany--> Item (* as "ToLocation") In my RequestController, I want to paginate all the Items in a Request's ToLocation. // RequestsController var $paginate = array( 'Item' => array( 'limit' => 5, 'contain' => array( "Location" ) ) ); // RequestController::add() $locationId = 21; $items = $this->paginate('Item', array( "Location.id" => $locationId )); And this is failing, because it is generating this SQL: SELECT COUNT(*) AS count FROM items Item WHERE Location.id = 21 I can't figure out how to make it actually use the "contain" argument of $paginate... Any ideas?

    Read the article

  • Can't call an object method. PHP reports variable undefined

    - by user1285697
    This is the weirdest bug! It is probably something silly, but I have no idea how to fix it. If anyone could help, I would be most grateful! I have three files, one is called items.php, another is called tableFunctions.php, and the third is called mysql.php. I use two global objects called 'mysql' and 'tableFunctions'. They are stored in the files 'mysql.php', and 'tableFunctions.php', respectively. In each file, I create an instance of its object, assigning it to the global variable $_mysql, or $_table. like this: In the file mysql.php: global $_mysql; $_mysql = new mysql(); In the file tableFunctions.php: global $_table; $_table = new tableFunctions(); Here's how it is supposed to work: The items.php file includes the tableFunctions.php file... Which in turn, needs the mysql.php file, so it includes it too. In the items.php file, I call the method getTable(), which is contained in the object tableFunctions.(and in the variable $_table.) Like this: $t = $_table->getTable('items'); The getTable function calls the method, arrayFromResult(), which is contained within in the object mysql.(and in the variable $_mysql.) Like this: $result = $_mysql->arrayFromResult($r); That's where I get the error. PHP says that the variable '$_mysql' is undefined, but I defined it in the 'mysql.php' file.(see above) I also included mysql.php with the following code: include_once 'mysql.php'; I have no idea what is wrong! If anyone can help that would be much appreciated. The source files can be downloaded with the following link: https://www.dropbox.com/sh/bjj2gyjsybym89r/YLxqyNvQdn

    Read the article

  • List of running minimum values

    - by scarle88
    Given a sorted list of: new []{1, 2, -1, 3, -2, 1, 1, 2, -1, -3} I want to be able to iterate over the list and at each element return the smallest value iterated so far. So given the list above the resultant list would look like: 1 1 -1 -1 -2 -2 -2 -2 -2 -3 My rough draft code looks like: var items = new []{1, 2, -1, 3, -2, 1, 1, 2, -1, -3}; var min = items.First(); var drawdown = items.Select(i => { if(i < min) { min = i; return i; } else { return min; } }); foreach(var i in drawdown) { Console.WriteLine(i); } But this is not very elegant. Is there an easier to read (linq?) way of doing this? I looked into Aggregate but it seemed to be the wrong tool. Ultimately the list of items will be very long, in the many thousands. So good performance will be an issue to.

    Read the article

  • Drupal 7 - I can't pass post data in module function

    - by user2603290
    I can't pass post data in my custom module. filenames: mymodule.info mymodule.mod .info name = My Module description = My custom module. package = DEV version = 1.0 core = 7.x .module <?php function mymodule_menu() { $items = array(); $items['getcountries'] = array( 'title' => 'Get Countries', 'page callback' => 'getcountries', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK, ); $items['getstates'] = array( 'title' => 'Get States', 'page callback' => 'getstates', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK, ); return $items; } function getcountries() { $result = db_query("select distinct(country) from region"); $jsonarray = Array(); foreach ($result as $record) { $jsonarray[] = array( 'item' => $record->country, 'value' => $record->country ); } $json = json_encode($jsonarray); echo $json; } function getstates() { echo $_POST["test"]; } Ajax call $(document).ready(function(){ $.ajax({ url: '/getstates', type: 'POST', data: '{"test":"1"}', success : function () { alert('ok'); }, error : function (jqXHR, textStatus, errorThrown) { alert('error'); } }); }); The first item "getcountries" is working fine however the second one is not. I can browse to http://mysite.com/getstates ok but when I call this function using ajax it is not passing the value of "test" which is "1" to $_POST["test"]. I am new to Drupal so I am positive that I miss something here. I thought I need a new set of eyes.

    Read the article

  • Metro: Introduction to the WinJS ListView Control

    - by Stephen.Walther
    The goal of this blog entry is to provide a quick introduction to the ListView control – just the bare minimum that you need to know to start using the control. When building Metro style applications using JavaScript, the ListView control is the primary control that you use for displaying lists of items. For example, if you are building a product catalog app, then you can use the ListView control to display the list of products. The ListView control supports several advanced features that I plan to discuss in future blog entries. For example, you can group the items in a ListView, you can create master/details views with a ListView, and you can efficiently work with large sets of items with a ListView. In this blog entry, we’ll keep things simple and focus on displaying a list of products. There are three things that you need to do in order to display a list of items with a ListView: Create a data source Create an Item Template Declare the ListView Creating the ListView Data Source The first step is to create (or retrieve) the data that you want to display with the ListView. In most scenarios, you will want to bind a ListView to a WinJS.Binding.List object. The nice thing about the WinJS.Binding.List object is that it enables you to take a standard JavaScript array and convert the array into something that can be bound to the ListView. It doesn’t matter where the JavaScript array comes from. It could be a static array that you declare or you could retrieve the array as the result of an Ajax call to a remote server. The following JavaScript file – named products.js – contains a list of products which can be bound to a ListView. (function () { "use strict"; var products = new WinJS.Binding.List([ { name: "Milk", price: 2.44 }, { name: "Oranges", price: 1.99 }, { name: "Wine", price: 8.55 }, { name: "Apples", price: 2.44 }, { name: "Steak", price: 1.99 }, { name: "Eggs", price: 2.44 }, { name: "Mushrooms", price: 1.99 }, { name: "Yogurt", price: 2.44 }, { name: "Soup", price: 1.99 }, { name: "Cereal", price: 2.44 }, { name: "Pepsi", price: 1.99 } ]); WinJS.Namespace.define("ListViewDemos", { products: products }); })(); The products variable represents a WinJS.Binding.List object. This object is initialized with a plain-old JavaScript array which represents an array of products. To avoid polluting the global namespace, the code above uses the module pattern and exposes the products using a namespace. The list of products is exposed to the world as ListViewDemos.products. To learn more about the module pattern and namespaces in WinJS, see my earlier blog entry: http://stephenwalther.com/blog/archive/2012/02/22/metro-namespaces-and-modules.aspx Creating the ListView Item Template The ListView control does not know how to render anything. It doesn’t know how you want each list item to appear. To get the ListView control to render something useful, you must create an Item Template. Here’s what our template for rendering an individual product looks like: <div id="productTemplate" data-win-control="WinJS.Binding.Template"> <div class="product"> <span data-win-bind="innerText:name"></span> <span data-win-bind="innerText:price"></span> </div> </div> This template displays the product name and price from the data source. Normally, you will declare your template in the same file as you declare the ListView control. In our case, both the template and ListView are declared in the default.html file. To learn more about templates, see my earlier blog entry: http://stephenwalther.com/blog/archive/2012/02/27/metro-using-templates.aspx Declaring the ListView The final step is to declare the ListView control in a page. Here’s the markup for declaring a ListView: <div data-win-control="WinJS.UI.ListView" data-win-options="{ itemDataSource:ListViewDemos.products.dataSource, itemTemplate:select('#productTemplate') }"> </div> You declare a ListView by adding the data-win-control to an HTML DIV tag. The data-win-options attribute is used to set two properties of the ListView. The ListView is associated with its data source with the itemDataSource property. Notice that the data source is ListViewDemos.products.dataSource and not just ListViewDemos.products. You need to associate the ListView with the dataSoure property. The ListView is associated with its item template with the help of the itemTemplate property. The ID of the item template — #productTemplate – is used to select the template from the page. Here’s what the complete version of the default.html page looks like: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ListViewDemos</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"> <script src="//Microsoft.WinJS.0.6/js/base.js"></script> <script src="//Microsoft.WinJS.0.6/js/ui.js"></script> <!-- ListViewDemos references --> <link href="/css/default.css" rel="stylesheet"> <script src="/js/default.js"></script> <script src="/js/products.js" type="text/javascript"></script> <style type="text/css"> .product { width: 200px; height: 100px; border: white solid 1px; } </style> </head> <body> <div id="productTemplate" data-win-control="WinJS.Binding.Template"> <div class="product"> <span data-win-bind="innerText:name"></span> <span data-win-bind="innerText:price"></span> </div> </div> <div data-win-control="WinJS.UI.ListView" data-win-options="{ itemDataSource:ListViewDemos.products.dataSource, itemTemplate:select('#productTemplate') }"> </div> </body> </html> Notice that the page above includes a reference to the products.js file: <script src=”/js/products.js” type=”text/javascript”></script> The page above also contains a Template control which contains the ListView item template. Finally, the page includes the declaration of the ListView control. Summary The goal of this blog entry was to describe the minimal set of steps which you must complete to use the WinJS ListView control to display a simple list of items. You learned how to create a data source, declare an item template, and declare a ListView control.

    Read the article

  • Validating a linked item&rsquo;s data template in Sitecore

    - by Kyle Burns
    I’ve been doing quite a bit of work in Sitecore recently and last week I encountered a situation that it appears many others have hit.  I was working with a field that had been configured originally as a grouped droplink, but now needed to be updated to support additional levels of hierarchy in the folder structure.  If you’ve done any work in Sitecore that statement makes sense, but if not it may seem a bit cryptic.  Sitecore offers a number of different field types and a subset of these field types focus on providing links either to other items on the content tree or to content that is not stored in Sitecore.  In the case of the grouped droplink, the field is configured with a “root” folder and each direct descendant of this folder is considered to be a header for a grouping of other items and displayed in a dropdown.  A picture is worth a thousand words, so consider the following piece of a content tree: If I configure a grouped droplink field to use the “Current” folder as its datasource, the control that gets to my content author looks like this: This presents a nicely organized display and limits the user to selecting only the direct grandchildren of the folder root.  It also presents the limitation that struck as we were thinking through the content architecture and how it would hold up over time – the authors cannot further organize content under the root folder because of the structure required for the dropdown to work.  Over time, not allowing the hierarchy to go any deeper would prevent out authors from being able to organize their content in a way that it would be found when needed, so the grouped droplink data type was not going to fit the bill. I needed to look for an alternative data type that allowed for selection of a single item and limited my choices to descendants of a specific node on the content tree.  After looking at the options available for links in Sitecore and considering them against each other, one option stood out as nearly perfect – the droptree.  This field type stores its data identically to the droplink and allows for the selection of zero or one items under a specific node in the content tree.  By changing my data template to use droptree instead of grouped droplink, the author is now presented with the following when selecting a linked item: Sounds great, but a did say almost perfect – there’s still one flaw.  The code intended to display the linked item is expecting the selection to use a specific data template (or more precisely it makes certain assumptions about the fields that will be present), but the droptree does nothing to prevent the author from selecting a folder (since folders are items too) instead of one of the items contained within a folder.  I looked to see if anyone had already solved this problem.  I found many people discussing the problem, but the closest that I found to a solution was the statement “the best thing would probably be to create a custom validator” with no further discussion in regards to what this validator might look like.  I needed to create my own validator to ensure that the user had not selected a folder.  Since so many people had the same issue, I decided to make the validator as reusable as possible and share it here. The validator that I created inherits from StandardValidator.  In order to make the validator more intuitive to developers that are familiar with the TreeList controls in Sitecore, I chose to implement the following parameters: ExcludeTemplatesForSelection – serves as a “deny list”.  If the data template of the selected item is in this list it will not validate IncludeTemplatesForSelection – this can either be empty to indicate that any template not contained in the exclusion list is acceptable or it can contain the list of acceptable templates Now that I’ve explained the parameters and the purpose of the validator, I’ll let the code do the rest of the talking: 1: /// <summary> 2: /// Validates that a link field value meets template requirements 3: /// specified using the following parameters: 4: /// - ExcludeTemplatesForSelection: If present, the item being 5: /// based on an excluded template will cause validation to fail. 6: /// - IncludeTemplatesForSelection: If present, the item not being 7: /// based on an included template will cause validation to fail 8: /// 9: /// ExcludeTemplatesForSelection trumps IncludeTemplatesForSelection 10: /// if the same value appears in both lists. Lists are comma seperated 11: /// </summary> 12: [Serializable] 13: public class LinkItemTemplateValidator : StandardValidator 14: { 15: public LinkItemTemplateValidator() 16: { 17: } 18:   19: /// <summary> 20: /// Serialization constructor is required by the runtime 21: /// </summary> 22: /// <param name="info"></param> 23: /// <param name="context"></param> 24: public LinkItemTemplateValidator(SerializationInfo info, StreamingContext context) : base(info, context) { } 25:   26: /// <summary> 27: /// Returns whether the linked item meets the template 28: /// constraints specified in the parameters 29: /// </summary> 30: /// <returns> 31: /// The result of the evaluation. 32: /// </returns> 33: protected override ValidatorResult Evaluate() 34: { 35: if (string.IsNullOrWhiteSpace(ControlValidationValue)) 36: { 37: return ValidatorResult.Valid; // let "required" validation handle 38: } 39:   40: var excludeString = Parameters["ExcludeTemplatesForSelection"]; 41: var includeString = Parameters["IncludeTemplatesForSelection"]; 42: if (string.IsNullOrWhiteSpace(excludeString) && string.IsNullOrWhiteSpace(includeString)) 43: { 44: return ValidatorResult.Valid; // "allow anything" if no params 45: } 46:   47: Guid linkedItemGuid; 48: if (!Guid.TryParse(ControlValidationValue, out linkedItemGuid)) 49: { 50: return ValidatorResult.Valid; // probably put validator on wrong field 51: } 52:   53: var item = GetItem(); 54: var linkedItem = item.Database.GetItem(new ID(linkedItemGuid)); 55:   56: if (linkedItem == null) 57: { 58: return ValidatorResult.Valid; // this validator isn't for broken links 59: } 60:   61: var exclusionList = (excludeString ?? string.Empty).Split(','); 62: var inclusionList = (includeString ?? string.Empty).Split(','); 63:   64: if ((inclusionList.Length == 0 || inclusionList.Contains(linkedItem.TemplateName)) 65: && !exclusionList.Contains(linkedItem.TemplateName)) 66: { 67: return ValidatorResult.Valid; 68: } 69:   70: Text = GetText("The field \"{0}\" specifies an item which is based on template \"{1}\". This template is not valid for selection", GetFieldDisplayName(), linkedItem.TemplateName); 71:   72: return GetFailedResult(ValidatorResult.FatalError); 73: } 74:   75: protected override ValidatorResult GetMaxValidatorResult() 76: { 77: return ValidatorResult.FatalError; 78: } 79:   80: public override string Name 81: { 82: get { return @"LinkItemTemplateValidator"; } 83: } 84: }   In this blog entry, I have shared some code that I found useful in solving a problem that seemed fairly common.  Hopefully the next person that is looking for this answer finds it useful as well.

    Read the article

< Previous Page | 83 84 85 86 87 88 89 90 91 92 93 94  | Next Page >