texts: Order line reversing (reversing line order)

texts:
I'm a student learning to code in C. I had to make a program for class to reverse lines of input from the keyboard (not character wise, but reverse the order of the lines input).
The program is working to the requirements of the assignment already, but feel free to have a look at my code and help me understand where I can make improvements to it. I am looking to learn as much as possible about the language.

Assignment:
Program will allow user to type in several lines of a poem. User signals the end of their input with a single dot on a newline (and enter). After input, the lines will be printed out from last entered to first. No line can be greater than 1000 characters in length. No max number of lines. Lines cannot contain a single '.' dot/period as the only character on the line. No use of global variables.

   1 #include <stdio.h>
   2 #include <stdlib.h>
   3 #include <string.h>
   4
   5 int main(){
   6
   7   /* array variables */
   8   int MAXSIZE = 1000;
   9   char **array;
  10   char *string;
  11   char inputStr[MAXSIZE+1];
  12
  13   /* declare for my while loop parameter*/
  14   inputStr[0] = 0;
  15
  16   /* logic variables */
  17   int i = 0;
  18   int j = 0;
  19
  20   /* allocate inital space for a line */
  21   array = malloc(sizeof(char*) * 1);
  22
  23   printf("Enter the poem:\n");
  24
  25   /* if the line is only a period, end loop */
  26   while(*inputStr != '.'){
  27
  28     /* get input from user, max 1000 chars per line */
  29     fgets(inputStr,MAXSIZE,stdin);
  30     inputStr[strlen(inputStr)-1] = '\0';
  31
  32     if(*inputStr != '.'){
  33
  34       /* allocate space to store the string and copy from input */
  35       string = malloc ( sizeof(char) * (strlen(inputStr)+1) );
  36       strncpy ( string, inputStr, strlen(inputStr)+1 );
  37
  38       /* allocate space in the array for the string and copy it in */
  39       array[i] = malloc((sizeof(char*))*(strlen(string))+1);
  40       strncpy(array[i],string,strlen(string)+1);
  41
  42       /* free the string, add to line count, reallocate with new line count */
  43       free (string);
  44       i++;
  45       array = realloc(array, (i + 1) * sizeof(char*));
  46     }
  47   }
  48
  49   /* print the array in reverse order using line count*/
  50   for( j = i-1 ; j >= 0; j-- ){
  51     printf("%s\n", array[j]);
  52   }
  53
  54   /* free the array strings and then the array */
  55   while(i--){
  56     free(array[i]);
  57   }
  58   free(array);
  59
  60   return(0);
  61
  62 }


texts:
I wrote a custom class which (atm) displays the +, -, =, x, and ÷ operators inside a circle. Apart from the issue of some symbols not appearing in the exact center (everything except + looks a bit off) it works great. It uses an enum to select the symbol to make using the ÷ symbol easier.

public enum Operators { Plus = '+', Minus = '-', Divide = '÷', Multiply = 'x', Equal = '=' };

class MathematicalOperator : Control
{
    private Operators op;
    public Operators Operator
    {
        get { return op; }
        set
        {
            if (value == op) return;
            op = value;
            Invalidate();
        }
    }

    private Color background;
    public Color Background
    {
        get { return background; }
        set
        {
            if (value == background) return;
            background = value;
            Invalidate();
        }
    }

    private Color foreground;
    public Color Foreground
    {
        get { return foreground; }
        set
        {
            if (value == foreground) return;
            foreground = value;
            Invalidate();
        }
    }

    public MathematicalOperator(Operators op)
    {
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        BackColor = Color.Transparent;
        TabStop = false;
        Operator = op;
        Foreground = Color.Black;
        Background = Color.White;
        Width = 35;
        Height = 35;
    }

    public MathematicalOperator()
        : this(Operators.Equal)
    { }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        Graphics graphics = e.Graphics;
        Rectangle rc = this.ClientRectangle;
        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        Font font = new Font("Arial", rc.Height * 0.65f, FontStyle.Bold, GraphicsUnit.Pixel);
        StringFormat sf = new StringFormat();
        sf.Alignment = StringAlignment.Center;
        sf.LineAlignment = StringAlignment.Center;

        using (var background = new SolidBrush(Background))
        using (var foreground = new Pen(Foreground, 2.0f))
        using (var text = new SolidBrush(Foreground))
        {
            graphics.FillEllipse(background, rc.Left + 1.5f, rc.Top + 1.5f, rc.Width - 4.0f, rc.Height - 4.0f);
            graphics.DrawEllipse(foreground, rc.Left + 1.5f, rc.Top + 1.5f, rc.Width - 4.0f, rc.Height - 4.0f);
            graphics.DrawString(((char)Operator).ToString(), font, text, rc, sf);
        }
    }
}


texts:
I am new to JavaScript so I am not sure if it's bad practice to nest a for loops inside of each other.

This script simply takes a WordPress HTML menu and restructures it into a format better suited to my requirements.

Below you can see the original HTML, the JS and the new HTML output by the JS.

The nested "for of" loop checks the deepest anchor tags to see if the href matched the window and gives it a "is-active" class if it does. Should this "for of" loop be in its own function or is the nesting okay?

Is there a better way to write the JS?

Original HTML:

      Label 1

link

link

link

link

link

      Label 2

link

link

link

link

link

JS

const menuWrapper = document.querySelector(`aside.menu`);
const badMenu = document.querySelector(`.menu-list`);
const badMenuItems = document.querySelectorAll(`.menu-label`);

function fixMenus(menu, items) {
  // Remove old menu
  menu.remove();
  let fixedMenu = ``;

  // Iterate through and build new menu
    items.forEach(x => {
        const labels = x.children[0].innerHTML;
    const subMenus = x.children[1];
    const subItems = x.children[1].children;

    //Set "is-active" to anchor tag
    for (let i of subItems) {
      if (i.firstElementChild.href === window.location.href) {
        i.firstElementChild.classList.add(`is-active`)
      }
    }

    //Build new menu
        fixedMenu += `

${labels}

        ${subMenus.innerHTML}

    `;
  });

  return fixedMenu;
}

const sideMenus = fixMenus(badMenu, badMenuItems);
menuWrapper.insertAdjacentHTML(`beforeend`, sideMenus);

NEW HTML (rebuild, returned from the JS)

Label 1

link

link

link

link

link

Label 2

link

link

link

link

link


texts: Regular expression matching with string slice in Go

texts:
I have a slice of strings, and within each string contains multiple key=value formatted messages. I want to pull all the keys out of the strings so I can collect them to use as the header for a CSV file. I do not know all potential key fields, so I have to use regular expression matching to find them.

Here is my code.

package main

import (
    "fmt"
    "regexp"
)
func GetKeys(logs []string) []string {
        // topMatches is the final array to be returned.
        // midMatches contains no duplicates, but the data is `key=`.
        // subMatches contains all initial matches.
        // initialRegex matches for anthing that matches `key=`. this is because the matching patterns.
        // cleanRegex massages `key=` to `key`
        topMatches := []string{}
        midMatches := []string{}
        subMatches := []string{}
        initialRegex := regexp.MustCompile(`([a-zA-Z]{1,}\=)`)
        cleanRegex := regexp.MustCompile(`([a-zA-Z]{1,})`)

        // the nested loop for matches is because FindAllString
        // returns []string
        for _, i := range logs {
                matches := initialRegex.FindAllString(i, -1)
                for _, m := range matches {
                        subMatches = append(subMatches, m)
                }
        }

        // remove duplicates.
        seen := map[string]string{}
        for _, x := range subMatches {
                if _, ok := seen[x]; !ok {
                        midMatches = append(midMatches, x)
                        seen[x] = x
                }
        }
        // this is where I remove the `=` character.
        for _, y := range midMatches {
                clean := cleanRegex.FindAllString(y, 1)
                topMatches = append(topMatches, clean[0])
        }
        return topMatches
}

func main() {
    y := []string{"key=value", "msg=payload", "test=yay", "msg=payload"}
    y = GetKeys(y)
    fmt.Println(y)
}

I think my code is inefficient because I cannot determine how to properly optimise the initialRegex regular expression to match just the key in the key=value format without matching the value as well.

Can my first regular expression, initialRegex, be optimised so I do not have to do a second matching loop to remove the = character?

Playground: http://play.golang.org/p/ONMf_cympM


texts: use trie data structure to solve the problem of clustering anagrams

texts:
Given an array of words, print all anagrams together. For example, if
  the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output
  may be “cat tac act dog god”.

The following is my c++ code. I use raw pointer to implement varying number of children
for practice. Actually, I guess maybe it's better to adopt STL containers.

#include <iostream>
#include <cstring>
using namespace std;

struct Index_node_base
{
    Index_node_base* next;
    Index_node_base():next(NULL){}
};

struct Index_node : public Index_node_base
{
    int index;
    Index_node(int i):index(i), Index_node_base(){}
};

void insert_index_node(Index_node** head, int i)
{
    Index_node* node = new Index_node(i);
    node->next = (*head);
    *head = node;
}

struct Trie_node_base
{
    typedef Trie_node_base* Base_ptr;

    Base_ptr* child;
    int num_of_child;

    Trie_node_base(int n)
    {
        child = new Base_ptr[n];
        for(int i=0; i < n; ++i)
            child[i] = NULL;
        num_of_child = n;
    }

    ~Trie_node_base()
    {
        delete [] child;
    }
};

struct Trie_node : public Trie_node_base
{
    bool is_end;
    Index_node* head;
    Trie_node(int n):Trie_node_base(n), is_end(false), head(NULL){}
};

class Trie
{
public:
    Trie(int n=26)
    {
        root = new Trie_node(n);
    }
    ~Trie()
    {
        destroy(root);
    }

    void insert_trie_node(const char* w, int ind);
    Trie_node* get_root_node();

private:
    Trie_node* root;
    void destroy(Trie_node* root);
};

Trie_node* Trie::get_root_node()
{
    return root;
}

void Trie::insert_trie_node(const char* w, int ind)
{
    Trie_node* r = root;
    while(*w)
    {
        int i = *w - 'a';
        if(r->child[i] == NULL)
        {
            r->child[i] = new Trie_node(r->num_of_child);
        }
        r = (Trie_node*)r->child[i];
        ++w;
    }

    if(r->is_end)
    {
        insert_index_node(&(r->head), ind);
    }
    else
    {
        r->is_end = true;
        r->head = new Index_node(ind);
    }
}

void traversal_trie(const char* word_arr[], Trie_node* r)
{
    size_t i;

    if(r->is_end)
    {
        Index_node* h = r->head;
        while(h != NULL)
        {
            printf("%s\n", word_arr[h->index]);
            h = (Index_node*)h->next;
        }
    }

    for(i = 0; i < r->num_of_child; ++i)
    {
        if(r->child[i] != NULL)
            traversal_trie(word_arr, (Trie_node*)r->child[i]);
    }
}

void Trie::destroy(Trie_node* root)
{
    size_t i;

    for(i = 0; i < root->num_of_child; ++i)
    {
        if(root->child[i] != NULL)
            destroy((Trie_node*)root->child[i]);
    }

    if(root->is_end)
    {
        Index_node* h = root->head;
        Index_node* tmp = NULL;

        while(h != NULL)
        {
            tmp = (Index_node*)h->next;
            delete h;
            h = tmp;
        }
    }

    delete root;
}

