texts: A fast approach to prime number sieving (non-threaded array)

texts:
I am posting this question for input on comparisons between other sieving methods and opinions on what I have discovered. I believe this might be the fastest (singular, non-threaded) array implementation of prime sieving to date, correct me if I am wrong.

My rudimentary benchmark tests stand as follows:

My optimized code: 4 seconds   N = 1,000,000,000
My original code: 7 seconds   N = 1,000,000,000
Standard Sieve-of-Eratosthenes: 16 seconds  N = 1,000,000,000

I have seen PrimeSieve and as I understand it utilizes better means to compute faster, but as it seems - it must dump the data somewhere and retrieve it to utilize it again, because it cycles the computations through the cache only.

My original thread with same pseudo-code is here, however, my original Java code did not match the pseudo-code I developed (but essentially performed similar functions at a lesser speed and easier complexity to code).

Pseudo-code as follows:

Initialize list with initial values \$(2, 3)\$.
Use the formula \$6k ± 1\$ where \$k = 1\$ and must increment by \$1\$. Store values to list.
Compute step two up to a product \$n\$, where \$n > 7\$ if \$k = 1\$.
Starting with \$x = 5\$, remove all products of \$x \times y\$ (up to \$n\$),
where \$y\$ starts at \$x\$ and
increments to the next number in the list as \$x\$ remains the same.
Repeat step four by assigning \$x\$ to the next number in the list.
Stop when \$x \times y > n\$.
Final step: We must remove all factors of the square of every prime number \$(25, 49)\$

//-----------------------------------------------------------------
//  Class:   SixesSieve.java
//  Author:  Alex Lieberman
//  Purpose: Finds all prime numbers up to a specified
//           maxNumber (exclusive) and marks them as true in the boolean array.
//-----------------------------------------------------------------

public class SixesSieve {
  public static void main (String[] args) {

   int maxNumber = 1000000000;
   boolean[] isPrime = new boolean [maxNumber];
   isPrime[2] = true;
   isPrime[3] = true;

   for (int i = 5, j = 7; i < maxNumber; i+=6, j+=6) {
     isPrime[i] = true;
     if (j < maxNumber)
      isPrime[j] = true;
    }

   for (int a = 5; a*a <= maxNumber; a+=2) {
     if (isPrime[a]) {

       for (int b = a, z = a*a; b*a <= maxNumber; ) {
        if(b*a == z && z < maxNumber/2) {
         while (true){
           if (z <= maxNumber) {
            isPrime[z] = false;
            z = z+(a*a*2);
           }
           else
            {b+=2; break;}
           }
         }
        else {
         isPrime[b*a] = false;
         b+=2;
         while (!isPrime[b])
         {b+=2;}
        }
       }
      }
    }

    for (int i = 0; i < maxNumber; i++) {
      if (isPrime[i])
       System.out.print(i + " ");
    }
  }
 }


texts: If height param is not number - then log and set to default

texts:
I am creating a class with a constructor and instead of double handling, I thought I would use a one line conditional and if the class property is not set correctly then console.log out a message.

I want to know if there is a cleaner implementation for the following height property as at the moment I don't think readability is overly terrific.

This is basically what I have:

class Example1 {
  constructor(height) {
    this.defaultHeight = 100;

    this.height = !isNaN(height) ? height : (() => {
      console.log("That was not a number >> " + height);
      return this.defaultHeight
    })();

  }
}

//////////////////////////////////////////////////////////////////////
console.log("init example 1 w/ height of 0")
var example1 = new Example1(0);
console.log("example1.height is ", example1.height);
console.log("init example 2 w/ height of 'bob'")
var example2 = new Example1("bob");
console.log("example2.height is ", example2.height);


texts: Validation for DTO using DataAnnotations

texts:
I need validation for all DTO objects using System.ComponentModel.DataAnnotations.
You can see how I implemented. Idea is to have one abstract class that will be inherited  in all dto classes.
This abstract class have check if object is valid and get all validation results.

Is this good approach?

What do you think?

dto base class :

  public abstract class DtoBase : IValidatableObject
    {
        public virtual IEnumerable<ValidationResult> GetValidationResult()
        {
            return Validate(new ValidationContext(this));
        }

        public bool IsValid()
        {
            return Validate(new ValidationContext(this)).Count() == 0;
        }

        public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List<ValidationResult>();
            Validator.TryValidateObject(this, validationContext, results, true);

            return results;
        }
    }

dto work item :

 public class WorkItemDto : DtoBase
    {
        public WorkItemDto()
        {
        }

        public int Id { get; set; }

        [StringLength(500, MinimumLength = 200)]
        public string Description { get; set; }

        [Range(20, 5000)]
        public int ItemNumValue { get; set; }

        public ICollection<ItemUsageDto> Usage { get; set; }
    }

Example how to use in wpf or in mvc project (it have to work in any client):

 var item = new WorkItemDto();
 item.Description = "my descryption";
 item.ItemNumValue = 5;
 item.Id = 7;

 var isValid = item.IsValid();
 var allResults = item.GetValidationResult();


texts: A simple C WinAPI program for terminating processes via process image names

texts:
(Also, see the next iteration.)
I have this small program for terminating processes via their respective process image names (.exe files):
#include <stdio.h>
#include <windows.h>
#include <TlHelp32.h>

int main(int argc, char* argv[]) {
    if (argc != 2) {
        puts("processkiller.exe PROCESS_NAME");
        return EXIT_SUCCESS;
    }

    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE) {
        while (Process32Next(snapshot, &entry) == TRUE) {
            if (strcmp(entry.szExeFile, argv[1]) == 0) {
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS,
                                              FALSE,
                                              entry.th32ProcessID);
                TerminateProcess(hProcess, 0);
                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);
    return EXIT_SUCCESS;
}

Note that you need to run processkiller.exe in administrator mode in order to actually terminate the requested processes.
Critique request
Please tell me anything that comes to mind.


texts:
I'm trying to improve the security for my backend:

/**
 *  This is the script that is executed when I add a new user - after the input has passed the validation.
 */
    $salt = base64_encode(mcrypt_create_iv(24,MCRYPT_DEV_URANDOM));  //  generate a random 32 character salt
    $hash = hash('sha256',$salt.$_POST['secret']);  //  create a 64 character hash based on the salt and the password

    $ins = $con['site']->prepare('INSERT INTO users (handle, salt, hash) VALUES (:handle, :salt, :hash)');
    $ins->execute(array(':handle'=>$_POST['handle'], ':salt'=>$salt, ':hash'=>$hash));
    if($ins){
        KD::addNotice('success','...message...');
    } else {
        KD::addNotice('error','...message...');
    }

/**
 *  This is the script that is executed when the user is logging in - also after the input has passed the validation.
 */
    $qry = $con['site']->prepare('SELECT handle, salt, hash FROM users WHERE handle = :handle');
    $qry->execute(array(':handle'=>$_POST['handle']));  //  look up the handle (username)
    if($qry->rowCount()==1){
        $get = $qry->fetch();
        if(hash('sha256',$get['salt'].$_POST['secret'])==$get['hash']){
            KD::addNotice('success','...message...');
            session_regenerate_id();
            $_SESSION['backend']->login($get['handle']);
        } else {
            KD::addNotice('error','...message...');
        }
    } else {
        KD::addNotice('error','...message...');
    }

This is as far as I've gotten and it works. I'm generating an unpredictable salt, creating a hash and saving it to a database.  Although this is an improvement from what it used to be, I'm fully aware of that there's more work to be done here.

I've been reading a bit about iterations. Or, rehashing the password, or the salt, or the hash, a couple of thousand times in order to prevent different forms of attacks. Could some of you please tell me how something like that could be implemented into my code?

Is it just putting some part of the code inside a for-loop when creating and verifying the password?


texts:
As a C++ beginner coming from Java, I have become increasingly confused on the topic of memory management and how to avoid memory leaks. Is the code below risking a memory leak that I'm not currently aware of? Any help or constructive feedback would be greatly appreciated.
#pragma once

template <class T>
class DynamicArray {
private:
    T *m_arr;
    int m_length; //amount of elements currently being stored in the array
    int m_capacity; //actual size of the array
public:
    DynamicArray();
    ~DynamicArray();
    T get(int index); //O(1)
    void add(T obj); //no need to push any objects forward, O(1)
    void insert(int index, T obj); //pushes forward all objects in front of the given index, then sets the obj at the given index, O(n)
    void set(int index, T obj); //sets the given index of m_arr as obj, O(1)
    void remove(int index); //removes the object at the given index and pushes all the array contents back, O(n)
    int size(); //O(1)
    void print();
};

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

template<class T>
DynamicArray<T>::DynamicArray() : m_arr(new T[1]), m_length(0), m_capacity(1) {}

template<class T>
DynamicArray<T>::~DynamicArray() {
    delete[] m_arr;
}

template<class T>
T DynamicArray<T>::get(int index) {
    if (index < m_length && index >= 0)
        return m_arr[index];
    else throw ("Index out of bounds!");
}

template<class T>
void DynamicArray<T>::set(int index, T obj) {
    if (index < m_length && index >= 0) {
        m_arr[index] = obj;
    } else throw ("Index out of bounds!");
}

template<class T>
void DynamicArray<T>::add(T obj) {
    if (m_length == m_capacity) {
        T *new_arr = new T[m_length * 2];

        for (int i = 0; i < m_length; i++) {
            new_arr[i] = m_arr[i];
        }

        delete[] m_arr;
        m_arr = new_arr;
        m_capacity = m_capacity * 2;
    }
    m_arr[m_length] = obj;
    m_length++;
}

template<class T>
void DynamicArray<T>::insert(int index, T obj) {
    if (index < m_length && index >= 0) {
        int size;
        if (m_length == m_capacity) size = m_length * 2;
        else size = m_capacity;
        T *new_arr = new T[size];

        for (int i = 0, j = 0; i < m_length; i++, j++) {
            if (i == index) {
                new_arr[j] = obj;
                j++;
            }
            new_arr[j] = m_arr[i];
        }

        delete[] m_arr;
        m_arr = new_arr;
        m_capacity = m_capacity * 2;
        m_length++;
    } else throw ("Index out of bounds!");
}

template<class T>
void DynamicArray<T>::remove(int index) {
    if (index < m_length && index >= 0) {
        T *new_arr = new T[m_capacity];

        for (int i = 0, j = 0; i < m_length; i++, j++) {
            if (i == index) i++;
            if(i < m_length) new_arr[j] = m_arr[i];
        }

        delete[] m_arr;
        m_arr = new_arr;
        m_capacity = m_capacity * 2;
        m_length--;
    } else throw ("Index out of bounds!");
}

template<class T>
int DynamicArray<T>::size() {
    return m_length;
}

template<class T>
void DynamicArray<T>::print() {
    std::cout << m_arr[0];
    for (int i = 1; i < m_length; i++) {
        std::cout << ", " << m_arr[i];
    }
}


texts: Eliminating repetitiveness in code to test hash functions

texts:
I usually take my school code as a playground to mess around with things. I was given a bunch of premade hash functions and had to test their output and find when they reach a specific lower range. Since the functions all have the same structure, I made a check function that uses a function pointer parameter(I think this is the most efficient way to deal with this problem?). Which I'm iterating through the potential keys to feed to all of the functions it I wanted it to stop at the first one of each, but couldn't think of a way to do so without using 11 individual flags or for loops. I've never messed with bitmasks (I specifically only remember the gist of them because there was a couple commands in quake3 that used them!), but I did that instead and it turned out to not be as pretty/elegant as I thought it would in practice.

in short:

How would you approach the assignment "Using the given 11 hash functions, find each of their first 'low' output?"

void findLowHash();
bool foundLow(unsigned int (*hash)(const std::string &key), std::string key);

void findLowHash() {
  string key;
  key.push_back(0);
  int mask = 2047;
  for (int i = 0; i < 100000; ++i) {
    incrStr(key);
    carryStr(key);
    if (mask == 0)
      break;
    if (mask >> 0 & 1) {
      if (foundLow(RSHash, key)) {
        mask -= 1;
        cout << "RSHash"
             << " " << mask << endl;
      }
    }
    if (mask >> 1 & 1) {
      //cout<<JSHash(key)<<" "<<key<<endl;
      if (foundLow(JSHash, key)) {
        mask -= 2;
        cout << "JSHash"
             << " " << mask << endl;
      }
    }
    if (mask >> 2 & 1) {
      if (foundLow(PJWHash, key)) {
        mask -= 4;
        cout << "PJWHash"
             << " " << mask << endl;
      }
    }
    if (mask >> 3 & 1) {
      if (foundLow(ELFHash, key)) {
        mask -= 8;
        cout << "ELFHash"
             << " " << mask << endl;
      }
    }
    if (mask >> 4 & 1) {
      if (foundLow(BKDRHash, key)) {
        mask -= 16;
        cout << "BKDRHash"
             << " " << mask << endl;
      }
    }
    if (mask >> 5 & 1) {
      if (foundLow(SDBMHash, key)) {
        mask -= 32;
        cout << "SDBMHash"
             << " " << mask << endl;
      }
    }
    if (mask >> 6 & 1) {
      if (foundLow(DJBHash, key)) {
        mask -= 64;
        cout << "DJBHash"
             << " " << mask << endl;
      }
    }
    if (mask >> 7 & 1) {
      if (foundLow(DEKHash, key)) {
        mask -= 128;
        cout << "DEKHash"
             << " " << mask << endl;
      }
    }
    if (mask >> 8 & 1) {
      if (foundLow(FNVHash, key)) {
        mask -= 256;
        cout << "FNVHash"
             << " " << mask << endl;
      }
    }
    if (mask >> 9 & 1) {
      if (foundLow(BPHash, key)) {
        mask -= 512;
        cout << "BPHash"
             << " " << mask << endl;
      }
    }
    if (mask >> 10 & 1) {
      if (foundLow(APHash, key)) {
        mask -= 1024;
        cout << "APHash"
             << " " << mask << endl;
      }
    }
  }
}

bool foundLow(unsigned int (*hash)(const std::string &key), std::string key) {
  if ((*hash)(key) < 10000) {
    std::cout << "key: " << key << " Output:" << ((*hash)(key)) << " ";
    return true;
  }
  return false;
}


texts: Creating unique names for uploaded images

texts:
I am trying to create a unique name for my uploaded images. It works, but I wonder whether I should make a few changes or not.

HTML

    <form action="upload.php" method="post" enctype="multipart/form-data" name="uploadform">
        <input type="hidden" name="MAX_FILE_SIZE" value="350000">
        <input name="picture" type="file" id="picture" size="50">
        <input name="upload" type="submit" id="upload" value="Upload Picture!">
    </form>

PHP

// if something was posted, start the process...
if (isset($_POST['upload'])) {

// define the posted file into variables
    $name = $_FILES['picture']['name'];
    $tmp_name = $_FILES['picture']['tmp_name'];
    $type = $_FILES['picture']['type'];
    $size = $_FILES['picture']['size'];

// if your server has magic quotes turned off, add slashes manually
    if (!get_magic_quotes_gpc()) {
        $name = addslashes($name);
    }

// open up the file and extract the data/content from it
    $extract = fopen($tmp_name, 'r');
    $content = fread($extract, $size);
    $content = addslashes($content);
    fclose($extract);

// connect to the database
    include "../cn/connect.php";

    $name = md5($name);
    $name = $name . uniqid($name);

    $path = $_FILES['picture']['name'];
    $ext = pathinfo($path, PATHINFO_EXTENSION);
    $name = $name.".".$ext;

// the query that will add this to the database
    $stmt = $sqli->prepare("INSERT INTO image1(name, type, size) VALUES (?,?,?)");
    $stmt->bind_param("sss", $name, $_FILES['picture']['type'], $_FILES['picture']['size']);
    $stmt->execute();
    $stmt->close();
    echo "Mission has been completed, sir!";

    if (!empty($_FILES)) {
        $target = "upload/";
        $target = $target . basename($_FILES['picture']['name']);
        $ok = 1;
        $picture_size = $_FILES['picture']['size'];
        $picture_type = $_FILES['picture']['type'];
        //This is our size condition
        if ($picture_size > 5000000) {
            echo "Your file is too large.
";
            $ok = 0;
        }

        //This is our limit file type condition
        if ($picture_type == "text/php") {
            echo "No PHP files
";
            $ok = 0;
        }

        //Here we check that $ok was not set to 0 by an error
        if ($ok == 0) {
            Echo "Sorry your file was not uploaded";
        } //If everything is ok we try to upload it
        else {
            if (move_uploaded_file($_FILES['picture']['tmp_name'], $target)) {
                echo "The file " . basename($_FILES['picture']['name']) . " has been uploaded
";
            } else {
                echo "Sorry, there was a problem uploading your file.";
            }
        }
    }

    echo "Successfully uploaded your picture!";
} else {
    die("No uploaded file present");
}


texts:
class BinaryTreeNode {

  private BinaryTreeNode left;
  private BinaryTreeNode right;
  private int data;

  BinaryTreeNode(int d) {
    data = d;
  }

  public void insertLeft(BinaryTreeNode n) {
    this.left = n;
  }

  public void insertRight(BinaryTreeNode n) {
    this.right = n;
  }

  public int height() {
    // height = Max(Hl, Hr) + 1
    int leftHeight = this.left != null ? left.height() : -1;
    int rightHeight = this.right != null ? right.height() : -1;
    return Math.max(leftHeight, rightHeight) + 1;
  }

  public String toString() {
    String leftStr = this.left == null ? "" : this.left.toString();
    String rightStr = this.right == null ? "" : this.right.toString();
    return leftStr + " : " + data + " : " + rightStr;
  }

  public static void main(String[] s) {
    BinaryTreeNode n  = new BinaryTreeNode(0);//             0         l0
                                              //            / \
    BinaryTreeNode l1 = new BinaryTreeNode(1);//           1   4       l1
                                              //          /
    BinaryTreeNode l2 = new BinaryTreeNode(2);//         2             l2
                                              //        /
    BinaryTreeNode l3 = new BinaryTreeNode(3);//       3               l3
    l2.insertLeft(l3);
    l1.insertLeft(l2);
    n.insertLeft(l1);
    n.insertRight(new BinaryTreeNode(4));
    System.out.println(n.height());
    System.out.println(isBalanced(n));
  }

  public static boolean isBalanced(BinaryTreeNode n) {
    // if height = (|hl - hr|) <=1
    int leftHeight = n.left != null ? n.left.height() : -1;
    int rightHeight = n.right != null ? n.right.height() : -1;
    return leftHeight - rightHeight <= 1;
  }
}


texts: Moving files from a directory to multiple with names same as file

texts:
I have a folder containing thousands of files and directories. I
  would like to move all the files that are not contained in a sub
  directory into a directory and name it the file name, while leaving
  the files already inside of directories alone, ie:

  create 'newdir' ;   move 123.mp4 ; into 'newdir' ; change name 'newdir' to
  '123' ; repeat .

In response to the mentioned question, I posted an answer with the following script.

#%%
import os

# %%
source = "/Users/me/Desktop/folder" # notice the missing last "/"
filenames = next(os.walk(source))[2]
filenames = [ x for x in filenames if not ".DS_Store" in x]
#%%
dirpaths = [os.path.splitext(file)[0] for file in filenames]

# %%
def making(directory,source=source):
   directory = os.path.join(source,directory+"/")
   os.makedirs(directory)

a = [making(directory) for directory in dirpaths]     #list comprehension could be faster than loops.

# %%
def movingfiles(onefile, source=source):
   os.rename(source + "/" + onefile, source + "/" + os.path.splitext(onefile)[0] + "/"  + onefile )

b = [movingfiles(onefile) for onefile in filenames]       #useless list again.

I want to know whether list comprehensions are better the way I used them. Also, I know that I can avoid the directory list and making a lot of empty directories at once by putting them in one function (and make "the" directory on the spot), but can anything else be improved? For e.g., I had to put a note to avoid putting / in source. Also, is this way of using lists to perform a function actually helpful?


texts:
Another more simple project from my CS1 class that I didn't upload while I was sick last week:

  Write a program that computes all of the following statistics for a
  file and outputs the statistics to both the screen and to another
  file: the total number of occurrences of characters in the file, the
  total number of non-whitespace characters in the file, and the total
  number of occurrences of letters in the file.

I must use at least two functions in this project. In addition, I am also supposed to count and output the number of occurrences of each character.

fileStats.cpp:

/**
 * @file fileStats.cpp
 * @brief
 * @author syb0rg
 * @date 10/23/14
 */

#include <iostream>
#include <sstream>
#include <fstream>

constexpr int ARRAY_LENGTH = 128;

struct Data
{
    size_t total = 0;
    size_t nonWhite = 0;
    size_t letters = 0;
    size_t charCount[ARRAY_LENGTH] = {0};
};

std::string constructString(Data data)
{
    std::stringstream sstm;
    sstm << "Number of characters: " << data.total << "\n";
    sstm << "Number of non-whitespace characters: " << data.nonWhite << "\n";
    sstm << "Number of letters: " << data.letters << "\n" << "\n";

    sstm << "Occurances of each character: " << "\n";
    for (int i = 0; i < ARRAY_LENGTH; ++i)
    {
        if(data.charCount[i]) sstm << (char) i << ": " << data.charCount[i] << "\n";
    }
    return sstm.str();
}

void outputToFile(std::string fileName, std::string str)
{
    std::ofstream out(fileName);
    out << str;
    out.close();
}

int main()
{
    Data data;
    std::ifstream file("test.txt");
    char input = '\0';

    while ((input = file.get()) && file.good())
    {
        data.total++;
        data.charCount[input]++;
        if(!isblank(input)) data.nonWhite++;
        if(isalpha(input)) data.letters++;
    }
    file.close();

    std::string result = constructString(data);
    outputToFile("output.txt", result);
    std::cout << result;
}


texts:
I'm not a great JS coder so I need your expertises to look into my code (although nothing very special and it works fine) to see if it is good practise or not because I heard that dodgy JS coding might slow down the site especially when it comes to reading mouse or user events.

function textbox_clear_default(form_field, mouse_event)
{
    var field_data = (document.getElementById(form_field).value).replace(/ /gi, '');
    var lower_case = field_data.toLowerCase();

    if (form_field == 'text_site_search')
    {
        if (lower_case == 'sitesearch')
        {
            document.getElementById(form_field).value = '';
        }
    }

    if (mouse_event == 'onclick')
    {
        if (lower_case == 'sitesearch')
        {
            document.getElementById(form_field).value = '';
        }
    }

    if (mouse_event == 'onblur')
    {
        if (lower_case == 'sitesearch' || lower_case == '')
        {
            document.getElementById(form_field).value = 'Site Search';
        }
    }
}
<input id="text_site_search" type="text" name="text_site_search" value="Site Search" onclick="textbox_clear_default(this.id, 'onclick')" onblur="textbox_clear_default(this.id, 'onblur')" />


