Sunday, April 3, 2011

Passing data from WPF tabs to a function

I have a WPF app with a single form containing some WPF tabs. Three of the tabs are used to collect data from the user. The last tab has an OK button and when clicked performs some calculations.

How to I pass data from the text boxes on the various tabs to the function located in the buttonclick event? I have the function created. I just need to know how to reference the values from the textboxes on the tabs.

From stackoverflow
  • Give the controls a name with the Name="myTextBox" attribute then Visual Studio or Blend will create identifiers for the controls in the code-behind for your form and you can access them via their names.

    void OKButton_Click(object sender, EventArgs e) {
       // string first = firstName.Text;
       // string last = lastName.Text;
       // etc.../
    }
    
    Scott : I thought that's the way it should work. After a reboot, my intellisense contained the textboxes and everything was fine.
    Will Eddins : If this worked for you, you make it your accepted answer.
  • If your textboxes have Name or x:Name attributes set on them in XAML, you can access them in your codebehind.

Algorithm to "smooth out" data values for visualization

I'm reading some data for countries around the world and am playing with Google's visualization gadgets, in particular the map visualizations. The problem is, that the US always comes out way in front. While most countries have values between 1 and 50, the US consistently has a value of 2000+. Which means in the visualization, it's hard to tell the difference between all the "small countries", as they all get about the same shade of pale green, while the US always is a fat dark green.

I don't particularly care about the accuracy of the visualization, so I'd like to smooth out or average out the values a bit so that there's a visible difference between the very-low, low and not-so-low countries. What's a good algorithm to do that?

A pretty simple problem, but I'm not a math guy at all. ^_^;;

From stackoverflow
  • How about displaying data on a logarithmic scale. That way a value of 10 translates to 1, a value of 100 translates to 2, 1000 translates to 3 and so on.

    deceze : There you go, learned what log() is good for. ;) Thanks.
    Jouni K. Seppänen : Note that 0 translates to minus infinity, which may cause problems. A practical trick is to take log(1+x) or log(0.001+x) or whatever works for you, or perhaps log(min(1,x)), log(min(0.001,x)), etc.

How to Escape Character in EL with JSTL tag?

I have this JSP code snippet:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<c:choose>
  <c:when test="${var1.properties[\"Item Type\"] eq \"Animal's Part\"}">
    <c:set var="cssClassName" value="animalpart" />
  </c:when>
  <c:otherwise>
    <c:set var="cssClassName" value="" />
  </c:otherwise>
</c:choose>

The JSP cannot be compiled by the server. However, if I remove the character "'" from "Animal's Part", it is compilable. I tried to escape it by using "\" character but it still gives me error.

Any suggestion/help is appreciated. I tried to avoid using scriptlet if possible.

Thanks.

EDIT: I managed to get it working (after posting to StackOverflow), posted as one of the solution in this question. I tried other solution posted before that (by Vincent and Eddie), however, unfortunately, none works in my environment, although I reckon that they might works in the answers' environment. Thanks.

From stackoverflow
  • try this

    <c:when test='${var1.properties["Item Type"] eq "Animal\'s Part"}'>
    
  • Use escapeXml="false" For example:

    <c:out value="${formulario}" escapeXml="false" />
    
  • You have two easy choices:

    <c:when test="${var1.properties['Item Type'] eq 'Animal\'s Part'}">
    
    <c:when test='${var1.properties["Item Type"] eq "Animal\'s Part"}'>
    
  • Hi, this is the solution that works in my use case:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    
    <c:set var="itemType"        value="${var1.properties[\"Item Type\"]}" />
    <c:set var="item_animalpart" value="Animal's Part" />
    <c:set var="item_treepart"   value="Tree's Part" />
    
    <c:choose>
      <c:when test="${itemType eq name_item_animalpart}">
        <c:set var="cssClassName" value="animalpart" />
      </c:when>
      <c:when test="${itemType eq name_item_treepart}">
        <c:set var="cssClassName" value="treepart" />
      </c:when>
      <c:otherwise>
        <c:set var="cssClassName" value="" />
      </c:otherwise>
    </c:choose>
    

CSS Help, Making Menu Fluid

I got some help with this menu earlier but have a different request now.

The menu works fine with fixed width but I would like the words to wrap ONLY on the top menu categories. I need to be able to have n categories and have the width be evenly distributed. Obviously n would be within reason (I am not going to have 50 categories) but I need to be able to add more and not worry about hitting my width limit.

Thanks for any help.

Link:

http://www.seth-duncan.com/Test/TestMenu.html

-Seth

From stackoverflow
  • For every top level menu item add the class 'heading' (or something similar).

    Then add the following CSS to your page:

    #menu li
    {
        white-space: nowrap;
    }
    
    #menu .heading
    {
        white-space: normal;
    }
    

Performance : encapsulating a string in a struct?

Hi,

Would there be any perforamce gain in ecapsulating a string in a lightweight reference object vs encapsulating a string in a struct. Would the string variable not utlimately point to the heap anyway , irrespective of whether it is contained within a value type or reference type?

