Who needs clean configuration? Swapping server.xml So I'm working on a project that sometimes requires me to switch my server configuration. This is due to some circumstances with database drivers and names that are "too expensive to fix" ...

That made me think though: "Why do I always copy these files around manually?"

I decided I won't and wrote this small script to help me:

#!/bin/bash

if [ $# != 1 ]
    then
    echo "you must provide a configuration to switch to"
    exit
fi;

if [ -a $TOMCAT_HOME/conf/server_$1.xml ]
    then
    rm $TOMCAT_HOME/conf/server.xml
    cp $TOMCAT_HOME/conf/server_$1.xml $TOMCAT_HOME/conf/server.xml
else
    echo "given configuration was not found. did not make any changes."
fi;

exit 0

Usage is dead simple: I made this available system-wide and can just call:

switch-config postgres

or

switch-config firebird

To make changes happen.

This is built for my personal convenience, so please ignore the incredibly bad error messages, also the (nonexistent) directory structure is for simple convenience. Comments like "move the different configurations somewhere else" don't help me.

In any case, what can I improve?

Method

I'd suggest, instead of rm-ing and cp-ing, keeping each configuration set as named and symlinking to them as needed.

This gives you a couple of benefits:

You can tell which the current one is without opening the file, just using ls -l:

lrwxrwxrwx 1 user group 4 Jul 29 07:12 server.xml -> config-for-blah.xml

Changes are (sort-of) atomic: rm and cp take time, while over-writing a symlink with a symlink is as close to instant as you can reasonably make it.
You can move the actual files anywhere later and just update the symlinks: version-control it in a repo directory, put configuration sets into separate directories, whatever.

Replacing the rm and cp in your current script, that'd be:

ln -sf "$TOMCAT_HOME/conf/server_$1.xml" "$TOMCAT_HOME/conf/server.xml"

(You need -f, or else ln will complain that the link you're trying to create already exists.)

You should also detect whether the main commands have completed successfully, probably using something like:

if [ $? -ne 0 ];
    then
    echo "Oops." >&2
    exit 1
fi

Scripting

Quote your filenames. This helps avoid accidents where variables are mis-set.
Check your test types. In [ $# != 1 ], $# is being referenced as a number, but != is for strings. Use -ne for numbers. (This is just a good habit to get into.)
You don't need the semicolons after the fi.
Error messages should usually go to stderr: echo "Error" >&2
When detecting an error and exiting, exit with an status other than 0: this lets you easily detect problems when using the script. (c.f. the check in the method section above.)
Maybe do something to avoid command aliases. Sometimes aliases for commands like rm, cp, and ln can get into scripts by accident and make scripts break. You can avoid this by making sure your use of them doesn't trigger alias expansion for the commands, either by quoting, escaping, or using the full path.


Acceptable way of using jQuery methods in Angular directives Here is my plunker example of what I am doing.

jQuery is a great way to use slide transitions and seem to work well with angular as long as you are only using the methods on the element object inside a directive.

Basically I am using a directive for divs I want to slide toggle which listens for a broadcast from the controller which happens when the click function is called in the controller.

I am not using jQuery selectors and am only calling slideToggle() on the angular element.

Is this an acceptable angular way of doing this?  If not, what is?

HTML

    <title></title>
    <link type="text/css" rel="stylesheet" href="style.css"/>

            <input type="text" placeholder="username" />
            <input type="password" placeholder="password" />
            <button class="btn-login">Login</button>

Click here

            <input type="text" placeholder="username" />
            <input type="email" placeholder="email" />
            <input type="password" placeholder="password" />
            <button class="btn-login">Sign up</button>

Click here again

            <button>X</button>

JavaScript

var myApp = angular.module("myApp", []);

myApp.controller('mainCtrl', function($scope, $rootScope) {
  $scope.toggleClick = function(){
    $rootScope.$broadcast("toogleDiv","");
  };
});

myApp.directive('toggle', function () {
    return {
        restrict:'C',
        link: function (scope, element, attrs) {
            scope.$on("toogleDiv", function(e, val){
              element.slideToggle();
            });
        }
    }
});

I see no reason not to use JQuery animations. If you want to have your app pure angular, use angular animations.

The main issue usually being nagged about is view (dom) manipulation code in the controller, so the directive is the way to go, for sure.

The event broadcast is overkill though, just put the onclick in the directive too :) unless you are planning to put the link outside of <div class="toggle"....


Writing the condition x  0 My current condition is written as follows:

.Where(m => Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0) <= 30 && Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0) > 0)

which basically says where the rounded value is less than or equal to 30 and the rounded value is greater than 0.

Is there a neater way to write this than having

Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0)

twice in the same statement?

The full expression is:

List<Meeting> finalList = initialList.Where(m => Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0) <= 30 && Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0) > 0).ToList();

If you need to store a result of a method you should just create a method for it.

private bool IsInRange(DateTime dateTime, decimal min, decimal max)
{
    decimal totalMinutes = Math.Round((dateTime - DateTime.Now).TotalMinutes, 0);
    return totalMinutes > min && totalMinutes <= max;
}

now your expression looks like so

.Where(m => IsInRange(m.DateAndTime, 0, 30));

but the values 0 and 30 are still magic numbers which should be extracted to meaningful constants.

The choosen method name is not the best like @Falco has correctly pointed out in his comment

  UhhOhhh Horribly wrong named Function.... AreMinutesInRangeFromNow or something like this would be better - with your Method-Name I would expect no Magic happening with DateTime.Now - or pass the already substracted value, but don't hide this!

so you should change it to a better name.  I don't like the name @Falco suggested either but couldn't come up with a different one. So it is up to you to choose one.


Finding whether a number of the form 1444....4 is a perfect square Someone asked me

  We know that \$12^2 = 144\$ and that \$38^2 = 1444\$. Are there any other perfect squares in the form?

Here is my code:

public class OneFours {
public static void main(String args[]) {
    final int power_of_ten = 8;
    int num = 14;
    for (int i = 0; i <= Math.pow(10, power_of_ten); i++) {
        if (Math.pow((int) Math.sqrt(num), 2) == num) {
            System.out.println(num + " is a perfect square with root "
                    + Math.sqrt(num));
        }
        if (i % (Math.pow(10, power_of_ten) / 100) == 0)
            System.out.println("--- Progress "
                    + (int)((i / Math.pow(10, power_of_ten)) * 100) + "% complete");
        num = num * 10 + 4;
    }
}
}

I suggest you modularize your code writing a function to check for perfect squares:

public static boolean isPerfectSquare(int n) {
    return Math.pow((int) Math.sqrt(n), 2) == n;
}

And you then you can call it:

if (isPerfectSquare(num)) {
                System.out.println(num + " is a perfect square with root "
                    + Math.sqrt(num));
            }

You should also take care of always putting braces, namely

    if (i % (Math.pow(10, power_of_ten) / 100) == 0)
        System.out.println("--- Progress "
                + (int)((i / Math.pow(10, power_of_ten)) * 100) + "% complete");

should become

    if (i % (Math.pow(10, power_of_ten) / 100) == 0) {
        System.out.println("--- Progress "
                + (int)((i / Math.pow(10, power_of_ten)) * 100) + "% complete");
    }

typing braces takes  a fraction of a second, fixing bugs caused by not writing them may take hours.

And make sure you get your indentation correct, after some tweaking in my ide I your code looks like this:

public class OneFours {
    public static boolean isPerfectSquare( int n) {
        return Math.pow((int) Math.sqrt(n), 2) == n;
    }
    public static void main(String args[]) {
        final int power_of_ten = 8;
        int num = 14;
        for (int i = 0; i <= Math.pow(10, power_of_ten); i++) {
            if (isPerfectSquare(num)) {
                System.out.println(num + " is a perfect square with root "
                    + Math.sqrt(num));
            }
            if (i % (Math.pow(10, power_of_ten) / 100) == 0) {
                System.out.println("--- Progress "
                    + (int)((i / Math.pow(10, power_of_ten)) * 100) + "% complete");
            }
            num = num * 10 + 4;
        }
    }
}


C++ SQLite insert statement I insert a value into a SQLite database and return the id of the last inserted value as a result of the method.

I asked a question on Stackoverflow and I found this solution to my problem. Now I would like to get feedback if there is a simpler, smarter and/or safer way to do that:

int MyRepository::Insert(std::shared_ptr<MyObject> myObject)
{
  if(myObject == nullptr) { return -1; }

  sqlite3_exec(_connection, "BEGIN TRANSACTION;", NULL, NULL, NULL);

  std::string query = R"(
     INSERT INTO myObject (EquipmentId, ExerciseId ) VALUES (?1, ?2);
  )";

  int lastInsertedId = -1;
  sqlite3_stmt* sqlStatement;
  sqlite3_prepare_v2(_connection, query.c_str(), -1, &sqlStatement, nullptr);

  sqlite3_bind_int (sqlStatement, 1, myObject->GetEquipmentId());
  sqlite3_bind_int (sqlStatement, 2, myObject->GetExerciseId() );

  int returnCode = sqlite3_step(sqlStatement);

  if (returnCode != SQLITE_DONE)
  {
    throw SqliteException(returnCode, std::string(sqlite3_errmsg(_connection)));
  }

  query = "SELECT last_insert_rowid()";

  returnCode = sqlite3_prepare_v2(_connection, query.c_str(), -1, &sqlStatement, NULL);

  if (returnCode != SQLITE_OK)
  {
    throw SqliteException(returnCode, std::string(sqlite3_errmsg(_connection)));
  }

  returnCode = sqlite3_step(sqlStatement);

  if(returnCode == SQLITE_ROW)
  {
    lastInsertedId = sqlite3_column_int(sqlStatement, 0);
  }

  sqlite3_exec(_connection, "COMMIT;", NULL, NULL, NULL);

  sqlite3_finalize(sqlStatement);

  return lastInsertedId;
}

std::shared_ptr has a contextual conversion to bool, just like raw pointers.  So instead of comparing to nullptr, you can simply write

if (!myObject)

The raw string seems to be unnecessary:

std::string query =
    "INSERT INTO myObject (EquipmentId, ExerciseId ) VALUES (?1, ?2)";

I don't think you need the ; statement terminator in SQL queries that are already bounded by C++ API calls - they are needed in an interactive SQL shell but not here.

When we exit early (via throw of an exception), is there some mechanism to abort the transaction for us?  And to finalize the statement?

Prefer to declare your variables nearer to where they are used - specifically, lastInsertedId is a long way from where you use it:

  int lastInsertedId = -1;
  if(returnCode == SQLITE_ROW)
  {
    lastInsertedId = sqlite3_column_int(sqlStatement, 0);
  }

Or even

  const int lastInsertedId = returnCode == SQLITE_ROW
                             ? sqlite3_column_int(sqlStatement, 0)
                             : -1;


Python program to convert a 24 hour format to 12 hour format Given a string in a 24 hour format the program outputs a 12 hour format. The rules are:

The output format must be 'hh:mm a.m.' if it represents before midday and 'hh:mm p.m.' after midday
When the hour is less than 10:00 you should not write a 0 before the hour, example: '9:05 a.m.'

For example:

12:30 → 12:30 p.m.
09:00 → 9:00 a.m.
23:15 → 11:15 p.m.

The code:

import datetime
def time_converter(time):
    midday_dt = datetime.datetime.strptime('12:00','%H:%M')
    time_dt = datetime.datetime.strptime(time, '%H:%M')

    if time_dt >= midday_dt:
        if time_dt >= datetime.datetime.strptime('13:00','%H:%M'):
            hours, minutes = clamp_to_twelve(time_dt, midday_dt)
            time = f'{hours}:{minutes}'
        time += ' p.m.'
    else:
        if time_dt < datetime.datetime.strptime('10:00','%H:%M'):
            time = time[1:]
        if is_midnight(time_dt):
            hours, minutes = clamp_to_twelve(time_dt, midday_dt)
            time = f'{hours}:{minutes:02d}'
        time += ' a.m.'
    return time

def clamp_to_twelve(time_dt, midday_dt):
    clamp_dt = time_dt - midday_dt
    minutes, seconds = divmod(clamp_dt.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return [hours, minutes]

def is_midnight(time_dt):
    return (time_dt >= datetime.datetime.strptime('00:00','%H:%M') and
        time_dt <= datetime.datetime.strptime('00:59','%H:%M'))

if __name__ == '__main__':
    assert time_converter('12:30') == '12:30 p.m.'
    assert time_converter('09:00') == '9:00 a.m.'
    assert time_converter('23:15') == '11:15 p.m.'

To help with readability, I'd just import datetime.datetime and then alias it, that way you aren't typing datetime.datetime all over the place:

from datetime import datetime as dt

def time_converter(time):
    midday_dt = dt.strptime('12:00','%H:%M')
    time_dt = dt.strptime(time, '%H:%M')

    if time_dt >= midday_dt:
        if time_dt >= dt.strptime('13:00','%H:%M'):
            hours, minutes = clamp_to_twelve(time_dt, midday_dt)
            time = f'{hours}:{minutes}'
        time += ' p.m.'
    else:
        if time_dt < dt.strptime('10:00','%H:%M'):
            time = time[1:]
        if is_midnight(time_dt):
            hours, minutes = clamp_to_twelve(time_dt, midday_dt)
            time = f'{hours}:{minutes:02d}'
        time += ' a.m.'
    return time

def clamp_to_twelve(time_dt, midday_dt):
    clamp_dt = time_dt - midday_dt
    minutes, seconds = divmod(clamp_dt.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return [hours, minutes]

def is_midnight(time_dt):
    return (time_dt >= dt.strptime('00:00','%H:%M') and
        time_dt <= dt.strptime('00:59','%H:%M'))

if __name__ == '__main__':
    assert time_converter('12:30') == '12:30 p.m.'
    assert time_converter('09:00') == '9:00 a.m.'
    assert time_converter('23:15') == '11:15 p.m.'

Next, if you are just unpacking the list returned from clamp_to_twelve, I would just return a tuple:

def clamp_to_twelve(time_dt, midday_dt):
    clamp_dt = time_dt - midday_dt
    minutes, seconds = divmod(clamp_dt.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return hours, minutes

This saves you from having to construct the list, as well as the additional overhead of over-allocating memory to take into account the mutable list.

As a last optimization, you could refactor your if statements to not be nested. Because you are using if if rather than if elif, all of your statements are executed within the nested blocks:

def time_converter(time):
    midday_dt = dt.strptime('12:00','%H:%M')
    time_dt = dt.strptime(time, '%H:%M')

    if time_dt >= dt.strptime('13:00', '%H:%M'):
        hours, minutes = clamp_to_twelve(time_dt, midday_dt)
        time = f'{hours}:{minutes} p.m.'

    elif time_dt > midday_dt:
        time += ' p.m.'

    elif time_dt < dt.strptime('10:00', '%H:%M'):
        time = f'{time[1:]} a.m.'

    elif is_midnight(time_dt):
        hours, minutes = clamp_to_twelve(time_dt, midday_dt)
        time = f'{hours}:{minutes} a.m.'

    else:
        time += ' a.m.'

    return time

The only issue being that the order is quite important, since time_dt > midday_dt and time_dt >= dt.strptime('13:00', '%H:%M') are not mutually exclusive. However, you do get a slight time bump because of the separation of blocks of code:

python -m timeit -s "from file import time_converter, time_converter_2; times = ['12:30', '09:00', '11:15']" '(time_converter(t) for t in times)'
1000000 loops, best of 3: 0.275 usec per loop

python -m timeit -s "from file import time_converter, time_converter_2; times = ['12:30', '09:00', '11:15']" '(time_converter_2(t) for t in times)'
1000000 loops, best of 3: 0.277 usec per loop

Emphasis on slight. Depends on what you find more readable.


Sudoku boxes count JavaScript I'm creating Sudoku in JS but can't find the way to extract the numbers from the squares. The numbers from the rows and columns are easy to extract but I can't find the way around the squares. According to users input, I'll validate the column, then the row and finally the squares to see if the numbers are being repeated. Is this best practice?

Globals:

 var numIni = 9; //Number of squares per side;
 var squared = Math.sqrt(numIni); // I'll need this.

Column check:

function getColumn(){
var num = 30; //USER's INPUT
var colNums = []; //numbers IN the column
var countCol = num; // column anchor
while(countCol > numIni ){
    countCol -= numIni
}
colNums[0] = countCol;

for(i=1;i< numIni;i++){
    colNums[i]= colNums[i-1]+9;
 }
}

Row check:

function getRow(){
var num = 50; //USER's INPUT
var rowAnchor = (Math.ceil(num/numIni))*numIni-(numIni-1);

var rowNums=[rowAnchor]//numbers IN the row

for(i=1;i< numIni;i++){
    rowNums[i]= rowAnchor+i;
}

}

These last two work, but the squares are killing me. I'm first extracting the anchors, then building the squares and validating the number against that. It's getting quite long. Is there a better way to write this? Is the logic inefficient? If it's right, I'm stuck anyway.

Squares check (so far):

function getSquare(){
var boxes = [];
var boxesAnchor = [];
boxes[0]=1;
boxesAnchor[0]=1;

for(i=0; i< numIni*numIni ; i++){
    boxes[i]= squared + ((i-1)* squared )+1;
    }

for(i=0; i< numIni*squared ; i++){
   for(j=0; j< squared ; j++){
      boxesAnchor[i] = boxes[i];
      boxesAnchor[i+j] = boxes[i+j];
      boxesAnchor[i+j] = boxes[i+j];
   }
  i +=(numIni-1);
}

boxesAnchor.clean(undefined);// method added to the Array object

}

As we know, the numbers that could be placed in sudoku cells are limited (1..9). So we can easily make an index to existence of 1 through 9 in each row, column and square.
Consider we use rowIndex[9][10], colIndex[9][10] and sqrIndex[9][10] for this purpose. Now checking that putting value v in row x and column y would be like below:

if ( rowIndex[x][v] ) return FAILURE;
if ( colIndex[y][v] ) return FAILURE;
var sqrID = (x/3)*3 + (y/3);
if ( sqrIndex[sqrID][v] ) return FAILURE;
return SUCCESS;

and if SUCCESS is returned we can put that value in the specified cell and update our maps:

rowIndex[x][v] = colIndex[y][v] = sqrIndex[(x/3)*3+(y/3)][v] = 1;

P.S: sqrIndex address all squares in row major.


Import class using OOP I'm starting to code in the OOP way, but I have doubts with the following example.
I have a Product entity and I want to import & create instances of this entity from a CSV file.
I load the CSV file into an array in another part of the code, then I pass the array with the data to CSVImport class.

class Product
{
    private $id;

    private $name;

    private $price;

    private $stock;

    private $imageUrl;

    public function __construct() {}

    /** Getters & setters */
}

class CSVImport extends ProductImport
{
    private $websiteUrl;

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

    public function import($csvData)
    {
        $productCollection = new ProductCollection();

        foreach ($csvData as $rowData) {
            $product = $this->parseProductData($rowData);
            $productCollection->addProduct($product);
        }

        return $productCollection;
    }

    private function parseProductData($productData)
    {
        $product = new Product();

        list(
            $id,
            $name,
            $price,
            $stock,
            $imagePath
        ) = $productData;

        $product
            ->setId($id)
            ->setName($name)
            ->setPrice($price)
            ->setStock($stock)
            ->setImageUrl($this->websiteUrl.$imagePath);

        return $product;
    }
}

My questions are:

Is it correct to pass an array of data to CSVImport class? Or should it take the responsability to read & load the CSV file?
Who should take care of data validation, Product setters, CSVImport class or a new class? And how can I manage validation errors?
In case I need to transform the source data, as I've done with imageUrl, is the correct place to do it?

As I said in the comments:

  For errors, that's harder to say. Use exceptions for validation errors, catch them in the CSV reading loop, so you can continue reading. You'll have to decide what state to leave the Product class in if you do a partial read. If you don't mind passing the constructor an array of this data, even an optional array, you could do all the setting there $this->{"set$key"}($value) etc. But the big advantage is throwing an exception before the constructor completes destroys the object. Because the constructor can't return the instance in that case

Something like this

class Product
{

    private $imageUrl = false;

    public function __construct(array $data = []){
          if(!empty($data)){
             foreach($data as $line=>$value){
                if(isset($this->{$key})){
                  $this->{"set$key()"}($value);
                }
             }
         }
    }

    public setImageUrl($image){
          if(empty($image)) throw new InvalidArgumentException("Image is empty");
           $this->imageUrl= $image;

    }
}

There are a few tricks here, but you have to set the default to false for if(isset($this->{$key})) to work, but it's faster then property_exists.  This part will dynamically call setimageUrl in this case. The lowercase i doesn't matter much in setImageUrl as user defined methods/function are case insensitive.

The other part I said is this:

  This is my Opinion, 1. CSVImport , unless you also need to do arrays, in which case make another method for reading the data from the file, but it should be part of the class. The class won't work well without the CSV data. You'd have to make changes to both if fields are added etc.. You can also remove a loop by importing where the foreach is and using the file reading loop instead. 2. Product setters, if you ever need to manually create a product, you want them to do the validation too. 3. Should be part of validation, bad data goes in set, good data comes from get

Most of that is pretty self explanatory.  For #3 the ->setImageUrl($this->websiteUrl.$imagePath); is part of the input data. So that is fine.  You don't want to have to pass them separately.  In fact with data loading in the constructor of the Product you can skip that method completely as it becomes:

 private function parseProductData($productData)
 {
     return new Product($productData);
 }

So that alone saves you a call to list and a call to parseProductData for each product.

I can give you more examples if you need them

I would do the CVSImport something like this (untested)

class CSVImport extends ProductImport
{
    private $websiteUrl;

    private $errors = [];

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

    public function import($csvData)
    {
        $productCollection = new ProductCollection();
         //you could do file reading here with a while loop
        foreach ($csvData as $line=>$rowData) {
            try{
                $productCollection->addProduct(new Product($rowData));
            }catch(Exception $e){
                $this->errors[$line] = get_class($e)."::{$e->getCode()} {$e->getMessage()} in {$e->getFile()} on {$e->getLine()}";
            }

        }

        return $productCollection;
    }

    //or for max flexabillity you can do it here
    public function readCsv($filename){
        if(!file_exists($filename)) throw new Exception("Could not find file $filename".);//etc.

        $f = fopen($filename, 'r');

        $header = fgetcsv($f); //get header row
        $len = count($header);

        $line = 0;
        $rowData= [];
        while(!feof($f)){
            ++$line;

            try{
                $current = fgetcsv($f);

                if(count($current) != $len) throw new Exception("Delimter count missmatch on line $line of $filname");

                $rowData[$line] = array_combine($header, $current); //combine [$haders => $current]
            }catch(Exception $e){
                $this->errors[$line] = get_class($e)."::{$e->getCode()} {$e->getMessage()} in {$e->getFile()} on {$e->getLine()}";
            }
        }

        return $rowData;
    }

    public function getErrors(){
        return $this->errors;
    }

    public function hasErrors(){
         return count($this->errors)
    }

}

So you see the try/catch is almost the same, you could combine these two methods readCsv and import. But then you cannot accept array as data only the file. That's up to you.

The basics are that you can do new Product($data) and it does all the setting of the data using it's set methods.  Then if you throw exceptions in those set methods it not only helps you when using them manually, but when constructing a product from the CSV, the product dies as the exception is thrown. Then we catch that, keep track of it, and move on to the next row.  Each part handling it's own concerns.

In any case now it's all nice and clean, the other option would be to make a class just for reading CSV data, that takes headers as an argument, and does some mapping on them etc.  But its a lot easier to find then putting the CSV stuff in some random place.

Cheers.


Python Minimization Functions: Is the code optimal? I am rather new to python and am porting my R functions into python. I have written the functions below and the primary function is called thetaMax. That function minimizes a likelihood function or optionally minimizes a posterior distribution, depending on the option selected by method. The function works exactly as intended and I have unit tested this against my R code.

However, because I am not familiar with pythonic ways of doing this, I am curious what parts of the code below could be improved to 1) write less/more compact code and 2) to improve speed and take advantage of vectorization when possible?

A complete reproducible example is below

import numpy as np
from scipy.stats import binom
from scipy.optimize import minimize
from scipy.stats import norm

def prob3pl(theta, a, b, c, D = 1.7):
    result = c + (1 - c) / (1 + np.exp(-D * a * (theta - b)))
    return(result)

def gpcm(theta, d, score, a, D = 1.7):
    Da = D * a
    result = np.exp(np.sum(Da * (theta - d[0:score])))/np.sum(np.exp(np.cumsum(Da * (theta - d))))
    return(result)

def thetaMax(x, indDichot, a, b, c, D, d, method = 'mle', **kwargs):
    method_options = ['mle', 'map']
    optional_args = kwargs
    if method not in method_options:
        raise ValueError("Invalid method. Expected one of: %s" % method_options)
    if method == 'map' and 'mu' not in optional_args:
        raise ValueError("You must enter a value for 'mu' for the posterior distribution. Example, mu = 0")
    if method == 'map' and 'sigma' not in optional_args:
        raise ValueError("You must enter a value for 'sigma' for the posterior distribution. Example, sigma = 1")
    x1 = x[indDichot]
    x2 = np.delete(x, indDichot)
    result = [0] * len(x2)
    def fn(theta):
        if(len(x1) > 0):
            p = prob3pl(theta, a, b, c, D = D)
            logDichPart = np.log(binom.pmf(x1,1,p)).sum()
        else:
            logPolyPart = 0
        if(len(x2) > 0):
            for i in range(0,len(x2)):
                result[i] = gpcm(theta, d = d[i], score = x2[i], a = 1, D = D)
            logPolyPart = np.log(result).sum()
        else:
            logPolyPart = 0
        if(method == 'mle'):
            LL = -(logDichPart + logPolyPart)
        elif(method == 'map'):
            normal = np.log(norm.pdf(theta, loc = optional_args['mu'], scale = optional_args['sigma']))
            LL = -(logDichPart + logPolyPart + normal)
        return(LL)
    out = minimize(fn, x0=0)
    return(out)

### In order to run
d = np.array([[0, -1, .5, 1],[0,-.5,.2,1]])
a = np.array([1,1,1,1,1])
b = np.array([-1,.5,-.5,0,2])
c = np.array([0,0,0,0,0])
#x = np.array([1,1,0,1,0])
x = np.array([1,1,0,1,0,1,1])
indDichot = range(0,5,1)

object = py.thetaMax(x,indDichot,a,b,c,D=1,d = d)

PEP-8 Violations

The Style Guide for Python Code enumerates many conventions that all Python code should follow.  You have deviated from these conventions in several areas:

mixedCase is discouraged.  Function names, methods and variable should all be snake_case.  This means thetaMax should be called theta_max.  (Exceptions are allowed for things like Da, where consistency with mathematical notation is more important than consistency with Python style.)
return is not a function call; it should not have parenthesis.  Ie) return(result) should be written as return result.
if is also not a function call, nor is Python a C-like language; it should not have parenthesis.  if(method == 'mle'): should be written as if method == 'mle':
Binary operators should have one space before and after it.  This is only violated by the division operation in gpcm from my quick perusal of the code.
Commas should be followed by one space.
The equal sign used in keyword=parameter should not have a space before or after it.  This applies both to the function definitions def gpcm(theta, d, score, a, D=1.7): and function calls p = prob3pl(theta, a, b, c, D=D)
Builtin Python identifiers should not be redefined without reason.  object is such an identifier.  A better name should be used.

