texts: Summing 3 consecutive integers in a list to see if the sum matches a specified value

texts:
I have a program where users can add integers to a list and then I want to check the list to see if any three consecutive integers in the list sum to a specified value. I have been told that it is taking too long when ran with a large number of integers in the list. The timing test that I am not passing is based upon looking for the first match of the sum of 3 consecutive integers, in a large list of integers, to one specific value. The specific value can vary with each run but not within the run and the single run is that is being timed.

class Aggro
{
    private List<int> _numbers = new List<int>();
    public void AddToList(int[] list)
    {
        for (int i = 0; i < list.Length; i++ )
        {
            _numbers.Add(list[i]);
        }
    }

    public bool SumExists(int sum)
    {
        int[] numbers = _numbers.ToArray();
        for (int i = 0; i < numbers.Length -2; i++)
       {
            if (numbers[i] + numbers[i + 1] + numbers[i + 2] == sum)
            {
                return true;
            }
        }
        return false;
    }

    public static void Main(string[] args)
    {
        Aggro a = new Aggro();
        a.AddToList(new int[] { 12, 21, 16, 4, 67, 1 });
        Console.WriteLine(a.SumExists(41)); // True
        Console.WriteLine(s.SumExists(69)); // False
        a.AddToList(new int[] { 1 });
        Console.WriteLine(a.ContainsSum3(69)); //True
    }
}


texts:
I feel like there is a code smell in this. Can someone help me to refactor/optimize it?

protected TimeZone resolveTimeZone() {
    IUserPreferences preferences = userProfileService.getCurrentUserPreferences();
    if (preferences != null) {
        String timeZone = preferences.getPreferredTimeZone();
        if (timeZone != null && !"".equals(timeZone))
            return TimeZone.getTimeZone(timeZone);
        else return defaultTimeZone();
    }
    else return defaultTimeZone();

}

public TimeZone defaultTimeZone() {
    Locale defaultLocale = new Locale(appConfiguration.getDefaultLocale());
    Calendar calendar = Calendar.getInstance(defaultLocale);
    return calendar.getTimeZone();
}


texts: Transforming a dict of lists into a list of dicts

texts:
I would like to transform a dict of one format into a dict of another format.

The raw_input dict will have the shape:

'key': ['list of strings']

I would like to reformat it into a list of dicts with the following shape:

[
    {'key': 'string'},
    {'key': 'string'},
    ...etc for each item in the list of strings
]

My implementation is functional but naive, using a doubly nested for loop:

raw_input = {
  'error': ['string 1', 'string2'],
  'error2': ['string 3']
}

def return_dict_as_list(raw_input):
    mylist = []
    for foo in raw_input:
        for bar in raw_input[foo]:
            mylist.append( { 'mykey': foo, 'myvalue': bar } )
    return mylist

The output is as expected but I can't help but think there's a better way.

I did try a couple of list comprehensions, but the output was not what was desired:

for example this:

elist = [[{'field': item, 'message': msg} for msg in raw[item]] for item in raw]

returns nested lists within a list, which I could unpack but doesn't seem very zen.

here's an online repl with the code:
https://repl.it/repls/UnpleasantBiodegradableSystems


texts:
I am refactoring code which contains many lines of NSString* image = [@"ipad_" stringByAppendingString:imageOrigName]; and wondered which is more optimized:

stringByAppendingString:

or

stringWithFormat:

In the first, you take one NSString object and concatenate another onto its tail.  In the second, you can use a formatter:

NSString* image = [NSString stringWithFormat:@"ipad_%@", imageOrigName];

The result is the same, but for optimization purposes, which is better?

For the above example, I would expect that a simple concatenation would be faster than having it parse the string for '%' symbols, find a matching type (NSString for the %@), and do all its background voodoo.

However, what happens when we have (sloppily written?) code which contains multiple stringByAppendingStrings?

NSString* remainingStr = [NSString stringWithFormat:@"%d", remaining];
NSString* msg = "You have ";
msg = [msg stringByAppendingString:remainingStr];
msg = [msg stringByAppendingString:@" left to go!"];
if (remaining == 0)
    msg = [msg stringByAppendingString:@"Excellent Job!"];
else
    msg = [msg stringByAppendingString:@"Keep going!"];

Here, a single stringWithFormat (or initWithFormat if we use [NSString alloc]) would seem to be the smarter path:

NSString* encouragementStr = (remaining == 0 ? @"Excellent Job!" : @"Keep going!");
NSString* msg = [NSString stringWithFormat:@"You have %d left to go! %@", remaining, encouragementStr];

Thoughts? Sites/blogs that you've found that helps answer this?


texts:
I'm using Twitter Bootstrap and I'm working on a page that has several tabs that all have carousels in them (each with a ton of images) I've managed to write an AJAX script that pulls the images from a JSON file I've created (for one of the carousels). I'm planning on making similar JSON file for the rest, but what I'm wondering though is there a way to write the AJAX script so that it grabs the id from the HTML so I don't have to make a unique AJX script for each version of the carousel

Here's how my HTML looks for the carousel:

And here's my AJAX script:

I'm basically wondering if there is a way to pull the id (carousel1b) from the htnl and inject it into the AJAX strip in the "url:'jason/carousel1b and the "$('carousel').append(d)"


texts:
This method randomly increments or decrements (with equal probability) until either -3 or 3 are reached. I'd like to maintain printing the value of pos on each iteration, and printing the largest positive number max reached at the end of the loop. How can I improve this method using the Random() function? I know this sounds pretty ambiguous, but I'd like to know if I can make rand.nextInt(2) == 0 an easier condition to understand? Any suggestions/improvements are welcome!

public static void randomWalk() {
    Random rand = new Random();
    int pos = 0;
    int max = 0;
    System.out.println("position = " + pos);
    while (pos > -3 && pos < 3) {
        if (rand.nextInt(2) == 0) {
            pos++;
            if (pos > 0) {
                max = pos;
            }
        } else {
            pos--;
        }
        System.out.println("position = " + (int) pos);

    }
    System.out.println("max position = " + max);
}


texts: Using a certain query field based on state

texts:
I need to be able to do a select to a table using a where clause that can use an email or phone field, depending on if they are set/not empty or not. Given this context, how can I simplify this PHP code?

 if(isset($email) && !empty($email) && isset($phone) && !empty($phone)){
        $partQuery = 'account_id = '.$account->id.' AND (phone = "'.(int)$phone.'" OR email = "'.$email.'")';
    }

    if(isset($phone) && !empty($phone)){
        $partQuery = 'account_id = '.$account->id.' AND phone = "'.(int)$phone.'"';
    }

    if(isset($email) && !empty($email)){
        $partQuery = 'account_id = '.$account->id.' AND email = "'. $email.'"';
    }


texts: Simple wrapper for PHP mysqli connection

texts:
I'm creating some web apis to sync some data between desktop/mobile apps.
Working on it, I wrote a simple wrapper for mysqli connection to simplify querying like:

// examples
$connection = new MySQLiConnection();

$connection->execute("INSERT INTO songs VALUES ('God\'s Plan', 'Drake')");
$connection->execute('INSERT INTO songs VALUES (?, ?)', 'Perfect', 'Ed Sheeran');

$result = $connection->getResult('SELECT * FROM songs');
var_dump($result);

$result = $connection->getResult('SELECT * FROM songs WHERE artist = ?', 'Ed Sheeran');
var_dump($result);

Code of the wrapper:

<?php

final class MySQLiConnection
{
    private $connection;

    public function __construct()
    {
        $this->connection = new mysqli('localhost', 'id', 'password', 'database');

        if ($this->connection->connect_errno)
        {
            throw new mysqli_sql_exception('Failed to open mysqli connection: ' . $this->connection->connect_error);
        }

        if (!$this->connection->set_charset('utf8'))
        {
            throw new mysqli_sql_exception('Failed to set utf8 character set: ' . $this->connection->error);
        }
    }

    public function __destruct()
    {
        if (!$this->connection->close())
        {
            throw new mysqli_sql_exception('Failed to close mysqli connection: ' . $this->connection->error);
        }
    }

    private function buildStatement(string $sql, ...$params) : mysqli_stmt
    {
        if ($statement = $this->connection->prepare($sql))
        {
            if (!empty($params))
            {
                $types = '';

                foreach ($params as $param)
                {
                    if (is_int($param))
                    {
                        $types .= 'i';
                    }
                    elseif (is_float($param))
                    {
                        $types .= 'd';
                    }
                    elseif (is_string($param))
                    {
                        $types .= 's';
                    }
                    else
                    {
                        $types .= 'b';
                    }
                }

                $statement->bind_param($types, ...$params);
            }

            return $statement;
        }

        throw new mysqli_sql_exception('Failed to prepare mysqli_stmt: ' . $this->connection->error);
    }

    public function execute(string $sql, ...$params) : void
    {
        $statement = $this->buildStatement($sql, ...$params);

        $success = $statement->execute();
        $statement->close();

        if (!$success)
        {
            throw new mysqli_sql_exception('Failed to execute mysqli_stmt: ' . $this->connection->error);
        }
    }

    public function getResult(string $sql, ...$params) : mysqli_result
    {
        $statement = $this->buildStatement($sql, ...$params);

        $success = $statement->execute();

        if ($success)
        {
            $result = $statement->get_result();

            $statement->close();
            return $result;
        }

        $statement->close();
        throw new mysqli_sql_exception('Failed to execute mysqli_stmt: ' . $this->connection->error);
    }
}

?>


texts: Sanitize input for a "robot on a grid" kata

texts:
I have the following piece of code which is FSI tested and works.
However, I want to trim it as much as possible (not only the comments, which are there for my own future reference) and make it as idiomatic as possible.

The gist of the code is the first step of the good ole' "Robot on a grid" kata: receive a path to a file holding strings, only some of which are valid commands.

Verify the path and sanitize the file, where for my needs "sanitize" means:

Remove all invalid strings (i.e. not valid commands).

Valid commands are defined in the active pattern in the code.

Remove all invalid placement commands, regardless of their position in the file.

Invalid in the sense that they place the robot outside the grid's bounds.

Once a valid placement command was found, remove all subsequent valid placement commands while keeping the first.

The async is there because I'm learning how to use it. It isn't material to the sanitation algorithm.

P.S. By "trim" I don't mean my (some would say) verbose function names. In the days of IDEs with IntelliSense and tab-completion, that's a non-issue for me and I much prefer clarity over succinctness.

open System.IO
open System.Text.RegularExpressions

let validatePathInsecurely filePath =
    match File.Exists filePath with
    // Decided to go with an exception since the path to the file is supplied to the function as a parameter, not queried from the user at runtime
    // so, if the path is wrong, there is no way of fixing it in runtime, and since the application can't operate a non-existing file... BOOM!
    | false -> failwith "Path specified is non existent, you don't have permissions or another error occured"
    | true -> filePath

let onlyOneCorretPlaceAsync xmax ymax filePath = async {
    // Tried using this code first:
    // ```
    // let allowedCommands =
    //     [ "place"; "advance"; "turn right"; "turn left" ]
    // ```
    // In hindsight this is wrong since the `place` command MUST also take a facing direction and X/Y coordinates (that may be any natural number).
    // We'll limit it to max 999-by-999 though, for this implementation.
    let (|AllowedCommands|_|) candidate =
        let pattern = Regex @"(place (?:north|south|east|west) \d{3} \d{3})|(advance)|(turn right)|(turn left)"
        let matches = pattern.Match candidate
        if matches.Success then matches.Groups.[1].Value.Trim() |> Some else None

    let onlyValidStrings filePath =
        File.ReadAllLines filePath
        |> Array.toList
        |> List.map (fun term -> term.ToLower())
        |> List.filter (fun term ->
                match term with
                | AllowedCommands term -> true
                | _ -> false)

    let sanitizeToFirstValidPlacement (content: string list) =
        content |> List.skipWhile (fun elem ->
                                        // By now we KNOW all strings in the file are valid-looking strings, however placement command might be invalid due to bounds.
                                        // No command is valid before the robot has been placed in a valid position!
                                        let splitElement = elem.Split()
                                        splitElement.Length <> 4 ||
                                        (int)(Array.item 2 splitElement) > xmax ||
                                        (int)(Array.item 3 splitElement) > ymax)

    let h::t = (onlyValidStrings filePath |> sanitizeToFirstValidPlacement)
    let sanitizeRestOfList (rest: string list) =
        rest
        |> List.filter (fun elem ->
                            Array.item 0 (elem.Split()) <> "place")

    let completeSanitizedList = h :: sanitizeRestOfList t

    return completeSanitizedList
}


texts:
I'm totally hooked on CodeEval, and one of the problems on there caught my attention. Here it is, copied from here:

Challenge Description:

Flavius Josephus was a famous Jewish historian of the first century, at the time of the destruction of the Second Temple. According to legend, during the Jewish-Roman war he was trapped in a cave with a group of soldiers surrounded by Romans. Preferring death to capture, the Jews decided to form a circle and, proceeding around it, to kill every j'th person remaining until no one was left. Josephus found the safe spot in the circle and thus stayed alive.Write a program that returns a list of n people, numbered from 0 to n-1, in the order in which they are executed.
Input sample:

Your program should accept as its first argument a path to a filename. Each line in this file contains two comma separated positive integers n and m , where n is the number of people and every m'th person will be executed. e.g.

10,3
5,2

Output sample:

Print out the list of n people(space delimited) in the order in which they will be executed. e.g.

2 5 8 1 6 0 7 4 9 3
1 3 0 4 2

Here's my solution in JavaScript, which succeeded in all test cases:

var fs  = require("fs"); //object for reading in a file
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
    if (line != "") {
        var lineSplit = line.split(",");
        var maxNum = parseInt(lineSplit[0], 10); //the number of people in the circle (n)
        var spacer = parseInt(lineSplit[1], 10); //Every m'th person is executed
        var counter = spacer - 1; //We're working with a zero-based array, so decrement accordingly
        var people = [];
        var deadPeople = [];
        for (var i = 0; i < maxNum; i++) {
            var person = [];
            person = new Array(i.toString(), 1);
            people[i] = person; //a new person is added with a status of 1 (alive)
        }

        while(deadPeople.length < maxNum){
            people[counter][1] = 0; //sadness
            deadPeople.push(people[counter][0]);
            counter += spacer;
            while(people.length > 0 && counter >= people.length){
                counter = counter - people.length;
                regroup(people);
            }
        }

        console.log(deadPeople.join(" "));
    }
});

function regroup(arr) {
    arr.forEach(function(element, index, array) {
        if (element[1] === 0) {
            array.splice(index, 1);
        }
    });
}

All comments are welcome, but I'm especially interested in efficiency.


texts: Compare the index of each char in a string in an alphabet array to a range of numbers

texts:
I saw this codegolf challenge and I set out to try and write a solution for it. I'm nowhere near an expert codegolfer (or programmer), but it was an interesting exercise.

Now I'm wondering how to improve my code, as it feels really bulky (especially compared to some of the answers to the challenge). Note that I'm not looking for ways to golf this code, I'm merely looking for general improvements and optimizations, hints and tips.

I hope the title is clear as to what the program does, it was pretty hard to describe!

Anyway, what my program does is pretty simple:

It accepts a string as input
It then fetches the index of each char in the string from the array
It checks if that char is within a certain range
Each range corresponds with a classic mobile phone button (0,1,2 = A,B,C)
The current button is compared to the previously used button
If the buttons match, the string does not pass and it returns false

My code:

int previousButton = -1;

char[] letters =
{
    'a', 'b', 'c',       // 2
    'd', 'e', 'f',       // 3
    'g', 'h', 'i',       // 4
    'j', 'k', 'l',       // 5
    'm', 'n', 'o',       // 6
    'p', 'q', 'r', 's',  // 7
    't', 'u', 'v',       // 8
    'w', 'x', 'y', 'z',  // 9
    ' '                  // 0
};

for (int i = 0; i < line.Length; i++) {
    char currentLetter = line[i];
    int index = Array.IndexOf(letters, currentLetter);
    int currentButton = 1;

    if (index >= 0 && index <= 2) {
        currentButton = 2;
    } else if (index >= 3 && index <= 5) {
        currentButton = 3;
    } else if (index >= 6 && index <= 8) {
        currentButton = 4;
    } else if (index >= 9 && index <= 11) {
        currentButton = 5;
    } else if (index >= 12 && index <= 14) {
        currentButton = 6;
    } else if (index >= 15 && index <= 18) {
        currentButton = 7;
    } else if (index >= 19 && index <= 21) {
        currentButton = 8;
    } else if (index >= 22 && index <= 25) {
        currentButton = 9;
    } else if (index == 26) {
        currentButton = 0;
    }

    if (previousButton == currentButton) {
        return false;
    }

    previousButton = currentButton;
}

return true;


texts: Here's my interface, so call me ...maybe

texts:
I'm inspecting VBA code to find obsolete code constructs - namely explicit Call statements, like this:

Call DoSomething(42)

The "correct" code construct would be to omit the Call token and drop the parentheses - my code locates the obsolete Call statements and rewrites them like this:

DoSomething 42

I have an IdentifierReference class, which I'm using to store the context of various identifier references throughout the VBA code I'm parsing. In order for my code inspection to easily locate method calls that use the obsolete Call syntax, I have added this method to the IdentifierReference class:

public bool HasExplicitCallStatement()
{
    try
    {
        var call = ((dynamic)Context.Parent).CALL();
        return call != null && call.Symbol.Text == Tokens.Call;
    }
    catch (Exception)
    {
        return false;
    }
}

But I didn't like having to handle exceptions here, so I rewrote it in a more strongly-typed way, like this:

public bool HasExplicitCallStatement()
{
    var memberProcedureCall = Context.Parent as VBAParser.ECS_MemberProcedureCallContext;
    var procedureCall = Context.Parent as VBAParser.ECS_ProcedureCallContext;

    return HasExplicitCallStatement(memberProcedureCall)
        || HasExplicitCallStatement(procedureCall);
}

private bool HasExplicitCallStatement(VBAParser.ECS_MemberProcedureCallContext context)
{
    if (context == null)
    {
        return false;
    }
    var statement = context.CALL();
    return statement != null && statement.Symbol.Text == Tokens.Call;
}

private bool HasExplicitCallStatement(VBAParser.ECS_ProcedureCallContext context)
{
    if (context == null)
    {
        return false;
    }
    var statement = context.CALL();
    return statement != null && statement.Symbol.Text == Tokens.Call;
}

And now I wonder... is this really an improvement?

Is there any more elegant way of dealing with different types that should be sharing an interface but aren't? ECS_ProcedureCallContext and ECS_MemberProcedureCallContext are ANTLR-generated types, nested in the VBAParser class, generated from the grammar file I'm using.


texts: Defining a Constructor In an Interface Java?

texts:
I have multiple different implementations of an object, which implement this custom interface I made called Board.

Board contains a method that looks like the following

public void ConvertFromString(String formattedString);

Each object implementing Board calls ConvertFromString() in its constructor.

Looks like the following.

public void BoardImpl1 implements Board
{
    public Board(string B)
    {
        ConvertFromString(b);
    }

    public void ConvertFromString(String formattedString)
    {
        //do some parsing on string and set up the BoardImpl properties
    }
}

ConvertFromString being public causes a warning, so the best practice workaround would be to make BoardImpl final. Is there a better way to write this?


texts: HLSL Shader Model 4: Is there a way to avoid pixel shader computing all code paths?

texts:
I have a pixel shader that needs to output either a plain colored pixel or a texel sampled from one of three textures - selected by a switch statement operating on an index fed in by the vertex shader:

// textures

tbuffer textures
{
    SamplerState                            sState;

    Texture2DArray                          system;
    Texture2DArray                          images;
    Texture2DArray                          render;
};

// input

struct ps_in
{
    float4                                  position    : SV_POSITION;
    nointerpolation float4                  color       : COLOR;
    nointerpolation uint                    atlas       : ATLAS;
    nointerpolation float                   slice       : SLICE;
    float2                                  texcoord    : TEXCOORD;
};

// shader

float4 main(ps_in input) : SV_TARGET
{
    [forcecase] switch (input.atlas)
    {
    case 1:
        return input.color * system.Sample(sState, float3(input.texcoord, input.slice));
    case 2:
        return input.color * images.Sample(sState, float3(input.texcoord, input.slice));
    case 3:
        return input.color * render.Sample(sState, float3(input.texcoord, input.slice));
    default:
        return input.color;
    }
}

It seems that the shader is computing all 4 code paths every time the shader is called. If there had been a way to make an array of Texture2DArrays, I could have indexed into it via the input.atlas variable and gotten rid of the switch, but apparently there isn't.

Each object in this system is a quad instance and the atlas is guaranteed to stay the same across each individual quad. Is there a better way to do this? The entire screen redraw has to be done in one draw call, so I cannot split this into 4 different pixel shaders.


texts:
I've hacked together some code to read the content from a sequence of files:

let fileContents =
    [ "filename1"; "filename2"; "etc" ]
    |> Seq.map(fun file -> async {
        use fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)
        let data = Array.create(int fs.Length) 0uy
        let! _ = fs.AsyncRead(data, 0, data.Length)
        return data
    })
    |> Async.Parallel
    |> Async.RunSynchronously
    |> Seq.map System.Text.Encoding.ASCII.GetString

It works, but I'm not really sure about it. For one thing, is async actually giving me any benefit here? Also inside the async function I need to wait for AsyncRead to finish, but I don't need the returned value from it. Is there a better way of doing this than let! _ = ...?


texts:
I'm making a simple container class for fun and education, but my rebuilding/resizing method seems rather inefficient.  Is there an easier way to do this?

// If FromFront is true, cells should be added or
// subtracted from the front of the array rather than the back.
void Rebuild(std::size_t NewSize, bool FromFront = false)
{
    const std::size_t OldSize = Size;
    Size = NewSize; // Size is used in other methods.

    Datatype* TemporaryStorage = new Datatype[OldSize]; // Allocate space for the values to be preserved while a new main array is made.

    for (std::size_t Index = 0; Index < OldSize; Index++) TemporaryStorage[Index] = BasePointer[Index]; // Copy values over to the temporary array.

    delete[] BasePointer; // Delete the main array...
    BasePointer = new Datatype[NewSize]; // ...And rebuild it with the appropriate size.

    for (std::size_t Iteration = 0; (Iteration < OldSize) && (Iteration < NewSize); Iteration++)
    {
        std::size_t BasePointerIndex = Iteration;
        std::size_t TemporaryStorageIndex = Iteration;

        if (FromFront) // We need to take special measures to give the indices offsets.
        {
            if (NewSize > OldSize) BasePointerIndex += (NewSize - OldSize);
            else TemporaryStorageIndex += (OldSize - NewSize);
        }

        BasePointer[BasePointerIndex] = TemporaryStorage[TemporaryStorageIndex]; // Copy values from the temporary array to the new main array.
    }

    delete[] TemporaryStorage; // Finally, delete the temporary storage array.
}


texts:
I solved this problem on LeetCode

  Given two binary trees and imagine that when you put one of them to
  cover the other, some nodes of the two trees are overlapped while the
  others are not.

  You need to merge them into a new binary tree. The merge rule is that
  if two nodes overlap, then sum node values up as the new value of the
  merged node. Otherwise, the NOT null node will be used as the node of
  new tree.

Example 1:
Input:
  Tree 1                     Tree 2
          1                         2
         / \                       / \
        3   2                     1   3
       /                           \   \
      5                             4   7
Output:
Merged tree:
       3
      / \
     4   5
    / \   \
   5   4   7

  Note: The merging process must start from the root nodes of both trees.

The code that I had written is.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public enum Direction
    {
        Left, Right, None
    }
    public TreeNode doMerge(TreeNode t1, TreeNode t2, Direction direction, TreeNode t3)
        {
            if(t1 == null && t2 == null)
            {
                return t3;
            }
            if(t1 == null || t2 == null)
            {
                TreeNode notNullTree = t1 == null ? t2 : t1;
                switch(direction)
                {
                    case Direction.None:
                        return notNullTree;
                    case Direction.Left:
                        t3.left = notNullTree;
                        break;
                    case Direction.Right:
                        t3.right = notNullTree;
                        break;
                }
                return t3;
            }
            var newNode = new TreeNode(t1.val + t2.val);
            switch (direction)
            {

                case Direction.None:
                    t3 = newNode;
                    break;
                case Direction.Left:
                    t3.left = newNode;
                    t3 = t3.left;
                    break;
                case Direction.Right:
                    t3.right = newNode;
                    t3 = t3.right;
                    break;
            }
            doMerge(t1.left, t2.left, Direction.Left, t3);
            doMerge(t1.right, t2.right, Direction.Right, t3);
            return t3;
        }
        public TreeNode MergeTrees(TreeNode t1, TreeNode t2)
        {
            return doMerge(t1, t2, Direction.None, null);
        }
}

The code has a lot of conditionals which could be refactored. Any suggestion on making the code a bit cleaner and concise would be helpful.


texts: Blade (similar to Jade) template with SCSS

texts:
I have this blade template with a main.scss file:

include "layout.blade"
replace block page
    ul.brand(data-orbit data-options="animation:slide;\
         pause_on_hover:true;\
         animation_speed:500;\
         slide_number:false;\
         navigation_arrows:false;\
         bullets:false;\
         swipe:true;")
        li.cta
            .row.slide
                .large-5.columns
                    i.icon-continental-logo
                    h1="Continental Collection"
                    h2="Quality Garments, Responsibly Sourced"
                    a(href="/")="Discover Continental"
                .large-7.columns
                    img.shadow(src="/images/slider/continental_duo_shadow.jpg")
                    img.figure(src="/images/slider/continental_duo.png")
        li.salvage
            .row.slide
                .large-5.columns
                    i.icon-salvage-logo
                    h1="Salvage Collection"
                    h2="A new range of clothing, 100% Recycled"
                    a(href="/")="Discover Salvage"
                .large-7.columns
                    img.shadow(src="/images/slider/salvage_duo_shadow.jpg")
                    img.figure(src="/images/slider/salvage_duo.png")

main.scss

$header-font-family: "Roboto Condensed", "Arial", "sans-serif";
// Primary colors
$ccc-color-ccc            : rgb(137,0,0); // #89000, darkbrown
$ccc-color-continental    : rgb(60,113,145); // #3C7191, blue
$ccc-color-earthpositive  : rgb(0,151,95);  // #00975F, green
$ccc-color-salvage        : rgb(205,113,38);  // #CD7126, brown

@mixin collection($main-color) {
  color: $main-color;
}

h1, h2, h3 {
  font-family: $header-font-family;
  margin-bottom: 20px;
}

ul.brand {
  i {
    font-size: 50px;
  }
  a {
    display: table;
    padding: 10px 15px;
    min-width: 230px;
    font-weight: 700;
    text-transform: uppercase;
    line-height: 1;
    margin: 20px auto;
    text-align: center;
    cursor: pointer;
    @include single-transition($ease:0.2s) {
      transition-delay: $ease;
    };
    &:hover {
      -webkit-box-shadow: 0px 0px 0px 10px #BCBCBC;
      -moz-box-shadow:    0px 0px 0px 10px #BCBCBC;
      box-shadow:         0px 0px 0px 10px #BCBCBC;
      color: #FFF;
      }
    }
  li.cta {
    i, h1, h2, a {
      @include collection($ccc-color-continental)
    }
    a {
      border: 1px solid $ccc-color-continental;
      &:hover {
        background-color: $ccc-color-continental;
        color: #FFF;
      }
    }
  }
  li.salvage {
    i, h1, h2, a {
      @include collection($ccc-color-salvage)
    }
    a {
      border: 1px solid $ccc-color-salvage;
      &:hover {
        background-color: $ccc-color-salvage;
        color: #FFF;
      }
    }
  }
}

I am trying to figure out how best to deal with the a, h1, h2 and i block within the li.


texts: Doubly linked list using C++ and templates

texts:
Working doubly linked list using C++ and templates, I tried to make it by myself. I tried to use head and tail as buffers and make a simple implementation. Please help me understand what I have done wrong, done good and could have done worse.

#pragma once
#include <iostream>

template <typename T>
struct node
{
    T value;
    node* prev = nullptr;
    node* next = nullptr;
};

template <typename T>
class LList
{
public:
    LList<T>();
    ~LList();
    T& get(const int& pos) const;
    void insert(const T& value, const int& pos);
    T& remove(const int& pos);
private:
    int n_elements;
    node<T> *head = new node<T>;
    node<T> *tail = new node<T>;

};

template<typename T>
LList<T>::LList()
{
    n_elements = 0;
    head->next = tail;
    tail->prev = head;
}

template<typename T>
LList<T>::~LList()
{
}

template<typename T>
T& LList<T>::get(const int & pos) const
{
    node<T> *temp = head;
    for (int i = 0; i <= pos; i++)
        temp = temp->next;
    return temp->value;
}

template<typename T>
void LList<T>::insert(const T & value, const int & pos)
{
    node<T> *temp = new node<T>;
    temp->value = value;
    node<T> *prev = head;
    node<T> *next = head->next;

    for (int i = 0; i < pos; i++)
    {
        prev = prev->next;
        next = next->next;
    }
    prev->next = temp;
    next->prev = temp;
    temp->prev = prev;
    temp->next = next;
    ++n_elements;
}

template<typename T>
T & LList<T>::remove(const int & pos)
{
    node<T> *prev = head;
    node<T> *curr = head->next;
    node<T> *next = curr->next;
    for (int i = 0; i < pos; i++)
    {
        prev = prev->next;
        curr = curr->next;
        next = next->next;
    }
    prev->next = next;
    next->prev = prev;
    T value = curr->value;
    delete curr;
    --n_elements;
    return value;
}

#include <iostream>
#include "LList.h"

int main()
{
    LList <double> mylist;
    mylist.insert(20, 0);
    mylist.insert(30, 1);
    mylist.insert(40, 2);
    mylist.insert(30, 2);
    mylist.insert(10, 0);
    std::cout << "removing: " << mylist.remove(0) << std::endl;
    mylist.insert(10, 0);
    mylist.insert(10, 0);
    mylist.insert(10, 0);
    std::cout << "removing: " << mylist.remove(3) << std::endl;
    std::cout << "removing: " << mylist.remove(2) << std::endl;
    std::cout << "removing: " << mylist.remove(1) << std::endl;
    std::cout << mylist.get(0) << std::endl;
    std::cout << mylist.get(1) << std::endl;
    std::cout << mylist.get(2) << std::endl;
    std::cout << mylist.get(3) << std::endl;

    system("pause");
    return 0;
}


texts: Printing an arrow of asterisks in Haskell

texts:
This code will print an arrow of asterisks, like:

*
**
***
****
***
**
*

raisingAsterisks, decreasingAsterisks, arrow :: Int -> [String]
raisingAsterisks n = take n $ iterate ('*' :) "*"
decreasingAsterisks = reverse . raisingAsterisks
arrow n = raisingAsterisks n ++ (tail (decreasingAsterisks n))

main :: IO()
main = mapM_ putStrLn $ arrow 4


texts: Calculate Hand Value in a Blackjack Hand

texts:
I have built a Blackjack simulator in Python. I need to decrease the execution time. I have used a profiler to identify key bottlenecks in the execution.
The following function is responsible for about 15% of the total run time.

def value(self):
    value = 0
    has_ace = False

    for card in self.cards:
        value += card.value

        if card.rank == "A":
            has_ace = True

    if has_ace and value <= 11:
        value += 10

    return value

The above function is used to calculate the score of a hand.
A hand can have multiple cards.
A card has a value and a rank.

In Blackjack, an Ace can be worth 1 or 11.

Is there a better way to go?


texts:
I have a function that converts any normal true-type font to my own font file .bff
That function works correct and am not going to post that function for that matter
(the function is also only compatible with a specific engine you may not hear about).

If I post the .bff file and you have an environment in which you could use putpixel(x, y) to put a pixel (for e.g a red one) on the x and y spot, then you can also test my rendering function.

Let me first explain my custom compression method:

I call "Arlo compression" vername "Arlo1" with compression level over 60%. You have to understand the compression before take a look at the rendering function.

Standart characters (dec 48+) to represent whitespaces.
5 will represent 5 spaces and so forth
After each space a pixel is placed. So if there is 00 it puts two pixels right next to each other if there is 20 it puts 1 pixel after 2 spaces and one pixel as a next.
Important: to prevent a vertical line after each character the rendering function is made to not put pixel after the last space-representing character of the line determined (that is what causes problems - some characters needs a pixel at the end and it renders them cropped (without these last pixels) thanks to the vertical-line prevention condition.
# character found in the bff means new line of the character
& character found in the bff means offset for next character
Characters are with ascii sequence, dec32-126

The function:

typedef unsigned char BYTE;

void
bitfox_render_text
(char *FONTNEX, char *STRING, int X_OFFSET, int Y_OFFSET)
{
    FILE* fp = fopen(FONTNEX, "r");
    char *buffer = STRING, *font;
    int fontsize, buffsize = strlen(buffer), strl;
    int line = 0, linep = 0, colp = 0;

    fseek(fp, EOF, SEEK_END);
    fontsize = ftell(fp);
    font = malloc(fontsize);
    rewind(fp);
    fread(font, sizeof(BYTE), fontsize, fp);
    fclose(fp);

    for(strl=0; strl<buffsize; strl++)
    {
        int chrOffset, chr = 32;

        // In-line code for finding the current index of characters
        for(chrOffset=0; chr != buffer[strl]; chrOffset++) { if(font[chrOffset] == '&') { chr++; }} // <--

        do
        {   linep++;
            if
            (font[chrOffset+linep] == '#') { colp++; line = 0; }
            else if
            (font[chrOffset+(linep+1)] != '#')  // if not NL and w/o ending supplement:
            {
                // there is a function that describes size and color of the brush here
                putpixel(X_OFFSET+(line+=(font[chrOffset+linep]-48)+1), Y_OFFSET+colp);
            }
        } while(font[chrOffset+(linep+1)] != '&');
    }
    free(font);
}

The function currently reads successfully only one character passed as a string. Don't mind the arguments currently not used. Despite the fact that this function is not fully functional.. the only problem is the condition:
(font[chrOffset+(linep+1)] != '#')  // if not NL and w/o ending supplement
It prevents for putting pixels at the end of each line.
If i remove that condition.. there will be a vertical line at the end of each character.. if it remains, some characters that need these pixels will be rendered cropped.

I will be doing constant edits to improve the level of clarification. Here is the download link of the .bff that response for the .ttf file "arial.ttf size 11 Normal".

Summary: The .bff file or "Bitfox Font File" is a custom font file, with custom compression method impiled ("Arlo1"). Each character from the ascii in the range of 32 to 126 in sequence is represented in raster-type where # determines there is a new line and & determines next character. To indicate where is a pixel placed, the current character's data consists of ascii characters (dec48-126) that represent whitespaces. The pixel is placed after the sapce is determined with chr-48. For the sake of the unrequired pixels prevention, the rendering function won't place pixels when the last character of the line is readed. That causes some characters to be cropped with 1 pixel at their end.


texts: digital clock in java using calendar class

texts:
I am able to make the clock layout and get the time but I don't understand how to continuously update the time.
I made the layout using Java labels and I have to change their texts continuously
calendar=Calendar.getInstance();
frame =new JFrame();
panel= new JPanel();

  hour=calendar.get(Calendar.HOUR);
minute=calendar.get(Calendar.MINUTE);
second=calendar.get(Calendar.SECOND);

a calendar is the name of my Calendar object


texts:
I have been working on where I want to improve my knowledge to do a safe JSON scraping. By that is that I could pretty much do a ugly workaround and wrap it into a try-except but that is not the case. I would like to know where it goes wrong and how I can improve the code I have been working with:
import json
from json import JSONDecodeError

import requests

payload = {
    "name": None,
    "price": None,
    "sizes": None
}

headers = {'origin': 'https://www.aplace.com', 'Content-Type': 'application/json'}
with requests.get("http://api.aplace.com/sv/dam/aaltoili-iso-mehu-gren-red-sand", headers=headers) as response:
    if not response.ok:
        print(f"Requests NOT ok -> {payload}")

    try:
        # They added extra comma to fail the JSON. Fixed it by removing duplicate commas
        doc = json.loads(response.text.replace(",,", ",")).get("productData", {})
    except (JSONDecodeError, KeyError, ValueError) as err:
        print(f"Not able to parse json -> {err} -> Payload: {payload}")
        raise

if doc:

    product_name = doc.get('name', {})
    product_brand = doc.get('brandName', {})
    product_price = doc.get('markets', {}).get('6', {}).get('pricesByPricelist', {}).get('3', {}).get('price', {})

    # Added exception incase the [0] is not able to get any value from 'media'
    try:
        product_image = doc.get('media', {})[0].get('sources', {}).get('full', {}).get('url', {})
    except KeyError:
        product_image = None

    product_size = doc.get('items', {})

    try:

        if product_name and product_brand:
            payload['name'] = f"{product_brand} {product_name}"

        if product_price:
            payload['price'] = product_price.replace('\xa0', '')

        if product_image:
            payload['image'] = product_image

        if product_size:

            count = 0
            sizes = []
            sizesWithStock = []
            for value in product_size.values():
                if value.get('stockByMarket', {}).get('6', {}):
                    count += value['stockByMarket']['6']
                    sizes.append(value['name'])
                    sizesWithStock.append(f"{value['name']} - ({value['stockByMarket']['6']})")

            payload['sizes'] = sizes
            payload['sizesWithStock'] = sizesWithStock
            payload['stock'] = count

    except Exception as err:
        print("Create notification if we hit here later on")
        raise

print(f"Finished payload -> {payload}")

My goal here is to cover all the values and if we do not find it inside the json then we use the if statements to see if we have caught a value or not.
Things that annoys me:

Long nested dicts but im not sure if there is any other way, is there a better way?
try-except for product_image, because its a list and I just want to grab the first in the list, is it possible to skip the try-except?
If unexpected error happens, print to the exception but am I doing it correctly?

Hopefully I can get new knowledge from here :)


texts: A custom session with transaction support using Dapper

texts:
I wanted to write a custom session to act as proxy for a Dapper connection that could support transactions without having to expose any other DB related entities.

At first, I thought of opening a connection upon creation of the session and keeping it open for the whole life of the instance. As I researched about the subject, I've learned that opening and closing the connections as needed would yield better performance because of the connection pool implemented by ADO.NET. So I tried the following implementation:

public class DBSession : IDisposable
{
    private readonly IConnectionFactory _connectionFactory;

    private IDbConnection _activeConnection;
    private IDbTransaction _activeTransaction;

    public DBSession(IConnectionFactory connectionFactory)
    {
        _connectionFactory = connectionFactory;
    }

    private void PreExecuteSingleStatement()
    {
        //Open DB connection if no transaction is open.
        if (_activeTransaction != null)
            return;

        _activeConnection = _connectionFactory.GetOpenConnection();
        if (_activeConnection.State != ConnectionState.Open)
            _activeConnection.Open();
    }

    private void PostExecuteSingleStatement()
    {
        //Close DB connection if no transaction is open.
        if (_activeTransaction != null)
            return;

        if (_activeConnection.State == ConnectionState.Open)
            _activeConnection.Dispose();
        _activeConnection = null;
    }

    public void BeginTransaction()
    {
        if (_activeTransaction != null)
            throw new InvalidOperationException("Não é possível criar uma nova transação pois já há uma transação aberta.");

        if (_activeConnection == null)
            _activeConnection = _connectionFactory.GetOpenConnection();

        if (_activeConnection.State != ConnectionState.Open)
            _activeConnection.Open();

        _activeTransaction = _activeConnection.BeginTransaction();
    }

    public void CommitTransaction()
    {
        if (_activeTransaction == null)
            throw new InvalidOperationException("Não é possível comitar uma transação pois não há nenhuma transação aberta.");
        _activeTransaction.Commit();

        _activeTransaction.Dispose();
        _activeTransaction = null;
        _activeConnection.Dispose();
        _activeConnection = null;
    }

    public void RollbackTransaction()
    {
        if (_activeTransaction == null)
            throw new InvalidOperationException("Não é possível dar rollback numa transação pois não há nenhuma transação aberta.");
        _activeTransaction.Rollback();

        _activeTransaction.Dispose();
        _activeTransaction = null;
        _activeConnection.Dispose();
        _activeConnection = null;
    }

    public void Insert<T>(T value)
    {
        if (value == null)
            throw new ArgumentNullException(nameof(value));

        PreExecuteSingleStatement();
        _activeConnection.Insert<T>(value);
        PostExecuteSingleStatement();

    }

    public void Dispose()
    {
        if (_activeTransaction != null)
        {
            _activeTransaction.Rollback();
            _activeTransaction.Dispose();
            _activeTransaction = null;
        }

        if (_activeConnection != null)
            _activeConnection.Dispose();
    }
}

IConnectionFactory code:

internal interface IConnectionFactory
{
    IDbConnection GetOpenConnection();
}

For now, I only implemented an Insert method. I plan to write other methods for different operations that will follow almost the same steps as this method.

This code seems somewhat convoluted to me. Lots of checks makes it look very hack-y.

Is there a better way to approach this problem?


texts:
I've seen this today on a mock interview and wanted to give it a try. I'd love to hear some feedback from you guys. This is my second attempt at the problem, initially I had a mess of if/else towers and nested loops.

/*
 * Write a function that takes two strings s1 and s2 and returns the
 * longest common subsequences of s1 and s2.
 *
 * Examples:
 * s1: ABAZDC s2: BACBAD  result: ABAD
 * s1: AGGTAB s2: GXTXAYB result: GTAB
 * s1: aaaa   s2: aa      result: aa
 * s1: aaaa   s2: ''      result: ''
 */
public class LongestSubsequence {

  public static void main(String[] args) {
    LongestSubsequence ls = new LongestSubsequence();

    assertEquals("ABAD", ls.solve("ABAZDC", "BACBAD"));
    assertEquals("GTAB", ls.solve("AGGTAB", "GXTXAYB"));
    assertEquals("aa", ls.solve("aaaa", "aa"));
    assertEquals("", ls.solve("aaaa", ""));
    assertEquals("ABAD", ls.solve("BACBAD", "ABAZDC"));
    assertEquals("aaaa", ls.solve("bcaaaa", "aaaabc"));
    assertEquals("aaaa", ls.solve("bcaaaade", "deaaaabc"));
  }

  private String solve(String s1, String s2) {
    if (s1.length() == 0 || s2.length() == 0) {
      return "";
    }

    String subSeq1 = getLongestSubsequence(s1, s2);
    String subSeq2 = getLongestSubsequence(s2, s1);
    return (subSeq1.length() >= subSeq2.length() ? subSeq1 : subSeq2);
  }

  private String getLongestSubsequence(String first, String second) {
    String retValue = "";
    int currentIndex = 0;
    for (int remaining = first.length(); retValue.length() < remaining; remaining--) {
      StringBuilder firstWorker = new StringBuilder(first.substring(currentIndex));
      StringBuilder secondWorker = new StringBuilder(second);
      StringBuilder possibleSequence = new StringBuilder();
      while (firstWorker.length() > 0 && secondWorker.length() > 0) {
        String ch = firstWorker.substring(0, 1);
        int firstIndex = secondWorker.indexOf(ch);
        if (firstIndex != -1) {
          possibleSequence.append(ch);
          secondWorker.delete(0, firstIndex + 1);
        }
        firstWorker.delete(0, 1);
      }
      if (possibleSequence.length() > retValue.length()) {
        retValue = possibleSequence.toString();
      }
      currentIndex++;
    }

    return retValue;
  }

}


texts:
I'd like to know if it's ok to write like this or there is a better, prettier way to do this. The merging itself is ok. I'm more interested in dealing with the situation when one of the arrays is finished and I need to copy the rest of the other array to the result array. I wrote it in a try catch block.

int[] result = new int[fst.length + snd.length];
int fstIndex = 0;
int fstIndexValue = 0;
int sndIndex = 0;
int sndIndexValue = 0;

while (fstIndex + sndIndex != result.length) {

    try{
        fstIndexValue = fst[fstIndex];
    }catch( java.lang.ArrayIndexOutOfBoundsException e) {
        System.arraycopy(snd, sndIndex, result, fstIndex + sndIndex, snd.length - sndIndex);
        break;
    }

    try{
        sndIndexValue = snd[sndIndex];
    }catch( java.lang.ArrayIndexOutOfBoundsException e) {
        System.arraycopy(fst, fstIndex, result, fstIndex + sndIndex, fst.length - fstIndex);
        break;
    }

    if (fstIndexValue < sndIndexValue) {
        result[fstIndex + sndIndex] = fst[fstIndex++];
    } else {
        result[fstIndex + sndIndex] = snd[sndIndex++];
    }
}
return result;


texts: Generating random number from a binomial distribution

texts:
In my application of Monte Carlo simulation, the crucial part is to generate a random number from a binomial distribution with parameters n = size and p = 0.5. Here is my current implementation

#include <stdio.h>
#include <stdint.h>
#include <x86intrin.h>

int64_t rbinom(int64_t size) {
    if (!size) {
        return 0;
    }

    int64_t result = 0;
    while (size >= 64) {
        uint64_t random64;
        while (!_rdrand64_step(&random64)) {
            fprintf(stderr, "HW_RND_GEN not ready\n");
        }
        result += _popcnt64(random64);
        size -= 64;
    }

    uint64_t random64;
    while (!_rdrand64_step(&random64)) {
        fprintf(stderr, "HW_RND_GEN not ready\n");
    }
    result += _popcnt64(random64 & ~(UINT64_MAX << size));

    return result;
}

However, the result of benchmarking terrifies me:

I'm spending 99.68% of the runtime on this function! How can I optimize it?

The result doesn't need to be cryptographically secure, as long as it's good enough for Monte Carlo simulations.


texts: Recursive Fibonacci in Rust with memoization

texts:
I'm trying to come up with an "elegant" way of calculating Fibonacci for number in Rust, using recursion and memoization (self-imposed requirements).

This is what I have so far:

fn fib(n: usize, memo: &mut [Option<usize>]) -> usize {
    memo[n].map(|v| v).unwrap_or_else(|| {
        let result = {
            if n > 1 {
                fib(n - 1, memo) + fib(n - 2, memo)
            } else {
                1
            }
        };
        memo[n] = Some(result);
        result
    })
}

fn main() {
    let number = 46;
    let mut memo: Vec<Option<usize>> = vec![None; number + 1];
    println!("{}", fib(number, &mut memo));
}

My cache in this implementation is just a slice of optional values, if the position contains Some(x) that's a cache hit, otherwise, in a closure, compute the value, passing the cache along, and just before returning the value save it as a Some(v) in the cache.

I figured that setting up a cache this way would make writes faster, since the memory is already allocated.

Can it be made faster? Or cleaner/more readable?


texts:
I'm just learning functional programming in JavaScript using Ramda.
I took this tutorial and implemented the server core.js component using Ramda.

The idea is that we'll have a collection of things to vote from: Movies, songs, programming languages, Horse JS quotes, anything. The app will put them against each other in pairs, so that on each round people can vote for their favorite of the pair. When there's just one thing left, that's the winner.

I attempted to use the point-free style as much as possible as I found this really forced me to avoid writing imperative code. I also avoided making any changes to the data structure defined by the tutorial though I felt that doing so could have potentially simplified some things quite a bit.  In real projects we can't always change an API.
Here is the data structure used:

(source: teropa.info)
Here's my code:
const R = require('ramda');

// overCalculatedValue :: Lens s a -> ( s -> (a -> a)) -> ( s -> s)
const overCalculatedValue = R.curry( (lens, func) => {
  return R.converge( R.over(lens), [func, R.identity]);
});
// setCalculatedValue :: Lens s a -> ( s -> a) -> ( s -> s)
const setCalculatedValue = R.curry( (lens, func) => {
  return R.converge( R.set(lens), [func, R.identity]);
});

// createEntryTallyLens :: string -> Lens s a
const createEntryTallyLens = R.useWith( R.lensPath, [R.flip(R.append)(['vote', 'tally'])] );
// isVotingOnLastCandidates :: State -> boolean
const isVotingOnLastCandidates = R.compose( R.equals(0), R.length, R.prop('entries'));
// pickWinner :: [[string],number] -> [ string, number] -> [[string],number]
const pickWinner = R.curry( ( result, candidate ) => {
  return result[1] === candidate[1] ? [ R.append(candidate[0], result[0] ), result[1]] :
            result[1] < candidate[1] ? [ [candidate[0]], candidate[1] ] : result;
});
const NoWinner = [[],-Infinity];

// getWinnerList :: State -> [string]
const getWinnerList = R.compose( R.nth(0), R.reduce(pickWinner, NoWinner), R.toPairs(), R.path(['vote', 'tally']));
// isWinnerDetermined :: State -> boolean
const isWinnerDetermined = R.compose( R.equals(1), R.length, getWinnerList);
// getOverallWinner :: State -> string
const getOverallWinner = R.compose(R.nth(0), getWinnerList);
// getNextCandidates :: State -> [string]
const getNextCandidates = R.compose(R.take(2), R.prop('entries'));
// addWinnerToList :: State -> ([string]->[string])
const addWinnerToList = R.compose(R.flip(R.concat()), getWinnerList);

// createNewVote :: State -> State
const createNewVote = R.compose( R.over(R.lensProp('entries'), R.drop(2)), setCalculatedValue(R.lensPath(['vote', 'pair']), getNextCandidates), R.omit('vote'));
// addWinnerBackToEntries :: State -> State
const addWinnerBackToEntries = overCalculatedValue( R.lensProp('entries'), addWinnerToList);

// doesWinnerExist :: State -> boolean
const doesWinnerExist = R.allPass([isVotingOnLastCandidates, isWinnerDetermined]);
// declareWinner :: State -> State
const declareWinner = R.compose( R.omit(['entries', 'vote']), setCalculatedValue( R.lensProp('winner'), getOverallWinner));
// setupNextElection :: State -> State
const setupNextElection = R.compose( createNewVote, addWinnerBackToEntries);

// setEntries :: State -> [string] -> State
exports.setEntries = (state, entries) => {
  return R.set(R.lensProp('entries'), entries, state);
};

// vote :: State -> string -> State
exports.vote = ( state, entry ) => {
  return R.over( createEntryTallyLens(entry), R.compose(R.inc, R.defaultTo(0)), state);
};

// startNextVote :: State -> State
exports.startNextVote = R.ifElse(doesWinnerExist, declareWinner, setupNextElection);

My questions:

Is converge with set or over the correct way to update a value in an object that must be calculated from other values in the object?
Any other areas where this could be simplified or improved?


texts: Locking in MySQL stored procedure for deduplication

texts:
Multiple upstream servers are sending notifications to a load-balanced django app. If all the upstream servers are working correctly, the app will always receive duplicates of these notifications (since all the upstream notifiers should send the same notifications; it's just for redundancy). I want to be able to filter out these duplicates. However, since the python app is load-balanced, the only place we can check for these duplicates is in the database (unless we did distributed locking, etc, which sounds like more of a pain).

To do this, I'm hashing the messages, then invoking a stored procedure in the database that checks if a message received in the last 10 seconds had the same hash (I know about hash collisions; it's a risk). I want to be 99% sure the store procedure is safe against race conditions.

Here's the SQL code that seems to work:

DROP TABLE IF EXISTS openduty_dedup;
CREATE TABLE openduty_dedup (
  request_hash CHAR(40) NOT NULL UNIQUE PRIMARY KEY,
  triggered TIMESTAMP NOT NULL);

-- main procedure for checking if a notification is a duplicate
-- given the SHA-1 hash of a notification, it will return 1 if the
-- same notification was received in the last 10 seconds (and was not
-- treated as a duplicate then), otherwise it will return 0
DROP PROCEDURE IF EXISTS openduty_check_duplicate;
CREATE PROCEDURE openduty_check_duplicate(IN new_hash CHAR(40))
  BEGIN
    DECLARE last_trigger TIMESTAMP;
    DECLARE now TIMESTAMP;
    DECLARE is_duplicate INT;
    SELECT CURRENT_TIMESTAMP INTO now;
    DO GET_LOCK('openduty_check_duplicate', 10);
      SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
      START TRANSACTION;
        SELECT triggered FROM openduty_dedup WHERE request_hash = new_hash INTO last_trigger;
        IF last_trigger IS NULL THEN
          INSERT INTO openduty_dedup (request_hash, triggered) VALUES (new_hash, now);
          SELECT 0 INTO is_duplicate;
        ELSEIF DATE_SUB(now, INTERVAL 10 SECOND) > last_trigger THEN
          UPDATE openduty_dedup SET triggered = now WHERE request_hash = new_hash;
          SELECT 0 INTO is_duplicate;
        ELSE
          SELECT 1 INTO is_duplicate;
        END IF;
        DELETE FROM openduty_dedup WHERE DATE_SUB(now, INTERVAL 1 MINUTE) > triggered;
      COMMIT;
    DO RELEASE_LOCK('openduty_check_duplicate');
    SELECT is_duplicate;
  END;

I'm much more worried about correctness than performance since notifications will only come on the order of every few seconds. In particular, I'm worried that the commit won't happen until after the lock is released.

Will this work as intended?


texts: Checking for many alertable conditions before saving customer information

texts:
What's the best way to refactor this code? The method does a lot of checking before showing an alert. And the method is too long for my taste.

I'm thinking of extracting the checkers into their own methods, but I'm not sure how to handle multiple instances that call return.

- (IBAction)saveCustomer:(id)sender {
    @try {
        [self.view endEditing:YES];

        // Cannot save if customer is pending
        if ([self.service isWaitingForApproval]) {
            APAlert(WARNING_TITLE, NSLocalizedString(@"message.waiting-approval", nil));
            return;
        }

        // Check required field
        NSString *incompleteRequiredField = [self.service checkRequiredFields];
        if (incompleteRequiredField) {
            NSString *message = [NSString localizedStringWithFormat:NSLocalizedString(@"message.required field %@", nil), NSLocalizedString(incompleteRequiredField, nil)];
            APAlert(WARNING_TITLE, message);
            return;
        }

        if(![self.service isDistributorOrWholesalerInTW]) {
            incompleteRequiredField = [self checkRequireCellOTM];
            if(incompleteRequiredField) {
                NSString *message = [NSString localizedStringWithFormat:NSLocalizedString(@"message.required otm %@", nil), NSLocalizedString(incompleteRequiredField, nil)];
                APAlert(WARNING_TITLE, message);
                return;
            }
        }

        Country_Identifier countryID = (Country_Identifier)[self.service.customer.country_id integerValue];
        if (countryID == Country_Taiwan || countryID == Country_Thailand) {
            if (![self.service isHasContact]) {
                APAlert(WARNING_TITLE, ALERT_CONFRIM_HAVE_CONTACT);
                return;
            }
        }
        [[SomeManager alertViewManager] showAlertWithTitle:SAVING_TITLE
                                                                  message:SAVE_CUSTOMER_CONFIRM
                                                                   target:self
                                                               actionView:nil
                                                        cancelButtonTitle:YES_BUTTON_TITLE
                                                        otherButtonTitles:NO_BUTTON_TITLE
                                                                   andTag:AlertViewTag_Save];
    }
    @catch(NSException *exception) {
        [self sendException:exception];
    }
}


texts: Checking if an array can be rotated to equal another in JavaScript

texts:
I needed to write a function in JavaScript which checks if any rotation of an array is equal to another array.

By rotation, I mean:

rotate [1, 2, 3] --> [3, 1, 2]
rotate [3, 1, 2] --> [2, 3, 1]
rotate [2, 3, 1] --> [1, 2, 3]

Here's the code for my function. It feels pretty verbose, especially since the array functions added by ES6 seem perfect for this sort of thing, yet I've used very few of them. In particular, using a label on the outer loop feels wrong.

Is there any way I can make this function shorter and/or faster?

/**
 * Taking two arrays, checks whether one may be rotated so that it equals
 * the other.
 */
function arraysEqualByRotation(first, second) {
  if (first.length !== second.length) {
    return false;
  }

  // We'll rotate the first continually and compare it to the second
  var rotatedFirst = first.slice(0);

  outer:
  for (var rotateCounter = 0; rotateCounter < rotatedFirst.length; rotateCounter++) {
    // Rotate the array
    rotatedFirst.unshift(rotatedFirst.pop());

    // Check if their elements are equal
    for (var i = 0; i < rotatedFirst.length; i++) {
      if (rotatedFirst[i] !== second[i]) {
        // Try another rotation
        continue outer;
      }
    }

    // At this stage, they're equal
    return true;
  }

  // At this stage, a matching combination was never found
  return false;
}

Example inputs and outputs:

first      | second     | result
-----------------------------------------------
[1, 2, 3]  | [1, 2, 3]  | true (same array)
[1, 2, 3]  | [3, 1, 2]  | true (rotate once)
[1, 2, 3]  | [2, 3, 1]  | true (rotate twice)
[1, 2]     | [1, 2, 3]  | false (different lengths)
[1, 2, 3]  | [1, 3, 2]  | false (no valid rotation)


texts: How can I have jQuery code further optimized?

texts:
I would like to see if my code below can still be optimized, resulting in lesser lines of code. My code retrieves the values from a multiselect field and assign them to hidden fields that will be passed to an integrated googlesheet. Thanks
 jQuery(".ff-btn-submit").click(function() {
        if(jQuery("input:radio[name=gift_choice]").is(":checked") ) {
            if (jQuery("input[name=gift_choice]:checked").val() == 'yes') {
                // Retrieve multi-select values
                var selectedValues = [];
                selectedValues = $('#ff_124_multi_select_gifts').val();

                // Set hidden input with the chosen gift.
                if (selectedValues.length > 0) {
                  jQuery("input[name=gift_1]").val(selectedValues[0]);
                  jQuery("input[name=gift_2]").val(selectedValues[1]);
                  jQuery("input[name=gift_3]").val(selectedValues[2]);
                  jQuery("input[name=gift_4]").val(selectedValues[3]);
                  jQuery("input[name=gift_5]").val(selectedValues[4]);
                  jQuery("input[name=gift_6]").val(selectedValues[5]);
                }
            }
        }
    });


texts:
I've written a script to harvest Name and Phone number from yellowpage Canada under pizza category. The web page doesn't show its full content until scrolled downmost. In my crawler's every cycle, it fetches 40 records. I twitched a little in my loop which I've learnt lately to get the full content. Hope I did it the way it should be.

import requests
from lxml import html

Base_url="https://www.yellowpages.ca/search/si/{0}/pizza/Toronto"
with requests.session() as session:
    page_num=1
    while True:
        response = session.get(Base_url.format(page_num))
        if response.status_code==404:
            break
        tree = html.fromstring(response.text)
        for titles in tree.xpath("//div[@itemprop='itemListElement']"):
            try:
                title = titles.xpath(".//h3[@itemprop='name']/a/text()")[0]
            except IndexError:
                title=""
            try:
                phone= titles.xpath(".//h4[@itemprop='telephone']/text()")[0]
            except IndexError:
                phone=""
            print(title,phone)
        page_num+=1


texts: A solution to the Journey Planner programming challenge

texts:
Here is my Javascript solution to the following problem:

  Given an un-ordered list of flights taken by someone compute the
  person's itinerary, given a starting airport.

  If none valid itinerary, return none.   If more than one journey is
  valid, print any valid solution.

Examples

Array: [['SFO', 'HKO'], ['YYZ', 'SFO'], ['YUL', 'YYZ'], ['HKO', 'ORD']]
Starting: 'YUL'
Return: ['YUL', 'YYZ', 'SFO', 'HKO', 'ORD'].

Array: [['SFO', 'COM'], ['COM', 'YYZ']]
Starting airport 'COM'
Return None

Array: [['A', 'B'], ['A', 'C'], ['B', 'C'], ['C', 'A']]
Starting: 'A'
Return ['A', 'B', 'C', 'A', 'C']

Please can someone comment on readability and efficiency of the code

Thank you

function plan_journey(place, journeys, route, itinerary){
    if(journeys.length == 0){
        itinerary.push(route + place)
    }
    let stops = []
    for(i=0; i<journeys.length; i++){
        if(journeys[i][0] == place){
            stops.push(i)
        }
    }
    if(stops == []){
        return
    }

    for(var i=0; i<stops.length; i++){
        let slice_index = stops[i]
        let remaining_journeys = journeys.slice(0,slice_index).concat(journeys.slice(slice_index + 1))
        let new_route = route + place + "-"
        let next_place = journeys[stops[i]][1]
        plan_journey(next_place, remaining_journeys, new_route, itinerary)
    }
    return itinerary
}

let first_stop = "A"
let journeys = [['A', 'B'], ['A', 'C'], ['B', 'C'], ['C', 'A']]
itinerary = plan_journey(first_stop, journeys, "", [])
if(itinerary.length != 0){
    console.log(itinerary[0])
}else{
    console.log("None")
}


texts:
Is this a proper selection sort?
Any code issues?

public static void SelectionSort(ref int[] a)
{
    int n = a.Length;
    for (int j = 0; j < n - 1; j++)
    {
        int iMin = j;
        for (int i = j + 1; i < n; i++)
        {
            if (a[i] < a[iMin])
            {
                iMin = i;
            }
        }
        if (iMin != j)
        {
            int temp = a[j];
            a[j] = a[iMin];
            a[iMin] = temp;
        }
    }
}

//test
int[] ar = new int[] { 90, 90, 71, 82, 93, 75, 81, 54, 36, 102, 99, 34, -56, 103, 78, 796, 52, -56, 5, 215 };
SelectionSort(ref ar);
foreach (int i in ar)
    Debug.WriteLine(i);


texts:
I have a button (or icon) which can have three states.

On hover, it changes state and on click, the new state gets transferred to another state. This state is kept until you click again for which it gets back to normal.

The code is working, but it does not look or feel good. Is there any way I can re-factor this?

Fiddle
More real example

HTML

    1

        2

        3

CSS

.hidden { display: none; }

JQuery

$(function() {
    $(".rendering-expert.request-list-supported").hover(function() {
        if (!$(this).hasClass("has-request")) {
            $(this).find(".fa-cog").hide();
            $(this).find("[rel='request-list-add']").removeClass("hidden");
        }
    }, function() {
        if (!$(this).hasClass("has-request")) {
            $(this).find(".fa-cog").show();
            $(this).find("[rel='request-list-add']").addClass("hidden");
        }
    }).on("click", "[rel='request-list-add']", function(e) {
        e.preventDefault();
        var toggler = $(this);
        var href = toggler.attr("href");
        toggler.parent().find(".fa-cog").hide();
        toggler.next("[rel='request-list-remove']").removeClass("hidden");
        toggler.toggleClass("hidden");
        toggler.parent().toggleClass("has-request");
    }).on("click", "[rel='request-list-remove']", function(e) {
        e.preventDefault();
        var toggler = $(this);
        var href = toggler.attr("href");
         toggler.parent().find(".fa-cog").show();
         toggler.prev("[rel='request-list-remove']").addClass("hidden");
         toggler.addClass("hidden");
         toggler.parent().removeClass("has-request");
    });
});

Please note that some parts are stripped in this example. It will only change state in my production if an AJAX request succeeds.


texts:
I was looking for a unit testing library for C++, and I found many. Unfortunately, I decided I didn't want to use any of them. I decided to make my own.

This is the result. I made heavy use of the preprocessor, and followed the convention of leading underscore to mean non-published. Everything is done in all-caps, to try to follow good conventions and to avoid name collisions.

Please note that this code is published under the MIT license.

unittest.h

#pragma once

#include <vector>
#include <iostream>

// Helper Macros
#define _STR_HELP(x) #x
#define _STR(x) _STR_HELP(x)
#define ESCAPE(...) __VA_ARGS__ // TEST_CASE(std::map<int, int>) would fail. Wrap in this Macro to not fail.

#define _FILE_LINE __FILE__ ":" _STR(__LINE__)

// Assertion Macros
#define _GENERATE_MESSAGE(test) _FILE_LINE " Failed " #test "." // Message in almost every assertion

/*
 * Assertions are intended to be used within a TEST_CASE macro. We return EXIT_FAILURE if we fail the assertion,
 * meaning that the TEST_CASE fails. Assertions can also be used straight inside the main function, in which case
 * the main function will exit. They are intended to be used within the TEST_CASE macro, so it's not recommended to do
 * that.
 */
#define _ASSERT(test, message)  if (!(test)) {\
                                    std::cerr << message << std::endl;\
                                    return EXIT_FAILURE;\
                                }
// One argument assertion. This generates a message to display.
#define _ASSERT_1(test) _ASSERT(test, _GENERATE_MESSAGE(test))
// Two argument assertion, which appends the user-defined message to the generated one.
#define _ASSERT_2(test, additional) _ASSERT(test, _GENERATE_MESSAGE(test) " " additional)

// Helper macro to get the correct assertion (out of _ASSERT_1 or _ASSERT_2)
#define _GET_ASSERTION(_1, _2, NAME, ...) NAME

// Public Macro for actually calling the ASSERT
#define ASSERT(...) _GET_ASSERTION(__VA_ARGS__, _ASSERT_2, _ASSERT_1)(__VA_ARGS__)
// More advanced macro than ASSERT; it tells the values of each of the arguments as part of the message.
#define ASSERT_EQ(a, b) {\
                            const auto& _VAL_1 = a;\
                            const auto& _VAL_2 = b;\
                            if (_VAL_1 != _VAL_2) {\
                                std::cerr << _FILE_LINE " Failed " #a " == " #b ". Actual Values:\n" \
                                    #a ": " << _VAL_1 << "\n" \
                                    #b ": " << _VAL_2 << std::endl;\
                                return EXIT_FAILURE;\
                            }\
                        }

/*
 * Convenience struct for storing test cases and all related data into a vector.
 */
struct _TEST_CASE
{
    const char *name;
    int (*function)();
    bool result;
};
std::vector<_TEST_CASE> _TEST_CASES; // All test cases are added to this global vector.

// Test Execution Macros
#define TEST_CASE(name, code) _TEST_CASES.push_back({ name, [](){ code; return EXIT_SUCCESS; }, false });

#define RUN_TESTS() std::cout << std::endl; \
                    for (_TEST_CASE& testCase : _TEST_CASES) {\
                        testCase.result = EXIT_SUCCESS == (*testCase.function)();\
                        if (!testCase.result) {\
                            std::cerr << "Failed test case " << testCase.name << "\n";\
                        }\
                    }\
                    std::cout << "Results: ";\
                    for (_TEST_CASE testCase : _TEST_CASES) {\
                        std::cout << (testCase.result ? '.' : 'F');\
                    }\
                    std::cout << std::endl << std::endl;


texts:
I have following exercise:

  If we list all the natural numbers below 10 that are multiples of 3 or
  5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below 1000.

So I wrote below code which finds the sum of all multiples of 3 or 5 below 1000.

Main.java:

package pl.hubot.projecteuler.problem1;

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i < 1000; i++) {
            if (i % 3 == 0 || i % 5 == 0) sum += i;
        }
        System.out.print(sum);
    }
}

How it code works?

I declared sum variable, iterated through i = 1 to i = 999 and if i is multiply of 3 or 5 then I add it to the sum. Finally, I printed out the sum variable.

Questions

Is it a efficient method to solve this exercise?
How can I simplify code?
How can I increase performance of this code?


texts: From object to array with revert and regroup

texts:
Basically, I need to regroup keys by values from an object to an array

An example worth a thousand words in my case, as I don't know how to clearly explain my problem.

Here is my input object:

{
    "Data 1": 0,
    "Data 2": 1,
    "Data 3": 3,
    "Data 4": 0
}

What I should output:

[
    ["Data 1", "Data 4"], // data 1 and 4 are grouped as they both "worth" 0
    ["Data 2"], // data 2 is alone to "worth" 1
    ["Data 3"] // data 3 is alone to "worth" 3
]

First solution:

var output = [];
for (var data in input) { // my input object
    var value = input[data];
    if (output[value] == undefined) {
        output[value] = [];
    }
    output[value].push(data);
}
console.log(output);

It works well for most of the cases, except the one presented at the beginning: if I skip a value - say 0, 1, 3 - then my output will be

[
    0: ["Data 1", "Data 4"],
    1: ["Data 3"],
    3: ["Data 4"]
]

What I understood so far is that since the key 2 is missing, JavaScript somehow understand the output as an associative array.

Final solution:

From the code below, I used a "trick", making an equivalent of array_values() from PHP:

function array_values(arr) {
    var tmp = [];
    for (key in arr) {
        tmp[tmp.length] = arr[key];
    }
    return tmp;
}

var output = [];
for (var data in input) { // my input object
    var value = input[data];
    if (output[value] == undefined) {
        output[value] = [];
    }
    output[value].push(data);
}
console.log(array_values(output));

This finally works perfectly fine.

Nevertheless, I feel like I could optimize and simplify my code. I fear that a big object could be long to process since I could have to parse it 2 times. Does anyone have a guess?


texts: fold expressions using a function recursively

texts:
I have written an accumulate function similar to std::accumulate that works on a std::array. The goal is to remove the loop using fold expressions.
This code currently works in c++17:
#include <array>

template<class U, class F>
class array_accumulate_helper
{
public:
    array_accumulate_helper(U& u, F f)
        : r(u), f(f)
    {
    }

    array_accumulate_helper& operator<<(const U& u)
    {
        r = f(r, u);
        return *this;
    }

private:
    F f;
    U& r;
};

template<class U, std::size_t N, class F, std::size_t... Is>
constexpr U array_accumulate_impl(const std::array<U, N>& u, U r, F f, std::index_sequence<Is...>)
{
    array_accumulate_helper h(r, f);
    (h << ... << u[Is]);
    return r;
}

template<class U, std::size_t N, class F>
constexpr U accumulate(const std::array<U, N>& u, U r, F f)
{
    return array_accumulate_impl(u, r, f, std::make_index_sequence<N>());
}

template<class U, std::size_t N>
constexpr U accumulate(const std::array<U, N>& u)
{
    return accumulate(u, {}, [](const U& a, const U& b) { return a + b; });
}

Is it possible to rewrite array_accumulate_impl using a fold expression that doesn't use array_accumulate_helper?
I can use a fold expression with an operator.
ie. using << in array_accumulate_impl above.
I have been unable to write one using a function recursively.
ie. for a std::array<int, 3> it should expand to:
f(f(f(r, a[0]), a[1]), a[2]);


texts: MCRYPT - are there any flaws or areas for improvement in this class?

texts:
I am working on a class for encryption to use on my site. I have read through many examples of these functions and would just like to clarify a few points I have read and check if this code is worthy. It is for storing sensitive information in a database. I am aware that making this method secure does not mean that the information is 100% secure, I simply need an appraisal of the code.

<?php

class Encryption
{
    private $eMethod = MCRYPT_RIJNDAEL_128;
    private $siteKey = "01234567890123456789012345678901"; # strlen = 32
    private $ivSize;
    private $iv;

    public function __construct()
    {
        $this->ivSize     = mcrypt_get_iv_size( $this->eMethod, MCRYPT_MODE_CBC );
        $this->iv         = mcrypt_create_iv( $this->ivSize, MCRYPT_RAND );
    }

    public function encrypt( $data, $salt )
    {
        $encryptedMessage = mcrypt_encrypt( $this->eMethod, $this->siteKey, $data, MCRYPT_MODE_CBC, $this->iv );
        $encryptedSalt    = mcrypt_encrypt( $this->eMethod, $this->siteKey, $salt, MCRYPT_MODE_CBC, $this->iv );
        $saltIdentifier   = str_pad( strlen($encryptedSalt), 6, '0', STR_PAD_LEFT );

        $newData          = $encryptedSalt.($this->iv).$encryptedMessage.$saltIdentifier;
        return($newData);
    }

    public function decrypt( $data )
    {
        $thisSaltID       = substr( $data, -6 );
        $saltID           = ltrim($thisSaltID,'0');
        $thisSalt         = substr( $data, 0, $saltID );
        $goTo             = $saltID + ($this->ivSize);
        $thisIv           = substr( $data, $saltID, ($this->ivSize) );
        $thisHash         = substr( $data, $goTo, -6 );

        $decryptedMessage = mcrypt_decrypt( $this->eMethod, $this->siteKey, $thisHash, MCRYPT_MODE_CBC, $thisIv );
        return($decryptedMessage);
    }
}

?>

When encrypting, it takes the data and a salt, encrypts both and then combines them with the iv and the padded strlen of the salt as per this line:

$newData = $encryptedSalt.($this->iv).$encryptedMessage.$saltIdentifier;

Then I know which order things appear and can pull it apart accordingly.

Is this salt unnecessary or poorly implemented?
When creating an object and encrypting a string, I pad the string to a length of multiple 16, and generate a random alphanumeric string of length 16 for the salt. Is it unnecessary to make sure the inputs are formatted in this way?
Should the site key be random every time (or static as it is now)? And are there advisements on its length?
Is using RIJNDAEL_128 with a 256-bit key the equivalent of using AES-256?
Is this code okay to use?/area of criticism


texts: Finding the number of integers that are a square and a cube at the same time

texts:
I have written some code that takes two integers and returns the numbers of numbers that are both a square and a cube. I would like to know if there is a more efficient way to write this. I have only just started learning Java so any feedback would be greatly appreciated.

Scanner input=new Scanner(System.in);
double a=input.nextInt();
double b=input.nextInt();
int coolnumbers=0; //counter for the # of numbers that are a square and cube
for(double i=a; i<=b; i++){
    for(double j=1; j<=b; j++){
       if(i==Math.pow(j,6)){
         coolnumbers++;
         break;
       }
    }
}
System.out.println(coolnumbers);


texts:
I've written a program that encrypts files (or stdin) with a user-specified key from 1 to 255. This "encryption" is very insecure, but still a bit better than ROT13 (at least for people trying to crack it using pencils and paper). How can I improve this program?

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

/*
 * A simple program for encrypting files (or stdin) using the XOR operation.
 * Such encryption is very insecure as there are only 254 valid key values,
 * but is still much more secure than ROT13, where there is only 1 valid key.
 *
 * Using a key value of 0 or 256 is equivalent to no encryption, and is
 * therefore not allowed. Other values are too large to fit into one byte
 * and therefore cannot be properly XORed with a byte.
 */

static void usage(const char *const);

int main(int argc, char *argv[])
{
    FILE *in = NULL;
    FILE *out = NULL;
    int k = 0;
    int c;

    while ((c = getopt(argc, argv, "i:o:k:h")) != -1) {
        switch (c) {
        case 'i':
            in = fopen(optarg, "r");
            break;
        case 'o':
            out = fopen(optarg, "w");
            break;
        case 'k':
            k = atoi(optarg);
            break;
        case 'h':
            usage(argv[0]);
            return EXIT_FAILURE;
        }
    }

    in = in ? in : stdin;
    out = out ? out : stdout;

    if (k <= 0 || k > 255) {
        fprintf(stderr, "%s: must specify a valid key via -k\n",
            argv[0]);
        fprintf(stderr, "%s: valid key values are from 1 to 255\n",
            argv[0]);
        return EXIT_FAILURE;
    }

    while ((c = fgetc(in)) != EOF) {
        fputc(c ^ k, out);
    }

    return EXIT_SUCCESS;
}

void usage(const char *const s)
{
    fprintf(stderr, "usage: %s -k key [-i input] [-o output]\n", s);
}

To compile:

$ clang -O2 -Weverything -Werror -o xor xor.c


texts:
The Collatz Conjecture is related to a type of problem called a Hailstone problem; because hailstones circulate up and down through a cloud around a planet until they eventually fall. The Collatz conjecture posits that for the function

$$
f(n) = \begin{cases} \text{even: } & n/2\\ \text{odd: } & 3n+1\end{cases}
$$

the sequence \$n, f(n), f(f(n)), \cdots, f^i(n), \cdots\$ will eventually arrive at the value 1.

The following example code, which calculates the sum of all even members of the sequence obtained for a given starting value \$n\$, is given as part of an exercise, but I'm looking to improve it. By improving it, I mean: shorten via composition; via mapping; via folding; or any other more powerful and better practice.

foo :: Integer -> Integer
foo 1 = 0
foo n
  | even n    = n + foo (n `div` 2)
  | otherwise = foo (3 * n + 1)

Here's what I got. I'm using point-free style with composition  in foo'. However, I'm not so sure how to improve f.

foo' :: Integer -> Integer
foo' = (sum . f)

f :: Integer -> [Integer]
f x
 | x == 1    = []
 | even x    = x : f (x `div` 2)
 | otherwise = f (3*x + 1)

Please critique this improvement.


texts: Updating the total when any of a set of spinners changes its value

texts:
I'm new person who working on jQuery and I need your help.

$('.spinner-input, #flight-class').change(function() {
    var ap = parseInt($('#adult-passenger').val());
    var sp = parseInt($('#student-passenger').val());
    var cp = parseInt($('#child-passenger').val());
    var bp = parseInt($('#baby-passenger').val());
    var fc = $('#flight-class option:selected').text();

    var totalCount = ap + sp + cp + bp;
    $('#kisi-sayisi').val(totalCount + ' - ' + fc);
});

You can see my code in here

And working demo is here

So, here is the situtation: There is nothing bad about this code, its working normally when you click "number of people" in form. You can see, if you click minus or plus sign, form is updating itself. But when I look this code, I'm feeling like repeating myself.

When I tried turn this code to DRY format, i do this:

('.spinner-input, #flight-class').change(function() {
    var passengerId = parseInt($(this).val());
});

Now I get value of input. I need to get sum of values but I can't because something is missing here.

How can I DRY this code?


texts:
I wanted to create a class that would allow me to draw an arc representing a percentage of progress, similar to the activity view on the Apple watch. There are various examples which I found helpful on the web and my output is a combination of many of these.

I have posted my code so that it works and renders in a Xcode playground. Could someone have a look over it and advise if i'm doing anything I shouldn't, or going wrong anywhere.

import UIKit
import XCPlayground

class CircleProgressView: UIView {

    var startPoint: CGFloat = 0
    var color: UIColor = UIColor.yellowColor()
    var trackColor: UIColor = UIColor.grayColor()
    var trackWidth: CGFloat = 1
    var fillPercentage: CGFloat = 100

    override init(frame: CGRect) {

        super.init(frame: frame)
        self.backgroundColor = UIColor.clearColor()

    } // init

    required init(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)
        self.backgroundColor = UIColor.clearColor()

    } // init

    private func getGraphStartAndEndPointsInRadians() -> (graphStartingPoint: CGFloat, graphEndingPoint: CGFloat) {

        // make sure our starting point is at least 0 and less than 100
        if ( 0 > self.startPoint ) {
            self.startPoint = 0
        } else if ( 100 < self.startPoint ) {
            self.startPoint = 100
        } // if

        // make sure our fill percentage is at least 0 and less than 100
        if ( 0 > self.fillPercentage ) {
            self.fillPercentage = 0
        } else if ( 100 < self.fillPercentage ) {
            self.fillPercentage = 100
        } // if

        // we take 25% off the starting point, so that a zero starting point
        // begins at the top of the circle instead of the right side...
        self.startPoint = self.startPoint - 25

        // we calculate a true fill percentage as we need to account
        // for the potential difference in starting points
        let trueFillPercentage = self.fillPercentage + self.startPoint

        let π: CGFloat = CGFloat(M_PI)

        // now we can calculate our start and end points in radians
        let startPoint: CGFloat = ((2 * π) / 100) * (CGFloat(self.startPoint))
        let endPoint: CGFloat = ((2 * π) / 100) * (CGFloat(trueFillPercentage))

        return(startPoint, endPoint)

    } // func

    override func drawRect(rect: CGRect) {

        // first we want to find the centerpoint and the radius of our rect
        let center: CGPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))
        let radius: CGFloat = rect.width / 2

        // make sure our track width is at least 1
        if ( 1 > self.trackWidth) {
            self.trackWidth = 1
        } // if

        // and our track width cannot be greater than the radius of our circle
        if ( radius < self.trackWidth ) {
            self.trackWidth = radius
        } // if

        // we need our graph starting and ending points
        let (graphStartingPoint, graphEndingPoint) = self.getGraphStartAndEndPointsInRadians()

        // now we need to first draw the track...
        var trackPath = UIBezierPath(arcCenter: center, radius: radius - (trackWidth / 2), startAngle: graphStartingPoint, endAngle: 2.0 * CGFloat(M_PI), clockwise: true)
        trackPath.lineWidth = trackWidth
        self.trackColor.setStroke()
        trackPath.stroke()

        // now we can draw the progress arc
        var percentagePath = UIBezierPath(arcCenter: center, radius: radius - (trackWidth / 2), startAngle: graphStartingPoint, endAngle: graphEndingPoint, clockwise: true)
        percentagePath.lineWidth = trackWidth
        percentagePath.lineCapStyle = kCGLineCapRound
        self.color.setStroke()
        percentagePath.stroke()

        return

    } // func

} // class

var circleProgress: CircleProgressView = CircleProgressView()
circleProgress.frame = CGRectMake(0 , 0, 200, 200)

circleProgress.trackWidth = 20

circleProgress.startPoint = 0
circleProgress.fillPercentage = 75

XCPShowView("Container View", circleProgress)


texts: Client Side JavaScript [aka Greasemonkey] Key Event Handler

texts:
Description

The code captures keypress events that do not occur in a text field and dispatches on the properties of a $command object in the application execution context. I have provided a sketch of the execution context in order to assist your review of the code of interest.

Execution Context Sketch

This is a sketch the dependencies of the code for review. The larger context is a user side script running in Firefox using Greasemonkey. The Greasemonkey script is part of a suite of user side tools. This code is not intended for review.

(function () {

  // There is additional application context for making this global
  window.$snatch = function ($class) {
    return document.getElementsByClassName($class)[0];
  };

  // There is additional application context for making this global
  window.$commands = {};

  /* Define links */
  // There is additional application context supporting defining links
  // independently of the code utilizing them.
  var yes = $snatch('yes');
  var maybe = $snatch('rmaybe');
  var no = $snatch('no');

  /* Create Commands */
  // There is additional application context that makes multiple
  // keypresses a more practical approach than it might appear
  $commands.ccc = () => { close(); };
  $commands.yyy = () => { location = yes };
  $commands.mmm = () => { location = maybe };
  $commands.nnn = () => { location = no };
})();

JavaScript for Review

This code for handling key events originated with a  copy-paste of this example on MDN. The modifications have been primarily to implement dispatch.

/* Key Event Handler */
(function () {
  const commandLength = 3;
  var nOffset = 0;
  var keyQueue = "";

  // Add a new property listing all the properties
  $commands.keys = Object.keys($commands);

  document.onkeypress = function (oPEvt) {
    var oEvent = oPEvt || window.event, nChr = oEvent.charCode, sNodeType = oEvent.target.nodeName.toUpperCase();
    if (nChr === 0 || oEvent.target.contentEditable.toUpperCase() === "TRUE" || sNodeType === "TEXTAREA" || sNodeType === "INPUT" && oEvent.target.type.toUpperCase() === "TEXT") { return true; }
    if (keyQueue.length < commandLength) {
      keyQueue += String.fromCharCode(nChr);
    }
    else if (keyQueue.length == commandLength) {
      if ($commands.keys.includes(keyQueue)) {
        $commands[keyQueue]();
        keyQueue = "";
      }
      else {
        keyQueue = keyQueue.slice(-2);
      }
    }
    else { alert("too many characters!"); }
    return true;
  }
})();


texts: Custom array like implementation with components x, y, z

texts:
I want to implement a custom vector-like in Python that stores its components in a list (or another container). And I want to access the components as x, y and z in order to get and set them. What is the best way to do it?

I implemented it like this:

import numpy as np

class Vector3d:
    components = ['x', 'y', 'z']

    def __init__(self):
        self._data = np.array([0.0, 0.0, 0.0])

    def __getattr__(self, key):
        if key in self.components:
            index = self.components.index(key)
            return self._data[index]
        else:
            return super().__getattr__(key)

    def __setattr__(self, key, value):
        if key in self.components:
            index = self.components.index(key)
            self._data[index] = value
        else:
            return super().__setattr__(key, value)

    def __repr__(self):
        return repr(self._data)

    def norm(self):
        return np.linalg.norm(self._data)

a = Vector3d()
a.x = 1.2
a.y = 2.3
a.z = 3.4
print(a.x, a.y, a.z)
print(a)
print(a.norm())

Here are the aspects that I dislike about it:

First, I duplicated the code if key in self.components: index = self.components.index(key).
Second, searching for the index every time seems to be non-optimal towards the consuming time. I believe there's a better way to implement it.

Please, suggest different approaches to me.

There may be many causes of doing it. For example, I may want to store the components as (ctypes.c_double * 3) array and to pass them to a DLL to gain performance of some calculations. Or to store them as numpy.array having the access to all numpy array methods. But I still want to keep the access to the components through x, y, z from the outside.


texts:
I'm currently writing a pure ruby webserver, and one of the things that I have to do is parse a HTTP request. The method I've pasted below takes a HTTP request, and puts it in a map keyed by the header field names.

The biggest issue I faced while doing this was dealing with the lack of an EOF from the TCPSocket on requests with bodies (basically every POST request). This meant that I couldn't just keep doing file.gets until I reached the end of the file, because there was no end. What I ended up doing instead, was to create a while true loop that breaks when it finds '\r\n', which are the last characters before the Body, then read the Body separately using the number I get from Content-length.

Is there a more elegant way in ruby to do this? I feel like it's unnecessary to use a infinite loop, but I can't think of anything else that would work.

   # Takes a HTTP request and parses it into a map that's keyed
   # by the title of the heading and the heading itself.
   # Request should always be a TCPSocket object.
   def self.parse_http_request(request)
      headers = {}

      #get the first heading (first line)
      headers['Heading'] = request.gets.gsub /^"|"$/, ''.chomp
      method = headers['Heading'].split(' ')[0]

      #parse the header
      while true
         #do inspect to get the escape characters as literals
         #also remove quotes
         line = request.gets.inspect.gsub /^"|"$/, ''

         #if the line only contains a newline, then the body is about to start
         break if line.eql? '\r\n'

         label = line[0..line.index(':')-1]

         #get rid of the escape characters
         val = line[line.index(':')+1..line.length].tap{|val|val.slice!('\r\n')}.strip
         headers[label] = val
      end

      #If it's a POST, then we need to get the body
      if method.eql?('POST')
         headers['Body'] = request.read(headers['Content-Length'].to_i)
      end

      return headers
   end


texts: Allow users to add custom queries to Mustache variables

texts:
I'm writing an application that will be managed by my team, it uses Mustache.php as template engine.

I have a PHP file that makes an array of variables and functions that is passed to the Mustache parser to populate the template.

I even provide a system to override partials of my template to edit the aspect of the application for specific users.

Now I'd like to add a way to allow my team to add custom variables to the array passed to Mustache.php without have to hack the core of my application.

I thought about a little function that checks if a .php file with the name of the user exists and if so, include it after I've generated the array and before I pass it to mustache.

It should looks like:

contents.php:

// my queries
$variables = Array(1,2,3,bla,foo,bar);

if (file_exists($_SERVER['BASE_DIR'] . '/customcontents/'. $username . '.php')) {
   include($_SERVER['BASE_DIR'] . '/customcontents/'. $username . '.php');
}

// Call mustache and pass $variables to it

<username>.php:

// custom queries
$variables = array_merge($variables, $customvariables)

I'm not sure if this can be a nice solution or if you guys have some better idea.


texts:
I am computing a random weighted classifier based on the rates at which 3 labels appear in a "train" set. I want to use this RWC as a baseline for other classifiers. I'm doing this over 1000 iterations and then computing the mean of F1, Precision and Recall of each class besides the overall kappa.

Can this code run faster/look nicer? Minimum example here:

library(caret)

random_weighted_classifier <- function(weightA, weightB, weightC){
  random_number = sample(1:100,1) / 100

  if(random_number <= weightA){
    return("better")
  }else if (random_number > weightA && random_number <= (weightA + weightB)){
    return("worse")
  }else if(random_number > (weightA + weightB) && random_number <= (weightA + weightB + weightC)){
    return("no change")
  }
}

test <- function(){

  betters = rep(x = "better", 100)
  worses = rep(x = "worse", 50)
  no_changes = rep(x = "no_change", 10)
  reference = sample(c(betters, worses, no_changes))

  better = sum(reference == "better")
  worse = sum(reference == "worse")
  no_change = sum(reference == "no_change")
  total = length(reference)

  # rwc = random weighted classifer
  prediction_rwc = vector("character", total)

  iterations = 1000
  f1_rwc = matrix(0., iterations, 3)
  pres_rwc = matrix(0.,iterations, 3)
  rec_rwc = matrix(0., iterations, 3)
  kappa_rwc = vector("double", iterations)

  for(i in seq(1:iterations)){

    for(j in seq(1:total)){
      prediction_rwc[[j]] = random_weighted_classifier(better/total, worse/total, no_change/total)
    }
    cm = (confusionMatrix(data = factor(prediction_rwc, levels = c("better","worse", "no_change")),
                          reference = factor(reference, levels = c("better","worse", "no_change")),
                          positive = c("better", "worse"),
                          mode = "everything"))

    f1_rwc[i,1:3] <-  cm$byClass[,"F1"]
    pres_rwc[i,1:3] = cm$byClass[,"Precision"]
    rec_rwc[i,1:3] = cm$byClass[,"Recall"]
    kappa_rwc[[i]] = round(cm$overall["Kappa"],2)
  }

  print(list("f1" = c(mean(f1_rwc[,1], na.rm = T),mean(f1_rwc[,2], na.rm = T),mean(f1_rwc[,3], na.rm = T)),
             "precision" = c(mean(pres_rwc[,1], na.rm = T),mean(pres_rwc[,2], na.rm = T),mean(pres_rwc[,3], na.rm = T)),
             "recall" = c(mean(rec_rwc[,1], na.rm = T),mean(rec_rwc[,2], na.rm = T),mean(rec_rwc[,3], na.rm = T)),
             "kappa" = mean(kappa_rwc, na.rm = T)))

}

test()