Convert to different bases Another code for exercism, It is to convert Vec of u32 from one base to another base. Please help to make it more idiomatic, Also if this type of question is welcomed here or not.

#[derive(Debug, PartialEq)]
pub enum Error {
    InvalidInputBase,
    InvalidOutputBase,
    InvalidDigit(u32),
}

pub fn convert(number: &[u32], from_base: u32, to_base: u32) -> Result<Vec<u32>, Error> {

    if from_base < 2 {
        return Err(Error::InvalidInputBase);
    }

    if to_base <2  {
        return Err(Error::InvalidOutputBase);
    }

    if number.iter().any(|&x| x > 0 && x >= from_base ){
        return Err(Error::InvalidDigit(from_base));
    }

    let  res: u32 = number.iter().rev().enumerate().map(|(index, x)| x*from_base.pow(index as u32)).sum();
    Ok(convert_back(res, to_base))

}

fn convert_back(number: u32, base: u32) -> Vec<u32>{

    let mut res: Vec<u32> = Vec::new();
    let mut inter = number as f64;

    loop {
        inter = inter as f64/base as f64;
        res.push((inter.fract()*base as f64).round() as u32);
        if inter as u32 ==0{
             break
             }

        inter = inter.trunc();
        }

        res.reverse();
        res

}

Some tests

fn decimal_to_binary() {
    let input_base = 10;
    let input_digits = &[4, 2];
    let output_base = 2;
    let output_digits = vec![1, 0, 1, 0, 1, 0];
    assert_eq!(
        ayb::convert(input_digits, input_base, output_base),
        Ok(output_digits)
    );
}

fn trinary_to_hexadecimal() {
    let input_base = 3;
        let input_digits = &[1, 1, 2, 0];
        let output_base = 16;
        let output_digits = vec![2, 10];
    assert_eq!(
       convert(input_digits, input_base, output_base),
        Ok(output_digits)
    );
}

fn hexadecimal_to_trinary() {
    let input_base = 16;
    let input_digits = &[2, 10];
    let output_base = 3;
    let output_digits = vec![1, 1, 2, 0];
    assert_eq!(
        convert(input_digits, input_base, output_base),
        Ok(output_digits)
    );
}

fn invalid_positive_digit() {
    let input_base = 2;
    let input_digits = &[1, 2, 1, 0, 1, 0];
    let output_base = 10;
    assert_eq!(
        convert(input_digits, input_base, output_base),
        Err(Error::InvalidDigit(2))
    );
}

fn output_base_is_zero() {
    let input_base = 10;
    let input_digits = &[7];
    let output_base = 0;
    assert_eq!(
        convert(input_digits, input_base, output_base),
        Err(Error::InvalidOutputBase)
    );
}