Truthiness of lists.

A container used in a boolean context is True if the container is not empty, and False if the container is empty.  There is no need to fetch the length of the container, test that value is greater than zero:

if x1:

is more "Pythonic" than:

if(len(x1) > 0):

Ranges Start at Zero by Default

By default, all ranges start at 0.  This means range(0, len(x2)) is much more commonly written as range(len(x2)).

Iteration over a container

Python is a scripting language, where the script can assign its own implementation for many operations including subscripting, and iteration.  This makes it impossible for Python to optimize code like:

for i in range(0, len(x2)):
    ... use the value x2[i] ...

It will usually be more efficiently written as:

for x2_i in x2:
    ... use the value x2_i ...

If the index is needed along with the values, then enumerate() is used for the most efficient result:

for i, x2_i in enumerate(x2):
    result[i] = gpcm(theta, d=d[i], score=x2_i, a=1, D=D)

Iterating over two (or more) parallel list (d and x2) would be done using zip:

for d_i, x2_i in zip(d, x2):
    ... = gpcm(theta, d=d_i, score=x2_i, a=1, D=D)

And if the indices are also needed, enumerate(zip(...)):

for i, (d_i, x2_i) in enumerate(zip(d, x2)):
    result[i] = gpcm(theta, d=d_i, score=x2_i, a=1, D=D)

But building up a complete array is more commonly done with list comprehension:

result = [ gpcm(theta, d=d_i, score=x2_i, a=1, D=D) for d_i, x2_i in zip(d, x2) ]

which eliminates the need for the result = [0] * len(x2) pre-allocation.

Keyword Arguments

What arguments can be passed to thetaMax()?

The answer is "any".  The user has no way of knowing what is possible, or allowed.  You can pass optimization_level=18 without error ... and without effect.

It would be safer to define the function with the allowed keyword arguments explicitly:

def thetaMax(x, indDichot, a, b, c, D, d, method='mle', *, mu=None, sigma=None):

    if method not in {'mle', 'map'}:
        raise ValueError("Invalid method")
    if method == 'map':
        if mu is None or sigma is None:
            raise ValueError("Both mu= and sigma= keyword arguments must be given")
    elif method == 'mle':
        if mu is not None or sigma is not None:
            raise ValueErorr("Neither mu= or sigma= is appropriate for 'mle'")

As a bonus, having the values already extracted into their own variables is faster than repeatedly looking up optional_args['mu'] and optional_args['sigma'] during each and every call of fn() during the minimize function.

Additional speed may come from defining different fn() functions for the 6 different combinations of len(x1) > 0, len(x2) > 0, and method, thus removing the conditionals from inside the nested calls.


BFS implementation in JAVA import java.util.*;

public class BFS {
    static LinkedList<Node> tracker = new LinkedList<>();
    static Node[] nodes = new Node[]{
            new Node(1),
            new Node(2),
            new Node(3),
            new Node(4),
            new Node(5),
            new Node(6),
    };

    public static void main(String[] args) {

        Map<Node, ArrayList<Edge>> graph = new TreeMap<>();
        graph.put(nodes[3], addEdges(2,3,5,6));
        graph.put(new Node(5), addEdges(3,4,6));
        graph.put(new Node(6), addEdges(4,5));
        graph.put(new Node(1), addEdges(2,3));
        graph.put(new Node(2), addEdges(1,4));
        graph.put(new Node(3), addEdges(1,4,5));

        traverse(graph, nodes[0]);

    }

    private static ArrayList<Edge> addEdges(int... edges) {
        ArrayList<Edge> edgeList = new ArrayList<>(edges.length);
        for(int edge : edges)
            edgeList.add(new Edge(nodes[edge-1]));
        return edgeList;
    }

    static class Node implements Comparable<Node>{
        final int vertex;
        boolean isExplored;

        Node(int vertex) {
            this.vertex = vertex;
        }

        @Override
        public int compareTo(Node node) {
            return this.vertex - node.vertex;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Node)) return false;
            Node node = (Node) o;
            return vertex == node.vertex;
        }

        @Override
        public int hashCode() {
            return Objects.hash(vertex, isExplored);
        }
    }

    static class Edge {
        Node endNode;
        boolean isExplored;
        Edge(Node endPoint) {
            this.endNode = endPoint;
        }
    }

    private static void traverse(Map<Node, ArrayList<Edge>> graph, Node startNode) {
        startNode.isExplored = true;
        tracker.add(startNode);
        System.out.println("Start Node -> " + startNode.vertex + " (" + startNode.hashCode() + ")");
        while(!tracker.isEmpty()) {
            Node top = tracker.pop();
            System.out.println("Top Node ->" + top.vertex + " (" + top.hashCode() + ")");
            for(Edge edge : graph.get(top)) {
                System.out.println("About to check Node ->" + edge.endNode.vertex);
                if(!edge.isExplored && !edge.endNode.isExplored) {
                    edge.endNode.isExplored = true;
                    edge.isExplored = true;
                    tracker.add(edge.endNode);
                    System.out.println("Marked Node ->" + edge.endNode.vertex);
                }
            }
        }
    }
}

I have implemented BFS can someone please review it and give recommendations. My main concern(but not limitted to) is the way I defined Graph i.e. Node and Edge class isn't a standard way of dealing with graphs.

Data structure
There is no such thing as a "standard graph data structure." There are a few different data structures for representing a graph and you have implemented the adjacency list. The main problem with your implementation is that you have actually implemented the traversal algorithm and the data structure is just an "accessory" to it. It is not possible to extract the graph from the code and use it somewhere else so there is not much point in spending a lot of time reviewing the graph implementation as a data structure.
I would expect a graph data structrue to be encapsulated in a class named Graph (or an interface named Graph with implementations in classes like AdjacencyListGraph and AdjacencyMatrixGraph). The purpose of the encapsulation is to protect the data structure from manipulation which would break the data structure. For example, as you represent the adjacency as a Map<Node, ArrayList<Edge>> you allow a situation where a single edge could be assigned to two nodes, which would destroy your traversal algorithm.
Your Edge implementation is tightly bound to the traversal algorithm because you have placed the isExplored attribute to it. A pure graph implementation should not be concerned about how it is traversed.


