texts: Pseudo-random generation able to regenerate backwards

texts:
Using the accepted answer from this question, I made a random number generator which can regenerate previous numbers in order.

Ideone version

byte[] Encrypt(byte[] ClearData, byte[] Key)
{
   MemoryStream ms = new MemoryStream();

    Rijndael alg = Rijndael.Create();
    alg.KeySize = 128;
    alg.BlockSize = 128;
    alg.Mode = CipherMode.ECB;

    alg.Key = Key;

    CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);

    cs.Write(ClearData, 0, ClearData.Length);

    cs.Close();

    byte[] encryptedData = ms.ToArray();

    return encryptedData;
}

int RandomValue(int Max)
{
    byte[] FirstHalf = BitConverter.GetBytes(Key);
    byte[] SecondHalf = BitConverter.GetBytes(Key);

    byte[] KeyBytes = new Byte[FirstHalf.Length + SecondHalf.Length];
    FirstHalf.CopyTo(KeyBytes, 0);
    SecondHalf.CopyTo(KeyBytes, FirstHalf.Length);

    byte[] RandValue = Encrypt(new byte[0], KeyBytes);

    int Rand = Math.Abs(BitConverter.ToInt32(RandValue, 0));

    return Rand % Max;
}

int NextValue(int Max)
{
    ++Key;
    return RandomValue(Max);

}

int PreviousValue(int Max)
{
    --Key;
    return RandomValue(Max);

}

static void Main()
{
    byte[] buffer = new byte[sizeof(Int64)];
    Rand.NextBytes(buffer);
    Key = BitConverter.ToInt64(buffer, 0);

    for(int i = 0 ; i < 4 ; ++i)
    {
        Console.WriteLine(NextValue(10));
    }

    Console.WriteLine();

    for(int i = 0 ; i < 4 ; ++i)
    {
        Console.WriteLine(PreviousValue(10));
    }
}

Sample output:

Value 0: 8
Value 1: 1
Value 2: 0
Value 3: 8

Value 2: 0
Value 1: 1
Value 0: 8
Value -1: 7

The desired output from the asker of the stackoverflow question could be obtained by incrementing Key after getting a random value in the NextValue function but for my use this output is more appropriate.

It won't generate backwards properly if the Max changes. It doesn't need to be able to do this especially since Max in unlikely to change between calls, but seeing as how the whole purpose of this is to generate forward and backwards accurately, it seems like something should change.

I'm using Encrypt blindly since I don't understand how it works or even what the ClearData is used for.

What can be changed to improve it and make it more understandable?


texts: A custom Java collection which doesn't support nulls

texts:
I am making a GWT application and have to prevent client code from using null values in collections.
I found an answer but GWT doesn't support Queue and its implementations as the GWT documentation says.

So, I had to make my own implementation.

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

/**
 * This implementation of {@link ArrayList} does not allow to add null values
 *
 * @author Maxim Dmitriev
 *
 * @param <E>
 */
public class NonNullArrayList<E> extends ArrayList<E> implements Serializable {

    private static final String NULL_VALUES_ARE_PROHIBITED = "Null values are prohibited";
    private static final String CLONING_IS_UNSUPPORTED = "Cloning is unsupported. Please support if necessary";

    public NonNullArrayList() {
        // For serialization. super() is called automatically.
    }

    public NonNullArrayList(int initialCapacity) {
        super(initialCapacity);
    }

    public NonNullArrayList(Collection<? extends E> c) {
    super(c);
        if (contains(null)) {
            throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED);
        }
    }

    /**
     *
     */
    private static final long serialVersionUID = 7716772103636691126L;

    public boolean add(E e) {
        if (e == null) {
            throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED);
        }
        return super.add(e);
    };

    @Override
    public boolean addAll(Collection<? extends E> c) {
        if (c.contains(null)) {
            throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED);
        }
        return super.addAll(c);
    }

    public void add(int index, E element) {
        if (element == null) {
            throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED);
        }
        super.add(index, element);
    };

    @Override
    public boolean addAll(int index, Collection<? extends E> c) {
        if (c.contains(null)) {
            throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED);
        }
        return super.addAll(index, c);
    }

    public E set(int index, E element) {
        if (element == null) {
            throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED);
        }
        return super.set(index, element);
    };

    @Override
    public Object clone() {
        throw new Error(CLONING_IS_UNSUPPORTED);
    }

}

Besides I want to prevent code from using the clone() method because I just don't need it.

Is the implementation good or not?


texts: keep track of friends and number of days not spoken to, dynamic memory location

texts:
Write a program that lets users keep track of the last time they talked to each of their friends. Users should be able to add new friends (as many as they want!) and store the number of days ago that they last talked to each friend. Let users update this value (but don't let them put in bogus numbers like negative values). Make it possible to display the list sorted by the names of the friends of by how recently it was since they talked to each friend.

This is the code I have written so far. I'm having problems with the array size not growing as it should do. Also I'm unsure about how to go about list the names with numbers of days out.

#include <iostream>
#include <string>

using namespace std;

int *growArray (int * friends, int * size)
{
    *size *= 2;
    int *new_friends = new int[*size];
    for (int i=0; i < *size; i++) {
        new_friends[i] = friends[i];
    }
    delete [] friends;
    return new_friends;
}

string *growArray2 (string * name1, int * size)
{
    *size *= 2;
    string *new_name2 = new string[*size];
    for (int i=0; i < *size; i++) {
        new_name2[i] = name1[i];
    }
    delete [] name1;
    return new_name2;
}

void printArray (string *name1, int *friends,int size, int element_set)
{
    cout << "the total size of the array is: " << size << endl;
    cout << "Values in the array: " << endl;
    for (int i = 0; i < element_set; ++i)
    {
        cout << name1[i] << "[" << i << "] = " << friends[i] << " days since you last spoke to them" << endl;
    }
}

int main()
{
    string exit = "X";
    string name;
    int noDays;
    int next_element = 0;
    int size = 4;
    int *friends = new int[size];
    string *name1 = new string [size];
        cout << "Please enter your friends name" << endl;
        cin >> name;
        cout << "Please enter no of days you last spoke to them" << endl;
        cin >> noDays;
    while(true) {
        if (size == next_element+1) {
            friends = growArray(friends, &size);
            name1 = growArray2(name1, &size);
        }
        friends[next_element] = noDays;
        name1[next_element] = name;
        next_element++;
        printArray(name1, friends, size , next_element);
        cout << "Please enter your friends name or X to exit" << endl;
        cin >> name;
        if (name == exit) {
            break;
        }
        cout << "Please enter no of days you last spoke to them" << endl;
        cin >> noDays;

        }
        delete name1;
        return 0;
}


texts: all the ways to fit some pegs into given holes

texts:
Suppose you have a list of the diameters of some circular holes, and a list of the diameters of some cylindrical pegs. Now the problem is finding all the ways you can fit the pegs in the holes, where the order in which you put them in doesn't matter, and it's OK to put a peg in a hole that's too large.

I've written the code below to solve the problem, and it works as intended. The innermost tuples of the answer matches a peg to a hole, i.e. (4, 7) means put d4 peg in d7 hole, and these tuples make up a set that represents one way of putting all the pegs in.

I'm not completely happy with the solution. It's not... snappy enough, and it feels overly complicated. Is there a smarter way to go about it?

def fit(pegs, holes):
    for h in holes:
        for p in pegs:
            if p <= h:
                pegs_left = [x for x in pegs if x != p]
                if pegs_left:
                    free_holes = [x for x in holes if x != h]
                    for rest in fit(pegs_left, free_holes):
                        yield frozenset(((p, h),)) | rest
                else:
                    yield frozenset(((p, h),))

def fitted(pegs, holes):
    return sorted(sorted(x) for x in set(fit(pegs, holes)))

pegs = [2, 4, 7]
holes = [1, 3, 4, 6, 9]

print fitted(pegs, holes)
# [[(2, 3), (4, 4), (7, 9)],
#  [(2, 3), (4, 6), (7, 9)],
#  [(2, 4), (4, 6), (7, 9)],
#  [(2, 6), (4, 4), (7, 9)]]


texts:
I have 2 nested resources in one of my Rails apps and the way the index is handled by the inner resources bothers me somewhat:

def index
    @program = Program.approved.find(params[:program_id]) if params[:program_id]
    if params[:tags]
      tags = params[:tags].split(" ")
      if @program
        @sites = Site.where(:program_id => @program.id).tagged_with(tags).page(params[:page])
      else
        @sites = Site.joins(:program => :user).tagged_with(tags).page(params[:page])
      end
    else
      if @program
        @sites = Site.where(:program_id => @program.id).page(params[:page])
      else
        @sites = Site.joins(:program => :user).page(params[:page])
      end
    end

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @sites }
    end
end

The complexity is caused because I want my Site resource to be accessible both through it's Program or directly. The results are also optionally filtered based on tags if they are included in the params.

The joins are required because if a site belongs to a user then I display Edit/Delete options.

It just doesn't feel like good Ruby code. So any refactoring tips would be helpful.


texts:
I somehow acquired the idea that I should reduce the number of trips to the database as much as possible and so I use a lot of very long queries.

For example, I had a function that does this:

$shelf = get_shelves($shop_id)
foreach($shelf)
{
    $weight = get_weight($shelf);
}

Everytime a user "view shop" it will list all the shelves, and when I see the loop, I thought I should "optimise" this, so that I only go to the database once. But I ended up with a long query:

$shelf = "SELECT * FROM shelf WHERE shop_id=?";
$weight = "SELECT tray.shelf_id, SUM(egg.weight) AS total_weight FROM tray LEFT JOIN egg WHERE egg.tray_id=tray.tray_id GROUP BY shelf_id";
$query = "SELECT * FROM ($shelf) AS shelf LEFT JOIN ($weight) AS weight ON shelf.shelf_id=weight.shelf_id";

With this, I didn't have to get_weight() anymore.

Is this "optimisation" at all, is it acceptable? Is there a rule of thumb so that programmers and DBA can be happy at the same time?


texts: Monitoring the recursive growth of a zombie rabbit population

texts:
Breeding like rabbits

  Write a function answer(str_S) which, given the base-10 string
  representation of an integer \$S\$, returns the largest n such that \$R(n) = S\$. Return the answer as a string in base-10 representation. If there
  is no such n, return "None". S will be a positive integer no greater
  than \$10^{25}\$

  where \$R(n)\$ is the number of zombits at time \$n\$:

  $$\begin{align*}
R(0) &= 1 \\
R(1) &= 1 \\
R(2) &= 2 \\
R(2n) &= R(n) + R(n+1) + n \quad\text{(for $n > 1$)} \\
R(2n+1) &= R(n-1) + R(n) + 1 \quad\text{(for $n \geq 1$}) \end{align*}$$

Test cases

>>> answer('7')
'4'
>>> answer('100')
None

My program is correct but it is not scalable since the range of \$S\$ can be a very large number like \$10^{25}\$.

Could anyone help me with some suggestions on improving the code further so that it can cover any input case?

