Sunday, April 3, 2011

Automatically import one header into each project .m file in Xcode

I have logger.h file with static logger class. Then I want to add log messages to into each method invocation to trace app execution.

In order to do that I have to include logger.h into almost each Xcode .m project file. Is there any way to tell Xcode to automatically import logger.h into each project's .m file.

thx

From stackoverflow
  • You could put the #include directive in your prefix header, effectively importing it across your project.

In Flex, how to use command-shortcuts in the browser?

I tried catching the command key shortcuts using the keyDown event and checking for KeyboardEvent.ctrlKey, but the browser(Safari) seemed to have intercepted all those key events because the shortcuts I am trying to use coincides with the safari ones. Is there anyway to override this behavior?

From stackoverflow
  • Unfortunately there's no way to mitigate the native browser handling of keystrokes directly from flash. You could create an adobe AIR app if thats even an option or check out that comment posted on your question to try doing it with javascript.

How to Encapsulate Change For Random Variations

I am writing a motor vehicle system for a county government that lets a user select many different types of car tags. The problem is that the state has built in a lot of special little exceptions for tag types. I realize it's very messy and inefficient to simply code if statements for each of these, but I can't seem to find a way to abstract this out because the variations on the tag types are so different. Does anyone have any ideas as to how one would do this? Thanks!

From stackoverflow
  • Here is the best solution I found. What I did was encapsulate the deviations into methods, then in the UI layer I called that function, which returned a boolean if the condition was met. So, for instance:

    if(tagType.IsSpecialTag(params)) {
         //display appropriate deviations
       }
    

Add folder and file using Team Foundation Server SDK

I am having a problem with a folder and a file showing up under my project which is under my solution. The files are being added to TFS but my project has no idea that the file exists and shows it as white

Dim tfs As TeamFoundationServer = TeamFoundationServerFactory.GetServer(txtServer.Text)

' Get a reference to Source Control.
Dim versionControl As VersionControlServer = CType(tfs.GetService(GetType(VersionControlServer)), VersionControlServer)

' Create a workspace.
Dim workspace As Workspace = versionControl.GetWorkspace(txtProject.Text)

If Not String.IsNullOrEmpty(txtUpdateScript.Text) Then
            Dim fooString = Array.Find(Of WorkingFolder)(workspace.Folders, Function(m) m.ServerItem.Contains("$/FOO.NET"))
            Directory.CreateDirectory(IO.Path.Combine(IO.Path.Combine(txtProject.Text, "FOOAdmin\Updates"), txtVersion.Text))
            Directory.CreateDirectory(fooString.ServerItem & "/FOOAdmin/Updates/" & txtVersion.Text)
            IO.File.Copy(txtUpdateScript.Text, IO.Path.Combine(IO.Path.Combine(IO.Path.Combine(txtProject.Text, "FOOAdmin\Updates"), txtVersion.Text), "Update.sql"), True)
            workspace.PendAdd(IO.Path.Combine(IO.Path.Combine(txtProject.Text, "FOOAdmin\Updates"), txtVersion.Text))
            workspace.PendAdd(IO.Path.Combine(IO.Path.Combine(IO.Path.Combine(txtProject.Text, "FOOAdmin\Updates"), txtVersion.Text), "Update.sql"))
End If

' Get Pending changes
Dim pendingChanges As PendingChange() = workspace.GetPendingChanges()

' Checkin the items we added.
Dim changesetNumber As Integer = workspace.CheckIn(pendingChanges, "FOO.Net AutoBuild")

If I do not add this line

 Directory.CreateDirectory(fooString.ServerItem & "/FOOAdmin/Updates/" & txtVersion.Text)

Then the project does not know about the folder or the file.

From stackoverflow
  • Just because a file exists on the server doesn't mean it's part of a solution or project. I'm not 100% sure what your code is supposed to do, but it won't affect any projects unless you also modify the corresponding *.vbproj (or whatever) file.

    PS - you shouldn't need to pend changes on a directory. PendAdd("$/path/to/file.txt") will pend implicit adds on the parent dirs if they do not exist yet.

How to bind test data to a SketchFlow ComboBox?

I haven't been able to successfully bind some test data to a SketchFlow ComboBox. I added a sample data source and created a collection with some basic string values. There are a number of tutorials on how to bind to a ListBox in SketchFlow and that works fine, just not finding anything for a ComboBox.