static int comp_char(const void* x, const void* y)
{
    const char* c1 = (const char*)x;
    const char* c2 = (const char*)y;

    return *(c1) - *(c2);
}

static void cluster_anagrams(const char* word_arr[], size_t size)
{
    Trie* trie = new Trie(26);
    size_t i;
    char* buffer;

    for(i = 0; i < size; ++i)
    {
        int len = strlen(word_arr[i]);
        buffer = new char [len+1];
        memcpy(buffer, word_arr[i], len+1);
        qsort(buffer, strlen(buffer), 1, comp_char);
        trie->insert_trie_node(buffer, i);
        delete buffer;
    }

    cout << "Debug!" << endl;
    traversal_trie(word_arr, trie->get_root_node());
}

int main()
{
    const char* word_arr[] = {"cat", "dog", "tac", "god", "act", "gdo"};
    size_t size = sizeof(word_arr) / sizeof(word_arr[0]);
    cluster_anagrams(word_arr, size);

    system("pause");
    return 0;
}


texts: Creating dialogs and modals with AngularJS

texts:
I wonder whether or not I should improve my current practice on creating/calling dialogs with AngularJS.

Think of a simple information, displayed on demand as a modal window. To create such a thing, I would write a directive, include it to my page and use ng-hide to hide it.

If I want to call it, I would simply change the associated ng-hide value to false from within my main controller.

app.directive('modal',function(){
  return{
    restrict: 'E',
    template: '

',
    // etc
  }
});

app.controller('Ctrl',function($scope){
  $scope.state.modalVisibility = false;

  $scope.changeVisibility = function(){
    $scope.state.modalVisibility = true;
  }
});

Are there any disadvantages or possible improvements on this practice?  Is it a bad idea to have the modal-element "always there" but only displayed on demand?


texts:
Background information: Given two different strings of equal length, the spacing between them is the number of other strings you would need to connect them on a word ladder. Alternately, this is 1 less than the number of letters that differ between the two strings.

The challenge: Given an input list of unique words and a maximum total spacing, output a list of distinct words taken from the input list. The output list's total spacing must not exceed the given maximum. The output list should be as long as possible.

My output list is 433 words long. May someone look over code proofreading/ efficiency? Much thanks.

Also, the text file used in the program can be found here: https://gist.githubusercontent.com/cosmologicon/0a4448e8fdb79ee620a68ed131eac58e/raw/a8831d08019f73e7d5a52042e2c4afe6fea70011/363-hard-words.txt

import operator

MAX = 100  # Max word ladder score I'm allowed in this program

with open("363-hard-words.txt") as f:
    data = f.read().splitlines()
    f.close()

def merge_two_dicts(x, y):
    z = x.copy()
    z.update(y)
    return z

# Returns numerical spacing between a and b on the word ladder
def spacing(a, b):
    score = 0
    for x, y in zip(a, b):
        if x != y:
            score += 1
    return score - 1

# Returns a dictionary of txt file words as key, with number of words with sp spacing as value
def space_dict(sp):
    totals = []
    for word in data:
        total = 0
        for word1 in data:
            if word == word1:
                continue
            if spacing(word, word1) == sp:
                total += 1
        totals.append(total)
    return dict(zip(data, totals))

# Given a word, returns a dictionary with every other word as the key,
# and the spacing between the word and the other word as the value
def words_dict(word):
    totals = []
    for w in data:
        if w == word:
            continue
        totals.append(spacing(word, w))
    return dict(zip(data, totals))

# Sorts a dictionary by its keys in ascending order and returns a list
def sort_dict(space):
    return sorted(space.items(), key=operator.itemgetter(1))

# Returns a list of words with number spacing to the word
def get_connections(word, number):
    output = []
    for w in data:
        if (spacing(word, w) == number) and (word != w):
            output.append(w)
    return output

# Attempts to return max list of words with a total word ladder score of 0
def method1():
    output = []
    sorted_dict = sort_dict(space_dict(0))
    output.append(sorted_dict[-1][0])
    data.remove(sorted_dict[-1][0])
    connections = get_connections(sorted_dict[-1][0], 0)

    while len(get_connections(connections[-1], 0)) != 0:
        connections = get_connections(connections[-1], 0)
        output.append(connections[-1])
        print("connections:", connections, "Output size:", str(len(output)))
        data.remove(connections[-1])
    return len(output)

# Attempts to return max length of a word ladder given first word, inspired by
# tajjet's solution
def method2_iter(wd):
    score, length = 0, 0
    output = [wd]
    sorted_dict = sort_dict(words_dict(wd))
    data.remove(wd)
    while score <= 100:
        length += 1
        word = sorted_dict[0][0]
        score += sorted_dict[0][1]
        if score > 100:
            break
        output.append(word)
        data.remove(word)
        sorted_dict = sort_dict(words_dict(word))
    print(output)
    return length

def main():
    # print(str(method1()))
    print(str(method2_iter("kats")))

main()


