Friday, April 29, 2011

Access mysql on netbeans

I tried to do this tutorial

http://www.linglom.com/2007/12/05/accessing-mysql-on-netbeans-using-jdbc-part-i-create-a-connection/

but it gives me an error. I searched to understand what the error means, but i don't know.

the error said :

Class Not Found Exception: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I think the error : error when load mysql driver !!

I don't know how to correct the error !

Can you help me please?

From stackoverflow
  • I found the error: I add the jdbc driver (mysql-connector-java-5.0.7.zip) not the jdbc driver (mysql-connector-java-5.0.7.jar)

What are the best practices for Design by Contract programming.

What are the best practices for Design by Contract programming.

At college I learned the design by contract paradigma (in an OO environment) We've learned three ways to tackle the problem :

1) Total Programming : Covers all possible exceptional cases in its effect (cf. Math)

2) Nominal Programming : Only 'promises' the right effects when the preconditions are met. (otherwise effect is undefined)

3) Defensive Programming : Use exceptions to signal illegal invocations of methods

Now, we have focussed in different OO scenarios on the correct use in each situation, but we haven't learned WHEN to use WHICH... (Mostly the tactics where inforced by the exercice..)

Now I think it's very very strange that I haven't asked my teacher (but then again, during lectures, noone has)

Personally, I never use nominal now, and tend to replace preconditions with exceptions (so i rather use : throws IllegalDivisionByZero, than stating 'precondition : divider should differ from zero) and only program total what makes sense (so I wouldn't return a conventional value on division by zero), but this method is just based on personal findings and likes.

so I am asking you guys :

Are there any best practises??

