Thursday, April 14, 2011

How to get ASP.NET control string property to display suggested list in designer dropdown?

How can I add a string property to my ASP.NET custom control that will result in the designer (either in HTML view or wysiwyg view) providing auto-complete by providing a list of some 30 suggested strings, while allowing for custom strings to be input?

Right now I'm using a property of type enum to allow the user to select from a list, but the strings have to be valid enum value names, and they need to be URIs. Also, it doesn't allow for inputting of custom strings.

From stackoverflow
  • Look at TypeConverter.

    You will need to override GetStandardValues and GetStandardValuesSupported. You can feed this want ever you want at runtime.

How to set "org.w3c.css.sac.parser" system property?

In this ParserFactory.java

String className = System.getProperty("org.w3c.css.sac.parser");
if (className == null) {
    throw new NullPointerException("No value for sac.parser property");  //line 35
} else {
    return (Parser)(Class.forName(className).newInstance());
}

When I run this DemoSAC.java file as Java Application in Eclipse, I got

Exception in thread "main" java.lang.NullPointerException: No value for sac.parser property
at org.w3c.css.sac.helpers.ParserFactory.makeParser(ParserFactory.java:35)

What exactly is the "org.w3c.css.sac.parser" property? How do I set it under Windows? What should I set it to?

Thanks!

From stackoverflow
  • It looks like you need to provide an interface implementation. Per this link here, this is one way to do it:

    • get the flute parser here
    • add it to your build path
    • add this to the DemoSAC class (before the getProperty call):

      System.setProperty("org.w3c.css.sac.parser", "org.w3c.flute.parser.Parser");

    I don't know why it is doing this reflection based instantiation to begin with, perhaps bypassing ParserFactory and returning a new instance of the flute parser would be cleaner altogether?

  • If you don't want to modify code, you can also set a Java property in Eclipse's Java launch configuration dialog. You specify a "VM option" in the "Arguments" tab . To set the property to "org.w3c.flute.parser.Parser" as suggested by javamonkey79, you would specify:

    -Dorg.w3c.css.sac.parser=org.w3c.flute.parser.Parser

How do I cancel a Delete in SQL

I want to create a trigger to check what is being deleted against business rules and then cancel the deletion if needed. Any ideas?

Update The solution used the Instead of Delete trigger. The Rollback tran stopped the delete. I was afraid that I would have a cascade issue when I did the delete but that did'nt seem to happen. Maybe a trigger cannot trigger itself. Anyhow, thanks all for your help.

From stackoverflow
  • Use an INSTEAD OF DELETE (see MSDN) trigger and decide within the trigger what you really want to do.

  • The trigger can roll back the current transaction, which will have the effect of cancelling the deletion. As the poster above also states, you can also use an instead of trigger.

  • According to MSDN documentation about INSTEAD OF DELETE triggers:

    The deleted table sent to a DELETE trigger contains an image of the rows as they existed before the DELETE statement was issued.

    If I understand it correctly the DELETE is actually being executed. What am I missing?

    Anyway, I don't understand why do you want to delete the records and if the business rules are not passed then undelete those records. I would have swear it should be easier to test if you pass the business rules before deleting the records.

    And I would have said use a transaction, I haven't heard before about INSTEAD OF triggers.

    Leo Moore : The problem is that the application allows the user to delete something assigned to them but since I don't have the source code I can only stop it at the DB level. I don't want users deleting tasks which have been assigned to them which are not completed.
  • The solution used the Instead of Delete trigger. The Rollback tran stopped the delete. I was afraid that I would have a cascade issue when I did the delete but that did'nt seem to happen. Maybe a trigger cannot trigger itself. Anyhow, thanks all for your help.

    ALTER TRIGGER [dbo].[tr_ValidateDeleteForAssignedCalls]
    on [dbo].[CAL]
       INSTEAD OF DELETE
    AS 
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;
    
        DECLARE @RecType VARCHAR(1)
        DECLARE @UserID VARCHAR(8)
        DECLARE @CreateBy VARCHAR(8)
        DECLARE @RecID VARCHAR(20)
    
        SELECT @RecType =(SELECT RecType FROM DELETED)
        SELECT @UserID =(SELECT UserID FROM DELETED)
        SELECT @CreateBy =(SELECT CreateBy FROM DELETED)
        SELECT @RecID =(SELECT RecID FROM DELETED)
    
         -- Check to see if the type is a Call and the item was created by a different user
        IF @RECTYPE = 'C' and not (@USERID=@CREATEBY)
    
        BEGIN
            RAISERROR ('Cannot delete call.', 16, 1)
            ROLLBACK TRAN
            RETURN
        END
    
         -- Go ahead and do the update or some other business rules here
        ELSE
         Delete from CAL where RecID = @RecID 
    
    END
    
  • dunno what you're using this for, but if its an application you need to be handling your business logic in your bus objects...not in a trigger....but if you have to....put the bus logic in the delete proc

Speech Recognition for Searching Files

Here is the problem I have:

I have a lot (tens of thousands) of mp3 files that my users would like to be able to search. Is there is software out there that you've used or heard good things about that would allow me to index that content and put it in a database so I can search on it later?

From stackoverflow
  • I've heard very good reviews of Dragon Naturally Speaking, by Nuance. They offer a software development kit, but I couldn't find out any information about pricing for small projects.

    Jon : Do you know if there is a developer's API?
    Jonathan : It seems that they do, yes.
  • There's an open source library Sphinx

multiple versions of Crystal Reports in web.config

Before we were not using Crystal Reports. In our project now we have added Crystal Reports to our project. When I transferred my project to the server it produced a Crystal error. I suspect that Crystal is not installed on the server. Then installed Crystal 11 on the server. The development machines have Crystal 8.5. The server produces this error at the application startup.

"Could not load file or assembly 'CrystalDecisions.ReportAppServer.ClientDoc, Version=10.2.3600.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified."

  • Is it possible to have two version reference in web.config? (i.e. crystal 8.5 & 11)

  • How can this issue be solved?

