CultureInfo with fallback routing to another language Our company needs a localization/translation behavior which allows incomplete (ResX) resources.
If a String

isn't available in italian
fall back to the next roman language, like french
fall back to our invariant (in this case: german)

The easiest approach was a custom CultureInfo.

/// <summary>
/// A <see cref="CultureInfo" /> which switches to another language instead of  <see cref="CultureInfo.InvariantCulture" />.
/// </summary>
public class FallbackCultureInfo : CultureInfo
{
    private static readonly List<FallbackCultureInfo> CultureInfos = new List<FallbackCultureInfo>();
    private readonly CultureInfo fallback;
    private CultureInfo determinedParent;

    public override CultureInfo Parent
    {
        get
        {
            if (this.determinedParent != null)
            {
                return this.determinedParent;
            }

            var originalParent = base.Parent;
            if (Object.Equals(originalParent, CultureInfo.InvariantCulture) && (this.fallback != null))
            {
                return this.determinedParent = this.fallback;
            }

            if (this.fallback == null)
            {
                return this.determinedParent = originalParent;
            }

            this.determinedParent = FallbackCultureInfo.Build(originalParent.Name, this.fallback.Name);
            return this.determinedParent;
        }
    }

    private FallbackCultureInfo(String name, CultureInfo fallback = null) : base(name)
    {
        this.fallback = fallback;
    }

    /// <summary>
    /// Builds a <see cref="CultureInfo"/> with a custom fallback behavior, which switsches to
    /// another language before it gets <see cref="CultureInfo.InvariantCulture"/>.
    /// </summary>
    /// <example>
    /// CultureInfo.CurrentUICulture = FallbackCultureInfo.Build("it-CH", "fr-CH", "de-CH");
    /// </example>
    /// <remarks>
    /// Due to a missing <see cref="CultureInfo" />.operator== we have to ensure a unique instance per name on our own.
    /// </remarks>
    /// <param name="name">Name of our culture, like "en-US"</param>
    /// <param name="fallbacks">Fallback stack, like "en-GB", "fr-FR"</param>
    /// <returns>The build <see cref="CultureInfo"/>.</returns>
    public static FallbackCultureInfo Build(String name, params String[] fallbacks)
    {
        lock (FallbackCultureInfo.CultureInfos)
        {
            return FallbackCultureInfo.QueuedBuild(new[] { name }.Concat(fallbacks).Reverse());
        }
    }

    private static FallbackCultureInfo QueuedBuild(IEnumerable<String> names)
    {
        FallbackCultureInfo result = null;
        FallbackCultureInfo lastFallback = null;
        foreach (var name in names)
        {
            result = FallbackCultureInfo.CultureInfos.FirstOrDefault(ci => String.Equals(ci.Name, name));
            if (result != null)
            {
                lastFallback = result;
                continue;
            }

            result = lastFallback = new FallbackCultureInfo(name, lastFallback);
            FallbackCultureInfo.CultureInfos.Add(result);
        }

        return result;
    }
}

CultureInfo.CurrentUICulture = FallbackCultureInfo.Build("it-CH", "fr-CH", "de-CH");

Works like a charm at a first glance.

But because it is located at a general .Net position, I would like to ask for other opinions about this way to solve the problem. Has anyone done a similiar approach which failed somehow - or even if you havent - do so see any issues with it?

Bugs

So, some interesting bugs. If I specify two cultures that have the same invariant, but are different versions it creates really unpleasant circumstances. (Infinite loops, anyone?)

var cultureInfo2 = FallbackCultureInfo.Build("en-GB", "en-US", "fr-CH");

That creates an infinite loop when rooting through the parent.
 So does:

var cultureInfo2 = FallbackCultureInfo.Build("en-GB", "fr-CH", "fr-FR", "de-CH");

Why does this matter? I could see a very real use case being:

cultureInfo = FallbackCultureInfo.Build("en-AU", "en-GB", "en-US");

(Use the Australian English culture, if you can't find it there use Great Britain English culture, if you can't find it there use the United States English culture.) Though, using the neutral (en) as the second in line may very well solve that problem with most strings, but it's still a possibility that this chain could be used and is now broken.

Of course, it's not consistent because of your static member there.

var cultureInfo = new System.Globalization.CultureInfo("en-GB");
cultureInfo = FallbackCultureInfo.Build("it-CH", "fr-CH", "de-CH");
cultureInfo = FallbackCultureInfo.Build("en-GB", "fr-FR", "de-CH");

When looking through all the parents of that second culture set, I don't get the correct tree.

en-GB
en
fr-CH
fr
de-CH
de

But I specified fr-FR for the second fallback!?!?!?!

Of course, we can get even more interesting results with a few other options:

cultureInfo = FallbackCultureInfo.Build("it-CH", "fr-CH", "de-CH");
cultureInfo = FallbackCultureInfo.Build("fr-CH", "it-CH", "de-CH");

fr-CH
fr
de-CH
de

Wait, what? Where did it-CH go?

cultureInfo = FallbackCultureInfo.Build("it-CH", "fr-CH", "de-CH");
cultureInfo = FallbackCultureInfo.Build("fr-CH");

fr-CH
fr
de-CH
de

Ah, I guess I really did need de-CH after all.

While both of these bugs are pretty major, for your situation they're really not something you would look for. You are specifically switching between languages that have different parents, and you're only creating one FallbackCultureInfo. (Which is probably the most likely scenario.)

Review

In C# we prefer the string alias instead of the String type.

Other than that, I have no real issues with the structure of your code, but I do have an issue with how you solved the problem.

Alternate Implementation

From what understand of the documentation, you should be able to get away with making this a lot simpler:

  The cultures have a hierarchy in which the parent of a specific culture is a neutral culture, the parent of a neutral culture is the InvariantCulture, and the parent of the InvariantCulture is the invariant culture itself. The parent culture encompasses only the set of information that is common among its children.

  If the resources for the specific culture are not available in the system, the resources for the neutral culture are used. If the resources for the neutral culture are not available, the resources embedded in the main assembly are used. For more information on the resource fallback process, see Packaging and Deploying Resources in Desktop Apps.

Basically, you should be able to just work with the Parent property and build from there.

public class NewFallbackCultureInfo : CultureInfo
{
    public NewFallbackCultureInfo FallbackCulture { get; }

    public NewFallbackCultureInfo(string name, params string[] names)
        : base(name)
    {
        if (names.Length > 0)
        {
            FallbackCulture = new NewFallbackCultureInfo(this, names);
        }
    }

    private NewFallbackCultureInfo(CultureInfo sourceCulture, params string[] names)
        : base(sourceCulture.Parent.Name)
    {
        var newNames = new string[names.Length - 1];

        for (int i = 1; i < names.Length; i++)
        {
            newNames[i - 1] = names[i];
        }

        FallbackCulture = new NewFallbackCultureInfo(names[0], newNames);
    }

    public override CultureInfo Parent => FallbackCulture ?? base.Parent;
}

Note that we also built this without the .Build pattern, and relied instead on constructors. It's more natural this way, and preserves the original CultureInfo usage.

The only downside I see is that the original parent chain may not be preserved, if it goes more than one level.

We can fix that by modifying our private constructor:

private NewFallbackCultureInfo(CultureInfo sourceCulture, params string[] names)
    : base(sourceCulture.Parent.Name)
{
    if (string.IsNullOrEmpty(base.Parent.Name))
    {
        var newNames = new string[names.Length - 1];

        for (int i = 1; i < names.Length; i++)
        {
            newNames[i - 1] = names[i];
        }

        FallbackCulture = new NewFallbackCultureInfo(names[0], newNames);
    }
    else
    {
        FallbackCulture = new NewFallbackCultureInfo(this, names);
    }
}

When tracing the Parent chain, I found that the chain produced by my version is identical to the chain produced by your version, except it doesn't break when tested against the criteria that broke your version.

I apologize if this felt brutal, but I was actually having a bit of fun with it after I realized what was happening.


Counting the occurrence of each letter in a string This function counts the number of times each letter appears in a string, then display the one that appears the most, and the number of times it appears. If there's a tie, it shows all of them, like "bz,5".

I've got the feeling this could be done much better. Suggestions?

private static void LinqTest()
{
    const string testString = "abbsabwertbfacsfgggdfgascd";
    var count = 0;

    var charGroups = (from c in testString
                      group c by c into g
                      select new
                      {
                          c = g.Key,
                          count = g.Count(),
                      }).OrderByDescending(c => c.count);
    foreach (var @group in charGroups.Where(@group => count <= @group.count))
    {
        Console.WriteLine(@group.c + ": " + @group.count);
        count = @group.count;
    }
}

The trick is to group by the character, as you are doing, then do a second grouping by the count:

var testString = "abbsabwertbfacsfgggdfgasc";

var characterCounts =
    from character in testString
    group character by character into characterGroup
    group characterGroup.Key by characterGroup.Count() into countedCharacterGroup
    orderby countedCharacterGroup.Key descending
    select new
    {
        Characters = new string(countedCharacterGroup.ToArray()),
        Count = countedCharacterGroup.Key
    };

var topCharacterCount = characterCounts.First();

Console.WriteLine("{0},{1}", topCharacterCount.Characters, topCharacterCount.Count);

Breakdown

First, we do the same initial grouping:

from character in testString
group character by character into characterGroup

Next, we group the characters by the number of times they appear:

group characterGroup.Key by characterGroup.Count() into countedCharacterGroup

Then, we order based on the character counts:

orderby countedCharacterGroup.Key descending

Finally, we create a string for each set of characters with the same count:

select new
{
    Characters = new string(countedCharacterGroup.ToArray()),
    Count = countedCharacterGroup.Key
}

We can also get rid of the loop, instead grabbing the top count and writing the joined character string:

var topCharacterCount = characterCounts.First();

Console.WriteLine("{0},{1}", topCharacterCount.Characters, topCharacterCount.Count);


A lightning-fast StringBuilder In the process of trying to build a serializable data structure, I found myself building large strings, which gets very slow because VBA copies a string every time concatenation is performed.

To alleviate this, referring to Dynamic Array and Java's StringBuilder interface, I cobbled together a unicode clsStringBuilder class.

This isn't a very big chunk of code, but I'd be interested in any advice about edge cases that I maybe haven't considered, unexpected copying behavior that VBA might be performing "behind my back" which I could avoid, or corrections to coding style (or lack thereof).

Option Compare Database
Option Explicit

'******
'* v2 *
'******

Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByVal dst As Long, ByVal src As Long, ByVal Length As Long)

Private Const DEFAULT_CAPACITY As Long = &H10
Private m_currLen As Long
Private m_stringBuffer() As Byte

Private Sub Class_Initialize()
    ReDim m_stringBuffer(0 To (DEFAULT_CAPACITY * 2) - 1) 'Each unicode character is 2 bytes
End Sub

Public Function Append(strString As String) As clsStringBuilder
On Error GoTo derp

    If m_currLen + LenB(strString) < UBound(m_stringBuffer) Then
        CopyMemory VarPtr(m_stringBuffer(m_currLen)), StrPtr(strString), LenB(strString)
    Else
        If m_currLen + LenB(strString) < UBound(m_stringBuffer) * 2 Then
            Expand
        Else
            Expand m_currLen + LenB(strString)
        End If
        CopyMemory VarPtr(m_stringBuffer(m_currLen)), StrPtr(strString), LenB(strString)
    End If
    m_currLen = m_currLen + LenB(strString)
    Set Append = Me
    Exit Function

derp:
    Stop
    Resume
End Function

Public Property Get Length() As Long
    Length = m_currLen / 2
End Property

Public Property Get Capacity() As Long
    Capacity = UBound(m_stringBuffer)
End Property

Private Sub Expand(Optional newSize As Long = 0)
    If newSize <> 0 Then
        ReDim Preserve m_stringBuffer(0 To newSize - 1)
    Else
        ReDim Preserve m_stringBuffer(0 To (UBound(m_stringBuffer) * 2) + 1)
    End If
End Sub

Public Function toString() As String
    toString = Mid(m_stringBuffer, 1, m_currLen / 2)
End Function

Here is a test:

Public Sub Main()
    Dim sb As clsStringBuilder
    Set sb = New clsStringBuilder
    Dim strString As String
    Dim i As Long
    Dim StartTime As Double

    'VBA String
    StartTime = MicroTimer()
    For i = 0 To 100000
        strString = strString + "Hello World;"
    Next
    Debug.Print "The VBA String took: " & Round(MicroTimer - StartTime, 3) & " seconds"

    'StringBuilder
    StartTime = MicroTimer()
    For i = 0 To 100000
        sb.Append "Hello World;"
    Next
    Debug.Print "The Stringbuilder took: " & Round(MicroTimer - StartTime, 3) & " seconds"

    'Are the strings the same?
    Debug.Print StrComp(strString, sb.toString, vbBinaryCompare)
End Sub

Here is Microsoft's MicroTimer function, which can be found here:

Private Declare Function getFrequency Lib "kernel32" _
Alias "QueryPerformanceFrequency" (cyFrequency As Currency) As Long
Private Declare Function getTickCount Lib "kernel32" _
Alias "QueryPerformanceCounter" (cyTickCount As Currency) As Long
Function MicroTimer() As Double
'

' Returns seconds.
    Dim cyTicks1 As Currency
    Static cyFrequency As Currency
    '
    MicroTimer = 0

' Get frequency.
    If cyFrequency = 0 Then getFrequency cyFrequency

' Get ticks.
    getTickCount cyTicks1

' Seconds
    If cyFrequency Then MicroTimer = cyTicks1 / cyFrequency
End Function

I like this, a lot. It's.. brilliant. Like .NET String objects, VBA strings are immutable, which means like in .NET, when "the quick brown fox" gets appended with "jumps over" and then "the lazy dog", it's 4 strings that have been generated, and thus the first one got copied 3 times; a VBA StringBuilder class is therefore definitely welcome to any VBA toolkit!

This is some serious code you've got here. Let's take a look.

So you've called the class clsStringBuilder. I know where you're coming from, but there's no real reason for this "cls" Hungarian prefix - I'd remove it, and call the class StringBuilder.

'******
'* v2 *
'******

Don't bother with that. I know version control is natively near-impossible with VBA, but there is no need to "version" code in comments nonetheless; do you actually maintain the version number? Why bother? Just remove it, it's useless clutter.

Private Const DEFAULT_CAPACITY As Long = &H10

Why not 16? Hexadecimal 10 is 16 right? I think it would be clearer to use a decimal notation. Actually that capacity is potentially confusing, especially given the hex notation. Is &H10 the number of bytes? Characters?

ReDim m_stringBuffer(0 To (DEFAULT_CAPACITY * 2) - 1) 'Each unicode character is 2 bytes

Ah, characters then. How about calling the constant DEFAULT_CHARACTER_CAPACITY? Nah, too long.. and I personally don't like the YELLCASE, I'd just call it InitialCharacterCapacity, but I've seen other people use ALL CAPS for constants - as long as you're consistent, it works :)

BTW that's a good comment you have there, but I wouldn't bother specifying "unicode" characters; it gets confusing when the IDE itself only supports ANSI strings!

I don't like prefixes and abbreviated names, so m_currLen would become currentLength and m_stringBuffer would become stringBufffer, or just buffer.

Actually since currentLength is in bytes, I'd call it currentByteLength, so as to avoid question marks when it comes to this:

Public Property Get Length() As Long
    Length = m_currLen / 2
End Property

Public Function Append(strString As String) As clsStringBuilder

strString, really? I doesn't get any more Hungarian than that! Also you should know that parameters are passed ByRef by default - I'd change the signature to this:

Public Function Append(ByVal value As String) As StringBuilder

The error handling isn't optimal - if anything blows up, you're bringing up the IDE for the end user to scratch their head and debug your code! That's not production-ready:

derp:
    Stop
    Resume

"derp" means nothing to me - I like following a "template" like this:

Public Sub Foo()
    On Error GoTo CleanFail

    'implementation

CleanExit:
    Exit Sub

CleanFail:
    'handle error
    Resume CleanExit
End Sub

You might also want to make sure Expand doesn't actually shrink the buffer. I think. ;)

Lastly, I'm not sure I understand why toString isn't following the convention and named in PascalCase like every public method - ToString would be better-looking.

Good job!


Updating an incoming PUT query I have the following spaghetti update method and I would like to improve its coding style.

This takes an incoming PUT query for a survey object and updates it accordingly.

update: function(req, res) {
  var slug = req.body.slug
    , errors = {}
    , surveyDiff = req.body.diff;

  surveyDiff.slug = slug;

  // Certains fields are not supposed to be updated, therefore they need to be removed before performing the update.
  var forbiddenFields = [ 'telerivetId', 'telerivetProjectId',
                          'votoId', 'votoApiKey', 'campaign', 'country' ];

  forbiddenFields.forEach(function(forbiddenField) {
    if (surveyDiff.hasOwnProperty(forbiddenField))
      delete surveyDiff[forbiddenField];
  });

  if (Object.keys(surveyDiff).length > 1)
    // We need to verify that the user is logged and is the author of the current survey.
    Session.getUser(req.cookies.logged.token, function(err, user) {
      var updateSurvey = function(surveyDiff) {
        // Once all verifications are done, we can safely update the survey.
        Survey.update({ slug: slug, user: user.phoneNumber }, surveyDiff)
          .exec(function(err, surveys) {
            if (!err)
              res.json({ success: true, survey: surveys[0] });
            else
              res.json({ success: false });
          });
      };

      // The order property correspond to a parent model called SurveyGroup, therefore this one is updated separately
      if (!surveyDiff.hasOwnProperty('order'))
        updateSurvey(surveyDiff);

      else
        Survey.findOne({ slug: slug }).exec(function(err, survey) {
          SurveyGroup.update({ id: survey.surveyGroup }, { order: surveyDiff.order },
            function(err, surveyGroup) {
              console.log('update survey group', err, surveyGroup);
              delete surveyDiff.position;

              if (!err) updateSurvey(surveyDiff);
              else res.json({ success: false });
            });
        });
    });

  else res.json({ success: false });
}

This code is running on node.js using sails.js and waterline.js.

For the first part of your code, it could be refactored into the following for readability and "better" practice:

update: function(req, res) {

  // I usually recommend one var per variable to explicitly say "this is a variable"
  // as well as not fumble with commas. Commas have a lot of uses in JS. I'd
  // like to avoid confusion.

  // Arrays can be indented this way to make it look like a list. Additionally,
  // this is a "constant", so let's make it appear like so. And let's pull it up
  // the scope, away from the action, because it does no action.
  var FORBIDDEN_FIELDS = [
    'telerivetId',
    'telerivetProjectId',
    'votoId',
    'votoApiKey',
    'campaign',
    'country'
  ];

  var slug = req.body.slug;

  // Highly suggest you not modify objects you don't own, especially ones
  // generated by the system. That's because something else might be need them.
  //
  // Instead of stripping, why not create one that doesn't include forbidden
  var surveyDiff = Object.keys(req.body.diff).reduce(function(carry, key){
    if(!~FORBIDDEN_FIELDS.indexOf(key)) carry[key] = surveyDiff[key];
    return carry;
  }, {});

  // We can coerce a value to a boolean, and get rid of "> 1"
  // As a colleague would say "What is 1? Is that arbitrary? What does it mean?"
  var hasDiff = !!Object.keys(surveyDiff).length;

  return hasDiff ? update(slug, diff) : res.json({ success: false });

}

As for the second part, callbacks look fine. Though there is a way to prevent "callback hell" and that is to break away the callbacks as named functions, and let the operation refer to them by name. Something like

// Something like this:

function asyncRoutine(){
  db.findSomething({...}, function(err, data){
    db.findAnotherSomething({...}, function(err, data2){
      // data
    });
  });
}

// into something like this:

function asyncRoutine(){
  db.findSomething({...}, handleDbFind);
}

function handleDbFind(err, data){
  db.findAnotherSomething({...}, handleAnotherDbFind);
}

function handleAnotherDbFind(err, data){
  // done!
}

However, you lose the advantage of scopes (visibility of outer variables in nested callbacks). It also makes the code rather long, since you're splitting them up.


iOS Attributes in the data model I am working on a product-related app where the data model for a product attribute feels too heavy. But I can't split it into several small data models because they are all about goods.

At present, my approach is to parse network data directly into a data model. The properties of the data model are readwrite. For example, when I want to modify a property, I will directly modify it, without copying or reinitializing the new data model.
 I know there may be problems with this, but I don't have a better way, if you have, please help me.

ATProductModel.h

#import "ATBaseModel.h"

NS_ASSUME_NONNULL_BEGIN

typedef NS_ENUM(NSUInteger, ATFilterType) {
    ATFilterTypeComplex = 0,
    ATFilterTypeSales,
    ATFilterTypePrice,
    ATFilterTypeVoucher,
};

typedef NS_ENUM(NSUInteger, ATFilterLayoutType) {
    ATFilterLayoutTypeNone = 0,
    ATFilterLayoutTypeOneRows,
    ATFilterLayoutTypeMoreRows,
};

@interface ATProductSubModel : ATBaseModel