From stackoverflow
  • It all boils down to what responsibilities do you wish to assign to the client and the implementer of the contract.

    In defensive programming you force the implementer to check for error conditions which can be costy or even impossible in some cases. Imagine a contract specified by the binarySearch for example your input array has to be sorted. you can't detect this while running the algorithm. you have to do a manual check for it which will actually bump the execution time an order of magnitude. to back my opinion up is the signature of the method from the javadocs.

    Another point is People and frameworks now tend to implement exception translation mechanisms which is used mainly to translate checked exceptions (defensive style) to runtime exceptions that will just pop up if something wrong happens. this way the client and implementer of the contract has less to worry about while dealing with each other.

    Again this is my personal opinion backed only with what limited experience I have, I'd love to hear more about this subject.

    Mykola Golubyev : You can check either array is sorted as precondition. We do this in the c++ with asserts.
    MahdeTo : checking the whole array is sorted takes more time than actually doing a binary search in it :)
    Peter : Just some thoughts : you could check preconditions only in certain modes, say for unittesting no? Further a precondition can be just stated and not tested, of course
  • ...but we haven't learned WHEN to use WHICH...

    I think the best practice is to be "as defensive as possible". Do your runtime checks if you can. As @MahdeTo has mentioned sometimes that's impossible for performance reasons; in such cases fall back on undefined or unsatisfactory behavior.

    That said, be explicit in your documentation as to what has runtime checks and what does not.

  • Like much of computing "it depends" is probably the best answer.

    Design by contract/programming by contract can help development greatly by explicitly documenting the conditions for a function. Just the documentation can be a help without even making it into (compiled) code.

    Where feasible I recommend defensive - checking every condition. BUT only for development and debug builds. In this way most invalid assumptions are caught when the conditions are broken. A good build system would allow you to turn the different condition types on and off at a module or file level - as well as globally.

    The actions taken in release versions of software then depend upon the system and how the condition is triggered ( usual distinction between external and internal interfaces ). The release version could be 'total programming' - all conditions give a defined result (which can include errors or NaN)

    To me "nominal programming" is a dead end in the real world. You assume that if you passed the right values in (which of course you did) then the value you receive is good. If your assumption was wrong - you break down.

  • I think that test driven programming is the answer. Before actually implementing the module, you first create a unit test (call it a contract). Then gradually implement the functionality and make sure the contract is still valid as you go. Usually I start with plain stubs and mockups, then gradually fill out the rest replacing the stabs with real stuff. Keep improving and making the test stronger. At the end you end up with a robust implementation of said module plus you've got a fantastic test bed - coded implementation of the contract. Later on, if someone modifies the module, first you see if it can still fit the test bed. If it doesn't, the contract is broken - reject the changes. Or, the contract is outdated, - fix the unit tests. And so on.. Boring cycle of software development :)

  • I didn't know about this division, and it doesn't really reflect my experience.

    Total Programming is virtually impossible. You could not guarantee that you cover all exceptional cases. So basically you should limit your scope and reject the situations that are out of scope (that's the role of the Pre-conditions)

    Nominal Programming is not desired. Undefined effect should be banned.

    Defensive Programming is a must. You should always signal illegal invocations of methods.

    I'm in favour of the implementation of the complete Design-by-Contract elements, which is, in my opinions a practical and affortable version of the Total Programming

    Preconditions (a kind of Defensive Programming) to signal illegal invocation of the method. Try to limit your scope as much as you can so that you could simplify the code. Avoid complex implementation if possible by narrowing a little bit the scope.

    Postconditions to raise an error if the desired effect is not obtained. Even if it your fault, you should notify the caller that you miss your goal.

    Invariants to check that the object consistency is preserved.

What's the best way to draw a bunch of (~200) colored rectangles in Cocoa?

My current plan is to draw the rectangles by subclassing NSView, but that seems like a very inefficient way for what I'm trying to do, which is to draw a bunch of fixed, non-overlapping rectangles that changes colors once in a while. Is there a better way? Thanks.

From stackoverflow
  • You can try using CALayers, kind of like this: http://theocacao.com/document.page/555.

  • If they're all the same color or image, you may find a single CGLayer more efficient. The purpose of that API is drawing the same thing many times.

    On the other hand, if the rectangles move independently or have different colors or images on them, Core Animation is definitely the way to go.

  • Core Animation would be a great technology for a game, but if you want to stick with NSView for the time being you could create a class similar to NSCell that the gameboard view uses to implement positioning and drawing. This would work in a similar way as many Cocoa control classes, which use a single cell (with different values) to draw multiple items inside a view.

    Keep in mind that using individual NSView objects may very well be more than fast enough, but regardless of any speed differences this strategy allows you to separate the logic in a way that makes sense.

How do you flip the coordinate system of an NSView?

I have created an NSScrollView in interface builder that has a variable number of semi-unique NSViews that can be programmatically added and removed from it. When I add subViews to the documentView, they appear in the lower-left hand corner instead of the upper-left hand corner. I see that you can check the isFlipped bool to figure out if the view's coordinate system is flipped, but I cannot find a way to set it as flipped.

Anyone know what I'm missing?

From stackoverflow
  • In your NSView subclass, override the isFlipped method:

    isFlipped Returns YES if the receiver uses flipped drawing coordinates or NO if it uses native coordinates.

    - (BOOL)isFlipped

    Discussion The default implementation returns NO; subclasses that use flipped coordinates should override this method to return YES.

Adding options to a select using Jquery/javascript

What's the easiest way to add an option to a dropdown using javascript? Can this work?

$("#mySelect").append('<option value=1>My option</option>');
From stackoverflow
  • I believe that's the easiest way. You might be interested in this cheat sheet (PDF) on using jQuery with selects for more info.

    StuperUser : You are a lifesaver!
  • That works well.

    If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.

  • If the option name or value is dynamic, you won't want to have to worry about escaping special characters in it; in this you might prefer simple DOM methods:

    var s= document.getElementById('mySelect');
    s.options[s.options.length]= new Option('My option', '1');
    
    Click Upvote : Doesn't look so simple to me!!
  • for whatever reason doing $("#myselect").append(new Option("text", "text")); isn't working for me in IE7+

    I had to use $("#myselect").html("text");

  • I agree Ashish, this did NOT work in IE8 (yet did in FF):

    $("#selectList").append(new Option("option text", "value"));

    This DID work:

    var o = new Option("option text", "value"); /// jquerify the DOM object 'o' so we can use the html method $(o).html("option text"); $("#selectList").append(o);

Google Android - how to figure out if 3g and 2g is turned on.

I'm developing a simple application for the Google Android to turn on and off the wifi or 3g or 2g.

I see http://developer.android.com/reference/android/net/wifi/WifiManager.html#isWifiEnabled() that you can see if the wifi is enabled or disabled and also us http://developer.android.com/reference/android/net/wifi/WifiManager.html#setWifiEnabled(boolean) to turn on and off the wifi.

I'm wondering if it's possible to do the same for 3G and for 2G/GPRS? I know it's possible because you can turn off 3G and left 2G on.

From stackoverflow
  • 2G/3G

    To determine your network type use:

    TelephonyManager.getNetworkType();
    

    here's some example code:

    bool is3G = (manager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
    

    Docs for the class can be found at: TelephonyManager


    On/Off

    To check if your telephone radio is on or off use:

    ServiceState.getState();
    

    To set it use:

    ServiceState.setState(STATE_POWER_OFF);
    

    It's unclear whether the setState method exists on all devices and functions in all states. There is no documentation for this method. Documentation for the class can be found at: ServiceState

    This issue might also be relevant: http://code.google.com/p/android/issues/detail?id=1065

  • You can also use ConnectivityManager. Something like that:

    ConnectivityManager connectivityManager =(ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    

Cheap WYSIWYG Editor for Static Websites (think Frontpage)

I am looking for an easy to use WYSIWYG athoring tool that lets me build a complete website that consists of multiple connected static html pages. Actually something like Frontpage would be exactly what I need. I can define menus, contact forms, design the layout and define how the sites are linked to each other. But frontpage seems to be discontinued and also the older versions are still slightly too expensive. Is there a good cheap (maybe open source) alternative that can to those things I mentioned? The resulting website doesn't have to be compliant to any html/css standards.

From stackoverflow

Determine if a function is available in a Python module

I am working on some Python socket code that's using the socket.fromfd() function.

However, this method is not available on all platforms, so I am writing some fallback code in the case that the method is not defined.

What's the best way to determine if a method is defined at runtime? Is the following sufficient or is there a better idiom?

if 'fromfd' in dir(socket):
    sock = socket.fromfd(...)
else:
    sock = socket.socket(...)

I'm slightly concerned that the documentation for dir() seems to discourage its use. Would getattr() be a better choice, as in:

if getattr(socket, 'fromfd', None) is not None:
    sock = socket.fromfd(...)
else:
    sock = socket.socket(...)

Thoughts?

EDIT As Paolo pointed out, this question is nearly a duplicate of a question about determining attribute presence. However, since the terminology used is disjoint (lk's "object has an attribute" vs my "module has a function") it may be helpful to preserve this question for searchability unless the two can be combined.

From stackoverflow
  • hasattr() is the best choice. Go with that. :)

    if hasattr(socket, 'fromfd'):
        pass
    else:
        pass
    

    EDIT: Actually, according to the docs all hasattr is doing is calling getattr and catching the exception. So if you want to cut out the middle man you should go with marcog's answer.

    EDIT: I also just realized this question is actually a duplicate. One of the answers there discusses the merits of the two options you have: catching the exception ("easier to ask for forgiveness than permission") or simply checking before hand ("look before you leap"). Honestly, I am more of the latter, but it seems like the Python community leans towards the former school of thought.

    Paolo Bergantino : I don't see how this answer deserves a downvote... :/
    bobince : I'd prefer hasattr over getattr just for readability's sake!
  • Or simply use a try..except block:

    try:
      sock = socket.fromfd(...)
    except AttributeError:
      sock = socket.socket(...)
    
    Paolo Bergantino : I believe that would throw an AttributeError if it doesn't exist, not a NameError
  • hasattr(obj, 'attributename') is probably a better one. hasattr will try to access the attribute, and if it's not there, it'll return false.

    It's possible to have dynamic methods in python, i.e. methods that are created when you try to access them. They would not be in dir(...). However hasattr would check for it.

    >>> class C(object):
    ...   def __init__(self):
    ...     pass
    ...   def mymethod1(self):
    ...     print "In #1"
    ...   def __getattr__(self, name):
    ...     if name == 'mymethod2':
    ...       def func():
    ...         print "In my super meta #2"
    ...       return func
    ...     else:
    ...       raise AttributeError
    ... 
    >>> c = C()
    >>> 'mymethod1' in dir(c)
    True
    >>> hasattr(c, 'mymethod1')
    True
    >>> c.mymethod1()
    In #1
    >>> 'mymethod2' in dir(c)
    False
    >>> hasattr(c, 'mymethod2')
    True
    >>> c.mymethod2()
    In my super meta #2
    

Where is the "work" directory located for a Tomcat instance running in Eclipse?

In Eclipse you can configure numerous servers to run inside the IDE, including Tomcat. Depending on your Tomcat configuration, at some point in the life cycle of a webapp your JSP files will get compiled into servlets. These new servlet .class files are stored in the %TOMCAT_HOME%/work directory along with the .java intermediate file created from the JSP. This .java file is very helpful when your JSPs throw exceptions and cite a line number corresponding to the .java and not the .jsp

Update: On my environment (Windows), it is located here:

C:/Documents and Settings/%USER%/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work

Perhaps to answer more completely somebody could post the location for *nix environments.

From stackoverflow
  • I assume it would be the same location relative to your workspace.

  • You can change it by setting scratchDir parameter in web.xml configuration of your server (in Servers project, not in your application web.xml!).

  • You will find it in

    projectworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0

    This is the default place where Eclipse 3.4 publishes the project. However, this can be changed by changing the settings in your 'Server' view.

  • The easiest way is most likely to ask a compiled JSP page about the source of the code.

    From http://www.exampledepot.com/egs/java.lang/ClassOrigin.html:

    // Get the location of this class
    Class cls = this.getClass();
    ProtectionDomain pDomain = cls.getProtectionDomain();
    CodeSource cSource = pDomain.getCodeSource();
    URL loc = cSource.getLocation();  // file:/c:/almanac14/examples/
    

    Hopefully this helps. What is it you want to do?

    Peter Štibraný : Great tip (if it works ;-))!
    Thorbjørn Ravn Andersen : I haven't tried it with JSP pages, but it works fine with plain classes in Tomcat. Also note that some JEE containers know how to work with unexploded web archives. The URL would then probably start with jar: - there is no guarantee that the URL is to a file resource.
  • Go to "Servers" window -> double click on your tomcat instance -> clik "Open launch configuration" -> go to "Arguments" tab.

    Look for variable definition like this:

    -Dcatalina.base="/Users/dirtyaffairs/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0"
    

InterPage Linking Problem in MHT

Hello sir,

I had a task were I have to process one big .xml file and genrate different .html from it by using xslt. Now after release coustomer wants to combime all the html to single .mht file. I have converted the source code to genrate the .mht file, but I am having problem in linking the html file in the .mht.

I have created a .mht file in following format (See attachment).

EXPLANATION:-

The .mht file contains following htmls. MHTLinkingProblem.html Left.html Right.html Start.html Plus.gif Mktree.css

  1. The MHTLinkingProblem.html is the main html which is divided in 2 frames.
  2. The Start.html dummy html to display the start of the page
  3. The Right.html contains :- An image with a source attribute pointing to the content-id of the image embedded in the .mht file. Code: -

b. And a anchor tag with a name attribute. Code: -

  1. The Left.html contains two links to the Right.html. :- LinkWithoutFragmentRefURL LinkWithFragmentRefURL
    1. The mktreee.css file contain some url that refers to the image that are present in the .mht file.

THE PROBLEM:-

  1. The .mht file has one mktree.css file where its using the url to access one of the image which is embedded in the .mht file. Like this ul.mktree li.liOpen .bullet { cursor: pointer; background: url(cid:minus.gif);
    center left no-repeat; } its not able to pic the image in the .mht file.

  2. The link shown in 5.b is not working. That is I am not able to refer a particular fragment of the html file using .mht. This is because the .mht resolve this URL in following format:- cid:Right.html#LinkName Now there is no content-id naming cid:Right.html#LinkName so it returns a error Page Cannot be displayed.

QUESTION:-

  1. How to use the Relative Reference URL in the "href" attribute of the anchor tag so that it refers to a fragment(anchor tag with name attribute) of ANOTHER html in the same .mht file?

  2. If the image is embedded in the .mht file then How to use the image embedded in the .css file.

Please help me with this problem. Its been two weeks since I am searching for a solution to this problem, but I had no success.

Regards, Thanks in advance, Naveen Murthy

From stackoverflow
  • Hello all,

    I apologize for not pasting the code in the correct format. I have attached the code in the correct format now, so please copy the code as some test.mht

    I have posted this topic in mime as well as html catgories as it is relevant to both the topics.

    The core problems remain the same:- We have one .mht file containing multiple html files

    1. How to use the Relative Reference URL in the "href" attribute of the anchor tag (a.html#some_locn1) so that it refers to a fragment (anchor tag with name attribute) of ANOTHER html contained within the same .mht file

    EXPLANATION:-

    1. The .mht file contains following htmls

      a. MHTLinkingProblem.html
      b. Left.html
      c. Right.html
      d. Start.html
      e. Plus.gif
      f. Mktree.css
      
    2. The MHTLinkingProblem.html is the main html which is divided in 2 frames.

    3. The Start.html serves no purpose other than bringing up a filler page on load.
    4. The Right.html contains :-

      a.An image with a source attribute pointing to the content-id of the image embedded in the .mht file.

         <img src="cid:plus.gif" alt="plus.gif">
      

      b. And a anchor tag with a name attribute.

         <a name="LinkName">
      

    5.The Left.html contains two links to the Right.html.

      <a href="cid:Right.html" target="Data">LinkWithoutFragmentRefURL</a>
      <a href="cid:Right.html#LinkName" target="Data">LinkWithFragmentRefURL</a>
    

    THE PROBLEM (Revisited):-

    1. The .mht file has one mktree.css file where its using the url to access one of the image which is embedded in the .mht file. Like this ul.mktree li.liOpen .bullet { cursor: pointer; background: url(cid:minus.gif); center left no-repeat; } its not able to pic the image in the .mht file.

    2. The link shown in 5.b is not working. That is I am not able to refer a particular fragment of the html file using .mht. This is because the .mht resolve this URL in following format:- cid:Right.html#LinkName Now there is no content-id naming cid:Right.html#LinkName so it returns a error Page Cannot be displayed.

    Regards,

    Thanks in advance,

    Naveen Murthy

    Code follows from here


       From: Regression
      To: Regression-User
      Subject: Regression
      Message-ID: Regression.html
      Mime-Version: 1.0
      AbsoluteURI: "thismessage:/"
      Content-Type: multipart/related; boundary="----------1234567890------00-----";
                    type="text/html"
    
      ------------1234567890------00-----
      Content-Type: text/html; charset="US-ASCII"   
    
      <html>
       <head>   
           <title>MHTLinkingProblem</title>
        </head>
        <frameset cols="350,*">
           <frame src="file://c:/Left.html" name="Navigation" scrolling="yes"   noresize/> 
           <frame src="cid:Start.html" name="Data" scrolling="yes" noresize/>
           <noframes>
               <h1>Sorry, this browser does not support frames.</h1>
           </noframes>
        </frameset>
      </html>
    
      ------------1234567890------00-----
      Content-Location: file://c:/Left.html
      <!-- Content-ID: Left.html -->
      Content-Type:text/html;
    
      <html>
         <head>
            <title>Right</title>     
         </head>    
         <body> 
            <ul>
               <li><a href="cid:Right" target="Data">LinkWithoutFragmentRefURL</a></li>         
               <li><a href="cid:Right#LinkName" target="Data">LinkWithFragmentRefURL</a></li>     
            </ul>
         </body>
      </html>
    
      ------------1234567890------00-----
      Content-Location: file://c:/Right.html
      Content-ID: Right
      Content-Type:  text/html    
    
      <html>
         <head>
         <title>Right</title>        
         </head>
         <body >
           This is a Right Hand Side of Page.<br/><br/>   
           <IMG SRC="cid:plus.gif" ALT="plus.gif"></body>     
           <a href="#LinkName">Name</a>
           <!-- Please dont delete these br. These are required. -->    <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>           <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
           <a name="LinkName"><b>This the Location where LinkWithFragmentRefURL should refer to.</b></a>     
          </body>
       </html>
    
      ------------1234567890------00-----
      Content-Location: cid:Start.html
      Content-ID: Start.html
      Content-Type: text/html     
    
      <html>
         <head>
           <title>Start</title>
         </head>
         <body>
            This is a Starting Page.
         </body>
      </html>
    
     ------------1234567890------00-----
     Content-Type: image/gif
     Content-ID: plus.gif
     Content-Transfer-Encoding: base64
     Content-Disposition: inline; filename="plus.gif"
    
    
     R0lGODlhEAAQAKIAAMDAwICAgACAgAAA/wAAAP///wAAAAAAACH5BAUUAAUALAAAAAAQABAAAANC
     WLpFxHC5MV5Uk1LLstZcIwBfyRHDWH4WmpLr1mhq7LhUDRJCMNMwx6iH+QiEgKRDAholAcvO5hmN
     oHjVSyOr7SoSADs=
    
     ------------1234567890------00-------
    
  • A quick way to solve your problem would be to build what you want in html, then open it inside a browser that saves pages as mht files (like IE or Opera), save your html as mht, then inspect the generated code. I'll post some code as soon as I get it working.

    Edit 1:
    Ok. I've made a few tests and here's what I found out.

    1. mhtml browsers support is incomplete
    2. Opera's mhtml support seems to be better then IE's, or at least more reasonable
    3. Saving a frameset from internet explorer doesn't includes the frames inside the mht file (who was the idiot who came up with this!?)
    4. Saving a frameset from Opera does includes the frames inside the mht file
    5. Opera supports interlinking between internal pages inside mht files using relative urls, but only from the starting page
    6. Opera supports interlinking between internal pages inside mht files using cid urls from all internal pages
    7. Opera doesn't supports framesets inside mht files at all, even though it is able to save them
    8. IE doesn't supports interlinking between internal pages inside mht files at all, nor it supports framesets inside mht files

    Maybe Safari web archive format will achieve what you want. I'll try that later and if it works I'll post the results.

    Edit 2:
    I noticed your question was posted on many other forums. I hope this also clarifies some of the answers posted elsewhere.

    The ietf rfc 2110 ("mhtml spec") links to the html 2 spec, so I guess I was written long before frames existed. The rfc 2557 which superseeded 2110 doesn't talks about interlinking html files inside mht, but Jacob Palme's page about mhtml (Mr. Palme was one of the 3 people who wrote the rfc) states that:

    The main idea of the MHTML standard is that you send a HTML document, together with in-line graphics, applets, etc., and also other linked documents if you so wish, in a MIME multipart/related body part. Links in the HTML to other included parts can be provided by CID (Content-ID) URLs or by any other kind of URI, and the linked body part is identified in its heading by either a Content-ID (linked to by CID URLs) or a Content-Location (linked to by any other kind of URL). (In fact, the "Content-ID: foo@bar header" can be seen as a special case of the "Content-Location: CID: foo@bar header".)

    So I guess what you're trying to do is perfectly legal, it's just not supported yet.

    I also gave a look on Safari web archive. It saves everything inside a binary xml plist, which is not very intuitive to edit by hand. Also, the page is encoded inside the xml instead of being stored in plain html, which is even less friendly, so I won't even bother to test if it supports frames because it would be a nightmare to create a whole site inside a plist.

  • Here's a minimal mht file with 2 internal pages and an image to everyone who whishes to test mht interlinking. It works fine with Opera. It opens with IE, but the links are broken.

    Content-Type: multipart/related; start=<index@local>; boundary=next_part
    Content-Location: /
    Subject: =?utf-8?Q?MHT Interlinking?=
    MIME-Version: 1.0
    
    --next_part
    Content-Disposition: inline; filename=index.htm
    Content-Type: text/html; charset=utf-8; name=index.htm
    Content-Id: <index@local>
    Content-Location: /
    Content-Transfer-Encoding: 8bit
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
    <title>Index</title>
    </head>
    <body>
    <p>this is the start page</p>
    <p><a href="cid:internal@local">internal page</a><img src="cid:gif@local" /></p>
    </body>
    </html>
    
    --next_part
    Content-Disposition: inline; filename=internal.htm
    Content-Type: text/html; charset=utf-8; name=internal.htm
    Content-Id: <internal@local>
    Content-Location: /
    Content-Transfer-Encoding: 8bit
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title>Right</title>
    </head>
    <body>
        <p>this is the internal page</p>
        <p><a href="cid:index@local">start page</a></p>
    </body>
    </html>
    
    --next_part
    Content-Type: image/gif
    Content-Id: <gif@local>
    Content-Transfer-Encoding: base64
    Content-Location: right.gif
    
    R0lGODlhCgAaANU/AAQWPAkcQwARNBYuWQAOLB03Yw8lTnqGky5NfTVVhy1LezdYiUFOZBozX6Cw
    x3N+i4SYt1VxmwsaN0tplS07VCZCcP39/m+Gqh44ZVRwmwwhSn+UtFtxlRkyXSM+ay1Jdxw1YbXH
    2zBGbQAPLwMRL5WmwZ2txitIeBwuTlNvmoCMmggXNxEnUBMoUDFRghgsUp2svR8yWAsgSIuYpw4j
    TIKXtmN2lE5rlxgxXC5MfB02Yg0hSgAOK3iEkTZXif///yH5BAEAAD8ALAAAAAAKABoAQAaMQIfD
    VNpwRLaQxcdk5nQ7Xq/phEp5WKyE8fj9qD4ExkBSgZ/RKTPhqrAEhF4kkkndEpUXCgZGWNVNaFJn
    f2AKIDJSDQ0dAzQAAjwMBxAQNRsXEx8xSU0LCwgeLCszfQU0BAeEaauDVIKAVayvhbQarmsnOAFS
    Cr4nHgMAIxI9AceQIwQUXT3OzwdeP0EAOw==
    
    --next_part--
    

How can a formcollection be enumerated in ASP.NET MVC?

How can I enumerate through all the key/values of a FormCollection (system.web.mvc) in ASP.NET MVC?

From stackoverflow
  • foreach(var key in Request.Form.AllKeys)
    {
       var value = Request.Form[key];
    }
    
  • Here are 3 ways to do it specifically with a FormCollection object.

    public ActionResult SomeActionMethod(FormCollection formCollection)
    {
      foreach (var key in formCollection.AllKeys)
      {
        var value = formCollection[key];
      }
    
      foreach (var key in formCollection.Keys)
      {
        var value = formCollection[key.ToString()];
      }
    
      // Using the ValueProvider
      var valueProvider = formCollection.ToValueProvider();
      foreach (var key in valueProvider.Keys)
      {
        var value = valueProvider[key];
      }
    }
    
  • foreach(KeyValuePair<string, ValueProviderResult> kvp in form.ToValueProvider())
    {
        string htmlControlName = kvp.Key;
        string htmlControlValue = kvp.Value.AttemptedValue;
    }
    
  • And in VB.Net:

        Dim fv As KeyValuePair(Of String, ValueProviderResult)
        For Each fv In formValues.ToValueProvider
            Response.Write(fv.Key + ": " + fv.Value.AttemptedValue)
        Next
    
    DrydenMaker : I get "Expression is of type 'System.Web.Mvc.IValueProvider', which is not a collection type" when I try this. If I leave out the "ToValueProvider" it compiles, but I get "Specified cast is not valid."

Uploading a Java Applet into a webpage

I have created a java letter game applet using netbeans 6.0 which also has a Microsoft Access Database for the High Scores. I want to upload it into a webpage (like how its done on miniclip facebook etc) I'd like to know how it could be done

From stackoverflow
  • I'm not sure what you mean with "upload it into a webpage". Applets are embedded into webpages using the <applet> tag or the <object> tag. However, the Access DB could become a problem, since it is poorly suited to an internet app with potentially many concurrent users.

    Additionally, accessing a DB directly from an applet is a very bad idea, since the applet code (which is globally accessible to everyone) will need to contain the DB user and password, which means that everyone who bothers to decompile the applet can do whatever they want (and that user is allowed) to do with the DB. At the very least, they'll be able to enter fairy tale highscores (e.g. 50 million when a perfect game gets you 1000).

    htw : Minor note: is technically a deprecated tag. While is simpler to use, it would probably be better to recommend using the tag (http://www.w3schools.com/TAGS/tag_object.asp).
  • As Michal Borgwardt said, in order to put the actual applet on your page you upload the compiled class file and then use an applet or object tag.

    For high scores, you need to use a database on your web server (such as MySQL) and write a page that interfaces it using PHP or ASP or your other web language of choice. You would then have the applet open the specified page, giving it POST parameters of the player's name, score, etc. Also, since things like that can be spoofed, you need to figure out a way to prevent people from just opening the page themselves with bogus name and score entries.

  • Manipulating <td>'s within different <tr>'s

    Hello, I'm wondering if the following can be done.

    I have a list of 'expenses' that I'm displaying in a table. 4 columns - amount, date, where, and what.

    I was thinking I'd like to make each clickable via jQuery which would expand that particular expense, inline, to show a more detailed description.

    What I'm trying to do is, on click, replace the contents of the 'tr' with a single 'td' that would contain the extended info. Problem is that 'td' only expands to about a quarter of the table. Is there any way of making it extend to the whole row, while maintaining the widths of the other 'td's in the other rows?

    From stackoverflow
    • <td colspan="4"> ?
      
    • Here's what I would do. Working Demo.

      <table id="expenses">
      <thead>
        <tr>
          <td>Amount</td>
          <td>Date</td>
          <td>Where</td>
          <td>What</td>
        </tr>
      </thead>
      <tbody>
        <tr class='expense' id='expense-1'>
          <td>$5.99</td>
          <td>4/2/2009</td>
          <td>Taco Bell</td>
          <td>Chalupa</td>
        </tr>
        <tr class='details' id='details-1'>
          <td colspan='4'>
          It was yummy and delicious
          </td>
        </tr>
        <tr class='expense' id='expense-2'>
          <td>$4.99</td>
          <td>4/3/2009</td>
          <td>Burger King</td>
          <td>Whopper</td>
        </tr>
        <tr class='details' id='details-2'>
          <td colspan='4'>
          The king of burgers, indeed!
          </td>
        </tr>
        <tr class='expense' id='expense-3'>
          <td>$25.99</td>
          <td>4/6/2009</td>
          <td>Olive Garden</td>
          <td>Chicken Alfredo</td>
        </tr>
        <tr class='details' id='details-3'>
          <td colspan='4'>
          I love me some italian food!
          </td>
        </tr>
      </tbody>
      </table>
      

      With styles like these:

      #expenses tr.expense {
          cursor: pointer;
      }
      #expenses tr.details {
          display: none;
      }
      

      And then have Javascript that looks like this:

      $(function() {
          $('tr.expense', '#expenses').click(function() {
              var id = $(this).attr('id').split('-').pop();
              var details = $('#details-'+id);
              if(details.is(':visible')) {
                  details.hide();
              } else {
                  details.show();
              }
          });
      });
      

      That should do it.

    • Whoops! Looks like I wasn't logged in... now I lost the ability to edit my question.

      Thanks to both of you. Paolo, that code is exactly what I was looking for. Thank you!

      Paolo Bergantino : You're welcome. :)

    Is there something like AppVerifier or Driver Verifier for Linux?

    I am hoping that someone can point me toward Linux software similar to the Microsoft tools Application Verifier and Driver Verifier. (They are stress testers for Windows applications and drivers, respectively.)

    Do such things exist for Linux?

    From stackoverflow
    • I'm not familiar with Application Verifier and Driver Verifier at all...

      For applications, Valgrind is very useful as a tool to check for leaks, use-after-free, double free, buffer overflow, use of unitialized data, unsafe concurrent data access, and much more.

      There also exist many fuzzers (zzuf, fusil, etc.) which test a program's resiliance to invalid input.

      GCC itself has -fstackprotector, which enables SSP (stack-smashing protector, aka ProPolice); -fmudflap, which detecs some other bad memory usage; and (in conjunction with glibc) -D_FORTIFY_SOURCE=n, which puts extra checking on various string and memory functions.

      In the Linux kernel, there are many configuration switches under the "Kernel hacking" menu:

      • CONFIG_DEBUG_SLAB, CONFIG_DEBUG_PAGEALLOC, etc., which ensure that memory is allocated, used, and freed sanely
      • CONFIG_DEBUG_OBJECTS, which checks that objects are used and freed orderly
      • kmemcheck, "Valgrind for the kernel"
      • CONFIG_PROVE_LOCKING, which analyzes for all possible deadlocks
      • CONFIG_DEBUG_PREEMPT, CONFIG_DEBUG_MUTEXES, CONFIG_DEBUG_SPINLOCK, CONFIG_DEBUG_SPINLOCK_SLEEP, etc., which warn on improper use of locking
      • CONFIG_FAULT_INJECTION & co., which probabilistically cause failures of memory allocation and I/O

    DataNucleus: How do I automatically perform actions when commiting a transaction?

    Consider having an application using DataNucleus with the following persistence structure:

    You have a class that has two attributes like created (Date) and lastUpdate (Date): How do you automatically fill those attributes with the appropriate values when an object of this class is going to be committed? Appropriate values would be setting both, created and lastUpdate to the current time when an object is inserted into the database and just updating lastUpdate when it has changed.

    From stackoverflow
    • I figured it out myself now.

      You need to create an InstanceLifecycleListener...

      public class BasicEntityLifecycleListener implements StoreLifecycleListener {
      
          public void postStore(InstanceLifecycleEvent evt) {
          }
      
          public void preStore(InstanceLifecycleEvent evt) {
           if((PersistenceCapable)evt.getSource() instanceof BasicEntity) {
            BasicEntity obj = (BasicEntity)evt.getSource();
            Date now = new Date();
            if(JDOHelper.isNew(obj))
             obj.setCreated(now);
            obj.setLastUpdate(now);
           }
          }
      }
      

      and then register it within you PersistenceManager...

      PersistenceManager pm = pmf.getPersistenceManager();
      pm.addInstanceLifecycleListener(new BasicEntityLifecycleListener(), null);
      

      I found the solution in the DataNucleus Access Plaftorm manual which I didn't have recognized until now. The online manual seems a bit complex to me.

    How to make WCF service using nettcpbinding reconnect automaticlly?

    I have an asynchronous WCF service using nettcpbinding. And I send a bunch of requests to it and get result by invoking EndDoWork() in my callback. If EndDonWork throw a exception once, all the invocation after that will throw exception said: communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.

    I think that's something close the connection because of the first exception. My question is: 1. what decide this behavior? If I use basicHttpBinding, the later invocation of EndDoWork work well. Is it related with keepAlive support? 2. Is there any property of configuration item I can set to ask service reconnect automatically?

    From stackoverflow
    • If I remember correctly, you can avoid the channel faulting if you declare the Fault in the operation contract.

      For example:

      [ServiceContract]
      public interface IService
      {
          [OperationContract]
          [FaultContract(typeof(MyDefinedFault))]
          void Operation();
      }
      

      As you have already declared MyDefinedFault in the Operation contract if you throw that from the service, the channel is not going to fault (unless of course you are using the System.ServiceModel.Description.ServiceDebugBehavior.IncludeExceptionDetailInFaults=true that may fault the channel anyways).

    • Where is the MyDefinedFault class. how to define this class.

      WillH : This is a class you create yourself. Can be very simple such as: [DataContract] public class MyDefinedFault { [DataMember] public string ExceptionString { get; set; } public MyDefinedFault(string exString) { ExceptionString = exString; } }

    Formatting integer for string output

    In a breakpoint action, I'm going this:

    @(const char *)[(NSString*)[myobject retainCount]UTF8String]@
    

    which gives this output:

    <Error: Cannot access memory at address 0x2>
    

    If I do this:

    @(NSString*)[myboject retainCount]@
    

    it outputs a memory address. But if I do this in code:

    NSLog(@"retain count is: %d", [myobject retainCount]);
    

    it gives this output:

    2009-04-18 09:58:48.085 myapp[80277:20b] retain count is: 1
    

    What is the syntax needed to output correctly in the breakpoint action?

    Also, where can I find a complete listing of the format keys for breakpoint actions?

    From stackoverflow
    • You should be able to actually use a "Debugger Command" breakpoint action over the "Log" action, setting the command text to:

      p (int)[myObject retainCount]

      If you want to log the description of an Objective-C object:

      po myObject

      You can use a Log action before it to display a message indicating what is being printed if you want.

      As for the specific retain count issue you're logging in this case, examining retain counts directly and trying to solve memory related bugs that way isn't considered a great practice. See this post for a good explanation about that.

    • retainCount returns a number. Simply casting it to a string is incorrect, since it's a number, not a string. To print a number as a string you have to either call:

      printf("%d",[myobject retaincount]);
      

      or print out this string:

      [NSString stringWithFormat:@"%d",[myobject retaincount]];
      

    Question about 3rd Normal Form

    The following table :

    EmpId  State   Zip
    1       FL   342008
    2       CA   342001
    

    is not in 3rd normal form because State is dependent on the primary key(EmpId) transitively.

    So, if I break it like this : (EmpId,State) (State,PIN)

    it's in 3NF.

    I could also break it like : (EmpId,State) (EmpId,PIN) and it will again be in 3NF.

    But in the second case, there is redundancy of information, for e.g.

    1  FL
    2  FL
    
    1 342008
    2 342008
    

    Which property does the second decomposition violate?

    From stackoverflow
    • This doesn't directly address your question, but, strictly speaking, the state column is redundant, because it can be derived from the ZIP code (although you're showing six-digit ZIP codes, which aren't standard in the USA.) You could break the table down by EmpID and ZIP, leaving State by itself in a lookup table.

    • As already said, there is redundancy because the State can be inferred by the ZIP Code, hence, you should have your tables in this way:

      EmpId Zip
      1     342008
      
      Zip    State
      342008 FL
      

      Always think on what depends on what. Of course, there is already an standard process to normalize based on set theory. This could help you too.

    • To directly address the question asked, the violated property is FFD (full functional dependency on the key).

    Learning resources to transerfer my MS SQL Server knowledge into MySQL

    I'm an experienced MS SQL Server developer
    But with my first MySQL project I got problems with very simple issues
    So can anyone suggest good resources helping me transfer my MS SQL Server knowledge into MySQL
    I'm not looking for a complete reference guide for MySQL
    I'm looking for something targeted for experienced SQL developers

    EDIT: here are sample of issues I faced (thanks Neil Butterworth)
    1- Where to write my first "select * from", NOW I know that
    - I've to download MySQL which is NOT coming with IDE
    - I can pick up SQLyog as MySQL IDE

    2- How to execute multiple sql statements in the same query(done)
    3- How to declare variables (done)
    4- How to write simple cursor (still trying)
    5- How to add primary key to existing table by MySQL query not by IDE (still trying)
    6- What is the different between Wamp Server and [MySQL + SQLyog] (still trying)

    From stackoverflow
    • There probably aren't going to be any guides that address your specific issues, so I'd just recommend reading through the excellent documentation on the MySQL website. If you have a particular problem that's causing grief, and that isn't addressed in the docs, then ask about it here.

    • There was a similar question with very usefull answers:

      http://stackoverflow.com/questions/368858/hidden-features-of-mysql

    • Here's a good place to start: Migrating From MS SQL to MySQL

    Passing an array as an argument in C++

    I'm writing a merge sort function, and right now I am just using a test case array (there is no input - this is static, for now). I don't know how to pass an array as an argument. Here is my code right now:

    //merge sort first attempt
    
    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    int mergeSort(int[]);
    int main()
    {
    int originalarray[] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
    mergeSort(originalarray[]);
    }
    
    int mergeSort(int[] originalarray)
    {
    int num = (sizeof(originalarray)/sizeof(int));
    std::vector<int> original(num);
    
    if (num > 2) {
        return num;
    }
    
    // Fill the array using the elements of originalarray
    // This is just for demonstration, normally original will be a parameter,
    // so you won't be filling it up with anything.
    std::copy(originalarray, originalarray + num, original.begin());
    
    // Create farray and sarray of the appropriate size
    std::vector<int> farray(num / 2);
    std::vector<int> sarray(num - farray.size());
    
    // Fill those using elements from original
    std::copy(original.begin(), original.begin() + farray.size(), farray.begin());
    std::copy(original.begin() + farray.size(), original.end(), sarray.begin());
    
    mergeSort(farray);
    mergeSort(sarray);
    

    }

    Note that this mergeSort function is not functional, as I have not figured out how to merge them yet (that's my assignment). I would like to get my two vectors sorted before I deal with that, and I can't compile this because of my need to pass an array as an argument. I don't understand pointers, so if that is the solution, my excuse is ignorance. I'm learning programming right now, with C++ as a first language, and only have a basic grasp of the language's features. Thanks for the help.

    From stackoverflow
    • You should not use sizeof(originalarray)/sizeof(int) like that. It'll only work for statically declared arrays (the size is known at compile time). You have to pass the size along with it. Why don't you just make a vector out of the array and pass it instead?

      Side Note: As a rule of thumb, always note that sizeof will be translated at compile time. So there's no way it could know the size of the array passed as an argument.

      Hooked : I don't know what you mean by that. Should I just std::copy all the elements into a vector and pass that? How do you use sizeof() with a vector?
      Mehrdad Afshari : You don't use sizeof on vector. v.size() will get the size. You should either do that, or if you want to pass an array, pass the size as another parameter.
      • When you pass arrays to functions, they decay to pointers to the first element of the array, the notation notwithstanding. So, your sizeof doesnot work as expected.

      • When you pass in an array, it is best to pass in the array size, so that you know where to stop. Add it as an additional parameter.

    • I see you include <vector>. I suggest you do away with all uses of arrays and only use the vector class. You can see examples of how to use STL containers such as vector here.

      Dan : I strongly concur.
    • Jut to extend this a bit, remember that C++ arrays are exactly C arrays. So all you have is the address of a piece of memory that purports (with no guarantees) to be an array of somethings.

      Update

      Okay, we'll expand a little more.

      C (and therefore C++) doesn't really have "arrays" as such. All it has are addresses, pointers. So when you make something an "array", what really happens is you tell the compiler that some variable represents an address.

      It's useful to make a distinction in C between a declaration and a definition. In a declaration, you're simply giving something a name and a type; in a definition, you actually allocate space.

      So, if we start off by definiing an array like

      int ar[100];
      

      that means we're telling the compiler we want space for 100 int's, we want it to all be allocated in one chunk, and we're going to use the name ar for it. The sizeof operator gives the number of bytes used by a type or an object, so our array ar will take up 100×sizeof(int) bytes. On most machines, that will be 400 bytes, but it varies from machine to machine.

      If we define a variable

      int * ar_p;   // using '_p' as a reminder this is a pointer
      

      we're defining space for a variable that will contain an address. Its size will be sizeof(int*), which will usually be either 4 or 8, but on some machines could be anything from 2 to 16 on some machines you're unlikely to run into soon.

      The name of the array is `ar. The compiler converts that name into an address, so we can save that address with

      ar_p = ar ;
      

      Now, let's say for convenience that our array ar happened to be starting at location 1000 in memory.

      That name ar` does not have any space allocated to it; it's like a constant, a number. So, you can't reverse that assignment

      ap = ar_p ;     // THIS WON'T WORK
      

      for the same reason you couldn't say

      1000 = ar_p ;   // THIS WON'T WORK EITHER
      

      ie, you can't change the value of 1000. (Back in early versions of FORTRAN, this trick would work, for complicated reasons. It was a mistake. You've never lived until you've tried to debug a program in which the value of "2" is 3.)

      Arrays in C are always zero-based, that is, the first index is always zero. Any other indices are just addresses computed using the index. So, ar[0] is just the address 1000 plus 0 bytes of offset, or 1000. ar[1] is 1000 plus 1 times the size of an int, so the next int over. And in fact, this is always true in C.

      This is called an array reference.

      When we use the syntax *ar_p we're telling the compiler to get the thing AT the address contained in ar_p. `.

      This is called dereferencing a pointer.

      If we say

      ar_p = ar;
      

      then *ar_p and ar[0] refer to the same thing.

      When we say ar[0] we're telling the compiler we want the thing at the address 0 bytes from ar. ar[1] is the address one int, or 4 bytes, from ar. So, *(ar_p+3) refers to the same thing as ar[3]. (We need the parentheses because we want to add 3 to the address first and then look at the contents. *ar_p+3 would get the contents pointed to by ap_p first, and then add 3 to those.

      The thing is, C doesn't know, or much care, how big the array really is. If I come along and do ar[365], the compiler will happily generate code to look in the cell 1000+(365×sizeof(int)). If that's in your array, fine, but if it's just random memory, that's fine too. C doesn't care.

      (Remember C comes from the phone company. "We don't care; we don't have to. We're the Phone Company.")

      So, now, we know some rules, which I've moved down here. Read "≡" as "is equivalent to" or "is the same as".

      What you can depend on:

      • foo(TYPE t[])foo(TYPE * t)

      Since C doesn't know a difference between pointers and arrays, you can declare either one. When you define a function, you can write

      void foo(int[] ar){
      

      or

      void foo(int* ar){
      

      and get exactly the same effect.

      • t[i]*(t+i)

      This was above. Anywhere you might write ar[i], you can replace it with *(ar+i). (There's actually a weird side case that breaks this, but you won't run into it as a beginner.)

      • where TYPE *t, (t+i) will equal the address at t plus i*sizeof(TYPE)

      Explained this above as well. When you index into an array, like ar[42], it means you want the 42nd whatever over from the start address. So, if you're using int, then you need to move over 42 times however wide an int is, which is to say sizeof(int).

      Now, that's all C, and since C++ is defined as a "kind of" C, it all holds for C++ as well. EXCEPT

      • unless TYPE is a user defined type that overloads operator[] and operator*.

      in C++, you can decide you want to define a new type that acts just like any other type, but you can change the way the language does specific things. So, a programmer can decide to "overload" -- ie, replace -- the default behavior of the array reference and pointer dereference operators with something of their own devising. As a beginner, you shouldn't be confronted with that soon, but you should be aware of it.

      Hooked : I think you overestimate my knowledge, because I have know idea what you just said. I'm currently learning programming right now, and am not onto pointers or the OOP parts of C++ yet.
      Charlie Martin : Ah. Okay, I'll add some.
      AlexW : That's a really good breakdown of arrays in C++. I'm glad I use .NET/Java! :)
      Charlie Martin : Thanks for the kind words, Alex, but actually understanding this would make a big difference to your understanding of Java/C# as well. For example, what to you get when you say Object a = new Object(); in Java. What is 'a' really?
    • In addition to all the answers above, you might also want to check out the Q&As on arrays from c-faq.com: http://c-faq.com/aryptr/index.html

    • Unfortunately, it's very hard to do exactly what you want to do in C or C++. You can pass around a fixed-size array like this:

      int mergeSort(int originalarray[20])
      {
          // do something
      }
      

      However, your array's size is not defined by a number, it's defined by the number of elements in initialization list.

      The thing to do in your case (even though it's really a wrong thing to do) is to do it in two steps:

      int originalarray[] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
      const size_t arraySize = sizeof originalarray / sizeof originalarray[0];
      int mergeSort(int array[arraySize])
      {
          // do something
      }
      

      Too bad it will not do what you need done: passing the array to a function like this makes a copy of the array, and the point of sorting would be to change the original array.

      In truth, you cannot go any further without understanding the concept of "pointer".

      The function you need to develop really should be like this:

      int originalarray[] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
      const size_t arraySize = sizeof originalarray / sizeof originalarray[0];
      
      int mergeSort(int *array, const size_t size)
      {
          // do something
      }
      
      mergeSort(&(originalArray[0]), arraySize);
      

      In other words, you pass a pointer to first element, and the number of elements.

      Alternatively, you can deal with vectors. Vector encapsulates the same two things (pointer to first element and size) in a single entity called "object". Plus, it manages memory for you, so you can extend the number of elements as you need. This is the C++ way. Too bad you can't initialize a vector with {...} like you can an array.

    • Looks like you're using both dynamically allocated arrays and vectors, when I believe just using std::vector will be enough.

      First, let your input array be changed to a std::vector, and fill it with your input data.

      int main()
      {
         std::vector<int> originalarray;
         for (int data = 1; data <= 10; data++)
         {
            originalarray.push_back(data);
         }
         mergeSort(originaldata);
      }
      

      Now it's important to declare your mergesort function to take a reference to a std::vector.

      int mergeSort(std::vector<int>& originalarray)
      {
         // The rest of your code, note that now you are passing 
         // in your array for sorting, so you can continue with your code to split
         // the vector into farray and sarray
      
         // then call sort on your halves.
         mergeSort(farray);
         mergeSort(sarray);
      
         // I'm guessing at this point you'd write code to combine your farray sarray, and
         // put it back into originalarray...don't forget to clear original array first!
      }
      

      Just a note, looks like you're not doing an inplace sort, so expect your sort to take a while since you're copying out a lot of data.