Is there more elegant way than using if - else to append or update the data array in a React app? Below is a React useEffect hook I used in my application, basically what it does is:

data is an array for objects such as {round:number, date:dateString}.

When the application starts running, data will be an empty array, whenever round gets updated, the useEffect() will be called:

if the data array is empty, we update it with its very first object.
else the data array is not empty and if the last object of data array has its date property equal to props.localeDate, I make a new array with the its last object updated
else the data array is not empty and else the last object's date property is not equal to props.localeDate, I append a new object to data array.

const Chart = ({ round, dateAndTime }) => {
  const [data, setData] = useState([]);
  const localeDate = dateAndTime.toLocaleDateString();

  useEffect(() => {
    if (data.length === 0) {
      setData([
        ...data,
        {
          round: round,
          date: localeDate,
        },
      ]);
    } else {
      //update item if date matches
      if (data[data.length - 1].date === localeDate) {
        let newData = data.map((item) => {
          let newItem =
            item.date === localeDate ? { ...item, round: round } : item;
          return newItem;
        });
        setData(newData);
      } else {
        setData([...data, { round: round, date: localeDate }]);
      }
    }
  }, [round]);
 return (jsx element);
}

My code works as expected, but I am wondering if there is any way to improve on it? Using if-else looks really ugly.

Note that you do the same thing if the array is empty or if the last item's localeDate doesn't match - you can combine those two paths.

You only want to update the existing object if the last item exists and its date matches, so I'd first set a flag for that, which can be done concisely via optional chaining.

Then, .map looks a bit verbose when all items of the array are unchanged except for one - you could consider using .slice instead to take all but the last item, spread them into a new array, then add the changed object as the last item.

useEffect(() => {
    // update item if date matches
    const changeExistingItem = data[data.length - 1]?.date === localeDate;
    const updatedData = changeExistingItem
        ? [...data.slice(0, data.length - 1), { ...data[data.length - 1], round }]
        : [...data, { round, date: localeDate }];
    setData(updatedData);
}, [round]);

Also see that you can use shorthand property names to keep things concise: { someProp: someProp simplifies to { someProp in modern Javascript.

As a side note: always use const to declare variables, whenever possible. When you use let, you're warning readers of the code that you may be reassigning that variable name in the future, which results in more cognitive overhead.


Crypto createCipheriv and createDecipheriv for authentication I'm not an expert in authentication, so I want to make sure I have done everything right.

I am using crypto.createCipheriv and crypto.createDecipheriv for authentication.

I will store the key in the database, and the initialization vector, IV, and encrypted data in cookies. When requested the server will try to decrypt encrypted data from cookies using the IV from the cookies and the key from the database. If the decryption is successful the request can proceed.

If the database is compromised, the hacker will not be able to use the database keys, because they will need the code to generate the IV and the data cookies.

The database key is the same for multiple sessions, only the IV and data are different.

Initial login conformation will be handled using external service, so I can focus on interacting with the cookies.

Are there problems with my solution?

import crypto from 'crypto'

function encrypt(dataToEncrypt /*random data*/) {
    let dbKey = crypto.randomBytes(32) //db
    let userKey = crypto.randomBytes(16) //cookie

    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(dbKey), userKey)
    let encryptedData = cipher.update(JSON.stringify(dataToEncrypt))
    encryptedData = Buffer.concat([encryptedData, cipher.final()])

    return { userKey: userKey.toString('hex'), dbKey: dbKey.toString('hex'), encryptedData: encryptedData.toString('hex') }
}

function decrypt(userProvidedKey, dbKey, dataToDecrypt) {
    let userKeyBuffer = Buffer.from(userProvidedKey, 'hex')
    let dbKeyBuffer = Buffer.from(dbKey, 'hex')

    let decryptedData = Buffer.from(dataToDecrypt, 'hex')
    let decipher = crypto.createDecipheriv('aes-256-cbc', dbKeyBuffer, userKeyBuffer)
    decryptedData = decipher.update(decryptedData)
    decryptedData = Buffer.concat([decryptedData, decipher.final()])

    return decryptedData.toString()
}

I am using crypto.createCipheriv and crypto.createDecipheriv for authentication.

Encryption is mainly used for providing confidentiality. You'd use a MAC (message authentication code) or authenticated encryption if you want authentication.

Note that CTR decryption always succeeds, even if it may result in incorrect ciphertext. CBC decryption succeeds 1 out of 256 times if PKCS#7 compatible padding is used (and it is) if random ciphertext is fed to it. Besides that, CBC is vulnerable to padding oracle attacks. Unauthenticated ciphertext is always vulnerable to plaintext oracle attacks.

Basically, you need a MAC (such as a HMAC over the IV and the ciphertext) or authenticated encryption.

GCM mode is provided by CryptoJS, if I'm not mistaken. GCM already authenticates the IV - but make sure it does authenticate the tag!

  I will store the key in the database, and the initialization vector, IV, and encrypted data in cookies.

I presume this is a textual error, as the initialization vector is the IV.

  If the database is compromised, the hacker will not be able to use the database keys, because they will need the code to generate the IV and the data cookies.

The IV should never be considered a secret. The data may of course be considered secret, but the algorithm to generate the data should not act as a key either (see Kerckhoff's principle).

  The database key is the same for multiple sessions, only the IV and data are different.

That's right, as long as you don't create millions of "messages" (in this case cookies). If you overextend the key you may want to create a different key (for instance using key derivation). Probably this is not a problem for you though.

Let's move to the code (which we now know is not secure).

function encrypt(dataToEncrypt /*random data*/) {

Random has a very specific meaning in cryptography, so I'd try and avoid that adjective, and use "any" instead. I'd simply document your functions, and not put inline comments in the code.

let dbKey = crypto.randomBytes(32) //db

Fine, although I would use 256 / 8, preferably with a constant KEY_SIZE = 256 for the key size.

Don't use end-of-line comments either, as refactoring will make them disappear behind the right margin or trigger a nasty text wrap in editors.

Where the key is stored is not within this method, so the comment should not be present in the final code.

 let userKey = crypto.randomBytes(16) //cookie

No! An IV is not a key, and - even if it was - only the first block of ciphertext cannot be decrypted without the IV in CBC mode. Again, at least use a constant like BLOCK_SIZE_BYTES = 16 or IV_SIZE_BYTES = 16.

let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(dbKey), userKey)

Wrong mode, but yeah.

let encryptedData = cipher.update(JSON.stringify(dataToEncrypt))

JSON-ify should be performed on a separate line. Now a significant operation is hidden inside another statement.

return { userKey: userKey.toString('hex'), dbKey: dbKey.toString('hex'), encryptedData: encryptedData.toString('hex') }

Ciphertext and keys are binary. I'd not stringify them unless strictly necessary. The IV and ciphertext may be concatenated and then converted to (URL-safe) base 64 to be more efficient than hex.

Skipping some lines to the final part of the decryption:

return decryptedData.toString()

That's no good, first you JSON-ify the input, and then you don't do the reverse during decryption. These methods should be symmetric. Either you take it out of encryption or you add it to decryption (if that's possible).


Game of Rock paper and scissors against a random bot I have to do a project on a game of rock, paper, and scissors, and the code I have so far is a complete code for the game, but my professor does not like it since it is too redundant. Is there anyway to shorten it or make it more simple?

import random

while True:
   bot = random.choice(["Rock", "Paper", "Scissors"]).lower()

   user_choice = input("Choose between Rock, Paper, and Scissors or -1 to exit: \n ").lower()
   if user_choice == bot:
      print("We tied! I chose", bot," and you chose", user_choice)
   elif user_choice == "rock":
      if bot == "paper":
         print("You lose! I chose", bot," and you chose", user_choice , ", Paper beats rock!")
      elif bot == "scissors":
       print("You win! I chose", bot," and you chose", user_choice , ", Rock beat scissors!")
   elif user_choice == "paper":
      if bot == "rock":
         print("You win! I chose",bot," and you chose", user_choice , ", Paper beats rock!")
      elif bot == "scissors:":
         print("You lose! I chose", bot," and you chose", user_choice , ", Scissors beats paper")
   elif user_choice == "scissors":
      if bot == "paper":
         print("You win! I chose", bot," and you chose",user_choice, ", Scissors beats paper")
      elif bot == "rock":
         print("You Lose! I chose", bot," and you chose", user_choice , ", Rock beats scissors")
   else:
      print("Invalid Entry, you typed:", user_choice, ", Please try again: ")

   if user_choice == '-1':
      print("You selected -1 to exit, Goodbye!")
exit()

Welcome to Code review. I want to start out by highlighting a few things that I like about this code.

One thing that I quite liked is handling the tie case first. It is often good to simplify logic as much as possible, and the tie case is a good spot of somewhere that you can simplify, rather than have three more elif lines.

It is also good to see handling of erroneous input from the user. This includes making minor corrections when it is clear what was intended: using the .lower() function to ensure that "Rock" and "rock" work the same. It also includes making clear to the user if they entered something from which you can't guess what they meant. In many ways the mark of a good programmer is how well they handle the unexpected.

There is a minor bug in that though: because the '-1' is after the else it will first complain that the input is invalid, and only then realise that it's the exit signal. (There is another minor bug in that it won't actually call exit() because it needs indenting in to the if, but I think that is probably just a copy paste error to codereview.)

Mast suggested in the comments that you really want to be using functions to help make the code less redundant. In general when you find yourself repeating things it is a good opportunity to think about using a function. For example before your while loop, have this function:

def print_win(bot, user_choice):
    print("You win! I chose",bot," and you chose", user_choice , ", ", user_choice, " beats ", bot, "!")

Then when you win, you can just use

print_win(bot, user_choice)

That way if you ever had to change the message (perhaps, say, to translate the program into another language) you could change all the win messages in one place.

You could also structure the program so that you separate out user input from the actual game, which also makes it easier to improve the game bit. If, for example, you had a function that tells you who won, then it would be easy to track a score over multiple rounds. With your set up, you'd have to update the score separately with every one of those ifs or elifs.


Convert a numeric string to number but without python's built in function I'd like to get a code review and some insights of whether I chose a good way to do this. What would other, clever ways look like.

"""
Convert numeric string to number withoutusing python's built in functions.
"""
dec_places = {6:100000, 5:10000, 4:1000, 3:100, 2:10, 1:1}
char_digit = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5,  '6':6, '7':7, '8':8,  '9':9}

def str2int(num_str):
    iter = len(num_str)
    number = 0
    for char in num_str:
        number += (char_digit[char] * dec_places[iter])
        iter -= 1
    return number

print(str2int('623297'))

Doctstrings

The docstring:

"""
Convert numeric string to number withoutusing python's built in functions.
"""

Should be at the top of the inside of the function.

(Also withoutusing should be without using.)

Global Variables

Global variables are typically a bad design practice. Move these:

dec_places = {6:100000, 5:10000, 4:1000, 3:100, 2:10, 1:1}
char_digit = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5,  '6':6, '7':7, '8':8,  '9':9}

Inside the function.

Function naming