From stackoverflow
  • It seems to work as I expected, so perhaps I'm not understanding your issue correctly, but I'll give it a shot! I created a sample DataSource with a couple of strings in it, added a ComboBox to the layout root and then just dragged the Collection from the DataSource and dropped it on the ComboBox.

    Keep in mind that if you drag the DataSource itself, you'll only be setting the DataContext property of the ComboBox and that's not enough to get your items to display. You also need the ItemsSource bound to the Collection of the DataSource and an ItemTemplate or a DisplayMemberPath to tell the ComboBox how to display your items.

    Additionally, if you use the drag and drop method of binding, it will use the ItemTemplate approach for you, which may or may not be what you want as it will generally create a StackPanel and display all fields from the row in your Collection per item in the ComboBox. You can remove the ItemTemplate and set DisplayMemberPath to whichever field you wish to have displayed from your data source's collection.

    Clay : I was doing what you described. I tried again on a new page (originally was on a page I created with a few different states that I was switching between). My new page just has a ComboBox control and a simple DataSource with just a few strings. When I run the project, I receive a runtime error "Unhandled Error in Silverlight Application AG_E_PARSER_BAD_TYPE". I just tried using DisplayMemberPath instead of the ItemTemplate but receive the same error. I appreciate the help, SketchFlow looks really promising.
    Clay : I just tried with a brand new project and the steps you described work fine now. There is apparently something else causing problems within my original project. Thanks again!
  • One thing that caught me out a few times is that you need to have your data in "list mode" before you drag it on to the control (combo box or list box).

Redirect non-www URL to www URL in conjunction with other rules

Redirecting a visitor who hits http://example.com to http://www.example.com isn't terribly difficult. But how is it done in conjunction with a RewriteRule that directs all page requests through "index.php"?

RewriteRule !\.(gif|jpg|png|css|js|php|ico|xml)$ /index.php
From stackoverflow
  • You just need to make sure that those rule, that cause an external redirect, appear before those, that cause internal rewrites. So simply:

    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    RewriteRule !\.(gif|jpg|png|css|js|php|ico|xml)$ /index.php
    
  • See the answer for this post, just do the opposite.

    <VirtualHost *:80>
        ServerName example.com/
        RedirectPermanent / http://www.example.com/
    </VirtualHost>
    
    SpoonMeiser : I was just writing something similar. I like this way because the re-directing from non-www doesn't interfere with your 'proper' virtual host at all.

Should I use passenger on Apache or Nginx?

What are the pros and cons between deploying passenger on top of Apache and Nginx?

From stackoverflow
  • Nginx is leaner than Apache and serves up static pages a bit quicker. However, you don't have the same market size that Apache has, therefore you will find less people that know Nginx.

    Apache is more resource intensive than Nginx, but you have much better module support than Nginx. Nginx doesn't have dynamically loadable modules like Apache. You have to compile them in, so updating Nginx could be a hassle if you don't keep your source files around.

    As far as Passenger goes, they are pretty much equivalent on either.

windows forms and calender field

how can we embed the calendar component in cell of a data grid view. actually my requirement is to catch the date of birth in column of one data grid view.

From stackoverflow

how to use url and jquery

i wanted to know how do you get

http://wesitename.com#overall

How to make a div show when the link is #overall ?

From stackoverflow
  • If the div has an id with the same name, then this should work:

    $("#"+location.hash).show();
    

    location.hash will get you the hash-value of a url.

    Gully : can i user it like this $("#"+location.hash == "#overview").css({"display":"none"})
    Josh : That would be if(location.hash=='#overview') $('#overview').hide();
  • use window.location. On the onLoad event of the page, parse everything after "#" in window.location.toString(), and act accordingly.

    Sinan Taifour : Or use location.hash as peirix pointed out. I didn't know about it. It is cross-browser?
    Tony Miller : Try it yourself in the browsers you are targeting: http://www.w3schools.com/HTMLDOM/prop_loc_hash.asp
    peirix : Yeah, it's been in IE since v.4, FF since v.1 and Opera since v.9...should be safe (:

Why does my jQuery fadeOut/remove get rid of the parent DOM element?

I have a list of items for example:

<li class="ui-state-default" ><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>test <a href="#" title="Delete" class="itemDelete">x</a></li>

$('.itemDelete').live("click", function() {

                $(this).parent().remove();
            });

All is ok. If I change it to

$(this).parent().fadeOut("slow", function() { $(this).parent().remove(); });

It seems to remove the <li> ok but also the <li> above it. I've tried running the fade then the remove on separate lines but that appears to the user as if its just done a remove and not the fade.

Any ideas?

From stackoverflow
  • It's an issue of what this refers to — in the callback, this is your faded element. You want:

    $(this).parent().fadeOut("slow", function() { $(this).remove(); });
    
    Jon : Thanks, I assume this in the callback is the object that has been faded?
    Blixt : @Jon: It is, yes.
  • You're removing the parent's parent. Change it to:

     $(this).parent().fadeOut("slow", function() { $(this).remove(); });
    

Why are my Validation Rules not being run when DataContext is set?

I have the following Loaded event on my Window:

void Window_Loaded(object sender, RoutedEventArgs e) {
    this.DataContext = new MyObject() {
        MyDateTime = DateTime.Now,
        MyNotEmptyString = "Not Empty",
        MyNotUpperCaseString = "not upper case",
        MyInteger = 20,
        MyIntegerInRange = 1,
        MyDouble = 4.56
    };
}

For each property initialized above, I have a TextBox that binds to it, each having its own validation rule(s) associated with it.

The problem is, my Validation Rules are not being run the very first time when this.DataContext is set, but work great when the form is used normally (they are run when the TextBox loses focus). What could be the reason behind this? I tried setting UpdateSourceTrigger="PropertyChanged", but that didn't help.

Edit: Here is an example of a TextBox that is binding to a property:

<TextBox Name="MyDoubleField">
    <TextBox.Text>
        <Binding Path="MyDouble">
            <Binding.ValidationRules>
                <local:TextIsDouble/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>
From stackoverflow
  • Is there a reason why your validation is not in your data classes? Using IDataErrorInfo should validate the data immediately and then bubble that up to your UI without having to do anything extra.

    I say should, because this works for us, but we don't use WPF.

    Pwninstein : I'm not sure if that's always possible (validation in my data classes) at all times. I'm working on a project that uses WCF and WPF, and the classes that the WPF client uses are auto-generated from the WCF Contracts. Unless there's a way to auto-generate that validation as well, I think I'm stuck doing things the way I've shown above. Please, prove me wrong!!
    TheCodeMonk : Oh, WCF changes everything. If you are getting the data from a WCF service, then you are not working directly with the datacontext. When I did my WCF to ASP.Net application, the WCF service just became a data provider and I wrote view model classes that had data validation in them. Those classes retrieved the data and use IDataErrorInfo to pass the errors to the ASP.Net pages.
  • The reason why your Validations are not being run when you set the DataContext is because WPF only runs validation when the source is updated with the value from the target (AKA, textbox is changed and the source is updated accordingly).

    If you want to validate your data when you set the DataContext you'll have to iterate the logical tree, and for every element you want to run your validation for, you'll need to get its BindingExpression and then call the binding Expression UpdateSource method. That will force a validation.

    The code to do something like that would be:

        private void ValidateData()
        {            
            //The XAML file defines a group of TextBox elements inside a Grid called grd
            foreach (UIElement uie in grd.Children)
            {
                if (uie.GetType() == typeof(TextBox))
                {
                    ((TextBox)uie).GetBindingExpression(TextBox.TextProperty).UpdateSource();          
                }
            }                    
        }
    

Call help file in .net window application

We want to know how to show related topic of help file when user click F1 on specific interface.

Thanks H N Mishra

From stackoverflow
  • If you are using windows forms, have a look at a help provider.

    Dropping one on your form will give you a ? button in the corner which you can then wire up to each control. You can even hyperlink that into a CHM file, along with any other part that you wish to do.

Looking for some clever sql strategies for dealing with a lookup table

I want to store the distance between different locations in a table.

CREATE TABLE `example` (
    `id` INT NOT NULL AUTO_INCREMENT ,
    `from` VARCHAR( 8 ) NOT NULL ,
    `to` VARCHAR( 8 ) NOT NULL ,
    `distance` DECIMAL( 6, 2 ) NOT NULL ,
    PRIMARY KEY ( `id` ) ,
    INDEX ( `from` , `to` )
 )

As a distance between two points is measured, it is inserted into the table. Getting the distance between 'from' and 'to' is obviously very easy. However the distance between 'to' and 'from' is exactly the same. I dont want to make another row just to switch the 'to' and 'from'. I would also prefer not to have to make a lookup table for this table, to accomplish this.

The sql to select the distance will be called quite a lot so it needs to be an efficient query.

I have simplified the table so don't worry about the places being varchars etc.

Anyone have any strategies they could recommend?

From stackoverflow
  • Call the locations 'A' and 'B'. If A < B, then search for A in 'from' and B in 'to', otherwise, search for B in 'from' and A in 'to'. Same logic when inserting values.

    That way you only store each combination once, and it is fast to query.

    ae : exactly the kind of solution I was after - well done
  • May I suggest something entirely different. Each point has coordinates relative to the same point, so the distances will be calculated when giving two points, and not saved in the DB.

    Now, if those are points on maps/Graph, then another solution is in place.

    Matt Howells : He didn't say that the locations had co-ordinates, nor that the distance between them is a straight line. If the locations are cities, and distance is the fastest road journey, they will certainly not be straight lines.
    Itay Moav : I mentioned graphs in my answer. Any way, the best way to store what he wants to store is not in a relational DB.

Filtering DataView with multiple columns

Hi,

In my application I am using a dataview for having the filters to be applied where the filter options are passed dynamically.if there are 2 filter parameters then the dataview should be filtered for parameter1 and then by parameter two. I am using a method which is called in a for loop where I am setting the count to the total no.of parameters selected using a listbox but the filtering is done only for the last parameter. Here is my code:

string str = "";
for (int i = 0; i < listbox.Items.Count; i++)
{
    if (listbox.Items[i].Selected)
    {
     if (str != string.Empty)
     {
      str = str + "," + listbox.Items[i].Text;

     }
     else
     {
      str = str + listbox.Items[i].Text;
     }
    }
}

string[] items = str.Split(',');
for (int i = 0; i < items.Length; i++)
{
    ApplyFilter(items[i],dv);
}

private DataView ApplyFilter(string str,DataView newdv)
{
    newdv.RowFilter = "[" + str + "]=" + ddl.SelectedItem.ToString();

    return newdv;
}

Please provide a suitable solution .

Thanks in advance...

From stackoverflow
  • You should apply your filter altogether, not one by one :

    newdv.RowFilter = "Column1 = " + value1 + " AND Column2 = " + value2;
    

    So you can change your code as :

    string[] items = str.Split(',');
    string filter = string.Empty;
    for (int i = 0; i < items.Length; i++)
    {
        filter += items[i] + " = " + dropdown.SelectedValue;
        if (i != items.Length - 1)
        {
             filter += " AND ";
        }
    }
    newdv.RowFilter = filter;
    
  • I think you should build a complete filter string and then set this filter to your DataView. For example:

    
    StringBuilder sb = new StringBuilder()
    for (int i = 0; i < listbox.Items.Count; i++) {
      if (!listbox.Items[i].Selected) {
        continue;
      }
    
      if (sb.Length > 0) {
        sb.Append(" and ");
      }
      sb.AppendFormat("[{0}] = {1}", listbox.Items[i].Text, ddl.SelectedItem);
    }
    
    dv.RowFilter = sb.ToString();
    

MSBuild specify platform for build

Hi,

Is it possible to specify the target platform (x64, x86) when building a project?

I have a build task that looks as follows:

<MSBuild Projects="%(AgentProjectFiles.FullPath)" Properties="Architecture=x86;Configuration=$(Configuration);Optimize=$(Optimize);Platform=$(Platform);OutputPath=$(OutputDirectory)\Agent\;ReferencePath=$(ReferencePath);DebugSymbols=$(DebugSymbols);DebugType=none;" />

As you can probably tell, I've thrown everything possible I have seen online into the Properties attribute in the hope that it will work. You will notice that for the Architecture property I've set it to be x86 explicitly. the $(Platform) is also set to x86. I've tried a number of permutations, without success.

Unfortunately, it seems that no matter what gets put into these properties, my class libraries are x86, but my executables are x64.

I thought perhaps the problem could be that the build properties specified in the project file itself were causing MSBuild to ignore the ones I pass through from MSBuild, but after changing these to x86, I still have the same problem.

Any ideas?

Thanks in advance.

From stackoverflow
  • In the declaration of the AgentProjectFiles item are you defining the Properties metadata. So does it look like:

    <ItemGroup>
        <AgentProjectFiles Include="something.proj">
            <Properties>SOME VALUES HERE</Properties>
        </AgentProjectFiles>
    </ItemGroup>
    

    If you have defined that then the properties passed into the Properties attribute of the MSBuild task are ignored. I've bloged about this MSBuild: Properties and AdditionalProperties Known Metadata.

    tardomatic : THANK YOU!!! (excuse the caps, but ive been hitting my head against the wall for a few hours with this.) I changed my ItemGroup to define the properties as you have above, and my assemblies are now being created for the correct platform.
    Pete Montgomery : I don't really believe this is the truth. Thank you Sayed.

How do I best get the top 2 unique rows when a JOIN is involved?

I have this query:

select top(2)
    property_id_ref
    ,image_file
    ,property_name 
from property_master a 
inner join image_master b 
    on a.property_id=b.property_id_ref 
inner join customer_master c 
    on a.customer_id=c.customer_id

When I execute it, I get the following result:

512 ~/propertyimg/3954493 id_1.jpg Commercial Land 
512 ~/propertyimg/3954493.jpg Commercial Land

But I need the output distinct property_id_ref with random image_file from the property_id_ref like this:

512 ~/propertyimg/3954493 id_1.jpg Commercial Land 
513 ~/propertyimg/3119918 Id.jpg Residential Plot

For that I made a query like:

select top(2) 
    max(pm.property_name) as property_name
    ,max(im.property_id_ref) as property_id_ref
    ,CONVERT(varchar(5000),  max( CONVERT(binary, im.image_file))) as image_file 
from property_master pm
inner join image_master im
    on pm.property_id=im.property_id_ref 
inner join customer_master cm
    on pm.customer_id=cm.customer_id 
group by im.property_id_ref

So I got the same output as the one I expected. I want to know whether this is the right way to do it, or is there any other better way of doing the same thing?