From stackoverflow
  • The string is always located on the heap, so it wouldn't help. Putting the reference to the string in the struct can only make it slower, since it needs an extra derefence. But this won't be measurable in practice probably.

    If you really wanted a string to be on the stack instead of the heap, you would have to create your own custom strings as a struct containing chars. But that's going to be a lot of pain for no gain and can only be used to represent a fixed sized string since the struct is of a fixed size.

  • Since you tagged this one as .NET the string will most certainly be stored on the heap. However I don't think that there will be a noticeable difference and why should there be? First the object or struct must dereferenced and located and after that the string itself. It could be a plus, if you could do without encapsulating the string from a performance and a memory perspective.

Sample code for JSON-RPC client in C#

I need a simple JSON-RPC 1.0 client in C#, preferably using .NET 2.0 or later. I checked out JRock 0.9 They have several samples including Yahoo reader, but the samples demo JSON, not JSON-RPC. I understand I could implement RPC part using any of the available JSON parsers, like JRock or two from Microsoft. I would prefer a ready sample.

From stackoverflow
  • 2 Samples here

    There are two different implementations. Read the whole thread + check the attachments

ASP.NET Authentication with Roles in IIS7 Integrated Mode for Static Content

I am experimenting with the integrated authentication mode for static content in IIS7. I followed the instructions in this article: http://aspnet.4guysfromrolla.com/articles/122408-1.aspx It is working fine if I allow/deny access by login status (like in the article). However I want to allow/deny access based on roles (using the ASP.NET built in Roles Provider). When I put an allow rule for the role "Admin" in the web.config and deny rule for all other users I am not able to access the static files even when I login as an admin. The same folder contains non-static content (aspx pages) that are accessed just fine based on the Role Provider information.

Any ideas?

From stackoverflow
  • I would say the most likely culprit is that the static files are not being processed by ASP.NET but being left up to IIS.

    Does it work if you add a wildcard script mapping?

    Stilgar : what do you suggest to add as a wildcard script mapping? and if this is the case why does the authentication based on login status work but not the roles?

Does GRASP Creator really decouples?

I'm learning GRASP pattern at school and I have a question about the Creator pattern.

Let's say you have three class, Computer, UserRespository and User.

One of the rules of the GRASP Creator pattern tells you to assign the responsibility of creating an object to the class containing those object. By following this guideline, UserRepository should be the creator of User.

So if Computer wants to create a user, he'll ask UserRespository.

//in Computer's code
repo.createUser("John");


//in UserRepository
public void createUser(String name)
{
    users.add(new User(name));
}

This effectively decouple Computer from User. Really?

Clearly, Computer doesn't have any reference to User, but I think Computer is still highly coupled to the creation of User. Why? The createUser method is poorly hiding the creation. If User change it's constructor, you'd have to change the createUser method to reflect those changes and also every client using the method.

What are the advantage of using this pattern then?

From stackoverflow
  • The decoupling arises from the fact that the repository object can be arbitrary; that is, you can choose which repository object to pass into the computer object. While there is still a CreateUser method, the source of the User data is determined by which repository object is used.

    In your example, the repository object would more commonly be called the UserRepository object.

  • I've learned that decoupling is really asking "Can you extract this class from the system?". So by hiding the creation of an object behind a method, given this object is not used anywhere else than in the creator, it effectively decouple the object from the system.

How to write a proxy-server in Python?

(Edited to note: exact duplicate of 989739)

Could you give any suggestions or online sourses as to the matter of writing one's own client proxy-server? In particular, this proxy must be able to make one thing: replace the HTTP-headers sent by browsers with my own ones.

From stackoverflow

How to change custom Paper size in Crystal Reports in VS 2005 ?

How to change custom Paper size in Crystal Reports in VS 2005 ?

From stackoverflow
  • This is based on the printer. You should be able to change the paper size of the printer the report is using to change the layout of the report. Try Page Setup to get to some of these settings.

    Also, In Crystal Reports XI you can click on the Details section in the section expert and select the layout tab to the right to change a few settings such as Detail Width Size, Gap Between Details (Horizontal, Vertical) and Printing Direction. Hope this helps.

Attached SQL 2000 DB in a SQL 2005 Server, Now getting VB6 App throwing errors

A SQL 2000 db was detached, SQL 2000 was uninstalled. Then SQL 2005 installed in the same machine. Then the database was attached to the newly installed SQL 2005 server. It seemed to work at first but after the users started to poke around, error related to null started to pop. Null values from datetime columns that DID NOT have nulls, and things like that. The db has a compatibility level to 2000 (8.0). What could be happening.

From stackoverflow
  • Have you you run DBCC UPDATEUSAGE?

    In earlier versions of SQL Server, the values for the table and index row counts and page counts can become incorrect. Therefore, databases that were created on versions prior to SQL Server 2005 may contain incorrect counts. After you upgrade a database to SQL Server 2005, we recommend that you run DBCC UPDATEUSAGE to correct any invalid counts. This DBCC statement corrects the rows, used pages, reserved pages, leaf pages and data page counts for each partition in a table or index. For more information, see DBCC UPDATEUSAGE (Transact-SQL).

    Have you rebuilt all indexes?

    exec sp_msforeachtable "dbcc dbreindex('?')"
    

    Note: be careful if this is in production, as it might take a while. Perhaps talk to your DBA.

    nmarmol : This solved the problem, there were multiple mismatches with reported number of pages and rows. Thanks
    nmarmol : It seems that I spoke too soon. One of the tables is still throwing errors.
    nmarmol : But the rest is working fine.
    Mitch Wheat : Run a low level disk check
    Mitch Wheat : ...after backing up of course...