```

Style

These are in order of me thinking of them; not in order of first appearance. Sorry!

#[test]

If you mark your tests with #[test], then running cargo test will run them. If you also mark them with #[cfg(test)], then they'll only be compiled in test mode.

Unneeded collect()

cargo clippy is an invaluable tool. Here, it found an optimisation!

if !number.iter().filter(|&x| *x > 0 && *x >= from_base ).collect::<Vec<_>>().is_empty(){
    return Err(Error::InvalidDigit(from_base));
}

It points out that .collect::<Vec<_>>().is_empty() should be replaced with .next().is_none():

if !number
    .iter()
    .filter(|&x| *x > 0 && *x >= from_base)
    .next()
    .is_none()
{
    return Err(Error::InvalidDigit(from_base));
}

The compiler's probably smart enough to turn this into efficient code,[citation needed] but this code can be made clearer:

if number.iter().any(|&x| x > 0 && x >= from_base) {
    return Err(Error::InvalidDigit(from_base));
}

Unnecessary casting

inter = inter as f64/base as f64;

can be

inter /=  base as f64;

and you can get rid of all of the base as f64 bits by putting

let base = base as f64;

at the top of convert_back.

After a quick pass through cargo fmt to clean up the errant spacing and expand the iterator chain to separate lines, this all looks pretty good.

Algorithm

Your algorithm is, sadly, more limited than it looks. Your use of as is a little risky, as casting to a smaller integer truncates it. However, that won't get to be a problem, because as soon as the from_base.pow ends up with a number bigger than u32 can store, it'll panic.

You need some kind of "too big" Error variant if you want to handle this gracefully; you could check whether number.len() > u32::MAX (otherwise as's truncation could cause issues), and then check whether all the .pow calls are guaranteed to work (perhaps with .checked_pow?), and then whether adding all the digits together will exceed the bounds of u32.

Alternatively, you could make the algorithm convert via base 2³² instead of u32s, which would resolve the issue.


What is the security issue in this code? I was asked how this code has a security risk.  Does anyone have any ideas what it is? I am new on the security topic and don't know what to look for.

String DBdriver = "com.ora.jdbc.Driver";
String DataURL = "jdbc:db://localhost:5112/users";
String loginName = "stackoverflow";
String passwd = "codeReview";
Class.forName(DBdriver);
Connection conn = DriverManager.getConnection(DataURL, loginName, passwd);
String Username = request.getParameter("USER");
String Password = request.getParameter("PASSWORD");
int iUserID = -1;
String loginUser = "";
String sel = "SELECT UserID, Username FROM USERS WHERE Username = '"
    +Username + "' AND Password = '" + Password + "'";
Statement selectStatement = conn.createStatement ();
ResultSet result = selectStatement.executeQuery(sel);
if (result.next()) {
       iUserID = result.getInt(1);
       loginUser = result.getString(2);
}
PrintWriter wr = response.getWriter ();
if (iUserID >= 0) {
       wr.println ("you logged in: " + loginUser);
} else {
       wr.println ("you cannot login in !Access Denied!")
}

Off the top of my head:

Those parameters don't seem to be escaped before being stitched into a query (opening up SQL injection attacks)
The database seems to be keeping passwords in plaintext rather than as salted hashes (which is an especially bad combo with the previous point)

You'd really want to

escape the username and password before dropping them into a SELECT statement
keep the password stored as a hashed value at minimum (you'd then want to verify the users' input by hashing the password you get from them and comparing that to what you have stored). Ideally, you'd salt them too.

It wouldn't hurt to accept the login info as a POST parameter either (just to reduce the number of logs username/password combos would end up in).


User Input in class sanitized I want to sanitize my user input in my class. All is working as expected but first of all, I would like to avoid to set a default value for my digit parameter. Secondly, I would like to avoid to put everything in a big while-loop and instead call implicitly a function which asserts the user input.

Initially, I thought to create a @staticmethod could do the job but I was obviously wrong (Why does staticmethod not assert my user input?).

My code is:

class CompositeNumbers:
    def __init__(self, digit=6):
        self.uinput = digit

        flag = True

        while flag:

            try:
                self.uinput = int(input("Enter a number: "))

                while self.uinput <= 0:
                    self.uinput = int(input("Please enter a positive number: "))

                else:
                    flag = False
                    for i in range(2, self.uinput):
                        if self.uinput % i == 0:
                            print("The number is composite!")
                            break
                        else:
                            print("The number is a prime!")
                            break

            except ValueError:
                print("Wrong input!")

EDIT

My previous attempt to use a function did not work as I wanted it to. I would need to call the check_input function. It would check my input but if I would call the userinput function, it would not check the input implicitly.

@staticmethod
def check_input(digit):
    try:
        while digit <= 0:
            digit = int(input("Try again: "))
    except TypeError:
        print("Wrong Input")

def userinput(self):

        uinput = self.digit

        for i in range(2, uinput):
            if uinput % i == 0:
                print("The number is composite!")
                break
            else:
                print("The number is a prime!")
                break

Welcome! Let's look at your code:

I notice that you have code that appears to be part of a class, so I will be treating it as a class for the purposes of review. In your original code, you use a class to group all your operations together, but the class doesn't really serve a purpose (i.e. the method could exist independent of the class, with a name like is_prime). In your second version, you have two separate method, and while the encapsulation of different functionally is better, they are not connected in a meaningful way so it is not clear how you run the program. In both cases, a class is unnecessary: you could have a single function that prompts the user for a positive integer input, and another function that checks if a positive integer is prime or composite (which I will demonstrate below). Personally I store my input validation methods in a separate module that I've added to my PYTHONPATH, since it's useful for many different projects if you use the command line often.
Commenting in general on your goal to "check the input implicitly", I would say this is misguided, but I will also say that you can use a property decorator to implicitly check variables on assignment. However, as Michael mentions you still would need to loop to prompt input from the user until they enter valid input, so it's not really that usefully for input validation.

Now, if you're trying to validate input in Python, this SO answer provides a good primer on the subject.

Your check_digit method checks if the input is valid before the user actually enters any input. As mentioned in the above answer, while True and with an if valid: break is a better structure for this kind of validation.
Your userinput method is ambiguously named (you can't tell what it does from the name alone), and it's broken: it only checks if 2 is prime before breaking. You need to only check if the number is composite inside the loop, and return prime if a composite factor is not detected.

Here's code that demonstrates the principles I mention above:

def prompt_positive_number(message):
    while True:
        try:
            num = int(input(message))
            if num <= 0:
                message = "Please enter a positive number. "
            else:
                return num
        except ValueError:
            message = "Please enter a number. "

def is_prime(num):
    for i in range(2, num):
        if num % i == 0:
            return False
    return True

if __name__ == "__main__":
    user_input = prompt_positive_number("Check if a number is prime: ")
    if is_prime(user_input):
        print(user_input, "is prime!")
    else:
        print(user_input, "is composite!")

There's one more optimization I can use to make my code even shorter: using the built-in function any for is_prime:

def is_prime(num):
    return not any(num % i == 0 for i in range(2, num))

Or, reversing the equality check, all is even shorter:

def is_prime(num):
    return all(num % i != 0 for i in range(2, num))

Finally, commenting on the algorithm, there are more efficient ways to check if a number is prime; however, this is outside of the scope of my knowledge and you'd have to do your own research on that. Rather famously in the world of computational complexity, it was proved that primes is in P.


Creating a database class in PHP with MySQLi I am creating a database class in PHP but I feel that there's something wrong with my code. Is there any suggestion to refactor this?  I feel like there's something wrong and missing in this code.

<?php
    require_once("db_constants.inc.php");

    Class MySqli_Database
    {
        public $db;

        public  function __construct($db_host,$db_username,$db_password,$db_name)
        {
            $this->db = new mysqli($db_host,$db_username,$db_password,$db_name);
        }

        public function __performSql($sql)
        {

        }

        public static function closeConnection($conn)
        {
            $this->db_close();
        }

    }

    $conn = new MySqli_Database (DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME)
    or die("Could Not Connect To Database: " . mysqli_errno());

Perform SQL will just basically execute the query, though I haven't included the code yet,  but I will soon. Also if you have tutorials or guide when creating a database class for MySQLi please post it. It would be a great help.

What is the purpose of this class?

  Creating a database class in PHP with mySQLI

MySQLi is a "database class."  (Whatever meaning of "database class" you choose)

Are you trying to make a class that adds on to MySQLi?
Are you trying to make a class that abstracts away certain operations (a DBAL)?
Are you trying to make a class that maps objects to a database (ORM)?

require_once("db_constants.inc.php");

The file that your class is defined in does not need to be aware of your connnection details.  Only the file that uses the class needs to know that, not the file that defines the class (unless of course, it's the same file, but it rarely should be).

or die

Constructors cannot return values, so this will never work.

The proper way to handle errors with objects is exceptions.  Please note though that exceptions should only be used when something that's actually exceptional happens.  It's far to easy to fall into the anti-pattern of using exceptions as return values.

In the case of mysqli's constructor failign to create a connection, that is definitely a cause for an exception.  (I tend to avoid the possibility of an object being in an unstable state.)

closeConnection

Why does this take a parameter when the connection is encapsulated in the class?

Also, unless you're going to have an openConnection method, avoid this.  Just let the destructor handle this.  Why would a user ever want to close the connection but keep the instance alive?

PDO vs MySQLi

I'm heavily biased in this one since I've always used PDO and never written a single line of code with MySQLi, but I've never seen the advantage of MySQLi over PDO.  I suppose there's a few MySQL functionalities that MySQLi supports and PDO doesn't, but they must be quite edge cases as I've never run into anything.

Concluding Remarks

I feel like there's barely anything here to review.  The goal of your code is not quite clear.  Can you explain a little more what your end goal is?  What is the purpose of this class?  What is an example use case?


Simple function to generate an HTML-safe string Sometimes, we have to do some fixing to insert a string into an HTML property. Or just to display it.

But not everything is safe! Consider the following example:

document.getElementById('name').innerHTML = prompt('What is your name?');

This allows to introduce HTML vulnerabilities quite easily. Specially when you want to do HTML > X/HTML conversions.

So, I've came up with the following:

var safetext = function(text){
    var div = document.createElement('div');
    div.innerText = div.textContent = text;
    var safetext = div.innerHTML;
    div = null;
    return safetext.replace(/^\s+|\s+$/g, '');
};

But then I realized that it could be optimized a little. That div is created and destroyed every single time you need a cleanup. So, I've optimized to the following:

var safetext = (function(text){
    this.innerText = this.textContent = text;
    return this.innerHTML.replace(/^\s+|\s+$/g, '');
}).bind(document.createElement('div'));

The this will always be the div we created, and will always be the same one, so, no unnecessary cleanups or anything. It is always kept in memory, since it is bound to the this in the anonymous function. Or isn't it?

The resulting text is a string that is safe to use in your HTML. Using the example from before:

document.getElementById('name').innerHTML = safetext(prompt('What is your name?'));

This should show &lt;script&gt; if your name (for some bizarre reason) is <script>. Or it leaves unsafe characters behind, bound to break everything?

To the best of my knowledge, and based on the 200 tests where I've used it, I didn't had a single problem or hiccup.

Am I missing something? Is my code indeed returning safe HTML strings? Is the 2nd iteration really more performant?

The Attack
What you are basically talking about is DOM based XSS.
But it's a self-XSS, so the only possible attack vector might be via ClickJacking (depending on the used browser).
Still, it should be defended against, especially for usability reasons.
Proper Defense
Here is OWASPs guide on preventing DOM based XSS. Basically, you should first HTML encode the input, and then JavaScript encode.
For your example, the second part doesn't seem necessary, just encoding <, >, ' and " should be enough.
Your Defense
Well, your defense works.
It could be simplified a bit though. There really doesn't seem to be a need to set this.textContent, and I also do not see the need for replace(/^\s+|\s+$/g, '') (or am I missing something here? Browser compatibility maybe?).
That would leave you with
var safetext = (function(text){
    this.textContent = text;
    return this.innerHTML;
}).bind(document.createElement('div'));

The reason this works seems to be the way textContent works.
But this really seems to be more of a side-effect, and it is never a good idea to use those for security related things.
Conclusion
Regarding performance, security, and readability, a simple replace for <, >, ' and " with their HTML representation seems to be preferable to your method.


Which FizzBuzz is better, and why? I was in an interview and the guy asked me to do the typical FizzBuzz question of printing numbers 1-100, but for each factor of 3 print Fizz, each factor of 5 print Buzz, and each factor of both print FizzBuzz. I wrote the following:

public static void fizzbuzz(){
    for(int i=1;i<=100;i++){
        if(i%15 == 0){
            System.out.println("FizzBuzz");
        } else if (i%3 == 0) {
            System.out.println("Fizz");
        } else if (i%5 == 0) {
            System.out.println("Buzz");
        } else {
            System.out.println(i);
        }
    }
}

The interviewer had me change my answer so that it looked like this:

public static void fizzbuzz(){
    for(int i=1;i<=100;i++){
        String str = "";
        if(i%3 == 0){
            str = "Fizz";
        }
        if(i%5 == 0){
            str += "Buzz";
        }
        if(str.equals("")){
            str = i;
        }
        System.out.println(str);
    }
}

Then he asked me which I would prefer if I was handed that code, and said there was no wrong answer (which I should have known was a lie), but I foolishly said mine because it was easier for me to look and see that something different was happening for factors of 15 in my code by just glancing over it, whereas without actually looping through the code in my mind, I wouldn't know that about the second version.

Anyways, my question is, is his version better for some reason that I am missing? I'm at entry level skill, so I honestly think that both versions are completely identical efficiency and readability wise.

I prefer your solution to his. My reasoning is that:

yours has constants only in the String manipulation
you do not do string concatenation
the logic is distinct for each remainder.

Both options could be better though. The lack of 'breathing space' (white space between keywords, variables, values, and operators) leads to hard-to-read code. Lines like:

for(int i=1;i<=100;i++){

should be:

for (int i = 1; i <= 100; i++) {

Then, your solution would actually be more efficient as a switch statement:

for (int i = 1; i <= 100; i++) {
    switch (i % 15) {
        case 0:
            System.out.println("FizzBuzz");
            break;
        case 3:
        case 6:
        case 9:
        case 12:
            System.out.println("Fizz");
            break;
        case 5:
        case 10:
            System.out.println("Buzz");
            break;
        default:
            System.out.println(i);
    }
}

The switch statement will be optimized so that there does not need to be more than one modulo, and there is no concept of an if/elseif/elsif/else... just a single condition check.


Calculating the result of a recurrence function The recurrence function is defined as follows:

\$f(0) = 1\$
\$f(1) = 1\$
\$f(2n) = f(n)\$
\$f(2n+1) = f(n) + f(n-1)\$

I was tasked to calculate the recurrence of a very large number, \$n = 66666666666666\$, using C++. As you can clearly see, the 3rd line applies for even inputs, and the 4th line for odd inputs. If this isn't clear consider the following derivation for \$f(10)\$:

\$f(10) = f(5) = f(2) + f(1) = f(1) + f(1) = 1 + 1 = 2\$

long long int function(long long int x) {
  if (x == 0 || x == 1)
      return 1;

  long long int result = 0;

  if (x % 2 != 0) {
      result += function((x-1)/2) + function((x/2)-1);
  } else {
      result += function(x/2);
  }

  return result;
}

The runtime of this implementation is very large (almost 30 seconds to finish). Clearly this is because recursion is very expensive. My runtime limit is 1.0s, at most. Therefore I think an iterative approach would work wonders.

This is the result of running time ./my_program:

real  0m29.893s
user  0m29.809s
sys   0m0.075s

I am wondering if there are other approaches, besides translating it to an iterative version, which would be suitable for this problem in particular. I would also be grateful if anyone has any pointers about my code/approach.

Avoid the result variable

The result variable is only ever incremented once and then returned. You can simplify by returning directly:

if (x % 2 != 0) {
  return function((x-1)/2) + function((x/2)-1);
} else {
  return function(x/2);
}

Eliminating the variable should also speed-up the program if the compiler did not optimize it out already.

Memoization

Memoization essentially stores already computed values for later re-use trading space for run-time. Memoization has already been implemented in C++ so you can just make use of it.


Transform a List of objects to a string of unique values for use in an SQL query I have a List of Results. My goal is to extract the Result property Method from all elements of List<Result>, make extracted elements unique and prepare a string for SQL statements like WHERE method IN ('A','B','C').

Here is the Result class and a List<Result> example. The solution is in the ListTransformation() method.

Result.cs

public class Result
{
    public int Id { get; set; }
    public string Method { get; set; }
}

Program.cs

A method value can be one method ("A") or more methods separated by a colon ("A:B:C").

static void ListTransformationTest()
{
    const string separator = ":";

    List<Result> results = new List<Result>
                { new Result { Id = 1, Method = null },
                  new Result { Id = 1, Method = "" },
                  new Result { Id = 2, Method = "A:B" },
                  new Result { Id = 3, Method = "B:C" },
                  new Result { Id = 4, Method = "A:C:B" }
                };

    string methods = string.Join(separator,
                                 results.Where(x => x.Method?.Length > 0)
                                        .Select(r => r.Method).ToArray());
    var uniqueMethods = methods.Split(separator[0]).Distinct();
    string uniqueMethodsSqlFormat =
            string.Join(",", uniqueMethods.Select(m => string.Format($"'{m}'")).ToArray());
}

I guess there are a lot of operations. Do you have any suggestions on improving the code or any alternative code?

Creating query (alternative)

Creating SQL like that is vulnerable to SQL Injection. You should use parameters instead.

Here's an example:

using (var cmd = new SqlCommand())
{
    var methods = results
        .SelectMany(x => x.Method?.Split(
            new[] { ':' },
            StringSplitOptions.RemoveEmptyEntries) ?? new string[0]
        ).Distinct();

    var methodParameterNames = new List<string>();
    foreach (var method in methods)
    {
        methodParameterNames.Add($"@Method{methodParameterNames.Count + 1}");
        cmd.Parameters.Add($"@Method{methodParameterNames.Count}", SqlDbType.NVarChar).Value = result;
    }
    var methodParameterString = string.Join(", ", methodParameterNames);

    // build the rest of the query
}

Extracting methods

To extract all methods use the SelectMany extension with the coalescing operator ?? so that you don't have to check for null later. You use an empty collection. The loop simply won't execute. Finally you get unique methods with Distinct.

Creating SQLParameters

In order to create a query for each result you create a SqlCommand. You add each method to a list with parameter names and at the same time add the parameters and the values to the command. The parameters have counters. The first counter needs to be +1 because it is just going to be added and it has to match the counter in the parameter line. At the end you build a string with parameter names that you can use to build the final query.

Example methodParameterString:

 @Method1, @Method2, @Method3

The query to create:

 var sql = $".. WHERE [Method] IN ({methodParameterString}) ..";

Review

string.Join(",", [...].ToArray());

There's no need to .ToArray() the collection for string.Join because it expects an IEnumerable<T>. Calling ToArray you loop over the collection twice.

const string separator = ":";
separator[0]

You can make the separator a char and drop the [0] which is very confusing.

.Where(x => x.Method?.Length > 0)

It's easier to do:

.Where(x => !string.IsNullOrEmpty(x.Method))


Custom caching class in Swift I'm using Swift 4.0 and I'm using UserDefaults in my project for storing Strings like login or something. I have a class:

class Cache: UserDefaultsManager {

    static var currentProfileID: Int? {
        get {
            return value(forKey: Constants.Cache.CurrentProfileID) as? Int
        }
        set {
            set(newValue, forKey: Constants.Cache.CurrentProfileID)
        }
    }

    static var login: String? {
        get {
            return value(forKey: Constants.Cache.Login) as? String
        }
        set {
            set(newValue, forKey: Constants.Cache.Login)
        }
    }

    // ... and there are more of this kind

, where UserDefaultsManager looks like this:

class UserDefaultsManager {
    private static var uds: UserDefaults {
        return UserDefaults.standard
    }

    static func value(forKey: String) -> Any? {
        if let encoded = uds.object(forKey: forKey) as? Data {
            return NSKeyedUnarchiver.unarchiveObject(with: encoded)
        }
        return nil
    }

    static func set(_ data: Any?, forKey: String) {
        let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: data as AnyObject)
        uds.set(encodedData, forKey: forKey)

        if (!uds.synchronize()) {
            NSLog("Failed sync UserDefaults?")
        }
    }
}

Constants.Cache is a structure that holds my keys. My question is:

  What would be a good approach to make my Cache class lighter with
  less code?

I imagine the final product should look like:

class Cache {
    static var hash: UDSObject<String>?
    static var currentProfileID: UDSObject<Int>?
    static var login: UDSObject<String>?
    static var selectedWindowID: UDSObject<Int>?
}

Your Cache class cannot be lighter than it already is. The most you can do is, introduce generics to remove the redundant casting every time you are trying to fetch from user defaults.

However, I see a major problem with the implementation here:

Is Cache also a UserDefaultsManager? Do you see Cache as something that extends the functionalities of the UserDefaultsManager class, or does your Cache use the functionalities of the UserDefaultsManager? I feel that composition is the way to go here than inheritance. I'd refactor this code to something like this:

protocol CacheHandling {
    func value<T>(forKey: String) -> T?
    func set<T>(_ data: T?, forKey: String)
}

extension CacheHandling {
    func value<T>(forKey: String) -> T? {
        let userDefaults = UserDefaults.standard
        if let encoded = userDefaults.object(forKey: forKey) as? Data {
            return NSKeyedUnarchiver.unarchiveObject(with: encoded) as? T
        }
        return nil
    }

    func set<T>(_ data: T?, forKey: String) {
        let userDefaults = UserDefaults.standard
        let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: data as AnyObject)
        userDefaults.set(encodedData, forKey: forKey)

        if (!userDefaults.synchronize()) {
            NSLog("Failed sync UserDefaults?")
        }
    }
}

struct Cache : CacheHandling {
    var currentProfileID: Int? {
        get {
            return value(forKey: Constants.Cache.CurrentProfileID)
        }
        set {
            set(newValue, forKey: Constants.Cache.CurrentProfileID)
        }
    }

    var login: String? {
        get {
            return value(forKey: Constants.Cache.Login)
        }
        set {
            set(newValue, forKey: Constants.Cache.Login)
        }
    }
}


Positioning boxes in a grid A small greedy algorithm to position boxes in a grid.

Version A

int lCurrentIndex = 0;
BoxInchesInterface lPreviousBbox = lSortedBboxes.iterator().next();
  double lEndPositionForCurrentIndex = pDimension.getEnd(lPreviousBbox);
for (BoxInchesInterface lBbox : lSortedBboxes)
{
    boolean lIsFirstIteration = lBbox == lPreviousBbox;
    if (!lIsFirstIteration && pDimension.getStart(lBbox) >= lEndPositionForCurrentIndex) {
        lCurrentIndex += 1;
        lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
    } else if (pDimension.getEnd(lBbox) < lEndPositionForCurrentIndex) {
        lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
    }
    lIndexFromBbox.put(lBbox, lCurrentIndex);
    lPreviousBbox = lBbox;
}
return lIndexFromBbox;

Version B

int lCurrentIndex = 0;
Iterator<BoxInchesInterface> lItor = lSortedBboxes.iterator();
BoxInchesInterface lPreviousBbox = lItor.next();
double lEndPositionForCurrentIndex = pDimension.getEnd(lPreviousBbox);
lIndexFromBbox.put(lPreviousBbox, lCurrentIndex);
while (lItor.hasNext())
{
    BoxInchesInterface lBbox = lItor.next();
    if (pDimension.getStart(lBbox) >= lEndPositionForCurrentIndex)
    {
        lCurrentIndex += 1;
        lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
    } else if (pDimension.getEnd(lBbox) < lEndPositionForCurrentIndex) {
        lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
    }
    lIndexFromBbox.put(lBbox, lCurrentIndex);
    lPreviousBbox = lBbox;
}

Version A has the advantage of fewer variables but has to make sure to check for the first case when the lBbox is equal to lPreviousBox. Version B has the advantage that lPreviousBox is always different from lBbox, but has to deal with the iterator.

Which one would be better practice? Any suggestions for improvement?

(and I should add that concurrency is not an issue in this case.)

Version A is definitely better, as it employs a more familiar pattern to get the job done, and it makes use of bit of trivial code (boolean lIsFirstIteration = lBbox == lPreviousBbox) to save you from duplication of non-trivial code. (lIndexFromBbox.put(lPreviousBbox, lCurrentIndex))

I would trivialize the trivial code even more, by saying bool IsFirstIteration = true right before entering the loop, and IsFirstIteration = false as the last instruction of the loop. Note that even though this is two lines of code instead of one, its complexity is smaller, because it deals with constants, not with variables.

I could perhaps give more advise if you explained what you mean by 'algorithm to position boxes in a grid'.  A grid is generally thought of as a two-dimensional structure, but I only see operations in one dimension, on variables which are defined outside of the code fragment that you provided, so... what is this code trying to accomplish?


How do I generate a list of n unique random numbers in Ruby? I am trying to create a randomly generated array of x numbers with no duplicates. I am choosing numbers, one at a time, then comparing each new number to the numbers already in the array.

Here is my code. At the end I should have an array of seven numbers, none that match, but sometimes I get a nil:

array = [] #DEFINES THE ARRAY

array[0] = rand(10)  #THIS CHOOSES FIRST NUMBER (FN) AND PUTS IT IN THE FIRST ARRAY SPOT
p "fn = #{array[0]}"

for i in 1..6  #START OF FOR LOOP TO GET 6 NUMBERS IN THE ARRAY - WHY 6?  THE FIRST NUMBER THAT POPPED IN MY HEAD

  p "Iteration #{i} -------------------------"  # THIS IS JUST SO I KNOW WHERE I AM IN THE LOOPS

  @x = rand(10)  #THIS CHOOSES THE NEXT NUMBER AND ALL NUMBERS AFTER

  array.each do |uc|  # THIS IS THE LOOP THAT COMPARES ALL NUMBERS

    @type = @x == uc ? "yes" : "no"  #DOES THE CHOSEN NUMBER EQUAL ANY NUMBER IN THE ARRAY

    p "does #{uc} = #{@x}? #{@type}"
    if @type == "yes"  # IF THE COMPARE IS TRUE, I DON'T WANT ANYTHING DONE.  IT WILL CYCLE THRU AND GET A NEW NUMBER

      i = 1
      p "YES #{@x} = #{uc}"
      break
    end  #END OF IF YES
  end  #END OF ARRAY EACH

  if @type == "no"  #IF NO, PUT NEXT NUMBER (@X) INTO THE NEXT ARRAY SPOT.

    p "in last if type= #{@type}"  #THESE STATEMENTS JUST PRINT OUT THE DIFFERENT VARIABLES SO I KNOW I AM GETTING WHAT I EXPECT

    p "in last if x = #{@x}"
    p "in last if i = #{i}"
    @x = array[i]  #THIS "SHOULD" FILL THE NEXT ARRAY SPOT - BUT DOESN'T SEEM TO

    p "#{array[i]} is in the array"  #THIS PRINT OUT IS BLANK - STATEMENT ABOVE DID NOT WORK.

    p array[i]
  end  #END OF IF NO

end  #END OF FOR LOOP

p array #PRINTS OUT THE CONTENTS OF THE ARRAY

I know there are probably quicker and easier ways to do this, but I am starting out with what I know, and building up.

The sample method does what you want:

(1..10).to_a.sample(7) #=> [2, 9, 1, 6, 8, 10, 4]


Create D lists of nodes where D is the depth of the binary tree I have used a HashMap of ArrayLists to maintain the nodes at each depth.
Also i maintained a depth at each node in the binary tree by using a HashMap that stores . While traversing the tree in a breadth first manner, store the depth of each node(just one more than the depth of its parent) in the hashmap and add the node to the queue. And add each element from the queue to the ArrayList corresponding to its depth in the binary tree.

import java.util.Collection;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.LinkedList;
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
public class Solution {

    public List<List<Integer>> levelOrder(TreeNode root)
    {
        List<List<Integer>> outputList = new ArrayList<List<Integer>>();
        if(root == null)
        {
            return outputList;
        }
        Queue<TreeNode> queue =  new LinkedList<TreeNode>();
        HashMap<Integer, ArrayList<Integer>> haMap = new HashMap<>();
        HashMap<TreeNode, Integer> nodeDepth = new HashMap<>();
        nodeDepth.put(root,0);
        queue.add(root);
        ArrayList<Integer>  tempList;
        while(!queue.isEmpty())
        {
            root = (TreeNode) queue.poll();
            if(root.left != null)
            {
                nodeDepth.put(root.left, nodeDepth.get(root)+1);
                queue.add(root.left);
            }
            if(root.right != null)
            {
                nodeDepth.put(root.right, nodeDepth.get(root)+1);
                queue.add(root.right);
            }
            if(haMap.containsKey(nodeDepth.get(root)))
            {
                tempList = haMap.get(nodeDepth.get(root));
                tempList.add(root.val);
                haMap.put(nodeDepth.get(root), tempList);
            }
            else
            {
                tempList = new ArrayList<>();
                tempList.add(root.val);
                haMap.put(nodeDepth.get(root), tempList);
            }
        }

        //List<List<Integer>> outputList = new ArrayList<List<Integer>>();

        outputList.addAll(haMap.values());

        return outputList;

    }

}

Are TreeNode and Solution in separate files? If the shown code is a single file, then it will not compile as you cannot have 2 top-level classes in the same file in Java.
Edit: Turns out it's fine as long as there is only one top-level public class.
Otherwise, just a few minor issues that I can see.
Diamond Operators
You have used the diamond operator <> for haMap and nodeDepth, but you should also use it on outputList and queue.
For example, instead of initializing outputList like:
List<List<Integer>> outputList = new ArrayList<List<Integer>>();

you should initialize it like:
List<List<Integer>> outputList = new ArrayList<>();

and similarly for queue, just like how you did for haMap and nodeDepth.
Favor interfaces over classes
When you define your collections, you should use an interface instead of specifying a specific implementation. That way you can change the implementation easily.
For example, you have done this for outputList and queue, but you should also do it for haMap, nodeDepth, and tempList.
haMap should be defined as:
Map<Integer, List<Integer>> haMap = new HashMap<>();

and similarly for nodeDepth.
Variable Names
Some of your variable names are decent, such as nodeDepth and outputList. They tell me what the object is used for as opposed to what it is. However, queue and haMap could be better. What is queue a queue of? What is being stored in haMap?


Basic linked list stack implementation with go Here goes my first stack implementation with go

New to the go language and it's been ages since I implemented a stack

Would love to discuss the data structure implementation itself and how "goish" the code looks.

package stack

import "errors"

var (
    errEmptyStack = errors.New("Stack is empty")
)

type node struct {
    next  *node
    Value interface{}
}

// Stack implementation
type Stack struct {
    head  *node
    Count int // O(1) count
}

// Push value at the top of the stack
func (stack *Stack) Push(value interface{}) {
    var node = node{Value: value}
    if stack.head == nil {
        stack.head = &node
    } else {
        node.next = stack.head
        stack.head = &node
    }

    stack.Count++
}

// Pop value from the top of the stack
func (stack *Stack) Pop() (value interface{}, err error) {
    if stack.head == nil {
        return nil, errEmptyStack
    }

    var node = stack.head
    stack.head = node.next

    stack.Count--
    return node.Value, nil
}

// Peek element at the top of the stack without changing the stack
func (stack *Stack) Peek() (value interface{}, err error) {
    if stack.head == nil {
        return nil, errEmptyStack
    }

    return stack.head.Value, nil
}

Your code is a fairly good representation of a Stack, but has some issues. Some issues are in the technicalities of how your program is written, but others are in how you've used the tools available in Go.

Technicals

The exported Count value on the Stack is OK, but it should be named Size or something - Count is an ambiguous name.

There's no reason to have a capital Value. It's not an exported struct, so the field can't be exported either.

Given that you have the Count, though, you should probably use that instead of the pointer dereferences to check for an empty list.... for example, this code:

if stack.head == nil {
    return nil, errEmptyStack
}

can be

if stack.Count == 0 {
    return nil, errEmptyStack
}

Another nit-pick is that this code has redundancies:

var node = node{Value: value}
if stack.head == nil {
    stack.head = &node
} else {
    node.next = stack.head
    stack.head = &node
}

That could be written as:

stack.head = &node{Value: value, next: stack.head}

A common practice in Go is to use a boolean to indicate a success (receive on channels & values in maps). You are using an error instead. I would have written your signatures as:

func (stack *Stack) Pop() (value interface{}, ok bool)

When you have named return values in Go you should have a value-less return statement. Your Pop and Peek methods declare output parameters of value and err.... but you return specific values return nil, errEmptyStack and return stack.head.Value, nil.

You should instead have code like:

// Pop value from the top of the stack
func (stack *Stack) Pop() (value interface{}, err error) {
    if stack.head == nil {
        err = errEmptyStack
        return
    }

    var node = stack.head
    stack.head = node.next

    stack.Count--
    value = node.Value
    return
}

I would actually have bool outputs, and have.... (the zero-value for a bool is false):

// Pop value from the top of the stack
func (stack *Stack) Pop() (value interface{}, ok bool) {
    if stack.head == nil {
        return
    }

    var node = stack.head
    stack.head = node.next

    stack.Count--
    value = node.Value
    ok = true
    return
}

Go native structures

Now, the bigger issues with your stack is really about using the struct at all....

Because Go is statically typed, and has no forms of "generics" or "templates", you are forced to use interface{} as the value type. This is awkward, and requires lots of casting to use the output values from Pop and Peek.

Writing a stack on top of a Slice is what I would do.... and not have the Stack code at all. You peek the stack by reading the last element value := stack[len(stack) - 1] and push with stack = append(stack, value)


Let's check that domain port Intro
This simple script will allow me to check for a specific opened port on a list of domains that I own. Instead of manually doing this check, I found Python a pretty good idea for such a task.
After profiling my code, I found out that def check_for_open_ports(): is really slow. It takes about 0:01:16.799242 seconds for 4 domains.
I wondered if there's a good / recommended way of improving this (maybe multithreading / multiprocessing). While asking for an answer which implements one of the above two methods is forbidden here, I wouldn't mind seeing one. I know that one shall use multiprocessing when there're I/O bound tasks which makes me believe I might go with a multithreading solution.

The code
from socket import gethostbyname, gaierror, error, socket, AF_INET, SOCK_STREAM
from sys import argv, exit
import re

DOMAINS_FILE = argv[1]
PORT = argv[2]
OUTPUT_FILE = argv[3]

def get_domains():
    """
    Return a list of domains from domains.txt
    """
    domains = []
    if len(argv) != 4:
        exit("Wrong number of arguments\n")
    try:
        with open(DOMAINS_FILE) as domains_file:
            for line in domains_file:
                domains.append(line.rstrip())
    except IOError:
        exit("First argument should be a file containing domains")
    return domains

def check_domain_format(domain):
    """
    This function removes the beginning of a domain if it starts with:

    www.
    http://
    http://www.
    https://
    https://www.
    """
    clear_domain = re.match(r"(https?://(?:www\.)?|www\.)(.*)", domain)
    if clear_domain:
        return clear_domain.group(2)
    return domain

def transform_domains_to_ips():
    """
    Return a list of ips specific to the domains in domains.txt
    """
    domains = get_domains()
    domains_ip = []
    for each_domain in domains:
        each_domain = check_domain_format(each_domain)
        try:
            domains_ip.append(gethostbyname(each_domain))
        except gaierror:
            print("Domain {} not ok. Skipping...\n".format(each_domain))
    return domains_ip

def check_for_open_ports():
    """
    Check for a specific opened PORT on all the domains from domains.txt
    """
    ips = transform_domains_to_ips()
    try:
        with open(OUTPUT_FILE, 'a') as output_file:
            for each_ip in ips:
                try:
                    sock = socket(AF_INET, SOCK_STREAM)
                    result = sock.connect_ex((each_ip, int(PORT)))

                    if result == 0:
                        output_file.write(each_ip + '\n')
                    sock.close()
                except error:
                    print("Couldn't connect to server")
    except KeyboardInterrupt:
        exit("You pressed CTRL + C. Will exit now...\n")

if __name__ == '__main__':
    check_for_open_ports()

A step further
After some checks, I realised that what was mainly slowing down the program can be improved by reducing the default timeout from the socket module using setdefaulttimeout(2).
Even if this solved a part of the problem, I still don't find it to be the cleanest one. Any advice related to performance is really welcome !

Extra info:

I'll probably use this only on Linux OSs
I've used Python 2.7.13

PS: I'd like you to ignore the fact that I didn't use optparse or argparse for parsing CLI arguments.

First a slight style note (IMHO, of course). You called your function check_domain_format, but it's actually returning a modified string and you're using the result, not checking it. I'd go for a name like validate_domain_format

About it being slow:

Yes, multi-threading would help in checking multiple domains at once, but if that was the only problem you could just make a separate bash script to launch your python script with different parameters.
You said that you own the domains, so I'm assuming you have RAW socket capabilities. If that's the case, you can speed up your check by using a SYN check. You can have a look here , even if the question has been down-voted, it should give you the general idea. Here you can find that same check.
If you're doing this for educational purposes that's ok, otherwise nmap will most likely do a better job, give you more options and be faster (because SYN check is already implemented and you can also scan for UDP ports, for example).


Convert hex string to byte array The goal is to convert a hex string to a byte array with the following requirements:

\$O(1)\$ additional space apart from input and output.
\$O(n)\$ runtime

This mostly just prohibits creating a new string with a 0 prepended to avoid having to deal with odd strings.

private static byte[] ConvertHexToBytes(string input) {
    var result = new byte[(input.Length + 1) / 2];
    var offset = 0;
    if (input.Length % 2 == 1) {
        // If length of input is odd, the first character has an implicit 0 prepended.
        result[0] = (byte)Convert.ToUInt32(input[0] + "", 16);
        offset = 1;
    }
    for (int i = 0; i < input.Length / 2; i++) {
        result[i + offset] = (byte)Convert.ToUInt32(input.Substring(i * 2 + offset, 2), 16);
    }
    return result;
}

Can we write this nicer, possibly using Linq (and some chained iterables) in C#?

Test code that covers I think all requirements:

private static void TestConversions() {
    var inputs = new[] { "",
                    "0",
                     "10",
                     "f",
                     "0f",
                     "010",
                     "0ff",
                     "f2ab"
                 };
    var i = 0;
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] {  }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0 }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0x10 }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0xf }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0xf }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0x0, 0x10 }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0x0, 0xff }));
    Debug.Assert(ConvertHexToBytes(inputs[i++]).SequenceEqual(new byte[] { 0xf2, 0xab }));
    Debug.Assert(i == inputs.Length);
}

In situations like this, when dealing with odd-offset values, and byte-manipulation, I recommend four things:

use a logical frame of reference.
get familiar with bit-wise operations.
pre-computing results at compile time is very efficient at runtime.
switch statements are high-performance lookup tables

End-of-data frame of reference

What I mean by frame-of-reference, is that your common reference point between the input string, and the output array, is the last character, and the last member of the byte[] array. You should line up your reference points, and work out from there. In this case, it means working backwards.

The next thing that you have as a frame of reference, is your input value. You use this value to drive the calculation of the output array size, and also to drive the iteration in the loop. In this case, what it means is that you should be using the input chars to drive the loop, not the size / 2.

Putting this together, consider a loop that iterates from the last char, to the first char, and then populates the last byte, to the first byte. We can then do math from the end of the input/output arrays based on the loop.

Bitwise manipulations

There are some bitwise manipulation tricks you can do here that help:

Because exactly 2 input chars are required to populate a byte, and because we are working in a base-2 (binary) system, we can take advantage of a trick in counting.... As we count from the end of the input chars to the beginning, we notice that every time we count 2, we move another output byte. If we divide the count by 2, we get the relative position from the output end.
Remember, a right-shift is the same as dividing by 2 (integer division):

int x = 10;
x = x >> 1; // right shift once...
// x now is 5.

Bit-wise ANDing of a value with 1 tells you what the last bit is.

int x = 5;
x = x & 1;
// x now is 1

Bit-wise ORing of two values sets the respective output bits to 1 if either of the input bits are 1.

int a = 0x0a;
int b = 0xb0;
int c = a | b;
// c now is 0xba;

switch statements for fast lookups

The compiler is able to optimize a switch statement very effectively. Consider the following switch statement that converts a character in to the corresponding hex value. This is very efficient because it is based on fancy compile-time logic. It takes some effort to code, but the results are worth it:

private static int HexToInt(char c)
{
    switch (c) {
        case '0':
            return 0;
        case '1':
            return 1;
        case '2':
            return 2;
        case '3':
            return 3;
        case '4':
            return 4;
        case '5':
            return 5;
        case '6':
            return 6;
        case '7':
            return 7;
        case '8':
            return 8;
        case '9':
            return 9;
        case 'a':
        case 'A':
            return 10;
        case 'b':
        case 'B':
            return 11;
        case 'c':
        case 'C':
            return 12;
        case 'd':
        case 'D':
            return 13;
        case 'e':
        case 'E':
            return 14;
        case 'f':
        case 'F':
            return 15;
        default:
            throw new FormatException("Unrecognized hex char " + c);
    }
}

On a character-by-character basis this will be faster than the use of ToUInt32()

Lookup Tables in memory

Again, there are only 16 hex values, this makes the memory usage very small, and you can do some memory lookup tricks.

Putting it together

use a loop that counts back from the end of the input/output. Then you don't need special odd-length input handling.
identify whether an input char is going to be a high or low nibble in the result.
use a lookup table (low/high nibble) to find a byte value for that input.
use a bit-wise OR to add the low and high nibbles together
use bitwise AND and bitwise right-shift to convert the input character to the output byte/nibble position.

The following code is a 'simple' loop, that is efficient, and works for your input cases:

private static readonly byte[,] ByteLookup = new byte[,]
{
    // low nibble
    {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f},
    // high nibble
    {0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0}
};

private static byte[] ConvertHexToBytesX(string input) {
    var result = new byte[(input.Length + 1) >> 1];
    int lastcell = result.Length - 1;
    int lastchar = input.Length - 1;
    // count up in characters, but inside the loop will
    // reference from the end of the input/output.
    for (int i = 0; i < input.Length; i++) {
        // i >> 1    -  (i / 2) gives the result byte offset from the end
        // i & 1     -  1 if it is high-nibble, 0 for low-nibble.
        result[lastcell - (i >> 1)] |= ByteLookup[i & 1, HexToInt(input[lastchar - i])];
    }
    return result;
}

Thus, you can accomplish the conversion with efficient switches, array lookups, and 'simple' math in the loops.

I have put together an Ideone implementation of this code so you can compare it with your code.


Extracting Javascript functions I have this jQuery click handler function that has three jobs:

Set the time interval for the refresh rate
Change the color on the clicked refresh rate selection
Callback the tablesort functions to resort the newly loaded data

I'd like to pull out the separate functionality into named functions, but I'm unsure (being a somewhat JS newb) how to do that an achieve the same behavior.

Javascript Code:

$(document).ready(function() {

    $("#refresh-buttons").on("click", "button", function(event) {

        var interval = 0;

        switch(event.target.id)  {
          case "refresh-off" :
                interval = 50000000;
                $(this).parent().children().removeClass("pressed-button");
                $(this).addClass("pressed-button");
                break;

          case "refresh-5-sec" :
              interval = 5000;
              $(this).parent().children().removeClass("pressed-button");
              $(this).addClass("pressed-button");
              break;

          case "refresh-30-sec" :
              interval = 30000;
              $(this).parent().children().removeClass("pressed-button");
              $(this).addClass("pressed-button");
              break;

          case "refresh-60-sec" :
              interval = 60000;
              $(this).parent().children().removeClass("pressed-button");
              $(this).addClass("pressed-button");
              break;
        }

        if (interval != 0)
        {
            clearInterval(intervalId);
            intervalId = setInterval(function(){
                $('#status-tables').load('/dashboard/index #status-tables', function(){
                  $("#workstation-table").tablesorter();
                  $("#report-table1").tablesorter({sortList:[[1,0]]} );
                  $("#report-table2").tablesorter({sortList:[[1,0]]});
                });
            }, interval);
        }

    });
});

Add the refresh-rates map to #refresh-buttons element ( use .data() function ), optimize amount of $() calls:

$(document).ready(function() {
    var refresh_btns$;

    // you can store id map where ever you prefer to
    // I've figured it would be good to keep them with
    // the element they are related to
    ( refresh_btns$ = $("#refresh-buttons") )
    .data(
        "refreshRates",
        {
            "refresh-off"    :50000000,
            "refresh-5-sec"  :5000,
            "refresh-30-sec" :30000,
            "refresh-60-sec" :60000
        }
    )
    .on("click", "button", function () {
        var
        interval = refresh_btns$.data("refreshRates")[ this.id ] || 0;
        if (
            interval !== 0
        ) {
            // yeah m_x is right about .toggleClass()
            // it producess weird behaviour
            // this shold to the job
            $( this )
            .addClass("pressed-button")
            .siblings()
            .removeClass("pressed-button");

            clearInterval(intervalId);
            intervalId =
            setInterval(
                function () {
                    $('#status-tables')
                    .load(
                        '/dashboard/index #status-tables',
                        function () {
                            $("#workstation-table").tablesorter();
                            $("#report-table1, #report-table2")
                            .tablesorter( { sortList : [ [ 1, 0 ] ] } );
                        }
                    );
                },
                interval
            );
        }
    });
});


Super simple templated memory pool in C++ I have a small program where I have a background thread that plays sound, so it needs to run really fast, but it also needs to do a small amount of memory management. I didn't want to use normal new and delete in a time critical area, so I threw this together, but set it up so I could reuse it elsewhere.

template <typename T, unsigned int capacity>
class MemoryPool
{
public:
    MemoryPool()
    {
        for (unsigned int i = 0; i < capacity; i++)
        {
            myUnusedMemory[i] = &myMemory[i];
        }
    }

    void* operator new(std::size_t size)
    {
        return myUnusedMemory[myUnusedIndex--];
    }

    void operator delete(void* ptr)
    {
        myUnusedMemory[++myUnusedIndex] = (T*)ptr;
    }

private:
    static int myUnusedIndex;
    static T myMemory[capacity];
    static T* myUnusedMemory[capacity];
};

template <typename T, unsigned int capacity> int MemoryPool<T, capacity>::myUnusedIndex = capacity-1;
template <typename T, unsigned int capacity> T MemoryPool<T, capacity>::myMemory[capacity];
template <typename T, unsigned int capacity> T* MemoryPool<T, capacity>::myUnusedMemory[capacity];

The intended usage is something like this:

struct Sound : public ag::util::MemoryPool<Sound, 100>
{
    // ...
};

Now when calling new Sound() I get one from my memory pool, which should be super fast. The only things that I can think of that could be improved are making operator new throw an exception when at capacity. I think I might be able to do away with typename T. The only  reason it's needed is so that myMemory knows the size of its elements, but I feel like there's another solution here.

This currently will not work.

As every-time you create an object derived from MemoryPool you re-initialize the myUnusedMemory structure thus potentially messing up your management.

struct Game : public ag::util::MemoryPool<Game, 2>  {};

int main()
{
    Game* p1  = new Game;
    Game* p2  = new Game;
    delete p1;
    delete p2;

    // myUnusedMemory now set like this:
    // myUnusedMemory[0] = &myMemory[1];
    // myUnusedMemory[1] = &myMemory[0];

    // Now when we create the next one it resets the array:

    Game* p3  = new Game;
    // myUnusedMemory now set like this: (because the constructor reset the array)
    // myUnusedMemory[0] = &myMemory[0];
    // myUnusedMemory[1] = &myMemory[1];

    Game* p4  = new Game;  // Now p3 and p4 point at the same memory location
}

This line:

static T myMemory[capacity];

Is also not good as you are actually initializing the objects. Thus, when you are calling new your new operator is returning a pointer to an already initialized object . The constructor will then be re-called. Thus overriding the original content without the destructor being called (thus leaking any memory that should have been deleted).

I suppose you could call the destructor inside the new operator but that seems wasteful (and may be expensive) and sort of counter intuitive. So you want to use uninitialized memory for your pool.
You could do this:

static char myMemory[capacity * sizeof(T)];

But unfortunately this is not guaranteed to be correctly aligned.
If you dynamically allocate the memory then it will be fine. Use std::vector and it will be dynamically allocated and safe.

static std::vector<char>  myMemory(capacity * sizeof(T));


Selecting element from a collection based on bitwise-and result I need to improve this section of code:

    uint32_t to_handle = 0;
    uint32_t test_const1 = Constraint3::VAL1 + Constraint3::VAL2;
    uint32_t test_const2 = Constraint1::VAL2 + Constraint1::VAL4 + Constraint1::VAL8;
    uint32_t test_const3 = Constraint2::VAL1 +  Constraint2::VAL2 + Constraint2::VAL4;

    to_handle = test_const1;

    for(ConstraintsContainer_t::iterator it = constraints_.begin(); it != constraints_.end(); ++it) {
        if( ( ((*it).get() & to_handle) == (*it).get() ) &&
                ( ((*it).get() & test_const2) == (*it).get() ) &&
                ( ((*it).get() & test_const3) == (*it).get() ) ) {
            choosen_.push_back((*it));
            to_handle -= (*it).get();
        }
    }

Here are declarations:

    namespace Constraint1 {
    typedef enum {
        NONE            = 0x00000000,
        VAL1            = 0x00000001,
        VAL2            = 0x00000002,
        VAL4            = 0x00000004,
        VAL8            = 0x00000008,
        ALL             = 0xFFFFFFFF
    } Type;
    }
    namespace Constraint2 {
    typedef enum {
        NONE            = 0x00000000,
        VAL1            = 0x00000001,
        VAL2            = 0x00000002,
        VAL4            = 0x00000004,
        VAL8            = 0x00000008,
        ALL             = 0xFFFFFFFF
    } Type;
    }
    namespace Constraint3 {
    typedef enum {
        NONE            = 0x00000000,
        VAL1            = 0x00000001,
        VAL2            = 0x00000002,
        VAL4            = 0x00000004,
        VAL8            = 0x00000008,
        VAL16           = 0x00000010,
        VAL32           = 0x00000020,
        ALL             = 0xFFFFFFFF
    } Type;
    }
    typedef std::vector  > ConstraintsContainer_t;
    ConstraintsContainer_t constraints_;
    ConstraintsContainer_t choosen_;

The goal is to select elements from a collection by performing a bitwise-and on them.

Order of insertion in that vector matters and number of element should reach about 100. It's currently taking about 50 microseconds to complete this section of codes, I'd need to make it 10-20 microseconds if possible.

Here is the source code on a live workspace if it helps:
http://coliru.stacked-crooked.com/view?id=356a9d8c94bddf6721f98bbc44c74fec-71380fc8ea55c1ab9f744d79fff5379c

I've tryed to use boost multi_index_containers, but it'd require to get this to work:
https://stackoverflow.com/questions/16101886/boost-multi-index-container-with-composite-key-and-logical-and-comparison

Any help is appreciated!

to_handle actually varies, but the test_consts are all constant, so we can give the compiler a hint here

const uint32_t test_const1 = Constraint3::VAL1 + Constraint3::VAL2;
const uint32_t test_const2 = Constraint1::VAL2 + Constraint1::VAL4 + Constraint1::VAL8;
const uint32_t test_const3 = Constraint2::VAL1 +  Constraint2::VAL2 + Constraint2::VAL4;

uint32_t to_handle = test_const1;
for(ConstraintsContainer_t::iterator it = constraints_.begin(); it != constraints_.end(); ++it) {

EDIT

I've just seen from the linked code that the posted code is completely wrong. So, the remainder of this answer is unlikely to be helpful.

I will however observe that you're timing both the operations you sort-of show above, but also the formatted output. Are you sure you're timing the right thing?

now, we de-reference your iterator a lot in this loop. I don't know how easily the compiler can handle it here, but IMO this is more readable:

    auto &item = it->get();

(if you don't have C++11 auto, just put the actual type in - I don't know what it is here)

    if( (item & to_handle) == item &&
        (item & test_const2) == item &&
        (item & test_const3) == item ) {
        choosen_.push_back((*it));
        to_handle -= item;
    }
}

Now, the second two conditions in your if never vary, and they simply test that all the set bits of item are inside both masks test_const2=0x0E and test_const3=0x07. That is, none of the set bits are outside test_const2 & test_const3, so

const uint32_t fail_test = ~(test_const2 & test_const3);

//...

    if( (item & to_handle) == item &&
        (item & fail_test) == 0) {
        choosen_.push_back((*it));
        to_handle -= item;
    }

again, the optimizer might have figured that out already, but this version is anyway more expressive.


Create all combinations of length N from a given alphabet (2) I implemented this challenge in Java before but performance was not the best so I decided to implement this in C++ to compare the two. The code works and performance is indeed much better than in the Java version. However I am unsure about the quality of this code.
I am still not overly familiar with modern C++ and would like to know if there is anything that I am doing awfully wrong.
Challenge description:

You are given a number N and a string S. Print all of the possible ways to write a string of length N from the characters in string S, comma delimited in alphabetical order.
The first argument will be the path to the input filename containing the test data. Each line in this file is a separate test case. Each line is in the format: N,S i.e. a positive integer, followed by a string (comma separated). E.g.
Print all of the possible ways to write a string of length N from the characters in string S comma delimited in alphabetical order, with no duplicates.
Input sample:
1,aa
2,ab
3,pop

Output sample:
a
aa,ab,ba,bb
ooo,oop,opo,opp,poo,pop,ppo,ppp

Code:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include <sstream>
#include <iterator>

void generate_words(const std::vector<char> &alphabet, size_t &word_length, std::vector<std::string> &results)
{
    std::vector<size_t> index(word_length, 0);

    for (;;)
    {
        std::string word(index.size(), ' ');
        for (size_t i = 0; i < index.size(); ++i)
        {
            word[i] = alphabet[index[i]];
        }
        results.emplace_back(word);

        for (int i = index.size() - 1; ; --i)
        {
            if (i < 0)
            {
                return;
            }

            ++index[i];

            if (index[i] == alphabet.size())
            {
                index[i] = 0;
            }
            else
            {
                break;
            }
        }
    }
}

int main(int argc, char **argv)
{
    std::ifstream infile(argv[1], std::ios::in | std::ifstream::binary);

    std::string line;
    while (infile.good() && getline(infile, line))
    {
        size_t word_length = std::stoi(line.substr(0, line.find(',')));
        std::string letters = line.substr(line.find(',') + 1);

        std::vector<char> alphabet;
        for (const auto &it : letters)
        {
            alphabet.push_back(it);
        }
        std::sort(alphabet.begin(), alphabet.end());
        auto last = std::unique(alphabet.begin(), alphabet.end());
        alphabet.erase(last, alphabet.end());

        std::vector<std::string> results;
        generate_words(alphabet, word_length, results);

        std::ostringstream result_line;
        std::copy(results.begin(), results.end() - 1, std::ostream_iterator<std::string>(result_line, ","));
        result_line << results.back();

        std::cout << result_line.str() << "\n";
    }
}

The generate_words code looks pretty good to me.

Actually, one minor thing - you can return the vector as opposed to passing out by reference. You won't get a performance hit (see move semantics), and it'll make the function easier to use:

auto words = generate_words(letters, word_length);

Some minor observations about the code in main:

1 - As a general rule, you should allocate a vector's memory up front if you know how many elements it will contain. This prevents reallocations from occurring when new elements are inserted into the vector. std::vector provides the reserve method for doing this:

std::vector<char> alphabet;
// allocate memory for at least letter.size() chars
alphabet.reserve(letters.size());
for (const auto &it : letters)
{
    // now you don't have to worry about reallocations happening
    // here
    alphabet.push_back(it);
}

See:

What happens under the hood of vector::push_back memory wise?

std::vector push_back is bottleneck

vector::reserve example code

In this case, you can skip the loop entirely by using std::vector's iterator constructor:

std::vector<char> alphabet(letters.begin(), letters.end());

2 - If you're not using the variable 'letters' after it's been initialized, you could do your sort/unique operation in place:

std::sort(letters.begin(), letters.end());
letters.erase(std::unique(letters.begin(), letters.end()), letters.end());

and then pass letters to generate_words() (you'd have to change the first parameter to a string)


Print diamond shape in Java I'm printing a diamond shape in Java. It's working fine, but is there a way to re-write this code to make it faster?

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

sc.close();

String ns = String.valueOf(n);
int z = n/2;

int k = n%2;

for (int j = 0 ; j<n;j++) {

    for (int i = 0; i < z; i++)
        System.out.print(" ");
    for (int i = 0; i < k ; i++){
        System.out.print("*");
    if (i==k-1)
        System.out.print("\n");
    }

    if ((k-n)==0)
        break;
    z--;
    k=k+2;

}

 z = (n)/2;

 k = (n)%2;
int w = k;
int y = n-2;

for (int j = 0 ; j<z  ;j++) {

    for (int i = 0 ; i<w;i++)
    System.out.print(" ");

    for (int i = 0 ; i< y ;i++)
        System.out.print("*");
    w=w+1;
    y=y-2;

    System.out.print("\n");

}

After reviewing your code, I'll point out that:

It would be better if you used more descriptive variable names. It improves readability and might even help you better understand your own code, ex:

int width = sc.nextInt(); // or whatever it represents

Always use curly braces for if and for statements, even if they wrap around a single statement. Shorter code isn't faster, but makes it easier to introduce bugs. You never pay a penalty for extra curly braces or parentheses, so use them as much as you want to clarify intention. For example this snippet can be ambiguous:

for (int i = 0 ; i< y ;i++)
    System.out.print("*");
w=w+1;
y=y-2;

Did you mean

for (int i = 0 ; i< y ;i++) {
    System.out.print("*");
    w=w+1;
    y=y-2;
}

or

for (int i = 0 ; i< y ;i++) {
    System.out.print("*");
}
w=w+1;
y=y-2;


Binary Search Algorithm in JavaScript I've written this implementation of a binary search algorithm, and wanted to know if it was efficient and where I can improve.

function search(el, list) {
    // list = list || LIST;
    var LIM = Math.ceil(Math.log2(list.length)),
        lb = 0,
        ub = list.length - 1,
        i;
    while (el !== list[i = ~~((lb + ub) / 2)] && el !== list[++i]) {
        if (!--LIM) return ("NOT FOUND");
        if (el > list[i]) lb = i;
        else ub = i;
    }
    return i;
}

What doesn't work properly

As pointed by @Roland Illig's answer, your solution produces an error when list contains only 1 item and this item doesn't match el.

It comes from the fact that:

for a 1-item list, LIM is 0
after the while() expression didn't find a match, --LIM gives -1, which evaluates to true
so if (!--LIM) is false and the loop continues infinitely...

This issue can be solved by merely changing this test to if (--LIM <= 0)

Possible improvements

As pointed by @Dair, your names are somewhat cryptic.
For the sake of readability you'd better to change:

el to searchedValue
LIM to tries (also note that using uppercase is supposed to be reserved for constants, while this data is not)
lb to lowerBound
ub to upperBound

Also, following best practices, I recommend to use block marks for if()s.

All that said, here is a suggested improved (and corrected) version:

function search(searchedValue, list) {
    var tries = Math.ceil(Math.log2(list.length)),
        lowerBound = 0,
        upperBound = list.length - 1,
        i;
    while (
        searchedValue !== list[i = ~~((lowerBound + upperBound) / 2)]
    &&
        searchedValue !== list[++i]
    ) {
        if (--tries <= 0) {
            return ("NOT FOUND");
        }
        if (searchedValue > list[i]) {
            lowerBound = i;
        } else {
            upperBound = i;
        }
    }
    return i;
}


A program that prints the longest substring of s in which the letters occur in alphabetical order Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print

Longest substring in alphabetical order is: beggh

In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print

Longest substring in alphabetical order is: abc

I have been working on a edX course, MITx: 6.00.1x Introduction to Computer Science and Programming Using Python. Encountering the problem mentioned above, I set out to write a piece of code which I found to be the most disgusting to date(excluding Project Euler draft code).
Note: s can be any input, but in my case, edX will automatically input a value for s, so I do not need to define s.
first=0
second=1
strang1=''
strang2=''
while second<len(s):
    if second>=len(s):
        break
    elif s[first]<=s[second]:
        strang1+=s[first:second+1]
        while second<=len(s):
            second+=1
            if second>=len(s):
                break
            elif s[second]>=strang1[-1]:
                strang1+=s[second]
                if len(strang1)>len(strang2):
                    strang2=strang1
            else:
                if len(strang1)>len(strang2):
                    strang2=strang1
                strang1=''
                first=second-1
                break
    else:
        if len(s[first])>len(strang2):
            strang2=s[first]
        first+=1
        second+=1
print("Longest substring in alphabetical order is:" + strang2)

The code can accurately take on any input(if defined) and output it accurately(according to the edX's test runs). I'm looking to make my code more efficient, any suggestions? I'll accept any, fancy newfangled functions or maybe a total rework, I don't mind.

if second>=len(s):
    break

This is not necessary. You have just checked that in the loop condition.

first=0
second=1
strang1=''
strang2=''

Consider renaming these variables to say what they do more clearly. Even "begin" and "end" would be clearer than "first" and second, but do not be afraid of longer variable names.

As a rule of thumb, be wary of variable names which you have numbered. They often mean either that they do sufficiently the same thing and you could simplify the code by putting them in a list and looping, or they do not do the same thing and you should name them appropriately. (As is the case here)

strang1+=s[second]
if len(strang1)>len(strang2):

Constructing strings, especially one character at a time, is an expensive operation. You could do this more efficiently by just storing the location in the input string. You can compare sizes just by subtracting the start of that location from the end. At the end of the loop, you can assign the result in one go using s[start:end] notation.

  Assume s is a string of lower case characters.

When you have assumptions like this, it is generally prudent to check them. Coding challenges won't tend to require it. When you have a larger code base and are trying to work out where something went wrong, you'll thank your past self if the first thing that was given input it wasn't designed for is screaming about it so you know where to look.


Fragment-changing in Android My current code is kinda atrocious to switch fragments and everything, but I don't know a better way to check to see if the fragment I'm trying to switch to.

private void FragmentChange(Bundle Data) {
    SetActionBarButtons(new String[] { "SearchButtonOff", "SearchExtraButtonOff" });
    String[] data = Data.getStringArray(ACTIVITY_MAIN.DATA);
    String type = data[0];
    String fragment = data[1];
    if (fragment.equals(POST_MAIN)) {
        postmainFragment = new Fragment_PostMain();
        mainContainer = postmainFragment;
    } else if (fragment.equals(POST_ACCOUNT)) {
        postaccountFragment = new Fragment_PostAccount();
        mainContainer = postaccountFragment;
    } else if (fragment.equals(POST_ACCOUNTLOGIN)) {
        postaccountloginFragment = new Fragment_PostAccountLogin();
        mainContainer = postaccountloginFragment;
    } else if (fragment.equals(POST_LOCATION_MAIN)) {
        postlocationmainFragment = new Fragment_PostLocationMain();
        mainContainer = postlocationmainFragment;
    } else if (fragment.equals(POST_IMAGES)) {
        postimagesFragment = new Fragment_PostImages();
        mainContainer = postimagesFragment;
    } else if (fragment.equals(POST_TEMPLATE)) {
        posttemplateFragment = new Fragment_PostTemplate();
        mainContainer = posttemplateFragment;
    } else if (fragment.equals(POST_LOCATION)) {
        postlocationFragment = new Fragment_PostLocation();
        mainContainer = postlocationFragment;
    } else if (fragment.equals(POST_CATEGORY)) {
        postcategoryFragment = new Fragment_PostCategory();
        mainContainer = postcategoryFragment;
    } else if (fragment.equals(POST_CATEGORY_MAIN)) {
        postcategorymainFragment = new Fragment_PostCategoryMain();
        mainContainer = postcategorymainFragment;
    } else if (fragment.equals(POST_LOCATION_MAIN)) {
        postlocationmainFragment = new Fragment_PostLocationMain();
        mainContainer = postlocationmainFragment;
    } else if (fragment.equals(LOADING)) {
        loadingFragment = new Fragment_Loading();
        mainContainer = loadingFragment;
    } else if (fragment.equals(POST_RESULTS_IMAGEVIEW)) {
        postresultsimageviewFragment = new FRAGMENT_POST_RESULTS_IMAGEVIEW();
        mainContainer = postresultsimageviewFragment;
    } else if (fragment.equals(SEARCH_RESULTS_REPLY)) {
        postresultsreplyFragment = new FRAGMENT_SEARCH_RESULTS_REPLY();
        mainContainer = postresultsreplyFragment;
    }

    FragmentTransaction FT = getFragmentManager().beginTransaction();
    if (type.equals(FRAGMENTCHANGE_FADEIN)) {
        FT.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
    } else if (type.equals(FRAGMENTCHANGE_FLIP_FORWARD)) {
        FT.setCustomAnimations(R.animator.card_flip_right_in, R.animator.card_flip_right_out);
    } else if (type.equals(FRAGMENTCHANGE_FLIP_BACK)) {
        FT.setCustomAnimations(R.animator.card_flip_left_in, R.animator.card_flip_left_out);
    }
    if (mainContainer != null) {
        FT.replace(R.id.main_fragment, mainContainer).commit();
    }
}

Basically, I want to pass a Bundle down and I set the first part of the bundle as the "type" for the animation, and the fragment as the actual fragment that I'm trying to switch it.  Then of course since I have so many fragments it just gets really messy with the if statements.

Is there a better way to write this so it's not as "ugly"?

Here's few things to avoid "ugly" dups and long-long methods:

Don't duplicate variables

Like your mainContainer variable, because you used one variable for each fragment and pass it to another global variable:

postmainFragment = new Fragment_PostMain(); // global variable outside fragmentChange()
mainContainer = postmainFragment; // global variable outside fragmentChange()
...
postaccountFragment = new Fragment_PostAccount();
mainContainer = postaccountFragment;
...

It should be better to use just one variable, and you will avoid duplicate allocations:

Fragment mainContainer = null; // inside fragmentChange()
...
mainContainer = new Fragment_PostMain(); // directly set the fragment
...
mainContainer = new Fragment_PostAccount();

Therefore, you will not create global fragments variables for each fragments in parent class (postmainFragment, postaccountFragment, etc).

Use "switch" as @dacories said

You can do with Integers instead of Strings (it might be faster), for example:

private final static int FRAGMENTCHANGE_FADEIN = 0;
private final static int FRAGMENTCHANGE_FLIP_FORWARD = 1;
private final static int FRAGMENTCHANGE_FLIP_BACK= 2;
...
private void fragmentChange(Bundle data) {
    int transition = data[0];
    switch(transition) {
        case FRAGMENTCHANGE_FADEIN:
             ...
        case FRAGMENTCHANGE_FLIP_FORWARD:
             ...
    }
}

You can do the same for fragments...

Do a general method and avoid long-long switch

Instead of passing an array and switching between all your fragment in the fragmentChange method, you could pass directly the fragment concerned:

private void fragmentChange(Fragment frag, String tag, int transition) {
    if (frag != null) {
        ...
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        switch (transition) {
            default:
            case FRAGMENTCHANGE_FADEIN:
                ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
                break;
            case FRAGMENTCHANGE_FLIP_FORWARD:
                ft.setCustomAnimations(R.animator.card_flip_right_in,
                                    R.animator.card_flip_right_out);
                break;
            case FRAGMENTCHANGE_FLIP_BACK:
                ft.setCustomAnimations(R.animator.card_flip_left_in,
                                    R.animator.card_flip_left_out);
                break;
        }
        ft.replace(R.id.main_fragment, frag, tag).commit();
    }
}

So, you could directly call the change method as follows:

fragmentChange(new Fragment_PostMain(), "PostMain", 0);

You will in this case avoid a global fragment variable mainContainer which is constantly allocated in the whole class and avoid a very long switch or if/else condition.

But, if I want to pass datas to the next fragment?

One solution could be using static instance methods to pass datas with setArguments.
You could have an instance in fragment class to attach the datas and return just the fragment into the fragmentChange method.
An example might be in each fragment:

public static Fragment_PostMain newInstance(int i, String n, boolean b) {
    Fragment_PostMain frag = new Fragment_PostMain();
    Bundle datas = new Bundle();
    datas.putInt(i);
    datas.putString(n);
    datas.putBoolean(b);
    frag.setArguments(datas);
    return frag;
}

You could retrieve these datas with getArguments methods in fragment.
And call the method by passing the fragment with datas:

Fragment_PostMain frag = Fragment_PostMain.newInstance(12, "NameSection", true);
fragmentChange(frag, "PostMain", 0);

Like this, you won't have to create a Bundle array in the method.

Finally

Your solution with long-long if/else can be more readable with switch statement, yes. My solutions above will be more readable with less code, yes again.
However, you will have to think of what you really need: a long condition code (which can be easier to change in future if one fragment change for all class) or a short version (with class customization and direct access to the datas).
I hope this will help you.

Just an advice: in Java, the standard naming conventions is Classes should begin with an uppercase whereas methods with lowercase.


Algorithm for dividing a number into largest "power of two" buckets? For example, these are expected outputs:
3: 2, 1
4: 4
5: 4, 1
6: 4, 2
7: 4, 2, 1
8: 8
9: 8, 1
...
20: 16, 4
...
25: 16, 8, 1
...
36: 32, 4
...
50: 32, 16, 2

Up to the max of 32 being the largest subunit. So then we get larger:
100: 32, 32, 32, 4
...
201: 32, 32, 32, 32, 32, 32, 8, 1
...

What is the equation / algorithm to implement this most optimally in JavaScript? By optimal I mean the fastest performance, or fewest primitive steps for example, with the least amount of temporary variables, etc. I feel like my solution below is a "brute force" approach which lacks elegance and it seems like it could be optimized somehow. Ideally there would be no Math.floor or division as well, if possible to use some sort of bit magic.

log(20)
log(25)
log(36)
log(50)
log(100)
log(200)

function log(n) {
  console.log(generate_numbers(n).join(', '))
}

function generate_numbers(n) {
  const chunks = count_chunks(n)
  const sum = chunks.reduce((m, i) => m + i, 0)
  const result = new Array(sum)
  const values = [ 1, 2, 4, 8, 16, 32 ]
  let i = chunks.length
  let j = 0
  while (i--) {
    let x = chunks[i]
    while (x--) {
      result[j++] = values[i]
    }
  }
  return result
}

function count_chunks(n) {
  let chunks = [0, 0, 0, 0, 0, 0]
  if (n >= 32) {
    let i = Math.floor(n / 32)
    chunks[5] = i
    n = n - (i * 32)
  }
  if (n >= 16) {
    chunks[4] = 1
    n = n - 16
  }
  if (n >= 8) {
    chunks[3] = 1
    n = n - 8
  }
  if (n >= 4) {
    chunks[2] = 1
    n = n - 4
  }
  if (n >= 2) {
    chunks[1] = 1
    n = n - 2
  }
  if (n >= 1) {
    chunks[0] = 1
  }
  return chunks
}

CertainPerformance's solution using .toString(2) is clever, but for a fast solution to such an elementary problem, simple bit manipulation and a while loop is the way to go:

function split(number, bits = 5) {
  let unit = 1 << bits;
  const result = new Array(number >> bits).fill(unit);
  while (unit >= 1) {
    unit >>= 1;
    if (number & unit) result.push(unit);
  }
  return result;
}

const numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201];
numbers.forEach(n => console.log(n, '=', split(n).join(' + ')));

In particular, you can indeed avoid division and Math.floor() by using the bitwise right shift operator >> instead: n >> k is a fast and compact way of calculating Math.trunc(n / 2**k) for any integer n and any non-negative integer k.  Also, the bitwise AND operator & makes it easy to check whether an integer has a particular bit set: n & k evaluates to a non-zero value if and only if n and k have any set bits in common.

Ps. To make this code even faster, at the cost of some extra complexity, we can precalculate the length of the result array so that we don't need to use .push():

function split(number, bits = 5) {
  // precalculate the length of the result array
  const maxUnit = 1 << bits, prefixLength = number >> bits;
  let length = prefixLength, unit = maxUnit;
  while (unit >= 1) {
    unit >>= 1;
    if (number & unit) length++;
  }

  // allocate and fill the array
  const result = new Array(length).fill(maxUnit);
  let i = prefixLength; unit = maxUnit;
  while (unit >= 1) {
    unit >>= 1;
    if (number & unit) result[i++] = unit;
  }
  return result;
}

const numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201];
numbers.forEach(n => console.log(n, '=', split(n).join(' + ')));

According to a quick benchmark, the preallocating version is about 40% faster than the one using .push() (and both are several times faster than the other solutions posted so far).

Pps. It turns out that, maybe a bit counter-intuitively, just building the entire output array one element at a time using .push() may be the simplest and fastest solution, at least for inputs that aren't too huge.  The credit for this solution goes to superb rain, so I'll just link to their answer for it, but I've added it to my benchmark above.  It seems to perform about as well in the benchmark (for all numbers from 0 to 999) as my fastest solution on Firefox, and outperforms all my solutions on Chrome.


First time jQuery on xkcd I'm a first time user of jQuery (and a huge fan already). I am trying to make the comic picture of an xkcd page onclick to the explanation page.

Here's what I've done.

$("#comic").click(function(){
  return window.open("http://www.explainxkcd.com/wiki/index.php/" +
    document.URL.split("/")[3]);
});

Is this efficient? Is this robust? Any jQuerying tips?

Besides not needing to return the result of window.open, it looks pretty good. See this thread for an explanation of what returning a value from event does. From this answer,

  return false from within a jQuery event handler is effectively the
  same as calling both  e.preventDefault and e.stopPropagation on
  the passed jQuery.Event object.

  e.preventDefault() will prevent the default event from occuring,
  e.stopPropagation() will prevent the event from bubbling up and
  return false will do both. Note that this behaviour differs from
  normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

Clearly, thats not what we want, so instead of returning the result of window.open, we should just omit the return.

This may not be necessary, but I would be more comfortable using

var comicID = location.pathname.split("/")[1];

over

var comicID = document.URL.split("/")[3]);

mainly because http:// may be omitted from the URL and the code will still work (shouldn't ever be a problem either way). It's also more intuitive. I would also leave a comment for the code such as

// where path name looks like /156/ for xkcd.com/156/

Indentation would also help the code be more readable, however it's short so it doesn't matter too much... That said, I would write your code:

// when a user clicks the comic open the explanation
$("#comic").click(function(){
   // where pathname is the comicID eg /156/ for xkcd.com/156
   window.open("http://explainxkcd.com/wiki/index.php/" + location.pathname.split("/")[1]);
});


Selection sorting an int array I'd like to improve this selection sort code

package com.arun.sort;

import java.util.Arrays;

public class SelectionSort {

    public static void main(String[] args) {

        int[] arr = { 5, 2, 131, 13, 11, 1 };

        SelectionSort sort = new SelectionSort();

        sort.selectionSort(arr);

        System.out.println(Arrays.toString(arr));

    }

    public int[] selectionSort(int[] a) {

        int min;
        for (int out = 0; out < a.length - 1; out++) {
            min = out;
            for (int in = out + 1; in < a.length; in++) {
                if (a[in] < a[min]) {
                    min = in;

                }
            }
            int tempValue = a[out];
            a[out] = a[min];
            a[min] = tempValue;

        }

        return a;

    }

}

Few points.

There is no need to create a object for SelectionSort. Declare it static.

selectionSort(arr);

Your variable names should be made better. Its not recommended to use 'out' as variable, or int a[]. You can use int inputArr[] as thats more descriptive. Imagine someone is reading your code then if you make their life easy by making your code more descriptive then job is done faster.

You can create a seperate swap method. This will structure your code properly. You can reuse the swap method for other sorting methods too.

private void swap(int out, int min)
{
int temp = a[out];
a[out] = a[min];
a[min] = temp;
}


Accelerate set of sed commands in files (recursively over full directory) I run this to fix some hard-coded references, replacing occurrences of mywar by clientwar:

find . -type f -exec sed -i "s% '/mywar/% '/clientwar/%g" {} +
find . -type f -exec sed -i "s%,'/mywar/%,'/clientwar/%g" {} +
find . -type f -exec sed -i 's% "/mywar/% "/clientwar/%g' {} +
find . -type f -exec sed -i 's% file="/mywar/% file="/clientwar/%g' {} +
find . -type f -exec sed -i 's%<TAB>href="/mywar/%<TAB>href="/clientwar/%g' {} +
find . -type f -exec sed -i 's% href="/mywar/% href="/clientwar/%g' {} +
find . -type f -exec sed -i 's% name="/mywar/% name="/clientwar/%g' {} +
find . -type f -exec sed -i 's% relativePath="/mywar/% relativePath="/clientwar/%g' {} +
find . -type f -exec sed -i 's% requestUrl.indexOf("/mywar/")% requestUrl.indexOf("/clientwar/")%g' {} +
find . -type f -exec sed -i "s% src='/mywar/% src='/clientwar/%g" {} +
find . -type f -exec sed -i 's%<TAB>src="/mywar/%<TAB>src="/clientwar/%g' {} +
find . -type f -exec sed -i 's% src="/mywar/% src="/clientwar/%g' {} +
find . -type f -exec sed -i "s% url('/mywar/% url('/clientwar/%g" {} +
find . -type f -exec sed -i 's% url("/mywar/% url("/clientwar/%g' {} +
find . -type f -exec sed -i 's% url(/mywar/% url(/clientwar/%g' {} +
find . -type f -exec sed -i 's% url="/mywar/% url="/clientwar/%g' {} +
find . -type f -exec sed -i 's% value="/mywar/% value="/clientwar/%g' {} +
find . -type f -exec sed -i 's% webapps/mywar/core% webapps/clientwar/core%g' {} +
find . -type f -exec sed -i 's% window.open("/mywar/"% window.open("/clientwar/"%g' {} +
find . -type f -exec sed -i 's%Disallow: /mywar/%Disallow: /clientwar/%g' {} +
find . -type f -exec sed -i 's%http://localhost:8080/mywar/%http://localhost:8080/clientwar/%g' {} +
find . -type f -exec sed -i 's%http://localhost:9200/mywar/%http://localhost:9200/clientwar/%g' {} +

However, though it looks very readable, it's not compact, and many commands really look like others.

And, worst of all, it's quite slow: more or less 1 hour for the whole set of commands to run on my 2-years old laptop...

Any advice on how to make this:

more performant?
(optionally) better written (if it stays easy to read and understand)?

There's a gross inefficiency in this script: not only are we opening each file n times (where n is the number of lines), we're also running n find instances.

Instead, consider running find just once, and using a single sed command to perform the substitutions.  The easiest way to do that is to make it an executable script (with a #! line):

#!/bin/sed -f

s% '/mywar/% '/clientwar/%g
s%,'/mywar/%,'/clientwar/%g
s% "/mywar/% "/clientwar/%g
s% file="/mywar/% file="/clientwar/%g
s%<TAB>href="/mywar/%<TAB>href="/clientwar/%g
s% href="/mywar/% href="/clientwar/%g
s% name="/mywar/% name="/clientwar/%g
s% relativePath="/mywar/% relativePath="/clientwar/%g
s% requestUrl.indexOf("/mywar/")% requestUrl.indexOf("/clientwar/")%g
s% src='/mywar/% src='/clientwar/%g
s%<TAB>src="/mywar/%<TAB>src="/clientwar/%g
s% src="/mywar/% src="/clientwar/%g
s% url('/mywar/% url('/clientwar/%g
s% url("/mywar/% url("/clientwar/%g
s% url(/mywar/% url(/clientwar/%g
s% url="/mywar/% url="/clientwar/%g
s% value="/mywar/% value="/clientwar/%g
s% webapps/mywar/core% webapps/clientwar/core%g
s% window.open("/mywar/"% window.open("/clientwar/"%g
s%Disallow: /mywar/%Disallow: /clientwar/%g
s%http://localhost:8080/mywar/%http://localhost:8080/clientwar/%g
s%http://localhost:9200/mywar/%http://localhost:9200/clientwar/%g

We can now run that for every file:

find . -type f -exec scriptname.sed -i {} +

Or (with GNU Find and Parallel), we can use as many processor cores as we have available:

find . -type f -print0 | parallel -0 -X scriptname.sed -i

We can combine some of the search patterns.  For example, consider these three substitutions:

s% '/mywar/% '/clientwar/%g
s%,'/mywar/%,'/clientwar/%g
s% "/mywar/% "/clientwar/%g

They can be replaced with a single substitution, using \1 to retain the part we want to keep unchanged:

s%\([ ,]'\| "\)/mywar/%\1/clientwar/%g

This can be extended to almost all the substitutions (excepting only the ones that need to match text beyond the end of mywar/).

If all those backslashes are irritating, consider using (GNU) grep's -r option to enable extended regular expressions (but then you'll need to escape the literal ( that are to be matched, so it might not be worth it).


Optimizing code for UVAJ 573 The Snail I'm getting the right results for the code for the sample outputs, but the OJ is giving a TLE (3 seconds max).

The questions is here.

int main()
{
    double h,u,d,f;
    while(scanf("%lf%lf%lf%lf",&h,&u,&d,&f)!=EOF)
    {
        //cin>>h;
       // if(h==0)
          //  break;
        //cin>>u>>d>>f;
        double fu=.01*f*u;
        double used_fu=0;
        int day=1;
        double crossed=0;
        int success=0;
        while(1)
        {
            crossed+=(u-used_fu);
            if(crossed>h)
            {
                success++;break;
            }
            crossed-=d;
            if(crossed<0)
                break;
            used_fu+=fu;
            day++;
        }
        if(success==0)
            cout<<"failure";
        else
            cout<<"success";
        cout<<" on day "<<day<<"\n";
    }
    return 0;
}

So first things first, your code looks terrible.

Use real names for your variables that are understandable without any further reading, e.g. instead of fu you could use fatique.
Your variable success is a boolean so make it one.
You should introduce a factor for the fatique rather than subtracting it. That would make the code simpler. Also your failure is most likely because the snail takes so much time to slide back down. So rather than checking for snailHeight > 0 check for heightSlid > fatique * heightClimbed

size_t numDays = 0;
double snailHeight = 0.0;
double fatique = 1.0;
bool fail = false;
while (true) {
    numDays++;
    snailHeight += fatique * heightClimbed;
    fatique *= 0.9;
    if (heightSlid > fatique * heightClimbed) {
        fail = true;
        break;
    } else if (snailHeight > heightWell) {
        break;
    }

    snailHeight -= heightSlid;
}

if (fail) {
    std::cout << "failure\n";
} else {
    std::cout << "success on day " << numDays << "\n";
}