str2int should be renamed to str_to_int.

Better algorithm

dec_places is unneeded and limits your algorithm significantly.

I would enumerate over the reversed of your string:

for ind, char in enumerate(reversed(num_str)):
    number += char_digit[char] * 10**(ind + 1)

enumerate takes an iterable and creates tuples of (0, el1), (1, el2) ....

We reverse the string and then multiply each character by the appropriate power of 10. This allows you to go beyond the 6th power.

Alternatively, you can keep an iter value that counts up from 1. I'll leave this as an exercise. It might be faster than using reversed. You should not need a dictionary though.


Querying the Google ads API I have a method which relies heavily on object supplied by third party APIs. Below is my working code, is there any scope of improvement?

public LineItem getLineItem(
      String networkId, String lineItemId) throws ApiException_Exception {
    LineItem lineItem = null;
    session.setCode(networkId);
    LineItemServiceInterface lineItemService = servicesInterface.lineItemService(dfpSession);
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("id = " + lineItemId.trim())
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    LineItemPage lineItemPage =
        lineItemService.getLineItemsByStatement(statementBuilder.toStatement());
    if (lineItemPage != null && lineItemPage.getResults() != null) {
      lineItem = lineItemPage.getResults().get(0);
    }
    return lineItem;
  }

Every type used above belongs to third party code. I also need to know the good strategy to handle exceptions?

Update 1

One frequent issue I encounter and I am sure many if us will is that there is usually references to the third party type LineItem is sprinkled everywhere in the code base. Is this a good practice to leave it like that or should I wrap that type into my own type and use that instead?

Reference code here.

SQL statement construction

Your third-party library do support bindings, so instead of .where("id = " + lineItemId.trim()), you should consider:

//  .where("id = " + lineItemId.trim())
    .where("id = :lineItem")
    .withBindVariableValue("lineItem", lineItemId.trim());

Early variable assignment

LineItem lineItem = null;
// ...
if (/* ... */) {
    lineItem = /* ... */;
}
return lineItem;

You usually should not need to declare the return result right at the start, perform the optional assignment, and then return from the method. You should just return below, without needing the lineItem variable:

// ...
if (/* ... */ ) {
    return /* ... */;
}
return null;


Code to convert number to words I am trying to practice objects and functions (specifically closures & higher order functions) in javascript. There is no specific reason why I chose this program but it struck my mind to work out this one.

The below code is available at my Github and it converts the number to words.

Kindly provide your feedback and suggest which parts of the code can be improved or modified.

// Author       : Harish Narayanan
// Date         : 15 May 2015
// Description  : Code to convert number to words

var ones_teens = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
  'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
var tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
var scales = ['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion',
  'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion'
];

function toWords(n) {
  var line;
  if (isNaN(n) || n > 999) {
    return null;
  }

  if (n == 0) {
    line = "";
  } else if (n < 20) {
    line = ones_teens[n];
  } else if (n < 100) {
    line = tens[(n / 10) | 0];
    if (n % 10) {
      line += "-" + ones_teens[n % 10];
    }
  } else {
    line = ones_teens[(n / 100) | 0] + " hundred " + toWords(n % 100);
  }

  return line.trim();
}

function chunkify(n) {
  var numbers = [];
  while (n > 0) {
    numbers[numbers.length] = n % 1000;
    n = Math.floor(n / 1000);
  }
  return numbers;
}

function scalify(item, index) {
  if (item) {
    return item + " " + scales[index];
  }
  return "";
}

function notEmpty(item) {
  return !!item; // using double ! returns boolean value. !!item is not same as item.
}

console.log(chunkify(999999999999999).map(toWords).map(scalify).filter(notEmpty).reverse().join(", "));

Really not much to review, here. I think you did a pretty good job. There are a few points I'd like to make, though:

Indents in Javascript (at least as far as I've seen) are four spaces, not two.
When you're continuing a line, you indent twice; this applies to things like where you defined scales.
Use || in place of | wherever possible. Functionally identicaly, but it's a free little performance boost at no cost. Oops! turns out that's wrong. Thanks to @Flambino for pointing that out. I was just thinking in terms of logical operators, not bitwise ones. However, I would recommend using Math.floor instead of it; it's clearer.
Rather than using array[array.length] = ..., use array.push(...). Much cleaner.
You never seem to handle negative numbers. See below for how you could do that without changing lots of your code.

One big point: Your toWords function should do everything itself. You shouldn't have to call chunkify, then map, then map again, then filter, etc. etc. Wrap all that in a function and you'll be golden. Plus, that lets you do fancy stuff like handle negative numbers -- for example, this (should) do the trick:

function toWords(n) {
    var asString =  chunkify(n).map(toWords).map(scalify).filter(notEmpty).reverse().join(", ");
    if (n < 0) {
        asString = "negative " + asString;
    }
    return asString
}

Anyway, that's about it! Nicely written.


Small graph API to track vertices and edges added to graph I'm working on my Scala chops and implemented a small graph API to track vertices and edges added to graph. I have basic GraphLike Trait, and have an Undirected Graph class ( UnDiGraph) and a Directed graph class (DiGraph ) that extend the GraphLike trait.

Here is some of the listing:

trait GraphLike[T] {
    val vertices: Map[T, VertexLike[T]]
    def addEdge( a:T, b:T ): GraphLike[T]
    def addVertex( t:T ): GraphLike[T]
    def addVertex( vert: VertexLike[T] ): GraphLike[T]
    def adjacency( t:T ): Option[ List[T] ]  =
    {
      if ( vertices contains t )
        Some( vertices(t).adjList )
      else
        None
    }
    def vertNum: Integer = vertices size
    def edgeNum: Integer =
    {
      def summer( sum: Integer, ms: Map[T, VertexLike[T] ] ): Integer =
      {
        if ( ms.isEmpty )
          sum
        else
          summer( sum + ms.head._2.adjList.size, ms.tail )
      }
      summer( 0, vertices )
    }
    def getVertex( t: T ): VertexLike[T] =
    {
      vertices( t )
    }
    def edgeExists( a:T, b:T ): Boolean =
    {
      try
      {
          if( vertices( a ).adjList contains b )
            true
          else
            false
      }catch {
        case ex: NoSuchElementException => false
      }
    }
}

Here's what the DiGraph looks like:

class DiGraph[T](val vertices: Map[ T, VertexLike[ T ] ] = Map.empty ) extends GraphLike[T] {
    def makeVertex( t:T ): VertexLike[T] = new Vertex( t )

    def addEdge( a:T, b:T ): GraphLike[T] =
    {
      //Make sure vertices exist
      if( edgeExists(a, b) )
        this
      else {
        try {
          vertices(b)
          vertices(a)
        } catch {
          case ex: NoSuchElementException => println("Vertices not Found"); this
        }
        addVertex( vertices( a ) + b )
      }
    }
    def addVertex( t:T ): DiGraph[T] =
    {
      if( vertices contains t ) this
      else
      new DiGraph[T]( vertices + ( t -> makeVertex(t) ) )
    }
    def addVertex( vert: VertexLike[T] ): DiGraph[T] =
    {
      new DiGraph[T]( vertices + ( vert.apply -> vert ) )
    }
}

Vertices are stored in a Map going from type T to VertexLike[T]. VertexLike basically holds an adjacency list for the specific Vertex.

Here's what VertexLike looks like:

trait VertexLike[T]
{
  def addEdgeTo( dest: T ): VertexLike[T]
  def adjList: List[T]
  def +( dest: T) = addEdgeTo(dest)
  def apply: T
}

class Vertex[T](t: T, adj: List[T] = List() ) extends VertexLike[T]
{
    def apply() = t
    def adjList = adj
    def addEdgeTo( dest: T ) =
      if( adjList contains dest )
        this
      else
        new Vertex[T]( t, dest :: adjList )
}

(Yes, I realize the apply method in the class is useless and it only works on objects.  I realized that a little later).

Anyways, I have a sample graph where I have about 80,000 vertices. Adding the vertices to the Graph is taking just way too long. I tried to do things functionally and in an immutable way. Whenever you add a vertex or an edge to a graph, you get a new graph (I tried to make sure the constructors of the graph types weren't doing much). This is the client code that I use to create my graph from my data.

def GraphInstantiater: GraphLike[Int] =
{
  println( "Total number of Vertices: " + synMap.keys.size )
  def vertexAdder( ls: Iterable[Int], graph:GraphLike[Int] ): GraphLike[Int] =
    if( ls.isEmpty) graph else vertexAdder( ls.tail, graph.addVertex( ls.head ) )

  val gr = vertexAdder( synMap.keys, new DiGraph[Int]( Map() ) )
  println( "Vertices added. Total: %d".format( gr.vertices.size ) )
  gr
}

I know constructing new graphs will take cycles but is it really all that great given that I'm not doing much in the constructors. Would repeatedly creating the Map of vertices keep causing problems (it's one of the parameters of the graph class). Any ideas on what the bottlenecks are in this method would be much appreciated.

Oh wow... I figured out what was going on. In the GraphInstantiater method, the very first call which passes synMap.keys, keys returns an iterable[Int]. Looks like taking tail on this is a long process, most likely going through the whole set of keys each time.

changing the call to

val gr = vertexAdder( synMap.keys.toList, new DiGraph[Int]( Map() ) )

made everything go faster. Does anyone know what is the underlying implementation of the container returned when you call keys on a Map ?


Finding legal knight moves in a chessboard in APL (follow-up) This question is a follow-up to this previous question of mine. Assuming I understood correctly what is outlined in this meta post.

I wrote (and now, re-wrote) a function that takes as input a vector with two integers between 1 and 8 representing a position in a chessboard. This function should output a vector where each cell is a similar vector of integers, with the positions that a knight in the input position could reach.

E.g. for the input 1 1, my function should output (2 3)(3 2).

KnightMovesRevised ← {
  ⍝ Monadic function, expects a vector with 2 integers, e.g. (1 1)
  ⍝ Given a chessboard position, find the legal knight moves.
  ⍝ Returns vector of 2-integer vectors, e.g. (2 3)(3 2)

  ⍝ aux train to check if position is inside chessboard
  isInsideBoard ← ∧/(1∘≤∧≤∘8)

  signs ← ¯1 1 ∘., ¯1 1
  offsets ← (1 2)(2 1)
  moves ← , signs ∘.× offsets
  ⍝ list all the locations the knight could go to
  locations ← moves + ⊂⍵
  ⍝ and keep the valid ones
  valid ← isInsideBoard¨ locations
  valid/locations
}

Changes

From the previous version to this one, I

Reformatted code a bit with a suggested naming convention, by naming an auxiliary train and adding a couple more comments;
Removed the train used to write offsets, which I had used just to give a go at tacit programming. This is such a small vector that I think it makes more sense to hardcode it;
Rewrote signs by writing twice the ¯1 1 and removing ,, ⍨. This made it slightly easier to digest and not much more annoying to type;

These changes were motivated by the two great reviews I got (here and here) and I was hoping I could get reviews on those changes, because I tried to adhere to their suggestions but I didn't necessarily agree with all of them.

Questions

(paired with the above)

Are the extra comments ok or are they too much?
Are signs and offsets defined in an acceptable way? I like the trade-off between hardcoding too much and using too many functions just to create a couple of constants.
What is the standard spacing notation around ¨? Should I write f¨ arg, f ¨ arg, f ¨arg or f¨arg?

On your previous version you commented, "This works and gives the expected result for a series of test cases." But you never provided those test cases, right? I think the biggest thing missing here is test cases. Especially since test cases would quickly clarify the expected behavior of the function on weird inputs, and then you could maybe even get rid of some of the vague comments like

expects a vector with 2 integers, e.g. (1 1)

I infer that the two integers are supposed to be in the range 1..8 (not 0..7 as one might expect if one'd been doing too much programming lately and not enough chess). What happens when they're not in the range 1..8?
What happens when there are three integers in the vector, or one, or none?
What happens when there's something other than integers in the vector?

I know you split out isInsideBoard into its own named function thanks to a comment on the earlier question; but if it's only ever used once, is that buying you anything? Honestly, as not-really-an-APLer-myself, ∧/(1∘≤∧≤∘8) is pretty much the only part of that code that I could instantly understand!

If I understand correctly, the output of KnightMovesRevised is a vector each of whose elements is suitable for feeding back into KnightMovesRevised; is that right? If so, that's good! You could even write a test case demonstrating how to find the number of cells that are exactly 2 knight-moves away from (1,1).


Getting Facebook app requests I have a JSON response from the Facebook API, which contains the app requests of certain Facebook apps via FB.API('/me/apprequests') (using Graph API 2.0, Facebook SDK for Unity 6.0).

There are 3 things I want to collect from the requests:

The response data (a JSON string)
A texture (in Texture2D class)
Status of loading texture (in bool)

Here is how I achieve it:

private Dictionary<int, JsonData> requestData;
private Dictionary<int, bool> requestLoadStatus;
private Dictionary<int, Texture2D> requestTexture;

void Start() {
    loaded = false;
    requests = new ArrayList();
    requestData = new Dictionary<int, JsonData>();
    requestLoadStatus = new Dictionary<int, bool>();
    requestTexture = new Dictionary<int, Texture2D>();
    GetFriendRequests();
}

protected void GetFriendRequests() {
    if(FB.IsInitialized) {
        FB.API("/me/apprequests", Facebook.HttpMethod.GET, GetFriendRequestsCallback);
    } else {
        InitFacebook();
    }
}

private void GetFriendRequestsCallback(FBResult result) {
    if(result != null) {
        if (!String.IsNullOrEmpty(result.Error)) {
            // Failed Case
            lastResponse = "Get Friend Request Callback: Error Response:\n" + result.Error;
        } else if (!String.IsNullOrEmpty(result.Text)) {
            // Success Case
            lastResponse = "Get Friend Request Callback: Success Response:\n" + result.Text;
            JsonData datas = JsonMapper.ToObject(result.Text);
            Debug.Log(datas["data"]);
            for(int i = 0; i < datas["data"].Count; i++) {
                requestData.Add(i, JsonMapper.ToObject((string)datas["data"][i]));
                requestLoadStatus.Add(i, false);
                requestTexture.Add(i, new Texture2D(50, 50));
                StartCoroutine(LoadUserProfilePic(i));
            }
        }
        Debug.Log(lastResponse);
    } else {
        Debug.Log("Get Friend Request Callback: Response is empty");
    }
}

Where InitFacebook() is simply calling FB.Init(). Note that I used LitJson as a JSON parser.

How can I simplify this code? Using 3 Dictionarys seems to be clumsy. Will there be a benefit if I use a custom class to wrap them?

Design

Try to put as little code as possible in your Start(), Awake() etc. methods. Have those methods call other methods. The reasoning is very similar to the reason behind avoiding code in the code-behind of WinForms or WPF applications. It seems like you could initialize those variables in the GetFriendRequests method.

In your if statements, it is common to put the most-expected outcome first, and put the edge case in the else. In your case, a success case is more accepted than a failure, so put that first.

So

    if (!String.IsNullOrEmpty(result.Error)) {
        // Failed Case
        lastResponse = "Get Friend Request Callback: Error Response:\n" + result.Error;
    } else if (!String.IsNullOrEmpty(result.Text)) {
        // Success Case
        lastResponse = "Get Friend Request Callback: Success Response:\n" + result.Text;
        JsonData datas = JsonMapper.ToObject(result.Text);
        Debug.Log(datas["data"]);
        for(int i = 0; i < datas["data"].Count; i++) {
            requestData.Add(i, JsonMapper.ToObject((string)datas["data"][i]));
            requestLoadStatus.Add(i, false);
            requestTexture.Add(i, new Texture2D(50, 50));
            StartCoroutine(LoadUserProfilePic(i));
        }
    }

should be:

    if (!String.IsNullOrEmpty(result.Text)) {
        // Success Case
        lastResponse = "Get Friend Request Callback: Success Response:\n" + result.Text;
        JsonData datas = JsonMapper.ToObject(result.Text);
        Debug.Log(datas["data"]);
        for(int i = 0; i < datas["data"].Count; i++) {
            requestData.Add(i, JsonMapper.ToObject((string)datas["data"][i]));
            requestLoadStatus.Add(i, false);
            requestTexture.Add(i, new Texture2D(50, 50));
            StartCoroutine(LoadUserProfilePic(i));
        }
    } else if (String.IsNullOrEmpty(result.Error)) {
        // Failed Case
        lastResponse = "Get Friend Request Callback: Error Response:\n" + result.Error;

    }

Spacing

You're cramping your code together and making it much harder to read. Spread it out a bit and things will look a lot less cluttered and complex.

e.g

protected void GetFriendRequests() {
    if(FB.IsInitialized) {
        FB.API("/me/apprequests", Facebook.HttpMethod.GET, GetFriendRequestsCallback);
    } else {
        InitFacebook();
    }
}

Is easier to read as:

protected void GetFriendRequests()
{
    if(FB.IsInitialized)
    {
        FB.API("/me/apprequests", Facebook.HttpMethod.GET, GetFriendRequestsCallback);
    }
    else
    {
        InitFacebook();
    }
}

I know the condensed form is how MonoDevelop decides to do bracing by default, which AFAIK is the Java style, but I prefer the expanded style for ease of reading, and it is the more common of the C# styles.

Secondly, it often helps to add breathing room around clauses in your code that use curly braces.

e.g.

        // Success Case
        lastResponse = "Get Friend Request Callback: Success Response:\n" + result.Text;
        JsonData datas = JsonMapper.ToObject(result.Text);
        Debug.Log(datas["data"]);
        for(int i = 0; i < datas["data"].Count; i++)
        {
            requestData.Add(i, JsonMapper.ToObject((string)datas["data"][i]));
            requestLoadStatus.Add(i, false);
            requestTexture.Add(i, new Texture2D(50, 50));
            StartCoroutine(LoadUserProfilePic(i));
        }

Looks easier to read as:

        // Success Case
        lastResponse = "Get Friend Request Callback: Success Response:\n" + result.Text;
        JsonData datas = JsonMapper.ToObject(result.Text);
        Debug.Log(datas["data"]);

        for(int i = 0; i < datas["data"].Count; i++)
        {
            requestData.Add(i, JsonMapper.ToObject((string)datas["data"][i]));
            requestLoadStatus.Add(i, false);
            requestTexture.Add(i, new Texture2D(50, 50));
            StartCoroutine(LoadUserProfilePic(i));
        }

Magic Variables

You're using magic variables in your code. Refactor these out as constants or static readonly variables.

e.g.

protected void GetFriendRequests()
{
    if(FB.IsInitialized)
    {
        FB.API("/me/apprequests", Facebook.HttpMethod.GET, GetFriendRequestsCallback);
    }
    else
    {
        InitFacebook();
    }
}

Should be:

private const string FacebookApiURL = "/me/apprequests";

protected void GetFriendRequests()
{
    if(FB.IsInitialized)
    {
        FB.API(FacebookApiURL, Facebook.HttpMethod.GET, GetFriendRequestsCallback);
    }
    else
    {
        InitFacebook();
    }
}

The reason you should do this is that if re-read the code it is more obvious what "/me/apprequests" means, which is invaluable when performing maintenance on year-old code.

Testing

Lastly, I am concerned by the heavy quantity of Debug.Log calls. I hope you're not testing your methods by writing status updates to the log, and are instead doing this so you can remain informed. If you are testing this way, stop right now. It's intensely inefficient, and Unity have released a free set of libraries for unit and integration tests that work very well with the engine.


"Flipping bits" Python implementation Problem Statement

  You will be given a list of 32 bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset).

Input Format

  The first line of the input contains the list size T, which is followed by T lines, each line having an integer from the list.

Constraints

  \$1≤T≤100\$

  \$0≤integer<2^{32}\$

Output Format

  Output one line per element from the list with the requested result.

Solution

for _ in range(int(raw_input())):
    N = int(raw_input())
    N = N & 0xffffffff # 32 bit representation
    print N ^ 0xffffffff

Hint: https://stackoverflow.com/a/16745422/4260745

There's not much to review; that said, the input is guaranteed to be
between zero and \$2^{32}\$, so there is no point to the N & 0xffffffff really.  Also the print statement would be more upwards
compatible with Python 3 if it was used like a function,
i.e. print(...).


Run query and insert the result to another table import csv
import logging
import itertools
from random import choice
from string import ascii_lowercase
from collections import namedtuple
from tempfile import NamedTemporaryFile

DELIMITER = '\t'
ENCODING = 'utf-8'

def get_random_cursor_name(length=7):
    return ''.join(choice(ascii_lowercase) for i in range(length))

def extract_table(conn, query, itersize=2000, use_named_cursor=True):
    """
    :type conn: psycopg2.connection
    :param conn: connection object returned by psycopg2.connect.

    :type query: string
    :param query: SQL query string.

    :type itersize: int
    :param itersize: If itersize == -1, then fetchall, else fetchmany(itersize)

    :type use_named_cursor: boolean
    :param use_named_cursor: If true, then use server side cursor, else client side cursor.
    """

    if use_named_cursor:
        cursor_name = get_random_cursor_name()
        with conn.cursor(cursor_name) as cursor:
            cursor.itersize = 2000 if itersize == -1 else itersize
            cursor.execute(query)
            row = cursor.fetchone()

            header = [desc[0] for desc in cursor.description]
            Row = namedtuple('Row', header)

            yield Row(*row)
            for row in cursor:
                yield Row(*row)
    else:
        with conn.cursor() as cursor:
            cursor.execute(query)
            header = [desc[0] for desc in cursor.description]
            Row = namedtuple('Row', header)
            if itersize == -1:
                rows = cursor.fetchall()
            else:
                cursor.arraysize = itersize
                rows = itertools.chain.from_iterable(iter(cursor.fetchmany, []))

            for row in rows:
                yield Row(*row)

def copy_table(src_conn, dst_conn, src_query, dst_table_name, use_named_cursor=False, truncate_table=False):
    """
    Run query and import result to another database.

    We use null="" in copy_from, because csv library dumps None as "" (empty string).

    :type src_conn: psycopg2.connection
    :param src_conn: Source database connection.

    :type dst_conn: psycopg2.connection
    :param dst_conn: Destination database connection.

    :type src_query: string
    :param src_query: Query to be executed on source database.

    :type dst_table_name: string
    :param dst_table_name: Table name in destination database.
    """
    rows = extract_table(src_conn, src_query, use_named_cursor=use_named_cursor)
    with NamedTemporaryFile('w+t', encoding=ENCODING, newline='') as fp, dst_conn.cursor() as cursor:
        logging.info("Writing result to a temporary file.")
        csv.writer(fp, delimiter=DELIMITER).writerows(rows)
        fp.flush()
        fp.seek(0)

        if truncate_table:
            logging.info("Truncating {}.".format(dst_table_name))
            cursor.execute('TRUNCATE {};'.format(dst_table_name))
        logging.info("Copying result to {}".format(dst_table_name))
        cursor.copy_from(file=fp, table=dst_table_name, sep=DELIMITER, null="")
    dst_conn.commit()

This code, in particular copy_table, is used to run a query, write the result to a temporary CSV file and copy the result to a table.

An example of the usage is as follows:

Let's say you want to copy a subset of the table public.my_table in DB1 to DB2.

import psycopg2
import credentials

src_conn = psycopg2.connect(
    database=credentials.DB1_DB,
    user=credentials.DB1_USER,
    password=credentials.DB1_PASS,
    host=credentials.DB1_HOST,
    port=credentials.DB1_PORT
)

dst_conn = psycopg2.connect(
    database=credentials.DB2_DB,
    user=credentials.DB2_USER,
    password=credentials.DB2_PASS,
    host=credentials.DB2_HOST,
    port=credentials.DB2_PORT
)

query = 'SELECT * FROM public.my_table where product_count > 200'

copy_table(src_conn, dst_conn, src_query=query, dst_table_name='public.my_table_subset')

How could I write this code to be more Pythonic?

Note that I'm using Python 3.5.

psycopg2 already implements your extract_table

Since you're using cursor.copy_from to load data into the new table, why not use something along the lines of cursor.copy_to to write them to a file?

However, cursor.copy_to will translate to COPY table_name TO 'filename' [ [ WITH ] ( option [, ...] ) ] in its current implementation. You thus need to use cursor.copy_expert and provide the whole SQL query to be executed.

The copy_expert call will write to STDOUT or read from STDIN and redirect to/from the file-like object passed as the second argument (file). I believe the query to execute should look like

copy_query = "COPY (" + query + ")"\
    "TO STDOUT"\
    "WITH CSV HEADER DELIMITER '\t' NULL '' ENCODING 'utf-8'"

with or without the HEADER option; not sure how copy_from would handle it.

You can thus rewrite copy_table something along the lines of:

# Using format string because we trust the query, are we?
copy_query = "COPY ({}) TO STDOUT WITH CSV HEADER DELIMITER '{}' NULL '' ENCODING '{}'".format(src_query, DELIMITER, ENCODING)
with NamedTemporaryFile('w+t', encoding=ENCODING, newline='') as fp:
    logging.info("Writing result to a temporary file.")
    with src_conn.cursor() as cursor:
        cursor.copy_expert(copy_query, fp)
    fp.flush()
    fp.seek(0)
    logging.info("Copying result to {}".format(dst_table_name))
    with dst_conn.cursor() as cursor:
        if truncate_table:
            logging.info("Truncating {}.".format(dst_table_name))
            # It seems like we do trust the new name too
            cursor.execute('TRUNCATE {};'.format(dst_table_name))
        cursor.copy_from(file=fp, table=dst_table_name, sep=DELIMITER, null="")
    dst_conn.commit()

Handling database state

The dst_conn.commit() at the end of copy_table is bad practice. You most likely want to use the context manager available on connection objects to handle that for you, especially if things goes wrong.

Using the connection's context manager is to handle commits and rollbacks only and does not close the connection when leaving the context block. So you can write, say

conn = psycopg2.connect(...)

with conn:
    # Use cursor(s)

with conn:
    # Use (other) cursor(s)

with conn:
    # You get the deal

conn.close()

You're also handling the creation of named cursors using lot of duplicated code. I understand that their use differ a bit from client cursors, but the creation can be simplified to:

cursor = conn.cursor(name=get_random_cursor_name() if use_named_cursor else None)

since the name argument is already None by default.

You can even go further by letting the user provide its own name using constructs such as:

def copy_table(..., cursor_name=None, ...):
    ...
    with src_conn:
        with src_conn.cursor(name=cursor_name) as cursor:
            ...

This way, you can have calls such as:

copy_table(src_conn, dst_conn, query, dst_table_name='foobar')
copy_table(src_conn, dst_conn, query, cursor_name='foobar', dst_table_name='foobar')
copy_table(src_conn, dst_conn, query, cursor_name=get_random_cursor_name(17), dst_table_name='foobar')

Protect from user input

As usual in SQL, you should not trust user input. As such, you might want to not directly use the provided query string. However you do want to build the copy query yourself. For these usages, psycopg2 provides the cursor.mogrify method.

The copy query can thus be built using:

copy_query = "COPY (%s) TO STDOUT WITH CSV HEADER DELIMITER '%s' NULL '' ENCODING '%s'"

and then passed to copy_expert with:

cursor.copy_expert(cursor.mogrify(copy_query, (src_query, DELIMITER, ENCODING)), fp)

You may also be interested in providing a way to build the source query by binding parameters. In such cases, variable length arguments can be used to simplify handling of bound arguments:

def copy_table(query, *args, src_conn, dest_conn, dest_table_name,
               cursor_name=None, truncate_table=False):
    copy_query = "COPY (%s) TO STDOUT WITH CSV HEADER DELIMITER '%s' NULL '' ENCODING '%s'"
    with NamedTemporaryFile('w+t', encoding=ENCODING, newline='') as fp:
        logging.info("Writing result to a temporary file.")
        with src_conn:
            with src_conn.cursor(name=cursor_name) as cursor:
                query = cursor.mogrify(query, args)
                copy_query = cursor.mogrify(copy_query, (query, DELIMITER, ENCODING))
                cursor.copy_expert(copy_query, fp)
        fp.flush()
        fp.seek(0)
        logging.info("Copying result to {}".format(dst_table_name))
        with dest_conn:
            with dest_conn.cursor() as cursor:
                if truncate_table:
                    logging.info("Truncating {}.".format(dst_table_name))
                    cursor.execute('TRUNCATE %s;', (dst_table_name,))
                cursor.copy_from(file=fp, table=dst_table_name, sep=DELIMITER, null="")

You will need to use named arguments for anything other than the query and its parameters:

copy_table('SELECT * FROM public.my_table WHERE product_count > %s', 200,
           src_conn=database_remote,
           dest_conn=database_local,
           dest_table_name='public.my_table_subset',
           cursor_name='foobar')


std::sort custom compare function I'm trying to solve the problem given here.

Arrange given numbers to form the biggest number | Set 1
Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are > {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. And if the given numbers are {1, 34, 3, 98, 9, > 76, 45, 4}, then the arrangement 998764543431 gives the largest value.
A simple solution that comes to our mind is to sort all numbers in descending order, but simply sorting doesn’t work. > For example, 548 is greater than 60, but in output 60 comes before 548. As a second example, 98 is greater than 9, but > 9 comes before 98 in output.
So how do we go about it? The idea is to use any comparison based sorting algorithm.
In the used sorting algorithm, instead of using the default comparison, write a comparison function myCompare() and use > it to sort numbers.
Given two numbers X and Y, how should myCompare() decide which number to put first – we compare two numbers XY (Y > appended at the end of X) and YX (X appended at the end of Y). If XY is larger, then X should come before Y in output, > else Y should come before. For example, let X and Y be 542 and 60. To compare X and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put Y first.
Following is the implementation of the above approach.
To keep the code simple, numbers are considered as strings, the vector is used instead of a normal array.

I'm getting the required output but the written code looks like code bloat(I mean could've have written better simpler and easy code). Can somebody suggest a better way of doing it. This is my code
#include <iostream>
#include <string>
#include <algorithm>

bool comp(const int32_t ia, const int32_t ib) {
    const std::string a = std::to_string(ia);
    const std::string b = std::to_string(ib);

    int32_t i = 0;
    if (a.size() == b.size()) {
        while (i < a.size()) {
            if (a.at(i) == b.at(i)) {
                ++i;

                continue;
            }
            else if (a.at(i) > b.at(i))
                return true;
            else
                return false;
        }
    } else {
        int32_t min_size = static_cast<int32_t>(std::min(a.size(), b.size()));
        int32_t max_size = static_cast<int32_t>(std::max(a.size(), b.size()));

        while (i < min_size) {
            if (a.at(i) == b.at(i)) {
                ++i;

                continue;
            }
            else if (a.at(i) > b.at(i))
                return true;
            else
                return false;
        }

        const char temp = a.at(0);
        const std::string& max_str = (a.size() > b.size()) ? a : b;
        if (max_str == b) {
            while (i < max_size) {
                if (temp >= max_str.at(i++))
                    return true;
                else
                    return false;
            }
        } else {
            while (i < max_size) {
                if (temp >= max_str.at(i++))
                    return false;
                else
                    return true;
            }
        }
    }
}

int32_t main() {
    int32_t arr[] = { 546, 548, 54, 60 };
    int32_t arr_size = sizeof(arr) / sizeof(*arr);

    std::sort(arr, arr + arr_size, comp);
    for (const int val : arr)
        std::cout << val;
    std::cout << std::endl;

    return 0;
}

The code is broken
Before asking “can this code be sexier”, you should be asking “does this code work”.
Spoiler: it doesn’t.
Always test your code
You have written a function comp(a, b). You haven’t written any tests for it. You’ve used it in a single case and got the correct answer, but that means very little.
At the bare minimum, you should have a test suite that has two test cases: one for when a and b are equal, and one for when they are not.
For example, for the “equal” test case, you can just generate bunch of random numbers between 0 and some maximum. Here’s what that might look like using the Catch2 test framework:
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"

#include <cstdint> // need for std::size_t, std::uint32_t
#include <limits>

// include the header with comp() declared

TEST_CASE("comparing equal")
{
    constexpr auto num_trials = std::size_t{10};

    constexpr auto min_val = std::int32_t{0};
    constexpr auto max_val = std::numeric_limits<std::int32_t>::max();

    auto value = GENERATE(take(num_trials, random(min_val, max_val)));

    INFO("value = " << value);
    CHECK_FALSE(comp(value, value)); // value cannot be less-than itself
}

This compiles (with warnings, more on that later), and runs, and all tests pass. That’s what happened for me, anyway. You may or may not get all tests passing, because there is a critical bug in your code. We’ll get back to that in the next section, but for now, I’ll just assume all tests passed.
So now for the “unequal” test case, you just list a bunch of pairs of numbers, where the first number should always compare less-than the second:
TEST_CASE("comparing unequal")
{
    auto data = GENERATE(table<std::uint32_t, std::uint32_t>({
        // single digit numbers
        {1, 0},
        {9, 0},
        {9, 8},
        // ... etc.
        // multi-digit numbers
        {111, 110},
        {124, 123},
        {130, 120},
        {130, 129},
        {200, 100},
        {200, 109},
        {200, 190},
        {200, 199},
        // ... etc.
        // other interesting cases, add as many as you please

        {1, 110}, // this works, but...
        {112, 1}, // try this one!

        {321, 3212}, // okay...
        {3214, 321}, // ... also okay...
        {3213, 321}, // ... but uh-oh!
    }));

    INFO("a = " << std::get<0>(data));
    INFO("b = " << std::get<1>(data));

    CHECK(comp(std::get<0>(data), std::get<1>(data)));

    CHECK_FALSE(comp(std::get<1>(data), std::get<0>(data)));
}

Again, compile and run. This time, there are failures.
Why does those cases fail? I’ll explain later, but for now I’ll just say that your algorithm will fail for some cases where one number is <pattern>, and the second number is <pattern>D<something> where the digit D is the same as the first digit of the pattern. For example, 545 and 54 (the former should come first, to get 54554, rather than 54545) would fail, but 565 and 56 work (56556 is less than 56565).
This is why we write tests.
Turn on warnings
If you compile with g++ or clang (and probably any other compiler), and turn warnings on… which you always should… you will get a warning like this:
warning: control reaches end of non-void function [-Wreturn-type]

(I actually get two warnings, and both matter, but the second isn’t as critical, because you’re only going to be dealing with small sizes. I’ll mention it later, though.)
What that warning is telling is you that you have a function—comp()—that returns something—something that is not void—but somehow it is possible to reach the end of the function—the closing }—without returning a value.
We can figure out exactly what is going on later, but for now, let’s hack a nasty little fix to shut the warning up. At the very end of comp(), right before the closing brace, add the following two lines:

    std::cerr << "you have a bug!" <<
        "\n    a = " << ia <<
        "\n    b = " << ib <<
        '\n';
    return false;