I am using SQL Server 2005.

From stackoverflow
  • The way you do is the right one. An group by of the ID_Ref and a random member by max. It's completly OK and I see no reason why to change it.

    Blixt : I disagree... There are unnecessary aggregate functions and conversions going on in there. This can be done with `ROW_NUMBER()` in SQL Server 2005, or joining to a sub-query in earlier versions of SQL Server. I was looking for a third, better solution I can't remember, but I can't find it. Maybe someone else remembers it though.
  • If you really only have that query you posted in example, this will work fine:

    SELECT TOP (2)
        pm.property_id,
        pm.property_name,
        (SELECT TOP 1 image_file
         FROM image_master
         WHERE property_id_ref = pm.property_id) AS image_file
    FROM
        property_master pm
    -- This is only needed if it's possible that [image_file] can be NULL and you
    -- don't want to get those rows.
    WHERE
        EXISTS (SELECT * FROM image_master
                WHERE property_id_ref = pm.property_id)
    

    I assume your query is more complex than that though, but I can't give you a more specific query unless you post your real query.

SSIS Package Troubleshooting

I'm working with an SSIS Package that pulls data from a DB2 source, runs through a conversion process (unicode stuff) and then stores the data in a SQL table. From the error information below, I have been able to determine that there is some kind of special characters in the DB2 file/table. What I do not know is how I can narrow down which specific record has the issue. There are about 200,000 records in the DB2 file and I need to know which one is specifically causing the issue.

Is there a way to query the DB2 source looking for "special characters"? Is there a way to have the SSIS package show me which record it is failing on?

Error: 2009-07-15 01:32:31.19
Code: 0xC020901C
Source: Import MY APP Data DETAIL [2670]
Description: There was an error with output column "COLUMN1" (2710) on output "OLE DB Source Output" (2680). The column status returned was: "Text was truncated or one or more characters had no match in the target code page.".

From stackoverflow
  • DB2 has a built-in function called HEX() that takes in just about any expression of any type and returns a VARCHAR of the hex representation of each byte. You can also specify any binary value as a literal by prepending it x', for example: x'0123456789abcdef'

    If the problem is coming from a single-byte character, you could find it by building up temp table of all single characters from x'00' to x'ff' and seeing which ones appear in each row of your DB2 data. You could also add some code to the utility that converts the data for Unicode so it will scan the DB2 records for any anomalies.

    RSolberg : Thanks, I'll run this by our DB2 folks tomorrow morning.

How to build iphone apps using .Net on windows?

Are there any tools (emulators, IDE) which can help you develop iphone apps using .Net on windows and then publish to iTunes?

From stackoverflow
  • You can't, especially if you want to publish to iTunes. The iPhone only runs Objective-C.

  • None that are viable at this point.

  • Mono are working on porting their .Net runtime to the iPhone, which will be available for testing next month.

    Unity is a game development platform for the iPhone that uses C# and .Net.

    ScottSEA : System Requirements for Unity iPhone Authoring * An Intel-based Mac * Mac OS X "Leopard" 10.5.4 or later * Using Occlusion Culling requires NVIDIA or ATI graphics card * The rest only depends on the complexity of your projects!
    Kevin L. : Mono on iPhone was actually discussed in SO Podcast #61 (see the fifth bullet point): http://blog.stackoverflow.com/2009/07/podcast-61
    a_hardin : MonoTouch is not available to develop C# apps for the iPhone.
  • Not only can you not use .Net on an iPhone, you also need an Intel Mac to do development. Apple is keeping it a very closed environment, and because they control everything from the hardware to the OS to the distribution channels, you really don't have any other choice than to play by their rules.

Managing XML files in a Visual Studio project (2 instances)

Managing XML files in a Visual Studio project (2 instances)

If I add an XML file to my VS project it at the root level of the project with the source files. But then if I want to test or build I need a copy down in the bin directory. Of course I always end up editing the one at the root level that is in VS and then I go to test and am using a different file (one in the bin directory).

Is there a good way to either point the file being edited to the bin file or to always copy when I go to debug (or some other good solution)?

From stackoverflow
  • On the properties pane when you have the file selected, choose "Always copy" (or whatever it is) for the Copy to Output Directory setting.

How do I sudo environment?

I am using spamassassin in a php script, but when I train spamassassin as my user the php script's exec command to call spamassassin get the untrained version because of the user specific nature of sa-learn. So I need to sudo to my user in the exec command and get the environment of my user along with the premissions

From stackoverflow
  • sudo -u <username> <command> ...
    
    kman99 : Tried that uses the prefence files of the users calling sudo not the user in sudo
  • sudo -H -u <username> <command>
    

    The -H flag sets the $HOME environment variable. Without setting this flag, SpamAssassin is probably looking in the old user's homedir for settings.

