Friday, April 15, 2011

Java bean machine

Here is what I'm suppose to accomplish:

Write a program that stimulates a bean machine Your program should prompt the user to enter the number of balls and the number of slots in the machine. Simulate the falling of each ball by printing its path.


Enter the number of balls: 5
Enter the number of slots: 7

_ _ 0
_ _ 0
0 0 0

Here is my code so far:

import javax.swing.JOptionPane;        
public static void main(String[] args) {
            int balls=0;
            int slots=0;
            char [] direction= new char [slots];
            int slot=0;
            int i=0;
            int path=0;

            balls= Integer.parseInt(JOptionPane.showInputDialog("Enter" +
                    " the number of balls to be dropped:"));
            slots= Integer.parseInt (JOptionPane.showInputDialog("Enter " +
                    "the number of slots:"));

            for (int j=1;j<=balls;j++){
                    path= (int)(Math.random()*100);
                    if (path <50){
                        direction [slots]='L';
                        direction [slots]='R';
            System.out.println("The pathway is" +direction[0]+direction[1]+direction[2]+direction[3]+direction[4]);


There are a few things that I'm having problems with:

  1. In the last line of my code where I try to print the pathway I have to basically guess the number of slots the user selected. Is there a better way to print this?

  2. How can I print the number 'balls' that the user entered in the pattern as shown above?

  3. Are there any other problems with my code?

From stackoverflow
  • Well, for starters, I'm getting a consistent ArrayIndexOutOfBoundsException on the line direction[slots] = 'L'; (or 'R'). That's because direction is always of length 0, since you initialized it to slots when slots was 0. Move the line

    char [] direction= new char [slots];

    to after slots is input.

    Next, you always assign the 'L' or 'R' to the position immediately after the end of the array. That's another reason for the ArrayIndexOutOfBoundsException I was getting. Change the assignment to

    direction[i] = 'L'; // or 'R'

    Next, you don't reset i after the while loop. So the path is calculated only for the first ball and then reused for all the others. I would make it a for loop instead, like this:

    for (i = 0; i < slots; i++) {
        // your code here (make sure you don't change i inside the loop)

    Finally, as others have said, you should be using a loop to print out the path. You know how long the direction array is (it's direction.length, if you didn't know), so you can just loop through it and print out each letter.

    Once you've made these changes, your program should work (edit: except that it doesn't keep track of which slot each ball ends up in). It will still have some room for improvement, but finding those things is part of the fun--isn't it?

    에이바 : Thanks for your help I'm working on fixing it right now.
  • In the last line of my code where I try to print the pathway I have to basically guess the number of slots the user selected. Is there a better way to print this?

    Use a for loop, and System.out.print() so you don't get a new line after each step.

    How can I print the number 'balls' that the user entered in the pattern as shown above?

    For each slot, you need to record the number of balls which ended up in that slot, and the maximum for any slot. Given these two values, you can loop over each slot, and print '_' or '0' the appropriate number of times with a nested loop.

    Are there any other problems with my code?

    You only appear to be printing the path of the last ball dropped, rather than each ball, but that might just be your indentation being squiffy. Post properly formatted, complete code.

    The example output you have seems to be reading input from the console, not using swing.

    You're declaring variables too early. It's better to declared variables on first use, and if they don't change mark them final. If you had:

    final int slots= Integer.parseInt (...

    instead of

    int slots = 0;
    slots= Integer.parseInt (...

    then at least one of your bugs would be caught by the compiler.

  • Some answers:

    1. Think for loop again. System.out.print or System.out.printf will help.
    2. System.out.println("Number of balls: "+ something that makes an int into a string (what would that be?)
    3. Why are you putting the result of Math.random() into an int? What would happen if you used:

      if(Math.random() < 0.5) { // do something
      } else { // do the opposite
      } thread monitoring from another page

In 2.0 , c#.

Is it possible to start a thread from a page, for example when a asp:button is clicked and from another page, check if that thread has exited?

Reason: We have a page that starts a long server-side script when a button is clicked. However, since we don't want to wait the ending of the script on that page, we thought about creating a thread that executes the script, then get the thread ID and redirect the user on a 'Please wait' page that refresh check every 5 seconds to check if the thread has exited.

Any better idea on how to achieve that?

Thank you!

From stackoverflow
  • This can be done, but I would use Ajax to make the experience better, however.

    Basically, you would call your method and it would return the identifier for the thread. It doesn't have to be the thread id, but you need some sort of unique identifier that can be passed between pages/calls.

    Before you return from that call/page, you would execute your thread.

    Then, when your client checks on the status, it would check the session, or some other shared state, which would have the result keyed on the id you returned earlier.

    If it finds a value corresponding to the key, then it displays the result (and removes the result from the shared state), otherwise, it checks again in a specified period of time.

  • There is already an approach built into ASP.NET to do this sort of thing - it is the Asynchronous page model. There are 2 ways that this can be implemented and you can find details on them here with all the benefits explained.

mysqldb on python 2.6

I am currently using python 2.6 and I would like to use the win32 mysqldb module. Unfortunately it seems it needs the 2.5 version of Python. Is there any way to get rid of this mismatch in the version numbers and install mysqldb with python 2.6?

From stackoverflow
  • You can try this mysql package, which has a 2.6 version:

    PierrOz : is there a package for windows ?
    Manzabar : The page coonj linked to indicates there is. You should be able to install the package using easy_install. Go to for details on using easy_install.
    Therms : No it doesnt. There are only linux packages there.
  • There are versions of mysqldb for python 2.6, they're just not available on the official site. It took me a while (and unfortunately I lost the link) but you can search google and find people who have compiled and released 2.6 versions of mysqldb for windows x64 and x32.


    That fourm has a link to versions of mysqldb for Python 2.6

    flybywire : The links take to which I tried and was satisfied with on 29th Nov 09
  • This one has both 32 and 64 versions for 2.6:

C#: Accessing Inherited Private Instance Members Through Reflection

I am an absolute novice at reflection in C#. I want to use reflection to access all of private fields in a class, including those which are inherited.

I have succeeded in accessing all private fields excluding those which are inherited, as well as all of the public and protected inherited fields. However, I have not been able to access the private, inherited fields. The following example illustrates:

class A
    private string a;
    public string c;
    protected string d;

class B : A
    private string b;

class test
    public static void Main(string[] Args)
        B b = new B();       
        Type t;
        t = b.GetType();
        FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic
                                         | BindingFlags.Instance); 
        foreach(FieldInfo fi in fields){

This fails to find the field B.a.

Is it even possible to accomplish this? The obvious solution would be to convert the private, inherited fields to protected fields. This, however, is out of my control at the moment.

From stackoverflow
  • You can't access the private fields of A using the type of B because those fields don't exist in B - they only exist in A. You either need to specify the type of A directly, or retrieve it via other means (such as getting the base class from the type of B).

    Timwi : Rubbish, of course they exist in B. If they weren't in B, how could a method inherited from A that accesses such a private field work?
    Andy : The instance of B may have A's private members, but the Type of B has no knowledge of such members.
  • I haven't tried it, but you should be able to access the base type private members through the Type.BaseType property and recursively accumulate all the private fields through the inheritence hierarchy.

  • As Lee stated, you can do this with recursion.

    private static void FindFields(ICollection<FieldInfo> fields, Type t) {
     var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
     foreach (var field in t.GetFields(flags)) {
      // Ignore inherited fields.
      if (field.DeclaringType == t)
     var baseType = t.BaseType;
     if (baseType != null)
      FindFields(fields, baseType);
    public static void Main() {
     var fields = new Collection<FieldInfo>();
     FindFields(fields, typeof(B));
     foreach (FieldInfo fi in fields)
      Console.WriteLine(fi.DeclaringType.Name + " - " + fi.Name);
    Timwi : Instead of the "if" clause to ignore inherited fields, you could just specify BindingFlags.DeclaredOnly.
  • You can access private members of Class A from Class B with 'Nested Classes' . You make Class A as Outer Class and Class B as Inner Class

    Class A { ... Class B { ....... }


    Odrade : I'm not able to modify the classes. I'm just trying to garner info about them via reflection.

Why does an SWT Composite sometimes require a call to resize() to layout correctly?

Sometimes we encounter an SWT composite that absolutely refuses to lay itself out correctly. Often we encounter this when we have called dispose on a composite, and then replaced it with another; although it does not seem to be strictly limited to this case.

When we run into this problem, about 50% of the time, we can call pack() and layout() on the offending composite, and all will be well. About 50% of the time, though, we have to do this:

Point p = c.getSize();
c.setSize(p.x+1, p.y+1);

We've had this happen with just about every combination of layout managers and such.

I wish I had a nice, simple, reproduceable case, but I don't. I'm hoping that someone will recognize this problem and say, "Well, duh, you're missing xyz...."

From stackoverflow
  • Looks to me like the layout's cache is outdated and needs to be refreshed.

    Layouts in SWT support caches, and will usually cache preferred sizes of the Controls, or whatever they like to cache:

    public abstract class Layout {
        protected abstract Point computeSize (Composite composite, int wHint, int hHint, boolean flushCache);
        protected boolean flushCache (Control control) {...}
        protected abstract void layout (Composite composite, boolean flushCache);

    I'm relatively new to SWT programming (former Swing programmer), but encountered similar situations in which the layout wasn't properly updated. I was usually able to resolve them using the other layout methods that will also cause the layout to flush its cache:

    layout(boolean changed)
    layout(boolean changed, boolean allChildren)

    Hope that helps...

    Jared : +1 and accepted. Wish I could +10 this one :P
  • A composite's layout is responsible for laying out the children of that composite. So if the composite's size does not change, but the relative positions and sizes of the children need to be updated, you call layout() on the composite. If, however, the size or position of the composite itself needs to be updated, you will have to call layout() on its parent composite (and so on, until you reach the shell).

    A rule of thumb: If you have added or removed a control, or otherwise done something that requires a relayout, walk up the widget hierarchy until you find a composite with scrollbars and call layout() on it. The reason for stopping at the composite with scrollbars is that its size will not change in response to the change - its scrollbars will "absorb" that.

    Note that if the change requiring a layout is not a new child, or a removed child, you should call Composite.changed(new Control[] {changedControl}) before calling layout.

  • In the meantime I learned a little more about SWT's shortcomings when changing or resizing parts of the control hierarchy at runtime. ScrolledComposites and ExpandBars need also to be updated explicitely when the should adapt their minimal or preferred content sizes.

    I wrote a little helper method that revalidates the layout of a control hierarchy for a control that has changed:

    public static void revalidateLayout (Control control) {
     Control c = control;
     do {
      if (c instanceof ExpandBar) {
       ExpandBar expandBar = (ExpandBar) c;
       for (ExpandItem expandItem : expandBar.getItems()) {
         .setHeight(expandItem.getControl().computeSize(expandBar.getSize().x, SWT.DEFAULT, true).y);
      c = c.getParent();
     } while (c != null && c.getParent() != null && !(c instanceof ScrolledComposite));
     if (c instanceof ScrolledComposite) {
      ScrolledComposite scrolledComposite = (ScrolledComposite) c;
      if (scrolledComposite.getExpandHorizontal() || scrolledComposite.getExpandVertical()) {
        .setMinSize(scrolledComposite.getContent().computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
      } else {
     if (c instanceof Composite) {
      Composite composite = (Composite) c;
      composite.layout(true, true);
    Jared : Yeah - I've had to do that before - it's a pain. It wouldn't hurt to phrase this as a separate question and answer, for searchability's sake.

Problem injecting a VB parameter into a stored procedure (FireBird)

Everyone here has always been such great help, either directly or indirectly. And it is with grand hope that this, yet again, rings true.

For clarification sakes, the Stored Procedure is running under FireBird and the VB is of the .NET variety

I have a stored procedure (excerpt below, important bit is the WHERE)

  select pn, pnm.description, si_number, entry_date, cmp_auto_key, 
  parts_flat_price,    labor_flat_price, misc_flat_price, woo_auto_key, 
  from parts_master pnm, wo_operation woo
 where pn like :i_pn || '%'
   and pnm.pnm_auto_key = woo.pnm_auto_key
  into :pn, :description, :work_order, :entry_date, :cmp, :parts_price,
       :labor_price, :misc_price, :woo, :wwt

I am trying to pass a parameter from a vb app, that uses the parameter I_PN, the code of which follows below (The variables for MyServer and MyPassword are determined form an earlier part of the code.)

        Dim FBConn As New FirebirdSql.Data.FirebirdClient.FbConnection()
        Dim FBCmd As FirebirdSql.Data.FirebirdClient.FbCommand

        Dim MyConnectionString As String
        MyConnectionString = _
        "datasource=" & MyServer & ";database=" & TextBox4.Text & "; & _
        user id=SYSDBA;password=" & MyPassword & ";initial catalog=;"

        FBConn = New FirebirdSql.Data.FirebirdClient. & _

        FBConn.CreateCommand.CommandType = CommandType.StoredProcedure

        FBCmd = New FirebirdSql.Data.FirebirdClient. & _
        FbCommand("WIP_COSTS", FBConn)

        FBCmd.CommandText = "WIP_COSTS"

        FBConn.CreateCommand.Parameters. & _
        Add("@I_PN", FirebirdSql.Data.FirebirdClient.FbDbType.Text). & _
        Value = TextBox1.Text

        Dim I_PN As Object = New Object()
        Me.WIP_COSTSTableAdapter.Fill(Me.WOCostDataSet.WIP_COSTS, @I_PN)
    Catch ex As System.Exception
    End Try

When I execute the VB.App and try to run the program, I get the following Error:

Dynamic SQL Error
SQL Error Code = -206
Column Unknown
At Line 1, column 29

And I can't quite put my finger on what the actual problem is. Meaning, I don't know if my logic is incorrect on the VB side, or, on the Stored Procedure.

Any coding that is included is kludged together from examples I have found with various bits of code found during long sojourns of GoogleFu.

As anyone with more than a month or two of experience (unlike me) with VB can attest with merely a glance - my code is probably pretty crappy and not well formed - certainly not elegant and most assuredly in operational. I am certainly entertaining all flavors of advice with open arms.

As usual, if you have further questions, I will answer them to the best of my ability.

Thanks again.


From stackoverflow
  • Can you show entire stored procedure here? What version of Firebird do you use?

  • Try changing this:

    FBConn.CreateCommand.Parameters. & _
            Add("@I_PN", FirebirdSql.Data.FirebirdClient.FbDbType.Text). & _
            Value = TextBox1.Text

    ... to this:

    FBCmd.Parameters.AddWithValue("@I_PN", TextBox1.Text)

    Basically, you want to add stored procedure parameters to the Command object, not the Connection object.

    Jasoomian : HardCode - still no joy. Still receiving the same error at run time.
    HardCode : I don't know the syntax of Firebird's SPs, but this statement - where pn like :i_pn || '%' - looks like it is saying "LIKE the parameter OR %" - instead of - "LIKE the parameter concatenated with %". Should it maybe be "where pn like :i_pn + '%'"
    Jasoomian : In Firebird, the || is the concatenation character, so, the code is already doing what you suggested (at least in that manner.)
  • Andreik,

    Here is the entire stored Procedure. And our Firebird is Version 1.5.3, written with IbExpert version 2006.12.13, Dialect 3

    select pn, pnm.description, si_number, entry_date, cmp_auto_key, parts_flat_price,
           labor_flat_price, misc_flat_price, woo_auto_key, wwt_auto_key
      from parts_master pnm, wo_operation woo
     where pn like :i_pn || '%'
       and pnm.pnm_auto_key = woo.pnm_auto_key
      into :pn, :description, :work_order, :entry_date, :cmp, :parts_price,
           :labor_price, :misc_price, :woo, :wwt
    Do begin
       labor_hours = null;
       work_type = null;
       parts_cost = null;
       labor_cost = null;
       ro_cost = null;
       customer = null;
       select company_name
         from companies
        where cmp_auto_key = :cmp
         into :customer;
       select work_type
         from wo_work_type
        where wwt_auto_key = :wwt
         into :work_type;
       select sum(sti.qty*stm.unit_cost)
         from stock_ti sti, stock stm, wo_bom wob
        where sti.wob_auto_key = wob.wob_auto_key
          and sti.stm_auto_key = stm.stm_auto_key
          and wob.woo_auto_key = :woo
          and sti.ti_type = 'I'
          and wob.activity <> 'Work Order'
          and wob.activity <> 'Repair'
         into :parts_cost;
       select sum(sti.qty*stm.unit_cost)
         from stock_ti sti, stock stm, wo_bom wob
        where sti.wob_auto_key = wob.wob_auto_key
          and sti.stm_auto_key = stm.stm_auto_key
          and wob.woo_auto_key = :woo
          and sti.ti_type = 'I'
          and wob.activity = 'Repair'
         into :ro_cost;
       select sum(wtl.hours*(wtl.fixed_overhead+wtl.variable_overhead+wtl.burden_rate)),
         from wo_task_labor wtl, wo_task wot
        where wtl.wot_auto_key = wot.wot_auto_key
          and wot.woo_auto_key = :woo
         into :labor_cost, :labor_hours;

    Hardcode - I responded in the comments to your suggestion.

  • After a little rethinking and a bit more research, I finally got my code working..

            ' Code for checking server location and required credentials
            Dim FBConn As FbConnection
            ' Dim FBAdapter As FbDataAdapter
            Dim MyConnectionString As String
            MyConnectionString = "datasource=" _
                            & MyServer & ";database=" _
                            & TextBox4.Text & ";user id=SYSDBA;password=" _
                            & MyPassword & ";initial catalog=;Charset=NONE"
            FBConn = New FbConnection(MyConnectionString)
            Dim FBCmd As New FbCommand("WIP_COSTS", FBConn)
            FBCmd.CommandType = CommandType.StoredProcedure
            FBCmd.Parameters.Add("@I_PN", FbDbType.VarChar, 40)
            FBCmd.Parameters("@I_PN").Value = TextBox1.Text.ToUpper
            Dim FBadapter As New FbDataAdapter(FBCmd)
            Dim dsResult As New DataSet
            Me.WIP_COSTSDataGridView.DataSource = dsResult.Tables(0)
            Dim RecordCount As Integer
            RecordCount = Me.WIP_COSTSDataGridView.RowCount
            Label4.Text = RecordCount
        Catch ex As System.Exception
            System.Windows.Forms.MessageBox.Show _
            ("There was an error in generating the DataStream, " & _
            "please check the system credentials and try again. " &_ 
            "If the problem persists please contact your friendly " &_ 
            "local IT department.")
        End Try
        ' // end of line

    I had also thought that I would need to make changes to the actual stored procedure, but, this turned out to be incorrect.

    The code may not be pretty, and I need to do more work in my TRY block for better error handling; but, it works.

    Thanks to all who chimed in and helped me get on track.


ASP.NET MVC jQueryUI datepicker not working when using AJAX.BeginForm

I have an ASP.NET MVC Partial View that contains a Html.TextBox that is configured to use the datepicker from JQueryUI. This is done by ensuring the style is set to .datepicker. This all worked fine. However I have changed my forms to Ajax.BeginForm and included a Ajax.ActionLink that displays it after clicking on the link. Since adding this the datepicker does not display. In fact no JavaScript that previously worked is now even being invoked after a returning a partialview from the controller. Even if i PUT THE JavaScript/JQuery in the partial view itself it still does not use it. I really am confused, can someone please help?

Examples shown below

<div id="claims">
        <div id="divViewClaims">
            <% Html.RenderPartial("ViewClaim", Model.Claims ?? null); %>
        <br /><br />
        <div id="claim">
            <% Html.RenderPartial("AddEditClaim", new Claim()); %>          

Action Link, when clickon calls Controller Action to return PartialView, The JavaScript called on the OnSuccess fires but nothing else, that previously was hooked up by the document.ready function. All my scripts are in seperate files and referenced in master page.

<%= Ajax.ActionLink(string.Format("Add A{0} Claim", Model.Count > 0 ? "nother" : string.Empty), "AddClaim", "Driver", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "claim", OnSuccess="showAddClaim" }, new { @class = "ControlLink" })%>

Controller Action

public ActionResult AddClaim()
      return PartialView("AddEditClaim", new Claim());

Partial View, which shows the textbox with the style set to datepicker

<% var ajaxOptions = new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divViewClaims", InsertionMode = InsertionMode.Replace, OnSuccess="hideAddClaim" }; %>
        <% using (Ajax.BeginForm("AddEditClaim", "Claim", ajaxOptions, new { @name = "ClaimControl", @id = "ClaimControl" }))
           { %>

        <legend><%= Model.Id==0?"Add":"Edit" %> Claim</legend> 
            <label for="Title">Claim Date</label>
            <%= Html.TextBox("Date", Model.Date.ToString().TrimEnd('0', ':', ' ') ?? "", new { @class = "datepicker" })%>  

I appreciate any help on this.

From stackoverflow
  • If the element is created after document.ready you should re-match the element to jQuery.

    Check out jQuery Live

  • I know it's bit too late to answer this ;), but what works for me is to use the OnSuccess property from the AjaxOptions. So, your code could be like this:

    using (Ajax.BeginForm("AddEditClaim", "Claim", ajaxOptions, new { @name = "ClaimControl", @id = "ClaimControl", OnSuccess="the_javascript_function_below" })

    where the_javascript_function is the name of a function that does this:


What is the best way to sort a data table in ADO.NET

What is the best for sorting a data table in c#, both from a performance and a code-readability point-of-view:

personsDT.OrderBy(person => person.PersonName);


personsDT.DefaultView.Sort = "PersonName ASC";

The personsDT is build from a SharePoint list, so it is impossible to use SQL (I am aware that an ORDER BY claude in a SQL SELECT statement would be the best way). Considering the performance, I am worried that the OrderBy<> clause might be slower than the Sort in the data view. Are you aware of such performance implications?

From stackoverflow
  • What's the purpose for the question? Performance is almost certainly a non-issue; if not, you'll need to test it in your context. I think if you are specifying a sort for a SQL statement it should be in the SQL statement; and I prefer to avoid constructing SQL statements stringwise if possible. Which do you like better esthetically?

  • I'll prefer the first option.

    1) For code the readability point-of-view i think that Lambda is clearer than the second one.

    2) In the first case you are using a strongly type way to sort your entity which is good.

    3) On the second case you are passing the field and the order in a string mmmm dont like it.

    Go Lambdas!!!


  • Well, if performance is very important, sort it on the SQL DB before getting the data.

    GenericMeatUnit : The poster states that the data source is a sharepoint list and that he is aware of, but cannot use, the sql ORDER BY method - although I don't know if that was written before or after your answer.
  • To throw my 2c into the pot:

    Coming from an sql background, I personally find the sql way more intuitive - but that's no reason to follow it. The lambda method has several good recommendations for it:

    As MRFerocius (is the missing 'o' intentional?) points out - the lambda method is strongly typed. That's a good thing.

    And then there's this - if your sorting criteria should ever become more complicated, the lambda method would allow you to tack on additional and esoteric conditions that the sql method would not.

    Performance-wise, they should be about equal, for a simple condition like this.

Why won't this change the color of my WPF Datagrid headers?

I fill my datagrid in code behind like this:

var customers = from c in _db.Customers
                select c;
TheDataGrid.ItemsSource = customers.ToList();

In my XAML below, the DataGrid.RowBackground works but the DataGridHeaderBorder gets the error "The Items listing must be empty before the use of ItemsSource" in the code-behind upon runtime.

This is odd because I'm just trying to change the color of the Datagrid headers and it gets a problem with ItemsSource. If I take the DataGridHeaderBorder line out, it works fine.

So how does one simply change the color of the column headers on a Datagrid?

        <toolkit:DataGridHeaderBorder Background="yellow"/>

            <LinearGradientBrush EndPoint="-0.136,-0.163" StartPoint="1.291,1.248">
                <GradientStop Color="#FFA8A929" Offset="0.004"/>
                <GradientStop Color="#FFF7F7ED" Offset="0.991"/>
From stackoverflow
  • Any time that you put elements within elements, the XAML parser has to decide if the sub-elements are complex property assignments (as you are trying to do), or whether you intend the sub-elements to be the "content" of the parent element. Because your problem "DataGridHeaderBorder" tag does not start with "toolkit:DataGrid", it is assumed that you are trying to set the DataGrid's content property (which happens to be Items) to this value.

    I am not in a position to try this, but I would guess you'd need to replace the problem tag with something like:

        <Style TargetType="{x:Type toolkit:DataGridRowHeader}">
            <Setter Property="Background" Value="Yellow" />

Where to stop/destroy threads in Android Service class?

I have created a threaded service the following way:

public class TCPClientService extends Service{  

public void onCreate() {
    Measurements = new LinkedList<String>();

public IBinder onBind(Intent intent) {
    //TODO: Replace with service binding implementation
    return null;

public void onLowMemory() {

public void onDestroy() {
    try {
    } catch(Exception e){


private Runnable backgrounSendData = new Runnable() {

    public void run() {

private void enableDataSending() {
    SendDataThread = new Thread(null, backgrounSendData, "send_data");

 private void addMeasurementToQueue() {
     if(Measurements.size() <= 100) {
         String measurement = packData();

 private void doSendData() {
     while(true) {
         try {      
             if(Measurements.isEmpty()) {
             //Log.d("TCP", "C: Connecting...");
             Socket socket = new Socket();
             socket.connect(new InetSocketAddress(serverAddress, portNumber), 3000);
             //socket.connect(new InetSocketAddress(serverAddress, portNumber));
             if(!socket.isConnected()) {
                 throw new Exception("Server Unavailable!");
             try {
                 //Log.d("TCP", "C: Sending: '" + message + "'");
                 PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
                 String message = Measurements.remove();
                 Log.d("TCP", "C: Sent.");
                 Log.d("TCP", "C: Done.");
                 connectionAvailable = true;              
             } catch(Exception e) {
                 Log.e("TCP", "S: Error", e);
                 connectionAvailable = false;
             } finally {
         } catch (Exception e) {
             Log.e("TCP", "C: Error", e);
             connectionAvailable = false;


After I close the application the phone works really slow and I guess it is due to thread termination failure.

Does anyone know what is the best way to terminate all threads before terminating the application?

From stackoverflow
  • There are several problems in the code sample you posted I will address in order:

    1) Thread.stop() has been deprecated for quite some time now, as it can leave dependent variables in inconsistent states in some circumstances. See this Sun answer page for more details. A preferred method of stopping and starting a thread is as follows:

    private volatile Thread runner;
    public synchronized void startThread(){
      if(runner == null){
        runner = new Thread(this);
    public synchronized void stopThread(){
      if(runner != null){
        Thread moribund = runner;
        runner = null;
    public void run(){
      while(Thread.currentThread() == runner){
        //do stuff which can be interrupted if necessary

    2) Your measurements list is accessed by multiple threads (the event thread and your user thread) at the same time without any synchronization. It looks like you don't have to roll your own synchronization, you can use a BlockingQueue.

    3) You are creating a new Socket every iteration of your sending Thread. This is a rather heavyweight operation, and only really make sense if you expect measurements to be extremely infrequent (say one an hour or less). Either you want a persistent socket that is not recreated every loop of the thread, or you want a one shot runnable you can 'fire and forget' which creates a socket, sends all relevant data, and finishes. (A quick note about using a persistent Socket, socket methods which block, such as reading, cannot be interrupted by Thread.interrupt(), and so when you want to stop the thread, you must close the socket as well as calling interrupt)

    4) There is little point in throwing your own exceptions from within a Thread unless you expect to catch it somewhere else. A better solution is to log the error and if it is irrecoverable, stop the thread. A thread can stop itself with code like (in the same context as above):

    public void run(){
        while(Thread.currentThread() == runner){
          //do stuff which can be interrupted if necessary
          if(/*fatal error*/){
            return; //optional in this case since the loop will exit anyways

    Finally, if you want to be sure a thread exits with the rest of your application, no matter what, a good technique is to call Thread.setDaemon(true) after creation and before you start the thread. This flags the thread as a daemon thread, meaning the VM will ensure that it is automatically destroyed if there are no non-daemon threads running (such as if your app quits).

    Obeying best practices with regards to Threads should ensure that your app doesn't hang or slow down the phone, though they can be quite complex :)

  • Actually, you don't need the "runner" variable as described above, something like:

    while (!interrupted()) {
        try {
        } catch (InterruptedException ex) {

    But generally, sitting in a Thread.sleep() loop is a really bad idea.

    Look at the AsyncTask API in the new 1.5 API. It will probably solve your problem more elegantly than using a service. Your phone is getting slow because the service never shuts down - there's nothing that will cause the service to kill itself.

  • I have tried Thread.interrupt() and then i checked whether thread is alive or not using thread.isAlive(),it still shows that thread is alive by returning true value for isAlive,its not correct way of killing the thread.

NHibernate ManyToMany relationship that includes all of one side of the relationship

Given this db schema (it was handed down to me):


I'd like suggestions on how to both model this and map it using fluent-nhibernate.

The only thing I can come up with is a very active record style of modeling (a class for each table and the obvious associations).

Ignoring the db for a second though, I think I want every facility to always have a list of all of the compliance flags. This way I can ask the facility what the compliance date for flag "XX" is.

Any help would be appreciated even it's only a slight nudge in the right direction.

Thanks, Rob

From stackoverflow
  • I think the best way is what you've already suggested, to map each table as an entity. If you didn't have additional data in the join table you wouldn't need to, but as you do they should really be separate entities.

    You'd have three entities. Facility and Compliance would have a HasMany to Facil_Compliance. You'd also have a References from Facil_Compliance back to each table. You may optionally remove a direction from this relationship if you only ever need to go one way.

Google Visualization API .net?

How can i use data in my .NET app that is coming in google's visualisation api json format? Can't imagine at the moment how to use this data.

Do i have to parse the json to an object by myself? Can i use Json.NET to deserialize it? For now i have no idea how start with this. Any help is appreciated.

Data looks like this:

  cols: [
    {id: '1', label: 'Name', type: 'string'},
    {id: '2', label: 'Age', type: 'number'},
    {id: '3', label: 'Birthdate', type: 'date'}
  rows: [
    {c:[{v: 'Dan'}, {v: 18.0, f: 'eighteen'}, {v: new Date(2008, 1, 28, 0, 31, 26), f: '2/28/08 12:31 AM'}]},
    {c:[{v: 'Frank'}, {v: 19.0, f: 'nineteen'}, {v: new Date(2008, 2, 30, 0, 31, 26), f: '3/30/08 12:31 AM'}]},
    {c:[{v: 'Esther'}, {v: 20.0, f: 'twenty'}, {v: new Date(2008, 3, 30, 0, 31, 26), f: '4/30/08 12:31 AM'}]}
From stackoverflow
  • Can i use Json.NET to deserialize it?

    Yes. That's what it's for.

    For now i have no idea how start with this. Any help is appreciated.

    The manual

    pantarhei : thank you for the answer. i forgot to mention that i'm pretty new to .NET. I read the manual and tried to figure out how to deserialize my data structure. But for now i'm more confused than before reading the manual.
  • You can use Json deserialisation via the DataContractJsonSerializer class in the System.Runtime.Serialization.Json namespace. It's pretty similar to XML Serialisation in that you create a bunch of data classes, dress them with attributes and chuck the Json into a deserializer.

    The article below explains how work with Json with a Google web search example:

Flex 3 sorting object fields

i have an object in actionScript3 code which i need to sort,

i iterate through the object and print out each value

for (var i:String in columnData)

however i need the data im iterating to be sorted aplhabetically. any suggestions on how to do this?

From stackoverflow
  • You can only sort Array/Lists, not fields in an object.

    If you want a sorted order, you first need to iterate thru the object and push the values in an array/list and then sort it.

    [Edit]: OK, so I assumed you just needed the data. No, flex doesn't provide a hashmap (like a TreeMap ala Java). What you could do is to store the name value pairs as objects in an array. Array provides a SortOn() method to let you sort on a specific field.

    combi001 : my problem is that the object contains name:value pairs so i cant just put into an arraylist
    combi001 : does flex provide any other datatype for storing name:value pairs , e.g like a hashmap in Java?
  • The ActionScript Foundry has an AS implementation of some of the Java collections--looks like you could find what you need there.

ASP.NET Controls and Update Panels

I am creating a series of client side component controls on the fly that are nested inside a update panel. The first time I create the controls, everything works as desired, however, when i trigger an update on the update panel and it does a partial postback the controls come back with several javascript errors describing how the control is already registered on the page.

I get a series of errors that say something about like: "Error: Sys.InvalidOperationException: Two components with the same id "master_ctl40_CCB_PALETTES" can't be added to the application"

Any ideas anyone?

From stackoverflow
  • In which event are you adding the components to the update panel? I.e. have you placed them inside the page load event without a postback check or have you placed them inside the update panel load event? etc...

    REA_ANDREW : Can you try adding your control inside the Page_Init event and remove the IsPostBack Code Block please.
  • Try these tricks:

    1. On Page_Load put uxFailedControl.ID = DateTime.Now.ToString(); It will ensure your control has unique ID every time page reloads (fully or partially), so theoretically you shouldn't see anymore "same id" errors.
    2. If you display your control in Modal Popup: Every time you hide the popup from the server, remove the control from it's container (Panel, Page, Control, etc.) Use uxModalPopupPanel.Controls.Clear(); or uxModalPopupPanel.Remove(uxFailedControl);
    3. When you are done with debugging set ScriptMode property of your ScriptManager to "Release". It will prevent internal AJAX exceptions to be bubbled up to the browser.
  • Looks like your client object is being created more than once.

    If you want your client side controls to be replaced when the update panel they're in refreshes, they should inherit from Sys.UI.Control, which takes takes an element in its constructor. When that element is replaced by the update panel, the client object will be disposed and then re-created. If you're currently using a ScriptComponentDescriptor on the server side to define the client control instance, you'll want to switch to a ScriptControlDescriptor.

    By the sounds of it, your client objects just inherit from Sys.Component, which will hang around until they're manually disposed, which is why you're getting an error about having more than one component with the same ID.

    I would advise against using a new ID every post back - this will just keep creating new client objects without ever cleaning up the old ones.

Problems with sending a multipart/alternative email with PHP

Here's the script that's builds/sends the email:

$boundary = md5(date('U'));

$to = $email;
$subject = "My Subject";

$headers = "From:" . "\r\n".
     "X-Mailer: PHP/".phpversion() ."\r\n".
     "MIME-Version: 1.0" . "\r\n".
     "Content-Type: multipart/alternative; boundary=--$boundary". "\r\n".
     "Content-Transfer-Encoding: 7bit". "\r\n";

$text = "You really ought remember the birthdays";     
$html = '<html>
   <title>Birthday Reminders for August</title>
   <p>Here are the birthdays upcoming in August!</p>

$message = "Multipart Message coming up" . "\r\n\r\n".
    "Content-Type: text/plain; charset=\"iso-8859-1\"" .
    "Content-Transfer-Encoding: 7bit".
    "Content-Type: text/html; charset=\"iso-8859-1\"". 
    "Content-Transfer-Encoding: 7bit". 

mail("", $subject, $message, $headers);

It sends the message just fine, and my recipient receives it, but they get the whole thing in text/plain instead of in multipart/alternative. Viewing the source of the received message gives this (lots of cruft removed):

Received: by with SMTP id x4cs111413agb;
    Wed, 25 Mar 2009 16:39:32 -0700 (PDT)
Received: by with SMTP id a6mr85081ane.123.1238024372342;
    Wed, 25 Mar 2009 16:39:32 -0700 (PDT)
Return-Path: <>
--- snip ---
Date: Wed, 25 Mar 2009 17:37:36 -0600 (MDT)
Message-Id: <>
Subject: My Subject
X-Mailer: PHP/4.3.9
MIME-Version: 1.0
Content-Type: text/plain;
Content-Transfer-Encoding: 7bit
X-OriginalArrivalTime: 25 Mar 2009 23:38:30.0531 (UTC) FILETIME=[CDC4E530:01C9ADA2]
X-TM-AS-Product-Ver: SMEX-
X-TM-AS-Result: No--4.921300-8.000000-31
X-TM-AS-User-Approved-Sender: No
X-TM-AS-User-Blocked-Sender: No

Multipart Message coming up

Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

You really ought remember the birthdays

Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

   <title>Birthday Reminders for August</title>
   <p>Here are the birthdays upcoming in August!</p>


It looks like the content-type header is getting changed along the way from multipart/alternative to text/plain. I'm no sysadmin, so if this is a sendmail issue I'm in way over my head. Any suggestions?

From stackoverflow
  • The line

    "Content-Type: multipart/alternative; boundary=--$boundary". "\r\n".

    should be

    "Content-Type: multipart/alternative; boundary=$boundary". "\r\n".

    You don't include the dashes in the header.

    saturdayplace : Gaaaaaa! - Thank RoBorg. That was indeed it.
  • Just a thought, but it might be a lot easier to simply worth with something like phpmailer or Zend_Mail.

  • use "\n" instead of "\r\n" looks like it qmail has problems with "\r"

URL Rewriter.NET web.config node issue

I'm using URL Rewriter.NET (which I'm liking a lot, by comparison to URL Rewriting.NET - more versitile it seems, don't get me wrong, I like URL Rewriting.NET, but it didn't seem to satisfy the need, given what I know of the tool). I'm trying to use the default-documents node to redefine the default documents for the site. I've tried adding it to the rewriter node, but I get a web.config error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. 

Parser Error Message: The element 'default-documents' is not allowed.

Source Error: 

Line 187:
Line 188:   <rewriter>
Line 189:    <default-documents>
Line 190:     <document>default.aspx</document>
Line 191:     <document>index.aspx</document>

Has anyone used this tool in the past, and does anyone know where to put this node (or proper usage)?


I tried the suggestion below, but it didn't seem to work quite right. Here is what is in my extra config file (this is the only contents in the config file)

     <rewrite url="^(/.+(\.gif|\.png|\.jpg|\.ico|\.pdf|\.css|\.js)(\?.+)?)$" to="$1" processing="stop" />
From stackoverflow
  • I've used urlrewriter before, and had some problems with actually setting a default document as well. However, eventually we got it (and other minor annoyances) to work by moving the urlrewriter config to different config file than web.config.

    <rewriter configSource="urlrewriter.config"/>

    Remember that you also have to disable default documents in IIS for the urlrewriter to work correctly. That caused a bunch of annoying problems as well.

    EDIT: Don't forget to add this line to your config sections in web.config

    <section name="rewriter" requirePermission="false" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter"/>

    Hope this helps.

    MasterMax1313 : I'll give this a shot, thanks!
    MasterMax1313 : adding it to a separate config file didn't resolve the issue.
  • This snippet works for me:

            <section name="rewriter" 
                     type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" 

    Edit: Be sure that where you added the wildcard application map, you also unchecked "Verify that file exists". If you don't do this, default-documents won't do anything.

    Another edit: Found the installation step that illustrates the "Verify that file exists" checkbox. See step 8 here:

    MasterMax1313 : I have all the same configSections listed in yours and SirDemon's responses. I've got the line in the httpModules node. I've got regular rewrite nodes working just fine. It's only the default-document node that isn't working.
    Moose : Check my edit. Where you added the wildcard application map, you also unchecked "Verify that file exists"? Otherwise, it's not going to do default documents..
    MasterMax1313 : Yes, I did check that the IIS settings. That didn't seem to resolve the issue. I'm thinking its the runtime being used.
    Moose : I am using the .Net 2.0 version without problems. Hope you get it figured out.
  • I believe the solution to this problem is the version of .NET I'm using on the website. I'm using the 2.0 runtime and the dll was built for the 1.1 runtime. I saw on the website that the 2.0 runtime is still in RC (since mid 2007), and hence I will not be using it on this production website. Instead, I figured out how to use the URL Rewriting.NET to accomplish the same goal.

    I added the following rule:

    <add name="Redirect54" virtualUrl="~/content/myvirtualpage.aspx"
        ignoreCase="true"  />

    This causes a HTTP 200 response on the myvirtualpage.aspx, instead of a rewrite. The eventual goal is to have the mydestinationpage.aspx?id=9 have a 301 to myvirtualpage.aspx, which would then serve up the myvirtualpage.aspx with a 200 HTTP response. That's a bit off though.

    SirDemon : Actually, I believe I used the 2.0 version as well and it worked, although, as I said before, with a few annoying bugs we managed to overcome eventually.

DAQ Triggers in Matlab

I'm writing a program that detects the speed of a object by hall effect sensors that are run into MATLAB through a DAQ (MCC USB-1408FS)

The problem that has arisen is that I'm using a non-stop scan technique to detect the state of one of 3 sensors. Unfortunately this means that unless the object is rotating past each sensor at the exact rate the program runs, I will see an instantaneous speed (done by comparing the time between two sensors) of zero.

I need the sensors to signal the program to count when they are hit, instead of constantly scanning for the signal. How can this be done?

From stackoverflow
  • Are you running the 1408FS in the continuous scan mode as opposed to the software paced mode (1408FS user manual - page 3-1)? Either way, it sounds like that your sampling rate is too slow to catch the signal from your sensor. Also are you using MATLAB's DAQ toolbox?

    Another point that comes to my mind, from your description it sounds like you have MATLAB logging the difference in time between signal from each of your three sensors (which are at known positions). Again if your sampling rate is too slow it will appear as if your object has moved instantaneously from one sensors to the next. Perhaps, you could use the external trigger on your DAQ with one of your sensors.

    I am having some difficulty in imaging the type of signal you receive from your sensors. I image it is some sort of step function. That is the sensor is will read zero and the pulse for a short time as the object passes it. Something like

    • data sensor 1: ... 0, .25, .5, .75, 1, 1, 1, .75, .5, .25, 0, 0, 0, 0, 0...
    • data sensor 2: ... 0, 0, 0, .25, .5, .75, 1, 1, 1, .75, .5, .25, 0, 0, 0 ...

    as the object passes the sensor the signal increases and then decreases back to zero. In this case the sensors might be too close together for the speed of your object. Since the signal from the two sensors overlap.

    just my 2c.

Why does WCF limit concurrent connections to 5?

I have a WCF service (basicHttpBinding) hosted in II7 on Vista that I expect to handle many requests concurrently. I'm attempting to load test the service by spawing 200 threads in a test app and calling the WCF service. I've run this test app on the same machine as the server as well as multiple other computers and I always get the same result - no more than 5 workers are used. Is this a WCF, HTTP or IIS bottleneck?

From stackoverflow
  • This is a feature to prevent denial of service attack. Out of the box, WCF is designed to be secure. Check the service behavior, look in msdn for maxConcurrentCalls and maxConcurrentSessions configuration. I think the limit is 10, but I could be wrong.

    James Cadd : This is the closest answer - if I changed maxConcurrentCalls the number of WCF workers actively reflects that value, to a point. Anything over 10 doesn't actually run more of my workers. Strangely, the default is 16 but I can't get 16 calls to be active at the same time.
    Vadmyst : The default limit is 16 not 10. Btw 0x10 is 16 :)
  • WCF is secure by default. This means that the default settings limit what you can do with your WCF service to avoid things like denial of service attacks. This is great for internet facing web services, but it can sometimes bite you. Depending on what bindings and behaviors you use, it could be a setting in any of those.

    Here is an overview of these settings - it'll require some experimentation on your part to determine what exactly is biting you.

  • No, it's just the default throttling settings in WCF. It's configured in the serviceThrottling element of a behaviour in the service config file, which has a maxConcurrentSessions attribute. Default 5, but you can set it to whatever you want.

  • Here's a nice article on WCF Instance Management from MSDN magazine by Juval Lowy: Issue from June 2006 (in case if MSDN will butcher their links again).

    It explains techniques and settings for managing service lifecycle (throttling is one of them) and shows what settings to apply to increase number of concurrent connection.

Combining cookies and sessions

This question Is a result of various questions I had today about cookies.

As you know it's not save to handle the login process with cookies.

But how can I set a cookie when I am logged in and to be automatically loggedon when I restart my browser?

If I redirect based on the existense of the cookie this is dangerous as someone else could just create a cookie. So what's the way to deal with this?

From stackoverflow