texts:
This is a program for converting English to the pseudo-language Pig Latin. Not the strictest form of Pig Latin but it most likely will accurately output an argument in Pig Latin. I got the idea from a list of ideas on Github. Is there any way I can improve it concisely?

def pig_latin(message):
    consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y',
                  'z']
    new_message = ''

    for word in message.split():
        ay = ['a', 'y']
        listed_word = list(word)
        word_copy = word
        moved_consonants = ''

        for letter in listed_word.copy():
            if letter.lower() == 'y':
                if letter in word_copy[0]:
                    moved_consonants += letter
                    listed_word.remove(letter)
                else:
                    break
            elif letter.lower() in consonants:
                moved_consonants += letter
                listed_word.remove(letter)
            else:
                break

        listed_word.append('-' + moved_consonants + ''.join(ay))
        new_message += ''.join(listed_word) + ' '

    return new_message

print(pig_latin('Can you read pig latin?'))


texts: Monkey-patching native JavaScript constructors

texts:
I've written a small utility for monkey-patching native JavaScript constructor functions. For example, you can use it to modify input arguments before returning an instance (this can be useful for unit tests).

There is much more detail about the utility on GitHub, so it may be useful to read through the readme on there.

I would be interested to know if I've hugely over-engineered this. There may be simpler techniques that I could take advantage of. Any comments are appreciated.

Here is the code:

var patch = (function () {
    /*jshint evil: true */

    "use strict";

    var global = new Function("return this;")(), // Get a reference to the global object
        fnProps = Object.getOwnPropertyNames(Function); // Get the own ("static") properties of the Function constructor

    return function (original, originalRef, patches) {

        var ref = global[originalRef] = original, // Maintain a reference to the original constructor as a new property on the global object
            args = [],
            newRef, // This will be the new patched constructor
            i;

        patches.called = patches.called || originalRef; // If we are not patching static calls just pass them through to the original function

        for (i = 0; i < original.length; i++) { // Match the arity of the original constructor
            args[i] = "a" + i; // Give the arguments a name (native constructors don't care, but user-defined ones will break otherwise)
        }

        if (patches.constructed) { // This string is evaluated to create the patched constructor body in the case that we are patching newed calls
            args.push("'use strict'; return (!!this ? " + patches.constructed + " : " + patches.called + ").apply(null, arguments);");
        } else { // This string is evaluated to create the patched constructor body in the case that we are only patching static calls
            args.push("'use strict'; return (!!this ? new (Function.prototype.bind.apply(" + originalRef + ", [{}].concat([].slice.call(arguments))))() : " + patches.called + ".apply(null, arguments));");
        }

        newRef = new (Function.prototype.bind.apply(Function, [{}].concat(args)))(); // Create a new function to wrap the patched constructor
        newRef.prototype = original.prototype; // Keep a reference to the original prototype to ensure instances of the patch appear as instances of the original
        newRef.prototype.constructor = newRef; // Ensure the constructor of patched instances is the patched constructor

        Object.getOwnPropertyNames(ref).forEach(function (property) { // Add any "static" properties of the original constructor to the patched one
            if (fnProps.indexOf(property) < 0) { // Don't include static properties of Function since the patched constructor will already have them
                newRef[property] = ref[property];
            }
        });

        return newRef; // Return the patched constructor
    };

}());

And here's an example usage (this is a real-world use case for working around a bug in date parsing in PhantomJS):

Date = patch(Date, "DateOriginal", {
    constructed: function () {
        var args = [].slice.call(arguments);
        if (typeof args[0] === "string" && /^\d{4}\/\d{2}$/.test(args[0])) {
            args[0] = args[0] + "/02"; // Make sure the argument has a 'day'
        }
        return new (Function.prototype.bind.apply(DateOriginal, [{}].concat(args)));
    }
});

There are some more examples, and details of the arguments to patch in the GitHub readme.


texts:
I am trying to give styles to the transport links li. I have done it, but I have a feeling it could be a cleaner code and I am not completely sure if using absolute position is the best approach here. Perhaps I should use before pseudo-class. Could you please point me out what it the best and clean way to achieve this?

Here is the link.

  #main .descript strong {
  font-family: 'proxima_nova_altbold';
  display: block;
  font-weight: 700;
  padding: 20px 0px 16px 0px;
  color: #000;
  font-size: 14px;
  border-bottom: solid 1px #e0e0e0;
  }
  /* line 226, ../sass/main.scss */
  #main .descript ol {
  list-style: none;
  padding: 0px;
  width: 100%;
  margin-bottom: 2px;
  }
  /* line 229, ../sass/main.scss */
  #main .descript ol li {
  width: 50%;
  float: left;
  height: 53px;
  border-bottom: solid 1px #e0e0e0;
  position: relative;
  color: #000;
  padding-left: 34px;
  font-size: 13px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  }
  /* line 236, ../sass/main.scss */
  #main .descript ol li img {
  float: left;
  position: absolute;
  left: 0px;
  top: 0px;
  }
  /* line 237, ../sass/main.scss */
  #main .descript ol li span {
  display: block;
  color: #9c9c9c;
  padding-bottom: 6px;
  }
  /* line 242, ../sass/main.scss */
  #main .descript ol li em {
  font-family: 'proxima_nova_altbold';
  position: absolute;
  top: 0px;
  right: 40px;
  line-height: 76px;
  color: #9c9c9c;
  font-style: normal;
  }
  /* line 250, ../sass/main.scss */
  #main .descript ol li.room {
  line-height: 53px;
  }
  /* line 252, ../sass/main.scss */
  #main .descript ol li.room img {
  width: 23px;
  height: auto;
  left: 3px;
  top: 15px;
  }
  /* line 254, ../sass/main.scss */
  #main .descript ol li.kitchen {
  line-height: 53px;
  }
  /* line 256, ../sass/main.scss */
  #main .descript ol li.kitchen img {
  width: 23px;
  height: auto;
  left: 3px;
  top: 15px;
  }
  /* line 258, ../sass/main.scss */
  #main .descript ol li.kilburn, #main .descript ol li.kilburnPark, #main .descript ol li.maida, #main .descript ol li.south {
  padding: 16px 0px 0px 34px;
  height: 64px;
  }
  /* line 260, ../sass/main.scss */
  #main .descript ol li.kilburn img, #main .descript ol li.kilburnPark img, #main .descript ol li.maida img, #main .descript ol li.south img {
  width: 19px;
  height: auto;
  left: 3px;
  top: 20px;
  }
  /* line 263, ../sass/main.scss */
  #main .descript ol:after {
  clear: both;
  content: "";
  display: table;
  }


texts:
Lately, I've been, I've been losing sleep
Dreaming about the things that we could be
But baby, I've been, I've been praying hard,
Said, no more counting dollars
We'll be counting stars, yeah we'll be counting stars
(One Republic - Counting Stars)

The 2nd Monitor is known to be a quite star-happy chat room, but exactly how many stars is there? And who are the most starred users? I decided to write a script to find out.

I chose to write this in Python because:

I've never used Python before
@200_success used it and it didn't look that hard
I found Beautiful Soup which seemed powerful and easy to use

The script performs a number of HTTP requests to the list of starred messages, keeps track of the numbers in a dict and also saves the pure HTML data to files (to make it easier to perform other calculations on the data in the future, and I had the opportunity to learn file I/O in Python).