How to emulate 'cp --update' behavior on Mac OS X?

The GNU/Linux version of cp has a nice --update flag:

-u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing

The Mac OS X version of cp lacks this flag.

What is the best way to get the behavior of cp --update by using built-in system command line programs? I want to avoid installing any extra tools (including the GNU version of cp).

From stackoverflow
  • rsync has an -u/--update option that works just like GNU cp:

    $ rsync -u src dest
    

Do not want Error Provider to check control validation until save event

I am writing a User Control. Into each control I am loading a custom biz object. Because the biz object implements IDataErrorInfo interface I am able to use the ErrorProvider control on the user control.

I am binding the ErrorProvider to the biz object like this:

Me.ErrorProvider1.DataSource=MyBizObject

This is all working perfectly EXCEPT. The validation is happening (and therefore I am displaying the blinkey error signs next to all feilds) as soon as the User control is loaded into the host form.

Each biz object implements a SAVE method and I want the validate to not happen until the save event is triggered on the biz object.

What is best practice for accomplishing this??

Seth

From stackoverflow
  • I don't know if this was the best way or not...but what I did was not assign the ErrorProvider.DataSource UNTIL the Save Event for the control.

    This is working for now.

    Seth

Where can I find a time range widget in Javascript/jQuery?

Hi,

I'm looking for some sort of TimeRange widget in Javascript/CSS/jQuery. I'm not looking for a time/date picker, which are widely available.

I need it for a website to allow businesses to select their openinghours by clicking and hovering over the hours they're open.

+-----------------------------+
| 0h 0h15m 0h30m    ... 23:45 |
+-----------------------------+

Anybody has seen such a nice looking customizable timerange selector widget?

Cheers

From stackoverflow
  • Google Calendar has nice one (you can see it when you click "Check guest and resource availability" link on the event details form). But I can imagine it would be hard to clone.

    Google Calendar Time Ranage

    javacoder : Thanks for the screenshot! That's exactly what I'm looking for, in a more compact form. I can't image it doesn't already exist, eg. as a pluggable jQuery widget.
  • I'd look for a slider widget.. then set the times you need as the intervals.

    The jQuery UI has one: jQuery UI Slider.

    Update: based on the comment below about (single vs. double slider)...

    1.) Theres a post already (just found) about making a 2 handled slider using the jQuery UI slider here.

    Or if you have 2 sliders... one for opening time and one for closing... where each is broken down into 15min segments, but only for half a day each, would this work?

    e.g. (ignore the ASCII-graphic uglyness)

     Open Time (AM): 12   1    2    3    4    5    6    7    8 |  9    10   11   12
                                                               ^ 8:15am
    
    Close Time (PM): 12   1    2    3    4    5    6  |  7    8    9    10   11   12
                                                      ^6:30pm
    

    Furthermore, if this is for "typical" businesses... you could likely chop from 11pm <-> 5am from the sliders.

    Or,

    I'm not a big fan of scriptaculous, but they seem to have a double slider:

    javacoder : I thought about that as well, but that wouldn't really work as we don't know how many regions there are from the start. Eg. A business could be open from 8am-10am, 12-14am and 18-20am. Moreover, as I understand from the documentation, there's a max of one range per slider it seems. This is an example I found with ticks: http://jsbin.com/iwime
    javacoder : Thanks scunliffe, I'm resorting to this not-so-flexible solution, until a widget emerges!

Execute code at end of Module/Class, like Ruby test/unit

Ruby's unit testing framework executes unit tests even though nobody creates unit test object. For example,

in MyUnitTest.rb

require 'test/unit'

class MyUnitTest < Test::Unit::TestCase
    def test_true
        assert true
    end
end

and when i invoke that script as

ruby MyUnitTest.rb

test_true method gets executed automatically. How is this done?

I am trying to come up with a framework that can do similarly. I dont want "if __ FILE __ == $0" at the end of every module that uses my framework.

thanks.

From stackoverflow
  • Test::Unit uses at_exit for this, which runs code immediately before your application quits:

    at_exit do
      puts "printed before quit"
    end
    
    .. other stuff
    

    I don't think there is any way to run code specifically after a class or module definition is closed.

    rampion : but you can redefine `Class.inherited` for your class to get references to all the subclasses, and then play with them in your `at_exit` hook.
  • Similar to Daniel Lucraft's answer, you could define a finalizer guard to have some code run when the garbage collector runs:

    ObjectSpace.define_finalizer(MyClass, lambda {
      puts "printed before MyClass is removed from the Object space"
    })
    

    But personally I think at_exit is a better fit since its timing is a bit more deterministic.

Delphi 2009 command line compiler using dcc32.cfg?

Hi,

