text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am reading three images using the RMagick gem and then adding them to an ImageList

imagelist = ImageList.new

imagelist << Image.read(path1)[0]
imagelist << Image.read(path2)[0]
imagelist << Image.read(path3)[0]

Then I combined these three images with the append method

combined_image = imagelist.append(false)

Then I try to write this image to Amazon S3:

AWS::S3::S3Object.store(filename, combined_image, bucket)

However, I get this error which prevents me from successfully writing the image to S3:

undefined method `size' for #<Magick::Image:0x00000101994498>

I played around with RMagic in the console, and I found that when you append images in an ImageList, it returns an Image that seems to omit its size in bytes.

How can I modify this image so that I can write it to S3?

share|improve this question

2 Answers 2

Figured it out. The trick was to turn the combined_image to a Binary Large Object by calling to_blob on it.

share|improve this answer

I will suggest you to check whether combined_image.display shows the desired appended image to you or not. If it does, AWS::S3 must store the image file like any other general storing syntax of cloud.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


Content-Type: application/http; msgtype=response

WARC-Type: response

text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm thinking about how one can write an extensible node-kind approach. Currently each node in a tree-structure must implement a method which returns the kind of node (currently an enum which defines how to serialize and deserialize nodes on disk depending on the kind of node). If a user wants to use the framework and define and implement other node-types we need some extensibility.

I thought about adding an interface (extensible enum pattern) and use somethink like

public interface IKind and in the node interface use something like public <E extends Enum<E> & IKind> E getKind() {...}. However I'm not even sure if that is ok:

public <T extends Enum<T> & IKind> T getKind() {
  return (T)ENode.ELEMENT_KIND;

for an ElementNode (XML) and an enum ENode which implements IKind. Furthermore it doesn't allow to switch on the kind of node which somehow seems to be a killer argument as one probably doesn't want to write a visitor implementation everytime.

The current implementation simply is:

public ENode getKind() {
  return ENode.ELEMENT_KIND;

I'm currently writing a simple PathSynopsis of a tree-structure and thus use PathNodes which I don't want to add to the core nodes.

BTW: Is it somehow possible to return any kind of an enum(value) to use with a switch-statement?... As one cannot switch on Enum.

Perhaps returning a simple byte value which is used for serialization/deserialization nontheless could also be used, but it's a bit ugly:

switch (ENode.getKind(pNewRtx.getNode().getKind()))

public enum ENode implements IKind {
  ELEMENT((byte) 0, ElementNode.class) {
    serialize(...) {...}
    deserialize(...) {...}
  /** Mapping of keys -> nodes. */
  private static final Map<Byte, ENode> INSTANCEFORID = new HashMap<>();

  /** Mapping of class -> nodes. */
  private static final Map<Class<? extends INode>, ENode> INSTANCEFORCLASS = new HashMap<>();

  static {
    for (final ENode node : values()) {
      INSTANCEFORID.put(node.mId, node);
      INSTANCEFORCLASS.put(node.mClass, node);
   * Get the related node based on the identifier.
   * @param pId
   *          the identifier for the node
   * @return the related node value
   public static ENode getKind(final byte pId) {
     return INSTANCEFORID.get(pId);

public interface IKind {
   * Deserializing a node using a {@link ITTSource}.
   * @param pSource
   *          input source
   * @return a {@link INode} instance
  INode deserialize(final ITTSource pSource);

   * Serializing a node from a {@link ITTSink}.
   * @param pSink
   *          where the data should be serialized to
   * @param pToSerialize
   *          the node to serialize
  void serialize(final ITTSink pSink, final INode pToSerialize);

   * Get the nodeKind.
   * @return the unique kind
  byte getKind();

However this would even introduce the possibility for NPEs and the implementers have to ensure that no byte-values are identical across implementations.

share|improve this question

1 Answer 1

When I write enums, they usually constitute a closed set. I wouldn't go that route if they had to be dynamic. I'd be more likely to think in terms of a common interface and polymorphism.

share|improve this answer
up until now they were a closed set (storage for XML-documents) but I think it's of more value as a framework to persistent revisioned tree-structured documents of any kind ;-) –  Johannes Jun 25 '12 at 16:51
I wouldn't do it using enums, then. I don't disagree with your idea, just your choice of implementation. I think it goes against the purpose of an enum. –  duffymo Jun 25 '12 at 17:00
Actually, with the method outlined above, you're both right. The methods take Collections of interfaces. The enum provides a default set of interface implementations. Everybody wins. –  Edwin Buck Jun 19 '13 at 15:38
"Can't we all just get along?" –  duffymo Jun 19 '13 at 15:56

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.

warcinfo:
robots: classic
hostname: ip-10-179-60-89.ec2.internal
software: Nutch 1.6 (CC)/CC WarcExport 1.0
isPartOf: CC-MAIN-2015-27
operator: CommonCrawl Admin
description: Wide crawl of the web for June 2015
publisher: CommonCrawl
format: WARC File Format 1.0
conformsTo: http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am learning the Prism framework and how MEF is integrated with it... I am looking at the "StockTraderRI" demo solution that comes with Prism as an example...

When the [EXPORT] attribute is used on a viewmodel such as this: [Export(typeof(TrendLineViewModel))]

Does MEF create a list of these in one of its internal structures so that when it is imported like this: [Import] TrendLineViewModel ViewModel it can be located?

The it looks like the exporting of views is doing something similar: [ViewExport(RegionName = RegionNames.ResearchRegion)]

which is then used in the AutoPopulateExportedViewsBehavior method to inject the views in the regions.. is this correct?

Thanks Harold

share|improve this question

1 Answer 1

up vote 1 down vote accepted

When you put "attributes" (the square bracket things) on types, you are attaching "metadata" to that type that can be discovered at runtime by using reflection.

When you configure MEF you give it a Catalog which tells it which assemblies it should scan for the [Import] and [Export] metadata attributes. For example a DirectoryCatalog will get MEF to scan a set of assemblies/DLLs in a particular directory.

When you ask for a type to be created/composed, it knows how to resolve the creation of that part i.e. it matches up [Import] and [Export]s which are of the same contract.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am looking to have a list of arguments passed across in an a URL.

Please Note I am trying to pass this in the URL in 1 GET variable. I know this would be better done by ?key1=1&key2=2&key3=3...etc but for reasons that are too complicated to try and explain they can't be in this format.

Any suggestions how I can convert this array into something that can be passed as 1 get var in a URL string?

Thanks in advance.

share|improve this question
You didn't indicate the semantic meaning of this data. There may be a serious security issue with letting remote, anonymous users manipulate $url directly. –  geocar Sep 7 '09 at 15:54

6 Answers 6

up vote 3 down vote accepted

Try http_build_query:

echo http_build_query($url);
//echos key1=1&key2=2&key3=3&key...

What it does is converting an array into a query string using the keys and automatically takes care of url-encoding.

Just read your additional requirement that it should be just one variable. So nevermind this answer. If your problem was the proper encoding though you might want to give this another try.

Hope that helps.

share|improve this answer
You gave me an idea: echo $newurl = http_build_query($url,"","|"); which could give me: ?key1=1|key2=2|key3=3|key4=4|key5=5|key6=6|key7=7 –  Lizard Sep 7 '09 at 15:06
Isn't that what I said 5 minutes before? :| –  Greg Sep 7 '09 at 15:07
@greg sorry! didnt see that! –  Lizard Sep 7 '09 at 15:25

You can use json_encode() or serialize()

$myUrl = 'http://www.example.com/?myKey=' . urlencode(json_encode($url));

$myUrl = 'http://www.example.com/?myKey=' . urlencode(serialize($url));

Using json_encode will usually give you a shorter string, but very old PHP version might not have the json_decode function available to decode it again.

The final way would be to create your own custom encoding... it could be as simple a pipe-separated values: key1|1|key2|2|key3|3
This would give you the best option for a short URL, but is the most work.

share|improve this answer
I had thought of that but the string becomes very long: serialized = :7:{s:4:"key1";i:1;s:4:"key2";i:2;s:4:"key3";i:3;s:4:"key4";i:4;s:4:"key5";i:5;s:4:"key6";i:6;s:4:"key7";i:7;} With url_enode: a%3A7%3A%7Bs%3A4%3A%22key1%22%3Bi%3A1%3Bs%3A4%3A%22key2%22%3Bi%3A2%3Bs%3A4%3A%22key3%22%3Bi%3A3%3Bs%3A4%3A%22key4%22%3Bi%3A4%3Bs%3A4%3A%22key5%22%3Bi%3A5%3Bs%3A4%3A%22key6%22%3Bi%3A6%3Bs%3A4%3A%22key7%22%3Bi%3A7%3B%7D Will the length be an issue? –  Lizard Sep 7 '09 at 14:47
~200 characters is not really a problem... just very ugly. Try json instead –  Greg Sep 7 '09 at 14:49
you have approx 2048 chars to work with although in theory there should be no limit: stackoverflow.com/questions/417142/… –  seengee Sep 7 '09 at 14:49
@Greg - you don't say :) –  karim79 Sep 7 '09 at 14:50
{"key1":1,"key2":2,"key3":3,"key4":4,"key5":5,"key6":6,"key7":7} and %7B%22key1%22%3A1%2C%22key2%22%3A2%2C%22key3%22%3A3%2C%22key4%22%3A4%2C%22key5%22%3A5%2C%22key6%22%3A6%2C%22key7%22%3A7%7D Better, just trying to do something a little bit more easy on the eye :( –  Lizard Sep 7 '09 at 14:51

The recommendation to use serialize() is fine. If space is an issue, then use a combination of bzcompress() and serialize().

However, there's a security considering that hasn't been brought up, and that's that the end user (who can see and edit this url) could manipulate the data within it. You may think it's difficult, but most of the PHP-attacking worms in the wild do this to some degree or another.

If letting the user directly manipulate any of the keys or values (or replacing it with an integer, or an object, or anything else), then you should protect your script (and your users) from this attack.

A simple solution is to simply use a shared secret. It can be anything; just so long as it's unique and truly secret (perhaps you should randomly generate it at install-time). Let's say you have in your config file something like this:

define('SECRET', 'unoqetbioqtnioqrntbioqt');

Then, you can digitally sign the serialized data created with: $s=serialize($m) using $k=sha1($s.SECRET) and make the url value $k.$s

Then, before you unserialize() do this:

if ($v != sha1($s.SECRET)) { die("invalid input"); }

This way, you know that $m is the same as the original value that you serialized.

If you like, you can use the following drop-in replacements:

define('SECRET','buh9tnb1094tib014'); // make sure you pick something else
function secureserialize($o) {
  return sha1($s.SECRET).$s;
function secureunserialize($i) {
  if ($v!=sha1($s.SECRET)){die("invalid input");}
  return unserialize($s);
share|improve this answer

You could serialize them as key-value pairs when constructing the URL, putting the resultant serialized value in a single $_GET variable (e.g. data=sfsdfasdf98sdfasdf), then unserialize the $_GET["data"] variable. You'll need to use urlencode to make sure the resultant serialized values are URL-safe. Make sure you watch out for maximum URL lengths - 2083 characters in IE.

However, unless you really can't use key-value pairs in URLs (per your question), key1=foo&key2=bar... is definitely the way to go.

share|improve this answer
You can use bzcompress() to save space as well. Also note that there may be security considerations to using serialize() that depend on what you use with the unserialize() data. –  geocar Sep 7 '09 at 15:56

If you don't mind dropping the key names, you can use

EDIT Keeping the key names:

Then in your PHP script:

$url = array_combine($_GET['keys'], $_GET['values']);
share|improve this answer
Sorry I will need key names :( –  Lizard Sep 7 '09 at 14:48
Ok, updated answer –  soulmerge Sep 7 '09 at 14:52

Could you solve your problem by saving the data as a HTML cookie? That way you don't have to modify the URL at all.

If you know the values in advance, you can set them from the server side when you send the user the page with your target link on it.

If you won't know the values until the user fills out a form it can still be done using JavascriptL When the user clicks the form submit you can set multiple cookies by making multiple javascript calls like: document.cookie = 'key1=test; expires=Mon, 7 Sept 2009 23:47:11 UTC; path=/'

The security model might give you some trouble if you are trying to pass this data from one domain to another though.

share|improve this answer
The question still remains: how to go about encoding the data, even if you resolve where to actually put it. –  geocar Sep 7 '09 at 15:57

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using Mule to access an Alfresco Server. We are using OpenCMIS via the CMIS Connector. I want to make a copy of a document in one folder and add it to another folder. Or just copy the entire folder. I need the copies to be independent of the originals, so that if the copies are static copies of the originals.

I suspect that in order to make copies I am going to have to go through the entire folder and copy not just the objects but also their relationships also.

share|improve this question

1 Answer 1

Document objects have a copy() method that lets you create an independent copy in a different folder. There is no copy method for folder hierarchies, though.

share|improve this answer
Thanks Florian! What about relationships? Does it copy those if there is a relationship between a document and another document? –  user1837371 Jan 3 '13 at 17:48
That is repository specific. The copy() method is based on the CMIS createDocumentFromSource operation, which main focus it is to do the content copy efficiently inside in the repository. But the repository might change everything else (permissions, properties, relationships, etc.) when it creates the new document. I think in Alfresco the copy behavior is configurable. –  Florian Müller Jan 6 '13 at 18:40

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Say I have three tables:

  • users with names IDs
  • emails containing rows which have their email address
  • messages containing rows which contain the dates and titles of their emails

the second and third tables can all be matched to the first using the user's ID of course.

I want a query which will return each user once only, their email address and the date of their most recent message.

If I use this:

SELECT name,email,title,date
FROM users
JOIN emails ON users.id = emails.user_id
JOIN messages ON messages.user_id = emails.user_id
group by name
order by date desc

I don't get the most recent message, because the ordering has happened after the joining and the grouping. I get one email each from my users, and the emails are sorted by their date.

Can this be done in one join? What am I missing?

Pastebin for a dummy database you can use: http://pastebin.com/1x273aEe -- the actual database is not exactly like this, but it's the same problem.

share|improve this question

1 Answer 1

up vote 3 down vote accepted
SELECT  a.*, b.*, c.*
FROM    users a
        INNER JOIN emails b
            ON a.ID = b.user_ID
        INNER JOIN messages c
            ON a.ID = c.user_ID
        INNER JOIN
            SELECT user_id, MAX(date) maxDate
            FROM messages
            GROUP BY user_ID
        ) d ON c.user_ID = d.user_ID AND
                c.date = d.maxDate
share|improve this answer
Hi, that's working exactly as required on JSFiddle, thank you. But curiously, it's not working as expected on my local setup, client and server both 5.1.44. Anyway, I've got the idea. –  John Horner Jan 2 '13 at 4:47
what results are you getting on your local machine? –  John Woo Jan 2 '13 at 4:49
I'm getting duplicates. The correct four results appear in the correct order, but then they appear again. It works on the production server though, different version of MySQL. –  John Horner Jan 2 '13 at 4:53
add DISTINCT, eg SELECT DISTINCT a.*, b.*, c.* ..... I guess you have duplicate rows in your table messages. –  John Woo Jan 2 '13 at 4:54
That worked. Thank you very much. Any idea why an older version of MySQL should behave that way? –  John Horner Jan 2 '13 at 4:56

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I asked this on the telerik forums, but sometimes responses can be slow there. I was wondering if anyone here know how to go about this.

I am in a situation where a user will have a variable number of items and beside each item I want a RadNumericTextBox. I was thinking of using the RadListView and setting the template to be the item name and a RadNumericTextBox associated with it. I want to ignore the edit, create, and the more advanced features of the RadListView. I just want a list of items with the input boxes that will auto post back when a user has changed the value.

The problem I am facing is when a user changes a number in the text box, how do I know which text box this is? I was looking to see if there was a attribute on RadNumericTextBox that could hold an arbitrary value such as my item key so I would know which number they changed. However, I don't see such an attribute.

Is there some way I can make a determination which text box they edited when I auto post back?

In case anyone asks, I do not want to force my user to click a button to make the row go into edit mode, change the number, then click a button to save the row.

share|improve this question

2 Answers 2

You could do this with a Repeater control.

Include a RadNumericTextBox in the repeater's item template, and then write a server-side event handler for it. The client ID of the text box can be accessed through the event handler's sender object, but if that isn't enough information you can rely on the repeater's data source to relate whatever data you need with each text box.

The simplest way might be to use the Label attribute of the text box. Here's an example:

<asp:ScriptManager ID="ScriptManager1" runat="server">
<asp:Repeater ID="Repeater1" runat="server">
        <br />
        <telerik:RadNumericTextBox ID="radNTB" runat="server" AutoPostBack="true" OnTextChanged="radNTB_TextChanged" ClientIDMode="Predictable"></telerik:RadNumericTextBox>

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then

        Dim dt As New DataTable
        dt.Columns.Add("Column1", GetType(String))

        For i As Integer = 1 To 5
            Dim row = dt.NewRow
            row.Item("Column1") = "TextBox" & i.ToString

        Repeater1.DataSource = dt

    End If
End Sub

Private Sub Repeater1_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater1.ItemDataBound
    If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then

        Dim tb As RadNumericTextBox = e.Item.FindControl("radNTB")
        tb.Label = DataBinder.Eval(e.Item.DataItem, "Column1").ToString()

    End If
End Sub

Public Sub radNTB_TextChanged(sender As Object, e As EventArgs)
    Dim ntb As RadNumericTextBox = sender
End Sub
share|improve this answer

What you can do is by the item your binding the listview with the data source, make the id of the RadNumericTextBox equals to your item key that you want to pass. In the RadNumericTextBox TextChanged event cast the sender object to RadNumericTextBox type. in this case you will get the unique item key you are looking for. example :

<asp:FormView ID="frmViewPicture" runat="server">
    <telerik:RadNumericTextBox ID='Eval("ItemKey")'
          OnTextChanged="radTxtNewPrice_TextChanged" AutoPostBack="true">

Make sure the item key is unique and available in your data source, other wise you will get an exception.

protected void radTxtNewPrice_TextChanged(object sender, EventArgs e)
   Telerik.Web.UI.RadNumericTextBox txtRadNumericTextBox= (Telerik.Web.UI.RadNumericTextBox)sender;
   var itemKey = txtRadNumericTextBox.ID;
   // Do Your Logic Here

Hope this is helpful.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have searched "ASP.NET authentication from a Windows Forms application" on google, but the results are "Windows Authentication using ASP.NET" which is not what I am looking for.

I have an ASP.NET application and a set of WCF services what provide data to the application via AJAX calls. These WCF services require ASP.NET authentication, which is fine from the browser because there is a cookie which provides the authentication information, or asks the user to authenticate via a login page.

I need to call these services from a Windows Forms application, without changing the way they work. i.e. The Windows Forms application will receive the JSON data from the service and process it.

I need to be authenticated before I can use the WCF services, but as this is not a web application, there is no cookie, and the login page cannot be displayed!

How do I provide authentication from a Windows Forms application to an ASP.NET web application?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

You need to store cookies for each request like browser. Once you send a request for log in form, cookie variables keep you authenticated for next requests.

static class Requester
    static CookieContainer cookieJar = new CookieContainer();
    static string userAgent = ""; //specify your user agent

    /// <summary>
    /// Static method to request a web page.
    /// It acts like a browser which means that keeps all cookies for depending domain.
    /// </summary>
    /// <param name="URL"></param>
    /// <returns></returns>
    static public FinalResponse sendRequest(string URL)
        return sendRequest(URL, "");

    static public FinalResponse sendRequest(string URL, string parameters)
        FinalResponse result = new FinalResponse();
        Stopwatch timer = new Stopwatch();
        HttpWebRequest request;

            request = (HttpWebRequest)HttpWebRequest.Create(URL);
            request.Referer = "http://google.com"; //specify your referer
            request.CookieContainer = cookieJar;
            request.UserAgent = userAgent;
            request.AllowAutoRedirect = true;
            if (parameters != "")
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = parameters.Length;

                //push parameters to request stream
                StreamWriter myWriter = new StreamWriter(request.GetRequestStream());
            //send request
            result.requestTime = DateTime.Now;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            result.responseMilliseconds = timer.ElapsedMilliseconds;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                result.document = sr.ReadToEnd();
                result.isSucceded = true;
        catch (Exception e)
            result.document = "";
            result.isSucceded = false;
        return result;

    /// <summary>
    /// Call this function before all usage of cookieJar.
    /// It fixes the bug (!) of CookieContainer Class.
    /// </summary>
    private static void BugFix_CookieDomain()
        System.Type _ContainerType = typeof(CookieContainer);
        Hashtable table = (Hashtable)_ContainerType.InvokeMember("m_domainTable",
                                   System.Reflection.BindingFlags.NonPublic |
                                   System.Reflection.BindingFlags.GetField |
                                   new object[] { });
        ArrayList keys = new ArrayList(table.Keys);
        foreach (string keyObj in keys)
            string key = (keyObj as string);
            if (key[0] == '.')
                string newKey = key.Remove(0, 1);
                table[newKey] = table[keyObj];
share|improve this answer
Nice example. Only thing missing is a ref to the bug your code 'fixes' in the cookieContainer - just so we know what you are actually addressing and if the bug is still present. –  beterthanlife Dec 15 '14 at 13:09
@beterthanlife Thank you. Here is where I got this workaround: stackoverflow.com/questions/1047669/cookiecontainer-bug –  Can Guney Aksakalli Dec 19 '14 at 1:09

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have been learning about the basics of C# but havent come across a good explenation of what this is.

var l = new List<string>();

I dont know what the < string > is doing or if its the List that is doing the magic. I have also seen objects been thrown within the < > tags.

Can someone explain this to me please with examples.

share|improve this question

7 Answers 7

up vote 24 down vote accepted

That is the generic syntax for C#.

The basic concept is that it allows you to use a Type placeholder and substitute the actual real type in at compile time.

For example, the old way:

ArrayList foos = new Arraylist();

worked by making ArrayList store a list of System.Objects (The base type for all things .NET).

So, when adding or retrieving an object from the list, The CLR would have to cast it to object, basically what really happens is this:

foos.Add("Test" as System.Object);
string s = foos[1] as String.

This causes a performance penalty from the casting, and its also unsafe because I can do this:

ArrayList listOfStrings = new ArrayList();

This will compile just fine, even though I put an integer in listOfStrings.

Generics changed all of this, now using Generics I can declare what Type my collection expects:

List<int> listOfIntegers = new List<int>();
List<String> listOfStrings = new List<String>();

// Compile time error.

This provides compile-time type safety, as well as avoids expensive casting operations.

The way you leverage this is pretty simple, though there are some advanced edge cases. The basic concept is to make your class type agnostic by using a type placeholder, for example, if I wanted to create a generic "Add Two Things" class.

public class Adder<T>
   public T AddTwoThings(T t1, T t2)
       return t1 + t2;

Adder<String> stringAdder = new Adder<String>();

Adder<int> intAdder = new Adder<int>();

For a much more detailed explanation of generics, I can't recommend enough the book CLR via C#.

share|improve this answer
fyi the performance penalty when using ArrayLists is when boxing and unboxing value types occurs (structs, ints, floats, etc). There is no appreciable performance penalty for casting the object reference back to a string reference. –  Robert Paulson Sep 30 '08 at 22:57
Additionally, it's a minor point, but Generics (or constructed types) in .net aren't realized (constructed) until runtime. The compiler only checks your code at compile-time and ensure that for IList<T>.Add(T) that the var in Add(var) is implicitly convertable to T. –  Robert Paulson Sep 30 '08 at 23:08
The AddTwoThings example has been covered numerous times on SO, and is not valid. –  erikkallen Feb 18 '10 at 23:00

This is generics in action. A regular List stores items of type Object. This requires casting between types. This also will allow you to store any kind of item in one instance of a list. When you are iterating through items in that list you cannot be sure that they are all of a certain type (at least not without casting each item). For instance lets say you create a list like this:

List listOfStrings = new List();

Nothing prevents someone from doing something like this:

listOfStrings.add(6); //Not a string

A generic list would allow you to specify a strongly-typed list.

List<string> listOfStrings = new List<string>();
listOfStrings.add("my name"); //OK
listofStrings.add(6); //Throws a compiler error

There is a more thorough examples on here Generics

share|improve this answer

< > is for generics. In your specific example, it means that the List is a List of strings, not say a list of ints.

Generics are used to allow a type to be, well, generic. It's used ALOT in Collections to allow them to take different types so that they can function much like a normal array and still catch invalid types being assigned at compile time. Basically it allows a class to say "I need to be associated with some specific type T, but I don't want to hard code exactly what that type is, and let the user select it.". A simple array for instance might look something like:

public class MyArray<T> {
    private T[] _list;

    public MyArray() : this.MyArray(10);
    public MyArray(int capacity)
    { _list = new T[capacity]; }

    T this[int index] {
        get { return _list[index]; }
        set { _list[index] = value; }

Here, we have a private list of type T that is accessed by using our class like a normal array. We don't care what type it is, it doesn't matter to our code. But anyone using the class could use it as, say MyArray<string> to create a list of strings, while someone else might use it as MyArray<bool> and create a list of flags.

share|improve this answer

It's generics - it's a form of type parameterisation. In your example, it's making l refer to a list of strings - the list will only ever contain strings: the compiler treats it (pretty much) as if everywhere that the API docs mention "T" it actually says "string". So, you can only add strings to it, and if you use the indexer you don't need to cast to string, etc.

To be honest, giving generics detailed coverage on an online forum is pretty much impossible. (In C# in Depth, I take nearly 50 pages talking about generics.) However, armed with the name of the feature, you should be in a much better position to find out more. The MSDN "Introduction to C# Generics" is probably a good starting point.

Asking specific questions about generics on SO is likely to yield good results - I just don't think it can really be covered properly in one question/answer.

share|improve this answer
Thanks, a nice answer. –  Ólafur Waage Sep 30 '08 at 22:04

Those are known as Generics (specifically List is a generic class).

Reading from MSDN

share|improve this answer

Those are generics. You are making a List that only contains strings. You could also say

and get a list that only contains ints.

Generics is a huge topic, too big for a single answer here.

share|improve this answer
Thanks for that and i have edited the question –  Ólafur Waage Sep 30 '08 at 22:01
NP. I deleted my suggestion as well. Into the memory hole they go. –  Eric Z Beard Sep 30 '08 at 22:02

This is .NET Generics. The type within the < > denotes the type of element contained in the list.

with ArrayList you'd have to cast the elements inside...

int x = (int)myArrayList[4];

with List you can avoid that step because the compiler already knows the type.

int x = myList[4];

Generics are available in .NET 2.0 and later.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In XmlBeans, I have a compiled schema and I create an instance through the

MyStuff stuff = MyStuff.Factory.newInstance() method.

But in a part of my application I need to treat MyStuff as a generic XmlObject and yet I want to create instances of it. Suppose that I want to do:

where workWithObjectsAbstractly is defined as:

public void workWithObjectsAbstractly(XmlObject o)
   SchemaType type = o.schemaType();
   XmlObject newInstance = type.???????   <--- is there such method?
  [Work with new instances as XmlObjects]

Is there a way to do that? I could inspect the schemaType through Particles and Properties and then create stuff with XmlCursor, but it seems cumbersome. Can I avoid it?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

I don't think you can avoid this, org.apache.xmlbeans.impl.xsd2inst.XmlSampleUtil does this abstraction in order to create auto-generated, valid instances from a SchemaType.

In this case, it uses

XmlObject object = XmlObject.Factory.newInstance();
XmlCursor cursor = object.newCursor();
// Skip the document node
// ... it then uses the cursor to add elements, attributes, etc

Hope that helps a bit...

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

New to Javascript here and from looking through Parse query string in JavaScript, I was not sure which answer could fit my needs.

I need a javascript solution that allows me to parse key/value pairs with multiple values for a single key. Example: ?key1=value1&key1=value2

share|improve this question
Hey. I think you'll find your answer here: stackoverflow.com/questions/2090551/… –  ovaherenow Oct 28 '13 at 19:09
There are lots of methods here for doing it the standard way: stackoverflow.com/questions/901115/… - You should then have your initial values be arrays and push to them each time instead of replacing the key. –  Evan Oct 28 '13 at 19:12

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I use SQL Server and Entity Framework as ORM.

Currently I have a table Product which contains all products of any kind. The different kinds of products possess different attributes.

For example:

  • All products of kind TV have attributes title, resolution and contrast
  • Where as all products of kind Car have attributes like model and horsepower

Based on this scenario I created a table called Attribute which contains all the attributes of a product.

Now to fetch a product from database I always have to join all the attributes.

To insert a product I have to insert all the attributes one by one as single rows.

The application is not just a shop or anything like it. It should be possible to add/remove an attribute to/from a kind of product on the fly without changing the db.

But my questions to you is still:

  • Is this a bad design?
  • Is there another way of doing it?
  • Will my solution slow down significant? (f.e. an insert takes several seconds assumed the product has hundreds of attributes...)

The problem is that my application is really complex. There are a lot of huge algorithms. The software is used for statistical purposes.

One problem for example is the following one: In an algorithm-table I'm storing which attributes are used for filters. Say an administrator wants to filter all cars that have less than 100 horsepowers. The filters are dynamical, what means that I have a filter table which stores the filter type (lessThan) and the attribute (horsepowers). How can I keep this flexibility with the suggested approaches (with "hardcoded" columns)?

share|improve this question
Yes, this is a really bad design - it's known as Entity Attribute Value and it's considered an anti-pattern - try to avoid it! See Five Simple Database Design Errors You Should Avoid (point #3) for a discussion of why EAV is really really bad, and see Bad CaRMa for a true horror story of an EAV system design that ruined a thriving company. –  marc_s Nov 14 '13 at 9:19
Thanks for your comment, but sometimes we have to use antipatterns when there seems to be no other solution... Or am I wrong? Is there another way? –  sjkm Nov 14 '13 at 9:33
There are lots of alternatives: (1) define a BaseProduct table with the common attributes, and then Cars and TV tables that reference the base products table, and add the additional attributes; or if that's still too rigid: (2) put the base attributes on the table, and store any additional custom attributes into an XML column - those are just the two alternatives that I've personally used with great success - I'm sure there are plenty more! –  marc_s Nov 14 '13 at 9:42
Thank you marc_s. Really appreciate your input! The thing is that I use complex sql calculations for all kinds of products. There are a lot of joins which I would have to make "dynamic" (one time it would have to join to "Cars" one time it would have to join to "TV"). Or I would have to write each piece of SQL several times for each kind of product... Can you please set me thinking :)? –  sjkm Nov 14 '13 at 9:52
Well - you're saying you're using Entity Framework - right? EF can use parent-child tables as a single entity, e.g. you could have a Car entity in EF that has some of its values in BaseProduct and the car-specific values in Car. Same for TV. That way, if you can move your calculations from SQL to EF, you could simply use a nice object model and don't worry about JOINs and everything ... –  marc_s Nov 14 '13 at 10:01

1 Answer 1

up vote 1 down vote accepted

There is a thing about EF that I don't think everybody is aware of when designing the relations.

When you query something, EF (at least <= 4) wants to create a single SELECT for that query.

What that implies is that if you have entity A, that have a one-to-many relationship to entity B (say Item to Attributes) then EF joins the two together such there will be a returned row for all dependent Bs for each A. If A have many properties, multiple dependencies or even worse if B has many sub-dependencies, then the returned table will be quite massive, since all A-properties will be copied for each row of dependent B. Over time, when your entity models grow in complexity, this can turn into a real performance problem.

EF only includes the Bs if you explicitly tell to it to eager load the dependencies "include"s. If the includes are omitted, your stuff will initially load faster, but once you access your attributes, they will be lazy-loaded by EF. This is known as the SELECT N+1 problem (each A will require N times B-lazy queries, which can be a huge overhead).

While this is not a straight answer to your question, it is something to consider when designing your tables.

Also note, that EF supports several alternatives for base-classing. One strategy is to have a common table, that automatically joined together with the sub-entities. The alternative, which typically performs better, but is harder to upgrade, is to have one table with a super-set of all properties of all sub-classes.

More (over) generalized database design considerations:

  • The devil is in the details. You can make a whole career out of making good database design choices. There is no silver bullet database patterns.
  • EF comes with a lot of limitations. This is the price for the convenience. If the model suits EF well, then EF is quite good, but do consider more flexible alternatives like NHibernate. Sometimes even plain old data tables with views and stored procedures are to be preferred.
  • EF is not efficient if your model has a lot of small dependents (like a ton of attributes to an item table). It will result in either a monster query and return table or the select n+1 problem. You can write some tricky multi-part LINQ queries to somewhat compensate, but it is tricky.
  • SQL's strength is in integrity and reporting which works best for rather rigid data models.
  • Depending on the details, your model looks like a great candidate for a NoSql backend, like RavenDb and MongoDb. NoSql is much better for dynamic datamodels and scale really well.
share|improve this answer
Thank you holstebroe! Please read my concerns about your suggestions in my last comment above. Thanks –  sjkm Nov 14 '13 at 10:16
If you have attributes that are not just custom metadata, but are used in actual business logic, then it makes sense to promote the attribute to something less dynamic. E.g. if "price" is an attribute shared by all entities, then you could dedicate an attribute for the base class. All in all, I don't think there is a clear-cut answer to how to represent attributes. It depends on an analysis of how likely it is that they will change, count (tens or tens of millions), if they can be shared. –  Holstebroe Nov 14 '13 at 10:41
Note that EF supports both stored procedures and views. Though they both come with a maintenance overhead, they allow you a few more degrees of freedom in your design. –  Holstebroe Nov 14 '13 at 10:43
Thank you very much. I also think that there is no clear-cut answer. Most of the attributes aren't shared and it must be possible to reference them for particular calculations. So you think that my antipattern approach is an acceptable compromise in the end? –  sjkm Nov 14 '13 at 10:45
added some points to my answer. –  Holstebroe Nov 14 '13 at 11:48

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there a way to create a lightning effect on the iPhone using opengl?(like this app)

Right now I have modified the glpaint sample to draw random points around a line (between two points that the user touches) and then connecting them, but the result is a zigzag line that constantly jumps around and lags horribly on the actual device.

share|improve this question
This appears to be a duplicate of this question: stackoverflow.com/questions/544097/… –  Brad Larson Apr 12 '10 at 21:40

2 Answers 2

you'll probably just want to make a triangle strip from the center of the device to the point that is being touched, then apply a drawn lightning texture to that resultant polygon.

You can animate the texture in order to get the jumping lightning effect.

share|improve this answer

A simple way to create a lightning effect is to compute the lightning path using a 2D Perlin function, rendering it to a glow buffer, blurring it with a Gaussian blur shader, and merging it with the scene. You can make the lightning move by computing two paths (start and end) with an identical number of path nodes and moving each node of the start path successively towards the corresponding node of the end path. Once the end path has been reached, it becomes the start path and a new end path is computed.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to save data from my existing webform written in php to a google spreadsheet. I tried the Zend GData and can't seem to find my way around it. Does anyone have a better solution for this.

Is it possible to grab the data and insert it into mysql database and to google spreadsheet at the same time?

share|improve this question

1 Answer 1

Have you checked the API? This page gives you what you need on inserting rows.

For a functional PHP implementation, see my question on this.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a checkbox in GridViewColumn which i use for show/change database value. The click event for the checkbox is used for change value in the database. For handling the state of property "IsChecked" I'm using datatrigger and a setter, se xaml code below:

<Style TargetType="CheckBox">
    <Setter Property="IsEnabled" Value="True" />
        <DataTrigger Binding="{Binding Path=ID, Converter={StaticResource Converter}}"   Value="true">
            <Setter Property="IsChecked" Value="True"/>

The binding works great until I click the checkbox. After I clicked the checkbox for the first time the state of the property "IsChecked" don't updates if a manually in the Database change the value which i mapped to the property "IsChecked". If I map for example the same value to the property "Content" of the checkbox the trigger works fine even after I've clicked the checkbox.

Does anyone no whats the problem is?

share|improve this question

3 Answers 3

up vote 3 down vote accepted

<Style TargetType="CheckBox">

instead be:

 <Style TargetType="{x:Type CheckBox}">

you could try this:

    <Style TargetType="{x:Type CheckBox}" >
        <Setter Property="IsChecked" Value="{Binding Path=ID, Converter={StaticResource Converter}}" />
share|improve this answer
Yes thats right. Thanks. But that does'nt help me with my propertytrigger :( –  KaJo Nov 13 '08 at 13:50
Thanks! Your last edit together with some modifications in the converter class (convert back function) solved my problem. –  KaJo Nov 13 '08 at 15:22

You can try to add a second data trigger to set the checkbox to false. As I can see from your code you set the IsChecked only to true, but never to false.

share|improve this answer

In stead of using Click to determine the changes, perhaps you can use the Checked and Unchecked events ?

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I think I need something like ruby's splat * here.

function foo() {
  var result = '';
  for (var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  return result;

function bar() {
  return foo(arguments) // this line doesn't work as I expect

bar(1, 2, 3);

I want this to return "123", but instead I get "[object Arguments]". Which makes sense, I suppose. It's passing the object that represents the arguments, but not the arguments individually.

So how do I simply forward any number of arguments to another function that takes any number of arguments?

share|improve this question

2 Answers 2

up vote 16 down vote accepted

To correctly pass the arguments to another function, you need to use apply:

function bar() {
  return foo.apply(null, arguments);

The apply method takes two parameters, the first is the thisObj, the value of it will be used as the this value inside the invoked function, if you use null or undefined, the this value inside the function will refer to the global object.

The second argument that apply expects, is an array-like object that contains the arguments to be applied to the function.

Check the above example here.

share|improve this answer

Try this return foo.apply(this,arguments). Also you can just use Array.prototype.slice.apply(arguments).join('') for your foo function.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to find information on how to serialize an object to query string format, but all my searches are drowning in results on how to go the other way (string/form/whatever to JSON).

I have

{ one: 'first', two: 'second' }

and I want

Is there a good way to do this? I don't mind plugins or whatnots - if the code I find is not a plugin, I'll probably re-write it to one anyway...

share|improve this question
Here are some nice plain JS solutions: stackoverflow.com/questions/1714786/… Some of them are not longer than the framwork solutions here. –  Simon Steinberger May 10 at 22:28

4 Answers 4

up vote 131 down vote accepted

You want $.param(): http://api.jquery.com/jQuery.param/

Specifically, you want this:

var data = { one: 'first', two: 'second' };
var result = $.param(data);

When given something like this:

{a: 1, b : 23, c : "te!@#st"}

$.param will return this:

share|improve this answer
Note that if you have an array in your object it doesn't get parameterized correctly. –  crv Apr 26 '12 at 19:46
@crv: Right. JSON is probably best in that case –  Chris Laplante Apr 28 '12 at 21:23
@crv I have an array in mine and it is working fine. –  Danyal Aytekin Dec 4 '12 at 16:52
This won't work with asp.net 4.0 because of the & in the query string without you specifically setting your requestValidationMode="2.0" –  Amicable Feb 26 at 12:00

Another option might be node-querystring.

It's available in both npm and bower, which is why I have been using it.

share|improve this answer

Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.

For example:

var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);
share|improve this answer

For a quick non-JQuery function...

function jsonToQueryString(json) {
    return '?' +
        Object.keys(json).map(function(key) {
            return encodeURIComponent(key) + '=' +

Note this doesn't handle arrays or nested objects.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've got a perl project's mercurial/hg repository here with a lot of modules. Now, I've realized that some of the modules, a branch of modules, does not fit into this project anymore but would be better suited in another project.

So, is it possible to "clone" these modules from repository1 into my other repository2 while keeping these modules's revision history and at the same time flagging the modules in repository1 as "removed"?

I think it is possible with a number of steps. But I think cloning the whole repo1 and then removing all the unnecessary files would clutter my new repo2 with a lot of unrelated revision history. Still, as I understand the "clone" and "pull" commands neither of them is suited to clone just a slice of another repository, right? Or is it possible to "move" a file from one repository into another? As I see it that's the analogy of what I want to do..

share|improve this question

1 Answer 1

up vote 5 down vote accepted

Absolutely! Take a look at the Convert extension, specifically the Mercurial-to-Mercurial section which should do exactly what you want.

After you've split off those modules, you can use hg forget, hg remove to remove them from your original repository, or even use hg convert again to create a new repository without them.

share|improve this answer
The Mercurial-to-Mercurial section is exactly what I need. Thanks! –  isync Aug 4 '10 at 21:05

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I hope this question hasn't been answered yet somewhere else. Didn't find an answer here.

In my localisation system I've got a class named Language

class Language(val name:String, dict:HashMap[String, String]) {
  def apply(key: String):String = (dict get key) match {
    case None    => "°unknown°"
    case Some(s) => s

and an object named LanguageCentral

object LanguageCentral {
  private var lang:Option[Language] = None

  def language = lang

  def language_=(l:Option[Language]) = l match {
    case None    => {}
    case Some(l) => setLanguage(l)

  def setLanguage(l:Language) {
    lang = Some(l)

I haven't written any code that's using this framework yet but trying it in an interactive session revealed a type error I don't really understand:

scala> val l = new LanguageCreator("Languages.csv").getLanguage("English")
l: Option[Language] = Some(Language@7aeb46d)

scala> LanguageCentral.language=l
<console>:23: error: type mismatch;
 found   : Option[Language]
 required: Option[Language]

scala> LanguageCentral setLanguage (l getOrElse null)
<console>:24: error: type mismatch;
 found   : Language
 required: Language
       LanguageCentral setLanguage (l getOrElse null)

I really don't have a clue what's wrong. But from my experience with Haskell I guess that the solution is only a minor change away.;)
Could somebody help me? Thx.

P.S.: using Scala 2.8.0.final

share|improve this question
The LanguageCreator class might be interesting? Maybe you could try to boil it down to as little code as possible that still gives the same error –  svrist Sep 1 '10 at 11:28
hi svrist and thx for your reply In an interactive session I boiled down the code to basically the getter-/setter stuff you see in LanguageCentral and it worked fine. So thanks for your tip: at least I know the error isn't there ;) LanguageCreator creates the demanded Language using a selfmade Wrapper around opencsv. I'm a bit reluctant to post the whole class (100 Lines). Any suspicions? What should I look for? Some lazy magic maybe? (didn't explicitly use lazyness) By the way: the localization framework has no package yet (so I can test it). The compiler creates only one Language.class –  Agl Sep 1 '10 at 13:13
no line breaks? (wasntme) –  Agl Sep 1 '10 at 13:14
I would look for nested classes perhaps? –  svrist Sep 1 '10 at 18:14
don't think so. But I'll have a closer look. Looks like there ARE two different Language classes (see the comments to Daniels answer) –  Agl Sep 1 '10 at 20:29

1 Answer 1

up vote 2 down vote accepted

To me it looks like there are two distinct Language classes defined. One way of that happening on REPL is like this:

class Language
class LanguageCreator // using Language
// Oops, there's something that needs fixing on Language
class Language
object LanguageCentral // refers to a different Language altogether

Outside REPL, they might just be in different packages. There's a way to make REPL print fully qualified types, but I couldn't find the incantation at the moment.

From the compiler side, you may use -uniqid and -explaintypes to get better error messages. I always use the latter, in fact. If you can't understand them, please update your question with them, and I'll take a look at it. Also, -Xprint-types may be of use, though that's a lot of information, so I'd rather avoid it if possible.

share|improve this answer
Just to be clear: I assume REPL is the interpreter? Language, LanguageCreator and LanguageCentral all reside in the same .scala File. With currently no package declaration around them and not importing anything except standard packages and the the Wrapper around opencsv (which, as I checked, does not declare a class Language). I have to run now but in 2 hours I'll do a project wide check and/or google for that REPL option. Thanks for your answer. Much appreciated. –  Agl Sep 1 '10 at 13:58
Oh and just to be clear about that: Currently there is NO WRITTEN CODE TRYING TO DO WHAT I DID IN THE INTERPRETER. I still have to do that but it's very likely I'll run into the same error at compile time. –  Agl Sep 1 '10 at 14:00
@Agl Yes, REPL is the "interpreter". It stands for read-eval-print loop, and it is more accurate than "interpreter" because Scala doesn't interpret code, just compiles it. I suggested it might be a problem that happened inside REPL because you have shown the errors as displayed from inside REPL. –  Daniel C. Sobral Sep 1 '10 at 15:23
@Agl I haven't found the REPL option yet, but I updated the answer with some compiler options. –  Daniel C. Sobral Sep 1 '10 at 15:29
The only 2 things that worked where: (A) altering the source file (as explained earlier or (B) putting all the Language stuff into it's final package and start REPL with scala -cp .:./lib/opencsv-2.2.jar -deprecation and load the needed packages in REPL. Now that I know it, it seems kind of obvious and I feel a little bit sorry for wasting your time. ;) Thanks a lot to both of you for your patience and guidance! –  Agl Sep 3 '10 at 17:46

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

We have a web application which contains a bunch of content that the system operator can change (e.g. news and events). Occasionally we publish new versions of the software. The software is being tagged and stored in subversion. However, I'm a bit torn on how to best version control the content that may be changed independently. What are some mechanisms that people use to make sure that content is stored and versioned in a way that the site can be recreated or at the very least version controlled?

share|improve this question

3 Answers 3

When you identify two set of files which have their own life cycle (software files on one side, "news and events" on the other, you know that:

  • you can not versionned them together at the same time
  • you should not put the same label

You need to save the "news and event" files separatly (either in the VCS or in a DB like Ian Jacobs suggests, or in a CMS - Content Management system), and find a way to link the tow together (an id, a timestamp, a meta-label, ...)

Do not forget you are not only talking about two different set of files in term of life cycle, but also about different set of files in term of their very natures:

Consider the terminology introduced in this SO question "Is asset management a superset of source control" by S.Lott

  • software files: Infrastructure information, that is "representing the processing of the enterprise information asset". Your code is part of that asset and is managed by a VCS (Version Control System), as part of the Configuration management discipline.
  • "news and events": Enterprise Information, that is data (not processing); this is often split between Content Managers and Relational Databases.

So not everything should end up in Subversion.

share|improve this answer

Keep everything in the DB, and give every transaction to the DB a timestamp. that way you can keep standard DB backups and load the site content at whatever date you want if the worst happens.

share|improve this answer

I suppose part of the answer depends on what CMS you're using, and how your web app is designed, but in general, I'd regard data such as news items or events as "content". In other words, it's not part of your application - it's the data which your application processes.

Of course, there will be versioning issues between your CMS code and your application code. You could manage this by defining the interface between the two. Personally, I'd publish the data to the web app as XML, which gives you the possibility of using XML schema to define exactly what the CMS is required to produce, and what the web app should expect to process.

This ought to mean that most changes in the web app can be made without a corresponding alteration in the rendering of the data. When functionality changes require this, you can create a new version of the schema and continue to make progress. In this scenario, I'd check the schema in with the web app code, but YMMV.

It isn't easy, and it gets more complicated again if you need additional data fields in your CMS. Expect to plan for a fairly complex release process (also depending on how complex your Dev-Test-Acceptance-Production scenario is.)

If you aren't using a CMS, then you should consider it. (Of course, if the operation is very small, it may still fall into the category where doing it by hand is acceptable.) Simply putting raw data into a versioning system doesn't solve the problem - you need to be able to control the format in which your data is published to the web app. Almost certainly this format should be something intended for consumption by software, and therefore not usually suitable for hand-editing by the kind of people who write news items or events.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

So I have a file that should never be accessed by a user directly, but included in another PHP file. If the file is called directly, it generates a HTTP Status 404 Not Found to trick a possible attacker that such file doesn't exist. However, if the hacker could tell that the 404 was generated by PHP or is not "natural" then the whole point of the header would be lost. So is it possible to tell whether the 404 was generated by the server naturally (because the file really doesn't exist) or by a PHP code?

PS: I know this question might seem pretty weird lol

share|improve this question
This doesn't directly answer your question...but why not use a 403 forbidden code instead? –  NickAldwin Jan 6 '11 at 17:58
RFC2616 states that the 404 status code may be used to indicate a refusal to respond to the request when the server does not wish to reveal exactly way the request was refused. w3.org/Protocols/rfc2616/rfc2616-sec10.html –  Brad Jan 6 '11 at 18:00
@Nick: I'm not the OP, but I imagine a 403 forbidden would let an attacker (particularly an automated one) know "hey, that file's there, I'm on the right track" –  Alan Storm Jan 6 '11 at 18:00
@Alan good point. –  NickAldwin Jan 6 '11 at 18:01
Alan is right, lol he's not me, but he's also right about the attacker knowing the file is there! –  JCOC611 Jan 6 '11 at 18:01

5 Answers 5

up vote 5 down vote accepted

A smart attacker would check the raw status headers and look for any discrepancies that might indicate if something was a "natural" 404 or not.

For example, the version of Apache on my server sends back the following headers if you request a file that's not there

HTTP/1.1 404 Not Found
Date: Thu, 06 Jan 2011 18:10:57 GMT
Server: Apache/2.2.17
Content-Type: text/html

However, if I setup a PHP page to send back a 404 header, my server sends back the following headers

HTTP/1.0 404 Not Found
Date: Thu, 06 Jan 2011 18:10:48 GMT
Server: Apache/2.2.17
Connection: close
Content-Type: text/html

So, there's nothing that obviously indicates that it was PHP that generated the headers in the second case, but that extra

Connection: close

header indicates there's something else going on. Very sophisticated attackers have built up default header profiles for as many web servers and dynamic runtimes as they can that looks at the exact content and order of the headers to determine what server and technology stack you may be running. A sophisticated attacker will know (or have a tool which indicates) that PHP always sends a Connection: close header, which may reveal your base technology.

I use the command line program curl to check headers.

curl -I 'http://example.com/asfasdfsd'

YOu can find more information on the OWASP wiki.

Similarly, make sure the raw text that your PHP page sends back matches what your apache server send back down to the byte level. A smart attacker would look for differences in the formatting of the output to determine if your page was a "natural" 404 or not.

share|improve this answer
The HTTP/1.0 rather than HTTP/1.1 might also give a hint –  Mark Baker Jan 6 '11 at 18:36
@Mark: Yep, and that one was my own fault for using my ancient PHP header code example. If your header signature doesn't match any known server baseline, the attack might suspect they're dealing with a dynamic 404 –  Alan Storm Jan 6 '11 at 18:37
You've got a good imagination, bro. –  Your Common Sense Jan 6 '11 at 18:42
Not an imagination Col. Shrapnel, I just pay attention. See the OWASP link I just added to the post (which breaks in the comments). –  Alan Storm Jan 6 '11 at 18:50

The only way to tell is if the page generated by PHP is different than that of the one generated by the webserver. Otherwise, there is no difference.

You should also set the expose_php value in your PHP.ini to off so that PHP doesn't insert a header saying "generated by..." among other things. See http://blog.arvixe.com/expose-php-servertokens-apache/

share|improve this answer

I would suggest you place the file that should not be available directly outside of your DOCUMENT_ROOT if that is possible.

share|improve this answer

This doesn't answer the question, but here's a related tip: files that should never be accessed by a user directly should be placed outside the web server's document root directory.

share|improve this answer

As long as the HTTP return status code is 404, then it is by definition, a real 404, regardless of what other content is returned.

But I think you may be asking the wrong question.

Internally included files should be protected by, for example, putting them into their own directory, and using a .htaccess or other webserver directive to deny all access to that directory. Then you don't have to worry about "protecting" each and every internal file, and you don't have to worry about a programming error accidentally letting someone in.

share|improve this answer
The thing is that I don't know if I'm going to store other data that should be accessible in the same directory. But I'll think about it. –  JCOC611 Jan 6 '11 at 18:05

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a .dll I would like to decompile to make some improvements to the code. What are some tools out there that will allow me to do this?

It's written in VB, I believe.

share|improve this question

2 Answers 2

The answer depends on what language the DLL was written in.

If it was a .NET language then, as pointed out, you can use .NET Reflector.

If it's the older Visual Basic (pre-.NET), then the DLL is compiled as what's called p-code and there are a few options for doing some variations on decompiling.

Finally, if it's written in a language like C++, there is no direct way to obtain the source code. Such a DLL is compiled to machine language and can only be directly decompiled to assembly language.

So, again, it depends on the language used. And the answer might be that it's just not possible to get anything resembling the original source code.

share|improve this answer
+1 Definitely the most complete answer. –  Babak Naffas Mar 4 '11 at 18:00
The language is Pre-.net –  curiousgeorge Mar 4 '11 at 18:24
Then, as stated, if it's Visual Basic, research p-code decompilers. –  Jonathan Wood Mar 4 '11 at 18:35
What what I was really looking for was a way to see the source code from a .dll. I don't know if there are free tools for this? –  curiousgeorge Mar 4 '11 at 19:17
Viewing the source code from a compiled DLL is called decompiling. The source code is not inside a DLL--it has to be reconstructed by decompiling the binary data. There's only so many different ways I can answer your question. I've been very thorough. –  Jonathan Wood Mar 4 '11 at 19:29

.NET Reflector!!!

It is even free, you won't need the pro version to see the dissassembled code.

share|improve this answer
That will work if it's VB.NET. If it's VB6 he's out of luck. –  David Mar 4 '11 at 17:52
true that, just made the assumption. –  Orbit Mar 4 '11 at 17:52

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this algorithmic problem to resolve, I have a vector with numbers and I must find the longest unimodal streak (that means it can increase then decrease, but not more than one time).

i.e : in the vector [4 5 8 5 9 6 3], 45863 is an unimodal streak while 458593 isn't because it's increasing to 8 then decreasing to 5 then increasing again (which is not permitted).

Using dynamic programming I managed to create 3 vectors : the first one with the length of the longest increasing streak that stops at the element x, the second one with the length of the longest decreasing streak that starts at the element x, and the third one is the sum of the first two.

Basically if I take the maximum of the third vector it's the length of the longest unimodal streak+1 (because the element x is counted twice).

What I want to do now is to display that streak. I'm thinking of using these vectors that way : using a "for" starting at the position of the maximum and going to the beginning of the vector. The I'm going to check the value in the first vector and if that value is exactely 1 less than the previous value (the first time it will be the value of the maximum in the first vector) I will keep that value in a queue and display it later, then continue. I will then do nearly the same thing for the second part of the vector using the second vector.

I know that sounds messy and complicated but with this example it will be clearer.

I have this base vector :
9 4 5 6 9 7 8 3 4 3

1 1 2 3 4 4 5 1 2 1 (first vector) = A
4 2 3 3 4 3 3 1 2 1 (second vector) = B
5 3 5 6 8 7 8 2 4 2 (sum of the two) = C

So the longest streak here is 7 and the peak is 9 (or 8 but thats the same thing).

So what I want to do is : The value of the peak is "4" in the first vector so I'll check the first being "3" going left, it's 6, I put it in the queue, I'm now looking for the first "2", it's 5, in the queue, and then it's 4 because it's the first with the value "1".

I will then display the queue, then the peak, then do the same thing with the second part. I will have 4 5 6 9 7 4 3. (Which is the good sequence).

My question is : Will this work every time? I have the feeling that something can screw up so I did some tests and every time it went fine. I'd like to know if there are specific base vectors that screw the thing up. If you could please tell me what you think that would be great!

Thank you for reading all this, I hope that someone can help me.

share|improve this question
Why is the peak 4 and not 5? Are you taking the maximum of the base vector or the maximum of A? –  IVlad Apr 15 '11 at 14:07
The peak is 9, which has the value 4 in A. The only maximum I track is the maximum of C which give me the position of the peak. –  Sword22 Apr 15 '11 at 15:10

2 Answers 2

up vote 0 down vote accepted

Looks good to me. The dynamic programming solution, if implemented correctly, is guaranteed to find the optimum because it indirectly checks all possible selections. In this case, the sequence needs to have a "center" (the point where it stops increasing and starts decreasing). That's the parameter you're brute-forcing.

One remark, though

The I'm going to check the value in the first vector and if that value is exactely 1 less than the previous value (the first time it will be the value of the maximum in the first vector) I will keep that value in a queue and display it later.

I think what you really want here is a stack, not a queue, given that the last element you'll find is the first one you want to display. That applies to the first vector.

More generally, you can use a regular array and that'll work for both vectors.

share|improve this answer
Yeah I coded a stack but I wrote queue here, no clues why. I fact what I'm afraid of, is that if by any chance when I put elements in the stack I put two elements that are not in the same streak that could go wrong. –  Sword22 Apr 15 '11 at 14:58
i.e. 7 4 9 5 10 ... There are three good sequences : 7 9 10, 4 9 10 and 4 5 10, I don't want to get 7 5 10 for instance. That's what I'm not sure of. Until now it looks that it's not gonna happen. About using a regular array that would simplify my code what do you mean, creating a vector of the right size and putting them in the right place directly? –  Sword22 Apr 15 '11 at 15:04
the thing about using an array is that you can later access it in either direction. –  abeln Apr 15 '11 at 15:45
About your first question. Once you have the two arrays with 1) the longest non-decreasing sequence ending at position i and 2) the longest non-increasing sequence starting at position i, then you can be certain of where the "center" of the sequence you're looking for should be. After that, you're good to go. In your example, say you find that 5 should be the center. When scanning to the left, you would never pick 7 5 10 because 7 > 5. You do have to keep track of what the last element you picked was, it's not enough with the length being one less than the previous one. –  abeln Apr 15 '11 at 15:51
I meant 10 the center but with two possible increasing streaks intersecting themselves like 7 4 9 5 10 2 1 => 4 5 10 2 1 and not 7 5 10 2 1. But the problem doesn't occur and it's not easy to be sure he won't. Anyway I ran a lots of tests and it works every time. Thank you for your time. –  Sword22 Apr 15 '11 at 16:49

I think it's sound. If the maximum element of the best unimodal streak is e, then the best possible left half and right half will be found in A and B. Since the left and right sequences are totally independent, this method will always work.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This seems like an obvious one, but I'm somehow missing it...

How do you send options along with a backbone.js collection fetch()?

Or, from a broader point of view: I have a large dataset on the server, messages in this case, that I want to make accessible through a collection. Seeing as there could be thousands of messages I don't want to simply fetch and store all of them at once, so my collection would have to at least understand limits and offsets. Not to mention querying filtered or sorted lists.

Is a backbone collection even the way to handle this?

share|improve this question

4 Answers 4

up vote 31 down vote accepted

I've been messing with Backbone for a couple days now and I had to deal with this problem almost immediately and I looked at this solution, but I found it clunky. After reading some more backbone documentation I discovered you can actually override any of the jQuery.ajax options within the fetch() method. So for example

Posts = Backbone.Collections.extend({
  model: Post,
  url: '/posts'

Now when you want to call fetch just send it whatever parameters you wish. e.g.

var posts = new Posts();
posts.fetch({ data: { page: 3, pagesize: 10, sort: 'asc' } });

This will produce the following request:

Anyway, I know you've already accepted an answer, but hopefully this will help someone.

share|improve this answer

Override the "url" function of your collection and add the parameters (?param=xyz).

The options parameter of fetch can also be used as it is the one passed along to the final jQuery ajax call. So if you add a "data" param there it will be used.

share|improve this answer

You can add an id to the url that can be used by the server to make a selection of the data send. E.g.

    var EventsCollection = Backbone.Collection.extend({

        model: Events,

    var eventCollection = new EventsCollection();
    eventsCollection.url = 'foo?offset=10&limit=20';
share|improve this answer

Consider this code, where when you instantiate your collection, you pass in preferences for its offset, limit, or sorting. The initialize takes defaults if preferences are not provided. And then the url function appends these into the call to the server. Thereafter, you would have to potentially update these values (probably just the offset), when processing responses from the server.

MessageList = Backbone.Collection.extend({

    initialize: function(models, options) {
        options || (options = {});
        this.offset = options.offset || 0;
        this.limit  = options.limit || MessageList.DEFAULT_LIMIT;
        this.sortBy = options.sortBy || MessageList.DEFAULT_SORTBY;

    url: function() {
        return '/messages?' +
               'offset=' + encodeURIComponent(this.offset) + '&' +
               'limit=' + encodeURIComponent(this.limit) + '&' +
               'sort_by=' + encodeURIComponent(this.sortBy);

    parse: function(response) {
       // Parse models
       // Parse offset, limit, sort by, etc

}, {

    DEFAULT_SORTBY: 'name_asc'

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am developing a site and want to centralize this site in the center of the screen (horizontally and vertically) but can not. I could only centers it horizontally.

Since I've been searching and the solutions I found when I try to apply them to my site, it all mangled.

This is the website http://amsdarquitetura.com.br/

share|improve this question
You have some errors on your page, like multiple id:s with the same name. Try to fix them first: validator.w3.org –  August Karlstrom May 17 '11 at 19:23

5 Answers 5

up vote 3 down vote accepted

This is what you need:

<style type="text/css">

#global {
    width: 700px;
    height: 400px;
    margin-top: -200px; /* half of the height */
    margin-left: -350px; /* half of the width */
    left: 50%;
    top: 50%;

    border: 1px solid #333;
    background-color: pink;

Put this on your parent div.

share|improve this answer

To lead you down the right path, try using JAVASCRIPT (might want to add a tag) to detect the window.height.

// The window.innerHeight and document.body.clientHeight will make sure it is cross-browser compatible.
function getHeight() {
    return window.innerHeight != null? window.innerHeight: document.body != null? document.body.clientHeight:null;

Then subtract the height of your main div.

var maindiv=500; //this is your total height of main div with content
var windowHeight = getHeight();
var displayHeight= windowHeight-maindiv;

Then divide by 2 (top/bottom)

var topMargin= displayHeight/2;

And finally, add a 'margin-top' to the main div.

share|improve this answer

Horizontal is easy:

<style type="text/css">
    #wrap {
        margin: 0 auto;
        width: 800px;

    <div id="wrap">

Vertical is much more difficult, and will likely require CSS3 or javascript positioning.

share|improve this answer

You'll have to define a height and width for your whole site to keep it centered in both directions.

From there, it's just doing the math on your vertical centering. Horizontal is pretty automatic with defining a width and having the margin:0 auto; (Don't use 5px auto.).

Here's a decent article on vertical centering:

share|improve this answer

There is a jQuery plugin to do this. I see you already using jQuery on your main page.

It seems the CSS options for doing this are complicated, unreliable, and hacky, as you found out.

You could implement a custom jQuery function to do the same thing. But why maintain that code when someone else has the problem solved already?

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there any methods to reduce processor time usage for a non-main thread in .NET environment. The thread is used for getting informaion from a web-server all the time and it consumes all one-core processor time. I know I can use Thread.Sleep() but it doesn't seem a nice solution for this task.

share|improve this question
... launch a separate process that will debug your process... –  modosansreves Dec 14 '11 at 18:02
... or, launching subprocess inside a Job –  modosansreves Dec 14 '11 at 18:03

2 Answers 2

up vote 2 down vote accepted

Messing with priorities, etc, will not work. If you have 1 thread in your system that's saying "I've got work to do, let me work", and no other competing threads, windows will keep scheduling it.

You indicate that this thread is getting information from a web server. Presumably, it's at least blocking whilst waiting for a response from the server, so hopefully not using CPU at that time. Unfortunately, it does sound like you're polling for information, so Thread.Sleep may be best here - unless there's some other out of band signal that could tell the thread when it should next poll.

If the web server "knows" when the thread should next poll, it could hopefully be modified to include such information in its responses. You could then extract that information from the response, and at least set your Sleep periods to an appropriate value.

Alternatively, if another thread will obtain information from elsewhere that indicates that a new request should be issued, then rather than Thread.Sleep, you should use an Event (e.g. AutoResetEvent), and WaitOne on that signal, again specifying a suitable sleep period. That way, something else can awaken this sleeping thread whenever they think polling should again occur.

share|improve this answer

You can modify the priority of the background threads

share|improve this answer
The thread is working in infinite loop. Seems the priority doesn't help in this case because the main thread is used for handling GUI and doesn't consume much processor time. –  MaxFX Jul 8 '11 at 6:31
I would expect .NET to properly throttle low priority threads, even if the main thread isn't consuming much processor time. I couls be wrong though –  Jim Deville Jul 8 '11 at 6:34
Oh boy one thing to not do is modify priorities because if you have a Thread.Sleep(0) call you can essentially deadlock that thread if a higher priority thread is executed after yielding your timeslice using Thread.Sleep(0). The OS should know what to do with the threads anyway. –  Jesus Ramos Jul 8 '11 at 7:04

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am working on a project that is adding a couple of features to a fragile and not well written Rails 2.3 app. I was trying to install just one gem, but I made a mistake when I ran 'gem install' and it updated 29 gems, including some of the Rails gems!

I know I can manually remove each new gem version, but I was wondering if there was an option to roll back the gem installation and undo all 29 updates. I am using rubygems 1.4.2 and do not have the option to upgrade.

share|improve this question

1 Answer 1

Had this accident today... I just had to write a short script to fix it:

while read line; do
    package=`echo $line | awk '{print $3}' | sed 's/\([a-z0-9_-]*\)-.*/\1/'`
    version=`echo $line | awk '{print $3}' | sed 's/[a-z0-9_-]*-\(.*\)/\1/'`
    gem uni $package -v $version
done < accident

accident is just the output of the renegade install:

Successfully installed builder-3.0.0
Successfully installed activemodel-3.2.6
Successfully installed rack-1.4.1
Successfully installed rack-cache-1.2
Successfully installed rack-test-0.6.1
share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am about to get rid of a few templates on one of my sites. There are many pages under those templates like

What is the right way to tell Google that this page does not exist anymore so that it takes that page out of its index?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

If you want Google to delete the pages without carrying forward the references then a simple HTTP 404 will do the trick. If you want Google to forward the references (such as page rank and etc) to the new page then you would be better off using an HTTP 301.

Also See: Google 301 Recommendation.

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using Visual Studio 2010 and asp .net C#. I wrote the code below:

protected void Page_LoadComplete(object sender, EventArgs e)

    tbTLCTitle.Text = readMainXml("homepage", "LeftColumnTop", "title");
    String[] liTable = readMainXmlList("homepage", "LeftColumnTop", "textRow");
    for (int i = 0; i < liTable.Length; i++)
        TextBox tb = new TextBox();
        tb.CssClass = "tbCss";
        tb.ID = "textbox" + i;
        tb.Text = liTable[i];
        tb.BorderStyle = BorderStyle.None;
protected void btnSave_Click(object sender, EventArgs e)
    ContentPlaceHolder cph = (ContentPlaceHolder)Master.FindControl("cpTextContent");
    if (cph != null)
        var div = cph.FindControl("divTextRow");
        if (div != null)
            var tb =
            if (tb != null)
                tb.Text = "TextBox found!";

I am going to explain what I want to do:

I have a div with id="divTextRow" and I want to add some textbox objects dynamically.

At Page_LoadComplete I read the xml and I create the TextBox objects with text from the xml and id = "textbox" + i (example: textbox0).

In my page I have a button with id="btnSave" and OnClick="btnSave_Click".

Now I want to take the text from those textbox objects and save it to xml.

I have the code to save to xml but I cannot take the text from textbox objects.

share|improve this question
can you post your html code also? –  Laurence Burke Nov 22 '11 at 14:52
can you post the front end code as well? It would be helpful to see that also. –  Robert Nov 22 '11 at 14:52
Please post the markup for these controls. Are they all server side (runat="server")? –  Oded Nov 22 '11 at 14:52
In your code, you are assigning a value to your textbox. I did not see any code which would get the value from the textbox. –  Angelo Nov 22 '11 at 14:52
Are you able to successfully get the div control in var div = cph.FindControl("divTextRow"); –  Kash Nov 22 '11 at 15:03

2 Answers 2

Your div tag with id="divTextRow" should be a server control in order to do that. Hence add the attribute runat="server" to this div tag in the markup of the .aspx file.

share|improve this answer
Thank you for the answer. I have already done this, so I can find this object (var div = cph.FindControl("divTextRow");). The problem is in that line: var tb = div.FindControl("textbox0"); I cannot find that object. –  Abraham Nov 22 '11 at 22:40
Usually ASP.NET would prefix the IDs of such dynamically generated UI controls based on its scope. hence your textbox might have an ID like "ctl00$cplh$textbox0". I would suggest to do a View Source of the rendered page which has these textboxes and check the IDs of these controls. –  Kash Nov 23 '11 at 2:36
I have tried everything. Asp.net gives them id="cpTextContent_textbox0","cpTextContent_textbox1",etc but I cannot find it.. Maybe the problem is that textboxes on every postback I won't find them because they just don't exist. –  Abraham Nov 23 '11 at 9:00

See this article in MSDN. Try using document.getElementById method.

share|improve this answer
Thanks, but doesn't help me. Maybe because I am not familiar with java. –  Abraham Nov 24 '11 at 10:48

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a PHP query that displays the first 30 documents, then an anhor which loads the rest of the documents using jQuery load.

Although, the parent uses javascript for some effects. Although once loaded onto the document it doesn't seem to inherit it's script tags.

is there any solution for this?

share|improve this question
What are the "documents" you're talking about? How about the parent? How do you mean it doesn't "inherit" its script tags? Whose script tags aren't getting inherited by who? –  jprofitt Nov 23 '11 at 16:07

1 Answer 1

you have to put your "effects" into a function, then in the success of the load you have to call that function again.

function effects(){
     //all your effects
$('#result').load('ajax/test.html', function() {
share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.


text:
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an iPhone app I am building with MonoTouch (C#). My current view has a segmented control with three options. Depending on which segment is chosen, I want to display data related to the segment. The data will most likely require scrolling. My question is, what control(s) should I use to accomplish this? Do I use three ScrollView controls? If so, how do I show/hide each control based on the selected segment?

Thank you!

share|improve this question

1 Answer 1

up vote 0 down vote accepted

I came across a situation like this. In short, I did it with a single UITableView and UITableSource. When the user selects one segment, the appropriate data source is replaced with the one that corresponds to that specific segment and the table is reloaded (tableView.ReloadData() in most occasions).

It might get a bit complex, if for example "Segment A" contains text-only rows and "Segment B" contains text + image rows. In this case, you will need a bit more logic in the UITableSource's GetCell method to determine what cell will be displayed based on the type of data.

To minimize complexity, I have created a custom interface and generic class that inherits it:

interface ITableRow

    string RowTitle { get; set; }
    string RowSubTitle { get; set; }

class TableRow<T> : ITableRow

    public TableRow(string rowTitle, string rowSubtitle, T dataObject)
        // fill the properties with values here

    public string RowTitle { get; set; }
    public string RowSubTitle { get; set; }
    public T DataObject { get; set; }

My data source is always a List<ITableRow> (or a Dictionary<TSome, ITableRow> in some cases), so the UITableSource.GetCell implementation "knows" what to assign to each cell every time.

You could also extend it (I have) by adding the following constructor:

public TableRow(Func<string, T> rowTitleFunc, Func<string, T> rowSubtitleFunc, T dataObject)
: this(rowTitleFunc(dataObject), rowSubtitleFunc(dataObject), dataObject) {}

This way you can display different data in each row based on each row's "dataObject".

PS (off topic): Don't you just love C# on iOS?

share|improve this answer

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.