python string input problem with whitespace!!

my input is something like this

23 + 45 = astart

for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this

SyntaxError: invalid syntax

the code is this

k=raw_input()
a,b=(str(i) for i in k.split('  +   '))
b,c=(str(i) for i in b.split('  =   '))

its always number + number = astar

its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error

From stackoverflow
  • Edit: as pointed out by Triptych, the generator object isn't the problem. The partition solution is still good and holds even for invalid inputs

    calling (... for ...) only returns a generator object, not a tuple

    try one of the following:

    a,b=[str(i) for i in k.split('  +   ')]
    a,b=list(str(i) for i in k.split('  +   '))
    

    they return a list which can be unpacked (assuming one split)

    or use str.partition assuming 2.5 or greater:

    a, serperator, b = k.partition('+')
    

    which will always return a 3 tuple even if the string isn't found

    Edit: and if you don't want the spaces in your input use the strip function

    a = a.strip()
    b = b.strip()
    

    Edit: fixed str.partition method, had wrong function name for some reason

    mekasperasky : still syntax error
    Triptych : -1. Generators can be unpacked just fine. Try a,b = (i for i in (1,2)) for confirmatino.
  • Testing with Python 2.5.2, your code ran OK as long as I only had the same spacing on either side of the + and = in the code and input.

    You appear to have two spaces on either side of them in the code, but only one on either side in the input. Also - you do not have to use the str(i) in a generator. You can do it like a,b=k.split(' + ')

    My cut and pastes:
    
    My test script:
    
    print 'Enter input #1:'
    k=raw_input()
    
    a,b=(str(i) for i in k.split(' + '))
    b,c=(str(i) for i in b.split(' = '))
    
    print 'Here are the resulting values:'
    print a
    print b
    print c
    
    
    print 'Enter input #2:'
    k=raw_input()
    
    a,b=k.split(' + ')
    b,c=b.split(' = ')
    
    print 'Here are the resulting values:'
    print a
    print b
    print c
    
    
    From the interpreter:
    
    >>> 
    Enter input #1:
    23 + 45 = astart
    Here are the resulting values:
    23
    45
    astart
    Enter input #2:
    23 + 45 = astart
    Here are the resulting values:
    23
    45
    astart
    >>>
    
    lyrae : Works fine here for me too. And if i take out the spaces, i get ValueError, not syntax error. If it was me, i would just do "a, b = (i for i in k.split('+')", without spaces.
  • I think I'd just use a simple regular expression:

    # Set up a few regular expressions
    parser = re.compile("(\d+)\+(\d+)=(.+)")
    spaces = re.compile("\s+")
    
    # Grab input
    input = raw_input()
    
    # Remove all whitespace
    input = spaces.sub('',input)
    
    # Parse away
    num1, num2, result = m.match(input)
    
  • You could just use:

    a, b, c = raw_input().replace('+',' ').replace('=', ' ').split()
    

    Or [Edited to add] - here's another one that avoids creating the extra intermediate strings:

    a, b, c = raw_input().split()[::2]
    

    Hrm - just realized that second one requires spaces, though, so not as good.

  • Rather than trying to solve your problem, I thought I'd point out a basic step you could take to try to understand why you're getting a syntax error: print your intermediate products.

    k=raw_input()
    print k.split('  +   ')
    a,b=(str(i) for i in k.split('  +   '))
    print b.split('  =   ')
    b,c=(str(i) for i in b.split('  =   '))
    

    This will show you the actual list elements produced by the split, which might shed some light on the problem you're having.

    I'm not normally a fan of debugging by print statement, but one of the advantages that Python has is that it's so easy to fire up the interpreter and just mess around interactively, one statement at a time, to see what's going on.

How can I "Click Through" a control in WPF?

I have an order entry form that has a listbox with a list of line items. I have my items template, and one of the values is a ComboBox in each of my Items.

Now, my form can also create Credit memo's in addition to purchase orders, but when I am creating a credit memo, I want to put the words "Credit Memo" over the list box, however, the textblock covers the combo box in two of my line items. I would like to pass my click event through the textblock to the combo boxes but I'm not sure how to do it.

This is what I have, ( Maybe I am coming at this totally wrong, I am kinda a noob with WPF )

