Thursday, April 21, 2011

Trying to Make mini Jeopardy flash game button help pls

Hey im a noob in flash cs3 and i want to create a jeopardy game where when a button is pressed we go in to the main question scene and when we come back the button the we pressed is now disabled via 'button._visible=flase'...pls any help...any suggestions or links to tutorials or tutorials from you guys or girls will grateful thanx...

From stackoverflow
  • More info would be helpful. Are you using Actionscript 2 or 3? Is the problem that the button is not hiding properly? Do you have any error messages in the Output window?

    If the problem is with hiding the button, the AS2 code would be:

    button._visible=false;
    

    The AS3 code would be:

    button.visible = false;
    

PHP equivalent of PyQuery or Nokogiri?

Basically, I want to do some HTML screen scraping, but figuring out if it is possible in PHP.

In Python, I would use PyQuery. In Ruby, I would use Nokogiri.

From stackoverflow
  • In PHP for screen scraping you can use Snoopy (http://sourceforge.net/projects/snoopy/) or Simple HTML DOM Parser (http://simplehtmldom.sourceforge.net/)

Include revision or tag name on website pages (ASP.NET) when deploying with CruiseControl.net and subversion

Is it possible to include the revision number or the name of the tag used for a build on an ASP.NET website when deploying with CruiseControl.net and subversion?

From stackoverflow
  • You can use SubWCRev for this. By integrating it into your build script, you can do keyword replacement in your source, replacing with things like the current revision number.

    You can also make use of the svn:keywords property for this. The svn:keywords property works on a file-by-file basis, though, and thus expands to the last revision of the file, as opposed to the last revision of the repository as a whole.

    Greg : Thanks for that useful clarification

Amazon API - is it possible to combine selling my own products, from my home, with other amazon products? (see desc)

This is what I would like -- a shopping area on my website. A user goes to this shopping page, they select the products they like, and they add them to shopping cart. When they are ready to check-out, they are transferred with all items in cart to Amazon to complete purchase.

Here's the twist: I would like to sell some DVD's from my home, ship them from my home, without listing them on the Amazon marketplace (only available through me). Those would appear in the shop on my website. And the other products in my store would be items I select from Amazon marketplace, that other users are selling, and list them in my shop so I earn affiliate commission from the sale.

Is this possible?

From stackoverflow
  • Listing Amazon products is possible (aStore).
    Selling things on your site is possible.
    Listing Amazon products on a site you are also selling things is also possible.

    The main thing is are you going to follow Amazon's rule's on listing those products among others? I really don't know. Read their rules.

ASP.NET custom RoleProvider error

I'm trying to use this article to learn about custom roleproviders, but I'm getting this error:

Could not load type 'TestRoles.SimpleRoleProvider'.

The relevant section from my web.config:

<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
        <providers>
            <add name="SimpleRoleProvider" type="TestRoles.SimpleRoleProvider"/>
        </providers>
    </roleManager>

The RolesProvider.cs class:

public class TestRoles{
public class SimpleRoleProvider : RoleProvider
{
    public override string[] GetRolesForUser(string username)
    {
        List<string> roles = new List<string>();
        roles.Add("Guest");
        if (username.Equals("Dave"))
            roles.Add("Admin");
        return roles.ToArray();
    }
 }
 }

From this error, it seems like it can't find the RoleProvider. Any ideas?

From stackoverflow
  • Well it seems to me that your namespace is wrong:

    TestRoles.SimpleRoleProvider

    Your namespace must me TestRoles and your class name SimpleRoleProvider

    Change your class TestRoles to namespace and make sure that you don't have any other namespace above TestRoles like xy.TestRoles.SimpleRoleProvider

    Ethan : Oh boy, that was it. I don't know how long I spent staring at that code without even realizing I'd typed 'class' instead of 'namespace'. Thanks!
    MUG4N : I am glad that I could help you ... shit happenz

How to perform ant path mapping in war task?

I have several JAR file pattern sets, like

  <patternset id="common.jars">
 <include name="external/castor-1.1.jar" />
 <include name="external/commons-logging-1.2.6.jar" />
 <include name="external/itext-2.0.4.jar" />
     ...
  </patternset>

I also have a war task containing a lib element:

   <lib dir="${src.dir}/jars">
      <patternset refid="common.jars"/>
      <patternset refid="web.jars"/>
         ...
   </lib>

Like this however, I end up with a WEB-INF/lib containing the subdirectories from my patterns:

WEB-INF/lib/external/castor-1.1.jar
WEB-INF/lib/external/...

Is there any way to flatten this, so the JAR files appear top-level under WEB-INF/lib, regardless of the directories specified in the patterns? I looked at mapper but it seems you cannot use them inside lib.

From stackoverflow
  • You can try to use mappedresources element (Ant 1.8+)

    <mappedresources>
        <!-- Fileset here -->
        <globmapper from="external/*.jar"
            to="*.jar"/>
    </mappedresources>
    

    http://ant.apache.org/manual/CoreTypes/resources.html#mappedresources

    If you have a typical web project it is better to split the web-app libraries and general-purpose libraries in different folders and leave WEB-INF/lib to have only those needed at runtime. This way you'll avoid collisions and also your project will look much clearer to other developers.

Appending Dataset in Core Data execution of Update through iTuneStore

This one Also Resolved by myself. Good answer would be, New Edition App: make change the sqlite file name. check file exist, get the old edition app sqlite name value then remove, and add into that folder. this is the best answer.

*New efficient answer

STEP 1:  select .xcdatamodel file
STEP 2:  Xcode -> Design -> Data Model -> Add Model Version
STEP 3:  Manipulate new changes

For more detail about migrate or re-organize data model structure, visit Apple <here>

Although I didn't quiet sure how to add model version before reading Apple's document, My old way is still works.

Old resolved self answer

Example from 'Reciepe' given by apple, it don't replace the file if it is there already. However, if your code need to update and get rid of old .SQL file then the explicit condition needed for check the old file sqlite name deleting function required for update. Basic sequence would be,

CHECK 1: check if old file exist.
CHECK 2: if it does, remove it.
CHECK 3: then copy new one.
CHECK 4: if the old file don't exist,
CHECK 5: (if the new file don't exist),
CHECK 6: copy new file into that folder.
CHECK 7: if new file exist do nothing.

solved.

Original Posted Question

So I have completed my code work. This is first time releasing the app through iTuneStore. Current state of reading Core Data (.sqlite) file is already prefetched (already has information like apple's 'Reciepie' program).

Assuming I have successfully released through apple store, and decide to update my application to existing users.

Say I have sqlite contents but it contains bit more information than previous SQLite file under same structure.

Question 1. Every time update held to the existing user, does it removes previous ones and move new updated application?

Question 2. if it is not, then HOW can I append the existing sql value?

From stackoverflow
  • If you do not change the underlying data model, then the answers are:

    1) updating from, say v1.0 to v1.1 does not remove the previous contents already stored and managed by Core Data.

    2) Simply check the version of your application using the main bundle, and, if the version retrieved needs additional data to be inserted, do the insert. You can do the check and the insertion in

    - (void)applicationDidFinishLaunching:(UIApplication *)application;
    

How do you add gestures to a UITableViewController?

I want to implement right-to-left and left-to-right gestures on a view that inherits from UITableViewController. I have the code for the gestures implemented in another view (UIViewController) and it works.

It does't seem like touchesBegan is even getting called.

Does anyone know know to do this?

Thanks

From stackoverflow
  • It depends on the SDK version. In 3.2, use UIGestureRecognizer. Prior to 3.2 use touchesBegan and friends. This is especially true when dealing with a UIScrollView because UIGestureRecognizer will cancel touchesBegan. So if you want to be forwards and backwards compatible you have to do both with a UIScrollView.

    For your particular case, use UISwipeGestureRecognizer or UIPanGestureRecognizer. You will have to implement gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: to prevent the UIScrollView from canceling your gesture recognizers.

    UITableViewController -> UITableView : UIScrollView
    
    mea36 : I'm running 3.1.2, do you know where I can get 3.2?
    mea36 : Or is there any way to do this without the gestureRecognizer?
    David Dunham : You can get 3.2 by buying an iPad. Or wait a few days for 4.0…

MATLAB plot inside a loop

I am doing something like this:

a = [1:100];
for i=1:100,
    plot([1:i], a(1:i));
end

My issue is that the plot is not shown until the loop is finished. How can I show/update the plot in every iteration?

From stackoverflow
  • Use DRAWNOW

    a = [1:100];
    for i=1:100,
     plot([1:i], a(1:i));
     drawnow
    end
    

    Alternatively, you may want to have a look at ANYMATE from the file exchange.

    woodchips : While drawnow is the correct answer, I think one can also add a pause(eps) statement in the code in the place of drawnow. When matlab does the pause, even if only for this nano-fraction of a time slice, it also does a refresh on the figure.
  • Another way to do this if you just want to visualise it without saving the animation, is to use refreshdata instead of plot for subsequent plots. You will still need to call drawnow for it to update on-screen.

    either use

    set(fig_handle,'XData',new_xdata_array)
    set(fig_handle,'YData',new_ydata_array)
    refreshdata
    drawnow
    

    or use

    set(fig_handle,'XDataSource',xdata_array)
    set(fig_handle,'YDataSource',ydata_array)
    
    %call this whenever xdata_array and ydata_array are assigned new values to see it updated in the plot
    refreshdata
    drawnow
    

    for your example, this might look like:

    a=[1:100];
    
    figure;
    h=plot(1,a(1));
    for i=2:100
      set(h,'XData',[1:i])
      set(h,'YData',a(1:i))
      refreshdata
      drawnow
    end
    

    It's not all that useful for simple line plots (for which plot(); drawnow; is simpler and faster), but when you need to create more complicated figures involving multiple plot types, this can be useful.

  • From the documentation for comet.m

    t = 0:.01:2*pi;
    x = cos(2*t).*(cos(t).^2);
    y = sin(2*t).*(sin(t).^2);
    comet(x,y);
    

Worked Example of Digital Signature Algorithm

Hi Folks,

Does anybody have a DSA worked example with simple values on how to calculate r,s and verify v == r. As this standard has been around awhile and is implemented in librarys e.g. the Java Cryptography Extension I'm finding it very hard to find an example of how the algorithm works.

Compute r=(gk mod p) mod q 
Compute s=(k-1 * (x * r + i)) mod q 
Verifying a signature; again i is the input, and (r,s) is the signature. 

u1 = (s-1 * i) mod q 
u2 = (s-1 * r) mod q 
v = ((gu1 * yu2) mod p) mod q 
If v equals r, the signature is valid.

Thanks,

From stackoverflow
  • There's a worked example at the end of the standard that defines DSA, FIPS 186.

    David Relihan : @Andrew - Unfortunately I'm just looking for a very simople version so I can figure out the maths behind it
    Andrew McGregor : That's as simple as it gets. Seriously, it's not complicated.

How to add my custom WPF control to the ToolBox by using the WPF ToolBox Control template

I have a custom control packed as myControl.dll. How to install it in VS2010 by using the WPF ToolBox Control template? I do not want to use the "Choose Toolbox..." or "Drag and Drop" techniques.

From stackoverflow

UITableViewCell checkmark change on select

Am I correct in thinking that to change the checkmark for "on" to "off", I must change the CellAccessoryType between none and checkmark on the didSelectRowAtIndexPath?

Because I have done this but I have noticed the behaviour is not perfectly identical to like the checkmark cells on the auto lock settings on the iphone.

Or is there some other way checkmarks are meant to be handled?

From stackoverflow
    1. Keep a property in your view controller called selectedRow, which represents the index of a row that represents the checked item in a table section.

    2. In your view controller's -tableView:cellForRowAtIndexPath: delegate method, set the accessoryType of the cell to UITableViewCellAccessoryCheckmark if the cell's indexPath.row equals the selectedRow value. Otherwise, set it to UITableViewCellAccessoryNone.

    3. In your view controller's -tableView:didSelectRowAtIndexPath: delegate method, set the selectedRow value to the indexPath.row that is selected, e.g.: self.selectedRow = indexPath.row

    Jonathan : Sorry, I did not mean that I had multiple checkmark cells (more like radio buttons). Just they didn't animate as smoothly (but I fixed that now). But your answer means I am using the correct methods :)

Entity Framework 4 missing features?

I'm well aware that similair topics have been brought up before e.g. http://stackoverflow.com/questions/1639043/entity-framework-4-vs-nhibernate

But instead of arguments like:

  • NHibernate have been around longer and is more mature
  • EF4 is drag n drop and not enterprisy
  • EF4 and LinqToSql are ...

I would like to see a more detailed list of features that you consider missing from EF4.

Personally, I think the lack of enum support is the biggest drawback of EF4.

From stackoverflow

ASP and Windows User Logon

Hey,

I want to use the Windows logon information to check if a user can use my "classic asp" site. So if the user is logon at a certain Windows Domain network he/she can enter the site and i can use this persons Windows logon information on my asp site.

I know its possible with ASP.NET but is it also possible with "classic asp", if yes, how?

From stackoverflow
  • Take a look at Request.ServerVariables("AUTH_USER"). I beleive that this will only have a value if anonymous authentication is turned off windows authentication is on. Heres a good reference for all the server variables: http://www.w3schools.com/asp/coll_servervariables.asp

Does STDIN/STDOUT flush data all at once or character by character?

I'm using C# to read another program's STDOUT. If I do this:

StreamReader reader = process.StandardOutput;
reader.ReadToEnd();

Is it guaranteed to get the last thing flushed out to the program's STDOUT in its entirety? Or is kind of like TCP where I'd have to have a message terminator or length header?

From stackoverflow
  • by default StandardOutput is buffered, which means that you would likely get whole messages from the other end (or multiple whole messages). But its not really guaranteed, especially because process you are reading from could have changed the buffering of StandardOutput.

    A message terminator would be the best way to figure it out. though usually with processes communicating over StandardOutput everything is line based so simply using newlines as message terminators is probably the simplest and most common place to start.

  • reader.ReadToEnd() doesn't return until the process terminates, so after that call you should see everything that it wrote to stdout. Buffering would only affect how quickly it gets from the other program into your reader's buffer, but your code can't tell the difference (at least on this thread) because it's still waiting for ReadToEnd() to return.

Using a WinForm as a Windows Installer Custom Action

Hello - I am working on in installer project that needs to gather some info and act on it during the install (mainly online key retreival and registration). The Setup Project UserInterface templates seem inflexible and poorly documented so I am looking at opening a WinForm as a Custom Action.

I know this is possible because I see reference to it in many places but this is my first Windows Installer experience and so far it is mired in googled contradictions, partial or outdated information and guesswork... erg....

Does anyone have (even a pointer to) a clear concise description of how one gets this done in a VS 2008 WinForm project...

Many thanks for inputs

From stackoverflow
  • There is no guarantee that the .net framework is installed when the installer is launched (especially on Windows XP). A best practice is to keep your installer away from any dependencies.

    Put the online key retrieval and registration in your application rather than doing all that stuff during install.

    Serexx : hmmm thanks will give that a think... this is for an Office Add-In product so pretty sure .net would be there and not sure how it would impact the user experience, but maybe an idea
    serhio : So, you have install conditions(requirements). If the requirement of .NET is not satisfied, the ".NET isn't installed" message-box appear and install dies; OR .NET is pre-installed as a pre-requisite. So, I don't think is a serious problem.
  • Create a standard installer class. In the class create your form and show it (ShowDialog is prefered)

Getting a unix timestamp as a string in C++

I'm using the function time() in order to get a timestamp in C++, but, after doing so, I need to convert it to a string. I can't use ctime, as I need the timestamp itself (in its 10 character format). Trouble is, I have no idea what form a time_t variable takes, so I don't know what I'm converting it from. cout handles it, so it must be a string of some description, but I have no idea what.

If anyone could help me with this it'd be much appreciated, I'm completely stumped.

Alternately, can you provide the output of ctime to a MySQL datetime field and have it interpreted correctly? I'd still appreciate an answer to the first part of my question for understanding's sake, but this would solve my problem.

From stackoverflow
  • http://www.codeguru.com/forum/showthread.php?t=231056

    In the end time_t is just an integer.

  • Try sprintf(string_variable, "%d", time) or std::string(itoa(time))?

    wyatt : This allowed the process timestamp to be printed, but it always returns 134515192. specifically, my code is: char timestamp[10]; sprintf(timestamp, "%d", time); then later query += timestamp query being an std::string.
  • time_t is some kind of integer. If cout handles it in the way you want, you can use a stringstream to convert it to a string:

    std::string timestr(time_t t) {
       std::stringstream strm;
       strm << t;
       return strm.str();
    }
    

Guice expert question

Hi All

I am wondering if someone would be such an expert in guice that he even would know how to implement that :

I have an injection annotation (@ConfParam)with some parameters , like that :

class TestClass {

private final int intValue;

    @Inject
    public TestClass(@ConfParam(section = "test1", key = "1") int intValue{
        this.intValue = intValue;
    }

    public int getIntValue() {
        return intValue;
    }

}

The ConfParam is my custom annotation.

Now , when the injection value is requested , I would like guice to create a dynamic binding, to resolve the value.

For that binding I will need the parameters inside the annotation.

Some example could be , I will have to look in the database in some table where the section is ? and the key is ?.

All the trouble is that the data is not available when the injector is created and could be also be added at runtime.

Ps. I static solution is easy. ( just have a look at the Names class)

From stackoverflow
  • Have a look at CustomInjections as a starting point. I have done something similar before that used a parameter to customize a logger further than simply the class name.

    Roman : This is exactly what I need.

How do I configure ELMAH programmatically?

I'm interested in using ELMAH but need to configure it programmatically. We have existing infrastructure for determining connection strings and the like, and can't code them into Web.Config.

How do I go about using ELMAH in this case?

From stackoverflow

Adding CKEditor through javascript onclick event adds a CKEditor to the DOM but does not allow me to enter text into it. Why?

Hi, I'm adding a ckeditor to my form using the onclick functionality - i.e., when the user clicks a button, the ckeditor is added to the form. I'm echoing out the html generated when a ckeditor is added to a page through the javascript function.

The ckeditor is added, but the text area cannot be modified.

is it because i'm adding the html to generate the ckeditor as : ckeditor.innerHTML = '......';

is there another way to add a ckeditor to my form using the javascript onclick (like: onclick="addCKEditor();")

Thanks!

From stackoverflow
  • Hi, using CKEDITOR.replace('id) after adding the textarea to the DOM - within the javascript function, got the job done.

  • any ideas? Please.. need solution

Capture global touch events (Symbian)

Basically I wanted what the pys60 module keycapture does (global capture of keystrokes) but I wanted to do this with the touchscreen. So if the program is running, all touch events can be intercepted and logged by the program. How is this possible?

From stackoverflow

In a Visual Studio C++ project with /clr, are its dependencies also compiled to managed code?

To be a bit more clear. If I have a Visual Studio C++ solution that has two projects, say a static library with CLR support turned off, and a second project with CLR support turned on that depends on this static library, does the static library get compiled as managed code? What about libraries that the CLR project uses that are external to this solution, do they also get compiled as managed code?

From stackoverflow
  • No, only the project with /clr gets compiled to a managed assembly. The static library will get compiled as unmanaged code and linked into the managed DLL.

  • No, your dependencies do not get compiled as managed code.

    Your "main" project actually ends up containing both managed and unmanaged code. Those parts when you call your dependency would be compiled as unmanaged.

How can I add spacing in RelativeLayout

Hi,

I have a Relative Layout. Which has 2 buttons, side by side and it is right-aligned.

So this is my layout xml file. My question is there are no spacing between the right-most button and the right border of the RelativeLayout and between the 2 buttons. How can I add that? I play with android:paddingRight, but nothing helps.

Thank you.

<RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="0dp" android:paddingRight="10dp">

    <Button android:id="@+id/1button" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:paddingLeft="10dp" android:paddingRight="10dp"/>

    <Button android:id="@+id/1button" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/1button"
        android:paddingLeft="10dp" android:paddingRight="10dp"/>
From stackoverflow
  • You have duplicated ids for the buttons, try fixing that and see if it looks ok.

    Otherwise, your layout looks good. However, if you fix the ID problem, there will be 20 dip padding on the right (10 from the layout and 10 from the button).

  • android:layout_margin="10dp"
    

    or

    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    
  • Fix ids and try android:layout_marginRight="10dip"

Using NHibernate with an EAV data model

I'm trying to leverage NH to map to a data model that is a loose interpretation of the EAV/CR data model.

I have most of it working but am struggling with mapping the Entity.Attributes collection.

Here are the tables in question:

--------------------
| Entities         |
--------------------
| EntityId  PK     |-|
| EntityType       | |
-------------------- |
         -------------
         |
         V
--------------------
| EntityAttributes |    ------------------    ---------------------------
--------------------    | Attributes     |    | StringAttributes        |
| EntityId  PK,FK  |    ------------------    ---------------------------
| AttributeId  FK  | -> | AttributeId PK | -> | StringAttributeId PK,FK |
| AttributeValue   |    | AttributeType  |    | AttributeName           |
--------------------    ------------------    ---------------------------

The AttributeValue column is implemented as an sql_variant column and I've implemented an NHibernate.UserTypes.IUserType for it.

I can create an EntityAttribute entity and persist it directly so that part of the hierarchy is working.

I'm just not sure how to map the EntityAttributes collection to the Entity entity.

Note the EntityAttributes table could (and does) contain multiple rows for a given EntityId/AttributeId combination:

EntityId AttributeId AttributeValue
-------- ----------- --------------
1        1           Blue
1        1           Green

StringAttributes row looks like this for this example:

StringAttributeId AttributeName
----------------- --------------
1                 FavoriteColor

How can I effectively map this data model to my Entity domain such that Entity.Attributes("FavoriteColors") returns a collection of favorite colors? Typed as System.String?

From stackoverflow
  • Hi there, Id be very interested to see how you implemented this

Joomla plugin install XML files <folder> tag

While developing a joomla plugin, if my plugin folder looks like so:

/install.xml
/mainPg.php
/subfolder/lib.php
/subfolder/config.php

Would the tag look like this?

<files>
    <filename plugin="mainPg">mainPg.php</filename>
    <folder>subfolder</folder>
</files>
From stackoverflow

Static methods on ASP.NET web sites

Hi, i was wondering.. if i have a static method on an asp.net web site (plain vanilla), is that accessible by all users of all sessions?

I guess what i am saying is the single instance of a method available to each client? or is there 1 instance for all clients for the site..

From stackoverflow
  • The static value is the same for all users on the same pool.

    Different pools have different static values.

    The session have nothing to do with the static values, and the users that are on the same pool have the same static values.

How do I know an array of structures was allocated in the Large Object Heap (LOH) in .NET?

After some experimenation using CLR Profiler, I found that:

Node[,] n = new Node[100,23]; //'84,028 bytes, is not placed in LOH
Node[,] n = new Node[100,24]; //'86,428 bytes, is 

    public struct Node {
        public int Value;
        public Point Point;
        public Color Color;
        public bool Handled;
        public Object Tag;
    }

During run-time, how do I know an array of structures (or any array) was allocated in the Large Object Heap (LOH)?

From stackoverflow
  • Any object larger than 85,000 bytes will be stored on the LOH. Here is a great blog post about .Net Memory Management.

  • From your comments, I don't think you actually need to know whether the object is going to go on the LOH or not. Whether or not that's the actual cause of your application's slowdown is kind of irrelevant when all you really want to do is display a warning to the user when they enter a value that's "too big".

    So I would suggest something a bit simpler: just use a bit of trial-and-error to determine the cut-off value. If they enter a size over your trial-and-error value, display the warning.

    As for your actual performance problems, instead of allocating one big two-dimensional array, you could simply allocate a bunch of "smaller" one dimensional arrays. Instead of:

    Node[,] n = new Node[100,100]; // this will go the LOH
    

    You'd do this:

    Node[][] n = new Node[100][];
    for(int i = 0; i < n.Length; i++) {
        n[i] = new Node[100];  // none of these will be on the LOH
    }
    

    You'd still have the same number of nodes in total, but nothing would go on the LOH. Personally, I think you will probably find that the performance is actually not going to be all that much different, but it might be worthwhile to just give it a try.

Named Blueprints with factory_girl

I am using Factory Girl but like the machinist syntax. So I wonder, if there is any way creating a named blueprint for class, so that I can have something like that:

User.blueprint(:no_discount_user) do
  admin           false
  hashed_password "226bc1eca359a09f5f1b96e26efeb4bb1aeae383"
  is_trader       false
  name            "foolish"
  salt            "21746899800.223524289203464"
end

User.blueprint(:discount_user) do
  admin           false
  hashed_password "226bc1eca359a09f5f1b96e26efeb4bb1aeae383"
  is_trader       true
  name            "deadbeef"
  salt            "21746899800.223524289203464"
  discount_rate { DiscountRate.make(:rate => 20.00) }
end

DiscountRate.blueprint do
  rate {10}
  not_before ...
  not_after ...
end

Is there a way making factory_girl with machinist syntax acting like that? I did not find one. Help appreciated.

Thx in advance Jason

From stackoverflow
  • Yes you can. require blueprint syntaxe

      require 'factory_girl/syntax/blueprint'
      Sham.email {|n| "#{n}@example.com" }
    
      User.blueprint do
        name  { 'Billy Bob' }
        email { Sham.email }
      end
    
      User.make(:name => 'Johnny')
    
    Jason Nerer : shingara, I know, thats the way I'm using it. But the question ist, if one can use named blueprints like: User.blueprint(:no_discount_user) do and User.blueprint(:discount_user) do so that I can call: User(:discount_user).make to create a user with a discountrate and User(:no_discount_user).make to create a user without. It would make Cucumber step definition much dryer in my case. But it seems I need to switch to machinist instead.
    shingara : Yes I think it's not possible. The extension of factory_girl can't made that

What is the 64 bit equivalent of Win32_OperatingSystem?

I inherited a script running on Windows Server 2003 that I need to port to Windows Server 2008. The current script is:

strComputer = "servernamexyz"  
Set objWMIService = GetObject("winmgmts:" _  
    & "{impersonationLevel=impersonate,(Shutdown)}!\\" & _  
        strComputer & "\root\cimv2")  
Set colOperatingSystems = objWMIService.ExecQuery _  
    ("SELECT * FROM Win32_OperatingSystem")  
For Each objOperatingSystem in colOperatingSystems  
    objOperatingSystem.Win32Shutdown(12)  
Next

How do I convert this to run on Windows Server 2008? Thanks!

From stackoverflow
  • There's nothing to translate. This works on Windows 2008 (both 32 and 64 bits).

  • It's still present on server2008.

    The Win32 label is a bit unfortunate, it wasn't the change from 16bit to 32bit memory that was the big thing in windows95 it was the switch to protected mode.
    It's just that "32bit better than 16bit" was easier to explain in the ads - but it has left an awful lot of internal naming legacies with 64bit OSs.

    Jim : ok, thanks. Looks like I'm chasing the wrong rabbit on this problem. It isn't working, so I'll have to dig a bit more - not sure why.
  • As noted above, the script was correct. The problem was with a firewall setting not allowing WMI from a remote computer. Thanks for the quick feedback. it enabled me to look in a different direction quickly. Sorry I cannot vote both of you up yet....

Strong name validation failed on VB.NET Assembly

I have a VB.Net 1.1 application works just fine after compiling in Visual Studio. However, I want to use ILMerge to combine all the referenced assemblies into a single executable just to make it easier to move around. After I send it through ILMerge and try to run it I get the error

"Strong name validation failed for assembly.exe" .....

But none of my stuff is strong named! I saw this post here: http://stackoverflow.com/questions/403731/strong-name-validation-failed and tried running it through 'sn.exe -Vr merged.exe' but that gives me this error:

"merged.exe does not represent a strongly named assembly"

Has anyone else had this problem before? How do I fix it?

UPDATE:

I'm starting to feel like Strong name validation isn't the real problem here. I'm building against .NET v1.1 and running on a machine where that is the only .NET version installed (happens to be Windows 2003). The merged executable appears to die with that error on every Windows 2003 machine I try, but if I try to run it on a more modern OS (Vista) it at least starts, but that's not really a good test since the environment isn't fit for a real test.

  • I have verified that my app.config has the correct settings (specifying required and supported runtime version of v1.1.4322)
  • I use the /targetplatform:v1.1 option when running my assemblies through ILMerge.

ILMerge is definitely causing the problem (i.e. it works fine before I merge), I just don't know how to fix it.

From stackoverflow
  • I had to find and download a very old version of ILMerge (v1.1) in order for my merged binary to work; there must be a bug in the way the current ILMerge application builds .NET 1.1 assemblies. Thankfully we had one internally because I would probably have never found it online.

How to set Border.BorderBrush from string

Theres a problem. I can't set value of BorderBrush fros C#-code (not in XAML):

 ((Border)((Image)sender).Parent).BorderBrush = "#FFBCC7D8";

How to solve this problem?

From stackoverflow
  • You must use an Converter to convert the string to a Brush-Object. In the Framework there is a BrushConverter to do this.

    BrushConverter converter = new BrushConverter();
    ((Border)((Image)sender).Parent).BorderBrush = converter.ConvertFromString("#FFBCC7D8") as Brush;
    

error occurred when run site

this error occurred when run site

Login failed for user 'NT AUTHORITY\NETWORK SERVICE

From stackoverflow
  • Sorry I solved It The Connection string information wasn't right

  • You may need to create the user and give them permission to your database.

    You can do this under Security in SQL Server Management Studio or create a SQL query and paste the following in:

    USE [DBNAME];
    CREATE USER [NT AUTHORITY\NETWORK SERVICE] FOR LOGIN [NT AUTHORITY\NETWORK SERVICE]
    GO
    

    You may also need to add them to a role like this:

    USE [DBNAME];
    EXEC sp_addrolemember N'db_owner', N'NT AUTHORITY\NETWORK SERVICE'
    GO
    

Serialize into an XML Fragment - not XML Document

How do I serialize an XML-serializable object to an XML fragment (no XML declaration nor namespace references in the root element)?

From stackoverflow
  • Hi Canoehead,

    How to serialize an object to XML by using Visual C#

    Canoehead : No. This will produce a valid xml document which includes the XML declaration and namespace references. I want a fragment only.
  • You should be able to just serialize like you usually do, and then use the Root property from the resulting document.

    You may need to clear the attributes of the element first.

    Canoehead : +1 Sounds good to me but what I didn't explain in my question was that I'd prefer to produce a stream and not an XmlDocument.
  • Here is a hack-ish way to do it without having to load the entire output string into an XmlDocument:

    using System;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    
    public class Example
    {
        public String Name { get; set; }
    
        static void Main()
        {
            Example example = new Example { Name = "Foo" };
    
            XmlSerializer serializer = new XmlSerializer(typeof(Example));
    
            XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
            emptyNamespace.Add(String.Empty, String.Empty);
    
            StringBuilder output = new StringBuilder();
    
            XmlWriter writer = XmlWriter.Create(output,
                new XmlWriterSettings { OmitXmlDeclaration = true });
            serializer.Serialize(writer, example, emptyNamespace);
    
            Console.WriteLine(output.ToString());
        }
    }
    
    Canoehead : +1 and accepted. Thanks! Works beautifully and no XmlDocument/XmlNode manipulations.
    Jim Leonardo : +1 - I don't think it's really hackish at all. Maybe more set up work than I'd like to do. But, at the end, it's telling it what format the output should be before it does the work. That's not a hack. A hack would be to strip everything out after the fact etc.

How can I get the X axis labels in Flot to be transformed with my data?

I am using Flot to chart some data that I pull back from the server. The X-axis data that I receive is in units of milliseconds, and I want to display the chart with the X-axis in units of seconds. So, I thought this was a good use of the API's transform axis option. I applied my transform like so:

var plot = $.plot($("#placeholder"),
       { 
         grid: { hoverable: true, clickable: true },
         xaxis: { transform: function(x) { return x/1000; } }
       });

I can see that my transform function is being called by the framework, and I can see that the points themselves are being transformed -- when I bind the plothover event and hover over the points, I can see that the X value is suitably transformed. The problem is that the x-axis tick labels are not also getting transformed. alt text

What do I need to do to get the axis labels themselves transformed with my data?

From stackoverflow
  • I'm not sure what the "right" answer is, but you can provide your own tick labelling function, and just have it perform the same job as your transform function.

    var plot = $.plot($("#placeholder"),
       { 
         grid: { hoverable: true, clickable: true },
         xaxis: { transform: function(x) { return x/1000; },
                  tickFormatter: function(x) { return x/1000; } }
       });
    

Spring Sample Application

Could anyone point me towards some good, detailed, sample Spring applications?

Ideally those with good test coverage!

From stackoverflow