def answer(str_S):

    d = {0: 1, 1: 1, 2: 2}
    str_S = int(str_S)
    i = 1
    while True:

        if i > 1:
            d[i*2] = d[i] + d[i+1] + i
            if d[i*2] == str_S:
                return i*2
            elif d[i*2] > str_S:
                return None

        if i>=1:
            d[i*2+1] = d[i-1] + d[i] + 1
            if d[i*2+1] == str_S:
                return i*2 + 1
            elif d[i*2+1] > str_S:
                return None

        i += 1

print answer('7')


texts: Method to return a string of max length (in bytes vs. characters)

texts:
In my (c#) code, I need to generate a string (from a longer string) which when UTF-8 encoded, is no longer than a given max length (in bytes).

    public static string OfMaxBytes(this string str, int maxByteLength)
    {
        return str.Aggregate("", (s, c) =>
        {
            if (Encoding.UTF8.GetByteCount(s + c) <= maxByteLength)
            {
                s += c;
            }
            return s;
        });
    }

Usage looks like:

    var shortName = longName.OfMaxBytes(32);

Does this look like a correct and sensible implementation?


texts: How can I optimize this array.each in ruby?

texts:
I'm trying to optimize this bit of code and I thought I'd throw it out here to see if anyone has any ideas. I've been testing the performance using Benchmark.measure {...} and wrapping the entire function.

Yes, the item has a date that is a Ruby Date

  puts Benchmark.measure {
    grouped_items
  }

  def grouped_items
    unless @grouped
      @grouped = {}
      @items.each do |item|
        key = item.date
        if @grouped.has_key?(key)
          @grouped[key] << item
        else
          @grouped[key] = [item]
        end
      end
    end
    @grouped
  end

Thanks for any insight you care to share.

Edit #1: My first optimization. I was aiming for a slightly more succinct function and gained a .2 seconds reduction in time to process 100_000 items.

  def grouped_items
    unless @grouped
      @grouped = Hash.new { |h, k| h[k] = [] }
      @items.map {|item| @grouped[item.date] << item }
    end
    @grouped
  end

Edit #2: My second iteration with more or less the same performance profile but with much less code.

def grouped_items
  @grouped ||= @items.group_by { |item| item.date }
end

Edit #3: An alternative way to do the same thing above.

def grouped_items
  @grouped ||= @items.group_by &:date
end


texts:
This is a multiple choice game. It has a web page where you enter a question, which can have multiple answers along with multiple options.

Can anyone recommend any improvements for my code?

//correct & options are both arrays. These arrays are being passed through an AJAX call
function addQuestion($topicID, $difficulty, $isMultiple, $quest,$correct, $options){
    global $numRecords,$dbConnection,$stmt;
    connect();

    //Insert into question table & recieve the question ID for use in the answers insert stmt
     $sql = "INSERT INTO question (topic_ID,difficulty,isMultiple, question)
            VALUES($topicID,$difficulty,$isMultiple,'$quest');";
    try{
        $stmt=$dbConnection->query($sql);
            $qID = $dbConnection->lastInsertId();

        if(!$stmt)
            die("error1".$dbConnection->errorInfo());
        $stmt = "";

        for($i = 0; $i < sizeof($correct); $i++):
            $stmt .= "INSERT INTO answer (question_ID, data, isCorrect)
                VALUES($qID,'".$correct[$i]."',1);";
        endfor;

        for($z = 0; $z < sizeof($options); $z++):
            $stmt .= "INSERT INTO answer (question_ID, data, isCorrect)
                VALUES($qID,'".$options[$z]."',0);";
        endfor;
        $dd = $dbConnection->query($stmt);

        if(!$dbConnection)
            die("error2".$dbConnection->errorInfo());

    }catch (Exception $e){
        //Rollback if fails
        $dbConnection->rollback();
        return "Error rolling back: ". $e;
    }
}


texts: "Acro Words" - Creating Acronyms of a Text that are Words

texts:
I wrote a program that given an input string returns a list of tuples in which each element of the tuple is a word given by dropping some number of characters of the original string, preserving order.

For example:

'valley' -> [('alley',), ('valley',)]
'friction' -> [('fiction',), ('friction',), ('ricin',)]
'university' -> [('unvest',), ('nesty',), ('unsty',), ...]
'freetrade' -> [..., ('erade',), ..., ('free', 'tade'), ..., ('free', 'trade'), ...('feer',), ...]

The algorithm I've written works as follows

Find the powerset of the characters in the string.  This gives us a set of lists of characters, conceptually given by "dropping" some number of characters of the input string, preserving order.  powerset('abc') = {(),('a',),('a', 'b'),('a', 'b', 'c'),('a', 'c'),('b',),('b', 'c'),('c',)}
Next, for each element of the powerset, we perform a "powersplit" in which we find every possible split (or, inversely, concatenation).  powerset(('a', 'b', 'c')) = {('a', 'b', 'c'), ('a', 'bc'), ('ab', 'c'), ('abc',)}
Finally, for each tuple produced by the powersplit, we check if the contents of the tuple are in our dictionary.  contents_in_dictionary(dictionary, ('free', 'trade')) = True

The following is my code

from functools import reduce
from itertools import chain, combinations, islice, zip_longest

def powerset(data):
    return {z for z in chain.from_iterable((x for x in combinations(data, r)) for r in range(len(data)+1))}

def slices(data, indices):
    return [[x for x in islice(data, *list(y))] for y in zip_longest(chain([0], indices), chain(indices, [len(data)]))]

def powersplit(data):
    return {tuple([''.join(x) for x in slices(data, indices)]) for indices in powerset(range(1, len(data)))}

def get_dictionary(min_length):
    return {line.rstrip('\n').lower() for line in open('/usr/share/dict/words') if len(line.rstrip('\n')) >= min_length}

def contents_in_dictionary(dictionary, in_string):
    return all([y in dictionary for y in in_string])

def acro_word(in_string):
    candidates = reduce(set.union, [powersplit(partial) for partial in powerset(in_string)])
    dictionary = get_dictionary(4)
    return [x for x in candidates if contents_in_dictionary(dictionary, x)]

My questions are:

Am I missing any obvious / not complex improvements to my algorithm?
Am I missing any obvious pythonic data structures / functions that I can take advantage of?
How can I

Make this generally faster. As you add characters to the input string, it takes exponentially (I believe) longer to return.
Turn everything into a generator and stream results to the client.


texts: Approximate String Matching Interview Question

texts:
I was working on the challenge Save Humanity from Interviewstreet for a while then gave up, solved a few other challenges, and have come back to it again.

The code below generates the correct answers but the time complexity  O(text * pattern) is not sufficient for the auto-grader. Could anyone perhaps give me a hint or a pointer on how to improve my algorithm?

final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
final StringBuilder builder = new StringBuilder();
final int number_trials = Integer.valueOf(input.readLine());

for(int trial = 0; trial < number_trials; trial++)
{
    final int allowed_mismatches = 1;
    final char[] text = input.readLine().toCharArray();
    final char[] pattern = input.readLine().toCharArray();
    input.readLine();

    for(int text_index = 0; text_index < text.length - pattern.length + 1; text_index++)
    {
        int pattern_index = 0;
        int missed = 0;

        while(pattern_index < pattern.length && missed <= allowed_mismatches)
        {
            if(text[text_index + pattern_index] != pattern[pattern_index])
            {
                missed++;
            }

            pattern_index++;
        }

        if(missed <= allowed_mismatches)
        {
            builder.append(text_index);
            builder.append(" ");
        }
    }

    if(builder.length() > 0 && builder.charAt(builder.length() - 1) == ' ')
    {
        builder.deleteCharAt(builder.length() - 1);
    }

    if(trial + 1 < number_trials)
    {
        builder.append("\n");
    }
}

System.out.println(builder.toString());


texts:
I implemented a class for relationships with the user (deletion, name change, check for existence), I created this class to remove extra logic from the activity class. Could you talk about how my code can be improved?

class UserActionManager @Inject constructor(private val repository : BaseAppRepository,
                                            private val sharedPreferences : JsonSharedPreferences) {

    fun editUserName(user: User,newUserName: String) {
        Completable.fromAction {
            val userObjective:Objective? = sharedPreferences.loadObject(GlobalConstants.OBJECTIVE_SAVE_KEY + user.userName,Objective::class.java)
            val userProfile:Profile? = sharedPreferences.loadObject(GlobalConstants.PROFILE_SAVE_KEY + user.userName,Profile::class.java)
            sharedPreferences.saveObject<Objective>(GlobalConstants.OBJECTIVE_SAVE_KEY + newUserName, userObjective)
            sharedPreferences.saveObject<Profile>(GlobalConstants.PROFILE_SAVE_KEY + newUserName, userProfile)
            repository.updateUserName(user.userName, newUserName)
            user.userName = newUserName
            repository.updateUser(user)
        }.subscribeOn(Schedulers.io()).subscribe()
    }

    fun deleteUser(user: User) {
        Completable.fromAction { repository.deleteUser(user) }.subscribeOn(Schedulers.io()).subscribe()
        sharedPreferences.saveObject<Objective>(GlobalConstants.OBJECTIVE_SAVE_KEY + user.userName, null)
        sharedPreferences.saveObject<Profile>(GlobalConstants.PROFILE_SAVE_KEY + user.userName, null)
    }

    fun isEmptyUser(userName: String): Single<Boolean> {
        return repository.getUserByUserName(userName)
                .subscribeOn(Schedulers.io())
                .isEmpty
    }
}


texts: Converting float from arbitrary base to arbitrary base

texts:
I needed to write a small program to convert floats from any base to any other base. The thing is, it got big. I know there are other ways to implement the conversions (such as doing subtractions instead of divisions), but isn't there a more simple way to do the whole process? I feel like I'm missing something. Any optimization tips are welcome as well.

import string
symbols = string.digits + string.uppercase

def _int_from_base(number, original_base):

    return int(number, original_base)

def _int_to_base(number, new_base):

    # Uses "the division method"
    sign = -1 if number < 0 else 1
    number *= sign
    ans = ''
    while number:
        ans += symbols[number % new_base]
        number //= new_base
    if sign == -1:
        ans += '-'
    return ans[::-1]

def _fractional_from_base(number, original_base):

    # The value of a symbol at position i after the decimal point is, by
    # definition, the value of that symbol * b^-i
    ans = 0
    for i in xrange(1, len(number)+1):
        ans += symbols.index(number[i-1]) * original_base**-i
    return ans

def _fractional_to_base(number, new_base, precision=5):

    # I don't know what this method is called
    ans = ''
    for i in xrange(precision):
        tmp = number * new_base
        itmp = int(tmp)
        ans += str(symbols[itmp])
        number = tmp - itmp
    return ans

def convert(number, original_base, new_base, precision=None):
    """Converts any number from any base to any other base (2 <= base <= 36).

    number should be a string representing a float in any base, e.g. '1.23'.

    original_base, new_base should be integers representing the desired bases.

    precision should be an integer representing how many digits after the
    decimal point will be calculated on the conversion. Default is the same
    number as the number of digits after the decimal point on number.
    """

    try:
        integer_part, fractional_part = number.split('.')
        precision = len(fractional_part) if precision is None else precision
        integer_part = _int_to_base(
            _int_from_base(integer_part, original_base),
            new_base
        )
        fractional_part = _fractional_to_base(
            _fractional_from_base(fractional_part, original_base),
            new_base,
            precision
        )
        return integer_part+'.'+fractional_part
    except ValueError:      # number was a str representing an int not a float
        return _int_to_base(_int_from_base(number, original_base), new_base)

I didn't test it thoroughly but it seems to work. A few test cases:

>>> a = convert('632.6442', 10, 2);a # Loss of info. is expected
'1001111000.1010'
>>> convert(a, 2, 10)
'632.6250'

>>> b = convert('222.0', 3, 16);b
'1A.0'
>>> convert(b, 16, 3)
'222.0'


texts:
I have the following code to select an image using Selenium, only now I have added an errorRecovery.  Is there is a better way to right the code in the catch?

    public static void selectHeader() {
    try {
        WebDriverWait wait = new WebDriverWait(driver, 20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By
                .xpath("//*[contains(@id, 'picture-und-0-select')]")));
        driver.findElement(
                By.xpath("//a[contains(@id, 'picture-und-0-select')]"))
                .click();
        driver.switchTo().frame("mediaBrowser");
        wait.until(ExpectedConditions.presenceOfElementLocated(By
                .linkText("LIBRARY")));
        driver.findElement(By.linkText("LIBRARY")).click();
        driver.findElement(By.tagName("img")).click();
        driver.findElement(By.linkText("Submit")).click();
        driver.switchTo().defaultContent();
    } catch (UnhandledAlertException alert) {
        errorRecovery error = _TestSuite.errorRecovery;
        if (error.getCount() == 0) {
            error.addCount();
            selectHeader();
        } else {
            error.resetCount();
            throw new UnhandledAlertException(alert.toString());
        }
    }
}