Double LinkedList Deep Copy in Kotlin with Generics and Thread Safety Goal

Return a deep copy of a double LinkedList.
Each node also contains an additional random pointer, potentially to any node or null.

Code to start
data class Node<T>(
    var data: T?,
    var previous: Node<T>? = null,
    var next: Node<T>? = null,
    var random: Node<T>? = null

class LinkedList {
    // TODO: Implement deep copy here.
}

Questions

Generics - Is there a better approach to handle the generic variance as to not need as T when passing in a generic type? i.e. linkedList.add(data = 1 as T)
Add thread-safety for operations - Are there any specific recommendations on thread-safety for this solution or broader topics to research to understand thread-safety considerations further?

Implement
See the full code on GitHub.
LinkedList.kt
class Node<T>(
        var prev: Node<T>? = null,
        var next: Node<T>? = null,
        var rand: Node<T>? = null,
        var data: T
)

class LinkedList<T>(
        var first: Node<T>? = null,
        var last: Node<T>? = null,
        val randMap: HashMap<Node<T>?, Node<T>?> = hashMapOf()
) {
    // Add Node to the end of LinkedList
    fun add(data: T): Node<T> {
        val temp = last
        val newNode = Node(prev = temp, data = data)
        last = newNode
        if (temp == null)
            first = newNode
        else
            temp.next = newNode
        return newNode
    }

    fun deepCopyWithoutRandoms(prev: Node<T>?, node: Node<T>?): Node<T>? {
        return if (node == null)
            null
        else {
            val newNode = Node(data = node.data)
            if (node.rand != null) {
                newNode.rand = node.rand
                randMap.put(node.rand, null)
            }
            newNode.prev = prev
            newNode.next = deepCopyWithoutRandoms(newNode, node.next)
            if (randMap.containsKey(node))
                randMap.put(node, newNode)
            return newNode
        }
    }

    fun updateRandoms(node: Node<T>?): Node<T>? {
        if (node != null) {
            if (node.rand != null)
                node.rand = randMap.get(node.rand!!)
            updateRandoms(node.next)
            return node
        } else return null
    }

    fun clear() {
        var node = first
        while (node != null) {
            node.prev = null
            node.next = null
            node.rand = null
            node.data = 0 as T
            node = node.next
        }
    }

    fun toString(first: Node<T>?): String {
        var output = ""
        var node = first
        while (node != null) {
            output += String.format("(prev:%s next:%s data:%s random:%s)\n", node.prev, node.next, node.data, node.rand)
            node = node.next
        }
        return output
    }
}

I'm not going to touch on your question on thread safety as it is a broad topic I am not familiar with. However, I can help with your questions about generics.
Right now, you're using generics great, except in one single place
node.data = 0 as T

The type of node.data is T. This code will fail if T is not Int - for example, if T is String, the code will look like this:
node.data = 0 as String

and that will throw a runtime exception.
Here's the important thing, though. There's no reason to do node.data = <anything>.
I assume the reason for having it originally was to "zero out" or get rid of the data as it's removed from the list - but that's what java will do for you automatically!
Let's say you have the following structure
linked list    /--> node 1   /--> value 1
-----------    |    ------   |    --------
first node ---/     data ---/        7

when you delete the pointer to node 1, you end up in this situation
linked list         node 1   /--> value 1
-----------         ------   |    --------
first node->null    data ---/        7

now that there is no reference anywhere to node 1, the jvm garbage collector deletes it
linked list         value 1
-----------         ------
first node->null        7

and because there is no reference to value 1, it's also deallocated.
This means that there's no reason to set the data field to anything - and, besides the point, there is no possible value you could set it to that would work for any value of T (in java, though, you could use null)


soundex implementation The soundex algorithm maps several spellings of a name to a 4 character term. (hopefully mapping all different transcriptions to the same term) The steps as described in Introduction to information retrieval are:

Keep first Letter for the rest:
Change any of 'A', 'E', 'I', 'O', 'U', 'H', 'W', 'Y' to zero
Change all other characters to 1-6, see below
remove consecutive doubles
remove all zeros, right pad with 0s, keep first 3

I implemented a working solution, but can it be implemented more readable?

import Data.Char

soundex :: String -> String
soundex []      = []
soundex (n:ame) = result
  where
    compr  = map (compress . toUpper) ame
    noDoub = remDoubles compr
    noZero = filter (/='0') noDoub
    result = n: take 3 (noZero++"000")

remDoubles :: String -> String
remDoubles []       = []
remDoubles (a:[])   = [a]
remDoubles (a:b:bs) | a==b      = remDoubles   (b:bs)
                    | otherwise = a:remDoubles (b:bs)

compress :: Char -> Char
compress char | char `elem` "AEIOUHWY" = '0'
              | char `elem` "BFPV"     = '1'
              | char `elem` "CGJKQSXZ" = '2'
              | char `elem` "DT"       = '3'
              | char `elem` "L"        = '4'
              | char `elem` "MN"       = '5'
              | char `elem` "R"        = '6'
              | otherwise              = char

Correctness

The algorithm is actually quite tricky to implement correctly.  Your algorithm gives the wrong results for some examples in the Wikipedia article:

$$\begin{array}{l|l|l}
\textrm{Name} & \textrm{Correct Soundex} & \textrm{Your result} \\
\hline
\textrm{Ashcroft} & \textrm{A261} & \textrm{A226} \\
\textrm{Pfister} & \textrm{P236} & \textrm{P123} \\
\end{array}$$

Specifically, note the following rule:

  Two letters with the same number separated by 'h' or 'w' are coded as a single number, whereas such letters separated by a vowel are coded twice. This rule also applies to the first letter.

As a consequence, the code must…

… treat "H" and "W" differently from the vowels, so char `elem` "AEIOUHWY" = '0' is wrong.  I recommend using '0' to temporarily indicate the presence of a vowel, and dropping 'H' and 'W' unless it is in the initial position.
… lookup the digit for the first character too, to see if the next nonzero digit should be discarded.  Therefore, compr  = map (compress . toUpper) ame is wrong.

Style

ame and noDoub are pretty weird variable names.  For a clear and idiomatic function definition, I suggest

soundex name@(n:ns) = n : take 3 (noZero ++ "000")
  where
    …

Note that result should probably be eliminated.

remDoubles could be simplified to map head . group, using the group function from Data.List.  I would rename remDoubles to dedup.

compress is oddly named, as it maps one Char to exactly one Char.

I prefer imports to be more explicit about what functions are imported.

Suggested solution

import Data.Char (toUpper)
import Data.List (group)

soundex :: String -> String
soundex []   = []
soundex name = (toUpper $ head name) : nnn
  where
    dedup = map head . group
    nnn = take 3 $ (++ "000") $ filter (/= '0') $ tail $ dedup $ digitize name

digitize :: String -> String
digitize name = d : filter (/= '-') ds
  where
    digitFor c
      | c `elem` "AEIOUY"   = '0'
      | c `elem` "BFPV"     = '1'
      | c `elem` "CGJKQSXZ" = '2'
      | c `elem` "DT"       = '3'
      | c `elem` "L"        = '4'
      | c `elem` "MN"       = '5'
      | c `elem` "R"        = '6'
      | otherwise           = '-'   -- 'H', 'W', and punctuation
    (d:ds) = map (digitFor . toUpper) name

Note that the order of the chain of functions used to define nnn is critical.  Yours was closer to…

nnn = take 3 $ (++ "000") $ filter (/= '0') $ dedup $ digitize $ tail name

… which explains the "Pfister" bug.

To address the "Ashcroft" bug, I've rewritten compress as digitize, which can return a shorter string that drops output corresponding to a non-initial 'H' and 'W'.


Create URL query string from dictionary I have a dictionary of parameters and value, and the function creates a URL query string from it:

Private Function _BuildUrlFromPermalinkArgumentDictionnary(ByVal oParameters As Dictionary(Of String, String))
    Dim returnString As String = ""
    For Each kvp In oParameters
        returnString += kvp.Key + "=" + kvp.Value + "&"
    Next
    Return Left(returnString, Len(returnString) - 1)
End Function

For example, the input dictionary

A -> 12356
B -> foo
C -> bar

have the output A=12356&B=foo&C=bar

I would like to improve this, not really for performance, because the dictionary is small enough that it will be really fast no matter what, but as an opportunity to learn what I could have done in a better way.

In particular, the way I remove the trailing & feels wrong.

This isn't a bad approach - simple, effective, and gets the job done. It could be ever-so-slightly better, though.

First, string concatenation (str1 & str2, str1 + str2) in .NET has been known to be extremely slow at times, due to extra allocations. (Basically, str1 + str2 + str3 + str4 creates a temp string str12, then creates another temp string str123 and then creates a final string str1234. Doing this in a loop means that it creates a temp string returnStringStr1234 then sets returnString to that, and then repeats all four of these new allocations for each iteration, at a minimum.) There's something in the framework called StringBuilder, and I'd like to recommend you look into it.

I should also mention that we also use StringBuilder from a semantics point of view: instead of wondering what returnString does (is it a bunch of sub-strings, is it just one string being set by a certain loop iteration, etc.) we have something that indicates that our return value should be building a string. Everything starts to make sense.

Essentially, the StringBuilder has a sort of internal buffer that, instead of creating a new copy of the strings, it just adds the strings together. This also exposes a few useful properties, one of which being Length, which can be increased or decreased, removing the need for Left(...).

Dim result As New StringBuilder()
For Each kvp in oParameters
    result.Append(kvp.Key).Append("="c).Append(kvp.Value).Append("&"c)
Next
result.Length -= 1
Return result.ToString()

This is only one line-of-code longer than your version, but it should perform more quickly and is also clearer about what the last step is (remove the last character). Of course, an alternative implementation that avoids manipulating the StringBuilder like that might look like:

Dim result As New StringBuilder()
For Each kvp In oParameters
    If result.Length > 0 Then result.Append("&"c)
    result.Append(kvp.Key).Append("="c).Append(kvp.Value)
Next
Return result.ToString()

In this situation we test if the Length is > 0 to see if it already has an element. If so, we append the ampersand ("&"c) and continue on. Now we don't need to worry about the last character being an ampersand at all.

I've used a couple constructs that may be unfamiliar to you:

The If expression Then statement is a single-line If statement. It must be on one line (unless in a line-continuation context) and will do the same thing as If expression Then <NEWLINE> statement <NEWLINE> End If, but is much more succinct. I use them for guard-clauses like this a lot.
The "_"c construct creates a character literal from the specified string (which should be one character only). The c is the magic bit, you can remove it from everything if you like.

I would also recommend adding the explicit type for your kvp:

For Each kvp As KeyValuePair(Of String, String) In oParameters
    ...
Next

This makes it much more clear to the compiler as to what type you expect, and tells future programmers that you do know what you're doing.

Overall, good work. Hopefully this is somewhat educational for you and not just a bunch of random nonsense. :)


Sleep and background wakeup system I'm looking for code review of part of my replacement of timeout() project. Namely, feedback on SleeperNotifier class:
https://github.com/ledestin/frugal_timeout/blob/master/lib/frugal_timeout.rb#L125