texts:
Problem: Make a slider, located at the bottom of the page. The slider should be dynamically loaded only when a div (#slider) becomes visible on the screen. Images do not have to load all at once. Load the first two images, then load the third when we switched to the second, and so on.

I would like other users to look look at my code and tell me what I'm doing wrong and what could be done better (if you can - in more detail).

$(function () {
    var countImg = 5,
        indexImg = 1,
        indexImgLoad = 2,
        pathImg = '/img/slider/',
        formatImg = 'jpg',
        controlFlag = 1,
        elWrap = $('#slider'),
        el =  elWrap.find('img');
    function create () {
        Img = new Image();
        Img.src= pathImg+indexImg+'.'+formatImg;
        $(Img).appendTo($("#slides"));
        $('').appendTo($("#slider"));
        navigation();
        check();
    }
    function change () {
        el.fadeOut(500);
        el.filter(':nth-child('+indexImg+')').fadeIn(500);
    }
    function newimg() {
        nextImg = new Image();
        nextImg.src= pathImg+indexImgLoad+'.'+formatImg;
        $(nextImg).appendTo($("#slides"));
    }
    function check() {
        if (controlFlag && indexImgLoad <= countImg) {
            newimg();
        }
        if (controlFlag){
            el =  elWrap.find('img');
        }
        if (el.length == countImg){
            controlFlag = 0;
        }
    }
    function navigation(){
        $('span.next').click(function() {
            indexImg++;
            indexImgLoad++;
            if(indexImg > countImg) {
                indexImg = 1;
            }
            check();
            change();
        });
        $('span.prev').click(function() {
            indexImg--;
            if(indexImg < 1) {
                indexImg = countImg;
            }
            indexImgLoad++;
            check();
            change ();
        });
    }
    var loadSlider = 1;
    window.onscroll = function() {
          var pageY = window.pageYOffset || document.documentElement.scrollTop,
        heightScreen = window.innerHeight + pageY;
        sliderTopY = $("#slides").offset().top;
        if ((heightScreen > (sliderTopY - sliderTopY * 0.05)) && loadSlider) {
            loadSlider = 0;
            create();
        }
    }
});
.slider_wrap {
        margin: 0px auto 0;
        width: 735px;
        height: 200px;
        position: relative;
        overflow: hidden;
    }
    .slider_wrap img {
        width: 645px;
        height: auto;
        display: none;
        position: absolute;
        top: 0;
        left: 45px;
    }
    .slider_wrap img:first-child {
        display: block;
    }
    .slider_wrap span {
        width: 45px;
        height: 200px;
        display: block;
        position: absolute;
        cursor: pointer;
        background: url(/img/rotator_buttons.png) no-repeat;
        opacity: 0.7;
    }
    .slider_wrap span.next {
        right: 0;
        background-position: -45px 0;
    }
    .slider_wrap span.next:hover, span.prev:hover {
        opacity: 1.0;
    }
    .slider_wrap span.prev {
        background-position: 0 0;
    }

div: height = 1800px


texts: Linked List class based implementation in Python

texts:
I have the following class based linked list created in Python. I need some help in the best way to actually call and test this (print the results and output to the screen).

For an accepted answer, could someone please
1. use my existing code, to test/output results showing the linked list implementation
2. Make any comments on my existing code and suggestions as to how it could be improved (if any)

I am not sure how to "call" the testing method to see the results, or whether it is better to take that out and test outside the class. If the latter is preferred, could someone please demonstrate this, as I am unclear/unsure of the creation of nodes and next pointer objects in order to test the class.

Code:

class Node:
        def __init__(self,contents=None, next=None):
                #Here we are defining the two attributes - contents of the list and the next pointer
                self.contents = contents
                self.next = next

        def getContents(self):
                return self.contents

        def __str__(self):
                return str(self.contents)

        def print_list(node):
                while node:
                        print(node.getContents())
                        node=node.next
                print()

        def testing():
                #Add content to each node
                node1=Node("A")
                node2=Node("C")
                node3=Node("D")
                node4=Node("B")
                #Define the pointers for each node (e.g. follow through A to B to C to D)
                node1.next=node4
                node4.next=node2
                node2.next=node3
                print(print_list(node1))

I am also unclear on the implementation, as when creating a queue you would have something like the below to add an element. Would this not be needed here for a linked list?

Method for adding an item to a queue

def add(self,item): #method to add something
        self.items.append(item) #to add something, use append

This would be added to the queue (and tested) like so:

    myQ.add("A")
    myQ.add("B")
    myQ.add("C")

I think some guidance on what exactly is happening (comments) would be helpful too.


texts: bash script - sed - template file processing

texts:
Using a bash script to process a file and pass it to AWS CLI. The script runs inside a docker container.

I'm using sed to do template string replace. When MY_VALUE contains special chars. (eg: MY_VALUE="http://aaa.com") the sed command fails.

This makes me question if sed is the right tool for this job, don't have a lot of control on the values that come in.

Because the template is a JSON file, I considered trying JQ or Python (something like this).

I haven't used bash or Unix tools a lot so I would like to hear your thoughts on:

Is sed the right tool for this type of job?
What else would you use?
What do you think about the script?

Simplified template (JSON)

{
    "networkMode": "bridge",
    "name": "[Placeholder.A]"
}

Script

#!/bin/bash

MY_VALUE=${myvalue}
rm -f processed.json

cat /app/template.json | \
sed s/\\[Placeholder.A]/${MY_VALUE}/ > /app/processed.json

aws cli command -file processed.json


texts: Returns two elements from a list whose sum is a target variable

texts:
def search(a,b):
    for d in b:
        if a==d:
            m=True
            break
        else:
            m=False
    return m

x=[1,4,5,7,9,6,2]
target=int(raw_input("Enter the number:"))
for i in x:
    if i<target:
        pair=int(target)-int(i)
        in2=search(pair,x)
        if in2==True:
            print "the first number= %d the second number %d"%(i,pair)
            break


texts: Repeated sequential subsetting of data.table

texts:
I have a long data.table, payoff_mat.  I would like to select the rows containing the maximum value of column X by group Y. There are several posts on this, and I think I am well optimized in this regard.

The twist is that I would like to repeat this process several times, for which I think I could do better.  This is the hot-spot of my script.

This is how it works:

Subset the rows containing the maximum value of column 3 by group (permutation of column 4-5).
Subset again by the maximum of column 2 by group (permutation of column 4).
Subset again by the maximum of column 1.

library(data.table)
library(iterpc)

set.seed(1)
I<-iterpc(table(rnorm(5)),3, ordered=TRUE,replace=FALSE)
support_n <-getnext(I,d=180) # not real size. Larger in practice.
payoff_n <-matrix(rnorm(180), ncol = 3) # not real size. Larger in practice.
payoff_mat<-cbind(payoff_n,support_n)
payoff_mat<-data.table(payoff_mat)

#My current solution:  eval(parse(text = ....)) is long but seems to be the standard best syntax for data.table in these cases.

cn<-colnames(payoff_mat) #need column names, data.table does not like using column number.
step_1<-payoff_mat[payoff_mat[ ,.I[ which.max(eval(parse(text = cn[3]))) ] , by = eval(cn[4:5]) ][,V1]] #
step_2<-step_1[step_1[ ,.I[ which.max(eval(parse(text = cn[2]))) ] , by = eval(cn[4:4]) ][,V1]]
step_3<-step_2[ ,.SD[ which.max(eval(parse(text = cn[1]))) ] ]

My intuition suggests I lose a lot of time writing to memory by saving each step, but I am happy with any improvement.

I have tried calling it as a single command, but have not been successful  figuring out the correct technique for sequential [] calls.  Below is my (current) best attempt, but it is clear they are not equivalent:

payoff_mat [payoff_mat[ ,.I[ which.max(eval(parse(text = cn[3]))) ] , by = eval(cn[4:5]) ][,V1]]  [payoff_mat[ ,.I[ which.max(eval(parse(text = cn[2]))) ] , by = eval(cn[4:4]) ][,V1]]  [ ,.SD[ which.max(eval(parse(text = cn[1]))) ] ]


texts: Subscribing to multiple sources in RxJava

texts:
I have used RxJava to Observe multiple sources and then perform action depending upon values of Observables. I want to know if it can be further simplified.

Goal:
Complete implementation of RxJava.

What I have:

Room (Database ORM) for storing local database using RxJava.
WebService API with Retrofit using RxJava.

Conditions:

Run Webservice call at regular interval.
Webservice call execute depending on result from Data retrieved from Database.

Code:

Dao class

@Query("select * from Login")
Flowable<List<Login>> getLoginRx();

API class

@Multipart
@POST("..")
Flowable<NotificationResponse> notification();

Java class

private Subscriber<List<Login>> loginSubscriber;
private Subscriber<NotificationResponse> notifSubscriber;
private Observer<Long> timerObserver;
private RoomDb roomDb;

@Override
protected void onCreate(Bundle b){
    roomDb = RoomDb.getInstance(this);
    notifSubscriber = new Subscriber<NotificationResponse>() {
        @Override
        public void onSubscribe(Subscription s) {
            s.request(1);
            notifSubscription = s;
        }

        @Override
        public void onNext(NotificationResponse nr) {
            if (nr.getSuccess()) {
                if (NetworkClient.STATUS_OK.equals(nr.getData().getStatus())) {
                    updateCounts(nr.getData());
                }
            }
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {

        }
    };

    timerObserver = new Observer<Long>() {
        @Override
        public void onSubscribe(Disposable d) {
            networkCallRepeat = d;
        }

        @Override
        public void onNext(Long aLong) {
            NetworkClient.getInstance(MainActivity.this).getNetworkAPI().notification(NetworkClient.stringPart(NetworkAPI.STAFF_TOKEN))
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(notifSubscriber);
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };
    loginSubscriber = new Subscriber<List<Login>>() {
        @Override
        public void onSubscribe(Subscription s) {
            s.request(1);
            loginSubscription = s;
        }

        @Override
        public void onNext(List<Login> logins) {
            if (logins != null && logins.size() > 0) {
                updateLoginState(logins.get(0));
                Observable
                        .interval(0L, 1L, TimeUnit.MINUTES)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(timerObserver);
            } else {
                if (networkCallRepeat != null && !networkCallRepeat.isDisposed()) {
                    networkCallRepeat.dispose();
                }
                updateLoginState(null);
            }
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {

        }
    };
}

@Override
protected void onResume() {
    super.onResume();
    roomDb.loginDao().getLoginRx()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(loginSubscriber);
}


texts: Compute the next occurrence of Friday the 13th

texts:
How can I get the date of the next occurrence of Friday the 13th?

Below is my attempt. It returns the correct results. I think there must be a better way of writing this without checking thirteenth > start_date for every month. It might also be possible to exploit the fact that every calendar year has a Friday 13th.

import itertools
from datetime import date

def next_fri_13(start_date):
    '''Get the next Friday 13th after the specified start_date.

    Args:
        start_date (datetime.date)

    Returns:
        datetime.date: The first Friday 13th after the start_date.
    '''
    for year in itertools.count(start_date.year):
        for month in range(1, 13):
            thirteenth = date(year, month, 13)
            # Ensure that the 13th is after the start date, and is a Friday.
            if thirteenth > start_date and thirteenth.weekday() == 4:
                return thirteenth

r = next_fri_13(date(2020, 2, 11))
print(r)  # Prints: 2020-03-13


texts: Updated: Questions on implementing Builder design pattern

texts:
I am in the process of using Java Builder design pattern to write a connector class that has optional member variables and need some suggestions. My question from here Standard practices for employing Java Builder design pattern has been updated and the code now presented is not psuedocode but is specific.

public class Connector {

    // Instance variables
    String appUrl = null;
    String oneTimePwd = null;
    String accessKey = null;

    // Private constructor
    private Connector(Builder builder) {
        this.appUrl = builder.appUrl;
        this.accessKey = builder.accessKey;
        this.oneTimePwd = builder.oneTimePwd;
    }

    public static class Builder {

        // Instance variables
        String appUrl = null;
        String accessKey = null;
        String oneTimePwd = null;

        public Builder() {
            // Empty constructor that accepts no arguments.
        }

        // Setter method for mandatory field/s
        public Builder setMandatoryParameters(String appUrl) {
            this.appUrl = appUrl;
            return this;
        }

        // Setter method1 for optional field/s
        public Builder setAccessKey(String accessKey) {
            this.accessKey = accessKey;
            return this;
        }

        // Setter method2 for optional field/s
        public Builder setOneTimePwd(String oneTimePwd) {
            this.oneTimePwd = oneTimePwd;
            return this;
        }

        public Connector Build() {
            if (accessKey != null) {
                return new Connector(this);
            } else if (oneTimePwd != null) {
                return new Connector(this);
            } else {
                // log.error("Either Access key or One time password must be specified.")
            }
            return null;
        }
    }

    // Other methods of the Connector class
    // ...
}

Question 1:
Is it sensible to make use of a method "setMandatoryParameters()" to obtain values for mandatory parameters? This will allow creation of an instance of the Builder without supplying the mandatory parameters which can be a drawback. Is it much better to ask the user to supply the values for mandatory parameters with Builder's constructor?

Question 2:
Either access key or one time password is needed to establish a successful connection. Thus, field validations such as null checks have been employed in the "Build()" method. Should such validations be performed in the Connector class's constructor instead?


texts:
Is there some way to speed this up, since it keeps timing out while running?

The spreadsheet is shared with a Google Group with editing permissions. I've loaded what I can into memory but each .addEditor and .removeEditor takes up to 3 seconds each x 100s of cells.

I have the sheet deleting the first row in the spreadsheet so it always shows the current day. I need to reapply cell-location-based named protections after deleting the first row since I need to use the named protection to delete the protection when a user deletes their booking.

var lockedRange = SpreadsheetApp.getActiveSheet().getRange("B3:F200");
  var lockedValues = SpreadsheetApp.getActiveSheet().getRange("B3:F200").getValues();
   var numRows = lockedRange.getNumRows();
   var numCols = lockedRange.getNumColumns();
   for (var i = 1; i <= numRows; i++) {
    for (var j = 1; j <= numCols; j++) {
      if (lockedValues[i-1][j-1].indexOf("@") > -1) {
          var protection = lockedRange.getCell(i, j).protect();
          protection.addEditor(lockedValues[i-1][j-1]);
          protection.setDescription(SheetName+lockedRange.getCell(i,j).getA1Notation());
          protection.removeEditor("Google Group Email");
          lockedRange.getCell(i,j).setBackground("#d6f8ff");
              if (protection.canDomainEdit()) {
                  protection.setDomainEdit(false);
              }
      }
    }
  }


texts: Implementing printf to a string by calling vsnprintf twice

texts:
I'm experimenting with writing a dynamic string library in C, and I decided to write an implementation of sprintf.

In my code, I call vsnprintf with a buffer of 0 bytes, just so I can get the number of bytes it requires. I was wondering if there is anything wrong with this code and if there a better way to do this. It feels wrong to me, but I can't seem to think of a better way to do so yet have the same effect.

string string_printf(const char *fmt, ...) {
    va_list in, copy;
    string a = NULL;
    int size;

    /* start the main input */
    va_start(in, fmt);
    /* make a copy of the input */
    va_copy(copy, in);

    /* run vsnprintf just to see how much bytes needed */
    size = vsnprintf(a, 0, fmt, copy) + 1;
    va_end(copy);

    /* allocate the amount now */
    a = string_new_size(size);
    string_to_sr(a)->len = size - 1;

    /* re-run */
    vsnprintf(a, size, fmt, in);
    va_end(in);

    /* done */
    return a;
}


texts: Spaceship Operation in for Lexicographic Comparison

texts:
I have written a program in Java 8 using BlueJ. There is just one function of type byte that accepts two String values and return 1 if the first word comes before the second in alphabetical order, and return -1 if the first word comes after the second in alphabetical order,  and 0 if both are equivalent strings. I would welcome any suggestions on how to make my code faster and more readable.

public class Test
{
    public static byte spaceshipAlphabetical (String str1, String str2)
    {
        int str1Length = str1.length();
        int str2Length = str2.length();
        int strLength;
        if
        (str1Length < str2Length)
        {
            str2 = str2.substring(0, str1Length);
            strLength = str1.length();
        }
        else
        {
            str1 = str1.substring(0, str2Length);
            strLength = str2.length();
        }
        str1 = str1.toUpperCase();
        str2 = str2.toUpperCase();
        char charStr1;
        char charStr2;
        int intChar1 = 0;
        int intChar2 = 0;
        for
        (int i = 0; i < strLength; i++)
        {
            charStr1 = str1.charAt(i);
            charStr2 = str2.charAt(i);
            intChar1 = (int) charStr1;
            intChar2 = (int) charStr2;
            if
            ((intChar1 < intChar2) || (intChar2 < intChar1) || ((intChar2 == intChar1) && (i == (strLength - 1))))
            {
                break;
            }
        }
        if
        ((intChar1 < intChar2) || ((intChar2 == intChar1) && (str1Length < str2Length)))
        {
            return 1;
        }
        else if
        ((intChar2 < intChar1) || ((intChar2 == intChar1) && (str2Length < str1Length)))
        {
            return -1;
        }
        else
        {
            return 0;
        }
    }


texts:
The following class holds an array with products that are generated from a Json file. This is what the json file looks like

[
  {
    "id": "A101",
    "description": "Screwdriver",
    "category": "1",
    "price": "9.75"
  },
  {
    "id": "A102",
    "description": "Electric screwdriver",
    "category": "1",
    "price": "49.50"
  },
  {
    "id": "B101",
    "description": "Basic on-off switch",
    "category": "2",
    "price": "4.99"
  }
]

I'm using a find method on a Product class, but I'm in doubt if storing all generated products in the class itself is a good idea

Should I maybe create a ProductCollection class?
Should I build my products[] collection differently then using my method
Should I generate a Factory for the product creation from my Json file.

This is my code

    class Product {

        private static $products = [];

        public static function initialize($url)
        {
            // Build the product from our JSON file
            $data = json_decode(file_get_contents($url));
            foreach($data as $item) {
                $product = new Product();
                $product->id = $item->id;
                $product->description = $item->description;
                $product->category = $item->category;
                $product->price = $item->price;

              self::$products[] = $product;
            }
        }

        public static function find($id)
        {
            foreach(self::$products as $product) {
                if($product->id == $id) {
                    return $product;
                }
            }

            return false;
        }
    }

Thank you.


texts: Single Validation function, called once per Animation function

texts:
Just looking for a way to include a single validation function inside of another function, that will stop any other lines from executing if it fails.

NOT an if statement... I'm trying to avoid nesting, because.. idk, I want to try to avoid it as much as possible.

So.... Is it bad to throw an Error to do this? I can't use return because it only ends the checkAnimationState(); but it doesn't also break out of the moveBlock() function...

JS FIDDLE

$(function(){
    // cache dom
    var $button = $('#button');
    var $block = $('#block');

    // event handlers
    $button.on('click', moveBlock);

    // functions
    function checkAnimationState(){
      if(!$block.hasClass('animating')){
        $block.addClass('animating');
      } else {
        throw Error('Block is already animating... BE PATIENT.');
      }
    }

  function moveBlock(){
    checkAnimationState(); // prevent animation if already animating.. validation..
    $block.animate(
        {marginLeft:'400px'},
      {
        duration: 3000,
        easing: "linear",
        complete: function(){
            $block.removeAttr('style').removeClass('animating');
        }
      }
    ); // end .animate();
  }
});


texts: A scroll to top button with fixed positioning

texts:
I have this JavaScript code that works as a top-of-page button when clicked. The button is hidden by default and only appears when the user scrolls 500px or more from the top of the page. But I am not that confident in this code as I am a beginner in JavaScript. Is there a shorter and more optimal way of doing it (excluding using the plain html anchor link Top):

var topBtn = document.getElementById("topButton");
var scrollExt = document.body.scrollTop;

window.onscroll = function() {
  ((document.body.scrollTop > 500 || document.documentElement.scrollTop > 500) ?
  topBtn.style.display = "block" : topBtn.style.display = "none");
};

topBtn.onclick = function() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}

CSS:

#topButton {display:none;position:fixed;bottom:50px;right:30px;z-index:99;padding:15px}

I have added this in the HTML as I have a difficult time creating the button using JavaScript:

<button id="topButton" title="Go to top">Top</button>


texts: Neatly Transforming Anorm ResultSet Into Map[Parent , (Set[Child1], Set[Child2]))]

texts:
I have a table Bill containing Bills with 0...n relationships to Material and Activity (line items on the bill).

My SQL query is essentially bill left join material left join activity.

I have the following insanely tangled code to transform the results into a Map[Bill, (HashSet[Activity], HashSet[Material])].

What's wrong with this code?  Is this whole approach wrong?  I'm new to Scala and the functional world, but it doesn't seem like this could be the right way.

 SQL(
          """
            |SELECT
            | b.id, b.dateDue
            | ,a.id as activityId, a.notes, a.startTime, a.endTime
            | ,m.id as materialId, m.cost, m.description, m.storageLocation
            |FROM Bill b
            |LEFT JOIN Activity a ON a.bill_id = b.id
            |LEFT JOIN Material m ON m.bill_id = b.id
            |WHERE b.id = {id}
          """.stripMargin)
        .on("id" -> id)
        .as(betterParser *)
        .groupBy( x=> (x._1, x._2))
        .map( q => q._1 ->
                q._2.foldLeft( (HashSet[Activity](), HashSet[Material]()) )
                ( (acc, item) =>  (acc._1 + item._3, acc._2 + item._4)))

betterParser transforms each row from the query into a (Long, DateTime, Activity, Material) where the  (Long, DateTime) portion are overall bill poperties.

 val betterParser = {
    billParser ~ activityParser ~ materialParser map {
      case bill ~ activity ~ material =>
       (bill._1, bill._2, activity, material)
   }
 }


texts: Clone a linked list with a random pointer (part 2)

texts:
This question is a follow-up question from here, where I implement the method from @vnp.

I have tested my code and it works, but the 3 steps processing seems a bit long to me. I also tried to write a few if/else, which seems a bit cluttering (e.g. code like newList.nextNode = newList.nextNode.nextNode if newList.nextNode else None). I'm wondering if there's any room to improve my code to make it even smaller and more elegant.

class LinkedListNode:
    def __init__(self, ID):
        self.ID = ID
        self.nextNode = None
        self.randomNode = None
    # return cloned new list
    def cloneList(self):
        # first step, add cloned node after each node
        node = self
        while node:
            newNode = LinkedListNode(node.ID)
            newNode.nextNode = node.nextNode
            node.nextNode = newNode
            node = node.nextNode.nextNode
        # 2nd step, setup random pointer
        node = self
        while node:
            node.nextNode.randomNode = node.randomNode.nextNode
            node = node.nextNode.nextNode

        # 3rd step, split existing and new list
        node = self
        newHead = node.nextNode
        newList = newHead
        while node:
            node.nextNode = node.nextNode.nextNode
            newList.nextNode = newList.nextNode.nextNode if newList.nextNode else None
            node = node.nextNode if node else None
            newList = newList.nextNode if newList else None

        return newHead

if __name__ == "__main__":
    node0 = LinkedListNode(0)
    node1 = LinkedListNode(1)
    node2 = LinkedListNode(2)
    node3 = LinkedListNode(3)
    node4 = LinkedListNode(4)
    node0.nextNode = node1
    node1.nextNode = node2
    node2.nextNode = node3
    node3.nextNode = node4
    node0.randomNode = node2
    node1.randomNode = node0
    node2.randomNode = node1
    node3.randomNode = node4
    node4.randomNode = node3

    newHead = node0.cloneList()

    while newHead:
        print (newHead.ID, newHead.nextNode.ID if newHead.nextNode else -1, newHead.randomNode.ID)
        newHead = newHead.nextNode


texts:
as a beginner in Python I made a rock, paper, scissors game and was wondering if my code was a bit weird and could be simplified???

print("Rock, Paper, Scissors")

def rps():
userInput = input("Please enter your choice: ")
userInput = userInput.lower()
if userInput != 'rock' and userInput != 'paper' and userInput != 'scissors':
    print("Your choice is invalid")
import random
computerChoice = ''
for x in range(1):
    num = random.randint(1,4)
if num == 1:
    computerChoice = 'rock'
elif num == 2:
    computerChoice = 'paper'
elif num == 4:
    computerChoice = 'scissors'
if userInput == computerChoice:
    print("DRAW!")
elif userInput == 'rock' and computerChoice == 'paper':
    print("COMPUTER WINS!")
elif userInput == 'rock' and computerChoice == 'scissors':
    print('USER WINS!')
elif userInput == 'paper' and computerChoice == 'rock':
    print("USER WINS!")
elif userInput == 'paper' and computerChoice == 'scissors':
    print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'rock':
    print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'paper':
    print("USER WINS!")
print("Would you like to try again?")
try_again = input("Y/N  ")
try_again = try_again.lower()
if try_again == "y":
    print("\n")
    rps()
else:
    print("\n")
    print("Thank you for using my Rock, Paper, Scissors Program")

rps()


texts:
I have a jQuery script and I should explain it line by line.  I already do that and I want to make sure that is correct.  If someone has any remarks, I will be very appreciative.

//Here we use the jQuery selector ($) to select the servers_id which is located into
//the delivers_id and we attaches a function to run when a change event occurs
$("#delivers #servers").change(function () {

    //Here we look if the servers_id value was changed and the value is different of 0

    if ($(this).val() != '0') {

        //Here we create a new variable sid and we stored the servers_id value in it
        var sid = $("#delivers #servers").val();

        //Here we use the Ajax $.get to get the sid value and send it by Ajax request then
        //we set the data into the o_vmats_id html and empty the vmtas_id
        $.get("/deliverability/get_vmtas/" + sid,
            function (data) {
                $('#o_vmtas').html(data);
                $('#vmtas').html('');
            });
    } else {
        //Here the else statement, we select the vmtas_id and set the html content like in the code (value=0)
        //and empty the o_vmtas_id html content
        $('#vmtas').html('<option value="0">All Classes</option>');

        $('#o_vmtas').html('');
    }
});


texts: File(s) encrypter implementation in python

texts:
I'm looking for any feedback in order to improve code styling, performance etc.
Also I want to make sure that the way I've implemented AES here is actually secure

import os
import hashlib
import sys
import base64

from cryptography.fernet import Fernet

class Cryptor:
    def __init__(self, password):
        self.__password = password

    def operate(self, file_):
        if file_.endswith("enc"):
            self.decrypt(file_)
        else:
            self.encrypt(file_)

    def decrypt(self, file_):
        file_name = "".join(file_.split(".")[:-1])

        with open(file_, "rb") as file_:
            save1 = file_.readline()
            save2 = file_.readline()
            save3 = file_.readline()
            salt = save3
            key = base64.urlsafe_b64encode(hashlib.pbkdf2_hmac("sha256", bytes(self.__password, encoding="utf-8"), salt, 100000, dklen=32))
            f = Fernet(key)
            decrypted = f.decrypt(save1)
            file_extention = f.decrypt(save2)
            save = decrypted

        with open(file_name + file_extention.decode(encoding="utf-8"), "wb") as file_:
            file_.write(save)

        os.remove(file_name + ".enc")

    def encrypt(self, file_):
        salt = os.urandom(64)
        key = base64.urlsafe_b64encode(hashlib.pbkdf2_hmac("sha256", bytes(self.__password, encoding="utf-8"), salt, 100000, dklen=32))
        f = Fernet(key)

        file_name = "".join(file_.split(".")[:-1])
        file_extention = "." + file_.split(".")[-1]

        with open(file_, "rb") as file_:
            file__ = file_.read()
            encrypted = f.encrypt(bytes(file__))
            save1 = encrypted
            save2 = f.encrypt(bytes(file_extention, encoding="utf-8"))
            save3 = salt

        with open(file_name + ".enc", "wb") as file_:
            file_.write(save1)
            file_.write(b"\n")
            file_.write(save2)
            file_.write(b"\n")
            file_.write(save3)

        os.remove(file_name + file_extention)

def main():
    password = sys.argv[1]
    files = sys.argv[2:]
    crypt = Cryptor(password)

    for file_ in files:
        crypt.operate(file_)

if __name__ == "__main__":
    main()


texts: Skiena's Programming Challenge [UVa ID 10137]- Getting WA

texts:
Question from Skiena's Programming Challenges.
Getting WA (wrong answer) in Online Judge even though it's working for sample test cases. Can somebody find a case where it fails?

I tried the tricky case from this link and it gave the right answer-

"The Trip" challenge from Programming Challenges

Input

Standard input will contain the information for several trips. Each trip consists of a
line containing a positive integer n denoting the number of students on the trip. This is
followed by n lines of input, each containing the amount spent by a student in dollars
and cents. There are no more than 1000 students and no student spent more than
$10,000.00. A single line containing 0 follows the information for the last trip.

Output

For each trip, output a line stating the total amount of money, in dollars and cents,
that must be exchanged to equalize the students’ costs.

Sample Input
3
10.00
20.00
30.00
4
15.00
15.01
3.00
3.01
0

Sample Output
$10.00
$11.99

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

int main()
{   vector <float> nums;
    int numStudents,loopVar1,pos;
    float amount,sum=0,roundAmt,ans;
    string strAns;
    stringstream ss;
    while(cin>>numStudents) {
        if(numStudents==0)
            break;
        ans=sum=0;
        nums.erase(nums.begin(),nums.end());
        for(loopVar1=0;loopVar1<numStudents;loopVar1++) {
            cin>>amount;
            nums.push_back(amount);
            sum+=amount;
        }
        sum/=numStudents;
        roundAmt=(int)(sum*100);
        roundAmt/=100.0f;
        //cout<<roundAmt<<"\n";
        for(loopVar1=0;loopVar1<numStudents;loopVar1++)
            if(nums[loopVar1]<roundAmt)
                ans+=(roundAmt-nums[loopVar1]);
        strAns="";
        ss.str("");
        ss<<ans;
        strAns=ss.str();
        pos=strAns.find('.');
        if(pos==-1)
            strAns+=".00";
        else
            strAns.erase(pos+3);
        cout<<'$'<<strAns<<"\n";
    }
    return 0;
}


texts: C program to find and replace a word in a file

texts:
This program will perform a find and replace on a single word in a file, with the condition that the new word must have the same length as the old one. It will also display the number of occurrences of the old word.

I'm not interested in anything type of feedback, anything would be appreciated, it's a school assignment and it'll be reviewed by my teacher.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_SIZE 24

void write_to_file(const char *s);
void replace_word(const char *s, const char *old_word, const char *new_word);

int main(void){
    const char file_name[] = "text.txt";
    int c;
    char old_word[WORD_SIZE];
    char new_word[WORD_SIZE];
    puts("Enter 'w' to write to the file, 'r' to replace a word");
    while((c = getchar()) != EOF){
        switch(c){
        case 'w':
            getchar();
            write_to_file(file_name);
            break;
        case 'r':
            getchar();
            puts("Enter the word you want to replace");
            fgets(old_word, sizeof(old_word), stdin);
            old_word[strlen(old_word) - 1] = '\0';
            puts("Enter the new word");
            fgets(new_word, sizeof(new_word), stdin);
            new_word[strlen(new_word) - 1]  = '\0';

            if(strlen(old_word) != strlen(new_word)){
                printf("Error: can't replace \"%s\" with \"%s\":\n\"%s\" the length is not the same", old_word, new_word, new_word);
                break;
            }
            replace_word(file_name, old_word, new_word);
            break;
        default:
            printf("Invalid command:%i\n", c);
            break;
        }
    }
    return 0;
}

void write_to_file(const char *s){
    FILE *in_file;
    if((in_file = fopen(s, "w")) == NULL){
        perror(s);
        exit(EXIT_FAILURE);
    }
    int c;
    while((c = getchar()) != EOF){
        fputc(c, in_file);
    }
    fclose(in_file);
}

unsigned long fsize(const char *s){
    FILE *f;
    if((f = fopen(s, "r")) == NULL){
        perror(s);
        exit(EXIT_FAILURE);
    }
    fseek(f, 0, SEEK_END);
    unsigned long len = ftell(f);
    fclose(f);
    return len;
}

void replace_word(const char *s, const char *old_word, const char *new_word){
    FILE *original_file;
    FILE *copy;

    if((original_file = fopen(s, "r")) == NULL){
        perror(s);
        exit(EXIT_FAILURE);
    }

    if((copy = fopen("copy.txt", "w")) == NULL){
        perror("text");
        exit(EXIT_FAILURE);
    }

    const int BUFFER_SIZE = fsize(s);
    char *buffer = malloc(BUFFER_SIZE);
    char *init_loc = buffer;

    int word_len = strlen(old_word);
    int word_frequency = 0;

    while(fgets(buffer, BUFFER_SIZE, original_file)){
        while((buffer = strstr(buffer, old_word))){
            memcpy(buffer, new_word, word_len);
            word_frequency++;
        }
        buffer = init_loc;
        fprintf(copy, "%s", buffer);
    }
    printf("'%s' found %i times\n", old_word, word_frequency);

    fclose(original_file);
    fclose(copy);

    if((original_file = fopen(s, "w")) == NULL){
        perror(s);
        exit(EXIT_FAILURE);
    }

    if((copy = fopen("copy.txt", "r")) == NULL){
        perror("text");
        exit(EXIT_FAILURE);
    }

    int c;
    while((c = fgetc(copy)) != EOF){
        fputc(c, original_file);
    }

    fclose(original_file);
    fclose(copy);
    free(buffer);
}


texts: Save list over many csv files each with given number of lines

texts:
I wrote a little code for outputting to csv. It takes a list object named outtext and saves multiple .csv files. Each csv file contains cutoff elements of the list (except for the last), where cutoff is a specified number of elements/lines. This is useful when the user has to avoid writing to too large files (i.e. GitHub restricts file sizes too 100MB). The filenames are numbered from 0 to n, where n is the length of the output object divided by cutoff.

However, the code looks quite clunky and is quite long, given that it performs a relatively simple task:

import csv
import math

# dummy content
outtext = mylist = [None] * 300000

# Parameters specified by user
output_file = "path/name.csv"
cutoff = 150000

output_file_tokens = output_file.rsplit('.', 1)
num_files = int(math.ceil(len(outtext)/float(cutoff)))

for filenumber in range(num_files):
    counter = 0
    output_file = output_file_tokens[0] + str(filenumber) + "." + output_file_tokens[1]
    while counter <= cutoff:
        with open(output_file, 'wb') as f:
            writer = csv.writer(f)
            for line in outtext[:cutoff]:
                writer.writerow(line)
                counter += 1
    del outtext[:cutoff]
    print ">>> " + output_file + " successfully saved"

Is there room for improvement?


texts: RSA algorithm implementation in Python 3

texts:
First, a reminder of the RSA algorithm and what my program implements:

Take two distinct, large primes p and q

Ideally these have a similar byte-length

Multiply p and q and store the result in n
Find the totient for n using the formula $$\varphi(n)=(p-1)(q-1)$$
Take an e coprime that is greater, than 1 and less than n
Find d using the formula $$d\cdot e\equiv1\mod\varphi(n)$$

At this point, the pair (e, n) is the public key and the private key (d, n) is the private key.

Conception:

Implement the RSA algorithm
Ask the user for necessary data (primes, coprime greater than 1 and less than n, string)
Encrypt and decrypt the given string by the user using the RSA algorithm

What do you think about my Python 3 implementation of the RSA algorithm? What's the performance of this program?

try:
   input = raw_input
except NameError:
   pass
try:
   chr = unichr
except NameError:
   pass
p=int(input('Enter prime p: '))
q=int(input('Enter prime q: '))
print("Choosen primes:\np=" + str(p) + ", q=" + str(q) + "\n")
n=p*q
print("n = p * q = " + str(n) + "\n")
phi=(p-1)*(q-1)
print("Euler's function (totient) [phi(n)]: " + str(phi) + "\n")
def gcd(a, b):
    while b != 0:
        c = a % b
        a = b
        b = c
    return a
def modinv(a, m):
    for x in range(1, m):
        if (a * x) % m == 1:
            return x
    return None
def coprimes(a):
    l = []
    for x in range(2, a):
        if gcd(a, x) == 1 and modinv(x,phi) != None:
            l.append(x)
    for x in l:
        if x == modinv(x,phi):
            l.remove(x)
    return l
print("Choose an e from a below coprimes array:\n")
print(str(coprimes(phi)) + "\n")
e=int(input())
d=modinv(e,phi)
print("\nYour public key is a pair of numbers (e=" + str(e) + ", n=" + str(n) + ").\n")
print("Your private key is a pair of numbers (d=" + str(d) + ", n=" + str(n) + ").\n")
def encrypt_block(m):
    c = modinv(m**e, n)
    if c == None: print('No modular multiplicative inverse for block ' + str(m) + '.')
    return c
def decrypt_block(c):
    m = modinv(c**d, n)
    if m == None: print('No modular multiplicative inverse for block ' + str(c) + '.')
    return m
def encrypt_string(s):
    return ''.join([chr(encrypt_block(ord(x))) for x in list(s)])
def decrypt_string(s):
    return ''.join([chr(decrypt_block(ord(x))) for x in list(s)])
s = input("Enter a message to encrypt: ")
print("\nPlain message: " + s + "\n")
enc = encrypt_string(s)
print("Encrypted message: " + enc + "\n")
dec = decrypt_string(enc)
print("Decrypted message: " + dec + "\n")


texts: CSS Good Practice on a JavaScript Plugin

texts:
I've realized a jQuery Plugin recently and made a basic default CSS for it.

As I'm mainly a server-side guy, I'm not too familiar with CSS and would like to have insight about what could be improved.

The main issues I've targeted are :

Are the CSS selectors appropriate, knowing that this CSS is meant to be on a plugin and to be side-effect-less as much as possible.
Are the property usages appropriate or are there better way of using some of the properties I have used.

Any suggestion of code style is also highly appreciated!

Here is a working fiddle

Here is the css :

div.paginateContainer {
    display : block;
    text-align: center;
}

div.paginateContainer > ul.paginateList{
    display: inline-block;
}

div.paginateContainer > ul > li{
    display: inherit;
}

div.paginateContainer > ul > li > a.paginateAnchor{
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    text-decoration: none;
    cursor: pointer;

    line-height: 20px;
    padding: 4px 12px;
    background-color: #ddd;
    color: #08c;
    font-size : 16px;
    min-width: 16px;
    float: left;

    border-top: 1px solid #ccc;
    border-bottom: 1px solid #ccc;

    /* Select None */
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

div.paginateContainer > ul > li > a.paginateAnchor:hover {
    color : #fff;
    background-color: #2ae;
    border-top: 1px solid #2ae;
    border-bottom: 1px solid #2ae;
}

div.paginateContainer > ul:first-child > li.paginatePrevious > a{
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
    border: 1px solid #ccc;
    font-size : 18px;
    font-weight: bold;
}

div.paginateContainer > ul:first-child > li.paginatePrevious > a:hover {
    border: 1px solid #2ae;
}

div.paginateContainer > ul:first-child > li.paginateNext > a {
    border-top-right-radius: 10px;
    border-bottom-right-radius: 10px;
    border: 1px solid #ccc;
    font-size : 18px;
    font-weight: bold;
}

div.paginateContainer > ul:first-child > li.paginateNext > a:hover {
    border: 1px solid #2ae;
}

div.paginateContainer > ul:last-child > li > a {
    border-radius: 10px;
    font-size: 18px;
    font-weight: bold;
}

div.paginateContainer ul.paginateList:last-child {
    float: right;
}

div.paginateContainer > ul > li.paginateActive > a,
div.paginateContainer > ul > li.paginateActive > a:hover {
    color : #fff;
    cursor: default;
    background-color: #08c;
    border-top: 1px solid #08c;
    border-bottom: 1px solid #08c;
}

div.paginateContainer > ul:first-child > li.paginateDisabled > a,
div.paginateContainer > ul:first-child > li.paginateDisabled > a:hover {
    color : #bbb;
    background-color: #eee;
    cursor: default;
    border: 1px solid #ddd;
}

Note that I've posted a question to review the JavaScript also, so this post is only about CSS. The JavaScript having no real dependency with the CSS in this case.


texts: Core Location - Practices for Supporting Common iOS Devices

texts:
Typical tutorials suggest simple CoreLocation code similar to the following:

Header

#import<CoreLocation/CoreLocation.h>
@interface MyCLController : NSObject <CLLocationManagerDelegate> {
    CLLocationManager *locManager;
}
@property (nonatomic, retain) CLLocationManager *locManager;
@end

Setup

....
   self.locManager = [[[CLLocationManager alloc] init] autorelease];
   if(!self.locManager.locationServicesEnabled)
   {
       NSLog(@"User has opted out of location services");
   }

   self.locManager.delegate = self;
   self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
   self.locManager.distanceFilter = 880.0f; // About 1/10th mile, in meters
   [self.locManager startUpdatingLocation];
....

Methods

- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
    // Respond to errors
    NSLog(@"Location manager error: %@", [error description]);
    return;
}

- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"%@\n", [newLocation description]);
}

Deallocate

....
   [self.locManager release]
....

The above code works, but what common problems should I expect once I start testing on the most common iOS devices and versions? (assuming target of iOS 3.2 and above, building on iOS 4.3 SDK, code should work on all iOS devices that support at least 3.2 and any devices that support above 3.2)

Many simple examples online are 1-2 years old - are there improvements to the above that should be made due to changes in CoreLocation and the new devices released since 3.2?

What other suggestions would make the above more robust, and are there any other pitfalls developers should be aware of as they develop for CoreLocation?


texts: Calculate number of co-occurrences for two vectors


texts:
Assume I have a cache:

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

trait Cache[K, V] {
  def put(key: K, value: V): Future[Unit]
  def get(key: K): Future[Option[V]]
  def remove(key: K): Future[Unit]

  def getOrElse(key: K)(ifNotFound: => V): Future[V] = {
    apply(key) {
      Future.successful(ifNotFound)
    }
  }

  def apply(key: K)(ifNotFoundFuture: => Future[V]): Future[V] = {
    get(key).flatMap { found =>
      found.map { x =>
        Future.successful(x)
      } getOrElse {
        ifNotFoundFuture.flatMap { value =>
          put(key, value).map { _ =>
            value
          }
        }
      }
    }
  }
}

I want to wrap an existing Akka Streams Flow from A to B with the cache (retrieving from Cache if it has the value, if not then invoking the flow, storing the value in cache, and returning that value).

I have currently done this, but I'm sure it can be done shorter, better or more idiomatic:

import akka.NotUsed
import akka.stream.scaladsl.{Flow, Source}

object CacheFlow {
  def apply[A, B](
    flow: Flow[A, B, NotUsed],
    cache: Cache[A, B]
  ): Flow[A, B, NotUsed] = {
    Flow[A]
      .flatMapConcat { a =>
        Source.fromFuture(cache.get(a))
          .map { x =>
            (a, x)
          }
      }
      .flatMapConcat { case (a, found) =>
        found match {
          case Some(x) => Source.single(x)
          case None    => Source.single(a).via(flow).flatMapConcat { x =>
            Source.fromFuture(cache.put(a, x)).map { _ => x }
          }
        }
      }
  }
}

Two tests follow. I also tried to write a more complex one going against a "real" in-memory Cache where I'd expect three flow invocations, but this was difficult due to race conditions.

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Sink, Source}
import org.scalatest.FlatSpec
import org.scalatest.Matchers._
import org.scalatest.concurrent.ScalaFutures.whenReady
import cats.syntax.option._
import scala.concurrent.Future