<ListBox SelectionMode="Single" Grid.Row="2" 
                 ItemsSource="{Binding Path=LineItems}" HorizontalContentAlignment="Stretch" 
                 IsSynchronizedWithCurrentItem="True" Background="#66FFFFFF">
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="Background" Value="WhiteSmoke"/>
                    <Setter Property="BorderThickness" Value="1" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsPartBackOrder}" Value="True">
                            <Setter Property="Background" Value="Orange" />
                        </DataTrigger>                       
                    </Style.Triggers>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type Entities:SalesOrderLineItem}" >
                    <OrderEntry:SalesOrderLineItemCreate DataContext="{Binding}" DeleteSalesOrderLineItem="DeleteSalesOrderLineItem" Margin="0,3,3,0" >
                        <OrderEntry:SalesOrderLineItemCreate.Resources>
                            <Style TargetType="{x:Type OrderEntry:SalesOrderLineItemCreate}">
                                <Style.Triggers>
                                    <DataTrigger 
                                            Binding="{Binding RelativeSource=
                                              {
                                                 RelativeSource 
                                                 Mode=FindAncestor, 
                                                 AncestorType={x:Type ListBoxItem}
                                              }, 
                                              Path=IsSelected
                                             }" Value="True">
                                        <Setter Property="Background" Value="LightBlue" />
                                        <Setter Property="Foreground" Value="Black" />
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </OrderEntry:SalesOrderLineItemCreate.Resources>
                    </OrderEntry:SalesOrderLineItemCreate>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

        <TextBlock Grid.Row="2" 
                Text="Credit Memo" 
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   FontSize="48" Height="Auto"
                   FontStyle="Italic"
                   Foreground="Red"
                   Opacity=".25">
             <TextBlock.Style>
                    <Style TargetType="{x:Type TextBlock}">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=OrderType}" Value="CR">
                                <Setter Property="Visibility" Value="Visible" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding Path=OrderType}" Value="CU">
                                <Setter Property="Visibility" Value="Hidden" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
        </TextBlock>