If the compiler is right, and if it is possible to get to the end of this function without returning a value, this will display an error message, and then just return false. So compile the test code again, and run it and…
… you get the same results as before… but now there are 10 messages in the output:
you have a bug!
    a = 1867888929
    b = 1867888929
you have a bug!
    a = 1276619030
    b = 1276619030
you have a bug!
    a = 1911218783
    b = 1911218783
... [ and so on ]

(The random numbers will be different, of course, but the pattern—the same number appearing for both a and b—will be the same.)
The compiler was right. You have a bug.
Looking at the messages printed, it seems to only happen when a equals b. Before we caught the bug, the function was just returning gibberish whenever a and b were equal… but you didn’t notice, because it didn’t matter to the algorithm (and also because you didn’t test), because when a and b are equal, the function could either return true or false and it makes no difference. It is undefined behaviour, and just happens to “work” on my platform (and probably yours, but who’s to say, because you didn’t test)… but on other platforms, anything could happen.
This is why we turn on warnings, and fix them.
Summary
Although your code appeared to be working, writing some tests and turning on warnings revealed:

There are cases where it fails.
Even when it appears to work, there is dangerous undefined behaviour.

You should always write tests to test your code; oftentimes it will blow your mind how it can fail in surprising and unexpected ways.
You should also always turn on all warnings, and then fix them. Some people even recommend turning warnings into errors, so that even a single warning will kill the compile. That’s not bad advice.
Code review
General issues
Overall, the biggest issue with your code is that it is—as you suspected—wildly overcomplicated. It is so ridiculously overcomplicated, that at least two expert level C++ programmers looked at your code and missed critical bugs, and/or failed to understand what was actually going on. (And I’m not even counting myself; I probably missed stuff, too.) That should be a sign.
There are two general rules that would make a HUGE difference:

Break up complicated functions into simpler ones. There are multiple parts of comp() that really should be broken out into separate functions. You have 4 loops in comp(); 1 is the max you should aim for… and even that might be too much, because of the second rule.
Avoid writing loops. If you find yourself writing a loop, stop… think about what you’re actually trying to do… it’s probably some standard algorithm. In that case, use that algorithm.

The second rule is really the most important, because when you stop yourself from writing naked loops and think in terms of algorithms instead:

Your code becomes easier to understand. std::mismatch(a.begin(), a.begin() + min_size, b.begin(), b.begin() + min_size) is already complicated, but I can still tell at a glance roughly what’s going on much easier than I can with a manual loop.
Complications are easier to spot. It is trivial to spot the difference between std::mismatch(p, p + max_str.size(), max_str.begin(), max_str.end()) and std::mismatch(max_str.begin(), max_str.end(), p, p + max_str.size()). Spotting the difference between those two loops? Not so much.
Mistakes are easier to spot. That first loop is just return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());. But because of the complexity of the loop, you didn’t realize you’d failed to account for the situation where the two strings are equal, and you get to the end of the loop without returning anything.
Especially when dealing with standard algorithms, they’re already tested and optimized. You can almost never beat them without serious sorcery (and even then, often not).

Review
bool comp(const int32_t ia, const int32_t ib)

You use int32_t throughout, but there are two problems with that.

First, it’s not int32_t. It’s std::int32_t, and you have to include <cstdint>. The reason it appears to work for you is probably that you’re using a C++ compiler/library that also doubles as a C compiler/library, and they just include int32_t without the std:: to be lazy. But it’s not guaranteed to work everywhere.
Second, int32_t is not portable in any case. All the fixed-width types are platform dependent. The moment you use one, you make your code less portable. And in this case, there’s no reason whatsoever for using one.

There’s absolutely no reason to use int32_t and not int. Using the wrong type breaks your code in some places (like returning it from main()).  Where it doesn’t, it just makes your code unnecessarily unportable.
const std::string a = std::to_string(ia);
const std::string b = std::to_string(ib);

While these work fine, they’re unnecessarily inefficient. You already know the maximum size string you’ll need, and you know that both ia and ib should be greater than or equal to zero. You could use arrays and numeric_limits<type>::digits10(), and then to_chars() to do all this lightning fast, and with no memory allocation, something like so:
auto a_chars = std::array<char, std::numeric_limits<decltype(ia)>::digits10() + 2>{};
auto b_chars = std::array<char, std::numeric_limits<decltype(ib)>::digits10() + 2>{};

std::to_chars(a_chars.data(), a_chars.data() + a_chars.size(), ia);
std::to_chars(b_chars.data(), b_chars.data() + b_chars.size(), ib);

Or, better yet, move all that into its own function.
int32_t i = 0;

This is bad practice for a number of reasons.
First, you should only declare variables where you’re going to use them; unless you have a damn good reason, you should never declare them up at the top of a function.
And you should especially not reuse a variable for different things throughout a function. i is used as a loop counter in both branches of that if, for two (or more) entirely different loops. That’s bad. You don’t need it at all for either of the first two loops; in the first loop, it should just be a local counter for a for, if anything, and in the second loop, the same, and after you could set it using min_size.
if (a.size() == b.size()) {
    while (i < a.size()) {
        if (a.at(i) == b.at(i)) {
            ++i;

            continue;
        }
        else if (a.at(i) > b.at(i))
            return true;
        else
            return false;
    }
} else {

Alright, so what exactly is going on here? The manual loop just complicates what is actually a very simple thing. If the two strings are the same size, you go through looking for any mismatched characters, and if you find a mismatched pair, you return true if the character in a is less than the character in b.
What you don’t account for, though, is what happens if all the characters are equal. In that case, you just fall out of the loop and continue on… and eventually get to the end of the function, which returns nothing. That’s your critical bug.
This is what the code above is actually doing, using algorithms to make everything clearer:
if (a.size() == b.size())
{
    auto [it_a, it_b] = std::mismatch(a.begin(), a.end(), b.begin()); // don't need b.end(), because the sizes are the same
    if (it_a != a.end()) // don't need to check it_b, because the sizes are the same
    {
        return *it_a < *it_b;
    }
    else
    {
        // what happens here?
        //
        // your current code does nothing, so the program continues on to the
        // end of the function, which has no return statement... thus, the bug
    }
}

So what is supposed to happen if the two strings are equal? Logically, I’d think, you would return false, because if the two strings are equal, then ia is not less-than ib. So:
if (a.size() == b.size())
{
    auto [it_a, it_b] = std::mismatch(a.begin(), a.end(), b.begin());
    if (it_a != a.end())
    {
        return *it_a < *it_b;
    }
    else
    {
        return false;
    }
}

But searching for the first mismatch and then returning true if the first char is less than the second is just a lexicographical compare:
if (a.size() == b.size())
{
    return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());
}

But that’s just what std::string’s operator< does:
if (a.size() == b.size())
{
    return a < b;
}

In other words, if the two strings are same size, return true only if a is lexicographically less than b. If you reason about your code at a higher level, rather than getting bogged down with loops, you can spot these simplifications much more easily. In other words, don’t focus on the details, step back and think about the big picture.
int32_t min_size = static_cast<int32_t>(std::min(a.size(), b.size()));
int32_t max_size = static_cast<int32_t>(std::max(a.size(), b.size()));

Forcing int32_t here introduces potential bugs. None are likely to trigger in reality, because the lengths of the two strings should be very, very small, even for 64- or 128-bit integers. However, there’s no sensible reason to tempt fate.
The first potential bug is truncation if the size is greater than what would fit in an int32_t. Again, that will never happen in reality, but again, why play dangerously for no good reason?
The second potential bug is what a decent compiler with warnings turned on will warn you about. Comparing signed and unsigned values is a craps shoot. If you are mixing signedness in a comparison, you can get absurdities like -1 > 1u.
There’s no reason to force-cast any of the above into int32_t… or to force-cast it into anything. Just use auto, and everything works:
auto const min_size = std::min(a.size(), b.size());
auto const max_size = std::min(a.size(), b.size());

Much less typing, too. Or:
auto const [min_size, max_size] = std::minmax(a.size(), b.size());

That works just as well.
while (i < min_size) {
    if (a.at(i) == b.at(i)) {
        ++i;

        continue;
    }
    else if (a.at(i) > b.at(i))
        return true;
    else
        return false;
}

The next naked loop; what exactly is this one doing? Well, it’s going from 0 (which is the value of i at the start of the loop, though it isn’t immediately obvious from the code), to the minimum size of the two strings, and doing a lexicographical comparison. In other words:
if (auto const res = a.compare(0, min_size, b); res != 0)
{
    return res < 0;
}

We don’t even need to check which one is smaller here, because we’re using the minimum size.
Now from this point on is where the problems really start. At this point, you’ve dealt with the case where the two strings have equal length (of course, you need to fix the bug when they’re exactly equal). You’ve also dealt with the case where you have a short string and a long string, and the first part of the long string is either greater or less than the short string. So what you have now is the case where you have a short string, and a longer string that starts with the short string. In other words: the short string is <pattern>, and the long string is <pattern><something>.
So what happens next?
Well, what you do is get the first digit of <pattern>, and then compare it with every digit in <something>. But does that make sense?
Consider when <pattern> is 42, and <something> is 41 or 49:

With 41, you compare the first 4 with the 4 in 41… it’s >=, so you return true.
No problem, 42 should compare less than 4241, because 424241 is greater than 424142.

With 49, you compare the first 4 with the 4 in 49… it’s >=, so you return true.
But 42 should compare less than 4249, because 424249 is NOT greater than 424942.

So your algorithm doesn’t work.
As for the rest of the function, I won’t review it in detail (because it needs to be rewritten), but I’ll just say:

Avoid std::string.at(). It’s unnecessary. You know for a fact the string is not empty, so a[0] is guaranteed to work.
You do some trickery with multiple loops to handle the two cases where a is shorter or longer than b, but that just caused confusion (as you saw). Instead, just do something like:

if (a.size() < b.size())
    some_helper_function(a, b);
else
    some_helper_function(b, a);

This is clearer, and safer.
Suggestions for fixing
First, write test cases. Especially consider test cases that might be troublesome.
Your function basically has two paths, one for when the two numbers have equal amounts of digits, and one for when they don’t. So you probably need (at least) three test cases:
TEST_CASE("equal values")
{
    // ...
}

TEST_CASE("unequal values with the same digit count")
{
    // ...
}

TEST_CASE("unequal values with different digit counts")
{
    // ...
}

In the latter case, you should check a bunch of of cases, but especially some cases where the short value is repeated one or more times, like:

1 and 11
1 and 1111111
12 and 1212
12 and 12121212
21 and 2121
21 and 21212121

And you should check cases where the short value is repeated, then followed by something that will make it sort before or after, like:

45 and 451
45 and 454
45 and 459
45 and 4545451
45 and 4545454
45 and 4545459
54 and 541
54 and 545
54 and 549
54 and 5454541
54 and 5454545
54 and 5454549

Once you have your test cases set up, you should think about what makes one number sort before or after another… especially when there is a repeated pattern. Like, does 56 come before or after 561, 565 and 569, and why? What about 56 and 5656561, 5656565, and 5656569? I’ll give you one tip: it’s all about lexical comparisons with the short pattern… repeated lexical comparisons with the short pattern, not just one-and-done.
And of course, turn on warnings, and heed them.