class CacheFlowSpec extends FlatSpec {
  implicit val actorSystem = ActorSystem()
  implicit val actorMaterializer = ActorMaterializer()

  val input = List("one", "two", "two", "three", "three", "three")

  val alwaysSuccessfulCache = new Cache[Foo, Bar] {
    override def put(key: Foo, value: Bar): Future[Unit] = Future.successful(())
    override def get(key: Foo): Future[Option[Bar]] = Future.successful(Bar(key.value).some)
    override def remove(key: Foo): Future[Unit] = ???
  }

  val alwaysMissingCache = new Cache[Foo, Bar] {
    override def put(key: Foo, value: Bar): Future[Unit] = Future.successful(())
    override def get(key: Foo): Future[Option[Bar]] = Future.successful(None)
    override def remove(key: Foo): Future[Unit] = ???
  }

  private def runTest(cache: Cache[Foo, Bar], expectedFlowInvocations: Int) = {
    var flowInvocations: Int = 0
    val flow = Flow[Foo]
      .map { x =>
        flowInvocations = flowInvocations + 1
        Bar(x.value)
      }

    val cacheFlow = CacheFlow(flow, cache)
    val output = Source(input)
      .map(Foo)
      .via(cacheFlow)
      .map(_.value)
      .runWith(Sink.seq)

    whenReady(output) { x =>
      x.toList shouldEqual input
      flowInvocations shouldEqual expectedFlowInvocations
    }
  }