texts: Turning a data class with too much functionality into a POD - SysLat Cleanup #2

texts:
This is a follow up question to Tuning the data class for the SysLat System Latency Testing hardware for gaming computers - SysLat Cleanup #1.
Since the program is too large and complex to put into one question I have also posted a question about the USB controller and the dialog that controls the entire program.
Here's my open source project: https://github.com/Skewjo/SysLat_Software
Today I'm attempting to clean up my "SysLatData" class, and the effort has gone very well so far, and I'm looking to pretty well finalize it now if possible.
Header file here: https://github.com/Skewjo/SysLat_Software/blob/master/SysLatData.h
Implementation here: https://github.com/Skewjo/SysLat_Software/blob/master/SysLatData.cpp
Definition and use here: https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.cpp
#pragma once

//Without the following 2 macros the date library spits out 50+ errors about min and max being undefined.
#undef max
#undef min
#include <date/date.h> //Should likely move this to StdAfx.h, but I'm not sure if I can because of the macro issue.
using namespace date;
using namespace std::chrono;

constexpr size_t MOVING_AVERAGE = 100;
constexpr size_t EVR_MIN = 3;
constexpr size_t EVR_MAX = 100;

struct SYSLAT_DATA {
    struct Statistics {
        std::size_t counter = 0;
        int total = 0;
        double average = 0.0;
        int median = 0;
        int max = 0;
        int min = 0;
        double approxMovingAvg = 0.0;
    };

    vector<int>         m_allResults;
    vector<string>      m_v_strRTSSWindow;
    vector<string>      m_v_strActiveWindow;

    Statistics          m_statistics;
    Statistics          m_statisticsEVR;
};

class CSysLatData
{
protected:
    SYSLAT_DATA         m_sld;
    Json::Value         m_JSONsld; //this is basically a second copy of the data... will probably eat up a BOATLOAD of memory for no reason. There's got to be a better way...
    int                 systemLatency = 0;

    std::mutex          m_Mutex;
    string              m_strError = "";

    const system_clock::time_point  m_startTime = system_clock::now();
    system_clock::time_point        m_endTime;
    duration<int>                   m_testDuration;

public:
    const SYSLAT_DATA&  GetData() {return m_sld;}
    const Json::Value&  GetJSONData() { return m_JSONsld; }
    const int&          GetSystemLatency() { return systemLatency; }

    double              CalculateMovingAverage(double currentAvg, int input);
    void                SetEndTime();
    void                UpdateSLD(unsigned int loopCounter, const string& sysLatResults, string RTSSWindow, string activeWindow, DWORD fgPID, DWORD rtssPID);
    void                AppendError(const string& error);

    void                CreateJSONSLD(); // I think I may need to make this and the following functions return bools or ints based on whether or not they failed.
    void                ExportData(int testNumber, string path = ".\\SysLat_Logs", int totalLogs = 10000);

    string              m_RTSSVersion = "0.0.0";
    string              m_targetApp = "Unknown";
    string              m_boxAnchor = "Unknown";

    bool                m_bDataExported = false;
    bool                m_bDataUploaded = false;
};


texts: Add items to a list, or update the quantity if already in the list

texts:
I have several lists that contain Part objects with a partNumber and quantity. When the user selects to add a part to an existing list, I want to check to see if the part is already on the list. If it is, I simply want to add the new quantity to the existing quantity, and if the part is not already on the list, I want to add the entire Part object to the list. This solution works, but it feels verbose.

My question is: Can the forEach and if(!partExistsOnTransfer) code be simplified?

var transfer = this.transferRequests[index],
    transferList = $filter("filter")(
        $this.openTransfers,
        { id: id },
        true
    ),
    partToAdd = new Part(
        $this.currentPart.partNumber, // partNumber
        transfer.quantity // quantity
    ),
    partExistsOnTransfer = false;

transferList[0].parts.forEach(function (part, indx) {
    if (part.partNumber === partToAdd.partNumber) {
        // if part already exists, add to existing quantity, do not push new part onto list
        partExistsOnTransfer = true;
        part.quantity = (Number(part.quantity) + Number(partToAdd.quantity)).toString();
        return false;
    }
});
if (!partExistsOnTransfer) {
    // if part does not exist, push new part onto list
    transferList[0].parts.push(partToAdd);
}


texts:
We are given a string which is compressed and we have to decompress it.

  (a(bc2)d2)$

"$" indicates end of string.

  (abcbcd2)$

  abcbcdabcbcd  (This is the final uncompressed string.)

My code:

import java.util.*;

class decompress
{
    public static void main(String[] ar)
    {
        int end = 0, st = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print(">> ");
        String s = sc.next();
        while(s.indexOf('(') != -1)
        {
        for(int i = 0; i < s.length(); i++)
        {
            char c = s.charAt(i);
            if(c == '(')
                st = i;
            else if(c == ')')
            {
                end = i;
                String t = s.substring(st+1,end);
                int n = t.charAt(t.length()-1) - '0';
                t = t.substring(0,t.length() - 1);
                String q = "";
                for(int j = 0; j < n; j++)
                    q += t;
                String m = "";
                if(st != 0)
                    m = s.substring(0,st);
                s = m + q + s.substring(i+1);
                break;
            }
        }
        }
        System.out.println(s);
     }
}

Is there a more elegant way to make this program ?


texts:
Here is my code;

import socket
def read_line(sock):
    "read a line from a socket"
    chars = []
    while True:
        a = sock.recv(1)
        chars.append(a)
        if a == "\n" or a == "":
            return "".join(chars)

def read_headers(sock):
    "read HTTP headers from an internet socket"
    lines = []
    while True:
        line = read_line(sock)
        if line == "\n" or line == "\r\n" or line == "":
            return "".join(lines)
        lines.append(line)

def parse_headers(headerstr):
    "Return a dict, corresponding each HTTP header"
    headers = {}
    for line in headerstr.splitlines():
        k, _, v = line.partition(":")
        headers[k] = v.strip()
    return headers

http_request = """GET / HTTP/1.1
Host: {}

"""

site = "www.google.com.tr"
conn = socket.create_connection((site,80))
conn.sendall(http_request.format(site))

headersstr = read_headers(conn)
headersdict = parse_headers(headersstr)

if "Transfer-Encoding" in headersdict and headersdict["Transfer-Encoding"] == "chunked":
    content = ""
else:
    content = conn.recv(headersdict["Content-Length"])

print content
conn.close()

Can you please comment on how I am using sockets. Is it correct practive to read characters one by one from socket as I did in read_line function? Are there any other mistakes I am doing?


texts: Calculate the sum of all primes less than 2,000,000 in Swift

texts:
This is a Swift program I wrote to calculate the sum of primes below 2 million, but it is tediously slow.

I am curious about what makes it so slow. My theory is that copying the filtered array is the heavy operation.  Any other ideas on how to speed it up?

func initArray (p:Array<UInt32>)  -> Array<UInt32> {

    var arr = Array<UInt32>()
    arr.reserveCapacity(2000000)

    func isDiv(p:Array<UInt32>, val:UInt32) ->Bool {

        for i in p {

            if val % i == 0 {
                return true
            }
        }

        return false
    }

    for i:UInt32 in 2...2000000 {

        if !isDiv(p, val: i) {
            arr.append(i)
        }

    }

    return arr

}

var primes:Array<UInt32> = [2,3,5,7]

primes.reserveCapacity(20000)

var numbers = initArray(primes)

while numbers.count != 0 {
    numbers = numbers.filter( { return ($0 % primes[primes.count - 1] != 0 )} )

    if !numbers.isEmpty {
        primes.append(numbers[0])
    }

}

let result = primes.reduce(0, combine: +)

print (result)


texts: DO.dom: Creating large DOM structures in Javascript

texts:
I have the library that I have found to be very useful when creating dynamic content rich web applications. I call it DO.js. It allows me to create entire DOM structures inside of Javascript in a similar manner that HTML markup should look. Additionally, it does it all without writing any HTML strings. It uses a hierarchy of embedded functions and objects to create the DOM structure. Please see my site below for examples.

My question is, is this a good way of doing this? I can and I have (the website below is created in this fashion) created whole websites using this method. I made it so that I could easily load and display large amounts of data pulled via ajax and where each bit of data will have events and variables attached. Of course, this is hard and tacky to do using normal HTML.

I kinda created documentation for it. However, I am not very good with documentation(or writing in general.)

What should/could be done better? What would be the best programming practices in this case?  Anykind of critique would be awesome.

Thanks

http://hurdevan.com/#!Home/Projects/DO.js

Please note that the website does not work at all in IE due to a Hashbang.js bug. And, I don't care about IE.

Code Examples:

Simple Example

with(DO.dom)
   {
   div({parentElement:document.body},
       span(b('Hello World!'))
        );
   }

An example using events and such:

var win = {};
with(DO.dom)
    {
    win.root = div({parentElement:document.body,style:'border:1px solid black;width:200px;height:200px;position:fixed;'},
        win.bar = div({style:'height:20px;text-align:center;background-color:#333333;color:white;cursor:pointer;',
            onmousedown:DO.Func(true,function(eve,winobj)
                {
                window.onmousemove = winobj.bar.onmousemove;
                window.onmouseup = winobj.bar.onmouseup;
                winobj.offsetX = winobj.root.offsetLeft - eve.x;
                winobj.offsetY = winobj.root.offsetTop - eve.y;
                winobj.activeDrag = true;
                },win),
            onmouseup:DO.Func(true,function(eve,winobj)
                {
                window.onmousemove = false;
                window.onmouseup = false;
                winobj.activeDrag = false;
                },win),
            onmousemove:DO.Func(true,function(eve,winobj)
                {
                if(!winobj.activeDrag)return false;
                winobj.root.style.position="fixed";
                winobj.root.style.left = (eve.x + winobj.offsetX)+"px";
                winobj.root.style.top = (eve.y + winobj.offsetY)+"px";
                },win)
            },'Move Window'),

        win.body = div(
            div(b('First Name:'),
                win.firstName = input({type:'text'})
                ),
            div(b('Last Name:'),
                win.lastName = input({type:'text'})
                ),
            div(b('Email:'),
                win.email = input({type:'text'})
                ),
                input({type:'submit',onclick:DO.Func(function(winobj)
                {
                alert("First Name:"+winobj.firstName.value +"\n"+"Last Name:"+winobj.lastName.value +"\n"+"Email:"+winobj.email.value +"\n");
                },win)}),
            "This window was created with DO.dom"
            )
        );

    }

Another example that allows the DOM structure to be child/parent aware.

with(DO.dom)
   {
var foo =div({parentElement:document.body},
       div({nid:'inputElements';},
        input({nid:'firstName'}),
        input({nid:'lastName'}),
        input({nid:'email'})
        )
    );
   }

foo.inputElements.firstName.value = 'Hello';
foo.inputElements.lastName.value = 'Word';
foo.inputElements.email.value = 'hello@world.com';


texts: Visualizing Newton-Raphson method for finding zeroes of a function

texts:
I have created a program to visualize the working of Newton-Raphson method to find the zeroes of a function:

newton.m:

% Dummy statement to avoid writing function in the first line and making it a 'function file' instead of a 'script file'
1;

% The function to find zeroes of.
% The function is specifically chosen to not have any zeroes
% so as to show the weakness of Newton's method.
function y = f(x)
    y = (x - 5).^2 + 5;
endfunction

% The derivative of f(x)
function y = fd(x)
    y = 2 * (x - 5);
endfunction

% Initial guess
x0 = 1.5;

% Max number of iterations
itermax = 20;

% Epsilon value initialized to a very large value
eps = 1;

% A vector for storing the history of the approximate roots
xvals = x0;

% Number of iterations done
itercount = 0;

% Required for plotting f(x) vs x
x = linspace(0, 10, 100);

% Create a figure whose output is not rendered on the screen
% Not working currently; supposedly a bug in Octave
% A workaround is to use gnuplot instead of qt - `graphics_toolkit gnuplot`
% but this is very slow.
% Uncomment the following to activate the feature once the bug is fixed
% figure('Visible','off');

% The main loop
while eps >= 1e-5 && itercount <= itermax
    % x1 = New value of root
    % x0 = Current value of root
    x1 = x0 - f(x0) / fd(x0);

    % Plot f(x)
    % Plot a line passing through points [x0, f(x0)] and [x1, 0]
    % Plot a line passing through points [x1, 0] and [x1, f(x1)]
    % Plot a line passing through points [x0, 0] and [x0, f(x0)]
    plot(x, f(x), ";f(x);", [x0 x1], [f(x0) 0], "-r;f'(x);", [x1 x1], [0 f(x1)], ":r", [x0 x0], [0 f(x0)], ":r");
    title('f(x) = (x-5)^2 + 5');

    % Set limits for the axes shown in the plots
    xlim([0 10]);
    ylim([0 30]);

    % Label the two consecutive zeroes on the X-axis
    text(x0, -2, sprintf('x%d', itercount), 'color', 'red');
    text(x1, -2, sprintf('x%d', itercount+1), 'color', 'red');

    % Print the plot to a file
    filename = sprintf('output/%05d.jpg', itercount);
    print(filename)

    % Append the zero to the array of zeroes calculated so far
    xvals = [xvals; x1];

    % Calculate the epsilon value
    eps = abs(x1-x0);

    x0 = x1;
    itercount = itercount+1;
end

% Print the result of the iteration
xvals
f_zero = f(xvals(end))
eps
itercount

This program produces a series of images which I have combined to create an animation:

The command I used to convert the images is:

convert -delay 100 -loop 0 *.png animation.gif

This code is also stored here.

I would like to get it reviewed on the following:

Octave conventions and coding patterns (This is my first programming attempt using Octave)
Any improvement on the algorithm itself
Readability and performance of the code
Method and quality of producing animations


texts: Given {origin, destination} objects, find all the paths from a place to another

texts:
I have an object like this:

[
   {
     origin: 'a',
     destination: 'b'
   },
   {
     origin: 'a',
     destination: 'c',
   },
   {
     origin: 'b',
     destination: 'c'
   },
   {
     origin: 'b',
     destination: 'd'
   },
   {
     origin: 'd',
     destination: 'c'
   },
   {
     origin: 'd',
     destination: 'e'
   }
];

given an origin and a destination I should find all the paths to get there.

So this is my code:

function getDestinations(origin, destinationEnd) {
  let destinations = payloads.filter(payload => payload.origin === origin);
  destinations = destinations.map(destination => {
    const destinationsRecursive = getDestinations(destination.destination, destinationEnd);
    if (destinationsRecursive.length) {
      return Object.assign({}, destination, {
        next: destinationsRecursive
      });
    } else if (destination.destination === destinationEnd){
      return Object.assign({}, destination, {
        end: true
      });
    }
  })
  destinations = destinations.filter(destination => destination !== undefined)
  return destinations;
}

Calling for example getDestinations('a', 'c'); would return this:

[
  {
    "origin": "a",
    "destination": "b",
    "next": [
      {
        "origin": "b",
        "destination": "c",
        "end": true
      },
      {
        "origin": "b",
        "destination": "d",
        "next": [
          {
            "origin": "d",
            "destination": "c",
            "end": true
          }
        ]
      }
    ]
  },
  {
    "origin": "a",
    "destination": "c",
    "end": true
  }
]

What whould you improve in my code to make the same better?


texts:
I am implementing a Fibonacci range in C++17 such that it supports

#include "fib.h"

#include <iostream>

int main() {

  for (int x : Fibonacci()) {
    std::cout << x << std::endl;

    if (x > 100000) {
      break;
    }
  }

  for (int x : Fibonacci(5)) {
    std::cout << x << std::endl;
  }

  for (int x : Fibonacci(3, 10)) {
    std::cout << x << std::endl;
  }

  return 0;
}

Here is how I defined the header

#ifndef FIB_H
#define FIB_H

#include <cstddef>
#include <iterator>

class Fibonacci {
 public:
  class iterator {
   public:
    using iterator_category = std::forward_iterator_tag;
    using value_type = int;
    using difference_type = int;
    using pointer = int*;
    using reference = int&;

   public:
    iterator() = default;

    iterator(int i, int a, int b);

    int operator*() const;

    iterator& operator++();

    bool operator!=(iterator const& other) const;
   private:
    int i_ {0};
    int a_ {0};
    int b_ {1};
  };

 public:
  Fibonacci();

  Fibonacci(int end);

  Fibonacci(int begin, int end);

  iterator begin() const;

  iterator end() const;

 private:
  iterator beginIt_;

  iterator endIt_;
};

#endif

And the source code

#include "fib.h"

#include <iterator>

Fibonacci::iterator::iterator(int i, int a, int b)
    : i_(i), a_(a), b_(b) {}

int Fibonacci::iterator::operator*() const {
  return b_;
}

Fibonacci::iterator& Fibonacci::iterator::operator++() {
  ++i_;
  b_ = b_ + a_;
  a_ = b_ - a_;
  return *this;
}

bool Fibonacci::iterator::operator!=(Fibonacci::iterator const& other) const {
  return i_ != other.i_;
}

Fibonacci::Fibonacci()
    : endIt_(-1, 0, 0) {}

Fibonacci::Fibonacci(int end)
    : endIt_(end, 0, 0) {}

Fibonacci::Fibonacci(int begin, int end)
    : beginIt_(std::next(Fibonacci::iterator(), begin)), endIt_(end, 0, 0) {}

Fibonacci::iterator Fibonacci::begin() const {
  return beginIt_;
}

Fibonacci::iterator Fibonacci::end() const {
  return endIt_;
}

I want to have a syntax similar to the standard library where the iterator of a class can be accessed using ::iterator, therefore I nested my iterator class into the main class itself. However, this makes the source code very verbose and results in very long function name. Is there a way to make this more readable? Furthermore, is there any new C++17 feature I should be aware of that can be applied here?


texts: How could I do DateTime.Now.Date (from C#) in JavaScript?

texts:
In C# I can use

DateTime dt = DateTime.Now.Date;

This will give the current date, without the TimeSpan value ('00:00:00'). In JavaScript I did this:

var dt = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());

But is so "ugly" that there must be a better, easier and clean way to do it.


texts: Handling large images efficiently (to avoid OutOfMemoryError)

texts:
After lots of attempts thanks to all the Android enthusiasts, I've found a method to handle large images efficiently in Android Applications in order to get rid of OutOfMemoryError. But I really need to know is this the correct formal way of doing this? Do I need to add some more, or should any changes be made? Please comment.

Bitmap bitmap1;

iv1 = (ImageView) findViewById(R.id.iv1);
iv2 = (ImageView) findViewById(R.id.iv2);
iv3 = (ImageView) findViewById(R.id.iv3);

BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;

BitmapFactory.decodeResource(getResources(), R.drawable.image1);
BitmapFactory.decodeResource(getResources(), R.drawable.image2);
BitmapFactory.decodeResource(getResources(), R.drawable.image3);

int srcWidth = o.outWidth;
int srcHeight = o.outHeight;
int dstWidth = 600;
 int dstHeight = 450;
int inSampleSize = 1;
if (srcHeight > dstHeight || srcWidth > dstWidth) {
            final int halfHeight = srcHeight / 2;
            final int halfWidth = srcWidth / 2;
            while ((halfHeight / inSampleSize) > dstWidth
                    && (halfWidth / inSampleSize) > dstWidth) {
                inSampleSize *= 2;
            }
        }
        o.inSampleSize = inSampleSize;
        o.inJustDecodeBounds = false;
        bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.image1, o);
        iv1.setImageBitmap(bitmap1);

        bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.image2, o);
        iv2.setImageBitmap(bitmap1);
        Toast.makeText(getApplicationContext(),
                "DEcoded", Toast.LENGTH_LONG).show();

        bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.image3, o);
        iv3.setImageBitmap(bitmap1);

    @Override
    protected void onDestroy() {
        bitmap1.recycle();
        super.onDestroy();
        Toast.makeText(getApplicationContext(),
                "Bitmap Destroyed", Toast.LENGTH_LONG).show();
    }


texts:
Looking for feedback on a question I solved in C++. It is a leetcode problem and I used divide and conquer to solve the problem.

  53. Maximum Subarray

  Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

  Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

  Follow up:

  If you have figured out the \$\mathcal{O}(n)\$ solution, try coding another solution using the divide and conquer approach, which is more subtle.

I am looking for feedback in terms of logic and also the implementation. If I search for a C++ solution online, I only see problem solved using arrays and I have used vector to solve to the problem while utilizing iterators.

Any feedback would be great.

Thanks!