@property (copy, nonatomic) NSString *productId;
@property (copy, nonatomic) NSString *productURL;
@property (copy, nonatomic) NSString *productURLShort;
@property (copy, nonatomic) NSString *productIcon;
@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) NSString *voucher;
@property (copy, nonatomic) NSString *currentPrice;
@property (copy, nonatomic) NSString *price;
@property (copy, nonatomic) NSString *couponURL;
@property (copy, nonatomic) NSString *discountRate;
@property (copy, nonatomic) NSString *endTime;
@property (copy, nonatomic) NSString *couponInfo;
@property (copy, nonatomic) NSString *volume;
@property (copy, nonatomic) NSString *couponStartTime;
@property (copy, nonatomic) NSString *couponEndTime;
@property (copy, nonatomic) NSArray <NSString *>* smallImages;
@property (copy, nonatomic) NSString *shopName;
@property (copy, nonatomic) NSString *shopLogo;
@property (copy, nonatomic) NSString *platType;
@property (copy, nonatomic) NSString *shopScore;
@property (copy, nonatomic) NSString *share;
@property (copy, nonatomic) NSString *shareFee;
@property (copy, nonatomic) NSString *income;
@property (copy, nonatomic) NSString *upIncome;
@property (strong, nonatomic) NSNumber *finished;

+ (instancetype)defaultModel;

@end

@interface ATProductModel : ATBaseModel

@property (strong, nonatomic) NSArray <ATProductSubModel *>* products;
@property (assign, nonatomic) ATFilterLayoutType layoutType;
@property (assign, nonatomic) BOOL recommended;

@end

NS_ASSUME_NONNULL_END

ATProductViewController.h

#import "ATProductModel.h"

NS_ASSUME_NONNULL_BEGIN

@interface ATProductViewController : UIViewController

@property (strong, nonatomic) ATProductSubModel *model;

@end

ATProductViewController.m

#import "ATStringUtil.h"

@implementation ATProductViewController

@property (strong, nonatomic) ATProductModel *productModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self defaultModels];
}

- (void)defaultModels{

    NSMutableArray *smallImages = [NSMutableArray arrayWithArray:self.model.smallImages];
    if (![ATStringUtil containStr:self.model.icon inArr:self.model.smallImages]) {
        [smallImages insertObject:self.model.icon atIndex:0];
    }
    self.model.smallImages = smallImages;
}

