Search Results

Search found 493 results on 20 pages for 'orderby'.

Page 6/20 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Recursive MySQL function call eats up too much memory and dies.

    - by kylex
    I have the following recursive function which works... up until a point. Then the script asks for more memory once the queries exceed about 100, and when I add more memory, the script typically just dies (I end up with a white screen on my browser). public function returnPArray($parent=0,$depth=0,$orderBy = 'showOrder ASC'){ $query = mysql_query("SELECT *, UNIX_TIMESTAMP(lastDate) AS whenTime FROM these_pages WHERE parent = '".$parent."' AND deleted = 'N' ORDER BY ".$orderBy.""); $rows = mysql_num_rows($query); while($row = mysql_fetch_assoc($query)){ // This uses my class and places the content in an array. MyClass::$_navArray[] = array( 'id' => $row['id'], 'parent' => $row['parent'] ); MyClass::returnPArray($row['id'],($depth+1)); } $i++; } Can anyone help me make this query less resource intensive?

    Read the article

  • Retreiving upcoming calendar events from a Google Calendar

    - by brian_ritchie
    Google has a great cloud-based calendar service that is part of their Gmail product.  Besides using it as a personal calendar, you can use it to store events for display on your web site.  The calendar is accessible through Google's GData API for which they provide a C# SDK. Here's some code to retrieve the upcoming entries from the calendar:  .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: Consolas, "Courier New", Courier, Monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } 1: public class CalendarEvent 2: { 3: public string Title { get; set; } 4: public DateTime StartTime { get; set; } 5: } 6:   7: public class CalendarHelper 8: { 9: public static CalendarEvent[] GetUpcomingCalendarEvents 10: (int numberofEvents) 11: { 12: CalendarService service = new CalendarService("youraccount"); 13: EventQuery query = new EventQuery(); 14: query.Uri = new Uri( 15: "http://www.google.com/calendar/feeds/userid/public/full"); 16: query.FutureEvents = true; 17: query.SingleEvents = true; 18: query.SortOrder = CalendarSortOrder.ascending; 19: query.NumberToRetrieve = numberofEvents; 20: query.ExtraParameters = "orderby=starttime"; 21: var events = service.Query(query); 22: return (from e in events.Entries select new CalendarEvent() 23: { StartTime=(e as EventEntry).Times[0].StartTime, 24: Title = e.Title.Text }).ToArray(); 25: } 26: } There are a few special "tricks" to make this work: "SingleEvents" flag will flatten out reoccurring events "FutureEvents", "SortOrder", and the "orderby" parameters will get the upcoming events. "NumberToRetrieve" will limit the amount coming back  I then using Linq to Objects to put the results into my own DTO for use by my model.  It is always a good idea to place data into your own DTO for use within your MVC model.  This protects the rest of your code from changes to the underlying calendar source or API.

    Read the article

  • SQL SERVER List All the DMV and DMF on Server

    “How many DMVs and DVFs are there in SQL Server 2008?” – this question was asked to me in one of the recent SQL Server Trainings. Answer is very simple: SELECT name, type, type_desc FROM sys.system_objects WHERE name LIKE 'dm_%' ORDERBY name Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: Pinal Dave, SQL, SQL Authority, SQL Query, [...]...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Compare Two NameValueCollections Extension Method

    - by Jon Canning
    public static class NameValueCollectionExtension     {         public static bool CollectionEquals(this NameValueCollection nameValueCollection1, NameValueCollection nameValueCollection2)         {             return nameValueCollection1.ToKeyValue().SequenceEqual(nameValueCollection2.ToKeyValue());         }         private static IEnumerable<object> ToKeyValue(this NameValueCollection nameValueCollection)         {             return nameValueCollection.AllKeys.OrderBy(x => x).Select(x => new {Key = x, Value = nameValueCollection[x]});         }     }

    Read the article

  • Choosing a type for search results in C#

    - by Chris M
    I have a result set that will never exceed 500; the results that come back from the web-service are assigned to a search results object. The data from the webservice is about 2mb; the bit I want to use is about a third of each record, so this allows me to cache and quickly manipulate it. I want to be able to sort and filter the results with the least amount of overhead and as fast as possible so I used the VCSKICKS timing class to measure their performance Average Total (10,000) Type Create Sort Create Sort HashSet 0.1579 0.0003 1579 3 IList 0.0633 0.0002 633 2 IQueryable 0.0072 0.0432 72 432 Measured in Seconds using http://www.vcskicks.com/algorithm-performance.php I created the hashset through a for loop over the web-service response (adding to the hashset). The List & IQueryable were created using LINQ. Question I can understand why HashSet takes longer to create (the foreach loop vs linq); but why would IQueryable take longer to sort than the other two; and finally is there a better way to assign the HashSet. Thanks Actual Program public class Program { private static AuthenticationHeader _authHeader; private static OPSoapClient _opSession; private static AccommodationSearchResponse _searchResults; private static HashSet<SearchResults> _myHash; private static IList<SearchResults> _myList; private static IQueryable<SearchResults> _myIQuery; static void Main(string[] args) { #region Setup WebService _authHeader = new AuthenticationHeader { UserName = "xx", Password = "xx" }; _opSession = new OPSoapClient(); #region Setup Search Results _searchResults = _opgSession.SearchCR(_authHeader, "ENG", "GBP", "GBR"); #endregion Setup Search Results #endregion Setup WebService // HASHSET SpeedTester hashTest = new SpeedTester(TestHashSet); hashTest.RunTest(); Console.WriteLine("- Hash Test \nAverage Running Time: {0}; Total Time: {1}", hashTest.AverageRunningTime, hashTest.TotalRunningTime); SpeedTester hashSortTest = new SpeedTester(TestSortingHashSet); hashSortTest.RunTest(); Console.WriteLine("- Hash Sort Test \nAverage Running Time: {0}; Total Time: {1}", hashSortTest.AverageRunningTime, hashSortTest.TotalRunningTime); // ILIST SpeedTester listTest = new SpeedTester(TestList); listTest.RunTest(); Console.WriteLine("- List Test \nAverage Running Time: {0}; Total Time: {1}", listTest.AverageRunningTime, listTest.TotalRunningTime); SpeedTester listSortTest = new SpeedTester(TestSortingList); listSortTest.RunTest(); Console.WriteLine("- List Sort Test \nAverage Running Time: {0}; Total Time: {1}", listSortTest.AverageRunningTime, listSortTest.TotalRunningTime); // IQUERIABLE SpeedTester iqueryTest = new SpeedTester(TestIQueriable); iqueryTest.RunTest(); Console.WriteLine("- iquery Test \nAverage Running Time: {0}; Total Time: {1}", iqueryTest.AverageRunningTime, iqueryTest.TotalRunningTime); SpeedTester iquerySortTest = new SpeedTester(TestSortableIQueriable); iquerySortTest.RunTest(); Console.WriteLine("- iquery Sort Test \nAverage Running Time: {0}; Total Time: {1}", iquerySortTest.AverageRunningTime, iquerySortTest.TotalRunningTime); } static void TestHashSet() { var test = _searchResults.Items; _myHash = new HashSet<SearchResults>(); foreach(var x in test) { _myHash.Add(new SearchResults { Ref = x.Ref, Price = x.StandardPrice }); } } static void TestSortingHashSet() { var sorted = _myHash.OrderBy(s => s.Price); } static void TestList() { var test = _searchResults.Items; _myList = (from x in test select new SearchResults { Ref = x.Ref, Price = x.StandardPrice }).ToList(); } static void TestSortingList() { var sorted = _myList.OrderBy(s => s.Price); } static void TestIQueriable() { var test = _searchResults.Items; _myIQuery = (from x in test select new SearchResults { Ref = x.Ref, Price = x.StandardPrice }).AsQueryable(); } static void TestSortableIQueriable() { var sorted = _myIQuery.OrderBy(s => s.Price); } }

    Read the article

  • Setting a DataGrid background color based on the previous row

    - by Zipper
    I'm trying to setup a grid where I do column sorting, but I wanted to do zebra striping, only rather than every other row or every x rows, I want it to be based on the value of cells. i.e. All cells that contain 0 have a blue background, the next value would have a white background, the next value would be blue, etc.... The problem I have is that I can't seem to find where to actually do the setting of the background colors. I'm using a custom sorter and I tried setting it in there after I re-order the list and set the data source, but it appears that when the data source is set, that the rows don't exist yet. I tried using the DataContextChanged, but that event doesn't seem to be firing. Here is what I have now. namespace Foo.Bar { public partial class FooBar { List<Bla> ResultList { get; set; } SolidColorBrush stripeOneColor = new SolidColorBrush(Colors.Gold); SolidColorBrush stripeTwoColor = new SolidColorBrush(Colors.White); //********************************************************************************************* public Consistency() { InitializeComponent(); } //********************************************************************************************* override protected void PopulateTabWithData() { ResultList = GetBlas(); SortAndGroup("Source"); } //********************************************************************************************* private void SortAndGroup(string colName) { IOrderedEnumerable <Bla> ordered = null; switch (colName) { case "Source": case "ID": ordered = ResultList.OrderBy(r => r.Source).ThenBy(r => r.ID); break; case "Name": ordered = ResultList.OrderBy(r => r.Source).ThenBy(r => r.Name); break; case "Message": ordered = ResultList.OrderBy(r => r.Message); break; default: throw new Exception(colName); } ResultList = ordered.ThenBy(r => r.Source).ThenBy(r => r.ID).ToList(); // tie-breakers consistencyDataGrid.ItemsSource = null; consistencyDataGrid.ItemsSource = ResultList; ColorRows(); } //********************************************************************************************* private void consistencyDataGrid_Sorting(object sender, System.Windows.Controls.DataGridSortingEventArgs e) { SortAndGroup(e.Column.Header.ToString()); e.Handled = true; } private void ColorRows() { for (var i = 0; i < ResultList.Count; i++) { var currentItem = ResultList[i]; var row = myDataGrid.ItemContainerGenerator.ContainerFromItem(currentItem) as DataGridRow; if (row == null) { continue; } if (i > 0) { var previousItem = ResultList[i - 1]; var previousRow = myDataGrid.ItemContainerGenerator.ContainerFromItem(previousItem) as DataGridRow; if (currentItem.Source == previousItem.Source) { row.Background = previousRow.Background; } else { if (previousRow.Background == stripeOneColor) { row.Background = stripeTwoColor; } else { row.Background = stripeOneColor; } } } else { row.Background = stripeOneColor; } } } } } }

    Read the article

  • PHP PSR-0 + several namespaces in one file and autoload

    - by Nemoden
    I've been thinking for a while about defining several namespaces in one php file and so, having several classes inside this file. Suppose, I want to implement something like Doctrine\ORM\Query\Expr: Expr.php Expr |-- Andx.php |-- Base.php |-- Comparison.php |-- Composite.php |-- From.php |-- Func.php |-- GroupBy.php |-- Join.php |-- Literal.php |-- Math.php |-- OrderBy.php |-- Orx.php `-- Select.php It would be nice if I had all of this in one file - Expr.php: namespace Doctrine\ORM\Query; class Expr { // code } namespace Doctrine\ORM\Query\Expr; class Func { // code } // etc... What I'm thinking of is directories naming convention and, unlike PSR-0 having several classes and namespaces in one file. It's best explained by the code: ls Doctrine/orm/query Expr.php that's it - only Expr.php Since Expr.php is somewhat I call a "meta-namespace" for Expr\Func, it make sense to place all the classes inside Expr.php (as shown above). So, the vendor name is still starts with an uppercased letter (Doctrine) and the other parts of namespace start with lowercased letter. We can write an autoload so it would respect this notion: function load_class($class) { if (class_exists($class)) { return true; } $tokenized_path = explode(array("_", "\\"), DIRECTORY_SEPARATOR, $class); // array('Doctrine', 'orm', 'query', 'Expr', 'Func'); // ^^^^ // first, we are looking for first uppercased namespace part // and if it's not last (not the class name), we use it as a filename // and wiping away the rest to compose a path to a file we need to include if (FALSE !== ($meta_class_index = find_meta_class($tokenized_path))) { $new_tokenized_path = array_slice($tokenized_path, 0, $meta_class_index); $path_to_class = implode(DIRECTORY_SEPARATOR, $new_tokenized_path); } else { // no meta class found $path_to_class = implode(DIRECTORY_SEPARATOR, $tokenized_path); } if (file_exists($path_to_class.'.php')) { require_once $path_to_class.'.php'; } return false; } Another reason to do so is to reduce a number of php files scattered among directories. Usually you check file existence before you require a file to fail gracefully: file_exists($path_to_class.'.php'); If you take a look at actual Doctrine\ORM\Query\Expr code, you'll see they use all of the "inner-classes", so you actually do: file_exists("/path/to/Doctrine/ORM/Query/Expr.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/AndX.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/Base.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/Comparison.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/Composite.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/From.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/Func.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/GroupBy.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/Join.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/Literal.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/Math.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/OrderBy.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/Orx.php"); file_exists("/path/to/Doctrine/ORM/Query/Expr/Select.php"); in your autoload which causes quite a few I/O reads. Isn't it too much to check on each user's hit? I'm just putting this on a discussion. I want to hear from another PHP programmers what do they think of it. And, of course, if you have a silver bullet addressing this problems I've designated here, please share. I also have been thinking if my vogue question fits here and according to the FAQ it seems like this question addresses "software architecture" problem slash proposal. I'm sorry if my scribble may seem a bit clunky :) Thanks.

    Read the article

  • C# Multiple Property Sort

    - by Ben Griswold
    As you can see in the snippet below, sorting is easy with Linq.  Simply provide your OrderBy criteria and you’re done.  If you want a secondary sort field, add a ThenBy expression to the chain.  Want a third level sort?  Just add ThenBy along with another sort expression. var projects = new List<Project>     {         new Project {Description = "A", ProjectStatusTypeId = 1},         new Project {Description = "B", ProjectStatusTypeId = 3},         new Project {Description = "C", ProjectStatusTypeId = 3},         new Project {Description = "C", ProjectStatusTypeId = 2},         new Project {Description = "E", ProjectStatusTypeId = 1},         new Project {Description = "A", ProjectStatusTypeId = 2},         new Project {Description = "C", ProjectStatusTypeId = 4},         new Project {Description = "A", ProjectStatusTypeId = 3}     };   projects = projects     .OrderBy(x => x.Description)     .ThenBy(x => x.ProjectStatusTypeId)     .ToList();   foreach (var project in projects) {     Console.Out.WriteLine("{0} {1}", project.Description,         project.ProjectStatusTypeId); } Linq offers a great sort solution most of the time, but what if you want or need to do it the old fashioned way? projects.Sort ((x, y) =>         Comparer<String>.Default             .Compare(x.Description, y.Description) != 0 ?         Comparer<String>.Default             .Compare(x.Description, y.Description) :         Comparer<Int32>.Default             .Compare(x.ProjectStatusTypeId, y.ProjectStatusTypeId));   foreach (var project in projects) {     Console.Out.WriteLine("{0} {1}", project.Description,         project.ProjectStatusTypeId); } It’s not that bad, right? Just for fun, let add some additional logic to our sort.  Let’s say we wanted our secondary sort to be based on the name associated with the ProjectStatusTypeId.  projects.Sort((x, y) =>        Comparer<String>.Default             .Compare(x.Description, y.Description) != 0 ?        Comparer<String>.Default             .Compare(x.Description, y.Description) :        Comparer<String>.Default             .Compare(GetProjectStatusTypeName(x.ProjectStatusTypeId),                 GetProjectStatusTypeName(y.ProjectStatusTypeId)));   foreach (var project in projects) {     Console.Out.WriteLine("{0} {1}", project.Description,         GetProjectStatusTypeName(project.ProjectStatusTypeId)); } The comparer will now consider the result of the GetProjectStatusTypeName and order the list accordingly.  Of course, you can take this same approach with Linq as well.

    Read the article

  • Sharepoint Lists.GetListItems Method rowLimit problem

    - by Linda
    In SharePoint I am using the default view of a list. When I use GetListItems method I can pass into it the following: public XmlNode GetListItems ( string listName, string viewName, XmlNode query, XmlNode viewFields, string rowLimit, XmlNode queryOptions, string webID ) I am passing in "" for the viewName and am passing a rowLimit of 1000. By Default view only returns 100 items. 100 Items are still being returned not 1000. Can you use the rowLimit when not specifying a view? Is it possible to bring back 1000 items using the query instead? I do not really want to use a GUID for the viewName as I would have to look it up for each list and perform a big refactor. Update I am now using the guid of the view and my list still returns the incorrect number of items. I know the guid is being used as I sued an incorrect one and it errord out. Any ideas what could be wrong? The code that is being sent to the service is as follows: <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> <listName>Media Outlet</listName> <viewName>{2822F0D9-A905-44B5-8913-34E6497F1AAF}</viewName> <query><Query><Where><Eq><FieldRef Name='Outlet_x0020_Type' /><Value Type='Lookup'></Value></Eq></Where><OrderBy><FieldRef Name='Title' /></OrderBy></Query></query> <ViewFields></ViewFields> <RowLimit>10000</RowLimit> <QueryOptions></QueryOptions> <webID></webID> </GetListItems>

    Read the article

  • Sharepoint GetListItems using rowLimit parameter is not limiting the results returned

    - by Linda
    In SharePoint I am using the default view of a list. When I use GetListItems method I can pass into it the following: public XmlNode GetListItems ( string listName, string viewName, XmlNode query, XmlNode viewFields, string rowLimit, XmlNode queryOptions, string webID ) I am passing in "" for the viewName and am passing a rowLimit of 1000. By Default view only returns 100 items. 100 Items are still being returned not 1000. Can you use the rowLimit when not specifying a view? Is it possible to bring back 1000 items using the query instead? I do not really want to use a GUID for the viewName as I would have to look it up for each list and perform a big refactor. Update I am now using the guid of the view and my list still returns the incorrect number of items. I know the guid is being used as I sued an incorrect one and it errord out. Any ideas what could be wrong? The code that is being sent to the service is as follows: <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> <listName>Media Outlet</listName> <viewName>{2822F0D9-A905-44B5-8913-34E6497F1AAF}</viewName> <query><Query><Where><Eq><FieldRef Name='Outlet_x0020_Type' /><Value Type='Lookup'></Value></Eq></Where><OrderBy><FieldRef Name='Title' /></OrderBy></Query></query> <ViewFields></ViewFields> <RowLimit>10000</RowLimit> <QueryOptions></QueryOptions> <webID></webID> </GetListItems>

    Read the article

  • Binding a DropDownList in ListView InsertItemTemplate throwing an error

    - by Telos
    I've got a ListView which binds to a LinqDataSource and displays selected locations. The insert item Contains a dropdownlist that pulls from another LinqDataSource to give all the unselected locations. The problem is that I get the following error when loading the page: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control. I'm doing a very similar setup in another page of the website, and it isn't giving us this error so I'm pretty confused. I know I can work around this by not binding, manually finding the control and getting the value, but this should work and I don't understand why it isn't. Any thoughts? The better part of the source code is below. <asp:LinqDataSource ID="ldsLocations" runat="server" ContextTypeName="ClearviewInterface.ESLinqDataContext" EnableDelete="true" EnableInsert="true" OnInserting="ldsLocations_Inserting" OnDeleting="ldsLocations_Deleting" TableName="crmLocations" OrderBy="addr1" OnSelecting="ldsLocations_Selecting" /> <asp:LinqDataSource ID="ldsFreeLocations" runat="server" ContextTypeName="ClearviewInterface.ESLinqDataContext" OrderBy="addr1" TableName="v_CVLocations" OnSelecting="ldsFreeLocations_Selecting" /> <asp:ListView ID="lvLocations" DataSourceID="ldsLocations" DataKeyNames="ID" InsertItemPosition="LastItem" runat="server" > <InsertItemTemplate> <tr> <td colspan="6"><hr /></td> </tr> <tr> <td colspan="2"> <asp:DropDownList ID="ddlFreeLocations" DataSourceID="ldsFreeLocations" DataTextField="addr1" DataValueField="record" MarkFirstMatch="true" SelectedValue='<%# Bind("record") %>' runat="server" /> </td> <td><asp:ImageButton ID="btnAdd" CommandName="Insert" SkinID="Insert" runat="server" /></td> </tr> </InsertItemTemplate>

    Read the article

  • Extension method using Reflection to Sort

    - by Xavier
    I implemented an extension "MyExtensionSortMethod" to sort collections (IEnumerate). This allows me to replace code such as 'entities.OrderBy( ... ).ThenByDescending( ...)' by 'entities.MyExtensionSortMethod()' (no parameter as well). Here is a sample of implementation: //test function function Test(IEnumerable<ClassA> entitiesA,IEnumerable<ClassB> entitiesB ) { //Sort entitiesA , based on ClassA MySort method var aSorted = entitiesA.MyExtensionSortMethod(); //Sort entitiesB , based on ClassB MySort method var bSorted = entitiesB.MyExtensionSortMethod(); } //Class A definition public classA: IMySort<classA> { .... public IEnumerable<classA> MySort(IEnumerable<classA> entities) { return entities.OrderBy( ... ).ThenBy( ...); } } public classB: IMySort<classB> { .... public IEnumerable<classB> MySort(IEnumerable<classB> entities) { return entities.OrderByDescending( ... ).ThenBy( ...).ThenBy( ... ); } } //extension method public static IEnumerable<T> MyExtensionSortMethod<T>(this IEnumerable<T> e) where T : IMySort<T>, new() { //the extension should call MySort of T Type t = typeof(T); var methodInfo = t.GetMethod("MySort"); //invoke MySort var result = methodInfo.Invoke(new T(), new object[] {e}); //Return return (IEnumerable < T >)result; } public interface IMySort<TEntity> where TEntity : class { IEnumerable<TEntity> MySort(IEnumerable<TEntity> entities); } However, it seems a bit complicated compared to what it does so I was wondering if they were another way of doing it?

    Read the article

  • How do I sort an internationalized i18n table with symfony and doctrine?

    - by Maurizio
    I would like to display a list of records from an internationalized table using sfDoctrinePager. Not all the records have been translated to all the languages supported by the application, so I had to implement a fallback mechanism for some fields (by overriding the getFoo() function in the Bar.class.php, as explained in another post here). I have different fallback list for each culture. Everything works fine until when it comes to sorting the records in alphabetical order. I'm sorting the records at the SQL (Dql) level, by adding an -orderBy('t.name') to the query: $q = Doctrine::getTable('Foo') ->createQuery('f') ->leftJoin('f.Translation t') ->orderBy('t.name') But here come the troubles: the list gets not sorted correctly, regardless of the active culture. I get rather better results when I limit the translations to the active culture, like this: ->leftJoin('f.Translation t WITH lang = ?', $request->getParameter('sf_culture'); Then the sorting is correct, as far as all the translations exist for the active culture. If a translation does not exist and I have to take the name from the fallback language, the record will be displayed at the very beginning of the list (I understand this happens because the value for the current culture is null). My question is: is there a best practice for getting internationalized fields (needing fallbacks) sorted correctly with doctrine and sfDoctrinePager? Thank you in advance.

    Read the article

  • Exclude rows with Doctrine ORM DQL (NOT IN)

    - by Sheriffen
    I'm building a chat application with codeigniter and doctrine. Tables: - User - User_roles - User_available Relations: ONE user have MANY roles. ONE user_available have ONE user. Users available for chatting will be in the user_available table. Problem: I need to get all users in in user_available that hasn't got role_id 7. So I need to express in DQL something like (this is not even SQL, just in words): SELECT * from user_available WHERE NOT user_available.User.Role.role_id = 7 Really stuck on this one EDIT: Guess I was unclear. The tables are already mapped and Doctrine does the INNER JOIN job for me. I'm using this code to get the admin that waited the longest but now I need the user: $admin = Doctrine_Query::create() ->select('c.id') ->from('Chat_available c') ->where('c.User.Roles.role_id = ?', 7) ->groupBy('c.id') ->orderBy('c.created_at ASC') ->fetchOne(); Now I need to get the user that waited the longest but this does NOT work $admin = Doctrine_Query::create() ->select('c.id') ->from('Chat_available c') ->where('c.User.Roles.role_id != ?', 7) ->groupBy('c.id') ->orderBy('c.created_at ASC') ->fetchOne();

    Read the article

  • French date format

    - by kwek-kwek
    I am a newbie in PHP & wordpress. I wanted to know how to make this codde renders the date formating in french (e.g. 5 Fev) when your on the french side but in english format in English (e.g. Jan 5) Here is my code: <?php if (strtolower(ICL_LANGUAGE_CODE) == 'en') {$sidePosts = get_posts('cat=3,4,5,19&posts_per_page=5&order=DESC&orderby=date');} if (strtolower(ICL_LANGUAGE_CODE) == 'fr') {$sidePosts = get_posts('cat=9,10,11,17&posts_per_page=5&order=DESC&orderby=date');} foreach($sidePosts as $sidePosts) { $array = (array) $sidePosts; print("<li>"); print("<span class='date'>".get_the_time('M j', $array[ID])."</span>"); print("<a href='".get_permalink($array[ID])."' title='".$array[post_title]."'>".$array[post_title]."</a>"); print("</li>"); } ?>

    Read the article

  • Adjust static value into dynamic (javascript) value possible in Sharepoint allitems.aspx page?

    - by lerac
    <SharePoint:SPDataSource runat="server" IncludeHidden="true" SelectCommand="&lt;View&gt;&lt;Query&gt;&lt;OrderBy&gt;&lt;FieldRef Name=&quot;EventDate&quot;/&gt;&lt;/OrderBy&gt;&lt;Where&gt;&lt;Contains&gt;&lt;FieldRef Name=&quot;lawyer_x0020_1&quot;/&gt;&lt;Value Type=&quot;Note&quot;&gt;F. Sanches&lt;/Value&gt;&lt;/Contains&gt;&lt;/Where&gt;&lt;/Query&gt;&lt;/View&gt;" id="datasource1" DataSourceMode="List" UseInternalName="true"><InsertParameters><asp:Parameter DefaultValue="{ANUMBER}" Name="ListID"></asp:Parameter> This codeline is just one line of the allitems.aspx of a sharepoint list item. It only displays items where lawyer 1 = F. Sanches. Before I start messing around with the .ASPX page I wonder if it possible to change F. Sanches (in the code) into a dynamical variable (from a javascript value or something else that can be used to place the javascript value in there dynamically). If I put any javascript code in the line it will not work. P.S. Ignore ANUMBER part in code. Let say to make it simple I have javascript variable like this (now static but with my other code it is dynamic). It would be an achievement if it would place a static javascript variable. <SCRIPT type=text/javascript>javaVAR = "P. Janssen";</script> If Yes -- how? If No -- Thank you!

    Read the article

  • Is there a better way to write this LINQ query?

    - by Raj Aththanayake
    Hi Is there a better simplified way to write this query. My logic is if collection contains customer ids and countrycodes, do the query ordey by customer id ascending. If there are no contain id in CustIDs then do the order by customer name. Is there a better way to write this query? I'm not really familiar with complex lambdas. var custIdResult = (from Customer c in CustomerCollection where (c.CustomerID.ToLower().Contains(param.ToLower()) && (countryCodeFilters.Any(item => item.Equals(c.CountryCode))) ) select c).ToList(); if (custIdResult.Count > 0) { return from Customer c in custIdResult where ( c.CustomerName.ToLower().Contains(param.ToLower()) && countryCodeFilters.Any(item => item.Equals(c.CountryCode))) orderby c.CustomerID ascending select c; } else { return from Customer c in CustomerCollection where (c.CustomerName.ToLower().Contains(param.ToLower()) && countryCodeFilters.Any(item => item.Equals(c.CountryCode))) orderby c.CustomerName descending select c; }

    Read the article

  • Is it possible to order by a composite key with JPA and CriteriaBuilder

    - by Kjir
    I would like to create a query using the JPA CriteriaBuilder and I would like to add an ORDER BY clause. This is my entity: @Entity @Table(name = "brands") public class Brand implements Serializable { public enum OwnModeType { OWNER, LICENCED } @EmbeddedId private IdBrand id; private String code; //bunch of other properties } Embedded class is: @Embeddable public class IdBrand implements Serializable { @ManyToOne private Edition edition; private String name; } And the way I am building my query is like this: CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Brand> q = cb.createQuery(Brand.class).distinct(true); Root<Brand> root = q.from(Brand.class); if (f != null) { f.addCriteria(cb, q, root); f.addOrder(cb, q, root, sortCol, ascending); } return em.createQuery(q).getResultList(); And here are the functions called: public void addCriteria(CriteriaBuilder cb, CriteriaQuery<?> q, Root<Brand> r) { } public void addOrder(CriteriaBuilder cb, CriteriaQuery<?> q, Root<Brand> r, String sortCol, boolean ascending) { if (ascending) { q.orderBy(cb.asc(r.get(sortCol))); } else { q.orderBy(cb.desc(r.get(sortCol))); } } If I try to set sortCol to something like "id.edition.number" I get the following error: javax.ejb.EJBException: java.lang.IllegalArgumentException: Unable to resolve attribute [id.name] against path Any idea how I could accomplish that? I tried searching online, but I couldn't find a hint about this... Also would be great if I could do a similar ORDER BY when I have a @ManyToOne relationship (for instance, "id.edition.number")

    Read the article

  • Silverlight - C# and LINQ - Ordering By Multiple Fields

    - by user70192
    Hello, I have an ObservableCollection of Task objects. Each Task has the following properties: AssignedTo Category Title AssignedDate I'm giving the user an interface to select which of these fields they was to sort by. In some cases, a user may want to sort by up to three of these properties. How do I dynamically build a LINQ statement that will allow me to sort by the selected fields in either ascending or descending order? Currently, I'm trying the following, but it appears to only sort by the last sort applied: var sortedTasks = from task in tasks select task; if (userWantsToSortByAssignedTo == true) { if (sortByAssignedToDescending == true) sortedTasks = sortedTasks.OrderByDescending(t => t.AssignedTo); else sortedTasks = sortedTasks.OrderBy(t => t.AssignedTo); } if (userWantsToSortByCategory == true) { if (sortByCategoryDescending == true) sortedTasks = sortedTasks.OrderByDescending(t => t.Category); else sortedTasks = sortedTasks.OrderBy(t => t.Category); } Is there an elegant way to dynamicaly append order clauses to a LINQ statement?

    Read the article

  • Why does File.Exists return false?

    - by Jonas Stawski
    I'm querying all images on the Android device as such: string[] columns = { MediaStore.Images.Media.InterfaceConsts.Data, MediaStore.Images.Media.InterfaceConsts.Id }; string orderBy = MediaStore.Images.Media.InterfaceConsts.Id; var imagecursor = ManagedQuery(MediaStore.Images.Media.ExternalContentUri, columns, null, null, orderBy); for (int i = 0; i < this.Count; i++) { imagecursor.MoveToPosition(i); Paths[i]= imagecursor.GetString(dataColumnIndex); Console.WriteLine(Paths[i]); Console.WriteLine(System.IO.File.Exists(Paths[i])); } The problem is that the output shows that some files don't exist. Here's a sample output: /storage/sdcard0/Download/On-Yom-Kippur-Jews-choose-different-shoes-VSETQJ6-x-large.jpg False /storage/sdcard0/Download/397277_10151250943161341_876027377_n.jpg False /storage/sdcard0/Download/Roxy_Cottontail_&_Melo-X_Present..._Some_Bunny_Love's_You.jpg False /storage/sdcard0/Download/album-The-Rolling-Stones-Some-Girls.jpg True /storage/sdcard0/Download/some-people-ust-dont-appreciate-fashion[1].jpg True /storage/sdcard0/Download/express.gif True ... /storage/sdcard0/Download/some-joys-are-expressed-better-in-silence.JPG False How is this possible? I downloaded these images myself from the internet! They should exist in disk.

    Read the article

  • Sonata Media Bundle sortBy created_at

    - by tony908
    I use SonataMediaBundle and i would like sort Gallery by created_at field. In repository class i have (without orderBy working good!): $qb = $this->createQueryBuilder('m') ->orderBy('j.expires_at', 'DESC'); $query = $qb->getQuery(); return $query->getResult(); and this throw error: An exception has been thrown during the rendering of a template ("[Semantical Error] line 0, col 80 near 'created_at D': Error: Class Application\Sonata\MediaBundle\Entity\Gallery has no field or association named created_at") so i add this field to Gallery class: /** * @var \DateTime */ private $created_at; /** * Set created_at * * @param \DateTime $createdAt * @return Slider */ public function setCreatedAt($createdAt) { $this->created_at = $createdAt; return $this; } /** * Get created_at * * @return \DateTime */ public function getCreatedAt() { return $this->created_at; } but now i have error: FatalErrorException: Compile Error: Declaration of Application\Sonata\MediaBundle\Entity\Gallery::setCreatedAt() must be compatible with Sonata\MediaBundle\Model\GalleryInterface::setCreatedAt(DateTime $createdAt = NULL) in /home/tony/www/test/Application/Sonata/MediaBundle/Entity/Gallery.php line 32 GalleryInterface: https://github.com/sonata-project/SonataMediaBundle/blob/master/Model/GalleryInterface.php So... how can i use sortBy in my example?

    Read the article

  • Is there any performance issue using Row_Number to implement table paging in Sql Server 2008?

    - by majkinetor
    I want to implement table paging using this method: SET @PageNum = 2; SET @PageSize = 10; WITH OrdersRN AS ( SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum ,* FROM dbo.Orders ) SELECT * FROM OrdersRN WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize ORDER BY OrderDate ,OrderID; Is there anything I should be aware of ? Table has millions of records. Thx. EDIT: After using suggested MAXROWS method for some time (which works really really fast) I had to switch back to ROW_NUMBER method because of its greater flexibility. I am also very happy about its speed so far (I am working with View having more then 1M records with 10 columns). To use any kind of query I use following modification: PROCEDURE [dbo].[PageSelect] ( @Sql nvarchar(512), @OrderBy nvarchar(128) = 'Id', @PageNum int = 1, @PageSize int = 0 ) AS BEGIN SET NOCOUNT ON Declare @tsql as nvarchar(1024) Declare @i int, @j int if (@PageSize <= 0) OR (@PageSize > 10000) SET @PageSize = 10000 -- never return more then 10K records SET @i = (@PageNum - 1) * @PageSize + 1 SET @j = @PageNum * @PageSize SET @tsql = 'WITH MyTableOrViewRN AS ( SELECT ROW_NUMBER() OVER(ORDER BY ' + @OrderBy + ') AS RowNum ,* FROM MyTableOrView WHERE ' + @Sql + ' ) SELECT * FROM MyTableOrViewRN WHERE RowNum BETWEEN ' + CAST(@i as varchar) + ' AND ' + cast(@j as varchar) exec(@tsql) END If you use this procedure make sure u prevented sql injection.

    Read the article

  • WordPress: Using a Where Clause With A Custom Field

    - by Steve Wilkison
    I have a bunch of events that are listed on a particular page. Each event is a post. I need them to display in the order in which they occur, NOT the order of the posting date. So, I've created a custom field called TheDate and enter in the date in this format for each one: 20110306. Then, I wrote my query like this: query_posts( array ( 'cat' => '4', 'posts_per_page' => -1, 'orderby' => 'meta_value_num', 'meta_key' => 'TheDate', 'order' => 'ASC' ) ); Works perfectly and displays the events in the correct order. However, I also want it to ONLY display dates from today onward. I don't want it to display dates which have passed. It seems the way to do this is with a "filter." I tried this, but it doesn't work. $todaysdate = date('Ymd'); query_posts( array ( 'cat' => '4', 'posts_per_page' => -1, 'orderby' => 'meta_value_num', 'meta_key' => 'TheDate', 'order' => 'ASC' ) ); function filter_where( $where = '' ) { $where .= "meta_value_num >= $todaysdate"; return $where; } add_filter( 'posts_where', 'filter_where' ); I figure it's just a matter of where I'm using this filter, I probably have it in the wrong place. Or maybe the filter itself is bad. Any help or guidance would be greatly appreciated. Thanks!

    Read the article

  • How to refactor this duplicated LINQ code?

    - by benrick
    I am trying to figure out how to refactor this LINQ code nicely. This code and other similar code repeats within the same file as well as in other files. Sometime the data being manipulated is identical and sometimes the data changes and the logic remains the same. Here is an example of duplicated logic operating on different fields of different objects. public IEnumerable<FooDataItem> GetDataItemsByColor(IEnumerable<BarDto> dtos) { double totalNumber = dtos.Where(x => x.Color != null).Sum(p => p.Number); return from stat in dtos where stat.Color != null group stat by stat.Color into gr orderby gr.Sum(p => p.Number) descending select new FooDataItem { Color = gr.Key, NumberTotal = gr.Sum(p => p.Number), NumberPercentage = gr.Sum(p => p.Number) / totalNumber }; } public IEnumerable<FooDataItem> GetDataItemsByName(IEnumerable<BarDto> dtos) { double totalData = dtos.Where(x => x.Name != null).Sum(v => v.Data); return from stat in dtos where stat.Name != null group stat by stat.Name into gr orderby gr.Sum(v => v.Data) descending select new FooDataItem { Name = gr.Key, DataTotal = gr.Sum(v => v.Data), DataPercentage = gr.Sum(v => v.Data) / totalData }; } Anyone have a good way of refactoring this?

    Read the article

  • Linq, should I join those two queries together?

    - by 5YrsLaterDBA
    I have a Logins table which records when user is login, logout or loginFailed and its timestamp. Now I want to get the list of loginFailed after last login and the loginFailed happened within 24 hrs. What I am doing now is get the last login timestamp first. then use second query to get the final list. do you think I should join those two queris together? why not? why yes? var lastLoginTime = (from inRecord in db.Logins where inRecord.Users.UserId == userId && inRecord.Action == "I" orderby inRecord.Timestamp descending select inRecord.Timestamp).Take(1); if (lastLoginTime.Count() == 1) { DateTime lastInTime = (DateTime)lastLoginTime.First(); DateTime since = DateTime.Now.AddHours(-24); String actionStr = "F"; var records = from record in db.Logins where record.Users.UserId == userId && record.Timestamp >= since && record.Action == actionStr && record.Timestamp > lastInTime orderby record.Timestamp select record; }

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >