texts:
I am new to AngularJS.  Here is my basic code for implementing Tabs with Pane.  Eventually, each tab-pane will have a form and a ui-grid that will display data from the DB.

Can I use separate controllers to initialize each tab to load the pane?
Is it good to give separate controllers for implementing a pane? I have DB calls in each pane of the tab.
Should I use any directive?

Can you suggest better ways?

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Bootstrap tab panel with Angular</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />

One

Two

Three

Panel 1 Content

Panel 2 Content

Panel 3 Content


texts:
In https://stackoverflow.com/a/39299060, I wrote the following program.

#include <fstream>
#include <iostream>
#include <string>

static std::string str_xor(const std::string &data, const std::string &key) {
  std::string result(data.size(), '\0');

  for (std::size_t i = 0, i < data.size(); i++) {
    result[i] = data[i] ^ key[i % key.size()];
  }
  return result;
}

Is it idiomatic C++ to evaluate data.size() in every iteration of the loop? Same for key.size().
Is the use of std::size_t ok here, or do I really have to write std::string::size_type?
Can I take advantage of move semantics here? I don't know them yet.

int main(int argc, char **argv) {
  if (argc != 3) {
    std::cerr << "usage: xor <datafile> <keyfile>\n";
    return 1;
  }

  std::ifstream data_in(argv[1]);
  std::string data(
    (std::istreambuf_iterator<char>(data_in)),
    (std::istreambuf_iterator<char>()));
  data_in.close();

The error checking is missing here. I would like the code for error checking to be as brief as possible. Ideally one or two lines that check for all errors at once. Is that still possible after closing the stream?

  std::ifstream key_in(argv[2]);
  std::string key(
    (std::istreambuf_iterator<char>(key_in)),
    (std::istreambuf_iterator<char>()));
  key_in.close();

  std::string result = str_xor(data, key);

  std::ofstream data_out(argv[1]);
  data_out << result;
  data_out.close();

  return 0;
}

Anything else?


texts: A very secure procedural MySQLI login script against injections

texts:
I know there are other ways to create a login script like Object Oriented, Prepared Statements and PDO, but how about those old MySQL PHP users like me trying to change from old style to the new ways? Here is a login script code I created for those like me changing from MySQL to MySQLI the easy way.

Please take a look at the follow code and help us improve it, make it shorter, give us ideas, review is the symbols used are safe or not. How about adding brute force check so users can only fail to login 3 times per hour?

session_start();
include 'database/connection.php';
// we clean username against sql injection
$username=mysqli_real_escape_string($database,$_POST['form_user']);
// we clean password against sql injection
$password=mysqli_real_escape_string($database,$_POST['form_password']);
// if we get empty username and password we redirect to error page
if (empty($username) || empty($password)){header('Location: index.php?error=1');exit();}
// we clean username and password against XS injection, 0 to 9 and a to z and A to Z only allowed or we redirect to error page
if (preg_match("/[^A-Za-z0-9]/", $username)){header('Location: index.php?error=2');exit();}
if (preg_match("/[^A-Za-z0-9]/", $password)){header('Location: index.php?error=3');exit();}
// now we check if user exist
$members="SELECT * FROM `accounts` WHERE `member` = '$username'";
$result=mysqli_query($database,$members);
// if user exist we redirect to error page
if(mysqli_num_rows($result)==0){header('Location: index.php?error=4');exit;}
// we will now check if salted password is correct
$user=mysqli_fetch_array($result,MYSQL_ASSOC);
// encoding method
$encoding=hash('sha256',$user['codificacion'].hash('sha256',$password));
// if password is not correct we redirect to error page
if($encoding!=$user['password']){header('Location: index.php?error=5');exit;}
// now everything is ok so we should set session, the session name will be member username
$_SESSION['username']=$user['member'];
// because we have admins, mods and users we need to check user privilege and redirect
if ($user['privilege']=="USER"){header('Location: users/index.php');exit();}
else if($user['privilege']=="ADMIN"){header('Location: admins/index.php');exit();}
else if($user['privilege']=="MOD"){header('Location: mods/index.php');exit();}
// if user is not admin or user or mod there must be something wrong so we kick them
else {header('Location: kick.php?error=6');exit();}


texts: Finding the class to which the IP address belongs

texts:
I have tried the code for finding the class of the IP address the user inputs, and printing the network and the host bits in the IP address. Could someone please review this approach and provide suggestions. Thanks:).

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<error.h>
#include<errno.h>
#define size 32
int bin[size];
void print(int class, int nb, int hb);
void convert_to_binary(uint32_t decimal);

void print(int class, int nb, int hb)
{
    int i = 0;

    printf("The Network bits are:\n");
    for(i = class; i < (nb + class); i++) {
        printf("%d ", bin[i]);
    }
    printf("\n");
    printf("The host bits are:\n");
    for(i = (class + nb); i < size; i++) {
        printf("%d ", bin[i]);
    }
}

void convert_to_binary(uint32_t decimal)
{

    int index = 0;
    int temp = 0;
    int i = 0;

    while (decimal > 0) {
        temp = decimal % 2;
        bin[index++] = temp;
        decimal = decimal / 2;
    }
    for (i = 0; i < size / 2; i++) {
        temp = bin[i];
        bin[i] = bin[size - i - 1];
        bin[size - i - 1] = temp;
    }

}

int main(int argc, char **argv)
{
    struct in_addr addr;
    uint32_t result;
    char *IP;
    int ret = 0;
    int value = 0;

    if (argc != 2)
        error(1, errno, "Too many or few arguments\n");
    IP = argv[1];
        ret = inet_aton(IP, &addr);
    if (ret == 0)
        error(1, errno, "Invalid IP- address provided\n");
    printf("The address in the structure is network byte order:(Big- Endian) %X %d\n", addr, addr);
    result = ntohl(addr.s_addr);
    convert_to_binary(result);
    if (bin[0] == 0) {
        printf("Class - A\n");
        print(1, 7, 24);
    } else if (bin[0] == 1 && bin[1] == 0) {
        printf("Class - B\n");
        print(2, 14, 24);
    } else if(bin[0] == 1 && bin[1] == 1 && bin[2] == 0) {
        printf("Class - C\n");
        print(3, 21, 8);
    } else {
        printf("It does not belong to any of the class\n");
    }
}
```


texts: BFS to check if path from start node to end node exists

texts:
I'm trying to solve a problem from leetcode called Jump Game and it seems to be a pretty simple graph problem where we have to find if a path exists from a start node to an end node. I personally always struggle with problems like this, where graphs are represented as arrays (instead of a Node class with connections) so I would appreciate a review of the code I wrote. My current solution looks as follows:

class Solution {

    public boolean canJump(int[] nums) {

        if(nums.length == 1)
            return true;

        HashMap<Integer, ArrayList<Integer>> graph = new HashMap<Integer, ArrayList<Integer>>();

        for(Integer i = 0; i < nums.length; i++) {

            ArrayList<Integer> edges = new ArrayList<Integer>();

            int jumps = nums[i];

            if (jumps != 0) {
                for(Integer j = 1; j <= jumps; j++) {
                    edges.add(i+j);
                }
            } else {
                edges.add(-1);
            }

            graph.put(i, edges);
        }

        //we have our graph ready

        Integer target = nums.length - 1;
        System.out.println("target is : " + target);

        HashSet<Integer> visited = new HashSet<Integer>();

        Queue<Integer> queue = new LinkedList<Integer>();
        queue.add(0);

        while(!queue.isEmpty()) {
            System.out.println("queue " + queue.peek());
            visited.add(queue.peek());
            ArrayList<Integer> edges = graph.get(queue.poll());

            System.out.println("edges is : " + edges);

            for(Integer edge : edges) {

                if(!visited.contains(edge)){

                    if (edge == target) {
                        return true;
                    }

                    if(!queue.contains(edge) && edge > 0){
                        queue.add(edge);
                    }
                }
            }

        }

        return false;

    }

}

So firstly, I know I'm doing some redundant operations. Right now I am creating a HashMap to store my graph in Node->ConnectionsList pairs since its just easier for me to visualize. I know I can just skip doing this and just directly use the input array and a queue to run my search, and I will be optimizing this later.

I would mostly like someone to go over my BFS logic implementation (in the while loop) and let me know if there is anything logically wrong with my code for it.

As it stands I pass 73/75 test cases on leetcode because of a time out, but I'd like to make sure my BFS logic is sound before I continue. There seems to be another easier way to solve this problem without BFS, but for now I'm using this to practice implementing graph search algorithms so I'd appreciate a review of that portion.


texts: Page Enum with overridden methods for the first and last members

texts:
I am managing the changing of views in an Android app using this enum and associated methods. I am particularly interested in the Page enum's use of overriding previous() and next() for the first and last elements.

Is this readable?
Is this idiomatic?
Is there a preferable data structure?
Are there general stylistic improvements that could be made?

public enum Page {
  INTRO { @Override public Page previous() {return this; } },
  PUBLIC_PROFILE, PRIVATE_PROFILE, SOCIAL_ACCOUNTS, LOOPS, INVITE,
  FINISHED { @Override public Page next() { return this; }; };

  public Page next() {
    return values()[ordinal()+1];
  }

  public Page previous() {
    return values()[ordinal()-1];
  }
}

private Page page = Page.INTRO;

private void setPage(Page page) { ... }

private void nextPage() {
  page = page.next();
  setPage(page);
}

private void previousPage() {
  page = page.previous();
  setPage(page);
}


texts: Testing an action returns a View with a ViewModel using xUnit and Moq

texts:
This is my first test, I think it's testing what I need it to test but wanted to get some feedback.

I wanted to test to make sure the controller action returns a view with a certain ViewModel.

The code that it will be testing:

Controller:

public class UserController : Controller
{
    private readonly ILogger<UserController> _logger;
    private readonly IViewModelService _vmService;

    public UserController(ILogger<UserController> logger, IViewModelService vmService)
    {
        _logger = logger;
        _vmService = vmService;
    }

    public async Task<IActionResult> Index()
    {
        return View(await _vmService.GetIndexVM());
    }
}

ViewModel

public class UserListVM
{
    public IQueryable<DimUser> UserList { get; set; }
}

ViewModelService

public async Task<UserListVM> GetIndexVM()
{
    return new UserListVM()
    {
        UserList = await _userRepo.GetUserList()
    };
}

The Test:

public class UserControllerTests
{
    [Fact]
    public async Task Index_ReturnsAViewResult_WithUserListVM()
    {
        // Arrange
        var logger = new Mock<ILogger<UserController>>();
        var vmService = new Mock<IViewModelService>();
        var myList = new List<DimUser>
        {
            new DimUser()
            {
                UserId = 1,
                FirstName = "Test",
                Surname = "TestSur",
                RefNumber = "ABC1111111",
                DateOfBirth = DateTime.Now
            }
        };

        vmService.Setup(x => x.GetIndexVM()).ReturnsAsync(new UserListVM()
        {
            UserList = myList.AsQueryable()
        });

        var userController = new UserController(logger.Object, vmService.Object);

        // Act
        var result = await userController.Index();
        var viewResult = Assert.IsType<ViewResult>(result);
        var model = Assert.IsType<UserListVM>(viewResult.ViewData.Model);

        // Assert
        Assert.IsType<UserListVM>(model);
    }
}


texts: Faster method to find data using search word?

texts:
I need to search through a string array to find every occurrence of "Parameters Table", and between each "Parameters Table" and the next, get another string from a specified index (that remains constant). I have been doing this like so:

public List<string> findlistOfNames(string[] arrayToLookForNames)
{
    List<string> listOfNames = new List<string>();

    const string separator = "Parameters Table"; //This is the string I am searching for

    var cuttedWords = arrayToLookForNames.SkipWhile(x => x != separator).Skip(1);

    while (cuttedWords.Any())
    {
        var variable = cuttedWords.TakeWhile(x => x != separator).ToArray();
        cuttedWords = cuttedWords.Skip(variable.Length + 1);
        listOfNames.Add(variable[2]); //This (always index 2) needs to be added to the list
    }
    return listOfNames;
}

This works but too slowly. Is there a better way to do this?

Here is a snippet of string[] arrayToLookForNames:

  Parameters Table

  0

  41

  Baro Pressure

  hPa

  AFD2

  recorded

  Parameters Table

  0

  42

  Baro Setting

  in-hg


texts: Ultra-simple, automatic, non-float, 1-4 column, grid system

texts:
Has everyone moved over to CSS Grid and/or Flexbox? If not, I've maintained and evolved this system over a fair amount of time, the concept was derived originally, I believe, from Mary Lou, although I don't recall where the article is.

I was never a proponent of floats, although the using font-size:0 to clear whitespace isn't an ideal solution either, neither is a DOM Cleaner function in javascript. Probably minimized (non-formatted) HTML without whitespaces is ideal, just difficult to maintain... There's a lot of other "hacky" concepts, comments in HTML, bleh... but I landed on the font-size:0. This served me well and I still use it in a handful of projects, though I've mostly moved to a CSSGrid/Flexbox combination as of late.

It's a similar to:

.table {display: table}
.table>div {display: table-cell}

With a higher degree of flexibility, if you need heights to match, the above or flexbox/css grid are probably a better solution. or min-height on columns if it's known content.

Any ideas to improve or flaws, let me know.

.autogrid {
    padding: .5rem; /* 8px */
    /** remove whitespace from container */
    font-size: 0;
    box-sizing: border-box}

  .autogrid>* {
    box-sizing: inherit; /* inherit border-box */
    display: block;
    font-size: inherit; /* inherit 0px */
    margin: 0 auto .5rem; /* 0 auto 8px */
    padding: 0 .5rem .5rem /* 0 8px 8px */}

  /** create vertical space in columns & prevent margin-collapsing */
  .autogrid>*:before {
    content: '';
    display: inline-block;
    vertical-align: 0; /* baseline or 0% */
    width: 0;
    height: .5rem /* 8px */}

  @media (min-width: 33.75em) { /* 540px */

    .autogrid>* {
      display: inline-block;
      margin: .5rem; /* 8px */
      /** align columns/cards to top, middle, etc. */
      vertical-align: top}

    .autogrid>*:first-child:nth-last-child(1),
    .autogrid>*:first-child:nth-last-child(3),
    .autogrid>*:first-child:nth-last-child(3)~* {width: calc(100% - 1rem) /* 100% - 16px */}

    .autogrid>*:first-child:nth-last-child(4),
    .autogrid>*:first-child:nth-last-child(4)~*,
    .autogrid>*:first-child:nth-last-child(2),
    .autogrid>*:first-child:nth-last-child(2)~* {width: calc(50% - 1rem) /* 50% - 16px */}

  }

  @media (min-width: 50em) { /* 800px */

    .autogrid>*:first-child:nth-last-child(3),
    .autogrid>*:first-child:nth-last-child(3)~* {width: calc(33.333% - 1rem) /* 33.333% - 16px */}

    .autogrid>*:first-child:nth-last-child(4),
    .autogrid>*:first-child:nth-last-child(4)~* {width: calc(25% - 1rem) /* 25% - 16px */}

  }

  /**
  ###############
  #  DEMO ONLY  #
  ###############
  html:
  `

col

col

col

col

  `
  */

  html {
    font: 400 100%/1 sans-serif;
    color: #333}

  body,
  p {
    font-size: 1rem; /* 16px */
    line-height: 1.45; /* 145% or 23.2px */
    margin: 0}

  .autogrid>* {text-align: center}

  .autogrid>*:first-child,
  .autogrid>*:nth-child(2) {color: #fff}

  .autogrid>*:nth-child(3),
  .autogrid>*:last-child   {color: inherit}

  .autogrid>*:first-child  {background-color: #4af}
  .autogrid>*:nth-child(2) {background-color: #fa4}
  .autogrid>*:nth-child(3) {background-color: #def}
  .autogrid>*:last-child   {background-color: #fed}

col

col

col

col


texts: Persistent login ("remember me" cookie) using PHP

texts:
The code below is a attempt to create a persistent login cookie. I am an amateur and not professional so this is the first attempt to have secure remember me cookie. Now I want you guys to review two things:

I am trying to create a system like best way to implement remember me but I am not sure if I have done the same thing as explained there ( username row in table and cookie value isn't there but i have added).
Is my code a good way to secure remember me cookie ?

Any other suggestions or critiques are welcome.

    if (isset($_POST['rememberme'])) {

    $hash = sometext;
    $identifier = md5($username);
    $token = hash('sha512',$hash);
    setcookie('auth', $username. "," .$identifier. "," . $token, time()+31556926);
    $query=$db->prepare("SELECT username from tokens WHERE username=:username");
    $query->execute(array(':username'=>$username));
    if($query->rowCount() <=0 ){
    $result = $db->prepare("INSERT INTO tokens (username,identifier,token) VALUES (:username,:identifier,:token)");
    $result->execute(array(':username'=>$username,':identifier'=>$identifier,':token'=>$token));
     }
    }

    if(isset($_COOKIE["auth"])){
    $pieces = explode(",", $_COOKIE["username"]);
    $username = $pieces[0];
    $Uidentifier = $pieces[1];
    $Utoken = $pieces[2];

    $sql=$db->prepare("SELECT * FROM tokens WHERE identifier=:identifier");
    $sql->execute(array(':identifier'=>$Uidentifier));
    if($sql->rowCount()>0){
     $row = $sql->fetch(PDO::FETCH_ASSOC);
     $dbtoken = $row['token'];
     if($Utoken==$dbtoken){
     $newhash = 'sometext';
     $newtoken = hash('sha512',$newhash);
     $que=$db->prepare("UPDATE tokens SET token=:token WHERE identifier=:identifier");
     $que->execute(array(':token'=>$newtoken,':identifier'=>$Uidentifier));
     setcookie('auth', $username. "," .$identifier. "," . $token, time()+31556926);
     header("Location:home.php");
     }
     if($Utoken!=$dbtoken){
     echo "Unauthorized login attempt!";
     setcookie("auth","",time()-31556926);
     $stmt->$db=("DELETE FROM tokens WHERE identifier=:identifier");
     $stmt->execute(array(':identifier'=>$identifier));
     header("Location:login.php");
      }
     }
    }


texts:
This a program I wrote to execute various power-related function on my computer. It accepts one command-line argument that describes what action to take and then performs that action. Usage looks like this:

C:\Users\Noah\My Code\GHCI> power sleep
execute sleep? (y/n)
y

//computer goes to sleep

Here's the code. Any feedback whatsoever is appreciated, regarding either my program's design or the style, formatting and good/bad practices of my code.

--power.hs

import System.Cmd(system)
import System.Environment(getArgs)

type Arg = String --A command-line argument
type Cmd = String --A command to execute

--paths to programs that will carry out the actions
shutdown_path = "C:\\Windows\\System32\\shutdown.exe"
rundll32_path = "C:\\Windows\\System32\\rundll32.exe"

--assoc list mapping arguments to the action that should be taken when that argument is received
cmds :: [(Arg, Cmd)]
cmds = [ ("shutdown",  shutdown_path ++ " /s /t 0"                           ),
         ("sleep",     rundll32_path ++ " powrprof.dll,SetSuspendState 0,1,0"),
         ("hibernate", shutdown_path ++ " /h"                                ), -- does not work
         ("lock",      rundll32_path ++ " user32.dll,LockWorkStation"        ),
         ("restart",   shutdown_path ++ " -t 0 -r -f"                        ) ]

--gets the argument passed to the program. Calls error if there is not exactly one argument.
extractCmdOrFail :: IO Arg
extractCmdOrFail = getArgs >>= check
    where check [s] = return s
          check _   = error "Wrong Number of arguments"

--finds the command to execute from the given command-line arg. Calls error if no command is found.
findCmdOrFail :: Arg -> Cmd
findCmdOrFail s = check $ lookup s cmds
    where check (Just s') = s'
          check Nothing   = error "Unknown command: " ++ s

--prompts the user to confirm whether or not they want to execute the command.
prompt :: Cmd -> Arg -> IO ()
prompt cmd name = putStr ("Execute " ++ name ++ "? (y/n)\n") >> getChar >>= branch cmd

--conditional "loop" that either executes the command, cancels, or awaits valid input.
branch :: Cmd -> Char -> IO ()
branch cmd 'y' = system cmd >> return ()
branch cmd 'n' = putStrLn "Command Cancelled" >> getChar >> return ()
branch cmd _   = getChar >>= branch cmd

--main function
main = extractCmdOrFail >>= (\arg -> prompt (findCmdOrFail arg) arg)


texts:
I wrote a little Perl script to Caesar shift strings. Usage:

$ # usage: caesar <string> [shifts,...]

$ caesar abcde # The default shift is 13.
nopqr

$ caesar abcde 1
bcdef

$ caesar abcde 1,13 # Multiple shifts are supported.
bcdef
nopqr

$ caesar abcde 1-3,5-6 # Shift ranges are supported.
bcdef
cdefg
defgh
fghij
ghijk

Here is the code:

#!/usr/bin/env perl

use strict;

sub usage {
    die 'usage: ceaser <string> [shifts,...]'
}

usage if $#ARGV < 0;

my @str = split //, $ARGV[0];
my @shifts = split /,/, $ARGV[1];
@shifts = (13) unless @shifts;

# Resolve ranges.
my @shifts2 = ();
SHIFT: for my $shift (@shifts) {
    my @ranges = split /-/, $shift;
    for my $range (@ranges) {
        if ($range < 0 || $range > 25) {
            warn "invalid shift size: $range";
            next SHIFT;
        }
    }
    push @shifts2, ($ranges[0]..$ranges[$#ranges]);
}
@shifts = @shifts2;

# Generate ciphered strings.
for my $shift (@shifts) {
    my @str2 = @str;
    for my $c (@str2) {
        my $d = ord($c);
        if ($d >= ord('a') && $d <= ord('z') - $shift ||
            $d >= ord('A') && $d <= ord('Z') - $shift) {
            $d += $shift;
        } elsif ($d >= ord('z') - $shift && $d <= ord('z') ||
                 $d >= ord('Z') - $shift && $d <= ord('Z')) {
            $d -= ord('z') - ord('a') - $shift + 1;
        }
        $c = chr($d);
    }
    printf "%s\n", join '', @str2;
}

This is my first Perl script. I am looking for advice on making the code simpler, cleaner, and more idiomatic.


texts:
I have an interesting problem to solve and despite having a running solution, I was wondering where I could improve it.

In a range from 1 to 1000, I want to create an array with different increments according to the current interval.
So, from 1.0 to 2.0, the increment should be 0.01, from 2.0 to 4.0 it should be 0.02, and so on. There are many intervals. The final result yields an array with 350 fields.

I've come up with a super basic, easy to implement solution using ifs. So it goes something like:

// In one file I have:
const grid = new Grid().buildGrid();
console.log(grid); // And expect a grid which respects the rules defined in the below class.

// Grid Class:
class Grid {
    constructor() {
        this.array = [];
    }

buildGrid() {
    _createKeysWithTicks(this.array);
}

_createKeysWithTicks(array){
    let i = 1.0;
    while (i < 1000){
        i = parseFloat((i + findStepSize(i)).toFixed(2));
            array.push(i);
    }
    return array;
}

findStepSize(number) {
    let res;
    if (number >= 1.0 && number < 2.0) {
        res = 0.01;
    } else if (number >= 2.0 && number < 4.0) {
        res = 0.02;
    } else if (number >= 4.0 && number < 5.0) {
        res = 0.1;
    } else if (number >= 5.0 && number < 10.0) {
        res = 0.5;
    } else if (number >= 10.0 && number < 50.0) {
        res = 1.0;
    } else if (number >= 50.0 && number < 100.0) {
        res = 10;
    }

    return res;
}

However, this is not elegant, at all because I get numerous if statements. I could swap for a switch statement, thus reducing the number of comparisons, which is nice. But does it improve performance?

The suggestion is:

findStepSize(i) {
    let res;
    switch (number):
        case(number >= 1.0 && number < 2.0) {
            res = 0.01;
            break;
        case(number >= 2.0 && number < 4.0) {
            res = 0.02;
            break;
        case(number >= 4.0 && number < 5.0) {
            res = 0.1;
            break;
        case(number >= 5.0 && number < 10.0) {
            res = 0.5;
            break;
        case(number >= 10.0 && number < 50.0) {
            res = 1.0;
            break;
        case(number >= 50.0 && number < 100.0) {
            res = 10;
            break;
    }
    return res;
}

The increments are not linear, otherwise the solution could be different.

How would you optimize or clean this code?

Note: I understand and respect the rules of this community and I appreciate your feedback. Unfortunately, I cannot disclose much more details. If this is still not sufficient for you to think of how would you get rid of those If statements, I can't help much more because I can't simply provide more details. In fact, the data above is random and it's not the use case.


texts: AngularJS wrapper for p5.js - p5 directive and service

texts:
I wrote an AngularJS wrapper for p5.js called angular-p5:

angular.module('angular-p5', [])
.service('p5', ['$window', function($window) {
  return $window.p5;
}])
.directive('p5', ['p5', function(p5) {
  return {
    restrict: 'EA',
    scope: {
      sketch: '='
    },
    link: function(scope, element, attrs) {
      var sketchObj = null;

      var destroySketch = function() {
        if(!sketchObj) {
          return;
        }
        sketchObj.remove();
        sketchObj = null;
      };

      scope.$watch('sketch', function(sketch, oldSketch) {
        if(oldSketch) {
          destroySketch();
        }
        if(sketch) {
          sketchObj = new p5(sketch, element[0]);
        }
      });

      scope.$on('$destroy', destroySketch);
    }
  };
}]);

View the repository for angular-p5.js here on GitHub.

I have a bunch of questions... And I'm open to any and all feedback about anything I didn't mention. Hit me with your best shot!

Naming convention - is the module name okay, or should I just name it "p5"? Or something else? Is it accepted practice for a wrapper like this to be called "angular-*", or is that considered redundant?
Is it weird to have a service and a directive with the same name? It seemed to make sense to me, since you can inject p5 into a controller or include <p5> in your template. And it seems to work... but is this sort of thing common?
Does it cause any issues for sketch to be a function reference? (See: `$scope.mySketch.) This is a requirement of the p5 api. Again, this seems to work, but I'm not sure if this is common...
Did I handle all the cases I need to handle for observing and cleaning up the bound sketch data? Does it look like I cleaned it up properly on change and destroy?
Is using link exclusively appropriate for this implementation, or should I try to factor this into a directive controller?