int FindMaximumSubarray(const vector<int> &vec) {
  if (vec.size() == 1) {
    return vec.at(0);
  }
  int midIndex = vec.size() / 2;
  vector<int> leftArray(vec.begin(), vec.begin() + midIndex);
  vector<int> rightArray(vec.begin() + midIndex, vec.end());
  int maximumSumLeftSubarray = FindMaximumSubarray(leftArray);
  int maximumSumRightSubarray = FindMaximumSubarray(rightArray);
  int maximumSumCrossingSubarray = FindMaximumSubarrayCrossing(vec);
  return FindMaximumNumber(maximumSumLeftSubarray,
                           maximumSumRightSubarray,
                           maximumSumCrossingSubarray);
}

int FindMaximumSubarrayCrossing(const vector<int> &vec) {
  int midIndex = vec.size() / 2, leftSum = INT_MIN, rightSum = INT_MIN, sum = 0;
  for (auto itr = vec.rbegin() + midIndex; itr != vec.rend(); ++itr) {
    sum += *itr;
    if (sum > leftSum) leftSum = sum;
  }
  sum = 0;
  for (auto itr = vec.begin() + midIndex + 1; itr != vec.end(); ++itr) {
    sum += *itr;
    if (sum > rightSum) rightSum = sum;
  }
  if (leftSum == INT_MIN || rightSum == INT_MIN) {
    return (leftSum == INT_MIN) ? rightSum : leftSum;
  }
  return (leftSum + rightSum);
}