To be safe, I included a little delay between some of the requests (Don't want to risk getting blocked by the system)

Unfortunately there's no way to see which user starred the most messages, but we all know who that is anyway...

The code:

from time import sleep
from bs4 import BeautifulSoup
from urllib import request
from collections import OrderedDict
import operator

room = 8595 # The 2nd Monitor (Code Review)
url = 'http://chat.stackexchange.com/rooms/info/{0}/the-2nd-monitor/?tab=stars&page={1}'
pages = 125

def write_files(filename, content):
    with open(filename, 'w', encoding = 'utf-8') as f:
        f.write(content)

def fetch_soup(room, page):
    resource = request.urlopen(url.format(room, page))
    content = resource.read().decode('utf-8')
    mysoup = BeautifulSoup(content)
    return mysoup

allstars = {}
def add_stars(message):
    message_soup = BeautifulSoup(str(message))
    stars = message_soup.select('.times').pop().string
    who = message_soup.select(".username a").pop().string

    # If there is only one star, the `.times` span item does not contain anything
    if stars == None:
        stars = 1

    if who in allstars:
        allstars[who] += int(stars)
    else:
        allstars[who] = int(stars)

for page in range(1, pages):
    print("Fetching page {0}".format(page))
    soup = fetch_soup(room, page)
    all_messages = soup.find_all(attrs={'class': 'monologue'})
    for message in all_messages:
        add_stars(message)
    write_files("{0}-page-{1}".format(room, page), soup.prettify())
    if page % 5 == 0:
        sleep(3)

# Create a sorted list from the dict with items sorted by value (number of stars)
sorted_stars = sorted(allstars.items(), key=lambda x:x[1])

for user in sorted_stars:
    print(user)

The results, you ask? Well, here they are: (Spoiler warning!) (I'm only showing those who have \$> 50\$ stars here, to keep the list shorter)

   ('apieceoffruit', 73)
 ('ChrisW', 85)
 ('Edward', 86)
 ('Yuushi', 93)
 ('Marc-Andre', 98)
 ('nhgrif', 112)
 ('amon', 119)
 ('James Khoury', 126)
 ('Nobody', 148)
 ('Jerry Coffin', 150)
 ('BenVlodgi', 160)
 ('Donald.McLean', 174)
 ('konijn', 184)
 ('200_success', 209)
 ('Vogel612', 220)
 ('kleinfreund', 229)
 ('Corbin', 233)
 ('Morwenn', 253)
 ('skiwi', 407)
 ('lol.upvote', 416)
 ('syb0rg', 475)
 ('Malachi', 534)
 ('retailcoder', 749)
 ("Mat's Mug", 931)
 ('Simon André Forsberg', 1079)
 ('Jamal', 1170)
 ('The Mug with many names', 2096) (Mat's Mug, retailcoder and lol.upvote is the same user)
 ('rolfl', 2115)

It feels strange to do .pop() to fetch data from the select soup, is there another approach available here? However, as this is the first time I'm using Python, any comments are welcome.


texts:
This code works. It is designed to retrieve website data directly, parse it, and open it as normal. I will develop it further later. Right now I want to know if there is any way to improve efficiency, such as not using a file etc. I would also like to know if my code could be made more pythonic (this would include PEP standards), or incidences where concatenation would be acceptable to readability. Here is the code:

import urllib.request
from tkinter import *
import webbrowser
import os

proxy_handler = urllib.request.ProxyHandler(proxies=None)
opener = urllib.request.build_opener(proxy_handler)

def navigate(query):
    response = opener.open(query)
    html = response.read()
    return html

def parse(junk):
    ugly = str(junk)[2:-1]
    lines = ugly.split('\\n')
    return lines

while True:
    url = input("Path: ")
    dump = navigate(url)

    content = parse(dump)
    with open('cache.html', 'w') as f:
        for line in content:
            f.write(line)

    webbrowser.open_new_tab(os.path.dirname(os.path.abspath(__file__))+'/cache.html')


texts:
This is the code I came up with:

void set_bit_at_pos(int* num, int pos, bool val)
{
    if (val) {
        int mask = 1 << pos;
        *num |= mask;
    }
    else {
        int mask = ~(1 << pos);
        *num &= mask;
    }
}

I'm new to bitwise operations, so this approach may not be the best. Nevertheless any suggestions are appreciated.

For the following main:

int main()
{
    int num = 5;
    cout << num << endl;
    set_bit_at_pos(&num, 1, true);
    cout << num << endl;
}

(I know about using namespace std;)

This is the output:

5
7


texts:
I have created an SslStream Abstract Class for my Client and i want you to review and enhance it for me if needed

SecureStream.cs

using System;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Program.Connections.Packets;
using Program.Core.Misc;

namespace Program.Connections.Network
{
    public abstract class SecureStream
    {
        private static readonly byte[] Buffer = new byte[0x1f80];
        private const string IpAddress = "192.168.1.65";
        private readonly int _port;
        private readonly Socket _socket;
        private SslStream _sslStream;

        public abstract void Receive(byte[] buffer);
        public abstract void Error(Exception e);

        protected SecureStream(int port)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
            _port = port;
        }

        public void Connect()
        {
            _socket.BeginConnect(new IPEndPoint(IPAddress.Parse(IpAddress), _port), Authenticate, null);
        }

        private async void Authenticate(IAsyncResult ar)
        {
            try
            {
                var onCertificateValidationCallBack =
                    new RemoteCertificateValidationCallback(
                        OnCertificateValidation);
                _sslStream = new SslStream(new NetworkStream(_socket, true), false, onCertificateValidationCallBack);

                await _sslStream.AuthenticateAsClientAsync(IpAddress);
                if (!_sslStream.IsAuthenticated) throw new Exception("not^authenticated");

                do
                {
                    var size = await _sslStream.ReadAsync(Buffer, 0, Buffer.Length);
                    if (size == 0) throw new Exception("invalid^size");
                    var buffer = new byte[size];
                    Native.MemoryCopy(Buffer, buffer, (uint)buffer.Length);
                    Receive(buffer);
                    Array.Clear(Buffer, 0, Buffer.Length);

                } while (_sslStream.CanRead);
            }
            catch (Exception e)
            {
                Error(e);
            }
        }

        internal async Task Send(PacketWriter writer)
        {
            var buffer = writer.GetWorkspace();
            await _sslStream.WriteAsync(buffer, 0, buffer.Length);
        }

        private static bool OnCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
        {
            return true;
        }
    }
}

CoreServer.cs

using System;
using System.Windows.Forms;

namespace Program.Connections.Network
{
    public sealed class CoreServer : SecureStream
    {
        public CoreServer(int p) : base(p) { }

        public override void Receive(byte[] buffer)
        {
            //TODO: Handle The Buffer
        }

        public override void Error(Exception e)
        {
            //TODO: Add Error Writer.
            MessageBox.Show(
                string.Format("Disconnected from the server."),
                string.Format("Connection Error"), MessageBoxButtons.OK,
                MessageBoxIcon.Error);
            Environment.Exit(1);
        }
    }
}

And i Simply Execute it using

var coreServer = new CoreServer(/*port*/);
coreServer.Connect();


texts:
The given code reverses an array of input characters.

The additional while loop in reverse() function is unnecessary I guess.
Any other method or way to remove it?

I would prefer to keep reverse() as void.

#include <stdio.h>

#define MAXLEN 65535 /* maximum length of input line */

void reverse(char s[], int l);

/* reverses given input line */

void main()
{
    int i, c;
    char line[MAXLEN];

    i = 0;

    while(i < MAXLEN-1 && (c = getchar()) != EOF && c != '\n')  /* input characters in array */
    {
        line[i] = c;
        ++i;
    }

    reverse(line, i);
    printf("%s", line);
}

void reverse(char s[], int l)
{
    char rev[MAXLEN];
    int i, len;

    i = 0;
    len = l;    /* duplicate length of initial array */

    if(s[l] == '\0')
    {
        --l;
    }

    while(i < len)
    {
        rev[i] = s[l];  /* reversing */
        ++i;
        --l;
    }

    i = 0;

    while (i < len) /* what i think is unnecessary */
    {
        s[i] = rev[i];  /* storing back to initial array */
        ++i;
    }
}


texts:
This is my first SFML game. There are 2 players: the red circle and the yellow circle. The red circle is controlled by Up,down,left and right keys, the yellow one is controlled by WASD keys. The players are supposed to keep on trying to get behind each other in order to move them and get them inside the black circle, the player who gets in the circle first loses.

#include <iostream>
#include <SFML/Graphics.hpp>

bool intersects(const sf::CircleShape& c1, const sf::CircleShape& c2){
    sf::FloatRect circ1 = c1.getGlobalBounds();
    sf::FloatRect circ2 = c2.getGlobalBounds();

    return circ1.intersects(circ2);
}

int main(){

    sf::VideoMode videomode(400, 400);
    sf::RenderWindow window(videomode, "GAME");
    sf::CircleShape circle;
    circle.setFillColor(sf::Color::Red);
    circle.setPosition(100, 100);
    circle.setRadius(20);
    sf::CircleShape circle2;
    circle2.setFillColor(sf::Color::Yellow);
    circle2.setPosition(200, 200);
    circle2.setRadius(20);
    sf::CircleShape circle3;
    circle3.setFillColor(sf::Color::Black);
    circle3.setPosition(300, 300);
    circle3.setRadius(50);

    while (window.isOpen()&&(!intersects(circle,circle3))&&(!intersects(circle2,circle3))){
        window.clear(sf::Color::Blue);
        window.draw(circle);
        window.draw(circle2);
        window.draw(circle3);

        window.display();

        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Up)){
            circle.move(0, -0.5);

        }

        else if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Down)){
            circle.move(0, 0.5);

        }

        else if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Right)){
            circle.move(0.5, 0);

        }

        else if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Left)){
            circle.move(-0.5, 0);

        }

        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)){
            circle2.move(0, -0.5);

        }

        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)){
            circle2.move(0, 0.5);

        }

        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)){
            circle2.move(0.5, 0);

        }

        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
            circle2.move(-0.5, 0);

        }

        if (intersects(circle, circle2)){
            circle2.move(0.5, 0);
        }
        if (intersects(circle2, circle)){
            circle.move(0.5, 0);

        }
        if (intersects(circle, circle3)){

            std::cout << "Red loses";
        }
        if (intersects(circle2, circle3)){

            std::cout << "Yellow loses";
        }
    }
}


texts: Clean and tidy Python code for dictionary look up and API interactions

texts:
I am new to programming and entirely self-taught. Below is a program I wrote to retrieve text content via an API and scan the text for important words. If the word is found URI is returned. The API returns data in JSON. The important words and URIs are linked via a dictionary. It works. I'm at a point in my programming education where I need to start focusing on writing clean code. I have a book about it, but there's something about peer review that is so much more helpful. Here is the code with commenting.
Any ideas on how I can make this cleaner?

#!/usr/bin/env python
# coding: utf-8
from __future__ import division
import urllib, json

#bio_dict is the dictionary used to assign DBpedia URIs. When a specific key is
#found in the text, the value URI is returned. Any dictionary can be used here.

bio_dict = eval(open('biodict.txt').read())

in_file_name = "text_object_id1.txt"
in_file = open(in_file_name, 'r')
out_file_name = "all_uri.txt"
out_file = open(out_file_name, 'w')

#At this point, you have imported all the modules you need, read the dictionary
#you will use to the assign the URIs and opened all the files you will be using. The
#InFile should be a list of DataObject IDs. The OutFile will hold your results.

def data_object_url(line):
    return 'http://eol.org/api/data_objects/1.0/' + line.strip() + '.json'

#data_object_url is a function that will create the URL needed to query the API
#for each data object ID in the list

for line in in_file:
    results = urllib.urlopen(data_object_url(line)).read()
    print line
    print len(results)
    data = json.loads(results)
    descriptions = data ['dataObjects'][0]['description'].lower()
    for k, v in bio_dict.iteritems():
        if k in descriptions:
            out_file.write(','.join([line.strip(),k,v + '\n']))
in_file.close()
out_file.close()

#This code goes over each line in the in_file (a list of text object IDs), retrieves
#them from the API in json format, pulls out the description text and then iterates over
#each key in the dictionary. If the key is found the value is returned and the system
#moves on to the next key. If the key is not found, the system returns nothing and moves
#on to the next key. Line 34 controls the format of the output. Lines 28 and 29 serve to
#show progress as the program runs.


texts:
Disclaimer: not a Pythonista, first actual Python programme written right here.

I'm reading a DHT11 sensor from GPIO pin 4 on my Raspberry Pi (thanks Thomas Ward for sending the RPi to me), and I want to log it to a file which will later be parsed into a web-page.

So I wrote the following Python script which is called by a Cron job every minute, and it reads the sensor 5 times then logs the average, min and max to a file for humidity and temperature.

Without further ado, here's my crap:

#!/usr/bin/python

import sys
import Adafruit_DHT
import time

def getLine(array):
    return str(sum(array) / float(len(array))) + "," + str(min(array)) + "," + str(max(array))

sensor = Adafruit_DHT.DHT11
gpio = 4

h = []
t = []

count = 5
date = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

for num in range(count):
    th, tt = Adafruit_DHT.read_retry(sensor, gpio)
    h.append(th)
    t.append(tt)

with open("MainLog.txt", "a") as file:
    file.write(date + ": ")
    # Write Humidity data
    file.write(getLine(h))
    file.write(" | ")
    file.write(getLine(t))
    # Write line break
    file.write("\n")

I have no idea how "good" or "bad" it is, if it were C# I would know but it's not. All suggestions welcome.

When I get my new hardware (looks like two-three days from now) I'm going to be adding a BMP180 sensor (barometric pressure/altitude).

The Adafruit_DHT library is on GitHub: https://github.com/adafruit/Adafruit_Python_DHT

I'm going to be replacing this with a DHT22, but that's one LoC change:

sensor = Adafruit_DHT.DHT11

To:

sensor = Adafruit_DHT.DHT22


texts:
CGbR project

I am currently working on a project that generates code from classes. The idea is to achieve maximum performance by replacing reflection use cases with fast, generated code.

Current results look good, but I want to take this chance to find room for further improvement.

Class under test:

[DataContract]
public partial class Partial
{
    [DataMember]
    public float Price { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public List<double> DecimalNumbers { get; set; }
}

Generated JSON

One of the generator creates methods to read and write JSON. Code is available in full at the benchmark project.

To JSON:

writer.Write(",\"Price\":");
writer.Write(Price.ToString(CultureInfo.InvariantCulture));

writer.Write(",\"Name\":");
writer.Write(string.Format("\"{0}\"", Name));

writer.Write(",\"DecimalNumbers\":");
if (DecimalNumbers == null)
    writer.Write("null");
else
{
    writer.Write('[');
    foreach (var value in DecimalNumbers)
    {
        writer.Write(value.ToString(CultureInfo.InvariantCulture));
        writer.Write(',');
    }
    writer.Write(']');
}

From JSON:

while (reader.Read())
{
    // Break on EndObject
    if (reader.TokenType == JsonToken.EndObject)
        break;

    // Only look for properties
    if (reader.TokenType != JsonToken.PropertyName)
        continue;

    switch ((string) reader.Value)
    {
        case "Price":
            reader.Read();
            Price = Convert.ToSingle(reader.Value);
            break;

        case "Name":
            reader.Read();
            Name = Convert.ToString(reader.Value);
            break;

        case "DecimalNumbers":
            reader.Read(); // Read token where array should begin
            if (reader.TokenType == JsonToken.Null)
                break;
            var decimalnumbers = new List<double>();
            while (reader.Read() && reader.TokenType != JsonToken.EndArray)
                decimalnumbers.Add(Convert.ToDouble(reader.Value));
            DecimalNumbers = decimalnumbers;
            break;

Generated binary conversion

Another generator maps the class directly onto a byte[].

Converter methods:

public static unsafe void Include(ushort value, byte[] bytes, int index)
{
    fixed (byte* b = bytes)
        *((ushort*)(b + index)) = value;
}

To binary:

// Convert Price
GeneratorByteConverter.Include(Price, bytes, index);;
index += 4;
// Convert Name
// Two bytes length information for each dimension
GeneratorByteConverter.Include((ushort)(Name == null ? 0 : Name.Length), bytes, index);
index += 2;
if (Name != null) Buffer.BlockCopy(_encoder.GetBytes(Name), 0, bytes, index, Name.Length);
index += Name == null ? 0 : Name.Length;
// Convert DecimalNumbers
// Two bytes length information for each dimension
GeneratorByteConverter.Include((ushort)(DecimalNumbers == null ? 0 : DecimalNumbers.Count), bytes, index);
index += 2;
if (DecimalNumbers != null)
for(var i = 0; i < DecimalNumbers.Count; i++)
{
    var value = DecimalNumbers[i];
    GeneratorByteConverter.Include(value, bytes, index);;
    index += 8;
}

From binary:

// Read Price
Price = BitConverter.ToSingle(bytes, index);
index += 4;
// Read Name
var nameLength = BitConverter.ToUInt16(bytes, index);
index += 2;
Name = _encoder.GetString(bytes, index, nameLength);
index += nameLength;
// Read DecimalNumbers
var decimalnumbersLength = BitConverter.ToUInt16(bytes, index);
index += 2;
var tempDecimalNumbers = new List<double>(decimalnumbersLength);
for (var i = 0; i < decimalnumbersLength; i++)
{
    var value = BitConverter.ToDouble(bytes, index);
    index += 8;
    tempDecimalNumbers.Add(value);
}
DecimalNumbers = tempDecimalNumbers;

I couldn't post all the code here, but maybe one of you already sees something I am missing.


texts: Switch MongoDB databases dynamically per user

texts:
I'm doing a POS (point of sale) as Saas with React in the frontend, NodeJs in backend (API Rest) and MongoDB as the database.

I've finished a basic program and now I want any registered user to have his own database.

After read some articles and question on the internet my conclusion was to switch between databases each time the frontend consume the backend (API).

General Logic:

User Log in
In the backend, I use a general database to check user credentials and also I acquire the name of the database of this user.
Each time the frontend consumes the API the next codes are executed in a middleware to know what database should use the API:

var dbUser = db.useDb('nameDataBaseUser');
var Product = dbUser.model('Product', ProductSquema);

I have the schemas and the variable db defined fixed in the code:

var db = mongoose.createConnection('mongodb://localhost');

Problem:

I don't know if is the correct solution about what I am trying to make, but it seems me inefficient that the model is generated constantly each time the API is called, because in some API (i.e in some middlewares I have until 4 different models)

Question:

This is the best way? or any suggestion to face this problem?


texts: Efficient numpy array manipulation to convert an identity matrix to a permutation matrix

texts:
Task

I want to be able to generate the permutation matrix that splits a 1D array of consecutive numbers (i.e. even, odd, even, odd, even, odd, ...) into a 1D array where the first half are the evens, and the second half are the odds. So (even1, odd1, even2, odd2, even3, odd3) goes to (even1, even2, even3, odd1, odd2, odd3).

For example, with N=6, the permutation matrix would be:

M = array([1, 0, 0, 0, 0, 0],
          [0, 0, 1, 0, 0, 0],
          [0, 0, 0, 0, 1, 0],
          [0, 1, 0, 0, 0, 0],
          [0, 0, 0, 1, 0, 0],
          [0, 0, 0, 0, 0, 1])

You can check that multiplying this with M * array([0, 1, 2, 3, 4, 5]) = array([0, 2, 4, 1, 3, 5]).

My approach in pseudocode

(Full code below.) This is the mathematically correct way to generate this:

I = NxN identity matrix
for i in [0:N-1]:
    if i < N/2:
        shift the 1 in row i by 2*i to the right
    if i >= N/2:
        shift the 1 in row i by 2*(i - N/2)+1 to the right

You can see how that works to generate M above.

Code (Python)

I implement the above pseudocode by using numpy array manipulation (this code is copy-and-pasteable):

import numpy as np

def permutation_matrix(N):
    N_half = int(N/2) #This is done in order to not repeatedly do int(N/2) on each array slice
    I = np.identity(N)
    I_even, I_odd = I[:N_half], I[N_half:] #Split the identity matrix into the top and bottom half, since they have different shifting formulas

    #Loop through the row indices
    for i in range(N_half):
        # Apply method to the first half
        i_even = 2 * i #Set up the new (shifted) index for the 1 in the row
        zeros_even = np.zeros(N) #Create a zeros array (will become the new row)
        zeros_even[i_even] = 1. #Put the 1 in the new location
        I_even[i] = zeros_even #Replace the row in the array with our new, shifted, row

        # Apply method to the second half
        i_odd = (2 * (i - N_half)) + 1
        zeros_odd = np.zeros(N)
        zeros_odd[i_odd] = 1.
        I_odd[i] = zeros_odd

    M = np.concatenate((I_even, I_odd), axis=0)

    return M

N = 8
M = permutation_matrix(N)
print(M)

Output:
array([[1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 1., 0.],
       [0., 1., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 1.]])

My issues

I have a feeling that there are more efficient ways to do this. To summarise what I am doing to each matrix:

Looping through the rows
At each row, identify where the 1 needs to be moved to, call it idx
Create a separate zeros array, and insert a 1 into index idx
Replace the row we are evaluating with our modified zeros array

Is it necessary to split the array in two?

Is there an Pythonic way to implement two different functions on two halves of the same array without splitting them up?

Is there an approach where I can shift the 1s without needing to create a separate zeros array in memory?

Do I even need to loop through the rows?

Are there more efficient libraries than numpy for this?


texts:
I have the following code that converts a string that looks like:

  aaa-bbb|ccc-ddd|eee-fff

to two strings that look like:

  aaa|ccc|eeeandbbb|ddd|fff

The code works fine, but I am wondering if I probably missed some string/array functions that can makes the job in fewer operations / or with faster runtime.

var id = "HEL-CAS|MAD-STO|XXX-YYY"
var splittedId = id.split('|');
var from = "",
  to = "";
$(splittedId).each(function(a, b) {
  from = from + b.split("-")[0] + "|";
  to = to + b.split("-")[1] + "|";
});
from = from.substring(0, from.length - 1);
to = to.substring(0, to.length - 1);


texts:
This is an implementation of the minion game, which takes in string input and declares a winner between two pre-determined players.

The logic is player 1 gets all sequenced words not starting with a vowel and player 2 gets all sequenced words starting with vowel in the input string.

Objective: performance optimisation. The code passed all the test cases, but I am very unsure where to tune the performance.

For a 1000 letter word, here are the time stats:

real 0m10.142s
user 0m6.386s
sys 0m0.743s

import string
import sys
import itertools

def minion(str):
    person_a_name = 'Stuart'
    person_b_name = 'Kevin'
    letter_list = [a for a in str]
    l = len(letter_list)
    vowel = ['A','E','I','O','U']
    consonants = ['Q','W','R','T','Y','P','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M']
    all_word = []
    person_a_words = []
    person_b_words = []
    all_word = [letter_list[start:end+1] for start in xrange(l) for end in xrange(start, l)]
    for array in all_word:
        if array[0] in vowel:
            person_b_words.append(array)
    for array in all_word:
        if array[0] in consonants:
            person_a_words.append(array)
    if len(person_a_words) == len(person_b_words):
        print 'Draw'
    if len(person_a_words) > len(person_b_words):
        print person_a_name, len(person_a_words)
    if len(person_b_words) > len(person_a_words):
        print person_b_name, len(person_b_words)

def main():
    str = raw_input()
    minion(str.upper())

if __name__ == '__main__':
    main()

Sample input / output:

banana
Stuart 12

guavaisanotherfruit
Kevin 98


texts:
How can I improve this component with using event delegation rather than doing a lookup using parentNode so that I can change the markup around without having to update the JavaScript?

HTML

          Lorem ipsum dolor sit amet, consectetuer adipiscing elit

JavaScript

(function(){

      var dropDownClosed = 'js-drop-down',
          dropDownButtonList = document.querySelectorAll('.drop-down-btn-wrapper');

      function init() {
        for(var i=0; i<dropDownButtonList.length; i++) {
          dropDownButtonList[i].addEventListener('click', initDropdown, false);
        }
      }

      function initDropdown(e) {

        var event          = e.target;
        var contentWrapper = event.parentNode.parentNode.parentNode.childNodes[3];
        var content        = event.parentNode.parentNode.parentNode.childNodes[3].childNodes[1];
        var closedButton   = event.parentNode.parentNode.parentNode.childNodes[1].childNodes[3];
        var contentHeight  = content.offsetHeight;

        if(hasClass(contentWrapper, dropDownClosed)) {
          removeClass(contentWrapper, dropDownClosed);
          contentWrapper.style.height = contentHeight+'px';
          closedButton.style.opacity = '0.0';
        } else {
          addClass(contentWrapper, dropDownClosed);
          contentWrapper.style.height = 0+'px';
          closedButton.style.opacity = '1.0';
        }
      }

      function hasClass(ele, cls) {
          return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
      }
      function addClass(ele, cls) {
          if (!hasClass(ele, cls)) ele.className += " " + cls;
      }
      function removeClass(ele, cls) {
          if (hasClass(ele, cls)) {
              var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
              ele.className = ele.className.replace(reg, '');
          }
      }

      init();

    }());

CSS

.drop-down-wrapper {
  position:relative;
  border: 2px black solid;
  margin-bottom:20px;
  padding:20px 0;
}

.content-wrapper {
  padding:15px;
  margin:30px 0;
}

.drop-down-open {
  position:absolute;
  top:0;
  border: thin red solid;
}

.drop-down-closed {
  position:absolute;
  top:0;
  border: 2px solid green;
}

.drop-down-content {
  background-color:#fff;
  overflow:hidden;
  height:0;
}

DEMO


texts: React modal visibility and content toggling based on action clicked

texts:
Learning React, I have created a basic App Component and Modal Component, the App Component renders 2 actions - hold and cancel, and a Modal based on the state modalVisible. I've kept the Modal Component light opting to pass the events back to the App Component (not sure if this is recommended), my reasoning is that this component could then be used by multiple actions. Would be great to get your thoughts in order to learn and improve!

/**
 * App Component
 * Holds actions, controls modal display using the state modalVisible.
 */
var AppComponent = React.createClass({
    getInitialState() {
        return {
            modalVisible: false
        }
    },

    _onModalYesClicked() {
        console.log('onYesClicked::contact the server');

        this.toggleModal();
    },

    _onModalNoClicked() {
        console.log('onNoClicked:contact the server');

        this.toggleModal();
    },

    toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'} = {}) {
        this.setState({
            modalVisible: !this.state.modalVisible,
            title: title,
            description: description,
            cancelLabel: cancelLabel,
            submitLabel: submitLabel
        });
    },

    onCancelClicked() {
        console.log('onCancelClicked');

        this.toggleModal({
            title: 'Cancel',
            description: 'Would you like to commit to cancelling?'
        });
    },

    onHoldClicked() {
        console.log('onHoldClicked');

        this.toggleModal({
            title: 'Hold',
            description: 'Are you sure you would like to hold the order?'
        });
    },

    render() {
        var modal = undefined;

        if(this.state.modalVisible) {
            modal = <ModalComponent
                title={this.state.title}
                description={this.state.description}
                onModalYesClicked={this._onModalYesClicked}
                onModalNoClicked={this._onModalNoClicked}  />
        }

        return (

                <button className="btn btn--negative" onClick={this.onCancelClicked}>Cancel</button>
                <button className="btn" onClick={this.onHoldClicked}>Hold</button>

                {modal}

        )
    }
});

/**
 * Modal Component
 * Uses props to tell parent component the action to take on action click.
 */
var ModalComponent = React.createClass({
    render() {
        return (

                  <button className="modal__close" aria-label="close" onClick={this.props.onModalNoClicked}></button>

{this.props.title}

{this.props.description}

                  <button type="button" className="btn" onClick={this.props.onModalYesClicked}>{this.props.submitLabel ? this.props.submitLabel : 'Yes'}</button>&nbsp;
                  <button type="button" className="btn btn--secondary" onClick={this.props.onModalNoClicked}>{this.props.cancelLabel ? this.props.cancelLabel : 'No'}</button>

        )
    }
});

/**
 *  Kicks the application off.
 */
ReactDOM.render(<AppComponent />, document.body.querySelector('.js-app'));

JSFiddle: http://jsfiddle.net/kyllle/xsrge3px/


texts: Sorting BIGINT column with ascending positive values followed by descending nonpositive values

texts:
I have a column flowing in with the full range of integers. Whilst generating keys on the INT column, I need to push the 0's and negatives down (ordered DESC) and the positive keys to stay at the top (ordered ASC/DESC). I came up with two approaches but I am not sure which is better.

Approach 1: Tidier but unsure about scalability

WITH t1(c1) AS
(
SELECT 11 UNION ALL
SELECT 2 UNION ALL
SELECT 0 UNION ALL
SELECT -1 UNION ALL
SELECT -11
)
SELECT c1, ROW_NUMBER() OVER (ORDER BY
                             CASE WHEN c1 <=0 THEN c1 END DESC ,
                             CASE WHEN c1 >0 THEN c1 END ASC) keys
FROM t1 ;

Approach 2: Scalable

WITH t1(c1) AS
(
SELECT 11 UNION ALL
SELECT 2 UNION ALL
SELECT 0 UNION ALL
SELECT -1 UNION ALL
SELECT -11
)
SELECT c1, ROW_NUMBER() OVER (ORDER BY c1 ASC) keys
FROM t1
WHERE c1 >0
UNION ALL
-- Need to include Max keys from previous step in actual implementation
SELECT c1,
       maxkeys + ROW_NUMBER() OVER (ORDER BY c1 DESC) keys
FROM t1
WHERE c1 <= 0 ;

Please suggest any other better alternatives for scalability (BIGINT range).


texts: Searching local drive for multiple files

texts:
Well, I'm writing a piece of code that will take a list of file names and should search a local drive for each file, determine if it's there or not, and return an array of all the paths found.

Right now I'm using a function that searches for one file and I call this function for each file in the list:

Public Function DriveSearch(ByVal sDir As String, sFile As String) As String()
    Dim filesFound As New List(Of String)
    Try
        For Each dir As String In Directory.GetDirectories(sDir)
            For Each file In Directory.GetFiles(dir, sFile)
                filesFound.Add(file)
            Next
            filesFound.AddRange(DriveSearch(dir, sFile))
        Next
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
    Return filesFound.ToArray
End Function

But I'm wondering if there's a faster way to achieve this. Maybe I should index all the files in the drive first before searching? (I'm not sure how to do this yet).

The number of files in the list is around 100 (for now) but it's likely to increase to couple thousands.

Edit:

I decided that I won't need the duplicates, so here's my current function:

Public Function DriveSearch(ByVal sDir As String, sFile As String) As String
    Dim filePath As String = String.Empty
    Try
        Dim arrFiles As String() = Directory.GetFiles(sDir, sFile)
        If arrFiles.Length > 0 Then
            filePath = arrFiles(0)
        Else
            For Each dir As String In Directory.GetDirectories(sDir)
                filePath = DriveSearch(dir, sFile)
                If filePath.Length > 0 Then Exit For
            Next
        End If
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
    Return filePath
End Function

Still not sure if this is the fastest way to search for 100+ files.


texts: How to refactor this function to solve cyclomatic issue?

texts:
I'm trying to fix this error on codeclimate

  Cyclomatic complexity for resource_icon is too high. [7/6]

What is the best way to refactor this function?

def resource_icon(resource)
    case resource.to_sym
    when :locations
      'fa-building'
    when :monitored_places
      'fa-globe'
    when :attendances
      'fa fa-bicycle'
    when :gym_distribuitions
      'fa fa-users'
    when :ranking_activities
      'fa fa-list-ol'
    when :attendance_by_group_class_trainers
      'fa fa-graduation-cap'
    else
      'fa-diamond'
    end
  end


texts: How do you "sordid sort" alphanumeric strings?

texts:
The question is about sorting alphanumeric string in a "more natural" order. Source: Marc LeBrun's "Sordid Sort" Computist Quiz

  Often a system string comparison sorts alphanumeric data “unnaturally”, as with these filenames:

File1
File10 ← ?
File11 ← ?
File12 ← ?
File2
File3
File3X
File4
File5
File6
File7
File8
File999

  Describe an algorithm that will sort alphanumeric strings in a “more natural” order:

File1
File2
File3
File3X
File4
File5
File6
File7
File8
File10
File11
File12
File999

  The algorithm may only rely on comparing characters; to avoid overflow problems with very long numbers it must not convert substrings of digits into their numerical values.

Spoiler alert: If you would like to independently solve the above, please do so now before you let the below spoil it for you.

This implementation has its inspiration from Computist Quiz Answer Guide. Misunderstandings would be mine.

From the Answer Guide: Extra credit: discuss the behavior with respect to leading zeros, as in “007”.

#!/usr/bin/perl -w

# Sordid Sort: http://fxpt.com/wp-content/uploads/2012/01/quiz.pdf
# Solution based on http://fxpt.com/wp-content/uploads/2012/01/QuizAnswers.pdf

use strict;

my $verbose = 0;    # set it to non-zero to get regex matches printed to STDERR
my $ALNUM = qr/(\D*)(\d*)/; # match a pair of alphas-optional and/or num-optional
my @in = ();

while (<>) {
    chomp;
    push @in, $_;
}

sub sordidcmp {
    my @a = $a =~ m/$ALNUM/g;   # always even number of elements since $ALNUM matches in pairs; and always has a sentinel pair
    my @b = $b =~ m/$ALNUM/g;
    my $cmp = 0;
    my $min_ab = (@a < @b) ? @a : @b;
    my $i;
    print STDERR "comparing (<".join("> <", @a).">) with (<".join("> <", @b).">)" if $verbose;
    for ($i = 0; $i < $min_ab; ++$i) {  # advance by 2; once here
        $cmp = $a[$i] cmp $b[$i];   # compare alphas
        last if $cmp;    # end if we found unequals

        ++$i;       # advance once more here
        # compare nums
        my $lenai = length($a[$i]);
        my $lenbi = length($b[$i]);

        # deal with Extra credit: prefix "0" to the shorter num
        if ($lenai < $lenbi) {
            $a[$i] = ("0" x ($lenbi-$lenai)).$a[$i];
        } elsif ($lenbi < $lenai) {
            $b[$i] = ("0" x ($lenai-$lenbi)).$b[$i];
        }

        $cmp = $a[$i] cmp $b[$i]; # note: stringwise compare of nums
        last if $cmp;    # end if we found unequals
    }
    print STDERR " = $cmp\n" if $verbose;
    return $cmp;
}

print join "\n", sort sordidcmp @in;
print "\n" if @in;  # guard against empty input

My questions are:

I observed that the match @a = $a =~ m/$ALNUM/g always produces a sentinel pair of ("", ""). Is the above code relying on undocumented behaviour? I could not find (read: understand) this from the perlop, perlretut, and perlre perldocs.
Can you help simplify the sordidcmp subroutine? Perl golf would be nice, but a more maintainable version is what I would be interested in. Of course, links to other solutions/implementations are welcome.


texts: How to make my code shorter. This Code formats Credit card number. Vanilla JS

texts:
How to make my script shorter and better? This code allows only digits, auto-format card number like this XXXX XXXX XXXX XXXX. if user hits delete or backspace to delete space in between digits, nothing happens caret just moves 1 space forward or backward, it depends on which key user pressed (delete or backspace). If user hits backspace after digit and the previous second symbol is space then backspace deletes the digit and moves 2 spaces back like this (XXXX X|XXX XXXX XXXX -> XXXX| XXXX XXXX XXX ). Delete key dose the same but vice versa like this (XXX|X XXXX XXXX XXXX -> XXXX |XXXX XXXX XXX ). It also allows ctrl+c,ctrl+v,ctrl+a,ctrl+x.

let input = document.querySelector('input');

input.addEventListener('keyup', function (e) {
    let cursor = input.selectionStart;
    let inpVal = input.value;
    let cardCode = inpVal.replace(/\s/g, '').substring(0, 16);
    cardCode = cardCode != '' ? cardCode.match(/.{1,4}/g).join(' ') : '';
    input.value = cardCode;
    let key = e.keyCode || e.which;
    // let ctrl = e.ctrlKey || key === 17 || e.metaKey;
    if ((key >= 48 && key <= 57) || (key >= 96 && key <= 105)) {
        if (cursor < parseInt(inpVal.length)) {
            input.selectionEnd = cursor;
        }
    } else if (key == 8) {
        if (input.value[cursor - 1] == ' ') {
            input.selectionEnd = cursor - 1;
        } else {
            input.selectionEnd = cursor;
        }
    } else if (key == 46) {
        if (input.value[cursor + 1] == ' ') {
            input.selectionEnd = cursor + 2;
        } else {
            input.selectionEnd = cursor;
        }
    }
});
input.addEventListener('keydown', function (e) {
    let inpVal = input.value;
    let cursor = input.selectionStart;
    let key = e.keyCode || e.which;
    let ctrl = e.ctrlKey || key === 17 || e.metaKey;
    if (
        key == 9 ||
        // Ctrl+A
        (key == 65 && ctrl === true) ||
        // Ctrl+C
        (key == 67 && ctrl === true) ||
        // Ctrl+X
        (key == 88 && ctrl === true) ||
        // Ctrl+V
        (key == 86 && ctrl === true) ||
        // home, end, влево, вправо
        (key >= 35 && key <= 40) ||
        (key >= 48 && key <= 57) ||
        (key >= 96 && key <= 105)
    ) {
        return;
    } else if (key == 8) {
        if (input.value[cursor - 1] == ' ' && cursor < parseInt(inpVal.length)) {
            e.preventDefault();
            input.selectionEnd = cursor - 1;
        }
    } else if (key == 46) {
        if (input.value[cursor] == ' ' && cursor < parseInt(inpVal.length)) {
            e.preventDefault();
            input.selectionStart = cursor + 1;
        }
    } else {
        e.preventDefault();
    }
});
<form method="GET" action="#" class="card">
                <label style="font-size: 20px; display: block; padding: 10px" for="cardnum">Credit Card number</label>
                <input style="font-size: 20px; padding: 10px" autocomplete="off" id="cardnum" name="cardnum" type="text" maxlength="19" title="Please enter a card number in XXXX XXXX XXXX XXXX format" pattern="^\d{4}\s\d{4}\s\d{4}\s\d{4}$" inputmode="numeric" required />
            </form>


texts: Read a text file and print pre-defined html when specific keywords are found

texts:
How can I code this in a better way, in one file? Output must be more than one (if there is more that one status_update with the given word "online or performancedegradation"), like:

#online
System is operating at peak performance.

#directonly
Traffic is bypassing Smart CDN system, and going directly to websites.

<?php
$filename = "export_file_system_status_output";
$status_update = "online";
$handle = fopen($filename, "r");
$file = fread($handle,filesize($filename));
if (preg_match('#' . $status_update . '#', $file, $match)) {
echo "

#online

System is operating at peak performance.

";
}
?>

<?php
$filename = "export_file_system_status_output";
$status_update = "performancedegradation";
$handle = fopen($filename, "r");
$file = fread($handle,filesize($filename));
if (preg_match('#' . $status_update . '#', $file, $match)) {
echo "

#performancedegradation

Performance is slower than normal.

";
}
?>

<?php
$filename = "export_file_system_status_output";
$status_update = "directonly";
$handle = fopen($filename, "r");
$file = fread($handle,filesize($filename));
if (preg_match('#' . $status_update . '#', $file, $match)) {
echo "

#directonly

Traffic is bypassing Smart CDN system, and going directly to websites.

";
}
?>

It must sort by first status_update found:

online
#online

System is operating at peak performance.

then performancedegradation
#directonly

Traffic is bypassing Smart CDN system, and going directly to websites.


texts: Using an object to contain references to almost all places? "Crossroad object"

texts:
I have an object ApplicationContext which is basically my "Cross-road" object that contains all references, to the model, to configuration, and basically everything.

That object will be sent to everything that will need to use any of the references that the object contains.

/**
 * The main application context
 */
public class ApplicationContext {

    /**
     * The main configuration of the application
     */
    private ApplicationConfig config;

    /**
     * The map manipulator
     */
    private MapManipulator mapManipulator;

    public ApplicationContext(ApplicationConfig cfg) {
        this.config = cfg;
        this.initializeModel();
    }

    /**
     * @return The configuration
     */
    public ApplicationConfig getConfig() {
        return this.config;
    }

    /**
     * @return The map manipulator
     */
    public MapManipulator getMapManipulator() {
        return this.mapManipulator;
    }

    /**
     * Initializes services
     */
    private void initializeModel() {
        this.mapManipulator = new MapManipulator(this);
        // TODO add more handlers
    }
}

The MapManipulator is a class that it's job is to do some actions that the MapController asks it to do, so the controller can update the MapDisplay view.

And an example on how the controller speaks to the manipulator using the ApplicationContext:

public MapController(ApplicationContext ctx, MapDisplay map) {
    super(ctx, map);
    // Set connection to the map manipulator
    ctx.getMapManipulator().setMapController(this);
}

Where MapDisplay is the view

/**
 * Gets the map manipulator
 * @return  The map manipulator
 */
public MapManipulator getManipulator() {
    return getContext().getMapManipulator();
}

The getContext() method is a parent method in AbstractController<T extends JComponent & ApplicationView> and is set on construct as dependency.

I know this way has flaws because I don't always need to use everything that the context contains and only send specific references, but it's very hard for me to control all the references that some places need, for example if tomorrow I need to access a new place that is also handled by another controller, or multiple places, it's just hard to explain but it confuses me.

I would like to see reviewws and ideas.
Thanks


texts: Class representing both cartesian and spherical coordinates

texts:
I have had little experience with OO programming, being a typical engineer I tend to hack together functional code. However, I'm trying to change that and I see value in implementing OO when modelling the physical world. I've written my first ever class for a position vector. I want an instance of the class to be able to store both the cartesian [x, y, z] and polar [z, theta, phi] coordinates of a position. Updating one attribute automatically updates the others. This class will be later be reused in other classes via composition.

I want an instance of my class to do the following:

>> p = PositionVector([15,5,5])
>> p.cartesian
[15,5,5]
>> p.polar
[16.583123951777, 0.0, 1.2645189576252271]
>> p.x = 3
>> p.cartesian
[3,5,5]
>> p.polar
[7.681145747868608, 0.7853981633974483, 0.8619682853367363]
>> p.theta = 0.5
>> p.cartesian
[5.117141702137862, 2.7955072527614058, 5.0]
>> p.polar
[7.681145747868608, 0.5, 0.8619682853367363]

The class I've written so far is below and while it works as expected, my limited understanding of Python classes and the property function tells me there's a better way to do this. I don't know if the methods for x y z r theta and phi need to be fully written since they are simply elements within each list/array but can't figure out how to get around this. I also don't know if this is the safest and most pythonic way of structuring a class object:

class PositionVector(object):
  def __init__(self, vector, system='cartesian'):
    if system == 'cartesian':
      self.cartesian = vector
      self.polar = self.position_vector_polar(self.cartesian)
    if system == 'polar':
      self.polar = vector
      self.cartesian = self.position_vector_cartesian(self.polar)

  @property
  def cartesian(self):
    return self._cartesian
  @cartesian.setter
  def cartesian(self, value):
    self._cartesian = value
    self._polar = self.position_vector_polar(self._cartesian)
    self._x, self._y, self._z = self._cartesian
    self._r, self._theta, self._phi = self._polar

  @property
  def polar(self):
    return self._polar
  @polar.setter
  def polar(self, value):
    self._polar = value
    self._cartesian  = self.position_vector_cartesian(self._polar)
    self._x, self._y, self._z = self.cartesian
    self._r, self._theta, self._phi = self.polar

  @property
  def x(self):
    return self._x
  @x.setter
  def x(self, value):
    self._x = value
    self._cartesian[0]  = self._x
    self._polar = self.position_vector_polar(self._cartesian)

  # repeat above for y and z variables

  @property
  def r(self):
    return self._r
  @r.setter
  def r(self, value):
    self._r = value
    self._polar[0]  = self._r
    self._cartesian = self.position_vector_cartesian(self._polar)

  # repeat above for thets and phi variables

  def position_vector_cartesian(self, polar):
    r, theta, phi = polar
    x = r * math.cos(theta) * math.sin(phi)
    y = r * math.sin(theta) * math.sin(phi)
    z = r * math.cos(phi)
    return [x, y, z]

  def position_vector_polar(self, cartesian):
    x, y, z = cartesian
    r = math.sqrt(x ** 2 + y ** 2 + z ** 2)
    theta = math.atan(y/x)
    phi = math.acos(z/r)
    return [r, theta, phi]

Note that the lists will be be replaced with NumPy arrays so I can perform algebra on the vectors, but for now I just want to get the class structure correct.


texts:
I would like any suggestions and improvements for this code, be it generics or my Node class being completely mutable. Should I make it mutable? Is it good? Why?

package ishan.trees.tree;

class Node implements Comparable<Node> {

    private int data;
    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getLeftChild() {
        return leftChild;
    }

    public void setLeftChild(Node leftChild) {
        this.leftChild = leftChild;
    }

    public Node getRightChild() {
        return rightChild;
    }

    public void setRightChild(Node rightChild) {
        this.rightChild = rightChild;
    }

    private Node leftChild;
    private Node rightChild;

    public Node(int data,Node leftChild,Node rightChild)
    {
        this.data=data;
        this.leftChild=leftChild;
        this.rightChild=rightChild;

    }

    @Override
    public int compareTo(Node o) {
        if(o.getData() > this.data)
        return -1;

        if(o.getData() < this.data)
            return 1;

        return 0;
    }
}

Tree class

package ishan.trees.tree;

public class Tree {

    private Node root=null;

    public Node getRoot() {
        return root;
    }

    public void insertData(int data)
    {
        Node node=new Node(data,null,null);
        insert(node,this.root);

    }

    private Node insert(Comparable<Node> node,Node root1)
    {
            if(root1==null)
            {

                root1=new Node(((Node)node).getData(),null,null);
                if(this.root==null)
                {
                    this.root=root1;
                }
            }
            else if(node.compareTo(root1) <0)
            {
                root1.setLeftChild(insert(node,root1.getLeftChild()));
            }
            else if(node.compareTo(root1) >0)
            {

                root1.setLeftChild(insert(node,root1.getRightChild()));
            }

     return root1;
    }
}


texts:
I recently implemented the Sieve of Atkin prime generating algorithm in Python. Though I know the term "pythonic" isn't exactly set in stone, I can tell that my program doesn't quite take advantage of python's inherent traits; my program looks like it was written with "C" in mind.

My question is two fold; (1) how can I make this more pythonic, and (2) how can I improve its performance?

I suspect the solution lies in making less use of lists in lieu of generators, but I'm not sure how to do so here:

def atkin_sieve(limit):
    sieve_list = [-1]*limit
    sieve_list[2] *= -1
    sieve_list[3] *= -1
    x = 1
    # Part I: preliminary work
    while(x*x < limit):
        y = 1
        while(y*y < limit):
            n = (4*x*x)+(y*y)
            if n <= limit and (n%12==5 or n%12==1):
                sieve_list[n] *= -1

            n = (3*x*x)+(y*y)
            if n <= limit and n%12==7:
                sieve_list[n] *= -1

            n = (3*x*x)-(y*y)
            if n <= limit and n%12==11 and x>y:
                sieve_list[n] *= -1
            y += 1
        x += 1
    # Part II: Remove the squares of primes (and their multiples)
    r = 5
    while r*r < limit:
        if sieve_list[r] > 0:
            i = r*r
            while i < limit:
                sieve_list[i] = -1
                i += r*r
        r += 1
    # Part III: Append everything into a list
    results = []
    x = 0
    for p in sieve_list:
        if p > 0:
            results.append(x)
        x += 1
    return results


texts:
I have implemented the topological sort.
Is there any suggestion for optimizing the solution?
Thanks.
package src;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;

class Graph{
    int V;
    LinkedList[] edges;

    public Graph(int vertices){
        V =vertices;
        edges = new LinkedList[V];
        for(int i=0;i<V;i++){
            edges[i] = new LinkedList();
        }
    }

    // Time complexity O(V+E)
    public void topologicalSort() {

        Stack stacks = new Stack();

        boolean[] visited = new boolean[V];

        for(int i=0;i<V;i++) {

            if(!visited[i]){
                topologicalSortUtil(i,visited,stacks);
            }
        }

        while(!stacks.isEmpty()){
            System.out.println(stacks.pop());
        }

    }

    private void topologicalSortUtil(int i, boolean[] visited, Stack stacks) {

        stacks.push(i);

        visited[i] =true;

        Iterator<Integer> iterator = edges[i].listIterator();
        while(iterator.hasNext()){

            int item = iterator.next();
            if(!visited[item]){
                topologicalSortUtil(item,visited,stacks);
            }
            stacks.push(item);
        }

    }
}

public class TopologicalSorting {

    public static void main(String[] args) {

        Graph graph = new Graph(8);

        graph.topologicalSort();

    }
}

package src;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;

class Graph{
    int V;
    LinkedList[] edges;

    public Graph(int vertices){
        V =vertices;
        edges = new LinkedList[V];
        for(int i=0;i<V;i++){
            edges[i] = new LinkedList();
        }
    }

    // Time complexity O(V+E)
    public void topologicalSort() {

        Stack stacks = new Stack();

        boolean[] visited = new boolean[V];

        for(int i=0;i<V;i++) {

            if(!visited[i]){
                topologicalSortUtil(i,visited,stacks);
            }
        }

        while(!stacks.isEmpty()){
            System.out.println(stacks.pop());
        }

    }

    private void topologicalSortUtil(int i, boolean[] visited, Stack stacks) {

        stacks.push(i);

        visited[i] =true;

        Iterator<Integer> iterator = edges[i].listIterator();
        while(iterator.hasNext()){

            int item = iterator.next();
            if(!visited[item]){
                topologicalSortUtil(item,visited,stacks);
            }
            stacks.push(item);
        }

    }
}

public class TopologicalSorting {

    public static void main(String[] args) {

        Graph graph = new Graph(8);

        graph.topologicalSort();

    }
}


texts:
I always read questions about a Windows solution to find a file in a directory structure like find and grep.
I created this working c++ program, where you give the program a path and a file name to find.
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <windows.h>

#ifndef INVALID_FILE_ATTRIBUTES
constexpr INVALID_FILE_ATTRIBUTES((DWORD) - 1)
#endif

BOOL IsDir(const std::string &path)
{
DWORD Attr;

Attr = GetFileAttributes(path.c_str());
if (Attr == INVALID_FILE_ATTRIBUTES)
    return FALSE;

return (BOOL)(Attr & FILE_ATTRIBUTE_DIRECTORY);
}

std::string sanitizePath(const std::string &path)
{
std::string fspath = path;

while (*(fspath.rbegin()) == '/' || *(fspath.rbegin()) == '\\')
    fspath.pop_back();

return fspath;
}

int findFiles(std::string &fspath, const std::string &fs)
{
static size_t i = 0;
WIN32_FIND_DATA FindFileData;

std::string destpath = fspath + std::string("\\*.*");

HANDLE hFind = FindFirstFile(destpath.c_str(), &FindFileData);

if (hFind != INVALID_HANDLE_VALUE)
    do {
        std::string fullpath = std::string(fspath) + std::string("\\") + std::string(FindFileData.cFileName);

        if (*(fullpath.rbegin()) == '.')
            continue;
        else if (FindFileData.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
            findFiles(fullpath, fs);
        else
        {
            if (FindFileData.cFileName == fs)
            {
                std::cout << fs << " was found in -> " << fspath << std::endl;
                i++;
            }
        }
    } while (FindNextFile(hFind, &FindFileData));

FindClose(hFind);
return i;
}

int main(int argc, char **argv)
{
if (argc <= 2)
{
    std::cerr << "No path or filename provided" << std::endl;
    return EXIT_FAILURE;
}

const char *path = argv[1];
const char *fileSearched = argv[2];

if (!IsDir(path))
{
    std::cerr << "Path doesn't exist" << std::endl;
    return EXIT_FAILURE;
}

std::string fspath = sanitizePath(path);
std::string fs = fileSearched;

std::cout << "Searching " << fspath << " and its subdirectories" << std::endl;

int i = findFiles(fspath, fs);

if (i == 0)
    std::cout << fs << " was not found in " << fspath << " or its subdirectories" << std::endl;
else if (i == 1)
    std::cout << fs << " was found once";
else
{
    std::cout << fs << " was found " << i << " times" << std::endl;
    std::cout << "Beware same filename does NOT automatically mean same file content." << std::endl;
}

return EXIT_SUCCESS;
}

it is used like this
find <path> <filename>

It is case sensitive and gives you whether and where the file was found and how many times.
I used an online code beautifier for indentation.
The sanitize method is for removing trailing "/" or "\".
It compiled and ran to multiple tests.
Please give me you opinions especially about its professionalism aka do code in big companies look like that?
Keep in mind, I graduated some time and failed so far in getting internship or a job in programming in my country.


texts: Checking a value before assigning it to variable

texts:
Throughout my code, I find myself testing if the output of a function is undefined or blank before i use the output. In this case, getQuery checks if the property of an object is either blank or if the object key is not set at all. In both cases, the output can be ignored. But if the object key holds a value, then I want to use this output as the value for my variable.

var filter = ""
if ( typeof getQuery("filter") != 'undefined' && getQuery("filter") != "" ) filter = getQuery("filter")
if ( filter != "" ) createFilterView( filter )

There must be a more optimized way of doing this without the repetition?

I often set the output of the function to a variable first, in order to not have to perform the function several times. A bit faster, I assume, but also not very elegant.

var getQueryFilter_output = getQuery("filter")
if ( getQueryFilter_output != 'undefined' && getQueryFilter_output != "" ) var filter = getQuery_output

What would be a better way of doing this?


texts:
Roman numerals are represented by seven different symbols: I, V, X, L,
  C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

  For example, two is written as II in Roman numeral, just two one's
  added together.  Twelve is written as, XII, which is simply X + II.
  The number twenty seven is written as XXVII, which is XX + V + II.

  Roman numerals are usually written largest to smallest from left to
  right. However, the numeral for four is not IIII. Instead, the number
  four is written as IV. Because the one is before the five we subtract
  it making four. The same principle applies to the number nine, which
  is written as IX. There are six instances where subtraction is used:

  I can be placed before V (5) and X (10) to make 4 and 9.
  X can be placed before L (50) and C (100) to make 40 and 90.
  C can be placed before D (500) and M (1000) to make 400 and 900.

  Given a Roman numeral, convert it to an integer. Input is guaranteed
  to be within the range from 1 to 3999.

  Example 1:
  Input: "III"
  Output: 3

  Example 2:
  Input: "IV"
  Output: 4

  Example 3:
  Input: "IX"
  Output: 9

  Example 4:
  Input: "LVIII"
  Output: 58
  Explanation: L = 50, V= 5, III = 3.

  Example 5:
  Input: "MCMXCIV"
  Output: 1994
  Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

My function in Python to accomplish this task:

def romanToInt(self, s: str) -> int:
    checks = {"IV":-2,"IX":-2, "XL":-20, "XC":-20, "CD":-200, "CM":-200}
    values = {"I":1, "V":5,"X":10, "L":50,"C":100, "D":500,"M":1000}
    sum = 0

    for i in s:
        sum += values[i]

    for i in range(len(s) - 1):
        combine = str(s[i] + s[i + 1])
        if combine in checks:
            sum += checks[combine]

    return sum

I'd love to get some feedback. I'm not sure if I should change the variable name from sum to something else, as I'm overwriting a python function. However, I don't use that function inside of my function, so does it matter?

Additionally, should I be converting the string to a list? Strings are immutable and I'm pulling apart and creating a new string with the combine variable, so I'm not sure if that's something I should be concerned about with regards to time complexity.


texts: Implemented my own version of every() from {purrr}

texts:
I am new to programming / R and new to writing functions. I am working through the book R for Data Science and am on the following exercise:
Implement your own version of every() using a for loop.
In case you're unaware, the every function from purrr does the following:
Do every element of a list satisfy a predicate?
Here is the function I came up with:
every_2 <- function(x, fun) {
  output <- vector("logical", length(x))
  output2 <- vector("logical", length = 1L)
  for (i in seq_along(x)) {
    output[[i]] <- fun(x[[i]])
    if (sum(output) < length(output)){
      output2 <- FALSE
    } else {
      output2 <- TRUE
    }
  }
  output2
}

Using the following numeric vector:
test_vec <- 1:100

The output matches that of the original every function.
every(test_vec, function(x) {x > 0}) # TRUE
every(test_vec, function(x) {x > 100}) # FALSE
every(test_vec, is.character) # FALSE
every(test_vec, is.numeric) # TRUE

every_2(test_vec, function (x) {x > 0}) # TRUE
every_2(test_vec, function(x) {x > 100}) # FALSE
every_2(test_vec, is.character) # FALSE
every_2(test_vec, is.numeric) # TRUE


texts: Python multiprocessing with multithreading - processing a list of work

texts:
Although this code can be used for many different purposes, I'm building it for use in web-scraping. I would like to know if this is the best approach. Can you see any bugs or potential lockups?

The idea is that I have a list of URLs to scrape. So to start processing it, I create a Process using the multiprocessing module. Along with that process, I create a BoundedSemaphore to control the number of active threads for that process. While there's work to do, it grabs an item from the Queue and processes it. (In reality, it would requesting the source code from a web page, parsing it and writing some contents to a file.) I keep repeating the above steps until I've maxed out a 1 to 1 ratio of processes to available cores.

I would like to utilize the full potential of the computer it runs on, assuming the website can handle the traffic.

"""Utilize all available cores to process a list of work."""
import multiprocessing as mp
import threading
import queue
from time import sleep

try:
    NUMB_PROCESSES = mp.cpu_count()
except NotImplementedError:
    NUMB_PROCESSES = 1
NUMB_THREADS_PER_PROCESS = 8
Q = mp.Queue()

class CustomThread(threading.Thread):
    """This functions the same as the inherited Thread
    class except with added semaphore parameter, which
    always releases the semaphore when the thread is done.
    """
    def __init__(self, semaphore=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._semaphore = semaphore

    def run(self):
        try:
            if self._target:
                self._target(*self._args, **self._kwargs)
        finally:
            if self._semaphore:
                self._semaphore.release()
            del self._target, self._args, self._kwargs

def do_work(i, process_name):
    """Do the heavy processing."""
    sleep(0.5)
    print('Process Number: {}, value: {}'.format(
        process_name,i*i))

def populate_queue():
    """Fill up the queue with work to do.
    Additional work will not be added."""
    for x in range(10000):
        Q.put(x)

def run_threads(p_name, semaphore):
    """As long as there are items on the queue,
    i.e. work to do, then we keep threading."""
    while not Q.empty():
        semaphore.acquire()
        try:
            i = Q.get(timeout=1)
        except queue.Empty:
            break
        CustomThread(
            target=do_work, daemon=1,
            args=(i,p_name), semaphore=semaphore
        ).start()

def start_processes():
    """Initialize the queue with work and start
    a number of process (defined above). With
    each process, we create a bounded semaphore
    to control the number of active threads
    per process."""
    populate_queue()
    process_list = []
    for x in range(NUMB_PROCESSES):
        semaphore = threading.BoundedSemaphore(
            NUMB_THREADS_PER_PROCESS)
        # pass the semaphore to the target func
        p = mp.Process(
            target=run_threads,
            args=(x,semaphore,), name=str(x)
        )
        process_list.append(p)
        p.start()
    for process in process_list:
        # make sure all processes have completed
        process.join()

if __name__ == '__main__':
    start_processes()