  "CacheFlow" should "only use cache if it has data" in {
    runTest(alwaysSuccessfulCache, 0)
  }

  it should "always use flow if cache is empty" in {
    runTest(alwaysMissingCache, input.size)
  }
}


texts: Checking if a 3D point is outside of a trapezoid

texts:
I have recently written if a 3D point is within a specified trapezoid. It does it by checking 3 different planes of the trapezoid. I place the relevant 2 coordinates from the 3D point into the current plane being checked, this will form four triangles within the plane, if this area is greater than the area of the plane then the point is outside of the trapezoid.

Here is my code in question. (note I have to work with BigDecimal as the coordinates can be rather large).

    //points[0-3] -- A[0] B[1] C[2] D[3]    Nearplane
//points[4-7] -- A[4] B[5] C[6] D[7]    Farplane
private boolean compareAreas(Point3[] points,Point3 coOrd){
    //checking topview plane    (x,z)   {af,bf,bn,an}
    ArrayList<Point2> tempP = new ArrayList<Point2>();
    tempP.add(new Point2(points[4].x,points[4].z));
    tempP.add(new Point2(points[5].x,points[5].z));
    tempP.add(new Point2(points[1].x,points[1].z));
    tempP.add(new Point2(points[0].x,points[0].z));
    BigDecimal a=   getTrapezoidArea(tempP);
    BigDecimal b=   checkPlanesTri(tempP,cameraCoord);
    tempP.clear();
    if(!(a.equals(b)))return false;
    a=null;
    b=null;

    //checking frontView plane  (x,y)
    tempP.add(new Point2(points[0].x,points[0].y));
    tempP.add(new Point2(points[1].x,points[1].y));
    tempP.add(new Point2(points[2].x,points[2].y));
    tempP.add(new Point2(points[3].x,points[3].y));
    a=              getTrapezoidArea(tempP);
    b=              checkPlanesTri(tempP,cameraCoord);
    tempP.clear();
    if(!(a.equals(b)))return false;
    a=null;
    b=null;

    //checking sideView         (z,y)
    tempP.add(new Point2(points[1].z,points[1].y));
    tempP.add(new Point2(points[5].z,points[5].y));
    tempP.add(new Point2(points[6].z,points[6].y));
    tempP.add(new Point2(points[2].z,points[2].y));
    a=              getTrapezoidArea(tempP);
    b=              checkPlanesTri(tempP,cameraCoord);
    tempP.clear();
    if(!(a.equals(b)))return false;
    a=null;
    b=null;
    //Met all conditions
    return true;
}