From stackoverflow
  • <TextBlock IsHitTestVisible="False" .../>`
    

    HTH, Kent

    Russ : Sometimes it’s the simplest things. Thanks a ton.

Using BackgroundWorker to update the UI without freezes...?

I have the following code for population a ListView from a background thread (DoWork calls the PopulateThread method):

delegate void PopulateThreadCallBack(DoWorkEventArgs e);
private void PopulateThread(DoWorkEventArgs e)
{

    if (this.InvokeRequired)
    {
        PopulateThreadCallBack d = new PopulateThreadCallBack(this.PopulateThread);
        this.Invoke(d, new object[] { e });
    }
    else
    {

        // Ensure there is some data
        if (this.DataCollection == null)
        {
            return;
        }

        this.Hide();

        // Filter the collection based on the filters
        List<ServiceCallEntity> resultCollection = this.ApplyFilter();

        // Get the current Ids
        List<Guid> previousIdList = this.GetUniqueIdList(listView);
        List<Guid> usedIdList = new List<Guid>();

        foreach (ServiceCallEntity record in resultCollection)
        {

            if (e.Cancel)
            {
                this.Show();
                return;
            }
            else
            {

                // Get the top level entities
                UserEntity userEntity = IvdSession.Instance.Collection.GetEngineerEntity(record.UserId);
                AssetEntity assetEntity = IvdSession.Instance.Collection.GetAssetEntity(record.AssetId);
                SiteEntity siteEntity = IvdSession.Instance.Collection.GetSiteEntity(record.SiteId);
                FaultEntity faultEntity = IvdSession.Instance.Collection.GetFaultEntity(record.FaultId);

                if (siteEntity == null || userEntity == null || faultEntity == null)
                {
                    continue;
                }
                else
                {

                    // Get the linked entities
                    RegionEntity regionEntity = IvdSession.Instance.Collection.GetRegionEntity(siteEntity.RegionId);
                    StatusEntity statusEntity = IvdSession.Instance.Collection.GetStatusEntity(record.ServiceCallStatus.StatusId);

                    ListViewItem item = new ListViewItem(siteEntity.SiteName);
                    item.SubItems.Add(siteEntity.Address);
                    item.Tag = record;

                    item.SubItems.Add(regionEntity.Description);

                    // Handle if an Asset is involved
                    if (record.AssetId > 0)
                        item.SubItems.Add(assetEntity.AssetDisplay);
                    else
                        item.SubItems.Add("N/A");

                    item.SubItems.Add(faultEntity.Description);
                    item.SubItems.Add(userEntity.UserDisplay);

                    item.SubItems.Add("TODO: Claimed By");
                    item.SubItems.Add(record.DateTimeStamp.ToString());

                    IvdColourHelper.SetListViewItemColour(item, false);
                    this.PopulateItem(item, ref usedIdList);

                }

            }

        }

        // Clean up the grid
        this.CleanListView(previousIdList, usedIdList);

        // Only autosize when allowed and when there are some items in the ListView
        if (this.AllowAutoSize && listView.Items.Count > 0)
        {
            rsListView.AutoSizeColumns(listView);
            this.AllowAutoSize = false;
        }

        this.Show();

    }

}

Unfortunately, this causes the UI to freeze whilst in the foreach... is there any way to update/populate the ListView without it freezing the main UI?

From stackoverflow
  • Pump the events manually with

    Application.DoEvents();
    
    GenericTypeTea : Perfect, thank you for the fast answer!
    Henk Holterman : -1, Sorry, but BgWorker->Invoke->DoEvents? Looks like patching one hole with another.
    Jared Updike : Good point, though I will say: you can get pretty far with Application.DoEvents instead of multiple threads if all you want is a moderately responsive GUI during computationally intensive tasks, just pump the message queue yourself. A lot of this machinery is just extra complexity with little gain (unless of course you really need the threads). For example, with multiple threads, debugging + exceptions = FAIL. But as you said in your answer this isn't multithreaded code at all. Concurrency in imperative languages is a PITA. Stay away unless you really need it.
    Henk Holterman : Jared, if you meant DoEvents instead of a BgWorker then I missed that. DoEvents is tricky though.
  • A) You probably don't need to use this.Invoke and instead use this.BeginInvoke. Invoke blocks the current thread.

    B) You don't need to define your own delegates you can use MethodInvoker

    if(this.InvokeRequired) {
      this.BeginInvoke(new MethodInvoker(() => PopulateThread(e)));
      return;
    }
    

    It's much cleaner :)

    GenericTypeTea : Thanks, I shall make some improvements.

Fast way to manually mod a number

I need to be able to calculate (a^b) % c for very large values of a and b (which individually are pushing limit and which cause overflow errors when you try to calculate a^b). For small enough numbers, using the identity (a^b)%c = (a%c)^b%c works, but if c is too large this doesn't really help. I wrote a loop to do the mod operation manually, one a at a time:

private static long no_Overflow_Mod(ulong num_base, ulong num_exponent, ulong mod) 
    {
        long answer = 1;
        for (int x = 0; x < num_exponent; x++)
        {
            answer = (answer * num_base) % mod;
        }
        return answer;
    }

but this takes a very long time. Is there any simple and fast way to do this operation without actually having to take a to the power of b AND without using time-consuming loops? If all else fails, I can make a bool array to represent a huge data type and figure out how to do this with bitwise operators, but there has to be a better way.

From stackoverflow
  • Short of writing your own fast modular exponentiation, the simplest idea I can come up with, is to use the F# BigInt type: Microsoft.FSharp.Math.Types.BigInt which supports operations with arbitrarily large scale - including exponentiation and modular arithmetic.

    It's a built-in type that will be part of the full .NET framework with the next release. You don't need to use F# to use BitInt - you can make use of it directly in C#.

  • I'd recommend checking over the Decimal documentation and seeing if it meets your requirements since it is a built in type and can use the mod operator. If not then you're going to need an arbitrary precision library like java's Bignum.

    Malfist : Not using Java. C#.
    Qberticus : no shit, i was saying like, as in he would need to find an equivalent. way to not read.
    Tim Lesher : He said *like* Java's Bignum. Not *use" Java's Bignum. Given that he knows about C#'s decimal type, it's probably a good bet that he knows the question is about C#.
  • Can you factor a, b, or c? Does C have a known range?

    These are 32 bit integers! Go check this site

    For instance, here is how you get the mod of n%d where d 1>>s (1,2,4,8,...)

      int n = 137;     // numerator
      int d = 32;      // denom d will be one of: 1, 2, 4, 8, 16, 32, ...
      int m;           // m will be n % d
      m = n & (d - 1);
    

    There is code for n%d where d is 1>>s - 1 (1, 3, 7, 15, 31, ...)

    This is only going to really help if c is small though, like you said.

    Nathan Fellman : do you mean, "where d is 1 << (s-1)"?
    johnnycrash : yeah. I can't even copy from another website without making a mistake!
  • Fast Modular Exponentiation (I think that's what it's called) might work.

    Given a, b, c and a^b (mod c):
    
    1. Write b as a sum of powers of 2. (If b=72, this is 2^6 + 2^3 )
    2. Do:
        (1) a^2 (mod c) = a*
        (2) (a*)^2 (mod c) = a*
        (3) (a*)^2 (mod c) = a*
        ...
        (n) (a*)^2 (mod c) = a*
    
    3. Using the a* from above, multiply the a* for the powers of 2 you identified. For example:
        b = 72, use a* at 3 and a* at 6.
        a*(3) x a*(6) (mod c)
    
    4. Do the previous step one multiplication at a time and at the end, you'll have a^b % c.
    

    Now, how you're going to do that with data types, I don't know. As long as your datatype can support c^2, i think you'll be fine.

    If using strings, just create string versions of add, subtract, and multiply (not too hard). This method should be quick enough doing that. (and you can start step 1 by a mod c so that a is never greater than c).

    EDIT: Oh look, a wiki page on Modular Exponentiation.

  • You could try this:

    C#: Doing a modulus (mod) operation on a very large number (> Int64.MaxValue)
    http://www.del337ed.com/blog/index.php/2009/02/04/c-doing-a-modulus-mod-operation-on-a-very-large-number-int64maxvalue/

  • You can try factoring 'a' into sufficiently small numbers.

    If the factors of 'a' are 'x', 'y', and 'z', then

    a^b = (x^b)(y^b)(z^b).

    Then you can use your identity: (a^b)%c = (a%c)^b%c

    Eclipse : Except that factoring is a much more difficult problem than modulus
    Robert Cartaino : I would just start out dividing a/2 in a loop until it didn't divide evenly.... Then a/3, etc with prime numbers until 'a' was "sufficiently small" for a^b not to overflow. Then complete the operation as outlined by the original poster.
  • It seems to me like there's some kind of relation between power and mod. Power is just repeated multiplication and mod is related to division. We know that multiplication and division are inverses, so through that connection I would assume there's a correlation between power and mod.

    For example, take powers of 5:

    5 % 4 = 1
    25 % 4 = 1
    125 % 4 = 1
    625 % 4 = 1
    ...
    

    The pattern is clear that 5 ^ b % 4 = 1 for all values of b.

    It's less clear in this situation:

    5 % 3 = 2
    25 % 3 = 1
    125 % 3 = 2
    625 % 3 = 1
    3125 % 3 = 2
    15625 % 3 = 1
    78125 % 3 = 2
    ...
    

    But there's still a pattern.

    If you could work out the math behind the patterns, I wouldn't be surprised if you could figure out the value of the mod without doing the actual power.

    Matthew Flaschen : The pattern is obvious and well-known. It's Fermat's Little Theorem (and the identity is used in the OP).
    Kai : Ah yes, you're right, thanks for pointing me to it. It's only obvious if you've considered this kind of problem before and I'm grateful to have derived the idea myself :)
    Tobias : Where is Fermat's little theorem used in the OP?
    Matthew Flaschen : Sorry, I spoke too quick. This isn't Fermat. Both Kai's post and the OP are basic modular multiplicatioon.
  • Python has pow(a,b,c) which returns (a**b)%c (only faster), so there must be some clever way to do this. Maybe they just do the identity you mentioned.

  • Looks like homework in cryptography.

    Hint: check out Fermat's little theorem.

  • I guess you are looking for : http://en.wikipedia.org/wiki/Montgomery_reduction or the simpler way based on Modular Exponentiation (from wikipedia)

    Bignum modpow(Bignum base, Bignum exponent, Bignum modulus) {
    
        Bignum result = 1;
    
        while (exponent > 0) {
            if ((exponent & 1) == 1) {
                // multiply in this bit's contribution while using modulus to keep result small
                result = (result * base) % modulus;
            }
            // move to the next bit of the exponent, square (and mod) the base accordingly
            exponent >>= 1;
            base = (base * base) % modulus;
        }
    
        return result;
    }
    
    Brian : If the modulus is smaller than the exponent, I think you could improve this algorithm by taking the modulus of the count of 1 bits of the exponents and only do that many loop iterations. One could actually do even better than that in some cases. See Kai's answer.
    johnnycrash : i think you can break out whenever result = 0 result = (result * base) % modulus; if (result == 0) break;
    johnnycrash : The formatting screwed up my comment. Add "if (result == 0) break;" after the calculation of result.
    johnnycrash : Actually before you mutliply result*base, check base==0 and break then.
    johnnycrash : You can break out at the bottom after "exponent >>= 1;" if exponent == 0 and avoid having to do the last mulitply and mod.
  • Here's an example of Fast Modular Exponentiation (suggested in one of the earlier answers) in java. Shouldn't be too hard to convert that to C#

    http://www.math.umn.edu/~garrett/crypto/a01/FastPow.html

    and the source...

    http://www.math.umn.edu/~garrett/crypto/a01/FastPow.java

  • .NET in general has poor performance for simple math operations. I'd actually look into adding an unmanaged dll into your project.

    The GMP library is probably a good candidate as it's fast and has well optimized big integer support... http://gmplib.org/

    In fact, I think GMP would support everything you need to do natively, and would be much, much faster than anything you'd write in .NET. I'd just try porting your C# example into an unmanaged C++ project that uses GMP. Then build the C++ project and add it as a reference in your .NET project. You'd end up with a kind of hybrid half managed, half unmanaged application but for heavy math operations like this it can be worth it.

Changing the active_resource_store database for sessions in rails 2.3.2

There's a great answer for my question over here http://stackoverflow.com/questions/378376/rails-shared-sessions-with-activerecord but it has to do with rails 2.2.2. The method used has been deprecated in 2.3.2.

Does anyone know how to use an external database for session data in rails 2.3.2? The overall goal is session sharing between two apps using two different databases. thanks!

From stackoverflow
  • Alright, found what I need. Not tested 100% to make sure it's working, but it doesn't spawn errors anymore.

    CGI::Session::ActiveRecordStore has been replaced in rails 2.3.2 with ActiveRecord::SessionStore

    So the new method to connect to an external db SHOULD be ActiveRecord::SessionStore::Session.establish_connection(:connection_name)

iReport: Sub-reports using XPath (XML Data Source) show up blank

Hello,

I am using iReport 3.5.2 to create a report using an XML data source. I followed the "Step by step" example from the "Sub-reports" section of "The Ultimate Guide to iReport", and I was able to get the example working with SQL. However, when I try to use an XML data source and XPath, the sub-report comes out blank in the master report's rendition (though it renders fine by itself).

What I am doing is fairly straight-forward:

  • I create a master report
  • I place a sub-report into it which passes a parameter with a value like "/Foo/Bar" (the XPath for the particular list of data I want in the sub-report)
  • I place a field in the sub-report which references this XPath using $P{}

Again, I can render the sub-report alone and enter a parameter value like "/Foo/Bar" and the report will render as anticipated. I have tried removing XPath from the equation all together and simply creating a field with the parameter value, and still I get a blank page. This makes me suspect that something deeper than XML/XPath is wrong.

Thank you! Sean Purser-Haskell, Kewill PLC

From stackoverflow
  • I came across your post and share your pain. I was in the exact same situation. The code in the iReport/XML datasource/sub report tutorial is broken. I found this on the jasper forums and it solved my issues. Essentially, the datasource expression used in the example is wrong, you need to replace it with an xpath query for the report items of the subreport. something like this:

    ((net.sf.jasperreports.engine.data.JRXmlDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("//YOUR_SUBREPORT_ENTITY")

    http://jasperforge.org/plugins/espforum/view.php?group_id=83&forumid=101&topicid=48534

Setting Data Property in Silverlight Path Style

I am trying to put as much properties of a Path element into a Style, this works out ok, as longs as I don't add Data to the Style setters:

<UserControl x:Class="Demo.Controls.SilverlightControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.Resources>
            <Style x:Name="PathStyle" TargetType="Path">
                <Setter Property="Data" Value="0,0 L1,0"></Setter>
                <Setter Property="Stroke" Value="Blue"></Setter>     
                <Setter Property="Stretch" Value="Fill"></Setter>
            </Style>

        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Path Grid.Row="0"
               Height="7"               
               Data="M0,0 L1,0"
               Stretch="Fill"
               Stroke="Black"/>
        <Path Grid.Row="1"
               Height="7"               
               Style="{StaticResource PathStyle}"/>
    </Grid>
</UserControl>

If you open this example, you'll see that the first path gives no problems, but the second one results in an AG_E_UKNOWN_ERROR in Visual Studio 2008.

Is it possible to define the Data of a Path in a Style?

From stackoverflow
  • This should work

    <Style x:Name="PathStyle" TargetType="Path">
                    <Setter Property="Data" Value="M0,0 L1,0"></Setter>
                    <Setter Property="Stroke" Value="Blue"></Setter>
                    <Setter Property="Stretch" Value="Fill"></Setter>
                </Style>
    

JQuery - web form to mysql via php - textfield not formatting correctly.

Can anybody suggest the best way of keeping the formatting intact of a text field - ie. keeping the line breaks or carriage returns in mysql and then recognising them when the form is populated on login?

Currently when the textfield data is stored (in a TEXT field in mysql) its losing the carriage return values and adding a small square box instead.

Would it be a case of formatting with nl2br or using a str_replace instead?

Thanks

From stackoverflow
  • The square box is likely just not having the character set to show the paragraph marker (¶) that MySQL wants to show in place of carriage returns.

    You should be able to pull the data back out of MySQL into a textarea to confirm that the data is being stored properly.

  • This is not a jQuery issue. The $_POST should come with the correct breaks included.

  • I solved my own problem. It wasn't a jQuery issue but I wasn't addressing the posted variable in the correct way.

    Elzo Valugi : what did I say?

How do I attach my application into another .Net application?

I'm trying to create a quick debugger, wherein I can attach my application to a running .net process and execute scripts from there. I'm using C#.

How will I do it?

Thanks :)

From stackoverflow
  • This looks like a decent introductory article.

  • You can attach to a process in Visual Studio and use VS tools for debugging. What does your application do that would require it to be attached to other processes outside of VS?

    http://msdn.microsoft.com/en-us/library/c6wf8e4z.aspx

    Marc Vitalis : The application should be small, and there will be no codes to step into. I'll be pushing those scripts in the running process.

(GoogleChartSharp) Why is this Google Charts scatter chart all messed up?

Hey gang,

So I'm putting together a little code metrics report based off of usage data I've been collecting via the CodeSharp AOP libraries.

Here's what the piechart data looks like: alt text

However, here's what I'm getting for the scatterchart: alt text

Here's the code, modified to change the datasets into literal arrays and minus the labels:

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using GoogleChartSharp;

int[] totalCalls={161,35,15,100,94,87,84,84,76,76,76,74,74,71,71,69,69,23,66,61};        
int[] totalCPU ={ 180, 100, 94, 55, 52, 48, 47, 47, 42, 42, 42, 41, 41, 39, 39, 38, 38, 38, 37, 34 };

        int[] averageRunningTime={18,45,100,9,9,9,9,9,9,9,9,9,9,9,9,9,9,27,9,9};

        List<int[]> dataList = new List<int[]>();
        dataList.Add(totalCalls);
        dataList.Add(averageRunningTime);
        dataList.Add(totalCPU);


        ScatterPlot sp = new ScatterPlot(600, 300);

        ChartAxis totalCallsAxis = new ChartAxis(ChartAxisType.Left);
        totalCallsAxis.SetRange(15, 161);

        ChartAxis averageRunningTimeAxis = new ChartAxis(ChartAxisType.Bottom);
        totalCallsAxis.SetRange(9, 100);

        sp.SetData(dataList);



        Image1.ImageUrl = sp.GetUrl();

What could be the problem?

Just in case someone has been following this question, here's the latest version of the scatterchart: alt text

From stackoverflow
  • Two possible solutions:

    1. You never explicitly added the ChartAxis types to the ScatterPlot. Check the Scatter Plots example for where I drew this info from.
    2. A poster on this page said his scatter plot was not working because he was attempting to add float values greater than 100. I noticed that you (might, not sure as I have not worked with this API before) are doing the same thing.

    Hope this helps!

    Chris McCall : Thanks, that's helpful, especially the > 100 tip
  • Basically, the CodeSharp library is doing some trickery with the numbers encoding Google Charts insists on, which results in these odd display problems. I tinkered with the data normalization procedures a little and achieved the results I was looking for.

  • Hi I am having the same problem with line graphs. What exactly did you tinker to get this to work.

    Thanks

"Access is Denied" error in javascript

I am using window.open(0 method to open a new popup window. It's showing javascript error "Access Denied". My code is below:

Script Code:

function wopen(url, name, w, h)
{
    var win = window.open(url,
                  name, 
                  'width=' + w + ', height=' + h + ', ' +
                  'location=no, menubar=no, ' +
                  'status=no, toolbar=no, scrollbars=no, resizable=no');
    win.resizeTo(w, h); 
    win.focus();       
}

HTML Code:

<a href="<%=link("*","PopupDisplay")%>" target="popup" 
    onClick="wopen('<%=link("*","PopupDisplay")%>', 'popup', 450,200); return false;" 
    id ="CommerceQuery_fourpartlink"4 Part Key#</a>

// "PopupDisplay" will forward to the corresponding link
From stackoverflow
    1. See if you have any popup blockers enabled.
    2. A security restriction on window.open is that you can only open windows in the same domain, to prevent any cross domain security forgeries. see http://www.mozilla.org/projects/security/components/ConfigPolicy.html
    3. make sure that your current script can access the window object. Some scripts in iframes, etc cannot open window objects.
    Cerebrus : +1 for mentioning the same/different domain issue. That was what I had in mind.

Is there a decent tool for automatically cleaning the crap out of VS solution directories?

I'm looking for a tool to automatically clean all the .suo, .user, files... bin, obj, directories, etc out of a VS solution directory... One I came across was Jeff Atwood's CleanSourcePlus but it's quite old at this point, requires .NET 1.0 to be installed (I know...but it's a pain), and was written in VB :P

I basically want the same functionality (explorer shell integration would be great) but something a bit newer and designed to handle Win32 projects, not just .NET (as CleanSourcePlus is limited too)

I was thinking about re-writing CleanSourcePlus to use .NET 2.0 (at least) and in C#, but don't want to duplicate work that's already been done...

Any good tools for this out there?

From stackoverflow

Is it possible to run Java ME apps in Palm Z22?

I want to develop a java app that should run in Palm Z22. Will it be possible?

If you could provide me some start point I would appreciate.

From stackoverflow

Silverlight 2 datagrid headers

Is there a way to change the column headers of a SL2 datagrid during databinding? I'm looking for something similar to ASP.net's rowDataBound, I'm looking at _LoadingRow is this the correct event?

From stackoverflow
  • You can bind DataColumns in your XAML

     <data:DataGridTextColumn Header="Latitude" Binding="{Binding lat}"  IsReadOnly="True"  />
    
  • Why would you change column headers based on row data. Binding/changing column headers should not be row driven.

    Jeff Yates : This should be a comment rather than an answer.
  • As suggested by rAyt in their answer, you can add bindings to the columns. With an appropriate binding and possibly a value converter, you could use this mechanism to update the headers.

    You can also set the DataGrid to auto-generate columns based on the collection data. You may find this a better route. You can also modify the auto-generated columns as described by this MSDN article.

MySQL SELECT with a condition help

CREATE TABLE `comments` (
  `comment_id` int(11) NOT NULL AUTO_INCREMENT,
  `comment_parent_id` int(11) NOT NULL DEFAULT '0',
  `user_id` int(11) NOT NULL DEFAULT '0',
  `comment_text` varchar(200) NOT NULL DEFAULT '',
  `comment_created` int(20) NOT NULL DEFAULT '0',
  `comment_updated` int(20) NOT NULL DEFAULT '0',
  `comment_replies_count` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`comment_id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1