If you would like to give feedback on the whole project, by all means do.

  # {{{1 SleeperNotifier
  # Executes callback when a request expires.
  # 1. Set callback to execute with #onExpiry=.
  # 2. Set expiry time with #expireAt.
  # 3. After the expiry time comes, execute the callback.
  #
  # It's possible to set a new expiry time before the time set previously
  # expires. In this case, processing of the old request stops and the new
  # request processing starts.
  class SleeperNotifier # :nodoc:
    include MonitorMixin

    def initialize
      super()
      @condVar, @expireAt, @onExpiry = new_cond, nil, proc {}

      @thread = Thread.new {
        loop {
          @onExpiry.call if synchronize {
            # Sleep forever until a request comes in.
            wait unless @expireAt

            timeLeft = calcTimeLeft
            disposeOfRequest
            elapsedTime = MonotonicTime.measure { wait timeLeft }

            elapsedTime >= timeLeft
          }
        }
      }
      ObjectSpace.define_finalizer self, proc { @thread.kill }
    end

    def onExpiry &b
      @onExpiry = b
    end

    def expireAt time
      synchronize {
        @expireAt = time
        signalThread
      }
    end

    private

    def calcTimeLeft
      synchronize {
        delay = @expireAt - MonotonicTime.now
        delay < 0 ? 0 : delay
      }
    end

    def disposeOfRequest
      @expireAt = nil
    end

    def signalThread
      @condVar.signal
    end

    def wait sec=nil
      @condVar.wait sec
    end
  end

How do you cancel a sleep once it starts?  I would expect that calling .expireAt(nil) might accomplish that.  However, if @expireAt is nil, calcTimeLeft() crashes.

Alternatively, one might try to call .onExpiry(nil), but you don't handle @onExpiry being nil either.


Time Limit decorator I have an interface named ICodeRunner, defined like this:

public interface ICodeRunner
{
        ExecutionResult Run(string code);
}

I have more classes that implement ICodeRunner, but regardless of which one is used, in some contexts only I have to impose a time limit on the execution of the Run method. This is a regular timeout: "if it's not done in x seconds, throw an exception."

To achieve this, I have created a class called CodeRunnerTimeLimitDecorator that can wrap any class implementing ICodeRunner and provide this functionality.

This is how the class is implemented:

public class CodeRunnerTimeLimitDecorator : ICodeRunner
{
        private readonly ICodeRunner _wrapped;
        private readonly int _timeoutInSeconds;

        public CodeRunnerTimeLimitDecorator(ICodeRunner wrapped, int timeoutInSeconds)
        {
                _wrapped = wrapped;
                _timeoutInSeconds = timeoutInSeconds;
        }

        public ExecutionResult Run(string code)
        {
                var executionResult = new ExecutionResult();

                var t = new Thread(() => executionResult = _wrapped.Run(code));

                t.Start();

                var completed = t.Join(_timeoutInSeconds * 1000);

                if (completed)
                        return executionResult;

                throw new ApplicationException(
                        string.Format("Code took longer than {0} seconds to run, so it was aborted.", _timeoutInSeconds));
        }
}

While I welcome any advice about how to make this code better, I'm particularly interested in comments/improvements regarding the time limit mechanism.

Update:

More specifically, the questions are:

Is there an easier/cleaner way to do it?
Would it be OK if I called t.Abort() in case the timeout had elapsed*?

*I do not control the process that goes on inside _wrapped.Run(code), so I cannot implement Task Cancellation or similar techniques.

This is actually a stab in the dark but could you use the .NET 4 System.Threading.Task object for this.  Something like:

var task = Task.Factory.StartNew(() => _wrapped.Run(code) });

// Wait returns true if the task finished within the allocated timeframe
// http://msdn.microsoft.com/en-us/library/dd270644.aspx
if(task.Wait(_timeoutInSeconds * 1000))
{
   return executionResult;
}
else
{
   throw new ApplicationException(string.Format("Code took longer than {0} seconds to run, so it was aborted.", _timeoutInSeconds));
}


Parse a specified arithmetic type from string This class has the responsibility of parsing a string to one of the primitive types: int, double, float, decimal...

While creating it, I have noticed that it'll be terribly ugly.

It basically should perform a TryParse of each primitive type and return the first that returns true, along with the parsed value.

public static class PrimitiveParser
{
    public static bool TryParse(Type targetType, string sourceValue, out object result)
    {
        result = null;

        if (targetType == typeof(int))
        {
            int intResult;
            var parseResult = int.TryParse(sourceValue, out intResult);
            {
                result = intResult;
                return parseResult;
            }
        }
        if (targetType == typeof(double))
        {
            double doubleResult;
            var parseResult = double.TryParse(sourceValue, out doubleResult);
            {
                result = doubleResult;
                return parseResult;
            }
        }
        if (targetType == typeof(float))
        {
            float floatResult;
            var parseResult = float.TryParse(sourceValue, out floatResult);
            {
                result = floatResult;
                return parseResult;
            }
        }

        /// ...

        return false;
    }
}

I'd prefer to use a dictionary for this.

private delegate bool TryParseDelegate<T>(string text, out T value);

private static readonly Dictionary<Type, object> TryParsers = new Dictionary<Type, object>
{
    { typeof(int), (TryParseDelegate<int>)int.TryParse },
    { typeof(float), (TryParseDelegate<float>)float.TryParse },
    { typeof(double), (TryParseDelegate<double>)double.TryParse }
};

The TryParse method:

public static bool TryParse<T>(string value, out T returnValue)
{
    // Check if we have a parse method for T in the dictionary.
    object parserObj;
    if (TryParsers.TryGetValue(typeof(T), out parserObj))
    {
        TryParseDelegate<T> parser = (TryParseDelegate<T>)parserObj;
        return parser(value, out returnValue);
    }
    // If no, fallback to IConvertible.
    if (typeof(IConvertible).IsAssignableFrom(typeof(T)))
    {
        try
        {
            returnValue = (T)Convert.ChangeType(value, typeof(T));
            return true;
        }
        catch { }
    }
    // No luck.
    returnValue = default(T);
    return false;
}

This approach support exensibility.
For example, imagine we have a class A:

public class A
{
    public static readonly A Zero = new A("Zero");
    public static readonly A One = new A("One");

    public readonly string Text;

    private A(string text)
    {
        Text = text;
    }

    public static bool TryParse(string text, out A value)
    {
        switch (text.ToLower())
        {
            case "zero":
                value = Zero;
                break;
            case "one":
                value = One;
                break;
            default:
                value = null;
                return false;
        }
        return true;
    }

    public override string ToString()
    {
        return Text;
    }
}

Then the only thing you have to do is to append an item to the dictionary:

{ typeof(A), (TryParseDelegate<A>)A.TryParse }

Let's test it:

int i;
double d;
A a;

if (TryParse("123", out i))
    Console.WriteLine($"i={i}"); // Prints i=123
if (TryParse("123.456", out d))
    Console.WriteLine($"d={d}"); // Prints d=123.456
if (TryParse("ONE", out a))
    Console.WriteLine($"a={a}"); // Prints a=One


Enumerating RCData resources from the EXE file which has been launched I am running Delphi XE6.

I recently integrated all of my read-only language INI files into the executables.

As a consequence, I need to enumerate RCData resources (and then simply filter out the languages).

I stumbled across solution, which I lightly changed into this form:

function EnumRCDataProc(hModule: HMODULE; lpszType, lpszName: PChar; lParam: NativeInt): BOOL; stdcall;
begin
  TStrings(lParam).Add(lpszName);
  Result := True;
end;

function EnumerateResourceNames: string;

var
  ExecutableHandle: HMODULE;
  ResourcesList: TStringList;

begin
  ExecutableHandle := LoadLibrary(PChar(Application.ExeName));
  try
    ResourcesList := TStringList.Create;
    try
      EnumResourceNames(ExecutableHandle, RT_RCDATA, @EnumRCDataProc, NativeInt(ResourcesList));
      Result := ResourcesList.Text;
    finally
      ResourcesList.Free;
    end;
  finally
    FreeLibrary(ExecutableHandle);
  end;
end;

It is indeed working. Do you see any possible problems?

The code is mostly fine but there a couple of minor issues:

The documentation for EnumResNameProc explains that lpszType and lpszName could be IDs rather than strings. Use the helper function Is_IntResource from the Windows unit to identify such IDs and treat accordingly.
Using LoadLibrary is fine, but it will result in code in the DLL being executed. Instead you are better to use LoadLibraryEx passing the LOAD_LIBRARY_AS_DATAFILE or LOAD_LIBRARY_AS_IMAGE_RESOURCE for the flags.


String validation based on multiple criteria I had me a code challenge and I was thinking: is there a way to make this more efficient and short? The challenge requires me to scan a string and ...

In the first line, print True if it has any alphanumeric characters. Otherwise, print False.

In the second line, print True if it has any alphabetical characters. Otherwise, print False.

In the third line, print True if it has any digits. Otherwise, print False.

In the fourth line, print True if it has any lowercase characters. Otherwise, print False.

In the fifth line, print True if  has any uppercase characters. Otherwise, print False.

Below is my approach :
def func_alnum(s):
    for i in s:
        if i.isalnum():
            return True
    return False

def func_isalpha(s):
    for i in s:
        if i.isalpha():
            return True
    return False

def func_isdigit(s):
    for i in s:
        if i.isdigit():
            return True
    return False

def func_islower(s):
    for i in s:
        if i.islower():
            return True
    return False

def func_isupper(s):
    for i in s:
        if i.isupper():
            return True
    return False
if __name__ == '__main__':
    s = input()
    s=list(s)
    print(func_alnum(s))
    print(func_isalpha(s))
    print(func_isdigit(s))
    print(func_islower(s))
    print(func_isupper(s))

It feels like I made a mountain out of a molehill. But I would defer to your opinions on efficiency and shortness before I live with that opinion.

Your five functions only differ by the predicate used to test each character, so you could have a single one parametrized by said predicate:

def fulfill_condition(predicate, string):
    for character in string:
        if predicate(character):
            return True
    return False

if __name__ == '__main__':
    s = input()
    print(fulfill_condition(str.isalnum, s))
    print(fulfill_condition(str.isalpha, s))
    print(fulfill_condition(str.isdigit, s))
    print(fulfill_condition(str.islower, s))
    print(fulfill_condition(str.isupper, s))

Note that you don't need to convert the string to a list for this to work, strings are already iterables.

Now we can simplify fulfill_condition even further by analysing that it applies the predicate to each character and returns whether any one of them is True. This can be written:

def fulfill_condition(predicate, string):
    return any(map(predicate, string))

Lastly, if you really want to have 5 different functions, you can use functools.partial:

from functools import partial

func_alnum = partial(fulfill_condition, str.isalnum)
func_isalpha = partial(fulfill_condition, str.isalpha)
func_isdigit = partial(fulfill_condition, str.isdigit)
func_islower = partial(fulfill_condition, str.islower)
func_isupper = partial(fulfill_condition, str.isupper)


Combinatorics challenge solved it Python The easiest way to explain this problem is to show these two test cases:
assert solution('ABC') == ['A', 'B', 'C', 'AB', 'AC', 'BC', 'ABC']
assert solution('ABCD') ==  ['A', 'B', 'C', 'D', 'AB', 'AC', 'AD', 'BC', 'BD', 'CD', 'ABC', 'ABD', 'ACD', 'BCD', 'ABCD']

my solution is below:
def subsolution(lst, length):
    return [lst + [x] for x in·
            range(lst[-1]+1, length)]