private BigDecimal checkPlanesTri(ArrayList<Point2>points,Point2 coOrd){
    BigDecimal ax,bx;
    BigDecimal ay,by;
    BigDecimal result= BigDecimal.ZERO;
    BigDecimal temp;
    BigDecimal cx=BigDecimal.valueOf(coOrd.x);
    BigDecimal cy=BigDecimal.valueOf(coOrd.y);

    for(int i=0;i<4;i++){
        //Ax(By-Cy) + Bx(Cy-Ay) + Cx(Ay-By)/2.0     ,where A=((i)%4) reference to element
        //Check AB BC CD DA vs coOrd
        ax=BigDecimal.valueOf(points.get((i)%4).x);
        bx=BigDecimal.valueOf(points.get((i+1)%4).x);

        ay=BigDecimal.valueOf(points.get((i)%4).y);
        by=BigDecimal.valueOf(points.get((i+1)%4).y);

        temp =  getTriangleArea(ax,ay,bx,by,cx,cy);
        // result+=temp
        result = result.add(temp);
    }
    return result;
}
private BigDecimal getTrapezoidArea(ArrayList<Point2>points){
    BigDecimal ax = BigDecimal.valueOf(points.get(0).x);
    BigDecimal ay = BigDecimal.valueOf(points.get(0).y);
    BigDecimal bx = BigDecimal.valueOf(points.get(1).x);
    BigDecimal by = BigDecimal.valueOf(points.get(1).y);
    BigDecimal cx = BigDecimal.valueOf(points.get(2).x);
    BigDecimal cy = BigDecimal.valueOf(points.get(2).y);

    //Triangle between elements 0-2
    BigDecimal triangle1 = getTriangleArea(ax,ay,bx,by,cx,cy);

    //Triangle between elements 1-3
    //reusing variables
    ax  = BigDecimal.valueOf(points.get(3).x);
    ay  = BigDecimal.valueOf(points.get(3).y);
    BigDecimal triangle2 = getTriangleArea(bx,by,cx,cy,ax,ay);
    return triangle1.add(triangle2);
}
private BigDecimal getTriangleArea(BigDecimal ax,BigDecimal ay,BigDecimal bx,BigDecimal by,BigDecimal cx,BigDecimal cy){
    return ((ax.multiply(by.subtract(cy))).add(bx.multiply(cy.subtract(ay))).add(cx.multiply(ay.subtract(by)))).divide(BigDecimal.valueOf(2.0));
}


texts: Erlang: pmap with max number of processes

texts:
I'm working through Joe Armstrong's Programming Erlang 2nd E. The book has exercises at the end of each chapter. Chapter 26, Question 5 is:

  Write a function called pmap(F, L, Max) that computes the list [F(I) || I <- L] in parallel but is subject to the restriction that no more than Max parallel processes run simultaneously.

My solution is:

-module(pmap_cap).
-export([pmap/3]).

pmap(F, L, Max) ->
    S = self(),
    Ref = make_ref(),
    Pids = lists:map(fun(SubL) ->
                             spawn(fun() -> do_f(S, Ref, F, SubL) end)
                     end,
                     partition(L, min(length(L), Max))),
    gather(Pids, Ref).

partition(L, N) ->
    M = length(L),
    if
        M =< N -> lists:map(fun(X) -> [X] end, L);
        true -> partition(L, M div N, M rem N)
    end.

partition([], _Q, _R) -> [];
partition(L, Q, R) ->
    Extra = if R > 0 -> 1; true -> 0 end,
    [lists:sublist(L, Q + Extra)|
     partition(lists:sublist(L, Q + Extra + 1, length(L)), Q, R-1)].

do_f(Parent, Ref, F, SubL) ->
    Parent ! {self(), Ref, lists:map(fun(X) -> catch F(X) end, SubL)}.