@end
```

In terms of number of properties, I wouldn’t worry about that. There are situations where you can have lots of properties. As the philosopher says, “it is what it is.”

Obviously, from a data modeling perspective, what doesn’t feel quite right is to combine product info, coupon info, shop info, etc. into a single object. E.g. products sometimes are eligible for multiple coupons. Or perhaps you’ll be repeating the “shop” information multiple times in your result set.

That having been said, it depends upon what this feed is for: If this is a search result employed within a particular view within the app, then perhaps a fairly flat structure, like yours, is fine (though I might call the object a “search result” rather than a “product”). But if this is for populating a local data store that users can search locally, then I might expect separate objects for the different entity types (a product object, a shop object, etc.). I’d ask myself how often can the same information be repeated in a particular result set. But whether you have a denormalized/flat result set, or a more normalized product database, just depends upon the nature of the API and how this is being used within the app.

The only change that really jumps out at me is that there are several properties that would appear to be numeric types that are captured as strings (e.g. prices, rates, fees, income, etc.). Perhaps your feed returns them as strings, but within your app, you don’t want to have to sprinkle your code with string-to-number conversions so that you can do things like show the user grand totals, convert rates to totals, or the like. I might be inclined to do that string-to-number conversion while parsing the feed (or, better, change the feed to actually return numeric types) and then I’m working purely with numeric types within the app.


Dice notation roller in JavaScript I have the following function, intended to take standard dice notation (XdY+Z) and return a (sort of) random number based on the input. Are there any bugs/bad ideas/optimizable sections I am missing?

function dieRoll(dice) {
    if (/^[\d+]?d\d+[\+|\-]?\d*$/.test(dice) == false) { //Regex validate
        return "Invalid dice notation"; //Return if input invalid
    }

    if(dice[0]=="d") { //If the first character is a d (dY)
        dice = "1"+dice; //Add a 1
    }
    var minus = dice.search(/\-/); //Search for minus sign

    if (minus == -1 && dice.search(/\+/) == -1) { //If no minus sign and no plus sign (XdY)
        dice += '+0'; //Add a +0
    }
    if (minus == -1) { //If no minus sign (XdY+Z)
        var dicesplit = dice.split('+'); //Split for plus sign
        var modifier = dicesplit[1] * 1; //Number to add to total
    } else { //If there is a minus sign (XdY-Z)
        var dicesplit = dice.split('-'); //Split for minus sign
        var modifier = ("-" + dicesplit[1]) * 1; //Number to add to total
    }

    var diesplit = dicesplit[0].split('d'); //Take the first section (XdY) and split for d
    var howmany = diesplit[0] * 1; //Number of dice to roll
    var diesize = diesplit[1] * 1; //How many sides per die
    var total = 0; //Total starts as 0

    for (var i = 0; i < howmany; i++) { //Loop a number of times equal to the number of dice
        total += Math.floor(Math.random() * diesize) + 1; //Random number between 1 and diesize
    }
    total += modifier; //Add the modifier

    return total; //Return the final total
}

You validate the input string against a regular expression, but then you manually parse it again the hard way.  Instead, you should use parentheses within the regular expression to define capturing groups.

I also think that your regular expression is not quite correct.  Optional digits X preceding "d" should be \d* or (\d+)?.  An optional ±Z should be ([+-]\d+)?.

function dieRoll(dieSpec) {
    var match = /^(\d+)?d(\d+)([+-]\d+)?$/.exec(dieSpec);
    if (!match) {
        throw "Invalid dice notation: " + dieSpec;
    }

    var howMany = (typeof match[1] == 'undefined') ? 1 : parseInt(match[1]);
    var dieSize = parseInt(match[2]);
    var modifier = (typeof match[3] == 'undefined') ? 0 : parseInt(match[3]);

    …
}


Create two random teams from a list of players The task is to create two random teams from a list of players.

Given an example of players = ["John", "Mike", "Alice", "Bob"]

One example random team would be:

team1 = ["Mike", "Alice"];
team2 = ["John", "Bob"];

This is my solution but I'm not sure how efficient it is because random can create same number for a number of times.

The question to separate equally and randomly without repeating the same player.

using System;
using System.Collections.Generic;

public class Program
{

    public static void Main(string[] args)
    {
        Random rnd = new Random();
        var numbers = new List<int>();

        var ilkListe = new List<int>();

        var ikinciListe = new List<int>();

        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);
        numbers.Add(4);
        numbers.Add(5);
        numbers.Add(6);
        numbers.Add(7);
        numbers.Add(8);
        numbers.Add(9);
        numbers.Add(10);
        Console.WriteLine("LIST 1: " + numbers.Count);

        do {
            int sayi = numbers[rnd.Next(numbers.Count)];
            if (!(ilkListe.Contains(sayi))) {
                Console.WriteLine(sayi);
                ilkListe.Add(sayi);
            }
        }

        while (ilkListe.Count < numbers.Count / 2);

        Console.WriteLine("Ikinci liste");

        do {
            int sayi = numbers[rnd.Next(numbers.Count)];
            if (!(ilkListe.Contains(sayi)) && !(ikinciListe.Contains(sayi))) {
                Console.WriteLine(sayi);
                ikinciListe.Add(sayi);
            }
        }

        while (ikinciListe.Count < numbers.Count / 2);
    }
}

Review

Don't use the main entry point to implement an algorithm. Create a method instead.
Think about how to allow this method to be usable for all kinds of types, not just integers. You have implemented the algorithm for integers, yet you show an example with strings.
When creating an algorithm, surely you have made some unit tests, at least for the happy paths. Feel free to include them in the question.
Use clear variable names, and stick to one written language.
Don't mix algorithm logic with Console output.

A possible method signature could be:

public static IEnumerable<IEnumerable<T>> SplitRandom<T>(
    this IEnumerable<T> source, int targetCount)
{
    // .. algorithm implementation
}

Called as..

var names = new [] { "John", "Mike", "Alice", "Bob" };
var teams = names.SplitRandom(2);

Or as..

var numbers = Enumrable.Range(1, 10);
var numberGroups = numbers.SplitRandom(2);


Show results of a runners' competition with details about each runner This is about to show the results of a runners' competition.  It shows us the runner's number, the sex ( 1 = man, 0 = woman ), age and time.  After showing the results of these runners, it shows the winner of each sex.

package *;
public class ArraysSix {
    public static void main(String[] args) {
      //int pm = position man, pw = position woman
      int pm = 0;
      int pw = 0;

      String[] a = {"Runner", " Sex", " Age", "    Min"};
      String[][] b = {
            {"  3457", "   1", "  41", "     39"},
            {"   344", "   1", "  30", "     38"},
            {"  3333", "   0", "  28", "     45"},
            {"  3450", "   0", "  45", "     50"},
            {"   101", "   1", "  21", "     52"},
            {"   455", "   1", "  37", "     41"},
            {"   100", "   0", "  40", "     37"},
      };
      //array int
      int[][] c = {
            { 3457, 1 , 41 , 39 },
            { 344 , 1 , 30 , 38 },
            { 3333, 0 , 28 , 45 },
            { 3450, 0 , 45 , 50 },
            { 101 , 1 , 21 , 52 },
            { 455 , 1 , 37 , 41 },
            { 100 , 0 , 40 , 37 },
     };
     //for print title
     for (int i = 0; i < a.length; ++i) {
        System.out.print("|"+a[i]+"|");
     }
     System.out.println("\n-----------------------------");
     //for print numb
     for (int i = 0; i < b.length; ++i) {
        for(int j = 0; j < b[i].length; ++j) {
            System.out.print("|"+b[i][j]+"|");
        }
        System.out.println("\n-----------------------------");
     }
     //for to find the minimun time of man
     for ( int i = 0 ; i < 7 ; i++) {
        if ( c[i][1] == 1 ) {
            if ( c[i][3] < c[pm][3] ) {
                pm = i ;
            }
        //else to find the minimum of woman
        } else {
            if ( c[i][1] == 0 ) {
                if ( c[i][3] < c[pw][3] ) {
                    pw = i ;
                }
            }
        }//end else
    }//end for

    //for to print the winners
    for (int i = 0 ; i < 1 ; i++ ) {
        System.out.print("Runner num "+c[pm][0]
                +" with an age of "+c[pm][2]
                +" and time of "+c[pm][3]
                +" min is the male winner.");
        System.out.println("");

        System.out.print("Runner num "+c[pw][0]
                +" with an age of "+c[pw][2]
                +" and time of "+c[pw][3]
                +" min is the female winner.");
    }//end for
 }//end method
}//end class

So I think there's is a better way to make this piece of program, but I don't have the knowledge yet.

for (int i = 0; i < a.length; ++i) {
        System.out.print("|"+a[i]+"|");
     }

This could be just

     for (String heading : a) {
         System.out.print("|" + heading + "|");
     }

You don't need an i variable.

        for(int j = 0; j < b[i].length; ++j) {
            System.out.print("|"+b[i][j]+"|");
        }
        System.out.println("\n-----------------------------");

This could be

        System.out.println(
            String.format("|%6d||%4d||%4d||%7d|\n-----------------------------",
            c[0], c[1], c[2], c[3]));

This allows you to get rid of b entirely.

You might point out that this hard codes c[0], etc.  But that's not nearly as big a deal as it might first seem.  The formats are specific for each one, so you have to write out those variables anyway.  The real solution would probably be a Runner class where you could say things like runner.getNumber() instead of c[0].  Because right now it's not clear why 0 means Runner.

      //int pm = position man, pw = position woman
      int pm = 0;
      int pw = 0;

If we replace that with

      final int SEX_COUNT = 2;
      int[] firstBySex = int[SEX_COUNT];

Then we can change

     //for to find the minimun time of man
     for ( int i = 0 ; i < 7 ; i++) {
        if ( c[i][1] == 1 ) {
            if ( c[i][3] < c[pm][3] ) {
                pm = i ;
            }
        //else to find the minimum of woman
        } else {
            if ( c[i][1] == 0 ) {
                if ( c[i][3] < c[pw][3] ) {
                    pw = i ;
                }
            }
        }//end else
    }//end for

with

    for (int runner = 0; runner < c.length; runner++) {
        int sex = c[runner][1];

        // [3] is the runner's time
        if (c[firstBySex[sex]][3] > c[runner][3]) {
            firstBySex[sex] = runner;
        }
    }

We no longer hard code the number of rows in c.  Now, if we change the number of rows in c, the code automatically handles it.

We don't have to handle males and females separately.  We use the same code for both.

The intermediate variable sex saves us from having to write a comment explaining what column 1 is.

    //for to print the winners
    for (int i = 0 ; i < 1 ; i++ ) {
        System.out.print("Runner num "+c[pm][0]
                +" with an age of "+c[pm][2]
                +" and time of "+c[pm][3]
                +" min is the male winner.");
        System.out.println("");

        System.out.print("Runner num "+c[pw][0]
                +" with an age of "+c[pw][2]
                +" and time of "+c[pw][3]
                +" min is the female winner.");
    }//end for

You could write this as

    for (int sex = 1; sex >= 0; sex--) {
        System.out.println(formatRunnerData(c[firstBySex][sex]]));
    }

with an array

public final String[] SEXES = { "female", "male" };

and a helper method

public static String formatRunnerData(int[] runnerData) {
     StringBuilder builder = new StringBuilder();

     builder.append("Runner num ").append(runnerData[0])
         .append(" with an age of ").append(runnerData[2])
         .append(" and time of ").append(runnerData[3])
         .append(" min is the ").append(SEXES[runnerData[1]).append(" winner.");

     return builder.toString();
}

Now if you make a change to this display, you can make it in one place rather than two.

Originally, you didn't need a for loop.  You only ran the code once.  This makes use of a loop.

This adds an extra end of line at the end, which I find better anyway.  So if you add more text, you don't have to put an end of line before it to print on a new line.

Other than that, this should produce the same display.


First non-repeated character in a string in c Write an efficient function to find the first non-repeated character
  in a string. For example, the first non-repeated character in "total"
  is 'o' and the first non-repeated character in "teeter" is 'r'.

Please see my solution and give me some feedback and suggestions for improving and optimizing it if needed.

#include <stdio.h>
#define SIZE 100                /* max size of input string */
#define LIM 5                   /* max number of inputs */
char repeat_ch(const char *);   /* return first non-repeated character */
int main(void)
{
    char line[SIZE];
    int i = 0;
    char ch;

    while(i < LIM && gets(line))
    {
        ch = repeat_ch(line);
        if(ch != NULL)
            printf("1st non-repeated character: %c\n", ch);
        else
                printf("There is no unique character in a string: %s\n", line);
        i++;
    }

}

char repeat_ch(const char *string)
{
    char array[130] = {0};
    char *p = string;

    /* store each character in array, use ascii code as an index for character
     * increment each time the same character appears in a string
     */
    while(*p)                               // stop when '\0' encountered
    {
        array[*p]+=1;
        p++;
    }
    while(*string)
    {
        if(array[*string] == 1)
            return *string;         // stop when unique character found
        string++;
    }

    return *string;
}

Alex, it looks quite efficient. There are some issues that I see:

gets should never be used. Use fgets (but note that you will have to strip the trailing \n)
define main at the end to avoid the need for a prototype for repeat_ch
declare repeat_ch as static
your limit does not work as i is not incremented.  But why not stop on
reading an empty string rather than limit the number of loops?
NULL is normally defined as (void *) 0 so comparing a char with NULL is
wrong.  The compiler will warn you of that.  Just use 0 or better '\0'

In repeat_ch

function name is inaccurate - function looks for a non-repeated char.
the two // comments are noisy (ie. don't tell reader anything)
array would be better sized 256
p should be const
for-loops would be better

for (const char *p=string; *p; ++p) {
    array[*p] += 1;
}
for (const char *p=string; *p; ++p) {
    if (array[*p] == 1) {
        return *p;
    }
}
return '\0';


Using goto to wait on the result of a database query to change This is a small personal project where most non-sensitive data is distributed to some globally hosted CDN servers, which store the JSON. Now one problem we've seen during testing is a few deadlocks during spike loading of Ajax resources at the precise time that the cache is being distributed to the cache servers. So I came up with this locking scheme. Basically it will loop until the cache-lock value from one of the slave db servers responds with a value of 1, where 1 represents readable and 0 represents a locked state.

Is this ok to put into production? The environment is a REST server written in Slim Framework. I'm not smart enough to know why goto is considered evil so I would like a different opinion. I'm also curious if I should choose an alternative to sleep(1).

public function wait_lock()
{
    $steps = 0;
    restart:
    if(! $this->is_enabled('cache-lock') ){
        if($steps > 4){
            // the following method is a short cut for throwing an exception.
            $this->e('cache error. wait a few moments and try again. if the problem persists, contact the administrator.');
        }else{
            sleep(1);
            $steps++;
            goto restart;
        }
    }
}

Besides the unjustified use of goto, I also object to the use of the number 4 for an operation that you try up to 6 times.

Counting loops are usually best written as for loops.

public function wait_lock() {
    for ($tries = 0; $tries < 6 && !($lock = $this->is_enabled('cache-lock')); ++$tries) {
        sleep(1);
    }
    if (!$lock) {
        // the following method is a short cut for throwing an exception.
        $this->e('cache error. wait a few moments and try again. if the problem persists, contact the administrator.');
    }
}


Print linkedlist reversely I'm working on the problem of print a linked list reversely without destruction. I'm wondering if any other better ideas, in terms of both time complexity improvement and space complexity improvement. I also welcome for code bugs and code style advice.

class LinkedListNode:
    def __init__(self, value, nextNode):
        self.value = value
        self.nextNode = nextNode
    def print_reverse(self):
        if not self.nextNode:
            print self.value
            return
        else:
            self.nextNode.print_reverse()
            print self.value
if __name__ == "__main__":
    head = LinkedListNode('a', LinkedListNode('b', LinkedListNode('c', LinkedListNode('d', None))))
    head.print_reverse()

Code Style notes:

follow PEP8 style guide, in particular:

one empty between the class methods
two empty lines after the class definition and before the next block

use print() function instead of a statement - this way you are staying compatible with the Python 3.x
rename nextNode to next_node
don't forget about the docstrings

Other improvements:

you should probably explicitly inherit from object to have a new-style class (reference)
instead of a print_reverse(), how about you create a generator method that would yield nodes instead of printing - this can come out handy later when you would actually need to use the node values, not just have them on the console

With all the suggestions applied (except the docstrings):

class LinkedListNode(object):
    def __init__(self, value, next_node):
        self.value = value
        self.next_node = next_node

    def reverse_traversal(self):
        if not self.next_node:
            yield self.value
        else:
            for node in self.next_node.reverse_traversal():
                yield node
            yield self.value

if __name__ == "__main__":
    head = LinkedListNode('a', LinkedListNode('b', LinkedListNode('c', LinkedListNode('d', None))))
    for node in head.reverse_traversal():
        print(node)

As a side note, if you would be on Python 3.3+, this part:

for node in self.next_node.reverse_traversal():
    yield node

can be rewritten using the generator delegation:

yield from self.next_node.reverse_traversal()


A variadic C function for concatenating multiple strings I have this function that takes a number \$N\$, and \$N\$ C strings, concatenates and returns the result:

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* mystrcat(int count, ...)
{
    char** p;
    char* result;
    char* ptr;

    size_t* len_array;
    va_list ap;
    int j;
    size_t total_length;

    if (count < 1)
    {
        return "";
    }

    va_start(ap, count);
    p = malloc(sizeof(char*) * count);
    len_array = calloc(count, sizeof(size_t));
    total_length = 0;

    for (j = 0; j != count; ++j)
    {
        p[j] = va_arg(ap, char*);
        total_length += (len_array[j] = strlen(p[j]));
    }

    result = malloc(sizeof(char) * (total_length + 1));
    ptr = result;

    for (j = 0; j != count; ++j)
    {
        strcpy(ptr, p[j]);
        ptr += len_array[j];
    }

    *ptr = '\0';
    va_end(ap);
    return result;
}

int main(int argc, char* argv[]) {
    puts(mystrcat(5, "Hello", ", ", "world", ", ", "friends!"));
}

As always, please tell me anything that comes to mind.

Always return allocated string or never do it

This code here:

if (count < 1)
{
    return "";
}

is bad because you return a static string whereas the normal case returns a string allocated by malloc.  If the caller then tries to free this static string, it will cause some kind of error.  You can fix this by either returning an allocated empty string:

if (count < 1)
{
    return calloc(1, 1);
}

or by just returning NULL:

if (count < 1)
{
    return NULL;
}

Memory leaks

Your function never frees p or len_array.  Actually, I would probably not even use temporary arrays like these.  If I were to write this function, I would measure the total length on one pass, and then copy the strings on a second pass.

Rewrite

After fixing the above issues, my rewrite of your function would look like this:

char *mystrcat(int count, ...)
{
    va_list ap;
    size_t  len = 0;

    if (count < 1)
        return NULL;

    // First, measure the total length required.
    va_start(ap, count);
    for (int i=0; i < count; i++) {
        const char *s = va_arg(ap, char *);
        len += strlen(s);
    }
    va_end(ap);

    // Allocate return buffer.
    char *ret = malloc(len + 1);
    if (ret == NULL)
        return NULL;

    // Concatenate all the strings into the return buffer.
    char *dst = ret;
    va_start(ap, count);
    for (int i=0; i < count; i++) {
        const char *src = va_arg(ap, char *);

        // This loop is a strcpy.
        while (*dst++ = *src++);
        dst--;
    }
    va_end(ap);
    return ret;
}


Method of uniquely identifying classes I have written the following class to allow me to uniquely identify classes in C++, and I was wondering if there are any better ways of going about it.

#ifndef _TYPE_IDENTIFIER_H_
#define _TYPE_IDENTIFIER_H_

typedef std::size_t Identifier;

class TypeIdentifier {
public:
    template<class T>
    static Identifier get_identifier() {
        static const Identifier current_identifier = ++next_identifier;

        return current_identifier;
    }

private:
    static Identifier next_identifier;
};

Identifier TypeIdentifier::next_identifier = 0;

#endif

And an example of using it:

class MyFirstClass {};
class MySecondClass {};

printf("%zu", TypeIdentifier::get_identifier<MyFirstClass>()); // 1
printf("%zu", TypeIdentifier::get_identifier<MySecondClass>()); // 2

printf("%zu", TypeIdentifier::get_identifier<MySecondClass>()); // 2
printf("%zu", TypeIdentifier::get_identifier<MyFirstClass>()); // 1

I'm using it in an ECS, where there can only be one instance of a certain component in an Entity. I store a vector of structs containing a void pointer to the component and an Identifier type of the component. Using TypeIdentifier::get_identifier<ComponentType>(), I can check the type of a passed component and check if it's already present in the Entity.

Well you can use typeid.

printf("%zu", typeid(MyFirstClass).hash_code());

Not sure how

TypeIdentifier::get_identifier<MyFirstClass>()
     //                       ^^^^^^^^^^^^    Compile time type.
     //  This will not help with runtime
     //  type checking.

is going to help you.

Assuming the above is in a single header file (because of include guards).

Then this:

Identifier TypeIdentifier::next_identifier = 0;

Is in the wrong place. It will be defined for every compilation unit that includes the header. Personally I would use a function rather than a static value.

class TypeIdentifier {
public:
    template<class T>
    static Identifier get_identifier() {
        static const Identifier current_identifier = getNext();
        return current_identifier;
    }

private:
    static Identifier getNext() {
        static Identifier next_identifier = 0;
        return next_identifier++;  //
    }
};


Filter by a transformed list, then untransform the result Both exercises have a common pattern of "filter by a transformed list, then untransform the result". See skip and localMaxima.

-- exercise 1
skips :: [a] -> [[a]]
skips xs = map (\n -> skip n xs) [1..(length xs)]

skip :: Integral n => n -> [a] -> [a]
skip n xs = map snd $ filter (\x -> (fst x) `mod` n == 0) (zip [1..] xs)

--exercise 2
isLocalMaximum :: Integral a => (a,a,a) -> Bool
isLocalMaximum (a,b,c) = b > a && b > c

sliding3 :: [a] -> [(a,a,a)]
sliding3 xs@(a:b:c:_) = (a,b,c) : sliding3 (tail xs)
sliding3 _ = []

localMaxima :: Integral a => [a] -> [a]
localMaxima xs = map proj2 $ filter isLocalMaximum (sliding3 xs)
  where proj2 (_,b,_) = b

-- *Main> filter isLocalMaximum (sliding3 [1,5,2,6,3])
-- [(1,5,2),(2,6,3)]

My instincts say that I could implement both of these something like this:

localMaxima' :: Integral a => [a] -> [a]
localMaxima' xs = filterBy isLocalMaximum sliding3 xs

if only I could implement filterBy

filterBy :: (b -> Bool) -> ([a] -> [b]) -> [a] -> [a]
filterBy p f as = as'
  where indexedAs = zipWith (,) [0..] as
        indexedBs = zipWith (,) [0..] (f as)
        indexedBs' = filter p indexedBs     -- doesn't typecheck; how can we teach p about the tuples?
        indexes = map fst indexedBs
        as' = map (\i -> snd (indexedAs !! i)) indexes

It's also slower than just writing out a fold. Is this all a bad idea? I've always considered fold a low level recursion operator and always try to structure in terms of higher level map and filter but maybe I am misunderstanding.

My Haskell level is: understand LYAH but not written much code.

This is a homework to CIS 194 (2013 version) (though I am not taking the class, I am working through the material on my own)

Exercise 1

If you have a lambda (or any function) of type (a,b)->c, instead of writting it like this (\x->...), you can write it like this (\(x,y)->...). It will remove the need of calling fst like in your skip function. You should change the name skip too, because it already exist in the prelude and it's kinda unclear because they have different meaning. I would call it something like skipEvery

Exercise 2

as is a keyword in Haskell, used for module importation. It will compile if you use it as a variable, but if you a text editor with syntax highlighting, it will be weird

  My instincts say that I could implement both of these something like
  this:

localMaxima' :: Integral a => [a] -> [a]
localMaxima' xs = filterBy isLocalMaximum sliding3 xs

Your instinct wasn't wrong, but there is an alternative to filterBy, which is mapMaybe. The resulting code would be something like this

whenMaybe p x = if p x then Just x else Nothing
localMaxima' = mapMaybe (whenMaybe isLocalMaximum) . sliding3

You should use zip instead of zipWith (,), because both operations are equivalent


Stack of integers in C I'm learning C, and currently I follows C99 standard. Here is my implementation of integer-stack, which is just a stack you can do: push, pop, and print the content of the stack.
Here are some problems I currently have:

Is that #define STACK_MAX 1000 a good idea? Should I consider make it configurable in runtime?
It's impossible to make struct int_stack * to int_stack *, like C++, right?

Other than these two problem, I need feedbacks about anything you think important, but I missed out, thank you.

int_stack.h:
#ifndef INT_STACK_H
#define INT_STACK_H

#include <stdio.h>
#include <stdbool.h>
#define STACK_MAX 1000

typedef struct int_stack {
    int top;
    int data[STACK_MAX];

    bool (*push)(struct int_stack *, int);
    bool (*pop)(struct int_stack *, int *);
    int (*size)(struct int_stack *);
    void (*print_stack)(struct int_stack *);

} int_stack;

bool push(int_stack *self, int item) {
    if (self->top == STACK_MAX)
        return false;
    self->data[self->top++] = item;
    return true;
}

bool pop(int_stack *self, int *out) {
    if (size(self) == 0)
        return false;
    *out = self->data[--self->top];
    return true;
}

int size(int_stack *self) {
    return self->top;
}

void print_stack(int_stack *self) {
    printf("| top |\n");
    for (int i = self->top-1; i >= 0; i--)
        printf("| %3d |\n", self->data[i]);
}

void array_zeros_init(int A[], int size) {
    for (int i = 0; i < size; i++)
        A[i] = 0;
}

void stack_init(struct int_stack *stack) {
    stack->top = 0;
    array_zeros_init(stack->data, STACK_MAX);
    stack->push = &push;
    stack->pop = &pop;
    stack->size = &size;
    stack->print_stack = &print_stack;
}

#endif // !INT_STACK_H

We wouldn't normally put the function definitions in the header like that.  Just write the declarations that are needed by the calling code, and put the definitions into their own source file.
It seems odd to have these function pointers:

bool (*push)(struct int_stack *, int);
bool (*pop)(struct int_stack *, int *);
int (*size)(struct int_stack *);
void (*print_stack)(struct int_stack *);

Nothing needs them, so just omit them.
pop() uses size() before the latter is defined.  We could solve this by re-ordering, but separating declarations from definitions will naturally fix this.
size() and print() don't need to modify the stack, so they should accept pointer to const object.
The function names are all vulnerable to collisions.  I'd suggest adding a common prefix to distinguish and group them.
Writing zeros to the unused elements is a bit pointless, as those elements are not reachable through the public interface.
Here's my re-write:
Header:
#ifndef INT_STACK_H
#define INT_STACK_H

#include <stdbool.h>

typedef struct int_stack int_stack;

int_stack *stack_create(void);
void stack_free(int_stack *self);

bool stack_push(int_stack *self, int item);
bool stack_pop(int_stack *self, int *out);
int stack_size(const int_stack *self);
void stack_print(const int_stack *self);

#endif // !INT_STACK_H

Implementation
#include <stdio.h>
#include <stdlib.h>
#define STACK_MAX 1000

struct int_stack {
    int top;
    int data[STACK_MAX];
};

int_stack *stack_create(void) {
    int_stack *stack = malloc(sizeof *stack);
    if (stack) {
        stack->top = 0;
    }
    return stack;
}

void stack_free(int_stack *self) {
    free(self);
}

bool stack_push(int_stack *self, int item) {
    if (self->top == STACK_MAX) {
        return false;
    }
    self->data[self->top++] = item;
    return true;
}

bool stack_pop(int_stack *self, int *out) {
    if (stack_size(self) == 0) {
        return false;
    }
    *out = self->data[--self->top];
    return true;
}

int stack_size(const int_stack *self) {
    return self->top;
}

void stack_print(const int_stack *self) {
    printf("| top |\n");
    for (int i = self->top-1; i >= 0; i--) {
        printf("| %3d |\n", self->data[i]);
    }
}


Insertion sort with binary search in Python I have a bit of trouble simplifying the binary search code. This is different from the traditional binary search because we effectively want to find the location for which A[j] is the least element larger than the current unsorted value.

Thoughts?

def binary_search(A, value, start, end):
    # we need to distinugish whether we should insert
    # before or after the left boundary.
    # imagine [0] is the last step of the binary search
    # and we need to decide where to insert -1
    if start == end:
        if A[start] > value:
            return start
        else:
            return start+1

    # this occurs if we are moving beyond left's boundary
    # meaning the left boundary is the least position to
    # find a number greater than value
    if start > end:
        return start

    mid = (start+end)/2
    if A[mid] < value:
        return binary_search(A, value, mid+1, end)
    elif A[mid] > value:
        return binary_search(A, value, start, mid-1)
    else:
        return mid

def insertion_sort(A):
    for i in xrange(1, len(A)):
        value = A[i]
        j = binary_search(A, value, 0, i-1)
        A = A[:j] + [value] + A[j:i] + A[i+1:]
    return A

print insertion_sort([0,1,-1])
print insertion_sort([0,1,2,3,9,-1])
print insertion_sort([1,2,3,4,5,6,7,8,11,10,0])

Your binary_search is the same as the built-in function bisect.bisect, and you might find the implementation helpful to study.


Trie string iterations \0
   / \
  a   b-a-t-s
 /|\
m s t

which contains [am, as, at, bat, bats]

The goal I'm trying to reach is to iterate through the trie to find if there's a next word or not, then if so get that word.

I would like to know your opinion on my approach.

The goal for this is that, at any point in the trie if there is a node that hasn't been visited, there's another word.

public boolean hasNext() {
    if (position < this.trie.nodeCount()) return true;
    return false;
}

What I'm trying to go for here is to check to see if the trie is not empty, then at the first trienode in the trie traverse it's children and descendants to find the next word in the trie. so for the trie above it would would go to a then first to m then back to a to s, then t. then eventually go onto b and it's children. then on the way, if it passes a full word, it will repeat that. so in this case, since bat is part of bats it would return 'bat' first then on the next iteration return bats

The logic in plain words is

string temp = null
  if has next
  while current != null
     look at current nodes children
     keep track of nodes visited
            (temp += char at that node)
            current = current nodes next node in trie (so a step down the trie)
     if fullword at that node found return next
  return false;

I also thought of trying a pre-order traversal but couldn't figure out how to do it with the arrays.

Current implementation:

public String next() {
    String next = null;
    if(hasNext()){
        current = trie.root.children[position];
        while(!current.children[position].isEndOfWord()){
            position++;
            current = current.children[position];
            next += current.letter;
            if (current.isEndOfWord()) return next;
        }
    }
    return null;
}

Here's the declaration of the trienodes:

    protected char letter = ' ';
    protected TrieNode parentNode = null;
    protected boolean fullWord = false;
    protected TrieNode[] children = new TrieNode[26];
    protected int prefixes = 0;

    public TrieNode(char letter, TrieNode parentNode){
        this.letter = letter;
        this.parentNode = parentNode;
    }

How the trie is built:

public void addWord(String s) {
        if (hasWord(s)) return;

        int index = 0;
        TrieNode current = root;
        char[] letters = s.toCharArray();

        while(index < s.length()){
            TrieNode child = current.children[letters[index] - 97];
            if(child == null){
                child = new TrieNode(letters[index], current);
                child.prefixes++;
                numOfNodes++;
            }

            current = child;
            index++;

            if(index == s.length()){
                current.fullWord = true;
                numOfWords++;
            }
        }
    }

This doesn't look too bad to me, though it would be nice to have the full source code that I could run. I'll comment on the things that stand out to me, though.

Unncessary logic

public boolean hasNext() {
    if (position < this.trie.nodeCount()) return true;
    return false;
}

can be written simply as

public boolean hasNext() {
    return position < this.trie.nodeCount();
}

Whitespace is your friend

This is purely stylistic, but to me

    if (hasNext()) {

is much easier on the eyes than

    if(hasNext()){

A lot of IDEs provide automatic formatting to do this for you, too (In Eclipse, Window -> Preferences -> Java -> Code Style -> Formatter).

More on the next method

Avoid nulls if you can. See Google Guava's rational and Effective Java Item 43. If you initialize next to "" instead of null, you can avoid some potential errors downstream.
This can be simplified:

position++;
current = current.children[position];

to just

current = current.children[++position];

Alarm bells should be going off anytime you're iteratively adding to a String. You should be using a StringBuilder instead. Read more about them here.
Using an if statement without brackets is rarely a good idea.
Some standards discourage more than one return statement per method.

With that said, here is how I would refactor the method:

public String next() {
    StringBuilder next = new StringBuilder();

    if (hasNext()) {
        current = trie.root.children[position];
        while (!current.children[position].isEndOfWord()) {
            next.append(current.children[++position]);
            if (current.isEndOfWord()) {
              break;
            }
        }
    }

    return next.toString();
}

Regarding TrieNode

Why are the fields protected? This suggests that the class is to be extended. If that's the case, TrieNode should be abstract (See Open-Closed principle and Effective Java Item 17: "Design and document for inheritance or else prohibit it").
If letter and parentNode variables don't change, you can make them final (again, IDEs like Eclipse can also do this automatically for you).
On the line

protected TrieNode[] children = new TrieNode[26];

26 is a magic number, and should be replaced with a constant.

Final thoughts on addWord

Use a for loop instead of the current while loop. Then you can remove two lines that deal with updating index.
Instead of

TrieNode child = current.children[letters[index] - 97];

you should be able to go

TrieNode child = current.children[letters[index] - 'a'];

which has the benefit of not using a magic number and is more clear.


Caesar cipher exercise I was doing this exercise from here.  I made a solution work but can't help feel it could have been done in fewer lines.  I'm quite new to python so I'm not too sure of the little shortcuts.

def shift(S, n):
   word = ''
   for i in S:
      if ord(i) == 32:
         word += ' '
      elif ord(i)+n > 90:
         a = n-(90-ord(i))+64
         word += chr(a)
      else:
         word +=chr(ord(i)+n)
   return word
def TGS(x): # Total goodness of string
   TGC = 0 # Total goodness of character
   for i in x:
      if ord(i) == 32:
         continue
      TGC += letterGoodness[ord(i)-65]
   return TGC
A = input()
LOSS = [shift(A,n) for n in range (1,27)] # List of shifted strings
LOTG = [TGS(x) for x in LOSS]
a = LOTG.index(max(LOTG))
print(LOSS[a])

Magic numbers.

Try to avoid them. 65 is really ord('A'), 90 is ord('Z'); so say that explicitly. Along the same line,

if i == ' ':

looks better than

if ord(i) == 32:

Naming

Try to use descriptive names. I'd prefer caesar_decrypt(ciphertext, shift) to shift(S, n). Same goes for A, a, etc.
Streamlining

I was really stumbled upon an asymmetry of elif and else cases of shift:

     a = n-(90-ord(i))+64
     word += chr(a)

is quite counter-intuitive. I'd suggest

for i in S:
  if ord(i) == 32:
      word += ' '
      continue
  a = ord(i) + n
  if a > ord('Z'):
      a -= ord('Z') - ord('A')
  word +=chr(a)


Sorting an HTML table with JavaScript The following code sorts an HTML table with JavaScript (without using any external libraries like jQuery). Are there any shortcomings or possible improvements I could make?

    <meta http-equiv="content-type" content="text/html;charset=Windows-1252">

                Name
                Surname
                Age

                Raja
                Dey
                18

                Mamata
                Sharma
                20

                Avijit
                Sharma
                21

                Sharanya
                Dutta
                26

                Nabin
                Roy
                27

To speed up the sorting you first have to find what is consuming time. In your case the slower part of your code is:

for(i = 0; i < rlen; i++){
    rows[i].innerHTML = ""+arr[i].join("	")+"	";
}

The reason is that the DOM elaboration is time consuming for the browser.

Here's an updated version that minimizes the access to the DOM:

function sort_table(tbody, col, asc){
    var rows = tbody.rows, rlen = rows.length, arr = new Array(), i, j, cells, clen;
    // fill the array with values from the table
    for(i = 0; i < rlen; i++){
    cells = rows[i].cells;
    clen = cells.length;
    arr[i] = new Array();
        for(j = 0; j < clen; j++){
        arr[i][j] = cells[j].innerHTML;
        }
    }
    // sort the array by the specified column number (col) and order (asc)
    arr.sort(function(a, b){
        return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1*asc);
    });
    for(i = 0; i < rlen; i++){
        arr[i] = ""+arr[i].join("	")+"	";
    }
    tbody.innerHTML = "
"+arr.join("

")+"
";
}

Proof: http://jsperf.com/table-sorting-stack-overflow


Project Euler #10 and #12 in Java - Prime Numbers I am dealing with a huge time taking with primes. I hope you know they are pretty random and that's why create many problem. Both are using the same logic/methods.

/*
 * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all
 * the primes below two million.
 * http://projecteuler.net/problem=10
 */

public static long get10() {
    long sum = 0;// 2 is also a prime
    for (int i = 2; i < 2000000; i++) {
        if (isPrime(i)) {
            sum += i;
        }
    }
    return sum;
}
/*
 * The sequence of triangle numbers is generated by adding the natural
 * numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 =
 * 28. The first ten terms would be:
 *
 * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
 *
 * Let us list the factors of the first seven triangle numbers:
 *
 * 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28:
 * 1,2,4,7,14,28 We can see that 28 is the first triangle number to have
 * over five divisors.
 *
 * What is the value of the first triangle number to have over five hundred
 * divisors?
 * http://projecteuler.net/problem=12
 */
public static long get12() {
    for (int i = 1;; i++) {
        long n_t = Sumk(i);
        int d = getDivisorCount(n_t);
        if (d >= 500) {
            return n_t;
        }
    }
}
public static long Sumk(int n) {
    // Sum of k from 1 to n =n*(n+1)/2 [Also n'th triangular number]
    return n * (n + 1) / 2;
}
public static boolean isPrime(int n) {
    if (n == 2)
        return true;
    if (n % 2 == 0)
        return false;
    for (int i = 3; i * i <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}

public static int getDivisorCount(long n) {
    int d = 1;
    for (int i = 2; i <= n;) {
        if (isPrime(i)) {
            int d2 = 0;
            while (n % i == 0) {
                ++d2;
                n /= i;
            }
            d *= (d2 + 1);
        }
        if (i == 2) {
            ++i;
        } else {
            i += 2;
        }
    }
    return d;
}

Currently the output is:

10

  Time taken 4.160109858 seconds

12

  Time taken 6.856344169 seconds

You could make use of the Sieve of Eratosthenes, which would give you all the speed you need. There's a lot of such code here on CR, so let's gop to the review.

long sum = 0;// 2 is also a prime
for (int i = 2; i < 2000000; i++) {

Right, but

long sum = 1;// 2 is also a prime
for (int i = 3; i < 2000000; i+=2) {

does the job as well. No big improvement as the evens get tested very fast.

    long n_t = Sumk(i);

This is a terrible name, but maybe OK in math code.

    int d = getDivisorCount(n_t);

What do we know about divisors of a product? Right, you could simply "add" them.1 No advantage here, but a big speed up for big numbers (coming in later Euler problems).

As you count the divisors of a * (a+1) and then (a+1) * (a+2), you could reuse the divisors for (a+1) for a speedup factor of 2.

public static long Sumk(int n) {

Method names always start with lowercase.

public static boolean isPrime(int n) {
    if (n == 2)
        return true;
    if (n % 2 == 0)
        return false;
    for (int i = 3; i * i <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}

That's fine. Just note that (i & 1) is a faster way of computing i % 2 for non-negative i.

public static int getDivisorCount(long n) {
    int d = 1;
    for (int i = 2; i <= n;) {
        if (isPrime(i)) {

And that's the culprit! You're doing an expensive operation (isPrime) in order to save a much cheaper one (division)!

Actually, the whole method is confusing, so let's go through:

public static int getDivisorCount(long n) {
    int d = 1;

But d is not a nice name. I'd suggest to call it simply result.

    for (int i = 2; i <= n;) {

Here, you could use a test like i * i < n again, couldn't you?

        if (isPrime(i)) {

My above point was about efficiency. Actually, in order for the below computation (d *= (d2 + 1)) to work, it's necessary to use only primes here. However,

when you get a divisor of the (reduced) n here
it's always the least divisor
and the least multiple is always a prime

        int d2 = 0;
        while (n % i == 0) {
            ++d2;
            n /= i;
        }
        d *= (d2 + 1);
    }
    if (i == 2) {
        ++i;
    } else {
        i += 2;
    }

That's OK, but I'd handle 2 specially. There's a nice trick (irrelevant here) for getting out all powers of two:

int d2 = Integer.numberOfTrailingZeros(n);
n >>= d2;

    }
    return d;
}

OK. Btw., my solutions to these problems take nearly one second. That's not fast, but I don't care as there's enough to optimize when working on the harder problems.

My divisorCount

It takes 0.12 seconds and could surely be improved via memoization or a precomputed list of primes (a list up to Math.sqrt(Integer.MAX_VALUE) can be easily found in internet).

private int divisorCount(int x) {
    int result = 1;
    {
        final int d2 = Integer.numberOfTrailingZeros(x);
        result *= d2 + 1;
        x >>= d2;
    }
    for (int i=3; i*i <= x; i+=2) {
        int d2 = 0;
        while (x%i == 0) {
            ++d2;
            x /= i;
        }
        result *= d2 + 1;
    }
    if (x!=1) result *= 2;
    return result;
}

1 I was wrong here. The prime factors list (multiset) can simply be concatenated. The number of divisors can be computed easily using them. Let's say that this is what I meant by "add" (it's not, I was plain wrong, but don't tell it further).


PHP Singletons Wrapper (Dynamic Admin) I need to create an administration board that allows devs to create or modify options and display them in a panel. The Admin needs to be the same on each call made to it.
I've chosen to make all dependencies as singletons wrapped under Admin. This code only covers the approach, disconsider the lack of details.

class Admin {
    private static $instance;

    public static function getInstance() {
        if ( null === static::$instance ) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    private function __clone() {

    }

    private function __wakeup() {

    }

    public $Options;
    public $Panel;

    protected function __construct() {
        $this->Options = Options::getInstance();
        $this->Panel = Panel::getInstance();
        $this->run();
    }

    protected function run() {
        $this->Panel->run();
    }
}

class Options {
    private static $instance;

    public static function getInstance() {
        if ( null === static::$instance ) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    private function __clone() {

    }

    private function __wakeup() {

    }

    protected $options = array();

    public function getOptions() {
        return $this->options;
    }

    public function addOption($option) {
        $this->options[] = $option;
    }
}

class Panel {
    private static $instance;

    public static function getInstance() {
        if ( null === static::$instance ) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    private function __clone() {

    }

    private function __wakeup() {

    }

    protected $title = 'Panel';

    public function run() {
        $this->render();
    }

    public function render() {
        $Options = Options::getInstance();
        $options = $Options->get_options();
        foreach($options as $option) {
            echo $option['name'];
        }
    }
}

$Admin = Admin::getInstance();
$Admin->Options->addOption( array( 'name' => 'Test' ) );

First, from a styling standpoint, your classes are structured strangely.  Typically, one would have all class properties defined as first thing in class, then the constructor as first method, then the other methods (oftentimes with public methods first with protected/private methods following).  Don't mix your properties throughout your class.

Be consistent with style around variable naming.  You probably should not be using first letter caps for any properties or variables in PHP (which is more or less industry standard).  See the PHP Standards Recommendations for good suggestions on standards to follow (particularly PSR-2 around coding style).

I have several concerns regarding class design:

I don't really understand need for singleton here.  I would actually suggest you consider dependency injection as a preferable way to inject dependencies into classes that need them.
It particularly doesn't seem to make sense to have late static binding in place like you do here if there is no intent to use inheritance.  Now if you had a Singleton base class from which you inherited singleton behavior for each of these classes, then use of late static binding might be appropriate.
Additionally, you make the options and panel properties on the Admin class mutable, so you are potentially allowing the caller to put the Admin class in a bad state.
I don't really even know why options are being held on Admin class at all.  Your dependency chain seems to be Options -> Panel -> Admin, so why put an Options dependency on Admin at all?
Why introduce run() alias to render() in Panel? This method adds nothing new.
I don't understand why you would call run() from Admin constructor when, in your usage example, you are adding options after the class is instantiated.  Would these options never be rendered?
I am  struggling to see the need for so much static/concrete duality across all these classes.  To me this could be greatly simplified using dependency injection with concrete implementations like shown below:

Example:

class Admin {
    // perhaps this should not really be public?
    // Do you really want this to be mutable outside the constructor
    public $panel;

    public function __construct(Panel $panel) {
        $this->panel = $panel;
    }

    protected function run() {
        $this->panel->render();
    }
}

class Options {
    protected $options = array();

    public function __construct() {}

    public function getOptions() {
        return $this->options;
    }

    public function addOption($option) {
        $this->options[] = $option;
    }
}

class Panel {
    protected $title = 'Panel';
    protected $optionContainer;

    public function __construct(Options $options) {
        $this->optionContainer = $options;
    }

    public function render() {
        $options = $this->optionContainer->get_options();
        foreach($options as $option) {
            echo $option['name'];
        }
    }
}

// usage
$options = new Options();
$options->addOption( array( 'name' => 'Test' ) );
$admin = new Admin(new Panel($options));
// maybe add more options
$admin->panel->options->addOptions( array( 'anotherName' => 'Another Test' )
$admin->run();


Implementation of KeyEventDispatcher in Java This is my first test at making a key event dispatcher. Some of the code is unnecessary if one is interested in separating lower and upper cases, however I want to treat them as the same. Hence my wonderfully named method keyToLowerCaseIfUpperCase(char c). I also want to lock the key if it has been pressed untill it is released by the user. To run an event twice the user first needs to release the key.

First of it checks if the key is in [A...Z], if so it returns the corresponding lower key. If not it will keep the key intact. Then I check whetever a key was pressed or not pressed, if it was pressed it will check if that specific key actually can be pressed (using my lock). If it was a key release it will simply release the lock of that key.

import java.awt.KeyEventDispatcher;
import java.awt.event.KeyEvent;

import java.util.HashMap;

public class KeyBindManager implements KeyEventDispatcher
{
    private HashMap<String, Boolean> keyPresses = new HashMap<>();

    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
        String pressed = keyToLowerCaseIfUpperCase(e.getKeyChar())+"";

        if (e.getID() == KeyEvent.KEY_PRESSED) {

            if (keyPresses.get(pressed) != null && keyPresses.get(pressed).booleanValue()) {
                return false;
            }
            keyPresses.put(pressed, new Boolean(true));

            switch (keyToLowerCaseIfUpperCase(e.getKeyChar())) {
                case 'a': System.out.println("D"); break; // these are just two test cases
                case 'b': System.out.println("E"); break;
                default: break;
            }

        } else if (e.getID() == KeyEvent.KEY_RELEASED){
            keyPresses.put(pressed, new Boolean(false));
        }
        return false;
    }

    private char keyToLowerCaseIfUpperCase (char c) {
        if (c >= 'A' && c <= 'Z') {
            c = Character.toLowerCase(c);
        }

        return c;
    }
}

Please tell me this can be done in a more clean approach than what I've accomplished. I don't like the looks of my code very much at all. For now, it gets the job done.

To emphasize, it is the first draft for it. Every criticism is welcome.

First...
I'd, personally, rely on the virtual key code over the key character.  It's possible that the key character may not have been interpreted  until the KEY_TYPED event (or at least I remember some issue where the char could be interpreted at certain stages)
private HashMap<Integer, Boolean> keyPresses = new HashMap<>();

@Override
public boolean dispatchKeyEvent(KeyEvent e) {
    int keyCode = e.getKeyCode();

    if (e.getID() == KeyEvent.KEY_PRESSED) {

        if (keyPresses.contains(keyCode) && keyPresses.get(keyCode).booleanValue()) {
            return false;
        }
        keyPresses.put(keyCode, new Boolean(true));

This also means you don't need to convert the key to lower case, as the virtual key doesn't carry the modifier information (the key character is the key code + the modifiers)
There is a problem with this, KeyEvent.VK_1 can represent both 1 and !, so you might need to consider using KeyStroke instead...
Second...
It's a nitpick on my behalf, but I like a single entry and single exit point in the code...
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
    int keyCode = e.getKeyCode();

    if (e.getID() == KeyEvent.KEY_PRESSED) {

        if (!keyPresses.contains(keyCode) || !keyPresses.get(keyCode).booleanValue()) {
            keyPresses.put(keyCode, new Boolean(true));

It generally makes the code easier to read and the logic to follow as return statements can "hide" in code and it's easy to miss them (IMHO)
Third
Rather than something like this...
switch (keyToLowerCaseIfUpperCase(e.getKeyChar())) {
    case 'a': System.out.println("D"); break; // these are just two test cases
    case 'b': System.out.println("E"); break;
    default: break;
}

I would consider using another Map, to map between the virtual key and the value or "callback" you want to call.  It will be easier to add new values and reuse the code
I'd also consider using a callback mechanism, which would notify of the KEY_PRESSED and KEY_RELEASED events, so the dispatcher didn't do the conversion itself, but simply managed the notification processes, further separating the implementation logic and allow the dispatcher to be more reusable.
You could achieve the same thing through abstraction, but I think some kind of Observer Pattern would be more pratical (IMHO)
Fourth
Unless you really need to know if a key is not been pressed, I would remove the keyCode from the Map on the KEY_RELEASED event
} else if (e.getID() == KeyEvent.KEY_RELEASED){
    keyPresses.remove(keyCode);
}

As it would simpler to just use something like keyPresses.contains(keyCode) instead of then actually needing to check the value associated with, but this comes down to needs.
You could replace the Map with a Set instead which would be simpler, either the keyCode exists or it doesn't...


Script for dynamically-loading data onto a restaurant menu for printing I have a script which dynamically loads data onto a restaurant menu for printing.  Could the following code could be shortened at all?

    <script>
                $(document).ready(function(){
                $('#prestarters').load('prestarters.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                $('#starters').load('starters.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });

                        $('#mains').load('mains.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }
            });

                        $('#sides').load('sides.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }
            });
                $('#dessert').load('dessert.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#dessertwines').load('dessertwines.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#afterdinnerdrinks').load('afterdinnerdrinks.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#whiskeys').load('whiskeys.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#hotdrinks').load('hotdrinks.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#ports').load('ports.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#cognacs').load('cognacs.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#liqueurs').load('liqueurs.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
    });
    </script>

Also, is there a way to alert the user once all data has been loaded? I currently have a message which tells the user to wait 5 - 10 seconds before printing...

Piece iterates over list, calling same $.ajax(), err or, other functions, etc., for each item within list. Save list items to _list , poll until _list.length === list.length - all list items processed - display "menu ready" to viewer.

JSFiddle

(function menus() {

var list = ["prestarters"
           , "starters"
           , "mains"
           , "sides"
           , "dessert"
           , "dessertwines"
           , "afterdinnerdrinks"
           , "whiskeys"
           , "hotdrinks"
           , "ports"
           , "cognacs"
           , "liqueurs"];

var err = function (jqxhr, textStatus, errorThrown) {
    if (textStatus == 'error') {
        var msg = "Sorry but there was an error: ";
        $(".s")
            .html(msg + textStatus + " " + errorThrown);
    };
};

var _list = [];

$.each(list, function (index, value) {
    $.when(value)
        .then(function (data) {
        // var _ids = "#" + data;
        // var _urls = data + ".php";
        // console.log(_ids, _urls);
        // i.e.g.,
        // `$.get(data + ".php")`
        $.post("/echo/json/", {
            json: JSON.stringify([value])
        }, "json")
            .then(function (response, textStatus, jqxhr) {
            _list.push(response);
            // `html`
            $("<section>", {
                    "id": response[0],
                    "html": response[0] + "<br />"
            }).appendTo("#menu");
        }, err)
            .always(function (response, textStatus, jsxhr) {
                // `always` complete callback,
                // when `list` complete
            if (_list.length === list.length) {
                $("<data>" + _list.length + " menus ready</data>")
                    .css({
                    "position": "absolute",
                    "left": "200px",
                    "top": "32px",
                    "fontSize": "28px",
                    "color": "blue"
                })
                .prependTo("#menu") && $("data").fadeOut(7500, function () {
                    $("#menu data").remove()
                });
                // alert(_list.length + " menus ready")
            };
        })
    })
});
}());


Flatten to get all child controls of certain type in a UIView extension Array {
    func flatten<TResult>(transform: (T) -> TResult?, childArray: (T) -> [T]) -> [TResult] {
        var result = [TResult]()

        for original in self {
            let transformed = transform(original)
            if transformed != nil {
                result.append(transformed!)
            }
            result += childArray(original).flatten(transform, childArray: childArray)
        }

        return result
    }
}

Example usage to get all UILabels in a view (including it's subviews) :

let labels = someView.subviews.flatten(
                        { $0 as? UILabel },
                        childArray: { $0.subviews })

The code can probably be simplified/optimized, but how?

Let's start with the method and parameter names (this part is highly
opinion based :)

flatten() does not describe well what you method does: It traverses
recursively a tree-like structure and maps the elements to some values.
Swift already has a flatMap() function (and similar methods for
arrays and other types) which does a similar thing, but only one level
deep. Therefore I would call the method recursiveFlatMap().

Also the descendants of a node in a tree are usually called "children",
so I would choose that as name for the second parameter. (And perhaps
you want to generalize the code for other types, such as sequences.)

for original in self { ... }

iterates of the array elements, therefore I would write that as

for element in self { ... }

let transformed = transform(original)
if transformed != nil {
     result.append(transformed!)
}

can be simplified with optional binding:

if let transformed = transform(element) {
    result.append(transformed)
}

Then we have:

extension Array {
    func recursiveFlatMap<TResult>(transform: (T) -> TResult?, children: (T) -> [T]) -> [TResult] {
        var result = [TResult]()
        for element in self {
            if let transformed = transform(element) {
                result.append(transformed)
            }
            result += children(element).recursiveFlatMap(transform, children: children)
        }
        return result
    }
}

Now let's have a look how the method is called:

let labels = someView.subviews.recursiveFlatMap(
                { $0 as? UILabel },
                children: { $0.subviews })

What strikes me is that you have to specify subviews twice:
In someView.subviews and in $0.subviews.
If the method were called on someView itself then we would have to
specify only once how to descend to the "child nodes".

This means that instead of an Array extension method we have a
(free) generic function which takes the "root of the tree" as the
first argument:

func recursiveFlatMap<T, TResult>(root: T, transform: (T) -> TResult?, children: (T) -> [T]) -> [TResult] {
    var result = [TResult]()
    if let value = transform(root) {
        result.append(value)
    }
    for child in children(root) {
        result += recursiveFlatMap(child, transform, children)
    }
    return result
}

The for-loop can be replaced by the built-in flatMap() method:

func recursiveFlatMap<T, TResult>(root: T, transform: (T) -> TResult?, children: (T) -> [T]) -> [TResult] {
    var result = [TResult]()
    if let value = transform(root) {
        result.append(value)
    }
    result += children(root).flatMap( { recursiveFlatMap($0, transform, children) } )
    return result
}

The function is called as

let labels = recursiveFlatMap(someView,
                { $0 as? UILabel },
                { $0.subviews as! [UIView] })

Finally, you can mark the two closure parameters with the @noescape
attribute. This is new in Swift 1.2 (described in the
Xcode 6.3  release notes) and tells the compiler that
the closure is used only during this function call and
does not outlive the lifetime of the call. This allows some
compiler optimizations:

func recursiveFlatMap<T, TResult>(root: T,
    @noescape transform: (T) -> TResult?,
    @noescape children: (T) -> [T]) -> [TResult]
{
    var result = [TResult]()
    if let value = transform(root) {
        result.append(value)
    }
    result += children(root).flatMap( { recursiveFlatMap($0, transform, children) } )
    return result
}

More thoughts (inspired by this blog post):

recursiveFlatMap() does actually three things:

Recursively traverse a tree-like structure,
transform each object, and
select the objects for which the transformation succeeded.

Swift has built-in methods for the second and third task: map()
and filter(). So you could just define a function that recursively
flattens the given object (in your case the tree of subviews):

func recursiveFlatten<T>(root: T, @noescape children: (T) -> [T]) -> [T] {
    return [root] + children(root).flatMap( { recursiveFlatten($0, children) } )
}

and then use it as

let labels = recursiveFlatten(someView, { $0.subviews as! [UIView] })
    .filter( { $0 is UILabel } )
    .map( { $0 as! UILabel } )

The advantage is that you have a simpler function and a clear
separation into different tasks.

There is a small drawback: an array of all subviews is created first,
and then the labels are extracted. But that is probably tolerable if
the number of subviews is not too large.

(One could work around this problem by defining a method which returns
a "lazy sequence", posted separately as Recursive flattening of Swift sequences.)


Sanitizing and validating a user signup form before submission The first part of the code (above the in-code comment in the middle) looks messy.

I know I could use variables to make it cleaner, I just don't exactly know yet how can I effectively apply those when dealing with jQuery objects. So I'd appreciate a review on that.

As for the if-statements, I think they're okay but if they could be improved I'm all open for it.

Any other suggestions are always welcome.

$(function() {
    // magic number
    var MAX_FIRST_NAME_LENGTH = 35;

    // Hide additional input messages by default except errors.
    $("#signup .addition:not(.error)").css("display", "inline-block").parent().hide();

    // Select (focus) first input and show it's additional (erroneous) message.
    if ($("#signup .error").length === 0) {
        $("#signup input[name=firstName]").select();
        $("#signup input[name=firstName]").siblings("#signup div").show();
    } else if ($("#signup .error").first().parent("#signup div").siblings($("#signup input[name=firstName]")).val().length >= 1) {
        if ($("#signup input[name=firstName]").val().length > MAX_FIRST_NAME_LENGTH) {
            $("#signup input[name=firstName]").select();
        } else {
            $("#signup input[name=lastName]").select();
        }
    } else {
        $("#signup .error").first().parent("#signup div").siblings($("#signup input")).select();
    }

    // Toggle slide on the additional message focus / blur of corresponding input.
    $("#signup input").on("focus blur", function(e) {
        if (!$(this).siblings("#signup div").children("#signup .addition").hasClass("error")) {
            $(this).siblings("#signup div").stop()[e.type === "focus" ? "slideDown" : "slideUp"]("fast");
        }
    });

/// I think the code below is good as is.

    var $form = $("#signup");

    $form.on("submit", function() {
        var emptyInputs = 0;

        $form.find("input").each(function() {
            var $this = $(this),
                val   = $this.val();

            if ($this.prop("type") !== "password") {
                val = $.trim(val);
            }

            // Focus (select) first empty field if any.
            if (val === "" && !emptyInputs++) {
                $this.select();
            }
        });

        if (emptyInputs === 0) {
            var $button = $("#signup button");

            $button.prop("disabled", true);

            return true;
        }

       return false;
    });
});

Kid Diamond! It's always great to see code improving over time. ☺

On loading, you treat input[name=firstName] and input[name=lastName] specially, due to the need for some specialised logic. Instead of selecting each of them every time, you can assign them to variables. The variables are prefixed with $ to remind you that these are jQuery objects.

var $firstName = $("#signup input[name=firstName]"),
    $lastName  = $("#signup input[name=lastName]");

In the first if block, you could optionally take advantage of method chaining. I get rid of the #signup in the selector: since $firstName is already a descendant of #signup, then its siblings will be too, and so it's unnecessary.

$firstName.select().siblings("div").show();

The else if condition is not immediately obvious. After looking at it more carefully, the logic flow is this:

Consider whether the error is associated with $firstName.

If so, consider whether $firstName is not empty.

If $firstName is not empty, then consider whether it is greater than the max length.

If so, then $firstName is the errant field and should be selected.
Otherwise, $firstName is fine, so $lastName must be errant and selected.

If $firstName is empty, then fall-back to the else (below).

Else, select the input associated with the first error.

This is actually rather complicated. In fact, for this snippet, I prefer your original code. Here is how I would rewrite it:

var $errors = $("#signup .error");
if ($errors.length === 0) {
    $firstName.select().siblings("div").show();
} else {
    var $firstError = $errors.first();
    if ($firstError.closest(".input").has($firstName).length > 0) {
        if (!$firstName.val() || $firstName.val().length > MAX_FIRST_NAME_LENGTH) {
            $firstName.select();
        } else {
            $lastName.select();
        }
    } else {
        $firstError.closest(".input").children("input").select();
    }
}

In the event handler, you can at least do var $div = $("#signup div"). Personally, I'd rather rewrite like the following, just because the logic reads slightly more clearly to me:

$("#signup input").on("focus blur", function(e) {
    var $div = $(this).siblings("#signup div");
    if ($div.has(".error").length > 0) {
        $div.stop();
        if (e.type === "focus") {
            $div.slideDown("fast");
        } else {
            $div.slideUp("fast");
        }
    }
});

Below the comment, the code is pretty good. The one thing I'd change is I wouldn't make a $button variable at all, since it's only used once. I might also reverse the order of the logic to avoid the unnecessary return true;:

if (emptyInputs > 0) {
    return false;
}
// if the form submits successfully, disable the button to prevent accidental double-submits.
$("#signup button").prop("disabled", true);