Also I graciously welcome any feedback about the project itself... It's fairly lightweight at the moment. Anything on GitHub is fair game if someone wants to take a look - docs, examples, etc.


texts:
This is my first bash script so I ask to you to say what you think.

The script must check every directory and if it finds a pdf file in this directory:  move all the pdf files to parent directory, change the name of the files and remove directory.

So if I had this folder structure:

folder1
  file.pdf
  file.txt
folder2
  some.pdf
  another.pdf
folder3
  some.txt

the script must change it to:

 folder1.pdf
 folder2.pdf
 folder2_2.pdf
 folder3
   some.txt

Here is a script code:

#!/bin/bash

working_directory="$HOME/MEGAsync/downloads/books"

cd $working_directory

# for each directory in working directory
for D in `find . -type d`
do
    # skip '.'
    if [[ $D != "." ]]; then
        # get folder name
        folder_name=${D##*/}
        # and cd to folder
        cd $D

        # number of pdf files in the current directory
        declare -i pdf_count=0
        # for each file in the current directory
        for f in *; do

            # get file without path
            file=$(basename "$f")
            extension="${file##*.}"
            filename="${file%.*}"

            if [[ $extension == 'pdf' ]]; then
                pdf_count=pdf_count+1
                if [[ pdf_count < 2 ]]; then
                    new_filename="${working_directory}/${folder_name}.pdf";
                else
                    new_filename="${working_directory}/${folder_name}_${pdf_count}.pdf";
                fi

                echo cp $working_directory/$folder_name/$f $new_filename
                cp $working_directory/$folder_name/$f $new_filename
            fi
        done

        # return to parent folder
        cd ..

        # delete directory if pdf-file was found
        if [[ $pdf_count != "0" ]]; then
            echo rm -R $working_directory/$folder_name
            rm -R $working_directory/$folder_name
        fi
    fi
done


texts: Find filenames with 4 digits which are not divisible by 20 and delete them

texts:
I have a set of files in folder my_dir, which is not the folder where my Python script resides. Sample content of my_dir:

  foo.bar
  ba.bar
  moog_0001.h5
  moog_0007.h5
  moog_0020.h5
  moog_0027.h5
  moog_0032.h5
  moog_0039.h5
  moog_0041.h5
  moog_0053.h5
  moog_0060.h5

I need to:

  find the files with extension .h5
  for each such file, extract the 4 digits in the filename which follow the underscore _. Note: if a file has the extension .h5, its filename always contains a substring _dddd. There can be other digit groups in the full pathname of the file, but none starts with a _, followed by 4 digits, and ends with a .
  if the resulting integer is not divisble by 20, delete the corresponding file

According to these rules, after running the script the content of the folder my_dir must be:

  foo.bar
  ba.bar
  moog_0020.h5
  moog_0060.h5

My solution:

import os
import re

MY_DIR = "/tmp/logs/20190519T1032"

root, dirs, files = next(os.walk(MY_DIR, topdown=True))
files = [ os.path.join(root, f) for f in files ]
print(files)

files = [ file for file in files if file.endswith(".h5") ]

for file in files:
    match = re.search(r'_\d{4}', file).group(0)
    match = match[1:]
    digits = int(match)
    if digits % 20 != 0:
        print("remove file " + file )
        os.remove(file)
    else:
        print("skip file " + file)

Any suggestions? I was told to put the content of the for block in a function, in order to substitute the for block with a list comprehension, but I don't know if it would be significantly faster (the number of files is O(103), tops). Also, the resulting function wouldn't do only one thing: at the very least, it would extract the 4 digits and delete those files for  which the corresponding integer is not divisible by 20. I think that most functions should only one thing.


texts: Heap's algorithm implementation - permutations

texts:
I wrote an implementation of Heap's permutation algorithm in JavaScript (ES2015):

const swap = (array, pos1, pos2) => {
  const temp = array[pos1];

  array[pos1] = array[pos2];
  array[pos2] = temp;
}

const heapsPermute = (() => {
  const result = [];

  return (array, n = array.length) => {
    const newArray = typeof array === 'string'
      ? array.split('')
      : array;

    if (n === 1)
      result.push(newArray.join(''));

    for (let i = 1; i <= n; i++) {
      heapsPermute(newArray, n - 1);

      const j = n % 2
        ? 0
        : i - 1;

      swap(newArray, j, n - 1);
    }

    return result;
  };
})();

console.log(heapsPermute('abcdef').length);

It should take an array|string argument and return array of strings with all permutations.

What do you think about it. Is there room for improvement anywhere?


texts: WPF Extension to directly inject dependencies in the Window constructor

texts:
I just finished writing the core for my WPF application and because I'm still a very beginner at software design I wanted to get some feedback about the design decisions I've made.

I've uploaded the project to Github and I'll post the most important parts here (the project is to big to be posted as a whole). To see the full code base please follow the link.

Purpose

The general purpose of the core I've written was to allow me to use dependency injection to inject directly in to the XAML System.Windows.Window throughout the application lifecycle:

public partial class MainWindow : Window
{
    public MainWindow(object myObj)
    {
        InitializeComponent();
    }
}

When specifying a StartupUri inside the WPF application for the startup window to use the WPF framework doesn't allow you to have a parameterized constructor inside the window. Because I'm a huge fan of dependency injection this was kind of a downside for me and the application core I've written has the purpose to allow me to use a startup window which gets dependencies injected in the constructor.

Component Management Module

One of the most important parts of the application is the component management module. In order to build and activate a System.Windows.Window I've written a WindowManager which itself is just a proxy for an IWindowManager which is being resolved by an IServiceResolver at runtime:

internal class WindowManager
{

    private static IWindowManager _windowManagerImpl;
    internal static IWindowManager WindowManagerImpl
    {
        get
        {
            if (_windowManagerImpl == null)
                _windowManagerImpl = ServiceResolverBuilder.GetServiceResolver()?.Resolve<IWindowManager>();
            return _windowManagerImpl;
        }
        set
        {
            Guard.NotNull(value, nameof(value));

            _windowManagerImpl.Dispose();
            _windowManagerImpl = value;
        }
    }

    public static Window BuildWindow(Type windowType) =>
        WindowManagerImpl?.BuildWindow(windowType);

    public static TWindow BuildWindow<TWindow>() where TWindow : Window =>
        WindowManagerImpl?.BuildWindow<TWindow>();

    public static void ActivateWindow(Window window) =>
        WindowManagerImpl?.ActivateWindow(window);

    public static void ShowAsDialog(Window window) =>
        WindowManagerImpl?.ShowAsDialog(window);

}

The resolved IWindowManager depends on an IWindowBuilder implementation for creating the window and an IWindowService for activating the window.

Application Startup

On application startup I use an IStartup mainly for setting up the dependency injection container and a StartupWindowHelper which gets the startup window type from the application config. Then I call into the component service module to create and activate the window:

public partial class App : Application
{

    protected override void OnStartup(StartupEventArgs e)
    {
        RunApplicationStartup();
        BuildAndActivateStartupWindow();

        base.OnStartup(e);
    }

    private void RunApplicationStartup()
    {
        var applicationStartup = ApplicationStartupBuilder.BuildApplicationStartup();
        applicationStartup.Run();
    }

    private void BuildAndActivateStartupWindow()
    {
        var startupWindowType = StartupWindowHelper.GetStartupWindowType();

        var startupWindow = WindowManager.BuildWindow(startupWindowType);
        WindowManager.ActivateWindow(startupWindow);
    }

}

I've tried my very best writing the core as clean as possible but as I've already mentioned I'm a beginner and not very experienced with good design.


texts:
Recently I completed the encapsulation lesson and I made a simple android app implementing encapsulation, I had difficulties understanding encapsulation.

My Soldier class:

public class Soldier {
    //Start of the class.

    private int solHealth;

   /* Soldier class constructor with the code to set the soldier health to 100
   * when ever we create a soldier object.*/

    public Soldier(){

        this.setSolHealth(100);
    }

    //setter method with the parameter to set the solHealth variable.

    private void setSolHealth(int solHealth) {
        this.solHealth = solHealth;
    }

    //getter method to get the solHealth value.

    public int getSolHealth(){

        return this.solHealth;
    }

    //Main method to heal the soldier by 25 every time this method is called.

    public int heal(){

        this.solHealth += 25;

        //Log used for debugging.

        Log.i("Info", "" + solHealth);

        return solHealth;
    }

    //Main method to injure the soldier by 25 every time this method is called.

    public int injure(){

        this.solHealth -= 25;

        //Log used for debugging.

        Log.i("Info", "" + solHealth);

        return solHealth;
    }

    //End of the class.
}

I created a soldier object in the MainActivity class and used it to access getSolHealth(), heal(), and injure() methods, and to manipulate solHealth values when the button is pressed.

Did I succeed implementing encapsulation correctly ?


texts:
I'd like some tips on optimizing the following code.

I'm a bit concerned that I'm 'polluting the global namespace' by not wrapping it in a function. The commented out var rotator { init { came from a JavaScript tutorial but I'm not sure it's the jQuery way? Should I wrap it in $(function()... instead?

$(document).ready(function() {

//Promos rotation
var $accordionList = $('.accordion').find('li');

// var rotator = {
//      init: function() {
        var numberOfItems = $accordionList.length;
        var currentItem = 0;

        // Set first item to active
        $accordionList.eq(currentItem).addClass('active').find('.content').slideToggle(800, function() {});
        var infiniateLoop = setInterval(function() {
            if(currentItem == numberOfItems - 1){
                currentItem = 0;
            }
            else {
                currentItem++;
            }

            // Remove active class, if is has it, and close content
            $accordionList.parent().find('li.active').removeClass('active')
                .find('.content').slideToggle(800, function() {
            });

            // Add active class and open content
            $accordionList.eq(currentItem).addClass('active').find('.content').slideToggle(800, function() {
            });

        }, 4000 );

        //$('.accordion li').on('click', function () {
        $accordionList.on('click', function () {
            // Stop rotation
            clearInterval(infiniateLoop);

            var $accordionHead = $(this);

            // Remove active class, if is has it, and close content
            $accordionHead.parent().find('li.active').removeClass('active')
                .find('.content').slideToggle(800, function() {
            });

            // Add active class and open content
            $accordionHead.addClass('active').find('.content').slideToggle(800, function() {
            });
        });
//      }
// };

// rotator.init();

});


texts: Generate a text file representing an email for a job application followup

texts:
Purpose: After you've submitted a resume and cover letter for a job position, you haven't heard anything back, so you decided to send a follow up email. The script generates the follow up e-mail based on this template.

"""
    followupemail.py

    A script to generate a follow up e-mail after a job application submission.

    Based on this example: https://www.themuse.com/advice/how-to-follow-up-on-a-job-application-an-email-template

"""

def determine_if_string_is_blank(stringtovalidate, parameterType):

    """
        Determine if the stringtovalidate parameter is empty, and if so,
        raise an exception.

        Args:
            stringtovalidate: The string to validate.
            parameterType: What the stringtovalidate parameter represents in your program.

        Returns:
            None. Raises an exception.
    """

    if not stringtovalidate:
        raise ValueError ("{0} is empty", parameterType)

def prompt_user_with_question(question, parameterType):

    """
        Prompt user with a question and call determine_if_string_is_blank to deteremine
        if an answer is empty.

        Args:
            question: the question we're going to ask
            parameterType: What the stringtovalidate parameter represents in your program.

        Returns:
            answer: the string that contains our user answer.

    """

    answer = input(question)
    determine_if_string_is_blank(answer, parameterType)
    return answer

def write_string_to_file(pathtofile,email):

    """
        Writes the email to a .txt file

        Args:
            pathtofile: The path where the e-mail will be stored
            email: The message we're going to write.

        Returns:
            None
    """

    with open(pathtofile, 'w') as f:
        f.write(email)

def main():

    position_title = None
    hiring_manager = None
    company_name = None
    your_name = None

    pathtofile = "email.txt"

    company_name = prompt_user_with_question("Company Name: ", "Company Name").strip()
    position_title = prompt_user_with_question("Position: ", "Position").strip()
    hiring_manager = prompt_user_with_question("Hiring Manager: ", "Hiring Manager")
    your_name = prompt_user_with_question("Your Name: ", "Your Name")

    email = f"Hi {hiring_manager},\n\nI hope all is well. I know how busy you probably are, but I recently applied to the \n" \
         f"{position_title} position, and wanted to check in on your decision timeline.\n\n" \
         f"I am excited about the opportunity to join {company_name} (insert additional details here).\n\n" \
         f"Please let me know if it would be helpful for me to provide " \
         f"any additional information as you move on to the next stage in the hiring process.\n\nI look forward to hearing from you,\n\n{your_name}"

    write_string_to_file(pathtofile,email)

if __name__ == "__main__":
    main()

Explanation: The script prompts the user for company name, position, hiring manager, and the name. It inserts those values into the email string and generates a text file.


texts: Fastest sum of absolute values of 32 differences

texts:
A long should be treated as a list of 32 unsigned numbers, each of them just two bit long. So 0x1234F... represents

{0, 1, 0, 2, 0, 3, 1, 0, 3, 3, ...}

and 0x55AA0... represents

{1, 1, 1, 1, 2, 2, 2, 2, 0, 0, ...}

Given two such lists, I need to compute the absolute values of the pairwise differences and sum them up. To continue the example, the difference list would be

{-1, 0, -1, 1, -2, 1, -1, -2, 3, 3, ...}

Now just drop the sign and sum it up. What I did is

static int funnySum(long x, long y) {
    int result = 0;
    for (int i=0; i<32; ++i) {
        int xNum = (int) (x & 3);
        int yNum = (int) (y & 3);
        result += Math.abs(xNum - yNum);

        x >>= 2;
        y >>= 2;
    }
    return result;
}

It's the taxicab-distance computing algorithm used in this question of mine. It occurred to me that it can be done without any loop, however I haven't figured the details out yet.


texts: ByteUnit class to convert across size units

texts:
Based on java.util.concurrent.TimeUnit class I wrote similar class to convert size units:

public enum ByteUnit {

  BYTES("B") {
    @Override
    public long toBytes(long value) {
      return value;
    }

    @Override
    public long toKiB(long value) {
      return value / KIBI;
    }

    @Override
    public long toMiB(long value) {
      return value / MIBI;
    }

    @Override
    public long toGiB(long value) {
      return value / GIBI;
    }

    @Override
    public long convert(long value, @NotNull ByteUnit unit) {
      return unit.toBytes(value);
    }
  },

  KIBIBYTES("KiB") {
    @Override
    public long toBytes(long value) {
      return safeTo(value, KIBI);
    }

    @Override
    public long toKiB(long value) {
      return value;
    }

    @Override
    public long toMiB(long value) {
      return value / (MIBI / KIBI);
    }

    @Override
    public long toGiB(long value) {
      return value / (GIBI / KIBI);
    }

    @Override
    public long convert(long value, @NotNull ByteUnit unit) {
      return unit.toKiB(value);
    }
  },

  MEBIBYTES("MiB") {
    @Override
    public long toBytes(long value) {
      return safeTo(value, MIBI);
    }

    @Override
    public long toKiB(long value) {
      return safeTo(value, MIBI / KIBI);
    }

    @Override
    public long toMiB(long value) {
      return value;
    }

    @Override
    public long toGiB(long value) {
      return value / (GIBI / MIBI);
    }

    @Override
    public long convert(long value, @NotNull ByteUnit unit) {
      return unit.toMiB(value);
    }
  },

  GIBIBYTES("GiB") {
    @Override
    public long toBytes(long value) {
      return safeTo(value, GIBI);
    }

    @Override
    public long toKiB(long value) {
      return safeTo(value, GIBI / KIBI);
    }

    @Override
    public long toMiB(long value) {
      return safeTo(value, GIBI / MIBI);
    }

    @Override
    public long toGiB(long value) {
      return value;
    }

    @Override
    public long convert(long value, @NotNull ByteUnit unit) {
      return unit.toGiB(value);
    }
  };

  private static final long KIBI = 1024L;
  private static final long MIBI = KIBI * 1024L;
  private static final long GIBI = MIBI * 1024L;

  @NotNull
  private final String name;

  private ByteUnit(@NotNull String name) {
    this.name = name;
  }

  public abstract long convert(long sourceValue, @NotNull ByteUnit sourceUnit);

  public abstract long toBytes(long value);

  public abstract long toKiB(long value);

  public abstract long toMiB(long value);

  public abstract long toGiB(long value);

  @Override
  public String toString() {
    return name;
  }

  private static long safeTo(long value, long multiplier) {
    final long overflow = Long.MAX_VALUE / multiplier;
    if (value > overflow) {
      return Long.MAX_VALUE;
    }
    if (value < -overflow) {
      return Long.MIN_VALUE;
    }
    return value * multiplier;
  }
}

But I don't realy like the design. I think there are two ways to improve it:

Use "from" instead of "to". Main disadvantage is that it differs from TimeUnit style. Usage will look like:

ByteUnit.KIBIBYTES.fromMiB(42)

Create intermediate object of class, which has all the methods of converting (leads to excess allocation on each call):

ByteUnit.mebibytes(42).toBytes()

Have anyone any suggestions?


texts: Accessing multiple data members in Blackjack classes

texts:
In my Blackjack game so far, I have multiple classes that access each other frequently.  For example, this is my hit() function for the Game class:

void Game::hit(unsigned playerNum)
{
    Card newCard = deck.deal();
    players[playerNum].getPlayerHand()[0].getHandCards().push_back(newCard);
}

First, a new Card object is assigned a new card from the Deck object.  However, the next line gets more complicated.  Essentially:

The specified player's Hand object vector is accessed.  As such, it needs an index.  I'm doing this so that I can easily destroy hands without looping.

players[playerNum].getPlayerHand()[0]

In that one Hand object in the vector, its card vector is accessed.

players[playerNum].getPlayerHand()[0].getHandCards()

That aforementioned card is pushed onto the player's hand card vector.

players[playerNum].getPlayerHand()[0].getHandCards().push_back(newCard);

Again, I'm using a Hand object so that I can easily destroy a player's cards at the end of each turn.  In the game, different players can end up with a different number of cards at the end of each turn.  If I assign each player a vector of cards instead, I would have to loop through the vector and pop each card.  With a Hand, I can just pop the Hand and push a new one.  However, using a Hand class here means more accessing, which complicates the code's flow.

What would be a good solution to this?  I'm okay with either method (preferably the one with Hand), but they do have their pros and cons.  If there is a better solution, I'd like to know about it.

Here are snippets of the relevant class' headers:

Game.h

class Game
{
private:
    std::vector<Player> players;
    Deck deck;

public:
    Game();
    ~Game();
};

Player.h

class Player
{
private:
    std::vector<Hand> playerHand;

public:
    Player();
    ~Player();
    std::vector<Hand>& getPlayerHand() {return playerHand;}
};

Hand.h

class Hand
{
private:
    std::vector<Card> cards;

public:
    Hand();
    ~Hand();
    std::vector<Card>& getHandCards() {return cards;}
};

Card.h

class Card
{
private:
    int rankValue;
    char rank;
    char suit;
    std::string card;

public:
    Card();
    Card(char, char);
    ~Card();
};


texts: Polling script to determine the continuous time a user has been connected

texts:
I've been asked to keep track of how long a user has been connected to a site without interruption.

So far the solution I've come up with is to use ajax to poll the site every now and then to check how much time has elapsed since the last call.

Any suggestions for possible improvements would be appreciated.

P.S: Not sure why but text isn't displaying if no text is in the div or echoed.

The javascript

The PHP code

if( isset( $_POST["data"] ) ){
    $id = (int) $_POST["data"];

    $sql ='INSERT INTO users_timeconnected ( profil_id, last_ajax_call ) VALUES ('. $id .', NOW() ) ON DUPLICATE KEY UPDATE id=id';

    $db->query( $sql );

    $sql ="
    select (
        (
            unix_timestamp( now() )
            - unix_timestamp( (select last_ajax_call from users_timeconnected where profil_id =" . $id ." ) )
        ) / 60
    )";

    $db->query( $sql );

    $timeSinceLastCall = $db->fetch_one();

    $sql = 'select minutes_connected from users_timeconnected where profil_id =' . $id;

    $db->query( $sql );

    $minutesConnected = $db->fetch_one();

    echo "current time:" . date("d/m/y : H:i:s", time()).'
';
    echo "id:" . $id .'
';
    echo "time since last call:" .$timeSinceLastCall.'
';
    echo "connected:" . $minutesConnected.'
';
    echo "lower than or equal to 6:" . (int)($timeSinceLastCall <= 6);

    if( $timeSinceLastCall <= 6 ){
        $timeSinceLastCall = 0; // reset
        $sql ='UPDATE users_timeconnected SET minutes_connected = minutes_connected+5 WHERE profil_id='. $id ;
        $db->query( $sql );
        $sql ='UPDATE users_timeconnected SET last_ajax_call = NOW() WHERE profil_id='. $id;
        $db->query( $sql );
    }
}

The SQL table

CREATE TABLE IF NOT EXISTS `users_timeconnected` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `profile_id` int(10) unsigned NOT NULL default '0',
  `last_ajax_call` timestamp NULL default NULL,
  `minutes_connected` int(10) default '0',
  PRIMARY KEY  (`id`),
  UNIQUE KEY `profil_id` (`profile_id`)
);

The html for tests

Output


texts:
I figured out a alternative way to make embedded videos responsive and I like to have some feedback on it.

Would this be considered a hack or just bad coding to add a extra piece of html to make this work?

.video-wrapper {
  position: relative;
}
.make-video-responsive-img {
  width: 100%;
  height: auto;
  display: block;
}
.video-wrapper iframe,
.video-wrapper object,
.video-wrapper embed,
.video-wrapper video {
  width: 100%;
  height: 100%;
  position: absolute;
  display: block;
  top:0;
  z-index:1;
}

Vimeo Responsive with base64 img

 <img class="make-video-responsive-img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIYAAABLCAYAAAC1D//7AAAABGdBTUEAALGPC/xhBQAAAU1JREFUeAHt0rENwDAMBDHF+++cpHAj4EagARf68sBnZt7/ewqsAmddDgVuATBQyAJgZBYjGAxkATAyixEMBrIAGJnFCAYDWQCMzGIEg4EsAEZmMYLBQBYAI7MYwWAgC4CRWYxgMJAFwMgsRjAYyAJgZBYjGAxkATAyixEMBrIAGJnFCAYDWQCMzGIEg4EsAEZmMYLBQBYAI7MYwWAgC4CRWYxgMJAFwMgsRjAYyAJgZBYjGAxkATAyixEMBrIAGJnFCAYDWQCMzGIEg4EsAEZmMYLBQBYAI7MYwWAgC4CRWYxgMJAFwMgsRjAYyAJgZBYjGAxkATAyixEMBrIAGJnFCAYDWQCMzGIEg4EsAEZmMYLBQBYAI7MYwWAgC4CRWYxgMJAFwMgsRjAYyAJgZBYjGAxkATAyixEMBrIAGJnFCAYDWQCMzGIEg4Es8AFyOgGVosq9uwAAAABJRU5ErkJggg==">


texts:
I made the following wrapper for the mediainfo command line. I did this mainly because mediainfo gives me more information than os.stat, specifically it gives me the Encoded date for .wma files, while the dates in os.stat don't represent the time the files were made, but rather the date the files were compressed (they were delivered to me in a compressed folder).

But is it actually a good idea to use a class for this? I needed to do this in bulk, for 20.000 files. Also it feels inefficient to let mediainfo format the information first and then read it again, but I'm not sure how to do that otherwise.

from pathlib import Path
from subprocess import Popen, PIPE

class MediaInfo:
    """Wrapper class for the mediainfo command line tool."""

    # Define the path to the `mediainfo` command line tool.
    mediainfo = "/usr/bin/mediainfo"

    def __init__(self, filename):
        self.file = Path(filename).resolve()
        self.info = self.readinfo()

        if not self.file.is_file():
            raise OSError(f"File not found: {file}")

    def __str__(self):
        """String representation (the same as what mediainfo shows)"""
        if hasattr(self, "info") and self.info is not None:
            return self.info.strip()

        return self.readinfo().strip()

    def infofield(self, field, postread=None):
        """Find a given field and return its value.

        If the `field` is not in the mediainfo metadata, return None.
        `postread` can be a callable to, for example, cast the returned type.
        """
        val = None
        for line in self.info.split("\n"):
            if not line.strip() or not ":" in line:
                continue
            key, val = line.strip().split(" : ")
            key = key.strip()
            val = val.strip()
            if key == field:
                break

        if postread is None:
            return val
        return postread(val)

    def readinfo(self):
        # Start the command line process
        proc = Popen([self.mediainfo, str(self.file)], stdout=PIPE, stderr=PIPE)
        # Catch the output
        stdout, stderr = proc.communicate()

        if stderr:
            self.info = stderr.decode()
            raise MediaInfoException("Error in MediaInfo process", self.info)

        self.info = stdout.decode()
        return self.info

class MediaInfoException(Exception):
    """Custom exception for MediaInfo."""
    pass


texts: Comparing performance of multi- and single - thread search of a maximum number

texts:
I have a class that compares the performance of two methods (multi- and single- thread) that searches for maximum number in the string of numbers. I want to improve the performance of a multithreaded variant because I think it can work more efficiently.

public class Part4 {

    private static String PATH = "part4.txt";
    private static String ENCODING = "Cp1251";

    public static void main(String[] args) {

        int max1;
        int max2;

        String[] lines = Util.read(PATH, ENCODING).split(System.lineSeparator());

        long t1 = System.currentTimeMillis();
        max1 = findMaxMT(lines);
        long t2 = System.currentTimeMillis();
        System.out.println(max1);
        System.out.println(t2-t1);

        long t3 = System.currentTimeMillis();
        max2 = findMax(lines);
        long t4 = System.currentTimeMillis();
        System.out.println(max2);
        System.out.println(t4-t3);

    }

    public static int findMaxMT(String[] lines) {

        int max;
        List<MaxFinder> threadList = new LinkedList<>();
        List<Integer> res = new LinkedList<>();

        for (String line : lines) {
            MaxFinder thread = new MaxFinder(line);
            thread.start();
            threadList.add(thread);
        }

        threadList.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        threadList.forEach(thread -> {
            res.add(thread.getCurrentMax());
        });

        max = MaxFinder.maxFrom(res);

        return max;
    }

    public static int findMax(String[] lines) {

        List<Integer> res = new LinkedList<>();
        int max;

        for (int i = 0; i < lines.length; i++) {
            List<Integer> numbers = new LinkedList<>();
            int currentMax;

            for (String s : lines[i].split("\\s")) {
                numbers.add(Integer.parseInt(s));
            }

            currentMax = MaxFinder.maxFrom(numbers);

            res.add(currentMax);
        }

        max = MaxFinder.maxFrom(res);

        return max;
    }

}

class MaxFinder extends Thread {

    private String line;
    private int currentMax = Integer.MIN_VALUE;

    public MaxFinder(String line) {
        this.line = line;
    }

    @Override
    public void run() {
        List<Integer> numbers = new LinkedList<>();

        for (String s : line.split("\\s")) {
            numbers.add(Integer.parseInt(s));
        }

        currentMax = maxFrom(numbers);
    }

    public int getCurrentMax() {
        return currentMax;
    }

    public static int maxFrom(List<Integer> numbers) {

        int max = Integer.MIN_VALUE;

        for (int n : numbers) {
            try {
                Thread.sleep(1);
                if (n > max) {
                    max = n;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return max;
    }
}

Thread.sleep(1) is for benchmarking.


texts: Representing a graph with passable marks and actions

texts:
I wanted to have a framework to build Petri Nets from C# code. Petri net is a digraph with functional transitions and mark types. In books they tend to look like this:

Here is what I came up with - simple example:
using ServicesPetriNet;
using ServicesPetriNet.Core;
using ServicesPetriNet.Core.Attributes;
using ServicesPetriNet.Core.Transitions;
using static ServicesPetriNet.Extensions;
using static ServicesPetriNet.Core.MarkType;
namespace ServicesPetriNetCore.Core.Tests
{
    public class SimpleAssistLoop : Group<SimpleAtoB>
    {
        public Place A, B, C;

        public Transition AtoC, BtoC;

        [Probabilety(0.5)]
        public Transition CtoA;

        [Probabilety(1,1,1,0,1,0)]
        public Transition CtoB;

        public SimpleAssistLoop()
        {
            AtoC.Action<OneToOne<Mark>>()
                .In<Mark>(A)
                .Out<Mark>(C);

            BtoC.Action<OneToOne<Mark>>()
                .In<Mark>(B)
                .Out<Mark>(C);

            CtoA.Action<OneToOne<Mark>>()
                .In<Mark>(C)
                .Out<Mark>(A);

            CtoB.Action<OneToOne<Mark>>()
                .In<Mark>(C)
                .Out<Mark>(B);

            Marks = At(A, Create<Mark>());
        }

        public class Mark : MarkType
        {
        }
    }
}

more complicated example:
using System.Collections.Generic;
using System.Linq;
using ServicesPetriNet;
using ServicesPetriNet.Core;
using static ServicesPetriNet.Core.MarkType;
namespace ServicesPetriNetCore.Core.Tests
{
    public class SimpleSummChainAtoF : Group<SimpleSummChainAtoF>
    {
        public Place A, B, C, D, E, F;

        private Transition SummABCtoD, SummDEtoF;

        public SimpleSummChainAtoF()
        {
            SummABCtoD.Action<Add>()
                .In<Mark>(A)
                .In<Mark>(B)
                .In<Mark>(C)
                .Out<Mark>(D);

            SummDEtoF.Action<Add>()
                .In<Mark>(D)
                .In<Mark>(E)
                .Out<Mark>(F);

            Marks = Extensions.At(A, Create<Mark>(5))
                .At(B, MarkType.Create<Mark>(6))
                .At(C, MarkType.Create<Mark>(7))
                .At(E, MarkType.Create<Mark>(8));
        }

        public class Mark : MarkType
        {
            public int value;
        }

        public class Add
        {
            public void Action(List<Mark> marks, out Mark result)
            {
                result = new Mark() { value = marks.Aggregate(0, (i, mark) => i + mark.value) };
            }
        }
    }
}

I wanted for my graphs to be as simple in terms of code letters as possible, yet keep it plainly C# comparable (which they currently are).
And here is the main problem for me: class Add void Action is not in any way marked.
Because the user nation can have any amount of inputs and outputs like this: Action(T1in ps, ..., TNin ps, out T1out,..., out TNout) and currently is checked only in runtime. To make the things worse currently I support not only the undefined amount of named types (action arguments) but also their mixing with List for in and out. So stuff like this is supported:
    public class Add
    {
        public Mark Action(List<Mark> marks)
        {
            return new Mark() { value = marks.Aggregate(0, (i, mark) => i+mark.value) };
        }
    }

As well as this:
    public class Add
    {
        public Mark Action(Mark fromA, Mark fromB)
        {
            return  new Mark(){value = fromA.value+fromB.value};
        }
    }

So my question is: What would be the way to some-how force check user Action not at runtime?


texts: Checking where/if another creature lies in a creature's field of view

texts:
Note: this is a more specific form of this

I am working on a simulation of some virtual creatures. They all have vision that lets them see other creatures. To do this, I calculate the difference between the creature's current heading and the angles to other creatures. Then, I check if the distance between them is close enough so that the creature can see the other.

It works, but it is quite slow. This is because it has complexity O(n2). It has to loop through the array and apply the angle function to every combination of creatures. Then, it needs to check distance between some of them.

My current code:

import math
import random
def getAngle(pos1,pos2):
    dx=pos2[0]-pos1[0]
    dy=pos2[1]-pos1[1]
    rads=math.atan2(dy,dx)
    rads%=2*math.pi
    degs=math.degrees(rads)
    return degs

def getDist(pos1, pos2):
    return math.hypot(pos1[0] - pos2[0], pos1[1] - pos2[1])
def angleDiff(source,target):
    a = target - source
    a = (a + 180) % 360 - 180
    return a
class Creature(object):
    """A virtual creature"""
    def __init__(self):
        self.pos=[random.randint(0,500) for _ in range(2)] #random x,y
        self.heading=random.randint(0,360)
        self.vision=[0,0] #left and right relative to creature's perspective

creatures=[Creature() for _ in range(100)]
creatureFOV=60 #can look 60 degrees left or right
creatureViewDist=100
for creature in creatures:
    for otherC in creatures:
        if otherC==creature:continue #don't check own angle
        ang=angleDiff(creature.heading,getAngle(creature.pos,otherC.pos))
        if abs(ang) < creatureFOV:
            if(getDist(creature.pos,otherC.pos)<creatureViewDist):
                if ang < 0:
                    creature.vision[0]=1 #left side
                else:
                    creature.vision[1]=1 #right side
        if sum(creature.vision)==2:
            break #if there is already something on both sides, stop checking

I feel like it could be greatly sped up by using numPy or some other method. How can this code be optimized for more speed?


texts:
Any suggestions on how to improve the Makefile, e.g. how to best replace the multiple uses of example1/example2, ex1_src/ex2_src, ex1_obj/ex2_obj with static pattern rules?
build := ./build
targets := $(build)/example1 $(build)/example2
src := ./src

srcfiles := $(shell find $(src) \( -name "*.cpp" -or -name "*.c" \) ! -path '*/examples/*')
objects  := $(srcfiles:%=$(build)/%.o)

ex1_src := $(shell find $(src) -name example1.cpp)
ex1_obj := $(ex1_src:%=$(build)/%.o)

ex2_src := $(shell find $(src) -name example2.cpp)
ex2_obj := $(ex2_src:%=$(build)/%.o)

all_obj := $(objects) $(ex1_obj) $(ex2_obj)
depends := $(all_obj:%.o=%.d)
incdirs := $(shell find $(src) -type d ! -path '*/examples')
includes := $(addprefix -I,$(incdirs))

CXX := g++
CXXFLAGS := -std=c++17 $(includes) -Wall -MMD -MP
LDFLAGS := -lpthread

all: $(targets)

$(build)/example1: $(objects) $(ex1_obj)
$(build)/example2: $(objects) $(ex2_obj)

$(targets):
    $(CXX) $(LDFLAGS) $^ -o $@

$(build)/%.cpp.o: %.cpp
    @mkdir -p $(dir $@)
    $(CXX) $(CXXFLAGS) -c $< -o $@

.PHONY: clean
clean:
    rm -rf $(build)

-include $(depends)


texts:
I found myself writing code to run at a specified frequency more than once, so I decided to make this simple timer. My main concern is that this is not the most efficient way of doing this since with SDL I would just ask for the time in ms and sleep in ms.

I'm storing the current time in timer_update() to avoid the possibility of it becoming greater than the final time and generating a huge pause since it's unsigned.

Usage is pretty simple, timer_init() is called once before the loop and timer_update() is called once at the end of every iteration.

timer.h

#ifndef TIMER_H
#define TIMER_H

typedef struct {
    double step;
    double tfinal;
} Timer;

void timer_init(Timer *timer, double hertz);
void timer_update(Timer *timer);

#endif

timer.c

#include "timer.h"

#define _POSIX_C_SOURCE 199309L
#include <time.h>
#include <errno.h>
#include <stdio.h>

static unsigned long get_ms(void)
{
    struct timespec buffer;
    unsigned long temp;

    if(clock_gettime(CLOCK_MONOTONIC, &buffer) != 0){
        perror("clock_gettime");
        return 0;
    }

    temp = buffer.tv_sec * 1000;
    temp += buffer.tv_nsec / 1000000;
    return temp;
}

static struct timespec ms_to_timespec(unsigned long ms)
{
    struct timespec temp = {ms / 1000, (ms % 1000) * 1000000};
    return temp;
}

void timer_init(Timer *timer, double hertz)
{
    timer->step = 1000 / hertz;
    timer->tfinal = get_ms() + timer->step;
}

void timer_update(Timer *timer)
{
    unsigned long now = get_ms();
    struct timespec required_sleep, rem;

    if(now < timer->tfinal){
        required_sleep = ms_to_timespec(timer->tfinal - now);
        timer->tfinal += timer->step;

        try_to_sleep:
        if(nanosleep(&required_sleep, &rem) == -1 && errno == EINTR)
            if(nanosleep(&rem, &required_sleep) == -1 && errno == EINTR)
                goto try_to_sleep;
    }

    else
        timer->tfinal += timer->step;
}


texts: Modify and import as numpy.ndarray a txt file in python

texts:
To import the data contained into the file my_file.txt that have the form:

Label[0] = 0.980252
Label[1] = -nan
Label[2] = -nan
Label[3] = -nan
Label[4] = 0.664706
Label[5] = -nan
Label[6] = -nan
Label[7] = -nan
Label[8] = -nan
Label[9] = -nan
Label[10] = -nan
Label[11] = 0.800183
Label[12] = -nan
Label[13] = -nan
Label[14] = -nan
Label[15] = 0
Mean Data = 15

I wrote the following code:

import numpy as np

with open('myfile.txt', 'r') as file_txt_original:
    data = file_txt_original.read()

    data = data.replace('Mean data', '-1')
    data = data.replace('Label[', '')
    data = data.replace(']', '')
    data = data.replace(' = ', ', ')

    file_txt_original.close()

with open('new_file.txt', 'w') as file_txt_copy:

    file_txt_copy.write(data)
    file_txt_copy.close()

my_array = np.loadtxt('new_file.txt', delimiter=',')

It works but this to me seems still quite an tricky solution... Any suggestion to improve this code without doing so many replacement or without saving an additional structure?


texts:
This is how I convert e.g. RGB(255, 0, 0) (where red is stored in the least significant byte of a Long) to a 6-digit hex string FF0000:

Function RgbToHex(l As Long) As String
Dim r As Long
Dim g As Long
Dim b As Long
    r = l And ColorConstants.vbRed
    g = (l And ColorConstants.vbGreen) / (2 ^ 8)
    b = (l And ColorConstants.vbBlue) / (2 ^ 16)
    RgbToHex = Right$("0" & Hex(r), 2) _
             & Right$("0" & Hex(g), 2) _
             & Right$("0" & Hex(b), 2)
End Function

I'm a bit worried about the string manipulations, but as VB6 lacks printf-like formatting, this is the best I could come up with. Can it be improved?


texts:
I'm going to have a lot of integer values, and at any value change I might need to update any number of UI elements, other values which are computed from the first ones, etc.  Sounds like time for the Visitor pattern, but I'm new to Java (more comfortable in C++).  I have:

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;

public abstract class Value {
    static public interface Listener {
        public abstract void valueChanged(Value val);
    };

    public Value(int init_val) {
        mVal = init_val;
        mListeners = new ArrayList<WeakReference<Listener>>();
    }

    public int getValue() { return mVal; }

    public void setValue(int val) {
        mVal = val;
        Iterator<WeakReference<Listener>> iter = mListeners.iterator();
        while (iter.hasNext()) {
            Listener listen = iter.next().get();
            if (listen == null)
                iter.remove();
            else
                listen.valueChanged(this);
        }
    }

    public void addListener(Listener listen) {
        cleanListeners();
        mListeners.add(new WeakReference<Listener>(listen));
    }

    private void cleanListeners() {
        Iterator<WeakReference<Listener>> iter = mListeners.iterator();
        while (iter.hasNext()) {
            if (iter.next().get() == null)
                iter.remove();
        }
    }

    private int mVal;
    private ArrayList<WeakReference<Listener>> mListeners;
};

I'm wondering if there are technical, style, or common practice issues, specifically relating to:

Is this a good and correct way to use WeakReferences, or is there a simpler way?  I don't want the Value to prevent its listeners from getting cleaned up, or to manually break links when a listener is no longer needed by the UI/calculations/whatever.
Use the interface List<...> or the actual implementation type ArrayList<...> when declaring the member mListeners?
Initialize mListeners with an empty list at the member declaration, or in the constructor?

Other comments and suggestions are welcome too.


texts:
I basically check for required input fields and if they fail to validate, I need to go to another level of output, check for other required fields, and so on...

I can't get my head around this easy step-by-step validation. I already had it in a while-loop, but found it even more horrible than with beginner-like if-cases. I still think, though, that it could be written a bit simpler (and maybe improve readability).

It already is a quite simple thing to do, but in the course of development it will get bigger and bigger, so it needs to stay simple.

    // CHECK FOR REQUIRED PROPERTIES
    if($properties['step'] == 2)
    {
        $req = array('cshort','cid');
        foreach($req as $required)
        {
            if(!validate_var($req,$properties[$req]) || empty($properties[$req]))
            {
                $step = 1;
            }

        }
    }
    if($properties['step'] == 1)
    {
        $req = array('cshort');
        foreach($req as $required)
        {
            if(!validate_var($req,$properties[$req]) || empty($properties[$req]))
            {
                $step = 1;
                return $st
            }

        }
    }


texts: Project Euler # 35 Circular primes in Python

texts:
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?

Here's my implementation in Python 3. Awaiting feedback.
from time import time

def is_prime(number):
    """returns True for a prime number, False otherwise."""
    factor = 2
    while factor * factor <= number:
        if number % factor == 0:
            return False
        factor += 1
    return True

def circulate(number):
    """returns all circulations of a number."""
    for n in str(number):
        if not int(n) % 2:
            return False
    circulations = []
    digits = list(str(number))
    for i in range(len(str(number))):
        last = digits.pop()
        circulations.append(last + ''.join(digits))
        digits = [last] + digits
    return [int(x) for x in circulations]

def circular_primes(limit):
    """returns all circular primes below limit."""
    all_circulations = [2]
    for num in range(3, limit, 2):
        if is_prime(num):
            check = 0
            if circulate(num):
                circulations = circulate(num)
                for circulation in circulations:
                    if not is_prime(circulation):
                        check += 1
                if not check:
                    all_circulations.extend(circulations)
    return all_circulations

if __name__ == '__main__':
    start_time = time()
    print(len(set(circular_primes(200000))))
    print(f'Time: {time() - start_time} seconds.')


texts:
After watching this video by Tom Scott, I decided to make a program that follows that idea. This is what I came up with:

# If a number is divisible by the key, add the value
RULES = {
    3: "Fizz",
    5: "Buzz"
}

def is_divisible(num: int) -> list:
    output = []
    for divider in RULES:
        if (num % divider) == 0:
            output.append(RULES[divider])
    return output

for num in range(100):
    output = is_divisible(num + 1)  # Increment num by 1 so it is 1-100 not 0-99
    if not output:
        print(num + 1)
    else:
        print("".join(output))

My whole idea behind the way I made this is because I wanted it to be as expandable as possible. That way if you wanted to change the code to do something different (like the examples at the end of the above video), you could just add it. I would like to know if there is anything I could do to improve its changeableness and if there are any glaring problems that when fixed doesn't affect the changeability of the code.


texts: How to deal with nested objects which might be string or undefined in a clean way?

texts:
So I'm parsing an object using Typescript. I am pushing a value from within the object into an array of strings.
Here's the code:
if (data.InstanceStatuses != undefined)
            if (data.InstanceStatuses[0].InstanceId != undefined)
                instanceIds.push(data.InstanceStatuses[0].InstanceId as string)

I feel there must be a better way to deal with the fact that both data.InstanceStatuses and data.instanceStatuses[0].InstanceId can be of type string || undefined, however I am not sure how to get it down to a simpler statement with less IF blocks.
Any ideas?


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

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

See the code in action - jsFiddle

Link to repository - GitHub

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

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

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

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

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

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


texts: My yld NPM - callbacks/promises alternative

texts:
I'd like feedback on my callbacks/promises alternative, please.

The yld repository

var yld;

yld = (function () {
'use strict';

var slice, clearer, defer, prepare, yld;

slice = Array.prototype.slice;

clearer = {
    yld: {
        value: undefined
    },
    throw: {
        value: undefined
    }
};

Object.freeze(clearer);

defer = typeof process === 'object' && typeof process.nextTick === 'function' ? process.nextTick : function nextTick(closure) {
    setTimeout(closure);
};

prepare = function* (parent) {
    var proto, generator, fnGenerator, response;

    proto = {
        yld: function (fn) {
            var parent;

            parent = this;

            return function () {
                var generator, proto, fnGenerator;

                generator = prepare(parent);
                proto = generator.next().value;
                generator.next(generator);
                fnGenerator = fn.apply(proto, arguments);
                generator.next(fnGenerator);

                return Object.create(proto, clearer);
            };
        },
        next: function (value) {
            defer(function () {
                generator.next(value);
            });
        },
        nextCb: function () {
            var value;

            value = slice.call(arguments);

            defer(function () {
                generator.next(value);
            });
        },
        throw: function(error) {
            defer(function() {
                fnGenerator.throw(error);
            });
        }
    };

    if (parent !== undefined) {
        proto.parent = Object.create(parent, clearer);
    }

    generator = yield proto;
    fnGenerator = yield null;

    while (true) {
        response = yield defer(function () {
            fnGenerator.next(response);
        });
    }
};

yld = function (fn) {
    return function () {
        var generator, proto, fnGenerator;

        generator = prepare();
        proto = generator.next().value;
        generator.next(generator);
        fnGenerator = fn.apply(proto, arguments);
        generator.next(fnGenerator);

        return Object.create(proto, clearer);
    };
};

return yld;
}());

if (typeof module === 'object' && module.exports !== undefined) {
    module.exports = yld;
}


texts: Find max number of items that can fit in a given max-width

texts:
Given a list of elements, each with own width, and a max-width.
I need to find how many elements can be fit inside that max-width, keeping the order of the elements.

Some examples:

elements: { width: 10 }, { width: 20 }
max-width: 30
result count should be 2, because both elements can be fit in this max-width
elements: { width: 10 }, { width: 20 }
max-width: 5
result count should be 0, because first element cannot be fit in this max-width
elements: { width: 10 }, { width: 20 }, { width: 5 }
max-width: 20
result count should be 1, because adding the second element exceed the max-width.

This piece of javascript code solve it, but I feel it is not readable enough:

function getNumberOfElementsInWidth(elements, maxWidth) {
  let accWidth = 0;
  let count = 0;
  for (let i = 0; i<elements.length; i++) {
    if (accWidth + elements[i].width <= maxWidth) {
      accWidth = accWidth + elements[i].width;
      count++;
    } else {
      break;
    }
  }
  return count;
}

function doSample() {
  const elements = [ { width: 10 }, { width: 12 }, { width: 15 } ];
  const maxWidth = 100;

  console.log(getNumberOfElementsInWidth(elements, maxWidth));
}

doSample();

I would appreciate your feedback on how to make the code for getNumberOfElementsInWidth function clearer.


texts:
Challenge:

  Given a positive integer which fits in a \$32\$ bit signed integer,
  find if it can be expressed as \$A^P\$ where \$P > 1\$ and \$A > 0\$.
  A and P both should be integers.

  Example

  Input : 4
  Output : True
  as \$2^2 = 4\$.

My approach:

public class Solution {
    public int isPower(int A) {
        int exp, base;

        if( A == 1)
            return 1;

        if( A%2 == 0)
            {
                for( int i = 2; i < A; i+= 2 )
                  {
                        double variable = Math.log(A) / Math.log(i);
                        double formatted = Double.parseDouble(String.format( "%.6f", variable));

                        if((formatted== Math.floor(formatted)) && !Double.isInfinite(formatted))
                            return 1;
                  }
                return 0;
            }

        else
            {
                for( int i = 3; i < A/2; i+= 2 )
                  {
                       double variable = Math.log(A) / Math.log(i);
                       double formatted = Double.parseDouble(String.format( "%.6f", variable));

                        if((formatted== Math.floor(formatted)) && !Double.isInfinite(formatted))
                           return 1;
                  }
                return 0;
            }

    }
}

I have the following questions with regards to the above code:

Is there any better method to solve this question?
How can I further optimise the time and space complexity of the solution?


texts: Promise Chaining for a Firebase v3 Auth Subsystem - Password Based Users

texts:
Firebase v3 Offers Authentication via 3rd party oAuth providers, facebook, github,google, and twitter.  They also offer password pased authentication.
Authenticated users have a firebase.User object with 4 key properties - displayName, email, photoURL.  A password is required to sign in and to register.
In oAuth, the email, displayName, and photoUrl are gotten from the oAuth provider.  Developers must enter this in the Firebase v3 Auth system via an .updateProfile method for Password based users.
So, for registering new users, I collect the 4 values from <inputs> and call the below homemade function to register the new user with all the values in one go.  Promise chaining was used.  Any missing arguments must be null (not undefined prior to invoking the firebase methods).
Is there a cleaner way to chain these or does this look fairly solid.  I know it works.  I'm just seeing if it can be smartened up a bit.
createUserWithEmailAndPassword
createUserWithEmailAndPassword(email, password) returns firebase.Promise containing non-null firebase.User.  Creates a new user account associated with the specified email address and password.
updateProfile
var profile = {displayName: nullable string, photoURL: nullable string};
updateProfile(profile) returns firebase.Promise containing void.  Updates a user's profile data.
function registerPasswordUser(email,displayName,password,photoURL){
  var user = null;
  //nullify empty arguments
  for (var i = 0; i < arguments.length; i++) {
    arguments[i] = arguments[i] ? arguments[i] : null;
  }

  firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(function () {
    user = firebase.auth().currentUser;
    user.sendEmailVerification();
  })
  .then(function () {
    user.updateProfile({
      displayName: displayName,
      photoURL: photoURL
    });
  })
  .catch(function(error) {
    console.log(error.message);
  });
  console.log('Validation link was sent to ' + email + '.');
}


texts:
I have done the source code for my lesson, which I shall publish later on my website:

<script src="three.min.js"></script>
<script>

var renderer, scene, camera, geometry, material, mesh, light, axisRotation;

function createScene() {
    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.set( 3, 3, 3 );
    camera.lookAt( scene.position );
    scene.add( camera );

    geometry = new THREE.CubeGeometry( 1, 1, 1 );

    material = new THREE.MeshLambertMaterial( { color: 0xff0000 } );

    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    light = new THREE.PointLight( 0xffff00 );
    light.position.set( 10, 10, 10 );
    scene.add( light );
}

function rotateCube( axis ) {
    switch ( axis ) {
        case 'x':
            mesh.rotation.x += 0.02;
            break;
        case 'y':
            mesh.rotation.y += 0.02;
            break;
        case 'z':
            mesh.rotation.z += 0.02;
            break;
    }
}

function toggleObjectWireframe() {
    material.wireframe = !material.wireframe;
}

function renderScene() {
    renderer.render( scene, camera );
}

function animateScene() {
    requestAnimationFrame( animateScene );
    renderScene();
    rotateCube( axisRotation );
}

function getChar( event ) {
    var inputChar = null;

    if ( event.which === null ) {
        if ( event.keyCode < 32 ) inputChar = null;
        else inputChar = String.fromCharCode( event.keyCode );
    }

    if ( event.which != 0 && event.charCode != 0 ) {
        if ( event.which < 32 ) inputChar = null;
        else inputChar = String.fromCharCode( event.which );
    }

    if ( ~['x', 'y', 'z'].indexOf( inputChar ) ) {
        axisRotation = inputChar;
    }
    else if ( inputChar == 'w' ) toggleObjectWireframe();
    else inputChar = null;
}

function initWebGLApp() {
    axisRotation = 'x';
    createScene();
    animateScene();
}

function setCssStyle() {
    document.body.style.width = "100%";
    document.body.style.height = "100%";
    document.body.style.margin = 0;
    document.body.style.padding = 0;
    document.querySelector('canvas').style.display = 'block';
}

window.onload = function() {
    initWebGLApp();
    setCssStyle();
    document.onkeypress = getChar;
}

</script>

You can see the working results on JSFiddle.


texts: Streamline code for checking if a directory exists and saving a file

texts:
I hate this code.  What is the slickest way to write the following:

MyFile = f;
SaveFolder = Server.MapPath("\\") + "returns\\";
if(!System.IO.Directory.Exists(SaveFolder) )
{
    System.IO.Directory.CreateDirectory(SaveFolder);
}
MyFile.SaveAs(SaveFolder + "2011" + "000-00-0000" + ".xlsx");


texts: Simple structure that would contain validation errors messages

texts:
Before I go too far, does this look right?

This is mostly to have a "central" place that hold a "hierarchical/structured" errors message.

public static class ValidationError
{
    static ValidationError()
    {
        Prefix = "VE";
        Notice = new _Notice();
        Exporter = new _Exporter();
        Importer = new _Importer();
        Shipping = new _Shipping();
        //few others one
    }

    public static string Prefix { get; private set; }

    public static _Notice Notice { get; private set; }
    public class _Notice
    {
        public _Notice()
        {
            Prefix = ValidationError.Prefix + "NO";
            MustHaveOneTreatmentOption = Prefix + "001";
        }

        public string Prefix { get; private set; }
        public string MustHaveOneTreatmentOption { get; private set; }
    }

    public static _Exporter Exporter { get; private set; }
    public class _Exporter
    {
        public _Exporter()
        {
            Prefix = ValidationError.Prefix + "EX";
            Mailing = new Address(Prefix, "MA");
            Physical = new Address(Prefix, "PH");
        }

        public string Prefix { get; private set; }

        public Address Mailing { get; private set; }
        public Address Physical { get; private set; }
    }

    public static _Importer Importer { get; private set; }
    public class _Importer
    {
        public _Importer()
        {
            Prefix = ValidationError.Prefix + "IM";
        }

        public string Prefix { get; private set; }
    }

    public static _Shipping Shipping { get; private set; }
    public class _Shipping
    {
        public _Shipping()
        {
            Prefix = ValidationError.Prefix + "SH";
        }

        public string Prefix { get; private set; }
    }

    public class Address
    {
        public Address(string _Prefix, string _Suffix)
        {
            Prefix = _Prefix + _Suffix + "AD";
        }

        public string Prefix { get; private set; }
    }
}


texts:
I wrote a short program for my exercise routine. It takes a JSON array of exercise names and duration (seconds) and puts it on the screen. The JSON looks like this:

var exerciseArray = [
    {
        "desc":       "Pushup/Pullup",
        "countdown":  30
    }, {
        "desc":       "Squat punch",
        "countdown":  45
    }, {
        "desc":       "Jumping jacks",
        "countdown":  60
    }
];

The function works, but it seems to be to be kind of a kludge. My problem was that I couldn't figure out how work with setInterval to iterate through the list of exercises (exerciseArray). What I did in the end is just decrement the countdown value, and when it's zero, move to the next item in exerciseArray (i++;). When I hit the end of the array — as measured by i and exerciseArray.length — I just run clearInterval and I'm done. Code below (I removed some of the extraneous stuff that just updates the HTML with the number of seconds, you can see the full thing on github):

function exerciseTimer(exerciseArray) {
    var i = 0;
    var exerciseObject = exerciseArray[i];
    // do stuff
    var tt = setInterval(function() {
        var exerciseObject = exerciseArray[i];
        // write html to the page
        exerciseObject.countdown = exerciseObject.countdown - 1;
        if (exerciseObject.countdown <= 0) {
            if(i < (exerciseArray.length - 1)) {
                i++;
            } else {
                clearInterval(tt);
            }
        }
    }, 100);
}

My question is, what is the appropriate way to iterate while using setInterval? Is there a cleaner way? This feels very ugly to me.


texts:
I am trying to have a Backbone.Model which is a singleton and I wish to instantiate it lazily. I only need to support modern browsers so please do not worry about the use of ES5 getter.

Is this the simplest way of achieving my goal?

var LazySingleton = function(){
    var _LazySingleton = Backbone.Model.extend({
        defaults: {
            foo: 0
        },
        initialize: function(){
            console.log('I am initializing');
        }
    });

    return {
        _instance: null,
        get instance() {
            if (this._instance === null) {
                this._instance = new _LazySingleton();
            }

            return this._instance;
        }
    };
}();

console.log('LazySingleton has been declared, but not initialized');
LazySingleton.instance.set('foo', 3);
console.log('foo should be 3:', LazySingleton.instance.get('foo'));


texts: Get list and default value of columns of table with Eloquent

texts:
I use the below code to get a list of columns in a table, and assign the default value to the protected var $attributes in a Laravel Model.

In this code, I use the DB function because I don't know how to achieve the same result with Eloquent.

Model.php

protected $attributes = [];

public function __construct(array $attributes = array())
{
    parent::__construct($attributes);

    $columns = DB::connection()->getDoctrineSchemaManager()->listTableColumns('mailboxes');

    foreach ($columns as $column) {
        $name = $column->getName();
        $value = $column->getDefault();
        if (!is_null($value)) {
            $this->attributes[$name] = $value;
        }
    }
}
```


texts:
Here's the code

max="$1"
date
echo "url: $2
rate: $max calls / second"
START=$(date +%s);

get () {
  curl -s -v "$1" 2>&1 | tr '\r\n' '\\n' | awk -v date="$(date +'%r')" '{print $0"\n-----", date}' >> /tmp/perf-test.log
}

while true
do
  echo $(($(date +%s) - START)) | awk '{print int($1/60)":"int($1%60)}'
  sleep 1

  for i in `seq 1 $max`
  do
    get $2 &
  done
done

This can be run as

sh load-test.sh 20 "http://api.myserver.com/get_info"

Please suggest if you think there's a way to take in multiple curl options.


texts:
I am implementing a modal dialog in my Android application, allowing the user to either pick a player from a list, or create one with predefined traits.

PlayerPickerListener

public interface PlayerPickerListener {
    Activity getActivity();
    void playerCreated();
}

PlayerPicker (extends Dialog)

public PlayerPicker(Context context, String title, final PlayerPickerListener listener) {
    super(context);

    setTitle(title);
    setContentView(R.layout.player_dialog);

    View.OnClickListener changeHandler = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // PlayersActivity is basically a ListView selecting the player
            Intent intent = new Intent(listener.getActivity(), PlayersActivity.class);
            intent.putExtra(REQ_CODE, SELECT_ACTION);
            listener.getActivity().startActivityForResult(intent, SELECT_ACTION);
        }
    };

    Button b = (Button) findViewById(R.id.button_change);
    b.setOnClickListener(changeHandler);

    View.OnClickListener newHandler = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EntityPlayer player = PlayerManager.createNewPlayer();
            listener.playerCreated();
        }
    };
    b = (Button) findViewById(R.id.button_new);
    b.setOnClickListener(newHandler);

}

MainActivity (implements PlayerPickerListener)

public Activity getActivity() { return this; }

public void displayPlayer(View view) {
    myPlayerPicker = new PlayerPicker(this, "Pick a player", this);
    myPlayerPicker.show();
}

public void playerCreated() {
    myPlayerPicker.dismiss();
    // some extra stuff
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PlayersActivity.SELECT_ACTION && resultCode == RESULT_OK && data != null) {
        myPlayerPicker.dismiss();
        // some extra stuff
    }
    super.onActivityResult(requestCode, resultCode, data);
}

I have the following issues with my approach:

I am led to add the getActivity() method in my listener, because I have no other way of starting an intent from the Dialog. I need an intent to go to my ListView and return with a result.
Because of the above behavior, I am calling dismiss() on my Dialog from inside my Activity. For the new player case, I could easily add the dismissal of the Dialog inside the OnClickListener, but I am leaving it on the Activity just to have a type of uniform behavior.

My main question is whether it is common practice to dismiss a Dialog in its own code, or externally.

I'd argue that it would not seem natural for a dialog to be shut down from another source. A Dialog should disappear when its objective is complete. Is this bad design?


texts: Improving performance of function to multiply vector with a matrix?

texts:
I wrote this function to multiply vector with a matrix and I was wondering if someone experienced can spot something can improved its performance.
class matrix:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.m = [[0 for i in range(width)]for i in range(height)]

class vec2:
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.vals = [x, y]

class vec3:
    def __init__(self, x, y, z):
        self.x, self.y, self.z = x, y, z
        self.vals = [x, y, z]

matrix = matrix(3, 3)
matrix.m[0][0] = 2
matrix.m[0][1] = 1
matrix.m[0][2] = 0.5
matrix.m[1][0] = 1
matrix.m[2][0] = 1
matrix.m[1][2] = 0.2

vector = vec3(1, 10, 10)

def multVecMat(vec, mat):
    canCarryOut = False
    if vec.__class__.__name__ == "vec3":
        if mat.width == 3 and mat.height == 3:
            canCarryOut = True
            newVec = vec3(0, 0, 0)
    else:
        if vec.__class__.__name__ == "vec2":
            if mat.width == 2 and mat.height == 2:
                canCarryOut = True
                newVec = vec2(0, 0)

    if canCarryOut:
        vecValues = []
        for v in range(mat.width):
            tempValues = []
            for m in range(mat.height):
                tempValues.append(vec.vals[v]*mat.m[v][m])
            vecValues.append(sum(tempValues))
        if vec.__class__.__name__ == "vec3":
            newVec.x, newVec.y, newVec.z = vecValues[0], vecValues[1], vecValues[2]
        else:
             newVec.x, newVec.y = vecValues[0], vecValues[1]

        return newVec
    raise ValueError

v = multVecMat(vector, matrix)
print(v.x, v.y, v.z)