gather([Pid|T], Ref) ->
    receive
        {Pid, Ref, Ret} ->
            lists:append(Ret, gather(T, Ref))
    end;
gather([], _) -> [].

What could be improved? Are there performance issues? Can the code be written more idiomatically?


texts: Short Java FizzBuzz using recursion and parameters

texts:
public void fizzbuzz(int count, int max, String fizzer) {
    fizzer += (count % 3 == 0) ? "fizz":"";
    fizzer += (count % 5 == 0) ? "buzz":"";
    fizzer += (count % 3 != 0 && count % 5 != 0) ? count:"";
    if (count != max) {
        fizzer += "\n";
        fizzbuzz(count+1,max,fizzer);
    } else {
        System.out.println(fizzer);
    }
}

fizzbuzz(1,30,"");

The code is performing fizzbuzz over the range count to max. No variables are initialized within the method.

I'd love to get rid of max, and instead take only two arguments for the method (String fizzer and int count), but how can I? I can do it backwards (i.e. working down until reaching the trivial case count == 0 and then stop), but is there a way to go from 1 to n with only one argument?


texts: Switching between tabs inside of a web application

texts:
I'm making a web application for the administration of a restaurant kind of type. The purpose of this application is to make customers, and the orders of those customers, which has products in it, etc...

This application is written in PHP combined with jQuery.

I have many tabs, such as:

Displaying the orders
A screen to make a new order (same  div as displaying the list from the orders)
A screen to show you all products, which you can click on to put them inside of a orders.
A screen where more order information appears whenever clicking on it.

On this moment, I'm using this kind of snippets to manage this:

if (orderListScreen.css('visibility', 'hidden')) {
    orderListScreen.css("visibility", "visible");
    newOrderScreen.css("visibility", "hidden");
}

if (availableProductsScreen.css("visibility", "hidden")) {
    availableProductsScreen.css("visibility", "hidden");
    orderInformationScreen.css("visibility", "visible");
}

Note: This is one block of code.
Note: the orderListScreen and all the other variables refer to different div elements.

Problem

This is very confusing to work with.
This takes me more time to actually think which one is active and which one is not.

My own try

I've made a small function which also switches between the visibility of the elements, but I still don't like it; it makes it too confusing.

function switchTab(activate, deactivate) {
    var _activate = $(activate);
    var _deactivate = $(deactivate);

    if (_activate.css("visibility", "hidden")) {
        _activate.css("visibility", "visible");
        _deactivate.css("visibility", "hidden");
    }
}


texts: Better way to set number of threads used by NumPy

texts:
Background

When NumPy is linked against multithreaded implementations of BLAS (like MKL or OpenBLAS), the computationally intensive parts of a program run on multiple cores (sometimes all cores) automatically.

This is bad when:

you are sharing resources
you know of a better way to parallelize your program.

In these cases it is reasonable to restrict the number of threads used by MKL/OpenBLAS to 1, and parallelize your program manually.

My solution below involves loading the libraries at runtime and calling the corresponding C functions from Python.

Questions

Are there any best/better practices in solving this problem?
What are the pitfalls of my approach?
Please comment on code quality in general.

Example of use

import numpy

# this uses however many threads MKL/OpenBLAS uses
result = numpy.linalg.svd(matrix)

# this uses one thread
with single_threaded(numpy):
    result = numpy.linalg.svd(matrix)

Implementation

Imports and definitions

import subprocess
import re
import sys
import os
import glob
import warnings
import ctypes

MKL = 'mkl'
OPENBLAS = 'openblas'

Class BLAS, abstracting a BLAS library with methods to get and set the number of threads:

class BLAS:
    def __init__(self, cdll, kind):

        if kind not in (MKL, OPENBLAS):
            raise ValueError(f'kind must be {MKL} or {OPENBLAS}, got {kind} instead.')

        self.kind = kind
        self.cdll = cdll

        if kind == MKL:
            self.get_n_threads = cdll.MKL_Get_Max_Threads
            self.set_n_threads = cdll.MKL_Set_Num_Threads
        else:
            self.get_n_threads = cdll.openblas_get_num_threads
            self.set_n_threads = cdll.openblas_set_num_threads

Function get_blas, returning a BLAS object given an imported NumPy module.

def get_blas(numpy_module):

    LDD = 'ldd'
    LDD_PATTERN = r'^\t(?P<lib>.*{}.*) => (?P<path>.*) \(0x.*$'

    NUMPY_PATH = os.path.join(numpy_module.__path__[0], 'core')
    MULTIARRAY_PATH = glob.glob(os.path.join(NUMPY_PATH, 'multiarray.*so'))[0]

    ldd_result = subprocess.run(
        args=[LDD, MULTIARRAY_PATH],
        check=True,
        stdout=subprocess.PIPE,
        universal_newlines=True
    )

    output = ldd_result.stdout

    if MKL in output:
        kind = MKL
    elif OPENBLAS in output:
        kind = OPENBLAS
    else:
        return None

    pattern = LDD_PATTERN.format(kind)
    match = re.search(pattern, output, flags=re.MULTILINE)

    if match:
        lib = ctypes.CDLL(match.groupdict()['path'])
        return BLAS(lib, kind)
    else:
        return None

Context manager single_threaded, that takes an imported NumPy module, sets number of threads to 1 on enter, resets to previous value on exit.

class single_threaded:
    def __init__(self, numpy_module):
        self.blas = get_blas(numpy_module)

    def __enter__(self):
        if self.blas is not None:
            self.old_n_threads = self.blas.get_n_threads()
            self.blas.set_n_threads(1)
        else:
            warnings.warn(
                'No MKL/OpenBLAS found, assuming NumPy is single-threaded.'
            )

    def __exit__(self, *args):
        if self.blas is not None:
            self.blas.set_n_threads(self.old_n_threads)
            if self.blas.get_n_threads() != self.old_n_threads:
                message = (
                    f'Failed to reset {self.blas.kind} '
                    f'to {self.old_n_threads} threads (previous value).'
                )
                raise RuntimeError(message)


texts:
I have the following code:

if (isMandatory)
{
    x.MandatoryServices.ForEach(y =>
    {
        if (!y.IsSelectedByUser)
        {
            containsRemovedSrvcs = true;
            return;
        }
    });
}
else
{
    x.OptionalServices.ForEach(y =>
    {
        if (!y.IsSelectedByUser)
        {
            containsRemovedSrvcs = true;
            return;
        }
    });
}

I would like to replace it with something more elegant like:

x.{isMandatory ? MandatoryServices : OptionalServices}.ForEach(y =>
{
    if (!y.IsSelectedByUser)
    {
        containsRemovedSrvcs = true;
        return;
    }
});

Of course, the compiler doesn't like that.  I have seen the GetType().GetProperty().GetValue() approach but I don't really know if that will work since my property is a List.  Does anyone know of any better solutions?


texts:
This code will check the database for an order number.  If none exist it creates one. If one does exist then it will increment it by one and update the database. Is this the most efficient way to handle this?

// Order Number check
let updateOrderNumber bizLocId =

    // order number record exist
    let numExist =
        query{
            for row in tool.db.Order_Order_OrderNumber do
            where(row.BusinessLocationId = bizLocId)
            count
        }

    // retrieve number
    if numExist < 1 then
        let firstOrder =
            dbSchema.ServiceTypes.Order_Order_OrderNumber(
                BusinessLocationId = bizLocId,
                OrderNumber = 1
            )
        // save to db
        tool.insertRowIn tool.db.Order_Order_OrderNumber firstOrder
        tool.saveToDb ()
        1
    else
        let numRecord =
            query{
                for row in tool.db.Order_Order_OrderNumber do
                where(row.BusinessLocationId = bizLocId)
                select row
                exactlyOneOrDefault
            }
        // update order number in db
        let newOrderNumber =
            numRecord.OrderNumber + 1
        numRecord.OrderNumber <- newOrderNumber
        tool.saveToDb ()

        newOrderNumber


texts: Using IServiceScopeFactory without implementing the Service Locator Pattern

texts:
I want to use IServiceScopeFactory in a way, which is not the Service Locator anti-pattern.

Therefore I thought about making a generic one, which supports explicitly only the given service.

I have made these interfaces:

public interface IServiceScopeFactory<T> where T : class
{
    IServiceScope<T> CreateScope();
}

public interface IServiceScope<T> : IDisposable where T : class
{
    T Service { get; }
}

And these implementations:

public class ServiceScopeFactory<T> : IServiceScopeFactory<T> where T:class
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public ServiceScopeFactory(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    public IServiceScope<T> CreateScope()
    {
        return new ServiceScope<T>(_serviceScopeFactory.CreateScope());
    }
}

public class ServiceScope<T> : IServiceScope<T> where T : class
{
    private readonly IServiceScope _scope;
    private T _service;

    public ServiceScope(IServiceScope scope)
    {
        _scope = scope;
    }

    public void Dispose()
    {
        _scope?.Dispose();
    }

    public T Service => _service ?? (_service = _scope.ServiceProvider.GetRequiredService<T>());
}

Usage is for example:

public class Foo
{
    private readonly IServiceScopeFactory<ConmaniaDbContext> _dbContextFactory;

    public Foo(IServiceScopeFactory<ConmaniaDbContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
    }

    public void Bar()
    {
        using (var scope = _dbContextFactory.CreateScope())
        {
            var dbContext = scope.Service
            //use service
        }
    }
}

For registering it, I have made these extension methods:

public static void AddServiceScopeFactory<T>(this IServiceCollection serviceCollection) where T : class
{
    serviceCollection.AddTransient<IServiceScopeFactory<T>, ServiceScopeFactory<T>>();
}

The registration is like that:

services.AddScoped<ConmaniaDbContext, ConmaniaDbContext>(); //Scoped Service
services.AddServiceScopeFactory<ConmaniaDbContext>();
services.AddSingleton<Foo, Foo>(); //Singleton Service

My base problem was that I need the Scoped Service DbContext in a Singleton service.

Is this a good way for dependency injection with a custom scope or is this just a wrapper around the Service Locator pattern? Is there anything you would improve? Or any obviously problems I might get with this implementation?

To clarify, this is where I am coming from:

public class Foo
{
    private readonly IServiceScopeFactory _scopeFactory;

    public Foo(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    public void Bar()
    {
        using (var scope = _scopeFactory.CreateScope())
        {
            var dbContext = scope.ServiceProvider.GetRequiredService<ConmaniaDbContext>()
            //use service
        }
    }
}

But this feels like the Service Locator Pattern, or am I wrong? The problem is here, that the class constructor doesn't know which dependencies the class needs.

The problem I am facing is that IServiceScopeFactory feels like the Service Locator Pattern. Therefore I created a IServiceScopeFactory<T>.

Since the whole Dependency Injection Pattern is relative new to me, I want to know if this is a suitable way of doing it, or some misconception.


texts: Efficiently determining if a number is prime

texts:
Is this the most efficient way to find if a number is prime? I can't think of a better way and it seems to run pretty quickly.

    public boolean primes(int num){
    for(int i = 2; i < num; i++){
        if(num % i == 0){
            System.out.println(num + " is not prime");
            return false;
        }
    }
    System.out.println(num + " is prime");
   return true;
}


texts: How can I improve the isolation for this controller spec?

texts:
So I'm doing things the BDD way, writing features first, then moving on to writing specs to add more detail to the mix as I move down the layers.

One thing that bothered me, but isn't a big problem, is that when I got to the controller part of the stack, I have calls to the User and Todo model in my controller spec.

Is this okay and normal? Or should I be stubbing these things out?

describe TodosController do
  let(:user) { Factory(:user) }