def solution(symbols):
    length = len(symbols)
    result = [[[x] for x in range(length)]]
    while True:
        subres = []
        for x in result[-1]:
            subres.extend(subsolution(x, length))
        if not subres:
            break
        result.append(subres)
    result = [ item for sublist in result
        for item in sublist
    ]
    result = [
        ''.join(symbols[s] for s in el)
        for el in result
    ]
    return result

Style
We all have our own 'what is the best' style. However even if you do something that others don't agree with, if you're consistent about it then that's all that matters.

From here you have some inconsistencies in your code.

Indent style. You don't have a fixed style, and you've mixed two styles together to make something I think both sides can agree is not right.

With opening delimiter:

return [lst + [x] for x in·
        range(lst[-1]+1, length)]

Hanging indent:

result = [
    ''.join(symbols[s] for s in el)
    for el in result
]

Both:

result = [ item for sublist in result
    for item in sublist
]

You're not consistent in your newlines in comprehensions.

Item and for _ in on first line:

return [lst + [x] for x in·
        range(lst[-1]+1, length)]

Item and entire for _ in ... on first line:

result = [ item for sublist in result
    for item in sublist
]

Item on first line:

result = [
    ''.join(symbols[s] for s in el)
    for el in result
]

We can fix these by just having a consistent style.
return [
    lst + [x]
    for x in range(lst[-1]+1, length)
]

result = [
    item
    for sublist in result
    for item in sublist
]

result = [
    ''.join(symbols[s] for s in el)
    for el in result
]

Improvements

Your last two comprehensions that build two lists are wasteful when you can just merge the comprehensions together. This will also improve readability.
return [
    ''.join(symbols[s] for s in item)
    for sublist in result
    for item in sublist
]

Your code is not very readable. I can't tell that you're effectively calling itertools.combinations len(symbols) times.
Whilst combinatorics are not very pleasant to read, your code doesn't show the most basic part clearly.
def solution(symbols):
    for i in range(1, 1 + len(symbols)):
        yield from itertools.combinations(symbols, i)

Overall
You should get a consistent style and your code has some improvements to be made.
However your code is pretty good on the combinations front.
The range aspect is smart, maybe too smart, but if you used a docstring to explain the input and output then the implementation details can be guessed at fairly easily from your code.


Optimizing this 'print up to the nth prime number' script I've been seeking to optimize this algorithm, perhaps by eliminating one of the loops, or with a better test to check for prime numbers.

I'm trying to calculate and display 100000 prime numbers has the script pausing for about 6 seconds as it populates the list with primes before the primes list is returned to the console as output.

I've been experimenting with using

print odd,

to simply print every found prime number, which is faster for smaller inputs like n = 1000, but for n = 1000000 the list itself prints much faster (both in the Python shell and in the console).

Perhaps the entire code/algorithm should be revamped, but the script should remain essentially the same: The user types in the number of prime numbers to be printed (n) and the script returns all prime numbers up to the nth prime number.

from time import time
odd = 1
primes = [2]
n = input("Number of prime numbers to print: ")
clock = time()
def isPrime(number):
    global primes
    for i in primes:
        if i*i > number:
            return True
        if number%i is 0:
            return False
while len(primes) < n:
    odd += 2
    if isPrime(odd):
        primes += [odd]
print primes
clock -= time()
print "\n", -clock
raw_input()

Welcome to programming and code review!

Your code is pretty good especially for a beginner, but I'm going to be picky:

from time import time

I recommend putting at least one blank line between the imports and the code proper

odd = 1

You don't use this until much later. Don't declare variables until you actually need them. It will make the code easier to read.

primes = [2]
n = input("Number of prime numbers to print: ")