Each comment can have multiple replies, however, replies cannot be replied to. So when someone replies to a comment, the row they insert will have the ID for the comment they replied to in the parent ID column.

I would like to retrieve all comments and if the comment has replies, I would like to retrieve the last reply.

SELECT c1.* 
FROM comments c1 
WHERE comment_parent_id = '0' 
ORDER BY comment_created DESC;

So if c1.comment_replies_count > 0 I would like to... 

SELECT c2.* 
FROM comments c2 
WHERE comment_parent_id = c1.comment_id 
ORDER BY comment_created DESC Limit 1;

Can this be achieved in 1 query? Or Is it best to do another call to the database, during the php loop statement, to fetch the last reply to the comment?

Thanks in advance and please pardon my ignorance as I'm learning still.

From stackoverflow
  • Try a sub-select:

    SELECT * FROM comments WHERE comment_parent_id in (
    SELECT c1.comment_id 
    FROM comments c1 
    WHERE c1.comment_parent_id = '0' 
    AND c1.comment_replies_count > 0
    ORDER BY comment_created DESC)
    ORDER BY comment_created DESC Limit 1;
    
  • You can join the table back onto itself:

    SELECT c1.*, c2.*, MAX(c2.comment_id)
    FROM comments c1 LEFT JOIN comments c2 ON c1.comment_id = c2.comment_parent_id
    WHERE c1.comment_parent_id = '0' 
    GROUP BY c1.comment_id
    ORDER BY c1.comment_created DESC
    
    Allain Lalonde : Dang, beat me to it.
    Seth : This kinda works, but it is not retrieving the last reply -always the first. eg: comment (ID 1, parent ID 0, text "Hello") first reply (ID 2, parent ID 1, text "Reply to comment 1") second reply (ID 3, parent ID 1, text "Another reply to comment 1") Even though MAX is returning 3, it returns the ID and text from the first reply.
    acrosman : Try adding a clause to the WHERE clause to compare the MAX() to the c2.comment_id.