int FindMaximumNumber(const int &a, const int &b, const int &c) {
  if (a >= b && a >= c) return a;
  if (b >= a && b >= c) return b;
  if (c >= a && c >= b) return c;
}
```


texts: Random Password Generator based on user input

texts:
This is my second program written in python. It basically creates a password made up of numbers, capital and lower case letters with the option to include special characters and dashes. I created a simpler project and I decided to build upon it to create version 2. Since I am still new, I would like to receive advice and any thoughts on how to improve my code as well as a programmer. Such as how random this password is, any syntax errors, or any ways to simplify my code. I commented as best as I could. Any thoughts would be appreciated.

#version 2 introduces option to include special characters and
the option for the password to be separated into
#sections by a dash as well as a more secure and better created
password which has no certain pattern to it
#as the previous version did

#loop goes through steps until user decides to quit
# 1. ask for user input if special characters can be added and set
     to var response
# 2. come up with random number between 1 and 3, set = to var
     typevalue if special is no
#    come up with random number between 1 and 4, set = to var
     typevalue if special is yes
# 3. assign randint between 0 and 25 to lowercase and uppercase
     var, assign randint between 0-9 to number var,
#    assign randint between 0-9 to character var
# 4. if type=0 number value is added to objects list
#    if type=1 upper[uppercase] is added to objects list
#    if type=2 lower[lowercase] is added to objects list
#    if response is yes and only yes, characters[character] is
     added to objects list

from random import randint

upper =
["A","B","C","D","E","F","G","H","I","J","K","L","M",
 "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
lower = ["a","b","c","d","e","f","g","h","i","j","k","l","m",
         "n","o","p","q","r","s","t","u","v","w","x","y","z"]
characters = ["!","@","#","$","%","^","&","*","_","+"]

objects = []

def RunFun(a,b):
    typevalue = randint(a, b)
    lowercase = randint(0, 25)
    uppercase = randint(0, 25)
    number = randint(0, 9)
    character = randint(0, 9)
    if typevalue == 1:
        objects.append(upper[uppercase])
    elif typevalue == 2:
        objects.append(number)
    elif typevalue == 3:
        objects.append(lower[lowercase])
    elif typevalue == 4:
        objects.append(characters[character])

def RunType2(c,d):
    first = c
    second = d
    for i in range(16):
        RunFun(first, second)
    Function1()

def Function1():
    dashes = raw_input("Would you like it to be seperated into"
    four sections of four characters divided by a dash?
    Y for yes N for no: ")
    if dashes == "Y" or dashes == "y":
        #print "dashes %s" % (objects)
        print "%s%s%s%s-%s%s%s%s-%s%s%s%s-%s%s%s%s" % (
            objects[0], objects[1], objects[2], objects[3],
            objects[4], objects[5], objects[6], objects[7],
            objects[8], objects[9], objects[10], objects[11],
            objects[12], objects[13], objects[14], objects[15])
    else:
        #print "no dashes %s" % (objects)
        print "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s" % (
            objects[0], objects[1], objects[2], objects[3],
            objects[4], objects[5], objects[6], objects[7],
            objects[8], objects[9], objects[10], objects[11],
            objects[12], objects[13], objects[14], objects[15])

#-------------foundation-----------
while True:
    #requests user input which determines if special characters
    #are included
    answer = raw_input("Can it have special characters? Y for yes
    N for no. X to exit: ")

    if answer == "Y" or answer == "y":
        RunType2(1,4) #hands over value 1 and 4 to include
                      #characters in the creation
    elif answer == "N" or answer == "n":
        RunType2(1,3) #hands over values 1 and 3, opts out 4
                      #which is special characters
    elif answer == "x" or answer == "X":
        exit()
    else:
        print "Invalid Input."
            del objects[:]


texts: Format seconds into the two biggest units of time

texts:
I wrote a function to convert seconds into the two biggest units of time and format it into a string. What I mean is that e.g. 134 second would be 02m14s and 3665 seconds would become 1h1m. Here is what I did:

def pprint_time(seconds):
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    format_str = lambda v1, v2, p: f"{v1:0>2}{p[0]}{v2:0>2}{p[1]}"
    if d > 0:
        return format_str(d, h, ("d","h"))
    elif h > 0:
        return format_str(h, m, ("h","m"))
    elif m > 0:
        return format_str(m, s, ("m","s"))
    else:
        return f" {s:0>2}sec"

I wonder if there is a more "pythonic" way of doing this since the if-elif-else statement does feel a bit clunky.


texts:
Is this code good? Or is it the noobiest PHP you've ever seen?

<?php
//Initialization Section
require "helper.php";
$dest = "../forms/addhandout.php";

//Check for $_POST Data
if(!$_POST) {
    send(array("msg" => "ERROR: No Data Recieved"));
} else if(!isset($_POST["name"]) || $_POST["name"] == "") {
    send(array("msg" => "ERROR: Name field cannot be left blank"));
} else if(!isset($_POST["class"])) {
    send(array("msg" => "ERROR: Class field cannot be left blank"));
}

//Set $_POST Data
$name = $_POST["name"];
$cid = $_POST["class"];

//Check if PHP is connected to database
if(!$sql) {
    send(array("msg" => "ERROR: Cannot Connect to Database"));
}

//Check for Existing Handout
$query = "SELECT id FROM Handouts WHERE name='$name' AND cid=$cid";
$result = mysqli_query($sql, $query);
if(!$result) {
    send(array("msg" => "ERROR: Cannot Connect to Database"));
} else if(mysqli_num_rows($result) > 0) {
    send(array("msg" => "ERROR: Handout already exists"));
}

//Add Handout to DB
$query = "INSERT INTO Handouts (name, cid) VALUES ('$name', $cid)";
$result = mysqli_query($sql, $query);
if(!$result) {
    send(array("msg" => "ERROR: Cannot Connect to Database"));
}

//Get Handout ID
$query = "SELECT id FROM Handouts WHERE name='$name' AND cid=$cid";
$result = mysqli_query($sql, $query);
if(!$result) {
    send(array("msg" => "ERROR: Cannot Connect to Database"));
}
$hid = mysqli_fetch_assoc($result)["id"];

//Get JSON from file
$json = jread("../data.json");

//Add handout to JSON
$json[$hid] = array();

//Write JSON to file
jwrite("../data.json", $json);

//Close Connection to DB
mysqli_close($sql);

//Return to Web Form
send(array("msg" => "SUCCESS: Your Handout has been Created!"));
?>

<?php
define("HOST", "localhost");
define("USR", "web");
define("PSWD", "thundercats...thundercats...HO!!!!!");
define("DB", "Inventory");

$sql = mysqli_connect(HOST, USR, PSWD, DB);
$dest = "";

function jread($file) {
    $handle = fopen($file, "r");
    if(!($data = fread($handle, filesize($file)))) {
        return FALSE;
    }
    $json = json_decode($data, TRUE);
    return $json;
}

function jwrite($file, $data) {
    $handle = fopen($file, "w");
    if(fwrite($handle, json_encode($data))) {
        return TRUE;
    } else {
        return FALSE;
    }
}

function redir() {
    global $dest;
    header("Location: " . $dest);
    exit();
}

function send($params) {
    global $dest;
    $get = http_build_query($params);
    header("Location: $dest?$get");
    exit();
}
?>


texts: Finding the coordinates on an edge of a square

texts:
I wrote a calculation that finds coordinates on an edge of a square, but it came out as a really long nested tangle of conditions. After some reduction and finding common pieces I arrived at this example:

  // targetX, targetY, sourceX, sourceY are provided as parameters
  // and are markers for the centers of the two locations connecting
  let tx;
  let ty;
  const dx = targetX - sourceX;
  const dy = targetY - sourceY;
  const adjY = (radius * Math.tan(Math.atan2(dy, dx)));
  const adjX = (radius / Math.tan(Math.atan2(dy, dx)));
  if (Math.abs(adjY) <= radius) { // A
    if (targetX <= sourceX) { // B
      tx2 = targetX + (Math.abs(adjX) <= radius ? adjX : radius);
      ty2 = targetY + (Math.abs(adjY) <= radius ? adjY : radius);
    } else {
      tx2 = targetX - (Math.abs(adjX) <= radius ? adjX : radius);
      ty2 = targetY - (Math.abs(adjY) <= radius ? adjY : radius);
    }
  } else if (targetY <= sourceY) { // C
    tx2 = targetX + (Math.abs(adjX) <= radius ? adjX : radius);
    ty2 = targetY + (Math.abs(adjY) <= radius ? adjY : radius);
  } else {
    tx2 = targetX - (Math.abs(adjX) <= radius ? adjX : radius);
    ty2 = targetY - (Math.abs(adjY) <= radius ? adjY : radius);
  }

Moving several of the conditions into the lines themselves was possible using ternary operators. But now I'm stuck, so how do I reduce the conditions even further?

I thought of using boolean logic gate reduction techniques, like Karnaugh maps, but fail to find a way to map that process to my problem.

Other solutions involving different math are welcome as well.

The problem is finding the new target X and Y so that they meet the edge of the target rectangle instead of its center.


texts: Filtering out, a list of games, based on their followers

texts:
so I am playing with Rawg.io 's API.
U can sort their game list by their release date, however there are just too many games. In their website, there's an option called "Popular only", which only shows games that are being followed by at least 1 people.
I implemented this feature by sorting the elements I get and creating a sorted list. I wanted to make sure that I would also acces their information in a systematically way ([game's number], [name or other topic]).
(the ##delete## parts are parts that are just for console visuals, I am planning to move this project to a Kivy app, so won't need them later)
I really want to know what I could have done differently. What's obnoxious, stupid,  ... could be better?
import requests

######Delete#########
import os

os.system("cls")
###################

#### Functions
def _Url(year1, month1, day1, year2, month2, day2, PageNumber=1):
    if month1 < 10:
        month1 = "0" + str(month1)
    if day1 < 10:
        day1 = "0" + str(day1)
    if month2 < 10:
        month2 = "0" + str(month2)
    if day2 < 10:
        day2 = "0" + str(day2)

    Url = (
        "https://api.rawg.io/api/games?dates="
        + str(year1)
        + "-"
        + str(month1)
        + "-"
        + str(day1)
        + ","
        + str(year2)
        + "-"
        + str(month2)
        + "-"
        + str(day2)
        + "&page="
        + str(PageNumber)
        + "&platforms=4,187,1,18,186&page_size=40&ordering=released"
    )
    return Url

def _GetData_Date(year1=2020, month1=8, day1=4, year2=2020, month2=8, day2=4): #just place holder values

    Url = _Url(year1, month1, day1, year2, month2, day2)
    StaticData = requests.get(Url).json()
    AmountOfGames = StaticData["count"]
    AmountOfPages = AmountOfGames // 40 #1 page contains 40 so it does amount//40 to get pages
    if(AmountOfGames%40 != 0):
        AmountOfPages = AmountOfPages + 1 #does +1 if there's a leftover page
    PageNumber = 1

#############Delete############
    Succes = 0
    Fail = 0
#########################

    while PageNumber <= AmountOfPages:

        for x in range(len(StaticData["results"])):
            if StaticData["results"][x]["added"] > 0:
                try:   #can't start with an empty Game variable
                    AStaticData = (StaticData["results"][x],)  # the ","turns it to tulpe, it keeps adding tulpes to 1 giant one that contains all the filtered information
                    Game = Game + AStaticData
                except:
                    AStaticData = (StaticData["results"][x],)  # the ","turns it to tulpe
                    Game = AStaticData
############################Delete#################
                os.system("cls")
                Succes = Succes + 1
                print("succes: ", (Succes))
                print("fail:", Fail)
                print("Total:", AmountOfGames, Succes + Fail)
            else:
                os.system("cls")
                Fail = Fail + 1
                print("succes: ", (Succes))
                print("fail:", Fail)
                print("Total:", AmountOfGames,"-", Succes + Fail)
##################################################
        # goes trough pages
        PageNumber = PageNumber + 1
        if PageNumber <= AmountOfPages:
            Url = _Url(year1, month1, day1, year2, month2, day2, PageNumber)
            StaticData = requests.get(Url).json()

    return Game

#### Save it to local variables #####
StaticData =_GetData_Date()

### Main program ###################
for x in range(len(StaticData)):
    print(StaticData[x]["name"])


texts: Get consecutive integer number ranges from list of int

texts:
This is an algorithm to return a list of consecutive integer ranges from a list of integers.

The practical use of such an algorithm is to filter lists more efficiently, i.e. rather than check e.g. 1000 items (1..1000; x==1 || x==2 || ... || x==1000), it might be possible to check only 2 items (x >= 1 && x <= 1000).

Does this algorithm have any mistakes, can it be optimized, or are there any other improvements you can suggest?

(As a side note: I know this code does not follow the standard C# naming conventions.  I do not like to follow that particular convention; I prefer "snake_case" as it is easier on my eyes.)

Sample output:

(x >= 0 && x <= 1690)
(x >= 13642 && x <= 15331)
(x >= 27283 && x <= 27296)
(x >= 27769 && x <= 27776)
(x >= 28249 && x <= 28256)
(x >= 28729 && x <= 28736)
(x >= 29209 && x <= 29222)

The algorithm (built Visual Studio 2017, C# 7.3, .NET 4.7.2):

public static List<(int from, int to)> get_consecutive_ranges(List<int> fids)
{
    if (fids == null || fids.Count == 0) return null;

    fids = fids.OrderBy(a => a).Distinct().ToList();

    var fids_fast = new List<(int from, int to)>();

    var is_conseq_with_last = true;
    var start_index = 0;
    var end_index = 0;
    for (var fids_index = 0; fids_index < fids.Count; fids_index++)
    {
        var first = fids_index == 0;
        var last = fids_index == fids.Count - 1;
        if (!first && fids[fids_index - 1] == fids[fids_index] - 1)
        {
            is_conseq_with_last = true;
        }
        else if (!first)
        {
            is_conseq_with_last = false;
        }

        if (!is_conseq_with_last && !first && !last)
        {
            end_index = !first && !last ? fids_index - 1 : fids_index;
            fids_fast.Add((fids[start_index], fids[end_index]));
            start_index = fids_index;
        }
        else if (last)
        {
            if (!is_conseq_with_last)
            {
                if (!first)
                {
                    end_index = fids_index - 1;
                }

                fids_fast.Add((fids[start_index], fids[end_index]));
                start_index = fids_index;
            }

            end_index = fids_index;
            fids_fast.Add((fids[start_index], fids[end_index]));
        }
    }

    fids_fast.ForEach(a => Console.WriteLine($"(x >= {a.@from} && x <= {a.to})"));

    return fids_fast;
}

Example use:

// slow:
body = body.Where(a => fids.Contains(a.fid)).ToList();

// fast:
body = body.Where(a => fids_fast.Any(x => a.fid >= x.from && a.fid <= x.to)).ToList();


texts:
As a beginner I try to implement a vokable memory game. It is still missing some feature (Loading, Display), but I would like to hear how to improve what is already there.

The user should identify matching pairs. Theses are then removed from the game. The game ends when there are not any pairs left.

I think there has to be nicer way to write the code for game' in mainLoop.

Any other suggestions to improve the code are also welcome.

module Main where

import Data.Maybe (fromMaybe)
import qualified Data.List.Safe as List
import Data.List (foldl')

type Vokabel = (String,String)

data Tile = Tile { _front   :: Bool
                 , _vokabel :: Vokabel
                 } deriving (Show)

instance Eq Tile where
  (==) (Tile _ v1) (Tile _ v2) = v1 == v2

getText :: Tile -> String
getText (Tile b (s1,s2)) | b  = s1
                         | not b = s2

newtype Game = Game { _tiles      :: [Tile]
                 } deriving Show

displayGame :: Game -> String
displayGame g = let
                tile2Line s x = s ++ getText x ++ "\n"
                in  foldl' tile2Line "" . _tiles $ g --(foldl' "" tile2Line) . _tiles $ g

makeTile s = Tile True (s++"-Front",s++"-Back")
makeVok s = (s++"-Front",s++"-Back")

gameExampel :: Game
gameExampel = generateGame . map makeVok $ ["Alpha","Beta","Gamma"]

generateGame :: [Vokabel] -> Game
generateGame vs = Game (map (Tile True) vs ++ map (Tile False) vs)

main :: IO ()
main = do
  putStrLn "Vokabel Memory"
  mainLoop gameExampel
  pure ()

chooseTile :: Game -> Int -> Maybe Tile
chooseTile g x = _tiles g List.!! x

mainLoop :: Game -> IO ()
mainLoop game = do
  putStrLn . displayGame $ game
  putStrLn "choose Tile, or exit"
  input <- getLine
  if input == "exit"
    then
      do
    putStrLn "exit now!"
    pure()
  else
    do
    let indexA = read input
    let choosenTileA = chooseTile game indexA
    putStrLn ("choosen: " ++  maybe  "nothing" getText choosenTileA)
    indexB <- read <$> getLine
    let choosenTileB = chooseTile game indexB
    putStrLn ("choosen: " ++  maybe  "nothing" getText choosenTileB)
    let game' = fromMaybe game (do
                                  vokA <- _vokabel <$> choosenTileA
                                  vokB <- _vokabel <$> choosenTileB
                                  if vokA == vokB && indexA /= indexB then
                                            Game <$> ((List.delete <$> choosenTileB) <*> ((List.delete <$> choosenTileA) <*> (pure . _tiles $ game)))
                                          else
                                            pure game
                               )
    if null . drop 1 . _tiles $ game' then
        return ()
      else
        mainLoop game'

EDIT: Having thought about it: I would like to know how to use the state monade in this example.


texts: "The Love Letter Mystery" - storing and comparison of strings

texts:
The problem goes like this.

Change the strings provided by user to form palindromes. To do this, 2
rules are:
(a) Reduce the value of a letter, e.g. Change 'd' to 'c',
but cannot change 'c' to 'd'.
(b) In order to form a palindrome, you
can repeatedly reduce the value of a letter until the letter becomes
'a'. Once a letter has been changed to 'a', it can no longer be
changed.
Each reduction in the value of any letter is counted as a single
operation. Find the minimum number of operations required to convert a
given string into a palindrome.

This is a HackerRank problem: the-love-letter-mystery
While I was solving it, I made a lot of mistakes. I was using char *str[n] and gets() to input the string. I thought it would work, but I realised after long time that I am not actually allocating any space at all. Later I came up with 2-d array char[n][1000] for storing the strings and scanf seemed to work for me.
Here is my solution:
int main() {

    int i, n, len, pos, ops, end;
    scanf("%d",&n);
    char str[n][10000];
    char a,b;
    for (i=0;i<n;i++) {
        scanf("%s",str[i]);
    }
    for (i=0;i<n;i++) {
        len = strlen(str[i]);
        pos = 0;
        end = len - 1;
        ops = 0;
        while ( pos < end) {
               a = str[i][pos];
               b = str[i][end];
               if ( a != b ) {
                   if ( b > a )
                       ops = ops + (b -a);
                   else
                       ops = ops + (a -b);
               }
               pos++;
               end--;
        }
        printf("%d\n", ops);
    }

return 0;
}

This works perfectly. I also have to assume in the program that the strings can be of max length 1000 as that is one of the constraint.
How can I improve this solution without making it too complex?


texts:
The Goldbach conjecture says: any even number greater than two can be represented by the sum of two prime numbers.

  G(n) = { (p1, p2) | p1 + p2 = n, p1 and p2 are prime numbers with p1 < p2 }

For example:

  G(6) = {(3, 3)}

  G(12) = {(5, 7)}

  G(26) = {(3, 23),(7, 19),(13, 13)}

So I have to do an algorithm that determines which three numbers n1, n2 and n3 are between 1,000,000 and 2,000,000 for which the
G (n1), G (n2) and G (n3) have the largest number of elements.

I do not know if I need to improve something in my code, or even optimize some part that is poorly written. It currently taking about 12 seconds.

public class Goldbach  {

    private static int j;
    private static int k;
    private static int [] primes;
    private static int [] just_primes;
    private static int [] conjunct;

    public static void main(String[] args)
    {

        primes = new int[2000000];
        for ( int i=0; i<2000000; i++ ) {
            primes[i] = i+1;
        }

        for ( int i=1; i<1000000; i++ ) {
            if ( primes[i] != 0 ) {
                j = primes[i];
                k = j;
                while ( k <= 2000000 ) {
                    k += j;
                    if ( k <= 2000000 ) {
                        primes[ k-1 ] = 0;
                    }
                }
            }
        }

        just_primes = new int [primes.length];
        for ( int i = 0; i< primes.length-1 ; i++ ) {
            just_primes[i] = 0;
        }

        k = 0;
        for ( int i = 1; i< primes.length-1 ; i++ ) {
            if ( primes[i] > 0 ) {
                just_primes[k] = primes[i];
                k++;
            }
        }

        conjunct = new int[1000001];
        for ( int i = 0; i<1000001 ; i++ ) {
            conjunct[i] = 0;
        }

        int p;
        for ( int i = 0; i< k ; i++ ) {
            for ( int j = i; j< k ; j++ ) {
                int w = just_primes[i]+just_primes[j];
                if ( w >= 1000000 && w <= 2000000 ) {
                    p = w - 1000000;
                    conjunct[p]++;
                }
            }
        }

        int big1 = 0;
        int big2 = 0;
        int big3 = 0;
        int n1 = 0;
        int n2 = 0;
        int n3 = 0;

        for ( int i = 0; i<1000001 ; i++ ) {
            if ( conjunct[i] >= big1 ) {
                big3 = big2;
                big2 = big1;
                big1 = conjunct[i];
                n3 = n2;
                n2 = n1;
                n1 = i;
            } else {
                if ( conjunct[i] >= big2 ) {
                    big3 = big2;
                    big2 = conjunct[i];
                    n3 = n2;
                    n2 = i;
                } else {
                    if ( conjunct[i] >= big3 ) {
                        big3 = conjunct[i];
                        n3 = i;
                    }
                }
            }
        }

        System.out.println( "Largest conjunct 1: " + n1 + " " + 1000000+big1 + " pairs" );
        System.out.println( "Largest conjunct 2: " + n2 + " " + 1000000+big2 + " pairs" );
        System.out.println( "Largest conjunct 3: " + n3 + " " + 1000000+big3 + " pairs" );

    }

}

Expected result:

Largest conjunct 1: 981980 100000027988 pairs
Largest conjunct 2: 951950 100000027802 pairs
Largest conjunct 3: 995630 100000027730 pairs


texts:
I have a URL in this format:

http://localhost:57279/AssociateCaseDetails?UId=176948&caseID=1123

I need the values of UId and CaseID:

var UId =window.location.href.split("?")[1].split("&")[0].split("=")[1];

It’s working, but is there a better way to access the same, given the same URL?


texts:
I have written code to check any birthday input's validity. As I am new in programming, and after going through several debugging steps, the code became very ugly.

month_dict = {'jan':'January',
          'feb':'February',
          'mar':'March',
          'may':'May',
          'jul':'July',
          'sep':'September',
          'oct':'October',
          'dec':'December',
          'apr':'April',
          'jun':'June',
          'aug':'August',
          'nov':'November'}

day = int(raw_input ('Enter your birth day: '))
month = raw_input ("Enter your birth month: ")
year_input = int (raw_input ('Enter your birth year: '))

days_31 = ['jan', 'mar', 'may', 'jul', 'aug', 'oct', 'dec']
days_30 = ['apr', 'jun', 'sep', 'nov']
days_28 = ['feb']

def valid_day_finding ():
    global valid_day
    if month_name in days_31:
        if day > 0 and day < 32:
            valid_day = day
        else:
            valid_day = 'invalid'
    elif month_name in days_30:
        if day >= 1 and day <= 30:
            valid_day = day
        else:
            valid_day = 'invalid'
    elif month_name in days_28:
        if year != 'invalid':
            if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
                if day >= 1 and day <= 29:
                    valid_day = day
                else:
                    valid_day = 'invalid'
            else:
                if day >= 1 and day <= 28:
                    valid_day = day
                else:
                    valid_day = 'invalid'
        else:
            valid_day = 'invalid'
    else:
        valid_day = 'invalid'
def valid_month_finding():
    global month_name
    if month in month_dict.keys():
        month_name = month
    else:
        month_name = 'invalid'
def valid_year_finding():
    global year
    if year_input > 1900 and year_input <2020:
        year = year_input
    else:
        year = 'invalid'
def birthday_checking():
    if valid_day != 'invalid' and month_name != 'invalid' and year != 'invalid':
        print 'your birthdate is %d - %s - %d' % (valid_day, month_dict[month_name], year)
    else:
        print 'Your Birthday is invalid'
valid_year_finding()
valid_month_finding()
valid_day_finding()
birthday_checking()

This code is very inefficient. How can I improve this code?

I know that there are built-in functions to check this, but I am trying to learn coding, which is why I am giving this a try.


texts:
I have this class whose code I pasted in full. The CredentialsManager class is not shown here as all it does is return the DB connection variables.

Can be improved or is this is OK as I've written it? Namely, I'm interested if it's OK to have a private variable mysqli populate inside the function openConnection() or if I should have done that in the constructor.

I'm pretty confident it would be a bad thing to have the same code for opening a connection in each function of the class, which is why I've put the connection opening code in a function itself.

<?php
class Logger
{
    // private variables
    private $_host;
    private $_database;
    private $_username;
    private $_password;
    private $_mysqli;

    // public functions
    public function __construct()
    {
        $credientials = CredentialsManager::GetCredentials();
        $this->_host = $credientials['host'];
        $this->_database = $credientials['database'];
        $this->_username = $credientials['user'];
        $this->_password = $credientials['pass'];
    }

    public function RecordLog($log){
        if ($this->openConnection()){
            if (!($stmt = $this->_mysqli->prepare("INSERT INTO logz (log) VALUES (?)"))) {
                echo "Prepare failed: (" . $this->_mysqli->errno . ") " . $this->_mysqli->error;
            }

            if (! $stmt->bind_param("s", $log)){
                echo "Binding failed: (". $stmt->errno .") " . $stmt->error;
            }

            if (! $stmt->execute() ){
                echo "Execute failed: " . $stmt->error;
            }

            if ($stmt->affected_rows > 0)
                return true;
            else
                return false;
        }
        else
            return false;
    }

    // private functions
    private function openConnection()
    {
        $this->_mysqli = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);
        if ($this->_mysqli->connect_errno) {
            echo "Failed to connect to MySQL: " . $this->_mysqli->connect_error;
            return false;
        }

        return true;
    }
}
?>


texts:
As part of an exercise by Jamal to clean up old questions on Code Review that have no code in them, I helped by writing this query on Stack Exchange Data Explorer: CodeLess Questions

select Id as [Post Link], CreationDate
from Posts
where PostTypeId = 1 --questions
  and Body not like '%
%'
  and ClosedDate is null
order by CreationDate

I realize this is a relatively simple query, but I am always looking for ways to avoid like conditions (and not like), and this query irks me.

Note that the like condition is %
% - this is to trap the automatically managed code blocks that Stack Exchange uses to identify code. I cannot easily trap the open-tags because sometimes, when a custom syntax is used, the open tags are hard to search on.

I am looking for insights on whether the query can be improved or whether there are alternatives to the systems I have used for identifying code-less questions.

For reference, when Stack Exchange gets a question, the markup is converted to HTML and stored in the Body column.

An example is as follows:

MarkDown:

I didn't write this but I noticed it in our codebase at work.

    var data = object && object.attribute && object.attribute.data ? object.attribute.data : {};

I get that the programmer is trying to check that the variable
`object.attribute.data` is defined before using it, but is seems like
so much repeated code. What's the best way to assign `data` the value
of `object.attribute.data` if it's defined, otherwise giving it a
value of `{}`?

HTML Encoding:

I didn't write this but I noticed it in our codebase at work.

var data = object &amp;&amp; object.attribute &amp;&amp; object.attribute.data ? object.attribute.data : {};

I get that the programmer is trying to check that the variable object.attribute.datais defined before using it, but is
seems like so much repeated code. What's the best way to assign
data the value of object.attribute.data if
it's defined, otherwise giving it a value of {}?


texts:
Here is my code for the LeetCode problem

  For a given binary tree, find the maximum width of the binary tree. The width of one level is defined as the length between the end-nodes even if there are None nodes in between

My code (in PyCharm) passess all the given tests but does not seem to pass on the LeetCode website. I am not sure why this is, so please don't try plugging it into the website as I assume the way I have built a binary tree is different to their method.

class Node:

    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

    level_width = {0: [0, 0]}

    def get_width(self, root, level=0, pointer=1):
        if root.left:
            if level + 1 not in self.level_width:
                self.level_width[level + 1] = [pointer * 2, 0]
            self.level_width[level + 1][0] = min(self.level_width[level + 1][0], pointer * 2)
            self.get_width(root.left, level + 1, pointer * 2)
        if root.right:
            if level + 1 not in self.level_width:
                self.level_width[level + 1] = [9999, pointer * 2 + 1]
            self.level_width[level + 1][1] = max(self.level_width[level + 1][1], level + 1, pointer * 2 + 1)
            self.get_width(root.right, level + 1, pointer * 2 + 1)
        return

    def widthOfBinaryTree(self, root):
        """
          :type root: TreeNode
          :rtype: int
          """
        self.get_width(root)
        max_distance = 1
        for k, v in self.level_width.items():
            max_distance = max(max_distance, v[1] - v[0] + 1)
        return max_distance

root = Node(1)
root.left = Node(3)
root.left.left = Node(5)
root.left.left.left = Node(6)
root.right = Node(2)
root.right.right = Node(9)
root.right.right.right = Node(7)

print(root.widthOfBinaryTree(root))


texts: Basic Collatz program with input validation in Python

texts:
In chapter 3 of Automate the Boring Stuff with Python by Al Sweigart, one exercise asks to write a program which performs the Collatz sequence.
I wrote a basic version first, then added and restructured some of it to account for an invalid input. Any thoughts or criticisms to make it more concise, organized or legible would be appreciated.
def collatz(number): # This evaluates and prints the sequence of numbers.
        if number % 2 == 0: # If it's an even number.
            print(number // 2)
            return number // 2
        else: # If it's an odd number.
            print(3 * number + 1)
            return 3 * number + 1

def main(): # The main loop inside a function so the ValueError message can appear as many times as needed.
    try:
        user_input = int(input())
        while user_input > 1:
            user_input = collatz(user_input)
        if user_input <= 0: # If a negative integer is entered.
            print('Please enter a positive integer.')
        else:
            print('Enter another integer.')

    except ValueError: # If something other than an integer is entered.
        print('Please enter a valid integer.')

print('Type any positive integer.') # Main prompt.

while True: # This calls the main loop so you can repeat the equation as many times as needed.
    main()


texts:
I'm posting a solution for LeetCode's "Non-decreasing Array". If you'd like to review, please do. Thank you!
Problem
Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
Example 1:

Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: nums = [4,2,1]
Output: false
Explanation: You can't get a non-decreasing array by modify at most one element.

Constraints:

1 <= n <= 10 ^ 4
-10 ^ 5 <= nums[i] <= 10 ^ 5

Code
// Since the relevant headers are already included on the LeetCode platform,
// the headers can be removed;
#include <stdio.h>
#include <stdbool.h>

static const bool checkPossibility(
    int *nums,
    const int nums_size
) {

    if (nums_size < 3) {
        return true;
    }

    int max_changes = 0;

    for (int index = 1; index < nums_size - 1; ++index) {
        if (!(nums[index] >= nums[index - 1] && nums[index + 1] >= nums[index])) {
            if (nums[index + 1] >= nums[index - 1]) {
                ++max_changes;
                nums[index] = nums[index - 1];

            } else {
                if (nums[index] < nums[index - 1] && nums[index + 1] < nums[index]) {
                    return false;

                } else if (nums[index] <= nums[index + 1]) {
                    nums[index - 1] = nums[index];

                    if (!(index - 1) || nums[index - 2] <= nums[index - 1]) {
                        ++max_changes;

                    } else {
                        return false;
                    }

                } else {
                    nums[index + 1] = nums[index];
                    ++max_changes;
                }
            }
        }

    }

    return max_changes < 2;
}

int main() {

    static const int nums_size = 3;
    int nums_array[nums_size] = {4, 2, 1};
    int (*nums)[nums_size] = &nums_array;

    fputs(checkPossibility(*nums, nums_size) ? "true" : "false", stdout);

    return 0;
}


texts:
I developed a lot of code locally with __uint128_t only to find out that it is not available on the target platform.

I am now trying to write my own struct that emulates the operators of __uint128_t I need: =, ~, ^, &, |, ^=, &=, |=

This is the code I have now, which will be compiled with a C++11 compiler:

struct board_t {
    uint64_t hi;
    uint64_t low;

    board_t operator~() const {
        return {~hi, ~low};
    }

    board_t operator|(const board_t & rhs) const {
        return {hi | rhs.hi, low | rhs.low};
    }

    board_t& operator|=(const board_t & rhs) {
        hi |= rhs.hi;
        low |= rhs.low;

        return *this;
    }

    // Complete equivalent functions for &, ^, &= ^=
};

Will anything behave unexpectedly with this code?
Do I need to create a constructor? Is the usage of the {} struct initializer good form?
Do I need to override the assignment operator?
Are there other ways to improve this code, style, correctness and speed?


texts: MongoDB CRUD operations for various types of data in Go

texts:
First of all I am a newbie in Go. I wrote a CRUD REST API that consists of handlers, a database layer and so on, and it contains a lot of code duplication. I see some patterns here, and I know how to reuse code in some other languages like JS or Java using generics or dynamic types.

What are my options in Go? Note that I don't want to use interface{}.

Here is my userdb CRUD set of function that create, update and so on.

package userdb

import (
    "github.com/atsman/interviewr-go/models"
    "github.com/op/go-logging"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

var log = logging.MustGetLogger("db.user")

func GetUserC(db *mgo.Database) *mgo.Collection {
    return db.C(models.CollectionUsers)
}

func Create(db *mgo.Database, user *models.User) error {
    return GetUserC(db).Insert(user)
}

func Update(db *mgo.Database, id *bson.ObjectId, user *map[string]interface{}) (error, *models.User) {
    var updatedUser = models.User{}
    err := GetUserC(db).UpdateId(id, bson.M{
        "$set": user,
    })
    if err != nil {
        return err, &updatedUser
    }

    err = GetUserC(db).FindId(id).One(&updatedUser)
    return err, &updatedUser
}

func List(db *mgo.Database, query *bson.M) (error, *[]models.User) {
    var users []models.User
    err := GetUserC(db).Find(bson.M{}).All(&users)
    return err, &users
}

func Delete(db *mgo.Database, id *bson.ObjectId) (error, *models.User) {
    var user = models.User{}
    err := GetUserC(db).FindId(id).One(&user)
    if err != nil {
        return err, &user
    }

    err = GetUserC(db).RemoveId(id)
    if err != nil {
        return err, &user
    }

    return nil, &user
}

And here is my companydb package. Its goals are almost the same except with the Company model.

package companydb

import (
    "github.com/atsman/interviewr-go/models"
    "github.com/op/go-logging"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

var log = logging.MustGetLogger("db.company")

func GetCompanyC(db *mgo.Database) *mgo.Collection {
    return db.C(models.CollectionCompanies)
}

func Create(db *mgo.Database, company *models.Company) error {
    return GetCompanyC(db).Insert(company)
}

func Update(db *mgo.Database, id *bson.ObjectId, user *map[string]interface{}) (error, *models.Company) {
    updatedCompany := models.Company{}
    err := GetCompanyC(db).UpdateId(id, bson.M{
        "$set": updatedCompany,
    })
    if err != nil {
        return err, &updatedCompany
    }
    err = GetCompanyC(db).FindId(id).One(&updatedCompany)
    return err, &updatedCompany
}

func List(db *mgo.Database, query *bson.M) (error, *[]models.Company) {
    var companies []models.Company
    err := GetCompanyC(db).Find(bson.M{}).All(&companies)
    return err, &companies
}

func Delete(db *mgo.Database, id *bson.ObjectId) (error, *models.Company) {
    company := models.Company{}
    err := GetCompanyC(db).FindId(id).One(&company)
    if err != nil {
        return err, &company
    }

    err = GetCompanyC(db).RemoveId(id)
    if err != nil {
        return err, &company
    }

    return nil, &company
}

The same duplication exists in my handlers. There is a lot of stuff like get struct from JSON, check for errors and so on. I am thinking of some generic stuff.

So, I think the question is quite easy for guys with some experience. How can I generalize this? Or I shouldn't care at all, maybe it is not a big deal here?


texts: Cosine similarity of one vector with many

texts:
I'm keen to hear ideas for optimising R code to compute the cosine similarity of a vector x (with length l) with n other vectors (stored in any structure such as a matrix m with n rows and l columns).

Values for n will typically be much larger than values for l.

I'm currently using this custom Rcpp function to compute the similarity of a vector x to each row of a matrix m:

library(Rcpp)
cppFunction('NumericVector cosine_x_to_m(NumericVector x, NumericMatrix m) {
  int nrows = m.nrow();
  NumericVector out(nrows);
  for (int i = 0; i < nrows; i++) {
    NumericVector y = m(i, _);
    out[i] = sum(x * y) / sqrt(sum(pow(x, 2.0)) * sum(pow(y, 2.0)));
  }
  return out;
}')

Varying n and l, I'm getting the following sorts of timings:

Reproducible code below.

# Function to simulate data
sim_data <- function(l, n) {
  # Feature vector to be used for computing similarity
  x <- runif(l)

  # Matrix of feature vectors (1 per row) to compare against x
  m <- matrix(runif(n * l), nrow = n)

  list(x = x, m = m)
}

# Rcpp function to compute similarity of x to each row of m
library(Rcpp)
cppFunction('NumericVector cosine_x_to_m(NumericVector x, NumericMatrix m) {
  int nrows = m.nrow();
  NumericVector out(nrows);
  for (int i = 0; i < nrows; i++) {
    NumericVector y = m(i, _);
    out[i] = sum(x * y) / sqrt(sum(pow(x, 2.0)) * sum(pow(y, 2.0)));
  }
  return out;
}')

# Timer function
library(microbenchmark)
timer <- function(l, n) {
  dat <- sim_data(l, n)
  microbenchmark(cosine_x_to_m(dat$x, dat$m))
}

# Results for grid of l and n
library(tidyverse)
results <- cross_d(list(l = seq(200, 1000, by = 200), n = seq(500, 4000, by = 500))) %>%
  mutate(timings = map2(l, n, timer))

# Plot results
results_plot <- results %>%
  unnest(timings) %>%
  mutate(time = time / 1000000) %>%  # Convert time to seconds
  group_by(l, n) %>%
  summarise(mean = mean(time), ci = 1.96 * sd(time) / sqrt(n()))

pd <- position_dodge(width = 20)

results_plot %>%
  ggplot(aes(n, mean, group= l)) +
  geom_line(aes(color = factor(l)), position = pd, size = 2) +
  geom_errorbar(aes(ymin = mean - ci, ymax = mean + ci), position = pd, width = 100) +
  geom_point(position = pd, size = 2) +
  scale_color_brewer(palette = "Blues") +
  theme_minimal() +
  labs(x = "n", y = "Seconds", color = "l") +
  ggtitle("Algorithm Runtime",
          subtitle = "Error bars represent 95% confidence intervals")


texts:
I understand that I should use prepared statements to prevent SQL injection. Unfortunately, having read the PHP docs on the matter I am none the wiser. Here is one of my simple active record SQL queries in a CI2 model, could someone show me an example of how I might turn this into a prepared statement - do I even need to?

function get_item($id){
        $this->db
            ->select('*')
            ->from('item_entries')
            ->where('item_entries.item_id', $id)
            ->join('item_categories_rel', 'item_categories_rel.item_id = item_entries.item_id');
        $query = $this->db->get();
        if(is_object($query)){return $query->result_array();}else{return $query;}
    }

Am I correct in thinking prepared statements are only necessary if I am accepting user data - if so lets assume $id is user submitted. Although it is not, I am about to write some form to db statements, so advice in preparation for this is appreciated.


texts: This technique for functional programming, and testing functional programming

texts:
I've been playing around with functional programming and testing with jest recently.

An issue I've run into, is that it's hard to mock ES6 module exports directly. See this Stack Overflow question for more details.

The solution I've come up with is to inject the dependency functions into the function that is calling it, via .bind.

Here's an example:

import axios from "axios";
const BASE_URL = "https://jsonplaceholder.typicode.com/";
const URI_USERS = 'users/';

/**
* These are the implementation of our functions, which take functions as arguments.
*/

export const _fetchUsers = async function (_makeApiCall, _URI_USERS) {
    return _makeApiCall(_URI_USERS);
}

export const _fetchUser = async function (_makeApiCall, _URI_USERS, id) {
    return _makeApiCall(_URI_USERS + id);
}

export const _fetchUserStrings = async function (_fetchUser, _parseUser, ...ids) {
    const users = await Promise.all(ids.map(id => _fetchUser(id)));
    return users.map(user => _parseUser(user));
}
export const _makeApiCall = async function (uri) {
    try {
        const response = await axios(BASE_URL + uri);
        return response.data;
    } catch (err) {
        throw new Error(err.message);
    }
}

export function _parseUser(user) {
    return `${user.name}:${user.username}`;
}

/**
 * Real exports
 */
export const makeApiCall = _makeApiCall;
export const parseUser = _parseUser;

export const fetchUsers = _fetchUsers.bind(null, _makeApiCall, URI_USERS);
export const fetchUser = _fetchUser.bind(null, _makeApiCall, URI_USERS);
export const fetchUserStrings = _fetchUserStrings.bind(null, _fetchUser, _parseUser);

And a test:

/**
 * Our most complicated test
 *
 */

describe("_fetchUserStrings", () => {

    describe("happy flow", () => {

        const fetchUserMock = jest.fn((i) => Promise.resolve({
            username: "foo",
            name: "bar"
        }));
        const parseUserMock = jest.fn(user => "string");
        const fetchUserStrings = _fetchUserStrings.bind(null, fetchUserMock, parseUserMock);

        it("returns an array of three strings", async () => {

            expect.assertions(3);
            const result = await fetchUserStrings(1, 2, 3);

            // I'm being a bit lazy here, you could be checking that
            // The strings are actually there etc, but whatevs.

            expect(fetchUserMock).toHaveBeenCalledTimes(3);
            expect(parseUserMock).toHaveBeenCalledTimes(3);
            expect(result).toHaveLength(3);
        })

    });
});

My question is - is this a super clean way of writing functional JavaScript, or is this overkill that is easily solved another way?

If you're interested, there are more examples here.


texts: Script for creating a hierarchy of directories

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

Hierarchy

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

The script

import os

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

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

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

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

    for i in folder_names():
        safe_make_folder(i)

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

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

if __name__ == "__main__":
    main()