Returning lines for a given function from a JavaScript file The function below iterates through an array that contains all the lines of a JavaScript file (a global array, this_file), and returns just those lines (current_function) containing the text of the function with the name that is passed by the argument (funShun). The code assumes that the function to copy ends whenever '}' by itself (not preceded by whitespace) is spotted (this is true of the file I'm working with).

My question is about whether it would be preferable (and how to do it) to substitute a regex in place of iterating through the file line by line.

This works fine, but it seems to me this could be done with a regex applied to the original Ajax string, but that might be beyond my current regex abilities.

All advice greatly welcome!

// Return an array containing the text of the input function.
function load_function_text(funShun) {
  // Iterate through the present JS file's text.
  var line_num = 0; // Track line num so you can grab the previous line.
  var current_function = [];
  var copying_lines = false;
  this_file.forEach(function(line) {
    // Start copying when 'function funShun' is spotted. (Start pushing from previous line.)
    if (line.match("function " + funShun)) {
      current_function.push(this_file[line_num - 1]);
      current_function.push(line);
      copying_lines = true;
      line_num += 1;
    // Stop copying when '}' is spotted.
    } else if (copying_lines && line === '}') {
      // Add the '}' line.
      current_function.push(line);
      // Stop copying when end of function is reached.
      copying_lines = false;
    } else {
      if (copying_lines) current_function.push(line);
      line_num += 1;
    }
  });
  return current_function;
}

Inefficient Array.forEach

The current implementation will needlessly iterate until the end of the array even after the function was found.
It would be better replace the .forEach with a regular counting loop,
and break out of it after you found the end of the function.

Avoid flag variables

Using a single loop and the copying_lines flag variable to alternate between processing logic (find start of function, copy content, find end), is not very easy to read.
It would be easier to use a nested loop after you found the start.
Something like this:

for (let i = 0; i < lines.length; i++) {
  if (lines[i].match(startPattern) !== null) {
    let function_lines = [];

    for (let j = i; j < lines.length; j++) {
      function_lines.push(lines[j]);

      if (lines[j] === '}') return function_lines;
    }

    throw new Error('Could not find end of function before end of content');
  }
}

return [];

Too weak start pattern

This condition is too weak to match the declaration of a function:

if (line.match("function " + funShun)) {

For example, if there are functions named convert_custom and convert,
and you call load_function_text('convert'),
it will find the first one.
I suggest to use a stronger pattern, for example:

startPattern = new RegExp("\\s*function " + funShun + "\\s*\\(");


Script for creating a hierarchy of directories This script creates a hierarchy of directories.  Is this a good approach or can it be made better? I am mainly concerned with maintainability here, not efficiency. Suppose I wanted to add more directories to this hierarchy.  Would this structure of the script make it easier to do?

Hierarchy

./project_euler
    ./001_050
    ./051_100
    ...
    ./401_450
./codechef
    ./easy
    ./medium
    ./hard
./spoj
./functions
./utilities

The script

import os

TOP = ['project_euler', 'codechef', 'spoj', 'functions',
       'utilities']
CODECHEF = ['easy', 'medium', 'hard']

def safe_make_folder(i):
    '''Makes a folder if not present'''
    try:
        os.mkdir(i)
    except:
        pass

def make_top_level(top):
    for i in top:
        safe_make_folder(i)

def make_euler_folders(highest):
    def folder_names():
        '''Generates strings of the format 001_050 with
        the 2nd number given by the function argument'''
        for i in range(1,highest, 50):
            yield (
                'project_euler' + os.sep +
                str(i).zfill(3) + '_' + str(i + 49).zfill(3)
                )

    for i in folder_names():
        safe_make_folder(i)

def make_codechef_folders(codechef):
    for i in codechef:
        safe_make_folder('codechef' + os.sep + i)

def main():
    make_top_level(TOP)
    make_euler_folders(450)
    make_codechef_folders(CODECHEF)

if __name__ == "__main__":
    main()

One of the things I would do is remove the double occurrence of the strings 'project_euler' and 'codechef'. If you ever have to change one of these in TOP, you are bound to miss the repetition in the functions.

You should at least use TOP[0] in make_euler_folders() and TOP[1] in make_codechef_folders. A better approach however would be to take both definitions out of TOP and change def safe_make_folder():

TOP = ['spoj', 'functions', 'utilities']

def safe_make_folder(i):
    '''Makes a folder (and its parents) if not present'''
    try:
        os.makedirs(i)
    except:
        pass

The standard function os.makedirs() creates the 'project_euler' resp.
'codechef', as the first subdirectory of each is created.

The other is that I would create the directory names using os.path.join() (as it prevents e.g. the mistake of providing double path separators), in combination with standard string formatting to get the leading zeros on the subfolder names:

os.path.join('project_euler', '{:03}_{:03}'.format(i, i+49))

the {:03} gives a 3 character wide field with leading zeros. @Josay improvemed function would then become:

def make_euler_folders(highest):
    for i in (os.path.join('project_euler', '{:03}_{:03}'.format(i, i+49)) \
       for i in range(1,highest, 50)):
        safe_make_folder(i)

And the other function would become:

def make_codechef_folders(codechef):
    for i in codechef:
        safe_make_folder(os.path.join('codechef', i))


Splitting a string of random length I am currently using this code, but I am pretty sure there is a better way of doing it:

private string ReturnEmployeeName(string userName)
{
    try
    {
        // Username coming is     RandomDomain\RandomLengthUsername.whatever
        string[] sAMAccountName = userName.Split('\\');
        return sAMAccountName[1];

How can I make this faster?  I am not sure if my try block will catch any exceptions that may arise because of this line.

Personally, I think you would be better off moving this code into a separate class as it's probably logic you are going to want in multiple places in your application and is most likely violating SRP (Single Responsibility Principle) wherever it is at the moment.

If we create a username class, we can encapsulate the logic in there and then re-use it from wherever we want in the application:

public class UserName
{
    private UserName() {}
    public string AccountName { get; private set; }
    public string DomainName { get; private set; }

    public static UserName Parse(string userName)
    {
        if (userName == null)
        {
            throw new ArgumentNullException("userName");
        }

        if (userName.Contains(@"\"))
        {
            var parts = userName.Split('\\');

            return new UserName { DomainName = parts[0], AccountName = parts[1] };
        }

        if (userName.Contains("@"))
        {
            var parts = userName.Split('@');

            return new UserName { DomainName = parts[1], AccountName = parts[0] };
        }

        return new UserName { AccountName = userName };
    }
}

You can then test the logic for this class in isolation:

public class UserNameTests
{
    public class WhenCallingParseWithANullUserName
    {
        [Fact]
        public void AnArgumentNullExceptionShouldBeThrown()
        {
            Assert.Throws<ArgumentNullException>(() => UserName.Parse(null));
        }
    }

    public class WhenCallingParseWithAUserNameWithNoDomainName
    {
        private UserName userName;

        public WhenCallingParseWithAUserNameWithNoDomainName()
        {
            userName = UserName.Parse("JohnSmith");
        }

        [Fact]
        public void TheDomainNameShouldBeNull()
        {
            Assert.Null(userName.DomainName);
        }

        [Fact]
        public void TheUserNameShouldEqualTheWholeUserName()
        {
            Assert.Equal("JohnSmith", userName.AccountName);
        }
    }

    public class WhenCallingParseWithDomainSlashUserName
    {
        private UserName userName;

        public WhenCallingParseWithDomainSlashUserName()
        {
            userName = UserName.Parse(@"Domain\JohnSmith");
        }

        [Fact]
        public void TheDomainNameShouldBeSetToTheDomainName()
        {
            Assert.Equal("Domain", userName.DomainName);
        }

        [Fact]
        public void TheUserNameShouldBeSetToTheUserName()
        {
            Assert.Equal("JohnSmith", userName.AccountName);
        }
    }

    public class WhenCallingParseWithUserNameAtDomain
    {
        private UserName userName;

        public WhenCallingParseWithUserNameAtDomain()
        {
            userName = UserName.Parse(@"JohnSmith@Domain");
        }

        [Fact]
        public void TheDomainNameShouldBeSetToTheDomainName()
        {
            Assert.Equal("Domain", userName.DomainName);
        }

        [Fact]
        public void TheUserNameShouldBeSetToTheUserName()
        {
            Assert.Equal("JohnSmith", userName.AccountName);
        }
    }
}


Python 2.7 text adventure map and movement I have been writing a python text adventure and the map module i wrote is very clunky. It is a list with compass dirs as the navigation. The problem with this is, i refer to each room by index number, and this is SUPER confusing. If anyone has any helpful advice it would be greatly appreciated.

map module (the sub-lists are just things that are in the room.):

map=[]
map.append({"name":"The Courtyard of the Castle Darkspur.",
"info":"You are in a courtyard with stone walls and moss covering the              ground.\nThere is a puddle of odd looking liquid south of you. \nTo the north is a large wooden door with a rusty iron handle.\n",
"connects":[{"north":1}],
"items":[Weapon("knife","Rusty Knife(lv 0)","It's pretty rusty...",2,4)],
"npcs":[NPC("davkas","Davkas",0,"Greetings, traveller.\nRead the scroll on the ground. It will cost you nothing.","The only advice I can give you is to read the scroll I have left in the room.")],
"npcitems":[],
"enemies":[Enemy(["onyx","spider"],"Onyx, Corrupted Spider","Fang","YOU INTRUDE UPON MY DOMAIN, HUMAN.",random.randint(0,5),5)],
"enemyitems":[Weapon("fang"," Corrupted Fang","It looks poisonous, but deadly.(lv 1)",5,5)],
"riddle":[],
"reward":[],
"scrolls":[Scroll("scroll","Scroll of Learning","scrollx","Hello, Traveller. It is I, the Prince Darkspur. I am the only one who made it out of this cursed fortress before the curse struck. I am leaving this scroll here in the hope that some valiant hero will attempt to restore the glory of my home. I tried many a time and the challenge proved too great for me.")]})
room=map[0]
map.append({"name":"The Castle Entry.",
"info": "\nA wrought iron Gargoyle looms above your head. On top of the gate is the crest of the family darkspur, who many years ago fell victim to a curse placed on the castle by a wizard.\n",
"connects":[{"south":0},{"north":2}],
"items":[Item("potion","Lesser Health Potion","It heals you, a little.",5,5),],
"npcs":[],
"npcitems":[],
"enemies":[],
"enemyitems":[],
"riddle":[Riddle("I weaken all men for hours each day.\nI show you strange visions while you are away.\nI take you by night, by day take you back,\nNone suffer to have me, but do from my lack.\n","sleep")],
"reward":[Item("key","Foyer Key","It opens the door to the castle.",0,0)],
"scrolls":[Scroll("scroll","Scroll of wisdom","scrolly","The story of the Family Darkspur.\nMany years ago, a family of valiant knights and warrior-women reigned over this land.\nThey were kind and generous to all that did them no harm.\nTo those that challenged their authority, a quick and painless death was their punishment.\nThe only thing more important to the Family Darkspur than power was wealth.\nThe family always ran into battle dressed in the finest dragon-scale mail with diamonds around their necks.\nLittle did they know that this would be their downfall.\nBEWARE OF MYSTERIOUS TREASURE.")]})

Being more familiar with appropriate data structures is going to help a lot here. I will suggest a better map structure that will make things less confusing at the end. First I want to suggest an intermediate cleanup which will let me think and talk about things more easily.

Room class: You have class for Weapon, Enemy, etc. It will help a lot to make a class to contain an element of the map. I'm going to call it Room. Maybe there's a term more appropriate for your game. Then your initialization could look something like this. (I'm leaving out the connects field for now. Hang on.)

map.append(Room(name="The Courtyard of Castle Darkspur",
                info="A description of the room"))

Turning it into a graph: Now we have a nicer way to link rooms. Without going into too much detail, a graph is a common way to represent specific connections between objects. I'm sure there's a cool graph library we could use, but this should be all we need to get us going:

start_room = Room(name="The Courtyard...."
                  # etc
                  )
castle_entry = Room(name="The castle entry")
start_room.add_connection(Direction.North, castle_entry)

And add_connection just has to look like this:

def add_connection(self, direction, room):
    self.connects[direction] = room

(direction is an Enum, by the way)

Now you can go straight to the connected room without worrying about indexing

But now what about all the local variables? This still isn't great. You're probably going to have a lot of local variables lying around, and this is mixing data and code pretty heavily. A cleaner solution would be to store the map in a .txt file. It might look something like this:

Room
Name: The Courtyard of Caslte Darkspur
Id: courtyard-darkspur
Info: Courtyard descr.
Weapons: rusty-knife-simple
connects: South, castle-entry

Room
Name: The castle entry
Id: castle-entry
Connects: North, room-entry

You would need a class or function to first parse each item individually, and then use the id fields to create all the links between nodes. Common ways to store configuration data like this are JSON (mainly) or XML.

You could also choose a hybrid of these approaches. Perhaps a class you could use in the REPL to dynamically construct a part of the map, then it saves it to your configuration file when you're done.


Write a program to find the longest word made of other words This is my solution to the problem in the title. The code is pretty straightforward. The one problem is with substring; it's \$O(n)\$ in .Net and creates garbage. Any other improvements?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LongestWordFromWords
{
    internal class Program
    {
        public static string FindLongestWords(string[] listOfWords)
        {
            if (listOfWords == null) throw new ArgumentException("listOfWords");
            var sortedWords = listOfWords.OrderByDescending(word => word.Length).ToList();
            var dict = new HashSet<String>(sortedWords);
            foreach (var word in sortedWords)
            {
                if (isMadeOfWords(word, dict))
                {
                    return word;
                }
            }
            return null;
        }

        private static bool isMadeOfWords(string word, HashSet<string> dict)
        {
            if (String.IsNullOrEmpty(word)) return false;
            if (word.Length == 1)
            {
                if (dict.Contains(word)) return true;
                else return false;
            }
            foreach (var pair in generatePairs(word))
            {
                if (dict.Contains(pair.Item1))
                {
                    if (dict.Contains(pair.Item2))
                    {
                        return true;
                    }
                    else
                    {
                        return isMadeOfWords(pair.Item2, dict);
                    }
                }
            }
            return false;
        }

        private static List<Tuple<string, string>> generatePairs(string word)
        {
            var output = new List<Tuple<string, string>>();
            for (int i = 1; i < word.Length; i++)
            {
                output.Add(Tuple.Create(word.Substring(0, i), word.Substring(i)));
            }
            return output;
        }

        private static void Main(string[] args)
        {
            string[] listOfWords = { "ala", "ma", "kota", "aa", "aabbb", "bbb", "cccc", "aabbbmacccc", "aabbbmaxxcccc" };
            string longest = FindLongestWords(listOfWords);
            Console.WriteLine(longest);
            string[] listOfWords2 = { "cat", "cats", "catsdogcats", "catxdogcatsrat", "dog", "dogcatsdog",
                                      "hippopotamuses", "rat", "ratcatdogcat" };
            Console.WriteLine(FindLongestWords(listOfWords2));
        }
    }
}

The first thing that strikes me is that you've put everything within the Program class, which forces your methods to be static, and any program where everything is static is a program I want to rewrite :)

Let's start with FindLongestWords(string[]):

if (listOfWords == null) throw new ArgumentException("listOfWords");

This guard clause is throwing the wrong exception, it should be an ArgumentNullException. Now the goal of a guard clause is to fail fast. Interestingly if you leave it out, the next line would throw an ArgumentNullException all by itself, merely by passing it to the OrderByDescending extension method:

var sortedWords = listOfWords.OrderByDescending(word => word.Length).ToList();

I see you're using var - I like that. So sortedWords is a List<string>. I think the method could happily take any IEnumerable<string> instead of an array.

Now the next thing I see is a lie - dict would be an almost-acceptable name for any IDictionary, but it's a HashSet<T>...

var dict = new HashSet<String>(sortedWords);

And here we are. You're using System.Linq, so this loop could very well be rewritten with a much shorter Linq-expression:

foreach (var word in sortedWords)
{
    if (isMadeOfWords(word, dict))
    {
        return word;
    }
}
return null;

Turns into this one-liner (notice dict is gone!):

return sortedWords.FirstOrDefault(word => isMadeOfWords(word, sortedWords));

isMadeOfWords should be named IsMadeOfWords, and can be happy with some ICollection:

private static bool IsMadeOfWords(string word, ICollection<string> dict)
{
    if (String.IsNullOrEmpty(word)) return false;
    if (word.Length == 1)
    {
        return dict.Contains(word);
    }
    foreach (var pair in generatePairs(word).Where(pair => dict.Contains(pair.Item1)))
    {
        return dict.Contains(pair.Item2) || IsMadeOfWords(pair.Item2, dict);
    }
    return false;
}

I find that's more readable than the more concise form that ReSharper suggests:

    if (String.IsNullOrEmpty(word)) return false;
    return word.Length == 1
        ? dict.Contains(word)
        : generatePairs(word).Where(pair => dict.Contains(pair.Item1))
                             .Select(pair => dict.Contains(pair.Item2) || IsMadeOfWords(pair.Item2, dict))
                             .FirstOrDefault();

And then generatePairs should be renamed to GeneratePairs and can return IEnumerable<Tuple<string, string>> instead of List<Tuple<string, string>>. The only thing that itches here is the absence of var in for(int i = 1... - if you're going to use var, might as well go all the way!

I'd put that logic in its own class, and then... looks good!


Named string interpolation On machines where I don't have C# 6 I use this named string interpolation method. I tried to make it as pretty a possible as far as good coding practices are concerned but I just can't get rid of the repeating code for braces validation and index incrementation. Somehow I don't like it.

public static string FormatFrom(this string text, object args, bool ignoreCase = true)
{
    var substrings = Regex.Split(text, "({{?)([A-Za-z_][A-Za-z0-9_]+)(}}?)");
    var argsType = args.GetType();
    var result = new StringBuilder(text.Length);

    const int leftBraceOffset = 0;
    const int propertyNameOffset = 1;
    const int rightBraceOffset = 2;

    for (int i = 0; i < substrings.Length; i++)
    {
        var leftBraceIndex = i + leftBraceOffset;
        var propertyNameIndex = i + propertyNameOffset;
        var rightBraceIndex = i + rightBraceOffset;

        var isPropertyName = substrings[leftBraceIndex] == "{" && substrings[rightBraceIndex] == "}";
        if (isPropertyName)
        {
            var propertyName = substrings[propertyNameIndex];
            var property = argsType.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
            result.Append(property.GetValue(args));
            i += 2;
            continue;
        }

        var isEscapedPropertyName = substrings[leftBraceIndex] == "{{" && substrings[rightBraceIndex] == "}}";
        if (isEscapedPropertyName)
        {
            result.Append("{").Append(substrings[propertyNameIndex]).Append("}");
            i += 2;
            continue;
        }

        result.Append(substrings[i]);
    }

    return result.ToString();
}

var text = "Lorem {ipsum} {dolor} {{sit}} met.";
var obj = new { ipsum = "abc", dolor = 2.1 };
var text2 = text.FormatFrom(obj);

Result:

  Lorem abc 2.1 {sit} met.

Always check the argument which is reffered by this in an extension method against null to early throw and return. Sure one could say it doesn't matter, because it will throw an ArgumentNullException but that would be thrown from the Regex.Split() method.
You don't check for args == null either.
The optional argument ignoreCase isn't used anywhere in that method so it can safely removed.
if by accident the property of the anonymous object isn't spelled exactly like in the string, the call to argsType.GetProperty() will return null and an NullReferenceException is thrown. Maybe it would be better for such a case to just assume it isn't a property. I will come back to this later.
if the passed in text only contains { the code will throw an IndexOutOfRange exception. This can be prevented by returning early if the length of text is < 3.
if the Length of substrings will be < 3 we can return early by returning text.
the regex pattern does not allow single letter variables being passed. So a text like {i} won't be matched.

Implementing the mentioned points will lead to

public static string FormatFrom(this string text, object args)
{
    if (text == null) { throw new ArgumentNullException("text"); }

    if (text.Length < 3 || string.IsNullOrWhiteSpace(text) || args==null) { return text; }

    var substrings = Regex.Split(text, "({{?)([A-Za-z_][A-Za-z0-9_]+)(}}?)")
                          .Where(s => s != string.Empty).ToArray();

    if (substrings.Length < 3) { return text; }

    var argsType = args.GetType();
    var result = new StringBuilder(text.Length);

    const int propertyNameOffset = 1;
    const int rightBraceOffset = 2;

    var bindingFlags = BindingFlags.Instance | BindingFlags.Public;

    for (int i = 0; i < substrings.Length; i++)
    {

        var possibleLeftBraces = substrings[i];
        var possibleRightBraces = substrings[i + rightBraceOffset];
        var propertyName = substrings[i + propertyNameOffset];

        var isPropertyName = possibleLeftBraces == "{" && possibleRightBraces == "}";
        if (isPropertyName)
        {
            var property = argsType.GetProperty(propertyName, bindingFlags);
            if (property == null)
            {
                result.Append("{").Append(propertyName).Append("}");
            }
            else
            {
                result.Append(property.GetValue(args, null));
            }
            i += 2;
            continue;
        }

        var isEscapedPropertyName = possibleLeftBraces == "{{" && possibleRightBraces == "}}";
        if (isEscapedPropertyName)
        {
            result.Append("{").Append(propertyName).Append("}");
            i += 2;
            continue;
        }

        result.Append(substrings[i]);
    }

    return result.ToString();
}

which will pass all of these tests

[TestMethod()]
public void FormatFromTestStringEmptyShouldPass()
{
    string expected = string.Empty;
    string actual = string.Empty.FormatFrom(null);

    Assert.AreEqual(expected, actual);

}
[TestMethod(),ExpectedException(typeof(ArgumentNullException))]
public void FormatFromTestStrinNullShouldPass()
{

    string actual = ((string)null).FormatFrom(null);

    Assert.Inconclusive("Shouldn't happen !");

}
[TestMethod()]
public void FormatFromTestArgsNullShouldPass()
{
    string expected = "lala";
    string actual = "lala".FormatFrom(null);

    Assert.AreEqual(expected, actual);

}
[TestMethod()]
public void FormatFromTestParamsButArgsNullShouldPass()
{
    string expected = "{land}";
    string actual = "{land}".FormatFrom(null);

    Assert.AreEqual(expected, actual);

}
[TestMethod()]
public void FormatFromTestArgsNotNullShouldPass()
{
    string expected = "germany";
    string actual = "{land}".FormatFrom(new { land = "germany" });
    Assert.AreEqual(expected, actual);

}
[TestMethod()]
public void FormatFromTestArgsNotNullButWrongShouldPass()
{
    string expected = "{land}"; // TODO: Passenden Wert initialisieren
    string actual;
    actual = "{land}".FormatFrom(new { lan = "germany" });
    Assert.AreEqual(expected, actual);
}


Largest divisible subset optimization So this is my solution to the following leetcode problem: https://leetcode.com/problems/largest-divisible-subset/description/

How could I optimize this code?
I think the run time is \$\mathcal{O}(n^2)\$, is that correct?

def largest_divisible_subset(nums)
return nums if nums.length < 2
nums.sort!
max_result = {}
(0).upto(nums.length - 1) do |i|
    j = i - 1
    result = Set.new

    while j >= 0
       if nums[i] % nums[j] == 0
          if max_result[nums[j]] && max_result[nums[j]].length > result.length
             result =  max_result[nums[j]].dup
          elsif result.length == 0
             result.add(nums[j])
          end
       end

        j -= 1
        break if result.length > nums[0..j].length
    end

    result.add(nums[i])
    max_result[nums[i]] = result
end

   max_result.values.max{|a,b| a.length <=> b.length }.to_a
end

Yes, the running time is \$O(n^2)\$.

When writing ruby, it's best to take advantage of ruby's built in methods, rather than writing procedural code the same way you would in C or Java.

Also, this problem expresses itself more naturally with recursion.

Notes on the solution below:

nums, in this recursion, are "the remaining numbers to be processed".  We start with smallest (first number on sorted list), pop off the head on each iteration.
ret is a hash of the results for all smaller numbers -- the same is max_result in the OP.

Here's a possible rewrite:

def largest_divisible_subset(nums, ret={})
  return ret.values.max_by(&:size) || [] if nums.empty?
  nums = nums.sort if ret.empty?
  head, *tail = nums
  max_set = ret.select {|n| head % n == 0}.values.max_by(&:size) || []
  ret[head] = max_set.dup.push(head)
  largest_divisible_subset(tail, ret)
end


Optimizing runtime on finding the nth perfect power number i was given a task to write a code to find the nth perfect power number. i wrote the following function to find that number but the runtime is long at high number (above 30).
you can assume that the input number is within the range of 1-100.
here's the code:

def perfect(n: int) -> int:
    """
    :param n: enter the n'th place perfect power num you'd like
    :return: the n'th perfect power number
    """
    powers = []
    i = 1
    for i in range(0, n**2+1):
        for k in range(0, i):
            for m in range(0, i):
                if m ** k == i:
                    powers.append(i)
                    i += 1
                    break
        if len(powers) == n:
            break
    return powers[n-1]

Naming

perfect is quite general for a function name. A better choice might be something like nth_perfect_power.

Docstring comments

You have documented the function with a docstring comment, which is good. There is some repetition and verbosity however. I would perhaps use a single-line description, plus a description of what a perfect power is. You could also add some doctest examples:

def nth_perfect_power(n: int) -> int:
    """Return the n'th perfect power.

    A perfect power is a positive integer of the form m ** k with
    m >= 1 and k >= 2. Examples from https://oeis.org/A001597:

    >>> nth_perfect_power(1)
    1
    >>> nth_perfect_power(10)
    49
    >>> nth_perfect_power(50)
    1521
    """

Of course this is largely opinion-based.

Review and performance improvements

The initial assignment

i = 1
for i in range(0, n**2+1):
    // ...
        i += 1

has no effect, and incrementing i within the loop makes the logic difficult to understand. Perhaps this is done to take care of duplicate powers such as \$ 8^2 = 4^3 \$, but there are better approaches to solve that. You can for example move the check for a perfect power to a separate function (where you can early-return).

Apart from the first perfect power \$ i = 1 \$ one only needs to check values \$ m, k \ge 2 \$.

The length of the powers array needs only to be checked again if we added an element, not for each value of \$ i \$.

The last element of an array can be retrieved as powers[-1].

Summarizing these topics so far, we get the following implementation:

def is_perfect_power(i: int) -> bool:
    if i == 1:
        return True
    for k in range(2, i):
        for m in range(2, i):
            if m ** k == i:
                return True
    return False

def nth_perfect_power(n: int) -> int:
    powers = []
    for i in range(1, n**2 + 1):
        if is_perfect_power(i):
            powers.append(i)
            if len(powers) == n:
                break
    return powers[-1]

This is more code than your original, but easier to read and slightly more efficient. It can be improved further: The exponentiation \$ m^k \$ can be replaced by repeated multiplication with \$ m \$. Also the inner loop can be exited as soon as a power is larger than the candidate \$ i \$:

def is_perfect_power(i: int) -> bool:
    if i == 1:
        return True
    for m in range(2, i):
        p = m * m
        while p < i:
            p *= m
        if p == i:
            return True
    return False

With these changes, the \$ 20^\text{th} \$ perfect power is found in approx. 3 milliseconds (compared to 2.6 seconds with your original code), and the \$ 100^\text{th} \$ perfect power is found in approx. 2.5 seconds.

A different approach

Your code determines for every candidate \$ i \$ if it is a perfect power by computing \$ m^k \$ for all \$ m, k \$ in the range \$ 0, \ldots, i \$. This is done for all \$i \$ up to  \$ n^2\$, until \$ n \$ perfect powers are found.

As an example, in order to find the \$ 20^\text{th} \$ perfect power, \$ m^k \$ is computed \$ 3382670\$ times.

We already improved that by restricting the base \$ m \$ and the exponent \$ k \$ to smaller ranges. But for larger values of \$ n \$ we need a different approach.

It is much more efficient to compute all perfect powers (in some range) instead, and then take the \$ n^\text{th} \$ smallest number. Since there can be duplicates (e.g. \$ 8^2 = 4^3 \$), a set should be used to collect the perfect powers.

You already used that there must be \$ n \$ perfect numbers in the range \$ 1, \ldots, n^2 \$. This can still be used to limit the range of the exponent \$ k \$.

As an example, in order to find the \$ 20^\text{th} \$ perfect power we need the numbers \$ m^k \$ in the range \$1, \ldots, 400 \$. The first perfect number \$ 1 \$ can be handled separately, so that \$ m \ge 2 \$ and \$ k \ge 2 \$:

$$
\begin{align}
 m&=2:  4, 8, 16, 32, 64, 128, 256 \\
 m&=3: 9, 27, 81, 243 \\
 m&=4:  16, 64, 256 \\
 m&=5:  25, 125 \\
 m&=6:  35, 216 \\
 m&=7:  49, 343 \\
 m&=8:  64 \\
 \vdots \\
 m&=20: 400
\end{align}
$$

This leads to the following implementation:

def nth_perfect_power(n: int) -> int:
    upper_limit = n * n
    powers = set([1])
    for m in range(2, n + 1):
        p = m * m
        while p <= upper_limit:
            powers.add(p)
            p *= m
    return sorted(powers)[n-1]

This finds the \$ 100000^\text{th} \$ perfect power is found in approx. 0.1 seconds, and the one-millionth perfect power in approx. 1.4 seconds.

For even more performance, we can use a heap structure to store only the \$ n \$ smallest powers found so far. The Python heapq is a min-heap but we need a max-heap. Therefore all powers are multiplied by \$(-1)\$. We start with the list of squares and then add the third, fourth, ... powers. For every base \$ m \$ we can stop as soon as \$ p = m^k \$ is larger than the \$ n \$ smallest powers found so far.

Implementation:

def nth_perfect_power(n: int) -> int:
    heap = [- i * i for i in range(1, n+1)]
    heapq.heapify(heap)
    powers = set(heap)
    for m in range(2, n + 1):
        p = - m * m * m
        if p <= heap[0]:
            break
        while p > heap[0]:
            if not p in powers:
                powers.remove(heapq.heappushpop(heap, p))
                powers.add(p)
            p *= m
    return -heap[0]

This computes the one-millionth perfect power in approx. 0.42 seconds.