Rather than using input, I recommend using int(raw_input(. Input actually interprets the text entered as a python expression which means it can do anything. If you really just wanted a number, using int(raw_input is better. Also, input has been modified in python 3 to be like raw_input.

clock = time()
def isPrime(number):

Typically functions are defined before the actual code not in the middle of it.

    global primes

global is only necessary if you want to modify the primes. Since you don't modify it, you don't need it.

    for i in primes:
        if i*i > number:

It's not immediately obvious why you can stop here. A comment would be helpful.

            return True
        if number%i is 0:

Put spaces around your operators: %

            return False
while len(primes) < n:
    odd += 2
    if isPrime(odd):
        primes += [odd]

When adding a single element to a list use primes.append(odd)

print primes
clock -= time()

That's kinda confusing. I'd suggest doing start_time = .., end_time = ..., time_spent = end_time - start_time. That ways it clear what you are doing, whereas what you've done with the clock is unusual and not immeadiately obvious.

print "\n", -clock
raw_input()

Also, don't put logic in the top level scope of your program. Put all logic especially loops inside a function. It'll run faster in the function, and will keep the program neater.


Tip Calculator in pure JS A simple tip calculator that asks for the total bill amount, service quality (used to determine what percentage of the total cost will be tipped), and how many people are sharing the bill (used to split the tip so that everyone pays the same amount).

I am primarily looking for possible improvements to performance or readability, but any suggestion is welcome.

See the code in action - jsFiddle

Link to repository - GitHub

// Pointers
const billAmountAlertPointer = document.getElementById('billAmountAlert');
const tipPercentageAlertPointer = document.getElementById('tipPercentageAlert');
const numberOfPeoplePointer = document.getElementById('numberOfPeople');
const serviceQualityPointer = document.getElementById('serviceQuality');
const numberOfPeopleLabelPointer = document.getElementById('numberOfPeopleLabel');
const eachPointer = document.getElementById('each');
const soundPointer = document.getElementById('cashRegisterSound');
soundPointer.volume = 0.05;
var numberOfPeople = 1;

// Display the text 'people' next to the input if the number of people is higher than 1
numberOfPeoplePointer.oninput = function(){
    numberOfPeople = numberOfPeoplePointer.value;
    numberOfPeople > 1 ? numberOfPeopleLabelPointer.innerHTML = 'people' : numberOfPeopleLabelPointer.innerHTML = 'lone wolf';
};

document.getElementById('calculateButton').addEventListener('click', function() {
    let billAmount = document.getElementById('billAmount').value;
    let tipPercentage = serviceQualityPointer.value;
    // Only proceed if both the billAmount and the tipPercentage have a value
    if (billAmount !== '' && tipPercentage !== ''){
        setDisplay(billAmountAlertPointer, 'none');
        setDisplay(tipPercentageAlertPointer, 'none');
        let tipAmount = (billAmount / (100 / tipPercentage)) / numberOfPeople;
        document.getElementById('tipAmount').innerHTML = '$' + tipAmount;
        /* If the number of people sharing the bill is higher than 1, display the text 'each'
        next to the input. Otherwise, don't.*/
        numberOfPeople > 1 ? setDisplay(eachPointer, 'block') : setDisplay(eachPointer, 'none');
        document.getElementById('tipAmountContainer').style.display = 'block';

        // Play the cash register sound
        playSound();
    } else{
        // If the user hasn't entered the bill amount, display an alert
        if (billAmount === ''){
            setDisplay(billAmountAlertPointer, 'inline');
        }
        // If the user hasn't entered the tip percentage, display an alert
        if (tipPercentage === ''){
            setDisplay(tipPercentageAlertPointer, 'inline');
        }
    }
});

function setDisplay(element, value){
    element.style.display = value;
}

function playSound(){
    soundPointer.play();
}

Review

For what it does that is very dense code. Consider reducing variable name length.

Major points

Direct element reference reduces code size, improves performance, and forces you to ensure element IDs and names are unique.
Adding content via innerHTML, clobbers events, forces reflows, and chews power.
Incorrect currency handling. Money comes in cents, not fractions of a cent. Always use integer math for calculations that involve cash exchanges.

Minor points

Avoid adding event listeners directly to the element's on property. Use addEventListener
There are some cases where innerHTML can be useful, most of the time it is the worst way to add to the DON. Don't use it!
Add text content via element.textContent.
Don't change element style properties directly, create CSS rules and set the appropriate class name.
Use const for constants.
Don't add comments that point out the obvious.
Use arrow functions for anon functions;

Direct element reference

All elements that have an Id property set can be accessed by that id directly in the global namespace.

Foo


Clone GitHub repository using Python I want to backup my GitHub repositories since there is news about blocking GitHub in India. I wrote Python code to automate this and would like for it to be reviewed.

import os
import requests

API_TOKEN='xxxxx'
#from https://github.com/settings/applications

api_repo='https://api.github.com/user/repos'

url = '%s?access_token=%s' % \
(api_repo,API_TOKEN,)

r = requests.get(url).json()
git_urls = [repo['git_url'] for repo in r]
for i in git_urls:
  os.system("git clone "+i)

requests is third-party, so (per the style guide) there should be a blank line in the imports:

import os

import requests

api_repo is constant, so should be API_REPO. There should also be spaces around the = in assignments:

API_REPO = 'https://api.github.com/user/repos'

Explicit line continuation isn't very Pythonic, especially when the line is short enough anyway:

url = '%s?access_token=%s' % \
(api_repo,API_TOKEN,)

Also, there should be spaces after commas (and I wouldn't bother with the trailing one). This would be better written as:

url = '%s?access_token=%s' % (API_REPO, API_TOKEN)

r and i aren't very good variable names. I would use req_json and git_url.

You are mixing % string formatting with + concatenation. You should at least be consistent, and I would use the more modern str.format:

os.system("git clone {}".format(git_url))

You should also be consistent with string literal quotes. Per the style guide:

  In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

In all, I would probably have written it as:

import os

import requests

API_TOKEN = "..."
API_URL = "https://api.github.com/user/repos"

url = "{}?access_token={}".format(API_URL, API_TOKEN)
req_json = requests.get(url).json()

for repo in req_json:
    os.system("git clone {}".format(repo["git_url"]))


Importing files into Excel Any tips to reduce lines, improve speed, or any cool thing, are welcome.

I have been using this for years and I just realized, why not improve ...?

Sub AtualizarRelatorioGeral()
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.DisplayAlerts = False
    SaveChanges = False

    Dim Arquivo(18) As String

    Arquivo(1) = "zpp03ontem"
    Arquivo(2) = "vl10a"
    Arquivo(3) = "mb51consumomensal"
    Arquivo(4) = "mb51repassegerado"
    Arquivo(5) = "mb52peixerev"
    Arquivo(6) = "mb52peixepro"
    Arquivo(7) = "mb52exp"
    Arquivo(8) = "mb52repassesaldo"
    Arquivo(9) = "zsd17"
    Arquivo(10) = "zsd25fat"
    Arquivo(11) = "zsd25dev"
    Arquivo(12) = "mc.9estoquecd"
    Arquivo(13) = "mc.9consumo"
    Arquivo(14) = "mc.9centro"
    Arquivo(15) = "mc.9cdhipet"
    Arquivo(16) = "mc.9valor"
    Arquivo(17) = "zpp25"
    Arquivo(18) = "mc.9produto"

    For i = 1 To 18
        Sheets(Arquivo(i)).Visible = True
    Next i

    Set WBgeral = ActiveWorkbook

    'IMPORTAR ARQUIVOS
    For i = 1 To 18
        WBgeral.Activate
        Sheets(Arquivo(i)).Activate
        Cells.Select
        Selection.Clear
        Workbooks.OpenXML ("C:\macrosm\prerelatoriolucimara\" & Arquivo(i) & ".xls")
        Range("A1").Select
        Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
        Selection.Copy
        WBgeral.Activate
        Sheets(Arquivo(i)).Activate
        ActiveSheet.Paste
        Workbooks(Arquivo(i)).Close SaveChanges:=False
    Next i
    'IMPORTAR ARQUIVOS

    Sheets("Principal").Activate

    For i = 1 To 18
        Sheets(Arquivo(i)).Visible = False
    Next i

    Cells(4, 16).Value = Date
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.DisplayAlerts = True
    SaveChanges = True
End Sub

Recommendations

The less tasks that a subroutine performs the easier it is debug and modify.  If I were to put this code into production (distribute it for general use) I would extract these functions from the main code:

ApplicationState(PauseEvents): - handles the application state
getWorksheetNames()  - returns Arquivo().  This will allow you to tests whether the worksheets exists in the main workbook and whether the files exists without having to run the main code.  This alone will reduce your main code from 49 lines to 31.  I personally like to keep my subroutines no bigger than 25 - 30 lines whenever possible.
getXMLWorkBook(FilePath) As Workbook - use Len(Dir(FilePath)) > 0 to test if the file exists, if so, open and return the workbook.

Next I would add error handlers to test if the workbook exists or if there are any missing worksheets.

Excel Do's and Don't

There are very few times where you'll need to Select or Activate an Object.

Watch: Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)

There is no reason to use Application.DisplayAlerts = False in this code.  Workbook.Close SaveChanges:=False does not display any alerts.

Range references should be fully qualified.  If you are working with multiple workbooks, you should also qualify the worksheets to their parent workbook.  It might take a little getting used to but fully qualifying your references will save you a ton of headaches.  What usually happens is that you get the code working great and but later when you come back and to modify it you get unexpected results.  This can be especially tough to resolve in a large project.

Refactored Code

Here is how I would refactor the code for in-house use.

Sub AtualizarRelatorioGeral()
    Const BasePath As String = "C:\macrosm\prerelatoriolucimara\FileName.xls"
    Dim wsName As Variant, wbName As String
    ApplicationState True

    For Each wsName In Array("zpp03ontem", "vl10a", "mb51consumomensal", "mb51repassegerado", "mb52peixerev", "mb52peixepro", "mb52exp", "mb52repassesaldo", "zsd17", "zsd25fat", "zsd25dev", "mc.9estoquecd", "mc.9consumo", "mc.9centro", "mc.9cdhipet", "mc.9valor", "zpp25", "mc.9produto")
        wbName = Replace(BasePath, "FileName", wsName)
        With Workbooks.OpenXML(wbName)
            ThisWorkbook.Worksheets(wsName).Cells.Clear
            .Worksheets(wsName).Cells.Copy ThisWorkbook.Worksheets(wsName).Range("A1")
            .Close SaveChanges:=False
        Next
    Next

    ThisWorkbook.Worksheets("Sheet1").Cells(4, 16).Value = Date

    ApplicationState False
End Sub

Sub ApplicationState(PauseEvents As Boolean)
    With Application
        .Calculation = IIf(PauseEvents, xlCalculationManual, xlCalculationAutomatic)
        .ScreenUpdating = Not PauseEvents
        .EnableEvents = Not PauseEvents
    End With
End Sub


Checking whether number is in given range Introduction

I want to check whether number is in given range.
Function takes:

long number that should be checked
2 longs threshold values
byte range mode

Range mode is represented as number of type byte that can be from 0 to 4

0 for 00 => exclusive check
3 for 11 => inclusive check
1 for 01 => maximum - inclusive, minimum - exclusive
2 for 10 => maximum - exclusive, minimum - inclusive

Code

Range check constant flags

public static final byte RANGE_EXCLUSIVE = 0; // 00
public static final byte RANGE_INCLUSIVE = 3; // 11
public static final byte RANGE_MAX_INCLUSIVE = 1; // 01
public static final byte RANGE_MIN_INCLUSIVE = 2; // 10

Function

public static boolean inRange(long value, long range_a, long range_b, byte checkMode) {
    if (range_a > range_b) {
        long tmp = range_a;
        range_a = range_b;
        range_b = tmp;
    }

    // If value is on the left edge - check if it is inclusive
    if (value == range_a && (checkMode & RANGE_MIN_INCLUSIVE) == 0) return false;
    // If value is on the right edge - check if it is inclusive
    if (value == range_b && (checkMode & RANGE_MAX_INCLUSIVE) == 0) return false;

    // If value is out of range - return false
    if (value < range_a) return false;
    if (value > range_b) return false;

    return true;
}

Question

What do you think about this code?

Should I throw exceptions if range_a is less than range_b?

Or I can return false because range_a is expected to be less or equal to range_b

My first(and current) variant was to swap their values so range_a is always minimum, and range_b is always maximum of them

About style

I'm using camelcase for methods and variables

Underscore is used to show that values are connected. and used together:

Example: pos_x, pos_y or range_a, range_b

Should I throw exceptions if range_a is less than range_b?

This depends on your requirements.
 - Does the user of this function have to provide the input in correct order because a wrong order is a follow up of serious problem in her preceding code? Then you should throw an exception and this might even be a checked custom type to make the user aware of it.
 - Or is the wrong order something that is likely to happen and no problem outside your method? The reordering and going on inside your method is  appropriate.

  Should I throw exceptions if range_a is less than range_b?

This also must be specified by the requirements. If there was no requirement add a Javadoc comment explaining that and why you (not) return true in this situation.

  I'm using camelcase for methods and variables

as expected by the java naming conventions.

  Underscore is used to show that values are connected. and used together:
  Example: pos_x, pos_y or range_a, range_b

Why not posX, posY and rangeX, rangeY

or even better: since Java is an object oriented language, why not using objects to group things that belong together?

class Tupel {
  long a,b;
  Tupel(int a, int b){
    this.a = a;
    this.b = b;
  }
}

Tupel pos = new Tupel(10,30);
Tupel range = new Tupe(5,59);
// ...
if (range.a > range.b) {
  range = new Tupel(range.b,range.a);
// ...

  Why isn't checkMode an enumeration? – Alexander

The good thing about Java enums is that they can hold logic. The enum constants are classes that extend the enum class. This way enums can improve your code by resolving if/else cascades or switch constructs with polymorphism.

  You don't need to access the enum's raw values.[...] – Alexander

With that in mind you have only 2 enum constants

enum CompareMode{
  RANGE_EXCLUSIVE{
    @Override
    protected abstract boolean isInRange(long value, long range_a, long range_b){
      return value > range_a && value < range_b;
    }
  },
  RANGE_INCLUSIVE{
    @Override
    protected abstract boolean isInRange(long value, long range_a, long range_b){
      return value >= range_a && value =< range_b;
    }
  };
  public boolean inRange(long value, long range_a, long range_b){
     if(range_a > range_b)
       return isInRange( value,range_b,range_a);
     else // <- not needed but her for readability
       return isInRange( value,range_a,range_b);
  };
}

you complete logic is inside the enum, no extra method needed.

Now lets join that with the Tupel class:

enum CompareMode{
  RANGE_EXCLUSIVE{
    @Override
    protected abstract boolean isInRange(long value, Tupel range){
      return value > range.a && value < range.b;
    }
  },
  RANGE_INCLUSIVE{
    @Override
    protected abstract boolean isInRange(long value, Tupel range){
      return value >= range.a && value =< range.b;
    }
  };
  public boolean inRange(long value, Tupel range){
     if(range.a > range.b)
       range=new Tupel(range.b,range.a);
     return isInRange( value,range_a,range_b);
  };
}

The benefit of that solution is:

the parameter list is shorter and has no more possibility to mix the values passed in accidentally.
if you later add another CompareMode (which is hard to imaging, but try...) the only thing you have to change is the lines for the new mode and the code where you decide which mode to use. The code that actually needs the result does not need to change.

  Also, how are you calling methods in enum? – Michael

like this:

   Tupel range = new Tupel(4,5);
   for(CompareMode compareMode : CompareMode.values()){
    System.out.println(4+" is in range with compareMode "+compareMode +" ="+compareMode.inRange(4,range);
    System.out.println(5+" is in range with compareMode "+compareMode +" ="+compareMode.inRange(5,range);
   }


In-place reverse of C-style string This is a question from the book "Cracking the Coding Interview".

  Write code to reverse a C-Style String (C-String means that “abcd” is
  represented as five characters, including the null character )

Please review this code.

#include <iostream>

void inPlaceReverseString(char str[], int size)
{
    int j = size - 2;
    int i;

    for (i = 0; i < (size-1)/2; ++i)
    {
        std::swap(str[i], str[j]);
        j--;
    }
    str[size - 1] = '\0';
}

int main()
{
    char str[255];
    std::cout << "Enter String\n";
    std::cin.getline(str, 255);
    std::cout << "String: " << str << '\n';
    int size = 0;
    while (str[size] != '\0')
    {
        size++;
    }
    size++;
    inPlaceReverseString(str, size);
    std::cout << "Reversed String: " << str << '\n';
}

Because this is an attempt to answer an interview question, let's assume a hypothetical interviewer then asked you,

what would happen if I called your function using the following code:
...
char mylongstr[] = "This is my long string with lots of character.";
inPlaceReverseString(mylongstr, 7); // should reverse "This is"
cout << '"' << mylongstr << '"';
cout << " has " << strlen(mylongstr) << " characters\n";
...

It would print,
"i sihT" has 6 characters

That doesn't seem to make sense. Not only that, your function potentially clobbered the rest of my string, by writing \0 over the s in the word is.
Don't break expectations/convention with strings
@koblas mentioned to use the standard library function strlen().
strlen() returns the number of characters, not including the terminating \0 character, in the string passed to it. C and C++ string handling functions that take a count parameter generally expect that count refers to the number of characters to work on.
But the size parameter to inPlaceReverseString() breaks that expectation. I think you're overthinking the C-style string's terminating \0 character.
For interview questions (as well as coding in general), start with the simplest thing that can work and meets the specifications
Note that the interview question you quoted said, "write code to reverse a C-Style String", not "write code to reverse a specified number of characters in a C-Style String". For an interview-type question like this, rather than pass the length of the string as a parameter, just discover the length of the string within your function:
void inPlaceReverseString(char str[])
{
    for (int i = 0, int j = strlen(str) - 1; i < j; ++i, --j) {
        std::swap(str[i], str[j]);
    }
}

Note also that I slightly changed the loop-terminating logic, by checking i < j. This makes the logic a bit easier to read, making it obvious that when the indexes i and j pass each other, there's no more replacement to be done.

Now, if you still want to have a length parameter (or are asked to extend the simple answer I wrote above), a couple suggestions:

Use a parameter name such as num, len, or even n, as opposed to size. This is really pedantic on my part, but size tends to suggest memory sizes, as opposed to length of strings or number of characters.

Use size_t as the type of the length parameter. This is an unsigned type, and conforms with the rest of C-style string functions that have a length/number parameter.

Don't write a terminating \0 after the in place reversal.

Even if a length is specified, you should still check for a terminating \0 character within the string.

So, a possible implementation of the answer would look something like:
void inPlaceReverseString(char str[], size_t num)
{
    int len = strlen(str);
    if (len < num) {
        // length of 'str' is less than 'num'. How to handle? ...
    }
    for (int i = 0, int j = strlen(str) - 1; i < j; ++i, --j) {
        std::swap(str[i], str[j]);
    }
}

Now, the original hypothetical question asked by the hypothetical interviewer at the start of this answer would work:
...
char mylongstr[] = "This is my long string with lots of character.";
inPlaceReverseString(mylongstr, 7); // should reverse "This is"
cout << '"' << mylongstr << '"';
cout << " has " << strlen(mylongstr) << " characters\n";
...

would print:
"si sihT my long string with lots of character." has 47 characters


Review of my CSS for aligning the navigation icons and text in a footer menu The navigation in my footer menu looks like this

It works, but I get a feeling that using spans the way I did was a bit of a hack. So I would also like to know how to maximize compatibility as used media queries.

I created it using the following

HTML

        HOME&raquo;

        FEATURES&raquo;

        VIDEOS&raquo;

        CASES&raquo;

        TESTIMONIALS&raquo;

        BLOG&raquo;

        AUTHORIZED BRUXZIR LABS&raquo;

CSS

.footer {
  background-color: #111;
  text-align: center;
  width: 100%;
  min-height: 120px;
  padding: 24px 0;
}

.footer a {
  color: #fff;
  text-decoration: none;
}

.footer ul { list-style: none; }

@media only screen and (min-width: 1px) and (max-width: 479px) {
  .footer { text-align: left; }
  .footer ul li {
    display: block;
    padding: 12px;
  }
  .footer ul li a { }
  .footer ul li a span:nth-of-type(2) {
    padding:9px;
    background-color: rgb(202, 0,0 );
    float: right;
    border-radius:2px;
  }
}

@media only screen and (min-width: 480px) {
  .footer { text-align: center; }
  .footer ul li { display: inline; }
  .footer ul li:not(:last-of-type) { margin-right: 12px }
  .footer ul li a span:nth-of-type(2) { display: none; }
}

HTML:

Since the the navigation is the only thing inside your <div class="footer">, how about moving the class to the ul?
Instead of using span's there, you can add the &raquo; to a pseudo-element (see the CSS part)

CSS:

For your arrows, you should use pseudo-elements:

.footer a:after {
    content: "\00BB";
    float: right;
    padding: 9px;
    border-radius: 2px;
    background-color: #ca0000; /* hex-based values are shorter */
}

You won't need to hide them on bigger screens either, if you define them inside a media query, because they're not present in your markup
Instead of actually writing the links in capital letters, write them like you would in normal language and make them appear uppercase with text-transform: uppercase;
I don't see a purpose for the min-width: 1px part in your media query. Just unnecessary.
Defining display: block; on list-items is not necessary, because they behave like block-level elements already
Select .footer li instead of .footer ul li and .footer a instead of .footer ul li a. No need for this extra layer of specificity and dependency. There will probably no other links and list-items in this ul other than these you already have


Integer factoring in C using GMP for numbers This code performs integer factoring using the GMP library, and can also use OpenMP for parallel computation.

I compile it using: gcc -lgmp -fopenmp and whatever optimization flags I wish to try.

#include <stdio.h>
#include <gmp.h>

void next_prime(MP_INT *x) {
    MP_INT r;
    mpz_init(&r);
    if (!mpz_probab_prime_p(x, 128u)) {
        mpz_mod_ui(&r, x, 2ul);
        if (mpz_cmp_ui(&r, 0ul) == 0)
            mpz_add_ui(x, x, 1ul);
        else
            mpz_add_ui(x, x, 2ul);
        while (!mpz_probab_prime_p(x, 128u)) {
            mpz_add_ui(x, x, 2ul);
        }
    }
    mpz_clear(&r);
}

void prev_prime(MP_INT *x) {
    MP_INT r;
    mpz_init(&r);
    if (!mpz_probab_prime_p(x, 128u)) {
        mpz_mod_ui(&r, x, 2ul);
        if (mpz_cmp_ui(&r, 0ul) == 0)
            mpz_sub_ui(x, x, 1ul);
        else
            mpz_sub_ui(x, x, 2ul);
        while (!mpz_probab_prime_p(x, 128u)) {
            mpz_sub_ui(x, x, 2ul);
        }
    }
    mpz_clear(&r);
}

unsigned long mp_log(MP_INT *x, MP_INT *base) {
    MP_INT r;
    mpz_init(&r);
    unsigned long lg = 0;
    mpz_set(&r, x);
    if (base != NULL) {
        while (mpz_cmp_ui(&r, 0ul) != 0) {
            mpz_div(&r, &r, base);
            lg += 1;
        }
    }
    else {
        while (mpz_cmp_ui(&r, 0ul) != 0) {
            mpz_div_ui(&r, &r, 2ul);
            lg += 1;
        }
    }
    mpz_clear(&r);
    return lg;
}

void factor(MP_INT *x, MP_INT *n, MP_INT *base) {
    /* Initialize variables. */
    MP_INT s;
    MP_INT r;
    mpz_init(&s);
    mpz_init(&r);
    /* Compute stuff. */
    mpz_set(x, n);
    if (mpz_probab_prime_p(n, 128u)) {
        goto end;
    }
    mpz_set(&s, base);
    mpz_mod(&r, n, &s);
    if (mpz_cmp_ui(&r, 0ul) == 0) {
        mpz_set(x, &s);
        goto end;
    }
    unsigned long k = mp_log(n, base);
    unsigned long a = mp_log(n, NULL);
    if (mpz_cmp(x, n) == 0) {
        /* Try different powers of n. */
        MP_INT p;
        mpz_init(&p);
        mpz_pow_ui(&p, &s, k);
        unsigned long i = 1ul;
        while (mpz_cmp(x, n) == 0) {
            #pragma omp parallel for
            for (unsigned long j = i; j < i + 2*a*a; ++j) {
                if (mpz_cmp(x, n) == 0) {
                    MP_INT g;
                    mpz_init(&g);
                    mpz_powm_ui(&g, n, j, &p);
                    mpz_gcd(&g, &g, n);
                    if (mpz_cmp_ui(&g, 1ul) != 0 && mpz_cmp(&g, n) != 0) {
                        mpz_set(x, &g);
                    }
                    mpz_clear(&g);
                }
            }
            i += 2*a*a;
        }
        mpz_clear(&p);
    }
    /* Clear variables. */
    end:
    mpz_clear(&s);
    mpz_clear(&r);
}

int main() {
    char str [65536];
    char bas [65536];
    while (fscanf(stdin, "%s %s", str, bas) != EOF) {
        MP_INT n;
        MP_INT base;
        mpz_init(&n);
        mpz_init(&base);
        mpz_set_str(&n, str, 10u);
        mpz_set_str(&base, bas, 10u);
        mpz_out_str(stdout, 10u, &n);
        int p = mpz_probab_prime_p(&n, 128u);
        printf(" %d ", p);
        mpz_out_str(stdout, 10u, &base);
        printf("\n");
        while (!p) {
            MP_INT x;
            mpz_init(&x);
            factor(&x, &n, &base);
            mpz_out_str(stdout, 10u, &x);
            printf(" ");
            mpz_div(&n, &n, &x);
            p = mpz_probab_prime_p(&n, 128u);
            mpz_clear(&x);
        }
        mpz_out_str(stdout, 10u, &n);
        printf("\n");
        mpz_clear(&n);
        mpz_clear(&base);
    }
    return 0;
}

You can improve the readability of your code, your indentation is great but you have magic numbers and the variable names aren't very clear. You probably wouldn't need comments if your variable names were clear and you had symbolic constants rather than numbers.

Magic Numbers:

You have a lot of raw numbers : 65536, 10u, 128u, 1ul, 2ul ...

For example you can have a symbolic constant CHARACTER_BUFFER_SIZE for 65536. Using the gcc compiler you would write your constant as

#define CHARACTER_BUFFER_SIZE 65536

When compiling with g++ you would use

static const CHARACTER_BUFFER_SIZE = 65536;

this would change the first 2 lines in main to

    char str[CHARACTER_BUFFER_SIZE];
    char bas[CHARACTER_BUFFER_SIZE];

If you use this number often, it makes it easier to change the value by just changing it where you define the constant. It also makes the code easier to read. The standard for symbolic constants in C and C++ is all caps with '_' between words.

Function Names:
Underscore in function names is a lot less common than it used to be, Camel Case is more common

next_prime => nextPrime
prev_prime => prevPrime

Variable Names:

The base variable name is almost understandable, but what kind of base, does it provide a starting point for the function, or is it a numeric base like Octal, Hex or Decimal?

It's really not clear from the code what x is.

In main() what are the variables str (almost obvious), bas, n, p, base?

Future Flexibility:

You main could be a little more flexible, currently you can only redirect input and a output, you could use command switches in your to select input and output files as well. In main it is possible to add a couple of FILE * variable to make it a little more general

    FILE *inputFile = stdin;
    FILE *outputFile = stdout;

    while(fscanf(inputFile, "%s %s", str, bas) != EOF) {
        ...
        mpz_out_str(outputFile, 10u, &base);


advantage of using __call method I have wrote simple class that allowing database selection and inserts.Could you please tell me does this a right way to use __call method with any useful advantage of it ?

 <?php
class _getDatabase
{
    public $db;

   public function __construct(PDO $connection)
    {
        $this->db = $connection;
    }
  public function __call($function, $args) {

          if ($function == 'getSelect') {
            $sql = $this->db->prepare($args[0]['query']);
            $sql->execute(array(
                $args[0]['parameters']
            ));
            return $sql->fetchALL(PDO::FETCH_OBJ);
          }

           if ($function == 'getInsert') {
            $sql = $this->db->prepare($args[0]['query']);
            $result = $sql->execute($args[0]['parameters']);
            return $result;
          }
  }
}

$dbh = new PDO("mysql:host=127.0.0.1;dbname=" . DATABASE, USERNAME, PASSWORD, array(
    PDO::ATTR_PERSISTENT => true
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception
$dbFactory = new _getDatabase($dbh);
$select = array();
$insert = array();
$select['query'] = 'SELECT * FROM `branches` WHERE B_CODE = ?';
$select['parameters'] = 'AMB';

$insert['query'] = 'INSERT INTO `commition`(`date`, `reg`, `com`, `oper`) VALUES (?,?,?,?)';
$insert['parameters'] = array('2014-02-20','86869','DITEC','Asuntha');
var_dump($dbFactory->getSelect($select));
var_dump($dbFactory->getInsert($insert));
?>

You are using the __call for a completly wrong purpose. Instead of defining the functions/methods in the class itself, you are in fact defining them in a __call function.

Everytime you call a method on your current class the compiler does this:

doest the method exist? does the scope have privileges to call the method? -> call the method.

No method found? doest the object have a __call method? does the scope have privileges to call the method? -> call the method.

Now you are in the __call method. It now does a lot of string comparisons (could be 'optmized' using switch statements if a lot of calls are made).

Not really optimal, not to mention that the compiler and or other developers now have no clue at all or it/they are passing enough arguments to a method. hell

But, what is the point of the __call method then you may ask. Some argue this should never have been implemented in the first place, some love it. But that is a different argument.

Some neat examples:

http://www.garfieldtech.com/blog/magical-php-call
Laravel facades (click here for the code)