In Delphi 2009, how can I build a project using command line. I tried using the command line compiler and supplying -a -u -i -r in dcc32.cfg file. But compiler is not recognizing the paths and throwing the error required package xyzPack is not found.

    -aWinTypes=Windows;WinProcs=Windows;DbiProcs=BDE;DbiTypes=BDE;DbiErrs=BDE
    -u"C:\MyProj\Output\DCP"
    -i"C:\MyProj\Output\DCP"
    -r"C:\MyProj\Output\DCP"

and on command line i execute the command :

    dcc32 "C:\MyProj\MyProject.dpr" -B -E"c:\MyProj\Output\EXE"

What am I doing wrong here?

Thanks & Regards, Pavan.

From stackoverflow
  • Instead of invoking the compiler directly, consider using MSBuild on your .dproj, since that's what the IDE uses. http://stackoverflow.com/questions/558147/delphi-msbuild-build-configuraions-from-command-line might help you with that.

  • From the related answer (as shown below) ie:

    http://stackoverflow.com/questions/1006831/compiling-with-delphi-2009-from-a-command-line-under-windows-vista-64-bit

    I notice that you should be able to build a single package from the command line this way. I have used batch files (buildall.cmd) to launch dcc32, and have not yet used msbuild.

    I have ultimately found both approaches frustrating, and have instead decided to opt for building a little GUI shell (a lite version of Final Builder, if you like) that basically works as a semi-graphical semi-command-line way of automating my builds and filtering the compiler output to produce results. I would be highly interested in anyone else's experiences with "tinder box" (daily or even continuous build) operations with Delphi.

    You may end up where I'm heading... just buy Final Builder. :-)

how to change the bar color in bar charts

hi All, how to change the bar chart color in bar charts?

Thanks, AravindakumarThangaraju

From stackoverflow
  • <?xml version="1.0"?>
    
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
      <mx:Script><![CDATA[
         import mx.collections.ArrayCollection;
         [Bindable]
         public var expenses:ArrayCollection = new ArrayCollection([
            {Month:"Jan", Profit:2000, Expenses:1500},
            {Month:"Feb", Profit:1000, Expenses:200},
            {Month:"Mar", Profit:1500, Expenses:500}
         ]);
      ]]></mx:Script>
      <mx:Panel title="Bar Chart">
         <mx:BarChart id="myChart" dataProvider="{expenses}" showDataTips="true">
            <mx:verticalAxis>
               <mx:CategoryAxis 
                    dataProvider="{expenses}" 
                    categoryField="Month"
               />
            </mx:verticalAxis>
            <mx:series>
               <mx:BarSeries 
                    yField="Month" 
                    xField="Profit" 
                    displayName="Profit"
                >
                <mx:stroke>
                    <mx:Stroke 
                        color="0x808080" 
                        weight="2" 
                        alpha=".8"
                    />
                </mx:stroke>
               </mx:BarSeries>
               <mx:BarSeries 
                    yField="Month" 
                    xField="Expenses" 
                    displayName="Expenses"
               >
                <mx:stroke>
                    <mx:Stroke 
                        color="0xC0C0C0" 
                        weight="2" 
                        alpha=".8"
                    />
                </mx:stroke>
               </mx:BarSeries>
            </mx:series>
         </mx:BarChart>
         <mx:Legend dataProvider="{myChart}"/>
      </mx:Panel>
    </mx:Application>
    
    aravindakumarThangaraju : thanks shua.but i need not like thatplease go through this like i need like that type of bar charts http://img200.imageshack.us/img200/1666/barcharts.png Thanks, aravindakumarThangaraju
    Shua : ok.... check out http://demo.quietlyscheming.com/ChartSampler/app.html and look at the customization -> per column colors
    aravindakumarThangaraju : Thanks Shua.It's very usefull for me and thank for your Patience.i have one more question there is any way to without using xml to load color dynamically?
    Shua : no prob. but I'm not sure what you mean by not using xml because the example uses and array to determine the fill colors. Make sure you are looking at the PerColumnFill Class in the examples.customizing Package. The fill Array has all the colors used
    Ravi K Chowdary : @Aravinda: - please help me out the same for me also. I also need same example. Thanks

Wait for bash background jobs in script to be finished

To maximize CPU usage (I run things on a Debian Lenny in EC2) I have a simple script to launch jobs in parallel:

#!/bin/bash

for i in apache-200901*.log; do echo "Processing $i ..."; do_something_important; done &
for i in apache-200902*.log; do echo "Processing $i ..."; do_something_important; done &
for i in apache-200903*.log; do echo "Processing $i ..."; do_something_important; done &
for i in apache-200904*.log; do echo "Processing $i ..."; do_something_important; done &
...

I'm quite satisfied with this working solution, however I couldn't figure out how to write further code which only executed once all of the loops have been completed.

Is there a way to get control of this?