Using C#, Visual Studio 2005, and Crystal Reports 8.5 in the development environment.

From stackoverflow
  • It's just a version conflict, since your development machine is using an earlier version it's looking for that version of the .DLL file when you try to run it on the server. You're probably best off making sure the same version is installed on both your dev machine and the server, and then making sure your web.config using the DLL files from Crystal 11 in both.

    The quick hack for now is to figure out the correct file version on the server, and enter that number into the web.config.

    EDIT: The other option is to change the version of the .DLL in your web.config on the server, which is basically what the others are saying. The problem there is that you'll have to keep changing it every time you deploy... which would be very annoying. Plus you're testing on the dev machine isn't really valid because you're testing a different program. You're almost guaranteed to see bugs in production that you'll never see in DEV because something's changed between versions.

    Is there some reason you can't install Crystal 11 on your dev PC?

    Kartik : is it possible can i use both version dll reference in web config ?
    Telos : No, I'm pretty sure it will complain about objects existing in two places...
  • You probably need to add the reference to that DLL in your project (or otherwise get it into your /bin folder.

    Kartik : Can you please explain more which dll is require?
    Jeff Martin : CrystalDecisions.ReportAppServer.ClientDoc that is version 10.2.3600
  • The error messages says it all, does your server have version 10.2.3600.0 of CrystalDecisions.ReportAppServer.ClientDoc with matching token in either the GAC or somewhere it will be found by your application or web site?

    Sounds like you need a config update on the server.

  • No, it is not possible to reference two different versions of the same named assembly.

    One way to make this work is to have two different web.config files. One for dev, the other for production. As part of your deployment, simply use the prod version of the file. If your deployment is automated this should be as simple as deleting the dev web.config and renaming the production version after the files have been copied over.

  • 10.2.3600.0 is the version of Crystal Reports that was included with Visual Studio 2005 with the latest patch.

    You need to install the Crystal Reports runtime for .net 2.0 on the server. You can obtain the runtime installers from a dev machine

    x64 C:\Program Files (x86)\Microsoft Visual Studio 8\Crystal Reports\CRRedist\X64

    x86 C:\Program Files (x86)\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\CrystalReports

Cast to LPCWSTR???

I'm trying to create a (very) simple Win32 GUI program, but for some reason the compiler (I'm using VC++ 2008 Express) wants me to manually typecast every string or char* to LPCWSTR:

I get this compiler error every time I do this, for example I get this error for the "Hello" and "Note":

error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'const char [22]' to 'LPCWSTR'

Please tell me I don't have to cast every time I do this....

Here's the code:

#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 
    LPSTR lpCmdLine, int nCmdShow)
{
    MessageBox(NULL, "Hello", "Note", MB_OK);
    return 0;
}
From stackoverflow
  • The problem is that you're building for UNICODE and are passing non-Unicode strings.

    Try:

    MessageBox(NULL, L"Hello", L"Note", MB_OK);
    

    or set up your build for ANSI/MBCS or look into using TCHARs (which are a pain).

  • The default for new projects in VS2008 is to build UNICODE aware applications. You can either change that default and go back to using ANSI or MBCS apps (Properties->Configuration Properties->General->Character Set), or use Unicode Strings like this:

    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 
        LPSTR lpCmdLine, int nCmdShow)
    {
        MessageBox(NULL, L"Hello", L"Note", MB_OK);
        return 0;
    }
    

    Do not cast your strings to LPCWSTR because that will lead to undefined behavior! A char is not the same as a wchar_t!

  • My memories of Win32 C programming are hazy, but as I recall, you need to start by wrapping your string literals in this macro:

    _T("mystring")

    When you build unicode, this will be converted to a unicode string.

    If you only build unicode, or you are sure that you are only handling a particular string in unicode, you can use the L"" marker, which is what the _T macro does under the covers.

    You may need to include the tchar.h header.

    When doing win32 programming, I usually declare strings as TCHAR * szWhatever so that things work on Win9x almost as well as NT/Win2k/XP. (There are other convenience macros in there as well such as the LPTSTR and so on, and MFC contains some easy conversion macros for the cases when you actually need to convert between ansi and unicode to call specific APIs).

  • As other posts said, you are building a Unicode application. You can switch to and from Unicode project in project settings (don't forget to set it for both "Debug" and "Release" configurations.

    If you want to use it, you'll have to prepend all your static strings with L:

    L"Some static string"
    

    For char[] strings there's a method mbstowcs_s, which is used roughly like this:

    std::string str; // the string you want to convert
    
    WCHAR wstr[128];
    size_t convertedChars = sizeof(wstr)/sizeof(WCHAR);
    mbstowcs_s(&convertedChars, wstr, str.c_str(), _TRUNCATE);
    

    This is how I used it in one of my projects. For exact usage refer to MSDN.

Why can I not concatenate two strings and assign them to a symbol?

. . . as in this example:

helloworld.rb:1: syntax error, unexpected '=', expecting $end
:helloworld = "hello ".concat("world")

I thought if I use concat I'm modifying the string "hello " and adding "world" to it and then ultimately assigning the resulting string - "hello world" - to the :helloworld symbol on the left side of the equals sign. I thought that would be legal, just as if I had written:

:helloworld = "hello world"

oh, wait, that doesn't work either. (scratches head).

From stackoverflow
  • Well, yeah. You can't assign to symbols. Do you mean something like:

    foo = { :helloworld => "hello ".concat("world") }
    

    ?

  • Ruby symbols cannot have values assigned to them since they represent a canonical value. If you want to build a symbol from a string, you can use "hello ".concat("world").to_sym.

    dbarker : There are a couple other options. :"hello world" is the most direct, but if the symbol is unknown until runtime, you could store it in a var: foo = "hello ".concat("world").to_sym.
  • symbols are confusing when coming from languages that don't have anything like them. You can't assign to symbols, that's not what they're for.

    Here are a couple of examples that may help explain it.

    5.times do |i|
      # a new string is created in each iteration of the loop
      puts "my string".object_id
    
      # there is only ever one symbol for each possible value
      # so a new object is not created during each iteration
      puts :my_symbol.object_id
    
      # this often makes a difference when you're using them for things like hash keys
      #some_method(:name => 'bob')
      #some_method('name' => 'bob')
    end
    

    The other big difference is that a symbol comparison is simply a pointer comparison.

  • Perhaps what you're actually looking for is a constant? They can be dynamically generated, referred to later, and you get a warning if you try to reassign one.

    >> HELLO_WORLD = "hello ".concat("world")
    => "hello world"
    >> HELLO_WORLD = "foo"
    (irb):3: warning: already initialized constant HELLO_WORLD
    => "foo"
    
  • Try this:

    :"hello world"
    

Confused on C# Array of objects and implicit type conversion

I am trying to pass an array of a simple object to a web service and I'm really stuck on this error during compile of my web client project:

Cannot implicitly convert type 'TRIMBrokerUtil.MetaData[]' to 'TRIMBrokerASMXProxy.ASMXProxy.MetaData[]'

Here is my "utility" project compiled into TRIMBrokerUtil.dll:

namespace TRIMBrokerUtil
{
    public class MetaData
    {
 protected string _Name;
 protected string _Value;
 public MetaData(string keyword, string setting) 
 {
     this.Name = keyword;
     this.Value = setting;
 }
 public string Name
 {
     get
     {
  return this._Name;
     }
     set
     {
  Name = value;
     }
 }
 public string Value
 {
     get
     {
  return this._Value;
     }
     set
     {
  _Value = value;
     }
 }
    }

Here is a snippet of the web service which also compiles fine: using TRIMBrokerUtil; namespace TRIMBrokerService { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class FileService : System.Web.Services.WebService {

 [WebMethod]
 public string UploadFile(byte[] incomingArray
     , string FileName
     , long FileLengthInBytes
     , MetaData[] metaDataArray)
 {

...and usage later as this:

Update update = BuildMetaData(metaDataArray);

...and this:

private Update BuildMetaData(MetaData[] nvPairs)
{
    Update update = new Update();
    InputProperty[] ip = new InputProperty[nvPairs.Length];
    int i;
    for (i=0; i < nvPairs.Length; i++)
    {
 ip[i].Name = "udf:" + nvPairs[i].Name;
 ip[i].Val = nvPairs[i].Value;
    }
    update.Items = ip;
    return update;
}

Next, (via "Add Web Reference") I have my proxy class for the ASMX webservice in a separate project and it compiles without problem. Inside the generated reference.cs file I find this which seems OK:

    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/UploadFile", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    public string UploadFile([System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] byte[] incomingArray, string FileName, long FileLengthInBytes, MetaData[] metaDataArray) {
        object[] results = this.Invoke("UploadFile", new object[] {
                    incomingArray,
                    FileName,
                    FileLengthInBytes,
                    metaDataArray});
        return ((string)(results[0]));
    }

Now for the error that occurs in compilation in the web client project (default.aspx.cs):

    using TRIMBrokerUtil;

public partial class _Default : System.Web.UI.Page
{
    private void UploadFile(HttpPostedFile postedFile
       , string fileNameOnly
       , MetaData[] metaDataArray)
 {
     string strURI = string.Empty;
     TRIMBrokerASMXProxy.ASMXProxy.FileService client = new TRIMBrokerASMXProxy.ASMXProxy.FileService();
     BinaryReader b = new BinaryReader(postedFile.InputStream);
     byte[] binData = b.ReadBytes(numBytes);
     TRIMBrokerASMXProxy.ASMXProxy.MetaData[] kvData = metaDataArray; // error complains about this line
     strURI = client.UploadFile(binData, fileNameOnly, binData.Length, kvData );

I have also tried changing the last 2 lines above to simply this one line:

strURI = client.UploadFile(binData, fileNameOnly, binData.Length, metaDataArray);

...but that change introduces a 2nd error from the compiler which reads as:

The best overloaded method match for 'TRIMBrokerASMXProxy.ASMXProxy.FileService.UploadFile(byte[], string, long, TRIMBrokerASMXProxy.ASMXProxy.MetaData[])' has some invalid arguments

(note the original error about "cannot convert" is the 2nd error).

Sorry about being so verbose above. Hope you can help shed light on this confusion.

From stackoverflow
  • You are trying to assign an array of TRIMBrokerUtil.MetaData to an array of TRIMBrokerASMXProxy.ASMXProxy.MetaData. Remember that the asp.net proxy declares its own type.

    Just copy the data into a new array with the proxy type.

    John Galt : Freddy, not sure what you mean: "copy the data". A loop?
    eglasius : y, a loop, a linq with ToArray, any way to copy the data from the array to a new one with the current loop.
    John Galt : I barely know C# and I seem to have stumbled into something "advanced". Apparently my attempt to share a type definition between service and client is thwarted because proxy "declares its own type". So, I'll try to copy from my intended type to the proxy's type. Is there a better way to do this?
    eglasius : Y, sharing the type isn't supported directly by the asmx way of doing it. The new way (WCF) supports sharing the type, but as you are learning I would stick to the simple. Just avoid doing it in a way you need to share the types.
  • When you add a reference to the Web Service, Visual Studio will automatically generate code for the objects that are used as parameters to the functions of the web service. This is where your TRIMBrokerASMXProxy.ASMXProxy.MetaData class comes from.

    This is not the same as your TRIMBrokerUtil.MetaData class. You can remove the class from your TRIMBrokerUtil namespace and just use the one from the web service proxy instead.

Why doesn't this work? Calling functions belonging to objects in a loop.

In my code jsc.tools is an object containing objects. Each sub-object contains a init() and run() method.

I have the following code running at startup:

for(tool in jsc.tools) {
 tool.init();
}

which gives me the error "tool.init is not a function".

A sample of a tool's declaration is:

jsc.tools.sometool = {};
jsc.tools.sometool.run = function() {
    // Apply tool
}
jsc.tools.sometool.init = function() {
    // Set bits of data needed for the tool to run
}
From stackoverflow
  • The for in x operator in javascript gives you the names of the properties off an object. Try:

    for(tool in jsc.tools) {
        jsc.tools[tool].init();
    }
    
    Pim Jager : This has caught me quite a few times too. You'd think the for(x in ..) would set x to the object/array/string/whatever, but it only sets x to the key.
  • you need to use

    for(tool in jsc.tools) {
        jsc.tools[tool].init();
    }
    

ms access sum on groups, not on details

I am trying to calculate a SUM in an MS Access report the following way:

  • Group1header - label

    • Group2header - value
      • Detail - example
      • Detail - example
    • Group2header - value
      • Detail - example
  • Group1footer [sum of Group2header value]

Somehow, when more detail rows appear, the sum in group1footer is incorrectly calculated (adds value for each detail).

I can not calculate the sums in the query, because the "value" is already a calculated in the query (a subquery would return to many rows):

(
    (
        (sl_ticketdetail.weight,0) * sl_ticketdetail.amount 
        - (
            SELECT SUM(sl_invoicedetail.amount)
            FROM sl_invoicedetail 
            WHERE ticketdetailid = sl_ticketdetail.ticketdetailid
        )
        / 1000
    )
    * sl_ticketdetail.cost
)
/ 1000

Thanks for your reactions.

From stackoverflow
  • Hi,

    Are you saying your are getting results like this:

    Group 1a
        Group 2a
            Foo1         1
            Foo2         1
            foo3         2
        Group 2a Sum   4
        Group 2b
            Foo1         3
            Foo2         3
        Group 2a Sum   6
    Group 1a Sum    10
    Group 1b
        Group 2a
            Foo1         4
            Foo2         1
            foo3         2
        Group 2a Sum   7
        Group 2b
            Foo1         4
            Foo2         3
        Group 2a Sum   14
    Group 1b Sum    21
    

    This is the behaviour I would expect. I was able to do it by putting =Sum([value]) in an unbound field in each group footer (and even in the report footer).

    I know 'works for me' isn't very helpful.

    Have you labelled the detail's values fields (or the summary fields) with the same name as the data source? Sometime MS Access has weird behaviour if your fields have the same name as their bound data source (I tend to rename them slightly so I'm sure what I'm referring to in code).

  • Since you already have the Group2 sums pre-calculated in your query they will be repeated for each row of results and therefore cannot be used (as you found out) to calculate the Group 1 totals.

    You have two solutions

    1) pre-calculate the Group1 totals in your query as well and simply report them liek you do the Group2 totals

    2) use code in the Group2 footer format/print events to capture the value and manually increment a running Group1 total

    I would say 1) is the easiest - 2) is a little hairy and sometimes results in inaccurate totals if the users pages back and forth

  • You would have to have the record source of the main report to include the totals for Group 2. Then you would need a sub report with a different record source that is on the detail level.

    I think your best bet, is to omit the totals in the query and just let the report do the totals on the details. Later, the user may want totals on the same date but a different grouping (yes, you could create another record source). This should also address if a user applies a filter on the report (You may or may not have given them this option.) on a field other than the grouping.

How can I restart a Windows service application written in Delphi?

I have a Windows service written in Delphi. One of the third-party resources it uses occasionally gets corrupted, and the only way I've found to fix the situation is to exit and restart the program. I can detect when the resource is corrupted from within the program, and I can tell Windows to restart the service after it stops, but I can't figure out how to have the service tell itself to stop.

The program is pretty simple. I created a service application in what seems to be the normal way. I have a subclass of TService to manage the service, while all of the functionality occurs in a separate thread. The TService subclass pretty much just manages the execution of the subthread, and it's in the subthread that I would be detecting the corruption.

For reference, here's the header info for the service and subthread.

type
  TScannerThread = class(TThread)
   private     
    Scanner    : TScanner;
    DefaultDir : String;
    ImageDir   : String;
    procedure CheckScanner;
   public      
    Parent     : TComponent;
    procedure Execute; override;
  end;         

  TCardScanSvc   = class(TService)
    procedure ServiceCreate(Sender: TObject);
    procedure ServiceExecute(Sender: TService);
    procedure ServiceStart(Sender: TService; var Started: Boolean);
    procedure ServiceStop(Sender: TService; var Stopped: Boolean);
    procedure ServicePause(Sender: TService; var Paused: Boolean);
    procedure ServiceContinue(Sender: TService; var Continued: Boolean);
   private        
    ScannerThread : TScannerThread;
   public         
    function GetServiceController: TServiceController; override;
  end;            

var
  CardScanSvc : TCardScanSvc;

In a GUI application, I'd call Application.Terminate, but TServiceApplication doesn't seem to have that method. I can terminate the subthread, but the main thread never notices, and Windows thinks the service is still running. I can't really think of much else to try.

The program was originally created in Delphi 5, and I'm currently using Delphi 2007, in case that makes a difference.


Edit:

With mghie's code, I can stop the service, but Windows will only restart the service if it fails unexpectedly, not if it's stopped normally. What I'm going to do is make a separate service application, have the first signal the second if it has problems, and then have the second restart the first.

From stackoverflow
  • You should be able to use WMI (Windows Management Instrumentation) to restart a service, even from within the service itself. Don't know if this would cause any strange problems but it should work. Here's an article on doing WMI with Delphi.

    UPDATE: Well well, I assumed (my mistake) that there is a single WMI service restart command, such as the button you can click in the services maangement listing. Apparently not.
    You could instead write a console app that the service starts when the data is corrupted. The console app would restart the service from a separate process.

    Rob Kennedy : Don't leave us hanging! What's the WMI command to restart a service?
  • There is no problem having the service stop itself - I just tried with one of my own services, written with Delphi 4 (without using the TService class). The following routine works for me:

    procedure TTestService.StopService;
    var
      Scm, Svc: SC_Handle;
      Status: SERVICE_STATUS;
    begin
      Scm := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
      if Scm <> 0 then begin
        Svc := OpenService(Scm, PChar(ServiceName), SERVICE_ALL_ACCESS);
        if Svc <> 0 then begin
          ControlService(Svc, SERVICE_CONTROL_STOP, Status);
          // handle Status....
          CloseServiceHandle(Svc);
        end;
        CloseServiceHandle(Scm);
      end;
    end;
    

    You need to check whether it will also work from your worker thread.

CSS precedence

My webpage contains:

<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<style type="text/css">
td {
    padding-left:10px;
} 
</style>

The referenced stylesheet contains:

.rightColumn * {margin: 0; padding: 0;}

I have a table in the rightcolumn ID where I want the cells to have a little padding. However, the referenced stylesheet is taking precedence over the inline styling. I see this visually and also via Firebug. If I turn off the padding:0 instruction in Firebug, the padding-left takes effect.

How can I get the padding-left to work?

From stackoverflow
  • The easiest way to get it to work is to add "!important" to CSS to guarantee its precedence (unless you've got multiple !important rules):

    td {
        padding-left: 10px !important;
    }
    

    If you're looking for an answer without !important, you should read into CSS specificity specifications. The linked site has a good explanation of how it works, though basically it goes from most important to least, with id selectors most important, class selectors second, and element selectors third.

    Rahul : Watch out when using !important. It will increase maintenance problems if you have other people working with the code that aren't familiar with your usage of the !important rule.
    Andrew Hare : Not to mention it breaks precedence which is confusing if you are looking at a rule that ought to be applied but isn't.
    Daniel Lew : I agree that !important should be used sparingly, but I find it similarly problematic when someone starts over-complicating their selectors just so they are more specific. For this example, it'd be td.rightColumn * { ... }, which is a horrific change to an otherwise simple selector.
  • Try this instead:

    td.rightColumn * {margin: 0; padding: 0;}
    

    The td in the external stylesheet is more specific so it wins out. If you qualify the rightColumn class with an element name then the page-level styles will be applied.

  • You could try adding the ! important flag to your inline css.

    e.g.

    td { padding-left:10px ! important; }

    Also, for general rules on css rule ordering, have a look at this :

    http://www.w3.org/TR/CSS2/cascade.html#specificity

    : Wow, this was my first question posted to StackOverflow. I thank you all for your responses. They made me think more deeply about the issue.
  • Do this:

    .rightColumn *,
    td.rightColumn * {
      margin: 0;
      padding: 0;
    }
    

    Precedence in CSS is as follows:

    • If some rule has an ID, then it will precede anything else.
    • If some rule has a class attribute, it will precede tag-only rules.
    • If two rules have both IDs or tags, then the number of them untie the "fight".

    Example:

    <style type="text/css">
      #myid{
        padding: 10px;
      }
    
      .class{
        padding: 20px;
      }
    </style>
    <div id="myid" class="class"></div>
    

    Although your div has both ID and a class, the ID rule will override the .class rule.

    To read more about CSS rules priorities, I'd recommend http://www.w3.org/TR/CSS2/cascade.html#specificity.

  • As others have mentioned, you have a specificity problem. When determining which of two rules should take precedence, the CSS engine counts the number of #ids in each selector. If one has more than the other, it's used. Otherwise, it continues comparing .classes and tags in the same way. Here, you have a class on the stylesheet rule, but not on the inline rule, so the stylesheet takes precedence.

    You can override this with !important, but that's an awfully big hammer to be using here. You're better off improving the specificity of your inline rule. Based on your description, it sounds like your .rightColumn element either is or contains a table and you'd like the cells in that table to have extra spacing? If so, the selector you're looking for is ".rightColumn td", which is more specific than the stylesheet rule and will take precedence.

  • Most of the answers are correct in saying that this is a specificity problem but are incorrect or incomplete in explaining the specificity rules.

    Basically in your case .rightColoumn * is "more specific" than td and so that rule wins even though it comes earlier.

    The CSS 2.1 rules are located here. These rules are:

    • count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
    • count the number of ID attributes in the selector (= b)
    • count the number of other attributes and pseudo-classes in the selector (= c)
    • count the number of element names and pseudo-elements in the selector (= d)

    Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.

    So in your case you have two rules:

    .rightColumn * {} /* a = 0, b = 0; c = 1, d = 0 : Specificity = 0010*/
    td {} /* a = 0, b = 0, c = 0, d = 1 : Specificity = 0001 */
    

    0001 is lower than 0010 and thus the first rule wins.

    There are two ways to fix this:

    1. Use !important to make a rule more "important". I'd avoid doing this because it is confusing when you have lots of rules spread out over several files.
    2. Use a higher-specifity selector for the td you want to modify. You can add a class name to it or an id and this will allow you to supersede the rule from the linked CSS file.

    Example:

    <style>
      .rightColomn * { padding: 0; } /* 0010 */
      td#myUnpaddedTable { padding: 10px; } /* 0101 */
      td.anUnpaddedTable { padding: 10px; } /* 0011 */ 
    </style>
    

    Edit: Fixed the specificity rules for *. David's comment prompted me to re-read the spec, which does show that the * selector contributes nothing to the specificity score.

    David Kolar : I concur. Based on the W3C page, though, I don't think that the star selector counts towards d-level (or any-level) specificity, so .rightColumn * should score 0010. I'd also recommend .rightColumn td {} as way to set the padding; it yields a good-enough score of 0011.
    Mr. Shiny and New : @David Kolar: Thanks, fixed.

PyObjC + Python 3.0 Questions

By default, a Cocoa-Python application uses the default Python runtime which is version 2.5. How can I configure my Xcode project so that it would use the newer Python 3.0 runtime? I tried replacing the Python.framework included in the project with the newer version but it did not work.

And another thing, are PyObjc modules compatible with the new version of Python?

From stackoverflow
  • PyObjC does not yet work with Python 3.0. According to Ronald Oussoren, a (the?) PyObjC developer, Python 3.0 support is possible, but not yet implemented:

    Support for Python 3.x is on my todo list but is non-trivial to achieve. PyObjC contains a large amount of pretty low-level C code, getting the details w.r.t. to the changes in 3.0 right is not easy. I have looked into a Python 3.x port and this should be fairly easy, but it's still a couple of days work. I'm not planning to work on that before the next release of PyObjC, that's way too long overdue as it is.

    I'm sure patches would be welcomed.

    Earl Claridad : I guess I have to wait. Thanks for the answer!

ASPX link to ASPX with IFRAME(ASP page inside)... now I want to redirect back to ASPX

I have an ASPX page that redirects to a page that has an IFRAME which requests an ASP page on an entirely different domain. Once I'm done doing what I need to do there, I need to get back to the original ASPX page.

Is there anyway to do this? history.goback(-1) does not work as it just refreshes the IFRAME. Any suggestions?

From stackoverflow
  • You could pass the original URL as a querystring parameter to the ASP.

    AnthonyWJones : Since the ASP is being displayed in the IFrame this isn't that helpful. I guess you meant the outer page that holds the IFrame for the ASP right?
  • I think you may want to consider some Javascript that can run from the page within the iFrame calling on the parent window to change the URL it has loaded.

  • You might consider includind a copy of the referer header as the HREF of an anchor in the outer page holding the IFrame. Clicking this link would return to the referer.

    This may not work in all circumstances. Browsers can be configured to not provide a referer.

    jlrolin : Adding a link outside the IFRAME won't work as the look of the page is supposed to be as if it was part of the application already. Basically, the IFRAME is serving up old pages we haven't converted yet to .NET. Preferably, I want a link inside the ASP page that would redirect.
    jlrolin : This is what I eventually had to do due to not being able to access the window.parent because of the different domains.

How to outer-join two tables (main and many-to-one sub-table) to get only ONE item from second table?

I have two tables that are something like this:

Main table: id (int), title (varchar), etc. Sub-table: main_table_id (foreign key into main table), tag (varchar), etc.

There can be zero or more subtable rows for a given row in the main table.

I want to do a query that will return every row of the main table, with the columns of the main table, and a the columns from only a single row (doesn't matter which) of the sub-table, if there are any, otherwise NULL in those columns.

Of course if I just do a basic LEFT OUTER JOIN then of course I get the main table repeated multiple times, one for each match in the sub-table.

I'm sure I have seen this done before using a LEFT OUTER JOIN and some sort of trickery that forces only one row to be selected from the sub-table, not all of them -- maybe picking out the minimum or maximum OID. However, more than an hour of googling has not yielded any solutions.

Does anybody have this trick in their toolbelt?

From stackoverflow
  • If you're just checking of there is something in the second table that goes with the items in the first table you can use an outer join with a group by clause and an aggregate:

    select t1.[name], count(t1.[name]) as t2count
       from table1 t1
       left outer join table2 t2 on t1.fk = t2.pk
    group by t1.[name]
    

    Then, anything that has 0 for t2count will be those that have nothing in table2

    edit: actually, I don't remember if t2count will have null or 0 in it...it should be one of those values.

    danwood : This one sort of works, though in reality my main table (t1) has multiple columns, and from what I can tell, I can't use the group-by trick for more than just the one column. select t1.*, t1.[name], .... --> (other column) must appear in the GROUP BY clause or be used in an aggregate function
    dustyburwell : you can just include multiple items in the group by if you need to select more than one column like "group by t1.[name], t1.id, t1.whatever
  • If you're using SQL Server, you can use the TOP clause. If it is something other than SQL Server, you'll have to see if that database offers something equivalent (many of them do). Something like this ...

    Select * from Main m
    left outer join 
    (select top 1 * from subtable s
      where s.main_table_id = m.id) q
    on q.main_table_id = m.id;
    

    Note: That is to show you the general idea. I didn't have a chance to run it, so there might be a couple of changes necessary, but the concept is there.

    danwood : Alas I'm on postgres so I don't think that can apply to me. Thanks anyhow!
    cbp : Including the inner WHERE clause doesn't work for me ("The multi-part identifier m.id could not be bound"). Removing it works ok.
    Charlie Flowers : I"m not surprised, I just typed it off top of my head without being able to run it. But the general idea is there. Thanks for supplying the detail.
  • I like Charlie's answer best, but i'm not sure if Postges has a TOP/LIMIT function, so here's an alternate solution that doesn't need one (but does assume sub_table has a primary key called "id"):

    SELECT * 
    FROM main_table m LEFT OUTER JOIN sub_table s 
    ON s.main_table_id = m.id
    WHERE s.id IS NULL OR s.id IN ( 
      SELECT MAX(id) FROM sub_table GROUP BY main_table_id
    )
    
    danwood : Hey it worked! I had to add a primary key to the sub-table but that did the trick.

Learning Trail for Java Web Development?

I've Inheritted a large Java Web project which I've got to make some modifications to, I'm a fairly competent Java Programmer when it comes the the basics but I've never done any JSP programming or EJB programming before. I remember vauguely doing some servlet programming 5 or so years ago in university, but I'm assuming that everything has changed since then.

I'd planned on getting myself up to speed this weekend, but I don't know where to start.

What would be a good learning trail to get me from Zero to proverbial Hero? or at least to a level of competency which will let me be able to read the JSP servlet and EJB code and understand how it works well enough to modify it and deploy it?

From stackoverflow
  • Ofcaurse it depends a lot on what project you inherited and when it was written. Also what technologies are used?

    The best resource on starting J2EE development I think it's the Java Passion site.

  • Find out how complex it is. There is a vast difference between a web application without EJB's and one with.

    Is it running in JBoss/Tomcat/Jetty/Resin/BEA/WebSphere?

  • The online tutorial on netbeans.org are very good. I recommend to download the NetBeans 6.5 IDE (free) and walk through the J2EE tutorials. The tutorials are very well written, and introduce the basic elements of enterprise and web development. They also require very little time to complete.

    http://www.netbeans.org/kb/

    Omar Kooheji : I'll have a look at it. We use eclipse at my company, but I'm sure I'll learn loads from using net beans.

Asynchronous Calls Newbie Question

Good Day,

I am working on a small project where I need to make two asynchronous calls right after another.

My code looks something like this:

AsynchronousCall1(); AsynchronousCall2();

The problem I'm having is that both calls take anywhere from one to two seconds to execute and I never know which one will finish last. What I'm looking for is a way to determine who finishes last. If Call1() finishes last, I do one thing. If Call2() finishes last, I do another thing.

TIA,

coson

From stackoverflow
  • I believe there is a method that is a member of the Thread class to check on a specific thread and determine its status. The other option would be to use a BackgroundWorker instead, as that would allow you to spell out what happens when that thread is finished, by creating seperate methods.

    The "thread-unsafe" option would be to use a class variable, and at the end of each thread if it isn't locked / already have the other thread's value, don't set it. Otherwise set it.

    Then when in your main method, after the call to wait for all threads to finish, test the class variable.

    That will give you your answer as to which thread finished first.

  • This is a simple example of using a lock to ensure that only one thread can enter a piece of code. But it's a general example, which may or may not be best for your application. Add some details to your question to help us find what you're looking for.

       void AsynchronousCall1()
       {
            // do some work
            Done("1");
       }
    
       void AsynchronousCall2()
       {
            // do some work
            Done("2");
       }
    
       object _exclusiveAccess = new object();
       volatile bool _alreadyDone = false;
       void Done(string who)
       {
            lock (_exclusiveAccess)
            {
                 if (_alreadyDone)
                     return;
    
                 _alreadyDone = true;
                 Console.WriteLine(who + " was here first");
            }
       }
    
    eglasius : +1 y, that will work
  • You may want to check out the Blackboard design pattern: http://chat.carleton.ca/~narthorn/project/patterns/BlackboardPattern-display.html. That pattern sets up a common data store and then lets agents (who know nothing about one another -- in this case, your async calls) report their results in that common location. Your blackboard's 'supervisor' would then be aware of which call finished first and could direct your program accordingly.

  • You can do this with two ManualResetEvent objects. The idea is to have the main thread initialize both to unsignaled and then call the asynchronous methods. The main thread then does a WaitAny on both objects. When AsynchronousCall1 completes, it signals one of the objects. When AsynchronousCall2 completes, it signals the other. Here's code:

    ManualResetEvent Event1 = new ManualResetEvent(false);
    ManualResetEvent Event2 = new ManualResetEvent(false);
    
    void SomeMethod()
    {
        WaitHandle[] handles = {Event1, Event2};
        AsynchronousCall1();
        AsynchronousCall2();
        int index = WaitHandle.WaitAny(handles);
        // if index == 0, then Event1 was signaled.
        // if index == 1, then Event2 was signaled.
    }
    
    void AsyncProc1()
    {
        // does its thing and then
        Event1.Signal();
    }
    
    void AsyncProc2()
    {
        // does its thing and then
        Event2.Signal();
    }
    

    There are a couple of caveats here. If both asynchronous methods finish before the call to WaitAny, it will be impossible to say which completed first. Also, if both methods complete very close to one another (i.e. call 1 completes, then call 2 completes before the main thread's wait is released), it's impossible to say which one finished first.

    Greg D : This doesn't really change the race condition that already exists. Don't your caveats defeat the point of the entire answer?

Change TreeViewItem Header by trigger

Having such Style

<Style TargetType="TreeViewItem">
  <Style.Triggers>
    <Trigger Property="IsExpanded" Value="True">
      <Setter Property="Header" Value="Pink"></Setter>
    </Trigger>
  </Style.Triggers>
</Style>

I would expect the text of the expanded TreeViewItems to be "Pink", but nothing set actually. If I change to Property="Background" instead, it works. How Header differs from Background?

From stackoverflow
  • I think I'll need more info to answer this more completely. However, if I have to guess, I'd say you're probably setting the Header property on the TreeViewItem explicitly like this:

    <TreeView>
        <TreeViewItem
            Header="Blue"/>
    </TreeView>
    

    And, in this case, setting it explicitly will override anything that you put in the style.

  • To elaborate on ascalonx's answer:

    copied from Josh Smith's blog:

    There is a well-defined set of rules which is used internally by WPF to figure out what the real value of a DP is. Here is a brief summary of the rules of precedence used when resolving the value of a DP (from highest to lowest priority):

    1. Property system coercion
    2. Active animations, or animations with a Hold behavior
    3. Local value
    4. TemplatedParent template
    5. Style triggers
    6. Template triggers
    7. Style setters
    8. Theme style
    9. Inheritance
    10. Default value from dependency property metadata

    So if you explicitly set the Header property, (or if you bind it I think), you have that problem.

Pivot against a SQL stored procedure (or LINQ)

I am trying to create a Stored procedure (or query expression) that Pivots on a grouping ID. After looking at the examples here and elsewhere I have failed to get my pivot statements to work in a stored procedure, and I am looking my help.

Also, if this could be done with LINQ on a LIST that would be a solution for me also.

theID     theGroup   theValue
1          2          Red
2          2          Blue
3          2          Green
1          3          10
2          3          24
3          3          30
1          4          1
2          4          2
3          4          3

the Group #2 means a CHOICE, the group # 3 means COUNT, the Group #4 means SORT so I want to name those columns (I realize this is a shortcoming of PIVOT but that's OK).

ID        CHOICE     COUNT      SORT
1         Red        10  1
2         Blue       24  2
3         Green      30  3
From stackoverflow
  • This worked for me and should work in an SP:

    SELECT  theID AS ID
           ,[2] AS CHOICE
           ,[3] AS COUNT
           ,[4] AS SORT
    FROM    so_666934 PIVOT ( MAX(theValue) FOR theGroup IN ([2], [3], [4]) ) AS pvt
    

    There are tricks you can do with dynamic SQL to handle varying groups over time and you can also pivot on the names by effectively replacing theGroup with the name before the PIVOT.

    Ash Machine : Thank you, that worked beautifully!
  • Here's a couple of ways to do this in-memory with LINQ.

    List<SomeClass> source = new List<SomeClass>()
    {
      new SomeClass(){ theID = 1, theGroup = 2, theValue="Red"},
      new SomeClass(){ theID = 2, theGroup = 2, theValue="Blue"},
      new SomeClass(){ theID = 3, theGroup = 2, theValue="Green"},
      new SomeClass(){ theID = 1, theGroup = 3, theValue=10},
      new SomeClass(){ theID = 2, theGroup = 3, theValue=24},
      new SomeClass(){ theID = 3, theGroup = 3, theValue=30},
      new SomeClass(){ theID = 1, theGroup = 4, theValue=1},
      new SomeClass(){ theID = 2, theGroup = 4, theValue=2},
      new SomeClass(){ theID = 3, theGroup = 4, theValue=3}
    };
    
    //hierarchical structure
    var result1 = source.GroupBy(item => item.theID)
      .Select(g => new {
        theID = g.Key,
        theValues = g
          .OrderBy(item => item.theGroup)
          .Select(item => item.theValue)
          .ToList()
      }).ToList();
    
    
    //holds some names for the next step.
    Dictionary<int, string> attributeNames = new Dictionary<int,string>();
    attributeNames.Add(2, "CHOICE");
    attributeNames.Add(3, "COUNT");
    attributeNames.Add(4, "SORT");
    //xml structure
    var result2 = source
      .GroupBy(item => item.theID)
      .Select(g => new XElement("Row",
        new XAttribute("ID", g.Key),
        g.Select(item => new XAttribute(attributeNames[item.theGroup], item.theValue))
      ));
    

Crunching xml with python

I need to remove white spaces between xml tags, e.g. if the original xml looks like:

<node1>
    <node2>
        <node3>foo</node3>
    </node2>
</node1>

I'd like the end-result to be crunched down to single line:

<node1><node2><node3>foo</node3></node2></node1>

Please note that I will not have control over the xml structure, so the solution should be generic enough to be able to handle any valid xml. Also the xml might contain CDATA blocks, which I'd need to exclude from this crunching and leave them as-is.

I have couple of ideas so far: (1) parse the xml as text and look for start and end of tags < and > (2) another approach is to load the xml document and go node-by-node and print out a new document by concatenating the tags.

I think either method would work, but I'd rather not reinvent the wheel here, so may be there is a python library that already does something like this? If not, then any issues/pitfalls to be aware of when rolling out my own cruncher? Any recommendations?

EDIT Thank you all for answers/suggestions, both Triptych's and Van Gale's solutions work for me and do exactly what I want. Wish I could accept both answers.

From stackoverflow
  • I'd use XSLT:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="yes"/>
        <xsl:strip-space elements="*"/>
    
        <xsl:template match="*">
            <xsl:copy>
                <xsl:copy-of select="@*" />
                <xsl:apply-templates />
            </xsl:copy>
        </xsl:template>
    </xsl:stylesheet>
    

    That should do the trick.

    In python you could use lxml (direct link to sample on homepage) to transform it.

    For some tests, use xsltproc, sample:

    xsltproc test.xsl  test.xml
    

    where test.xsl is the file above and test.xml your XML file.

    David Zaslavsky : I know nothing about XSLT but if that does the job, it looks really cool ;-)
    Johannes Weiß : XSLT is really great when transforming XML preferably to XML. It is indeed a turing-complete functional programming language but normal programming is (at least in XSLT1.x) a bit of pain since function invocation types very long ;-)
    : Thanks, I will give it a try, from the first look seams like it should do the trick
  • Not a solution really but since you asked for recommendations: I'd advise against doing your own parsing (unless you want to learn how to write a complex parser) because, as you say, not all spaces should be removed. There are not only CDATA blocks but also elements with the "xml:space=preserve" attribute, which correspond to things like <pre> in XHTML (where the enclosed whitespaces actually have meaning), and writing a parser that is able to recognize those elements and leave the whitespace alone would be possible but unpleasant.

    I would go with the parsing method, i.e. load the document and go node-by-node printing them out. That way you can easily identify which nodes you can strip the spaces out of and which you can't. There are some modules in the Python standard library, none of which I have ever used ;-) that could be useful to you... try xml.dom, or I'm not sure if you could do this with xml.parsers.expat.

  • This is pretty easily handled with lxml (note: this particular feature isn't in ElementTree):

    from lxml import etree
    
    parser = etree.XMLParser(remove_blank_text=True)
    
    foo = """<node1>
        <node2>
            <node3>foo  </node3>
        </node2>
    </node1>"""
    
    bar = etree.XML(foo, parser)
    print etree.tostring(bar,pretty_print=False,with_tail=True)
    

    Results in:

    <node1><node2><node3>foo  </node3></node2></node1>
    

    Edit: The answer by Triptych reminded me about the CDATA requirements, so the line creating the parser object should actually look like this:

    parser = etree.XMLParser(remove_blank_text=True, strip_cdata=False)
    
    : If CDATA is present then this method would html encode everything inside CDATA block, e.g. converting < into < etc.
    : Works now with the changes to the line creating the parser.
  • Pretty straightforward with BeautifulSoup.

    This solution assumes it is ok to strip whitespace from the tail ends of character data.
    Example: <foo> bar </foo> becomes <foo>bar</foo>

    It will correctly ignore comments and CDATA.

    import BeautifulSoup
    
    s = """
    <node1>
        <node2>
            <node3>foo</node3>
        </node2>
        <node3>
          <!-- I'm a comment! Leave me be! -->
        </node3>
        <node4>
        <![CDATA[
          I'm CDATA!  Changing me would be bad!
        ]]>
        </node4>
    </node1>
    """
    
    soup = BeautifulSoup.BeautifulStoneSoup(s)
    
    for t in soup.findAll(text=True):
       if type(t) is BeautifulSoup.NavigableString: # Ignores comments and CDATA
          t.replaceWith(t.strip())
    
    print soup
    
    Van Gale : I don't believe this is quite right because it will strip valid whitespace at the end of contents. But, it reminded me that my snippet does the wrong thing with CDATA so thanks for that! :)
    : Thanks! This does exactly what I wanted
    Johannes Weiß : But that does CHANGE the document! It's not an equal XML document anymore...
    Van Gale : @Johannes Weiß: exactly