  describe "post 'create'" do
    lambda {
      post :create
    }.should change(user.todos, :count).by(1)
  end
end


texts:
I wrote this snippet:

template <typename ContainerT>
class ReverseIterator
{
public:
    ReverseIterator(ContainerT& iContainer) : m_container{iContainer}
    {

    }

    typename ContainerT::reverse_iterator begin()
    {
        return m_container.rbegin();
    }

    typename ContainerT::reverse_iterator end()
    {
        return m_container.rend();
    }

private:
    ContainerT& m_container;
};

template <typename ContainerT>
auto Reverse(ContainerT& iContainer)
{
    return ReverseIterator<ContainerT>(iContainer);
}

To be able to do something like this:

std::vector<int> myList{1, 2, 3};
for (auto& itr : Reverse(myList))
{
    ++itr;
}

First I'd like a feedback up to this point.

Then, I'd like to be able to write something like this:

for (auto itr : Reverse(std::vector<int>{1, 2, 3}))
{
    std::cout << itr << " ";
}

Without having a separate and near identical implementation of ConstReverse.

I thought about making everything with forwarding references but for some reason that didn't work out very well and I'm not exactly sure where I was mistaken. Could someone show me how it could be done?


texts: Building a string representing 50+ ActiveDirectory options

texts:
I have a switch statement used to handle options that a user selected (stored in an array). The array is iterated through, and for each element (enum object) in the array, an appropriate action is performed. However, the enum has over 50 items, so the switch statement is very long.

The items are all necessary and related, so they cannot be moved or removed. They also each call a method or get a property of an object, so no dictionaries. Are there any other options to make this shorter?

public string GetUserAttributes(UserPrincipal user,
    ActiveDirectoryUserAttribute[] attributes)
{
    var userAsDirectoryEntry
        = (DirectoryEntry)user.GetUnderlyingObject();
    var userAttributes = string.Empty;
    foreach (ActiveDirectoryUserAttribute attribute in attributes)
    {
        switch (attribute)
        {
            case ActiveDirectoryUserAttribute.AccountExpirationDate:
                userAttributes += AttributeToString(
                    user.AccountExpirationDate.ToString());
                break;
            case ActiveDirectoryUserAttribute.AccountLockoutTime:
                userAttributes += AttributeToString(
                    user.AccountLockoutTime.ToString());
                break;
            case ActiveDirectoryUserAttribute.Assistant:
                userAttributes += AttributeToString(
                    userAsDirectoryEntry.Properties[AttributeAssistant]
                    .Value.ToString());
                break;
            case ActiveDirectoryUserAttribute.BadLogonCount:
                userAttributes += AttributeToString(
                    user.BadLogonCount.ToString());
                break;
            ...
        }
    }
    return userAttributes;
}


texts: Looking for advice - Dependency Injection over Service Locator in Mef

texts:
I'm wondering what people think about Dependency Injection vs Service Locator patterns. Specifically I'm using Prism with MEF. I'm also using the MVVM pattern.

So I have a service which I export. I also have a class which doesn't export its class type as I don't need that to be registered with MEF. This class is actually a View-Model which is assigned to a hierarchical data template inside a TreeView.

However the view-model needs to import an interface registered with MEF.

Now I have three possible ways to do this:

Set an [Import] on the interface and use ComposeParts in the constructor to inject the dependency.
Use SerivceLocator.Current pattern to get the instance of the service.
Pass in the service interface on the constructor, which is kind of a manual dependency injection.

Here some example code to demonstrate.

public interface IFooService
{

}

[Export(typeof(IFooService))]
[PartCreationPolicy(CreationPolicy.Shared)]
class FooSevice : IFooService
{

}

Then the three possible implementation of the View-Model are:

public class TreeItemVM_MefInjection
{
    [Import]
    public IFooService FooService { get; set; }

    public TreeItemVM_MefInjection()
    {
        var catalog = new AssemblyCatalog
          (System.Reflection.Assembly.GetExecutingAssembly());

        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }
}

public class TreeItemVM_ServiceLocator
{
    [Import]
    public IFooService FooService { get; set; }

    public TreeItemVM_ServiceLocator()
    {
        FooService = ServiceLocator.Current.GetInstance<IFooService>();
    }
}

public class TreeItemVM_ManualInjection
{
    public IFooService FooService { get; set; }

    public TreeItemVM_ManualInjection(IFooService fooService)
    {
        FooService = fooService;
    }
}

Each of the tree-view items actually has an ObservableCollection as the tree is hierarchical. Each ViewModel can create it's own children, based on the model data it uses (this is not shown in the above examples just to keep them simple).

So my issues with each of these are:

It seems a lot of code to write to get automatic injection and I'm worried about the performance of creating a catalog and container temporarily. Is this OK to do it like this?
The service locator seems easier but I've read that the service locator is an anti-pattern. Should I be concerned with this?
The last one will give better performance as each instance just passes the IFooService interface on the constructor, and can pass it down to it's children when they are instantiated. However if I want to add more dependency injection latter on I need to change the constructor so maybe automatic injection or service locator maybe better.

So what would people say is the best method? Is there is a defined best practices method to follow? Are all the methods valid is it is up to the company coding standards to define the pattern to use?

Obviously the TreeItems are just normally instanced with new. I don't want these to be exported to MEF as that is overkill and nothing outside of the class library needs to know about them. They are just normal class that need to have MEF dependency injection or find MEF registered interfaces.

Anyone have an opinion on the most desirable solution and any gotchas I should be aware of? I'm sure there are other possible solutions to this as well. Any info would be appreciated.


texts:
I am working on an online ordering form and am looking for some advice about my jQuery.  I am re-developing the code base for this ordering form and improving what was created by a web design group years ago.  The existing form uses Javascript to dynamically generate a new line of item information when the starts typing in the form.  Reviewing the existing code there is close to 100 lines of JS (many being DOM manipulations) to add the HTML elements and so forth.  I could redo it in JS no problem, but I would like to reduce this amount of code and convert the solution to jQuery. It is already in use for other parts of the site so I may as well utilize it.

I've written a function to facilitate this that I am toying around with to get the functionality down.

function createNewRow() {
    //createNewRow.rc = 1;
    if(typeof createNewRow.rc == 'undefined') {
        createNewRow.rc = 1;
    }
    //Select the existing parent div
    var div = $('div#div');
    //Create a child div (container to the form elements)
    var cell = $('

');
    //Create "cells" (really divs) and form elements

    itemQty = $('

');
    itemQty.append('
Quantity
')
           .append('<input type="text" size="5" class="inputbox" name="ooItem[' + createNewRow.rc + '][qty]" id="' + createNewRow.rc + '" />');

    itemUnit = $('

');
    itemUnit.append('
UOM
');
    unitSlct = $('<select name="ooItem[' + createNewRow.rc + '][unit]"></select>');
    unitSlct.append('<option value="pc">PCS</option>')
            .append('<option value="sq">SQ</option>')
            .append('<option value="lf">LF</option>')
            .append('<option value="ea">EA</option>');
    itemUnit.append(unitSlct);

    itemDesc = $('

');
    itemDesc.append('
Description
')
            .append('<input type="text" class="inputbox" name="ooItem[' + createNewRow.rc +'][description]" />');

    itemColor = $('

');
    itemColor.append('
Color
')
             .append('<input type="text" class="inputbox" name="ooItem[' + createNewRow.rc +'][color]" />');

    itemText = $('
');
    itemText.append('
Texture
');
    textSlct = $('<select class="inputbox" name="ooItem[' + createNewRow.rc +'][texture]"></select>');
    textSlct.append('<option value="rough">Rough</option>')
            .append('<option value="smooth">Smooth</option>');
    itemText.append(textSlct);

    cell.append(itemQty)
        .append(itemUnit)
        .append(itemDesc)
        .append(itemColor)
        .append(itemText);

    //Append child div to the parent div
    div.append(cell);
    //Increase the row count
    createNewRow.rc++;
}

JSFiddle is here: http://jsfiddle.net/McFRV/3/

From a functionality standoint this works fine.  HTML rows are created as I like (minus the presentation layer of course) and the form information passes to the webserver correctly with all the information in the right places.  What is bugging me a bit is how "dirty" this code appears to me.  It seems as if using jQuery to make all that HTML in a bunch of strings is uncanny. Is there a better way to create chunks of HTML other than how I am going about it, or am I simply stressing about nothing?


texts:
I am trying to clean up and make the following code more efficient -

https://gist.github.com/eWizardII/6757364

from PIL import Image
import numpy as np
from PIL import ImageChops
import subprocess
import math
import datetime
from PIL import ImageFont
from PIL import ImageDraw
from collections import deque

def image_entropy(prev, curr, smasumm, values):
    im1 = Image.open(prev)
    im2 = Image.open(curr)
    img = ImageChops.difference(im1, im2)

    w, h = img.size
    a = np.array(img.convert('RGB')).reshape((w * h, 3))
    h, e = np.histogramdd(a, bins=(16,) * 3, range=((0, 256),) * 3)
    prob = h / np.sum(h) # normalize
    prob = prob[prob > 0] # remove zeros
    comp = -np.sum(prob * np.log2(prob))
    framsd = SD(values, smasumm)
    information = 'ENT: ' + str('{0:.2f}'.format(comp)) + ' SMA: ' + str('{0:.2f}'.format(smasumm)) + ' LB: ' + str(
        '{0:.2f}'.format(smasumm - framsd)) + ' UB: ' + str('{0:.2f}'.format(smasumm + framsd))
    cimg = Image.open(curr)
    draw = ImageDraw.Draw(cimg)
    font = ImageFont.truetype("arial.ttf", 24)
    draw.text((0, 0), information, (0, 255, 0), font=font)
    cimg.save(curr)
    return comp

def SD(values, mean):
    size = len(values)
    sumsd = 0.0
    for n in range(0, size):
        sumsd += math.sqrt((values[n] - mean) ** 2)
    return math.sqrt((1.0 / (size - 1)) * (sumsd / size))

try:

    print "Initial Image ..."

    time = datetime.datetime.now()
    filename = "image_"
    subprocess.call(
        "raspistill -t 1000 -ex night -awb auto -w 720 -h 480 -o %s" % filename + '1.jpg',
        shell=True)
    prev = filename + '1.jpg'
    i = 1
    summ = smasumm = 0.0
    period = n = 10
    values = deque([0.0] * period)
    while True:
        time = datetime.datetime.now()
        filename = "image_" + str(i) + ".jpg"
        subprocess.call(
            "raspistill -t 1000 -ex night -awb auto -w 720 -h 480 -o %s" % filename,
            shell=True)

        i += 1
        curr = filename
        sma = image_entropy(prev, curr, smasumm, values)
        values.append(sma)
        summ += sma - values.popleft()
        smasumm = summ / n
        prev = curr
        print(datetime.datetime.now() - time)
except KeyboardInterrupt:
    print "  Quit"

I believe my biggest bottleneck is in using the subprocess.call in Python but I don't know of any way to improve up such a call - in the long run when I know the program works properly I'll try and transition to Java/C; but this is easier for my immediate application and debugging. Any help or advice would be appreciated thanks in addition to any improvements in the other aspects of the code.