From stackoverflow
  • There's a bash builtin command for that.

       wait [n ...]
              Wait for each specified process and return its termination  sta‐
              tus.   Each  n  may be a process ID or a job specification; if a
              job spec is given, all processes  in  that  job’s  pipeline  are
              waited  for.  If n is not given, all currently active child pro‐
              cesses are waited for, and the return  status  is  zero.   If  n
              specifies  a  non-existent  process or job, the return status is
              127.  Otherwise, the return status is the  exit  status  of  the
              last process or job waited for.
    
    mark : That was quick and solved my problem, well earned, thanks!

Use of ebay API

I am given a task to R& D ebay api. As i have tried to explore on net i still have no clear idea that how and why to use it in my apps. Also are there many ebay api's for different purposes? Any sample code available using this api in objective c for iPhone. Any doc available providing general info about it.

From stackoverflow
  • You can find this information on eBay's developer site. They have a pretty good explanation of the various API's they offer as well as sample code and plenty of documentation. You can sign up for a free account and get a sandbox to play in as well.

how do I create an enum from a string representation? c#

im trying to pass back from a user control a list of strings that are part of an enum, like this:

<bni:products id="bnProducts" runat="server" ProductsList="First, Second, Third"  />

and in the code behid do something like this:

public enum MS 
    {
     First = 1,
     Second,
     Third
    };
    private MS[] _ProductList;
    public MS[] ProductsList
    {
     get
     {
      return _ProductList;
     }
     set
     {
      _ProductList = how_to_turn_string_to_enum_list;
     }
    }

my problem is I dont know how to turn that string into a list of enum, so what should be "how_to_turn_string_to_enum_list"? or do you know of a better way to use enums in user controls? I really want to be able to pass a list that neat

From stackoverflow
  • You need to look at the System.Enum.Parse method.

    Best Regards

    Ayyash : this one "or"s the values passed, not what im looking for
    Oliver Hanappi : What do you mean exactly? Of course this method just converts one single value to an Enum, you need to loop through all and apply the method on each element ;)
  • string[] stringValues = inputValue.Split(',');
    
    _ProductList = new MS[stringValues.Length];
    
    for (int i=0;i< stringValues.Length;i++)
      _ProductList[i] = (MS) Enum.Parse(typeof(MS), stringValues[i].Trim());
    

    (updated my code because I misread your code)

  • Enum.Parse is the canonical way to parse a string to get an enum:

    MS ms = (MS) Enum.Parse(typeof(MS), "First");
    

    but you'll need to do the string splitting yourself.

    However, your property is currently of type MS[] - the value variable in the setter won't be a string. I suspect you'll need to make your property a string, and parse it there, storing the results in a MS[]. For example:

    private MS[] products;
    
    public string ProductsList
    {
        get
        {
            return string.Join(", ", Array.ConvertAll(products, x => x.ToString()));
        }
        set
        {
            string[] names = value.Split(',');
            products = names.Select(name => (MS) Enum.Parse(typeof(MS), name.Trim()))
                            .ToArray();
        }
    }
    

    I don't know whether you'll need to expose the array itself directly - that depends on what you're trying to do.

    Hans Kesting : eh, Enum.Parse needs a Type if I am not mistaken? MS ms = (MS)Enum.Parse(typeof(MS), "First");
    Jon Skeet : Oops, thanks :)
    Ayyash : you're right, it sould be a string, i would combine this answer with "280Z28" answer above because i think the CovertAll is more elegent, thanks
  • This is a short solution, but it doesn't cover some very important things like localization and invalid inputs.

    private static MS[] ConvertStringToEnumArray(string text)
    {
        string[] values = text.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
        return Array.ConvertAll(values, value => (MS)Enum.Parse(typeof(MS), value));
    }
    
    Jon Skeet : +1 for validation. From the example, localization isn't much of an issue because this isn't user-supplied data - it's in the page code.
  • Mark your enum with the [Flags] attribute, and combine flags instead of an array of enum values.

    Jon Skeet : That's not always valid. For instance, HTTP response codes aren't *logically* flags - but you might have a collection of them (e.g. "I handle these response codes"). Don't rush to use flags for enums which aren't logically flags.

Set authentication request prop in j2me works?

Hi, I have followed the answer to http://stackoverflow.com/questions/950885/http-authentication-in-j2me by setting the request property for HttpConnection object with

setRequestProperty("Authorization", "Basic "+ encodedUserAndPass)

but it didn't work.

  • When make request to Http protocol -> 401 Unauthorized
  • When make request to Https protocol -> javax.microedition.pki.CertificateException: Certificate was issued by an unrecognized entity.

Has anyone have the problem solved? Thanks in advance.

From stackoverflow
  • You probably have two separate problems

    1) Make sure you have Base64 encoded the details

    2) For ssl make sure the certificate you are using on the webserver is signed by an authority that there is an appropriate root certificate installed for on the device you are testing with