Rectangle 27 45

Making your own itoa is also easy, try this :

char* itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char* p = b;
    if(i<0){
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

or use the standard sprintf() function.

To clarify: do while loops are used instead of while for when i is zero.

There's a bug in this code: it will fail when i = INT_MIN because of the i *= -1 line.

@Max, while tests the condition before the loop start, do while tests the condition after the loop has started.

@kasrak How to deal with that case. Is a larger type the only option?

How to convert integer to string in C? - Stack Overflow

c string integer type-conversion
Rectangle 27 38

That's because itoa isn't a standard function. Try snprintf instead.

char str[LEN];
snprintf(str, LEN, "%d", 42);
LEN
(CHAR_BIT * sizeof(int) - 1) / 3 + 2

you don't have to - 1 for snprintf.

snprintf() is safer in that you specify how much input you're taking. Otherwise, If your string has multi-byte characters, or ends up longer than you expected due to large numbers, you can overflow your buffer and crash your program (etc).

How to convert integer to string in C? - Stack Overflow

c string integer type-conversion
Rectangle 27 12

Yes, but you can't specify the base with std::to_string like you can with itoa

c++ - Error:‘itoa’ was not declared in this scope - Stack Overflow

c++
Rectangle 27 44

itoa was a non-standard helper function designed to complement the atoi standard function, and probably hiding a sprintf (Most its features can be implemented in terms of sprintf): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html

Despite the fact some functions are not in the standard, as rightly mentioned by "onebyone" in one of his comments, most compiler will offer you an alternative (e.g. Visual C++ has its own _snprintf you can typedef to snprintf if you need it).

Use the C++ streams (in the current case std::stringstream (or even the deprecated std::strstream, as proposed by Herb Sutter in one of his books, because it's somewhat faster).

You're in C++, which means that you can choose the way you want it:

@Chris Kaminski: My one tests did show the sprintf was a 5 to ten times faster, which is confirmed my Herb Sutter's own measurements. if you have tests with different results, I'm interested.

@Chris Kaminski: If you study the c++ stream's interface, you'll understand why they are slower, even when output a simple integer: In C, you use your own buffer, possibly allocated in the stack, whereas in C++, the stringstream will use its own. In C, you can then reuse your buffer. In C++, you must extract the string from the stringstream, which is a std::string copy.

@fuzzyTew : Thanks for your concern, but I guess I'm familiar enough with both C API and C++ API to handle sprintf, and know when (and how) to use it safely, and when NOT to use it at all... :-D

@fuzzyTew: 1 In my post, I spoke about sprintf and its secure variants, not only sprintf. 2 Knowing where your code is compiled is not an impossible task (in my case, at worst, Windows/VC++, Solaris/CC and Linux/g++, at best, Windows/VC++ only). 3 You are describing a world where saboteurs trying to crash your code are the norm. My world is composed by normal developers, so losing time trying to protect my code from saboteurs by rewriting my "secure" version of every API is not productive. [...]

@fuzzyTew: [...] Conclusion Use the best tool at hand. And if the best tool is a sprintf hidden inside a wrapper class or function... Now, if you advocate the rewriting of sprintf as an answer for this question, feel free to write your own answer. I'm not sure the question author reads all the comments.

Alternative to itoa() for converting integer to string C++? - Stack Ov...

c++ integer stdstring itoa
Rectangle 27 44

itoa was a non-standard helper function designed to complement the atoi standard function, and probably hiding a sprintf (Most its features can be implemented in terms of sprintf): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html

Despite the fact some functions are not in the standard, as rightly mentioned by "onebyone" in one of his comments, most compiler will offer you an alternative (e.g. Visual C++ has its own _snprintf you can typedef to snprintf if you need it).

Use the C++ streams (in the current case std::stringstream (or even the deprecated std::strstream, as proposed by Herb Sutter in one of his books, because it's somewhat faster).

You're in C++, which means that you can choose the way you want it:

@Chris Kaminski: My one tests did show the sprintf was a 5 to ten times faster, which is confirmed my Herb Sutter's own measurements. if you have tests with different results, I'm interested.

@Chris Kaminski: If you study the c++ stream's interface, you'll understand why they are slower, even when output a simple integer: In C, you use your own buffer, possibly allocated in the stack, whereas in C++, the stringstream will use its own. In C, you can then reuse your buffer. In C++, you must extract the string from the stringstream, which is a std::string copy.

@fuzzyTew : Thanks for your concern, but I guess I'm familiar enough with both C API and C++ API to handle sprintf, and know when (and how) to use it safely, and when NOT to use it at all... :-D

@fuzzyTew: 1 In my post, I spoke about sprintf and its secure variants, not only sprintf. 2 Knowing where your code is compiled is not an impossible task (in my case, at worst, Windows/VC++, Solaris/CC and Linux/g++, at best, Windows/VC++ only). 3 You are describing a world where saboteurs trying to crash your code are the norm. My world is composed by normal developers, so losing time trying to protect my code from saboteurs by rewriting my "secure" version of every API is not productive. [...]

@fuzzyTew: [...] Conclusion Use the best tool at hand. And if the best tool is a sprintf hidden inside a wrapper class or function... Now, if you advocate the rewriting of sprintf as an answer for this question, feel free to write your own answer. I'm not sure the question author reads all the comments.

Alternative to itoa() for converting integer to string C++? - Stack Ov...

c++ integer stdstring itoa
Rectangle 27 38

Wakes up all waiters whenever the lock becomes available

Here's pseudo-code for a ver simply reader/writer lock using a mutex and a condition variable. The mutex API should be self-explanatory. Condition variables are assumed to have a member wait(Mutex&) which (atomically!) drops the mutex and waits for the condition to be signaled. The condition is signaled with either signal() which wakes up one waiter, or signal_all() which wakes up all waiters.

read_lock() {
  mutex.lock();
  while (writer)
    unlocked.wait(mutex);
  readers++;
  mutex.unlock();
}

read_unlock() {
  mutex.lock();
  readers--;
  if (readers == 0)
    unlocked.signal_all();
  mutex.unlock();
}

write_lock() {
  mutex.lock();
  while (writer || (readers > 0))
    unlocked.wait(mutex);
  writer = true;
  mutex.unlock();
}

write_unlock() {
  mutex.lock();
  writer = false;
  unlocked.signal_all();
  mutex.unlock();
}

If most of the waiters are waiting for a write lock, this is wastefull - most waiters will fail to acquire the lock, after all, and resume waiting. Simply using signal() doesn't work, because you do want to wake up everyone waiting for a read lock unlocking. So to fix that, you need separate condition variables for readability and writability.

You can fix that by tracking the number of pending read and write locks, and either stop acquiring read locks once there a pending write locks (though you'll then starve readers!), or randomly waking up either all readers or one writer (assuming you use separate condition variable, see section above).

To guarantee this, you'll need a real wait queue. You could e.g. create one condition variable for each waiter, and signal all readers or a single writer, both at the head of the queue, after releasing the lock.

This one is hard to fix. One way is to use atomic instructions to acquire read or write locks (usually compare-and-exchange). If the acquisition fails because the lock is taken, you'll have to fall back to the mutex. Doing that correctly is quite hard, though. Plus, there'll still be contention - atomic instructions are far from free, especially on machines with lots of cores.

Implementing synchronization primitives correctly is hard. Implementing efficient and fair synchronization primitives is even harder. And it hardly ever pays off. pthreads on linux, e.g. contains a reader/writer lock which uses a combination of futexes and atomic instructions, and which thus probably outperforms anything you can come up with in a few days of work.

That last drawback you mentioned - contention between readers - was the one I was really trying to deal with. I ended up with an implementation that worked in every specific test case I ran it in but failed randomized sequences of locking. At that point I gave up and simply used boost::shared_lock. :(

c++ - How would you implement your own reader/writer lock in C++11? - ...

c++ multithreading c++11 locking readwritelock
Rectangle 27 5

cd is not a program, it's a built-in command. The built-in command are directly built into the shell.

cd
chdir()
  • Update some environment variables (like Klas Lindback said: OLDPWD and PWD)

The check for existence is unnecessary, chdir fails in that case. (And it's useless, too, the directory could exist while stating and be deleted before the chdir call.)

I suggest emphasizing that cd cannot be implemented as a program. Similar questions came up a few times during the last weeks and often people aren't aware that a process cannot change its parent's environment.

c - How to implement your own cd command in your own shell - Stack Ove...

c linux shell cd pwd
Rectangle 27 5

//
// Multi-reader Single-writer concurrency base class for Win32
//
// (c) 1999-2003 by Glenn Slayden (glenn@glennslayden.com)
//
//


#include "windows.h"

class MultiReaderSingleWriter
{
private:
    CRITICAL_SECTION m_csWrite;
    CRITICAL_SECTION m_csReaderCount;
    long m_cReaders;
    HANDLE m_hevReadersCleared;

public:
    MultiReaderSingleWriter()
    {
        m_cReaders = 0;
        InitializeCriticalSection(&m_csWrite);
        InitializeCriticalSection(&m_csReaderCount);
        m_hevReadersCleared = CreateEvent(NULL,TRUE,TRUE,NULL);
    }

    ~MultiReaderSingleWriter()
    {
        WaitForSingleObject(m_hevReadersCleared,INFINITE);
        CloseHandle(m_hevReadersCleared);
        DeleteCriticalSection(&m_csWrite);
        DeleteCriticalSection(&m_csReaderCount);
    }


    void EnterReader(void)
    {
        EnterCriticalSection(&m_csWrite);
        EnterCriticalSection(&m_csReaderCount);
        if (++m_cReaders == 1)
            ResetEvent(m_hevReadersCleared);
        LeaveCriticalSection(&m_csReaderCount);
        LeaveCriticalSection(&m_csWrite);
    }

    void LeaveReader(void)
    {
        EnterCriticalSection(&m_csReaderCount);
        if (--m_cReaders == 0)
            SetEvent(m_hevReadersCleared);
        LeaveCriticalSection(&m_csReaderCount);
    }

    void EnterWriter(void)
    {
        EnterCriticalSection(&m_csWrite);
        WaitForSingleObject(m_hevReadersCleared,INFINITE);
    }

    void LeaveWriter(void)
    {
        LeaveCriticalSection(&m_csWrite);
    }
};

I didn't have a chance to try it, but the code looks OK.

Thanks, this seem to be good. And it includes a trivial method to promote a reader to a writer, which is often a nice to have feature

c++ - How would you implement your own reader/writer lock in C++11? - ...

c++ multithreading c++11 locking readwritelock
Rectangle 27 5

Apart from the ugly query string, your at risk that you will exceed the query string limits, particularly if your messages are long and you add further properties to Error.

One option would be to persist the Error to a TempData property, then return RedirectToAction("Index", "Error") and in the Index() method get the value from TempData and render the view.

[HandleError(ExceptionType = typeof(MyException), View = "MyError")]
[HandleError(ExceptionType = typeof(AnotherException), View = "AnotherError")]
public class BaseController : Controller
{
}

and in the /Views/Shared folder, add specific error views (MyError.cshtml)

@model System.Web.Mvc.HandleErrorInfo
....
@Model.Exception.Message // display error message
...

Note HandleErrorInfo gives you access to the controller and action names as well as the exception details.

Then, in a specific method, if you throw an exception, the associated view will be displayed

public class MyController : BaseController
{
  public ActionResult SomeAction()
  {
    if(someCondition)
    {
      throw new MyException("Some friendly error message");
    }
    return View();
  }
}

Where MyException is an inbuilt exception, or you own custom exception that derives from Exception

Note you also need to set the following in web.config

<system.web>
  <customErrors mode="On" defaultRedirect="Error" />
</system.web>

How to implement your own error view in ASP.NET MVC - Stack Overflow

asp.net-mvc error-handling
Rectangle 27 2

I did this once before in a Django server. There's two parts - client-side and server-side.

Client side you will have to send out XmlHttpRequests to the server as the user is typing, and then when the information comes back, display it. This part will require a decent amount of javascript, including some tricky parts like callbacks and keypress handlers.

Server side you will have to handle the XmlHttpRequests which will be something that contains what the user has typed so far. Like a url of

www.yoursite.com/suggest?typed=www.sta

and then respond with the suggestions encoded in some way. (I'd recommend JSON-encoding the suggestions.) You also have to actually get the suggestions from your database, this could be just a simple SQL call or something else depending on your framework.

But the server-side part is pretty simple. The client-side part is trickier, I think. I found this article helpful

He's writing things in php, but the client side work is pretty much the same. In particular you might find his CSS helpful.

autocomplete - How to implement Google Suggest in your own web applica...

python autocomplete autosuggest
Rectangle 27 1

Is there any need for redirect to special error action while you are filling Error class in each action and will have the same view ? You may just do the following:

try{
   DoSomeStuff();
}
except (Exception e)
{
    Error error = new Error { UserFriendlyText = "The friendly message", ErrorDescription = "Error to be logged" };
    return View("Error", error);  //error view
}
return View(); //Default way

For ourself we have choosen another approach to show errors. There is no special view to show error. In this case user will loose context where error happened. Instead of special view we created the following structure.

  • We have BaseController with couple of useful functions: protected void AddErrorMessage(String errorMessage) { var errorMessages = TempData["ErrorMessages"] as List<String>; if (errorMessages == null) errorMessages = new List<String>(); errorMessages.Add(errorMessage); TempData["ErrorMessages"] = errorMessages; } protected void AddSuccessMessage(String successMessage) { var successMessages = TempData["SuccessMessages"] as List<String>; if (successMessages == null) successMessages = new List<String>(); successMessages.Add(successMessage); TempData["SuccessMessages"] = successMessages; } protected void AddWarningMessage(String warningMessage) { var warningMessages = TempData["WarningMessages"] as List<String>; if (warningMessages == null) warningMessages = new List<String>(); warningMessages.Add(warningMessage); TempData["WarningMessages"] = warningMessages; }
  • We have modified _Layout to display those messages: @if (@TempData.ContainsKey("ErrorMessages")) { foreach (var errorMessage in TempData["ErrorMessages"] as List<String>) { <div class="alert alert-error"> <button type="button" class="close" data-dismiss="alert"></button> @(new HtmlString(errorMessage)) </div> } } //The same stuff for warnings and messages

And in the controller we are using it as follows:

if (!ModelState.IsValid)
{

    this.AddErrorMessage("Something wrong with your model");

    return View(customer);

}

We just return the same view, but with additional messages. So customer may check problem or see some warning/information message without loosing context.

Also a nice approach. I just try to avoid using Tempdata or Viewbag as much as I can

How to implement your own error view in ASP.NET MVC - Stack Overflow

asp.net-mvc error-handling
Rectangle 27 1

One of the reasons I don't like using RedirectToAction for error handling is that it changes the url of the page you're browsing, which is not the best user experience.

The simplest way would be to move your Error.cshtml into the /Views/Shared folder and make sure that file doesn't exist in the Controller throwing the error. Then you can just do this:

Error error = new Error { UserFriendlyText = "The friendly message", ErrorDescription = "Error to be logged" };
return RedirectToAction("Error", new System.Web.Routing.RouteValueDictionary(error));

By default MVC convention, it will search for the Error.cshtml file in the "Controller" directory, and upon not finding it then search in the Shared directory.

If you ever need to customize the error page for that controller, you would just create a new Error.cshtml page inside the Controller needing the custom error.

How to implement your own error view in ASP.NET MVC - Stack Overflow

asp.net-mvc error-handling
Rectangle 27 1

Obviously this does nothing to help you out in getting the data - but it looks like you have your own source and arent actually looking to get data from Google.

autocomplete - How to implement Google Suggest in your own web applica...

python autocomplete autosuggest
Rectangle 27 0

That's because itoa isn't a standard function. Try snprintf instead.

char str[LEN];
snprintf(str, LEN, "%d", 42);
LEN
(CHAR_BIT * sizeof(int) - 1) / 3 + 2

you don't have to - 1 for snprintf.

snprintf() is safer in that you specify how much input you're taking. Otherwise, If your string has multi-byte characters, or ends up longer than you expected due to large numbers, you can overflow your buffer and crash your program (etc).

How to convert integer to string in C? - Stack Overflow

c string integer type-conversion
Rectangle 27 0

In my project I have used chdir() to implement my cd command and it works. Every process has its own PWD(Present Working Directory). A shell is also a process and its default PWD is the PWD of its parent (bash shell where I have executed ./my_sh).

For future reference, I have posted all the detailed explanation of the project in the following link :

c - How to implement your own cd command in your own shell - Stack Ove...

c linux shell cd pwd
Rectangle 27 0

Your platform doesn't have itoa. It's not specified by any standard. You can use any replacement you like, including printf or just writing your own.

c++ - itoa to std::to_string - Stack Overflow

c++ tostring itoa