texts: Automatically push git submodule's parents recursively

texts:
I'm absolutely terrible with .bat files, but sometimes they are just needed. Right now I'm working on a project with quite some submodules, which have quite some submodules, and sometimes even those have submodules. Now, being a lazy programmer I figured I'd automate the task of committing the submodule-update in every single parent, and then having to push those parents manually. So I created this script:

@echo off
for /f "delims=" %%i in ('git rev-parse --show-toplevel') do set toplevel=%%i
cd %toplevel%
for /f "delims=" %%i in ('basename %cd%') do set reponame=%%i
echo "Master repo is %cd%"
git remote | xargs -L1 git push --all
:intorepo
for %%* in (.) do set submodulename=%%~nx*
for %%* in (.) do set submoduledir=%cd%
cd ..
set result=false
for /f "delims=" %%i in ('git rev-parse --is-inside-work-tree') do set result=%%i
if %result%==true (
    echo "%cd% is a parent"
    echo "%submodulename% is the submodule"
    git reset
    git add %submodulename%
    git commit -m "%submodulename% has been updated, committing recursively"
    goto :intorepo
)
echo "No more parents"
cd "%submoduledir%"
for /f "delims=" %%i in ('git remote get-url origin') do set pushto=%%i
echo "Pushing top-most repository, and submodules on demand."
git remote | xargs -L1 git push --all --recurse-submodules=on-demand
echo "done"

Are there any improvements I could make?


texts: Asynchronous Stripe API and aiohttp parameters formatting

texts:
I'm testing the Stripe payment API. I couldn't find a Python wrapper that provides asynchronous requests so I'm writing one. My first goal was to implement the async equivalent of stripe.PaymentIntent.create.

I used aiohttp client for my tests. One implementation detail: the Stripe API can take HTTP requests containing tables and maps. They are respectively encoded as "table[]=1,2" and "map[a]=1&map[b]=2". The aiohttp client doesn't seem to have any rewriting tool for this kind of parameters. I could have passed parameters as key value pairs: params={"table[]": "1,2"} but it seemed a bit ugly to me. Instead I decided to have input parameters of the form params={"table": [1, 2]} and have them automatically translated to their string forms on the fly. The same goes for maps, and {"map": {a:1, b:2}} is automatically translated to "map[a]=1&map[b]=2".

Here is my current implementation:

import asynctools
from aiohttp_params import session_complex_params
from aiohttp import client_exceptions
import uuid

API_KEY = "" # Your Stripe API key
ROOT_URL = "https://api.stripe.com/v1/payment_intents"

class Stripe(asynctools.AbstractSessionContainer):
    def __init__(self):
        super().__init__(raise_for_status=True)

    async def session_hook(self, session):
        return session_complex_params(session)

    @asynctools.attach_session
    async def create_payment(self, session=None, **kwargs):
        params = {
            **kwargs,
            "payment_method_types": ["card"],
            "metadata": {
                "order_id": 6735,
            },
        }
        async with session.post(ROOT_URL, params=params, headers=stripe_header()) as response:
            return await response.json()

def stripe_header():
    return {
        "Idempotency-Key": str(uuid.uuid4()),
        "Authorization": f"Bearer {API_KEY}",
    }

async def main():
    async with Stripe() as stripe:
        try:
            x = await stripe.create_payment(amount="1000" , currency="eur", receipt_email="me@web.com")
            print(x)
        except client_exceptions.ClientResponseError as e:
            print("Error", e)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

The asynctools module simply allows to turn a class into an asynchronous aiohttp session manager (by inheriting asynctools.AbstractSessionContainer). Inside the class, the session can be retrieved by any method using the decorator @asynctools.attach_session.

It then allows to simply use Stripe as a :

async with Stripe() as stripe:
    pass # Unique aiohttp session used for all requests
# aiohttp session closed

Finally, the code from aiohttp_params is the following:

def session_complex_params(session):
    session.post = patch_params(session.post)
    return session

def patch_params(request_method):

    def decorated_request(*args, **kwargs):
        try:
            kwargs["params"] = format_params(kwargs["params"])
        except KeyError:
            pass
        return request_method(*args, **kwargs)

    return decorated_request

def format_params(params):
    return '&'.join(format_param(*item) for item in params.items())

def format_param(k, v):
    if isinstance(v, list):
        return format_list_param(k, v)
    if isinstance(v, dict):
        return format_dict_param(k, v)
    return format_simple_param(k, v)

def format_dict_param(key, dic):
    return '&'.join(f"{key}[{k}]={str(v)}" for k, v in dic.items())

def format_list_param(key, li):
    li = map(str, li)
    return f"{key}[]={','.join(li)}"

def format_simple_param(key, value):
    return f"{key}={value}"

Is there anything important missing, or any improvement you think I could add ? Note that I just discovered the Stripe API so there is a good chance I'm not using it properly either. Any comment is welcome.


texts: Maintaining a single collection subdivided by a value's property

texts:
I'm working on a networked game. In this game, the base entity is called an actor. An actor can either be replicated or local, with each instance having a "replicates" field that represents this.

When managing a scene, a collection of actor must be maintained. My problem is finding a suitable solution to this. Right now I store a collection of references to local actors, replicated actors and all actors. This means data is duplicated which results in code like this:

        for( int i = 0; i < actorsToRemove.Count; ++i )
        {
            if( actorsToRemove[i].Replicates )
            {
                replicatedActors.Remove( actorsToRemove[i].Id );
            }
            else
            {
                localActors.Remove( actorsToRemove[i] );
            }
            allActors.Remove( actorsToRemove[i] );
        }
        actorsToRemove.Clear();

Instead of just removing from a single collection.

I could have one single collection that holds all actors and use properties that return another collection. For example:

public List<Actor> ReplicatedActors
{
    get
    {
        // loop through all actors and return a new list that holds all replicating actors.
    }
}

But this seems like too much unnecessary copying.

What would be the best way to go about this?


texts:
A guy at the company I work for needed a small application that would combine multiple text files into one, larger text file.

I wrote a console application for this. it seems pretty efficient, but I was wondering if there would be an even more efficient way of doing this.

It has 2 important functions, one that gets the files from a folder, where string input is the folder location:

static string[] getFiles(string input)
{
    DirectoryInfo dinfo = new DirectoryInfo(@input);

    FileInfo[] files = dinfo.GetFiles("*.txt");
    List<string> list = new List<string>();

    foreach(FileInfo file in files)
    {
        list.Add(input + @"\" + file.Name);
    }

    string[] arr = list.ToArray();
    return arr;
}

And of course the function that combines the files together, its input are the name of the file (string newName) and an array with the names of the files found in the folder by getFiles() (string[] files):

static void writeDump(string newName, string[] files)
{
    if (!File.Exists(newName))
    {
        using (StreamWriter sw = File.CreateText(newName))
        {
            for (int i = 0; i < files.Length; i++)
            {
                using (StreamReader sr = File.OpenText(files[i]))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        sw.WriteLine(s);
                    }
                }
            }
        }
    } else
    {
        Console.Clear();
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("File already exists");
        start(); //start is called from the main function
    }
}

And because start(); might be confusing, I'll also add the main function here:

static void Main(string[] args)
{
    start();
}

How efficient is this and could it be more efficient?


texts: String cut by a separator with the separator in the respective list element in python

texts:
Python 3.6.5

Is there any better solution than this one? Particularly the last line. I don't like it.

import re
s = "my_separator first thing my_separator second thing"
data = re.split("(my_separator )", s)[1:]
data = [even+odd for i, odd in enumerate(data) for j, even in enumerate(data) if i%2==1 and j%2==0 and i==j+1]


texts:
Given a list of objects, return an iterator for such a list. Looking for code-review, optimizations and best practices. Verifying complexity to be O(n) where n is sum of all objects, including elements of collections if contained. previously solved here.

public class FlattenIterator implements Iterator<Object> {

    private final Stack<Iterator<?>> iteratorStack;
    private Object next;

    public FlattenIterator(Iterable<?> list) {
        if (list == null) {
            throw new NullPointerException();
        }

        iteratorStack = new Stack<Iterator<?>>();
        iteratorStack.push(list.iterator());
    }

    private void moveToNext() {
       while ((next == null) && !iteratorStack.empty()) {
            Iterator<?> itr = iteratorStack.peek();

            // if iterator is empty, then pop it from stack.
            if (!itr.hasNext()) {
                iteratorStack.pop();
            } else {
                final Object next = itr.next();
                if (next instanceof Iterable) {
                    iteratorStack.push(((Iterable<?>) next).iterator());
                    moveToNext();
                } else {
                    this.next = next;
                }
            }
        }
    }

    /**
     * Returns if there are any objects left to iterate over. This method
     * can change the internal state of the object when it is called, but repeated
     * calls to it will not have any additional side effects.
     */
    public boolean hasNext() {
        moveToNext();
        return next != null;
    }

    /**
     * Returns the next element in our iteration, throwing a NoSuchElementException
     * if none is found.
     */
    public Object next() {
        moveToNext();
        if (next == null) {
            throw new NoSuchElementException();
        }

        Object objectToReturn = next;
        next = null;
        return objectToReturn;
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}

public class FlattenIteratorTest {

    @Test
    public void testIterator() {
        /**
         *  < <1, 2>, <"abc", "xyz">  <<1, 2>, <"abc", "xyz">> , a, 10 >
         */
        List<Object> genericList = new ArrayList<Object>();

        // integer list
        List<Integer> listInteger = new ArrayList<Integer>(Arrays.asList(1, 2));

        // string list
        List<String> listString = new ArrayList<String>(Arrays.asList("abc", "xyz"));

        // nested lists.
        List<Object> nestedList = new ArrayList<Object>();
        nestedList.add(listInteger);
        nestedList.add(listString);

        genericList.add(listInteger);
        genericList.add(listString);
        genericList.add(nestedList);
        genericList.add('a');
        genericList.add(10);

        /**
         * A very simple test case.
         */
        FlattenIterator fi = new FlattenIterator(genericList);
        final List<Object> listExpected = new ArrayList<>(Arrays.asList(1, 2, "abc", "xyz", 1, 2, "abc", "xyz", 'a', 10));
        final List<Object> listActual = new ArrayList<>();
        while (fi.hasNext()) {
           listActual.add(fi.next());
        }
        assertTrue(listExpected.equals(listActual));
    }

    @Test
    public void testEmpty() {
        List<Integer> list = new ArrayList<>();
        list.addAll(list);
        FlattenIterator fi = new FlattenIterator(list);
        assertFalse(fi.hasNext());
    }

}


texts: Change filename of Excel-files based on the content of a cell

texts:
I have hundreds of Excel-sheets looking something like this:

 I can't use the actual sheet, and not the exact document numbers, since they are confidential.

The name of the files are something like

2301 Item 1.xlsx
2014 Item 2.xlsx
5321 Item 3.xlsx
3212 Item 200.xlsx

I want to change the names of these files, based on the document name that's given in cell C5 in each Excel-sheet. Note: the cells C5 - E5 are merged.

I've written the following Python 3 script:

import os
import xlrd

def rename_excel_files():

    path = r"C:\Users\Stewie\Documents\excel_folder\\"

    for filename in os.listdir(path):

        excel_file = xlrd.open_workbook(path + filename)
        work_sheet = excel_file.sheet_by_index(0)
        new_filename = work_sheet.cell_value(4,2)
        os.rename(path + '\\' + filename, path + new_filename + '.xlsx')

rename_excel_files()

It works perfectly fine... But I guess it's not perfect..?

Any tips?

Note, this finishes almost instantly, so I don't really want to improve the execution time if that results in code that's harder to read, write and understand.

Also note: It's always cell C5. I don't need the cell-number to be dynamic. This is a fixed template that's used on literally thousands of files. I will only use it on the files on that template.


texts: Making an efficient and healthy db call for a real-time browser game

texts:
I'm doing a calculation for a real-time browser game, where users can invest some of their balances to the site. I need to update their invest's based on AN_AMOUNT_FROM_SITE and their percentage of shares (see PROFIT line). This function needs to run every 20-100 ms because AN_AMOUNT_FROM_SITE is coming consistently.

When this process finish, I'm saving a few unimportant data in callback().

When FUNDS collection has a few hundred document, this process will be very slow. Are there any ways I can reduce this process with Mongo to make it more efficient?

FUNDS.aggregate().group({ //get sum of invested amounts
        _id: '$id1',
        invest_total: { $sum: '$invest_amount'}}).exec(function ( e1, d ) {
             if( !e1 && d ){
                FUNDS.find().exec(function( e2, invests ){ //find all invests
                    if ( !e2 && invests ){
                      //calculate PROFIT value to each invest according to their rates (it can be +/-)
                        for (var i = 0; i < invests.length; i++) {

                        var invest_amount = invests[i].invest_amount,
                            invest_id     = invests[i].invest_id,
                            PROFIT        = AN_AMOUNT_FROM_SITE * invest_amount / d[0].invest_total; //
                            //update each invest
                            FUNDS.findOneAndUpdate({ 'invest_id': invest_id }, { $inc: { 'invest_profit': profit } }, function(e3) {
                                callback()
                            });
                    };
                }

                })
             }
})


texts:
I need to monitor my functions for "errors" and want to print the warnings at the end of the functions. I thought using singleton class could be a good idea in here (code inspired by this example):

class Warning
{
  bool status;
  std::string message;
  static Warning *global_warning_ptr;
  Warning() {
    defaults();
  }
public:
  void defaults() {
    message = "no warnings";
    status = false;
  }
  void set(std::string v) {
    message = v;
    status = true;
  }
  void print() {
    if (status) {
      std::cout << message std::endl;
      defaults();
    }
  }
  static Warning *msg() {
    if (!global_warning_ptr)
      global_warning_ptr = new Warning;
    return global_warning_ptr;
  }
};

Warning *Warning::global_warning_ptr;

that is used by multiple functions as below

void bar(double x) {
  if (x < 0)
    Warning::msg()->set("Wrong values");
}

void foo(std::vector x) {
  int n = x.size();

  for (int i = 0; i < n; i++) {
    bar(x[i]);
  }

  Warning::msg()->print(); // print single warning if any error occures
}

However using singletons is often considered as a bad coding practice. Is there any better alternative or place for improvment in my code? Is there anything I should worry about when using it?


texts: Project Euler problem 19 - How many Sundays fell on the first

texts:
Here's the problem:

  How many Sundays fell on the first of the month during the twentieth
  century (1 Jan 1901 to 31 Dec 2000)?

And here's my code:

#include <stdio.h>

int main(void){
    int months[12] = { 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 };
    int year=1901;
    int dayoftheweek=2;  //put a 2 because the 1 jan 1901 is tuesday. 0-sunday 6-Saturday
    int sunday=0;
    int firstsundays=0;

    while(year<=2000){
        if(year%4==0)    //checking if it's a leap year
            months[1]=29;

        for (int i = 0; i < 12; ++i) {
            for (int d = 1; d <= months[i]; d++){
                if(dayoftheweek==7)  //reset the week
                    dayoftheweek=0;

                if(dayoftheweek==sunday && d==1)
                    firstsundays++;

                dayoftheweek++;
            }
        }

        months[1]=28;
        year++;
    }

    printf("There are %d Sundays that fell on the first of the month\n", firstsundays);

    return 0;
}

What could I improve?


texts: Elegantly exclude part of an operation for the last iteration in a loop

texts:
I'm afraid just about everybody who read this question has misunderstood it. I'm not trying to find the best way of printing a vector. I'm trying to find the best way of excluding part of an operation from the last iteration in a loop. I'm seeking advice about a pattern that is repeated is many different contexts. For this reason, I cannot provide a concrete example.

This question is off-topic

A well-formed comma-separated list has commas after all but the last element. This means that when dealing with these lists, the comma has to be dealt with on all but the last iteration. This is how I do things currently:

for (auto e = vec.cbegin(); e != vec.cend(); ++e) {
  // code that has to be executed for every element
  std::cout << *e;
  if (e != vec.cend() - 1) {
    // code that must not be executed for the last element
    std::cout << ", ";
  }
}

There are five instances of the above pattern in the project that I'm working on. I feel like there might be a more elegant way of doing this. An alternative that I've come up with is this:

// infinite loop if vec is empty
if (!vec.empty()) {
  for (auto e = vec.cbegin(); e != vec.cend() - 1; ++e) {
    // code that has to be executed for every element
    std::cout << *e;
    // code that must not be executed for the last element
    std::cout << ", ";
  }
  // code that has to be executed for every element
  std::cout << vec.back();
}

This alternative is slightly faster because there isn't an if in the body but that's not a big deal. The if is true for all but the last iteration so the branch predictor will probably only miss on the last iteration. I also have to repeat code that has to be executed for every element which means that I need to hoist that into a function.

The first snippet is the best that I can come up with but I feel like this could be done better. Note that writing to std::cout is just an example.


texts:
This program calculates up and downspeed of a given connection for as long as it is running.

#upspeed/downspeed indicator
#written by Chubak -> aurlito@riseup.net

import requests
import time
import os

def get_seconds(datetime):
    time = datetime.split(' ')[3].split(':')

    time_hours = int(time[0])
    time_minutes = int(time[1])
    time_seconds = int(time[2])

    return time_hours*360 + time_minutes*60 + time_seconds

def downspeed():
    url = "http://speedtest.ftp.otenet.gr/files/test100k.db"

    current_seconds = get_seconds(time.asctime())

    file = requests.get(url)
    headers = file.headers

    file_size = int(headers['Content-Length'])/1000

    dl_seconds = get_seconds(time.asctime())

    time_difference = dl_seconds - current_seconds

    return round(file_size / time_difference)

def upspeed():
    current_seconds = get_seconds(time.asctime())

    dummy_file = os.path.join(os.getenv('APPDATA'), 'dummy.txt')
    post_url = 'http://httpbin.org/post'
    with open(dummy_file, 'wb') as dummy:
        for i in range (1500):
            dummy.write(str.encode('This is a dummy text. Its sole propose is being uploaded to a server. '))

        dummy.close()

    files = {'file' : open(dummy_file, 'rb')}

    request = requests.post(post_url, data=files)

    headers = request.headers

    file_size = int(headers['Content-Length'])/1000

    dl_seconds = get_seconds(time.asctime())

    time_difference = dl_seconds - current_seconds

    return round(file_size / time_difference)

if __name__ == '__main__':
    while True:
        up = None
        down = None

        if up == None and down == None:
            up = upspeed()
            down = downspeed()

            print('At {0} your Downspeed is: {1}, and your Upspeed is: {2}'.format(time.asctime(), down, up))

            time.sleep(5)

            up = None
            down = None

I'd appreciate it if your dropped any hints about turning this into a desktop widget.


texts:
To improve my programming style, I have been writing solutions for popular code katas. I have written a partial solution for the Berlin Clock kata and have been trying to follow the SOLID Principles. Can anyone critique the code and suggest improvements?

public class BerlinClock {

    private static List<TimeUnit> timeUnits = new ArrayList<TimeUnit>();

    public static void main(String[] args) {

        timeUnits.add(new Second());
        timeUnits.add(new Hour());
        timeUnits.add(new Minute());

        System.out.println(getTime("13:17:01"));
    }

    public static String getTime(String time) {

        StringBuilder timeSB = new StringBuilder();
        String[] timeElements = time.split(":");

        int i=0;
        int j=2;

        for(TimeUnit timeUnit : timeUnits){

            for(String timeElement : timeElements){
                timeSB.append(timeUnits.get(i).getLamps(Integer.parseInt(timeElements[j]))).append("\n");
                i++;
                j--;
                break;
            }
        }

        return timeSB.toString();
    }
}

TimeUnit

public interface TimeUnit {

    public String getLamps(int unit);

}

Hour

public class Hour implements TimeUnit {

    private static final String ALL_LIGHTS_OFF = "OOOO";
    private static final String RED_LIGHT = "R";
    private static final int MULTIPLE_OF_FIVE = 5;

    @Override
    public String getLamps(int hrs) {

        return getLampsForHoursMultiplesOfFive(hrs) + "\n" + getLampsForSingleHours(hrs);
    }

    public String getLampsForHoursMultiplesOfFive(int hours) {

        StringBuilder lamps = new StringBuilder(ALL_LIGHTS_OFF);

        for (int i = 0; i < (hours / MULTIPLE_OF_FIVE); i++) {
            lamps.replace(i, i + 1, RED_LIGHT);
        }
        return lamps.toString();
    }

    public String getLampsForSingleHours(int hours) {

        StringBuilder lamps = new StringBuilder(ALL_LIGHTS_OFF);

        for (int i = 0; i < (hours % MULTIPLE_OF_FIVE); i++) {  //dont do calculaion ever loop, do outside loop
            lamps.replace(i, i + 1, RED_LIGHT);
        }
        return lamps.toString();
    }
}

Minute

public class Minute implements TimeUnit {

    private static final String RED_LIGHT = "R";
    private static final String YELLOW_LIGHT = "Y";
    private static final String ALL_FOUR_LIGHTS_OFF = "OOOO";
    private static final String ALL_ELEVEN_LIGHTS_OFF = "OOOOOOOOOOO";

    @Override
    public String getLamps(int minutes) {

        int minutesDividedBy5 = minutes / 5;
        int minutesModulus5 = minutes % 5;

        return getLampsForMinutesMultiplesOfFive(minutesDividedBy5) + "\n" + getLampsForSingleMinutes(minutesModulus5);
    }

    private String getLampsForMinutesMultiplesOfFive(int minutes) {

        StringBuilder lamps = new StringBuilder(ALL_ELEVEN_LIGHTS_OFF);

        for (int i = 0; i < minutes; i++) {
            if (0 == (i + 1) % 3) {
                lamps.replace(i, i + 1, RED_LIGHT);
            } else {
                lamps.replace(i, i + 1, YELLOW_LIGHT);
            }
        }
        return lamps.toString();
    }

    private String getLampsForSingleMinutes(int minutes) {

        StringBuilder lamps = new StringBuilder(ALL_FOUR_LIGHTS_OFF);

        for (int i = 0; i < minutes; i++) {
            lamps.replace(i, i + 1, YELLOW_LIGHT);
        }
        return lamps.toString();
    }
}

Second

public class Second implements TimeUnit {

    @Override
    public String getLamps(int seconds) {

        if (0 == seconds%2) {
            return "Y";
        }

        return "O";
    }
}


texts: Graph (adjacency list) for BFS and DFS in Golang

texts:
I am trying to implement a Graph data structure in Golang and choose to use adjacency list representation. When starting to implement adjacency list, I have an idea that if I use map instead of list. I think (not sure though) this is much much easier to implement and I can find element in \$O(1)\$ rather using \$O(n)\$. I hope anyone can help review my code and the correct way to do adjacency graph.

I try to make it general by declaring payload as a new Interface type which needs a Compare() method to use in BFS and DFS later on.

type Graph struct {
    nodes map[int]Node
}

type Node struct {
    payload  Interface
    adjNodes map[int]struct{}
}

func (g *Graph) addNode(key int, payload Interface) {
    if _, ok := g.nodes[key]; ok {
        return
    }
    g.nodes[key] = Node{payload: payload, adjNodes: make(map[int]struct{})}
}

func (g *Graph) addEdge(src, dst int) {
    // expand if no this node in graph
    if src < 0 || dst < 0 {
        panic("Node number can't be below 0")
    }
    // check if node exists
    if _, ok := g.nodes[src]; !ok {
        panic("No node " + string(src))
    }
    if _, ok := g.nodes[dst]; !ok {
        panic("No node " + string(dst))
    }
    // connect by adjacent list
    g.nodes[src].adjNodes[dst] = struct{}{}
    g.nodes[dst].adjNodes[src] = struct{}{}
}


texts: Possible Combinations m out n, sorted and without repetition

texts:
I wrote the following function to get all possible m-of-n combinations, sorted and without repetition. I am new to Go and I am wondering what are the possible enhancements I can make, in terms of performance and best practices.
Input is: m and an array of strings
Output is: an array all possible combinations concatenated in strings
package main
import (
    "fmt"
    "sort"
    "strings"
)

func main() {

    var m int64 = 3
    items := []string{"b", "a", "d", "e", "f", "c", "k", "h"}
    result := FindPossibleCombination(m, items)

    fmt.Println( result )
    fmt.Println( len(result) )
}

func FindPossibleCombination(m int64, items []string) []string {
    sort.Strings(items)

    return rec(m, items, 0)
}

func rec(m int64, items []string, start int) []string {
    var res []string
    n := len(items)

    // edge cases
    if
    int64(n) < m ||
    (m == 0 || n == 0) ||
    start < 0 ||
    m < 0 {
        return res
    }

    // Base case, recursion stops here
    if int64(n) == m {
        comb := strings.Join(items,"")
        return []string{comb}
    }

    for i := start; i < n; i++ {
        // copy items so I don't tamper with the original array
        tempArr := make([]string, len(items), cap(items))
        copy(tempArr, items)

        if  i == 0 {
            // i = 0: remove last item
            tempArr = tempArr[:n-1]
        } else {
            // i > 0: remove item at len(items) - i
            // when i increases move left to remove another item
            // until we arrive to m items and recursion stops
            copy(tempArr[n-1-i:], tempArr[n-i:])
            tempArr[n-1] = ""
            tempArr = tempArr[:len(tempArr)-1]
        }

            // call function again with new array and new start.
            // By specifying new start i, we freeze all items to the right of the
            // removed item to make sure no combination is repeated.
            res = append(res, rec(m, tempArr, i)...)
    }
    return res
}

Try it in playground:
https://play.golang.org/p/hJN8gatqzud


texts:
I've written a backup script to make a backup of the latest modified files in 12 hours. Basically, it searches two directories for modified files (statically coded) then the find command is used to find the related files. A log file is then created to keep a list of the files. Later on, they are used to form a list of files and these files are used for the backup by tar.

Let me know which parts could be developed so that I can improve on and learn new things.

#!/usr/bin/env python
''' backup script to make a backup of the files
    that are newer than 12 hours in the
    home directory
    see
    " man find "
    " man tar  "
    for more information on the dates and the specific options
    on how to set different specifications for the selections
    '''
import sys
import os
import time

if (len(sys.argv) != 2):
  # if argument count is different
  # than 2, then there is an error
  print "Error on usage -> binary <hours_count_back>"
  quit()
else:
  # convert to integer value
  hours_back = int(sys.argv[1])

message_start = "Operation is starting".center(50, '-')
message_end   = "Operation terminated with success".center(50,'-')
#
print message_start
# source directories to check for backup
source = [ '/home/utab/thesis', '/home/utab/Documents' ]
# find files newer than 24 hours
# change to the target directories
newer_files = []
#
log_file = "log.dat"
# cmd to find newer files
# than 24 hours
cmd_find = "find . -type f -a -mmin " + str(-hours_back*60) + " > " + log_file
for directory in source:
  # iterate over the directories
  # change to the directory first
  os.chdir(directory)
  # apply the command
  os.system(cmd_find);
  # files are found with respect to the current directory
  # change the "." to directory for correct backups
  c = 0
  # process log file
  files = []
  lines = []
  log_in = open(log_file,'r')
  # read lines without \n character
  while 1:
      l = log_in.readline()
      if not l:
        break
      # do not include the newline
      # -1 is for that
      lines.append(l[:-1])
  #
  for l in lines:
      l_dummy  = l.replace( '.', directory, 1 )
      files.append(l_dummy)
  # extend the list with newer files
  newer_files.extend(files)
#print newer_files
print newer_files
# date
today =  time.strftime('%Y%m%d')
# current time of the date
# possible to do different backups in different times of the day
now   = time.strftime('%H%M%S')
#
target_directory = "/home/utab/"
target = target_directory + today + "_" + now + \
         '.tgz'

# do the actual back up
backup_cmd = "tar -C ~ -zcvf %s %s" % ( target , ' '.join(newer_files) )
status = os.system(backup_cmd)

if status == 0:
    print message_end
else:
    print "Back-up failed"


texts: Timing single operation to not be repeated for a fixed time

texts:
Sometimes "a" service does not respond and so we need to restart it. Usually it's a glitch in the network. We can have like 100 calls at the same time so the service cannot be restarted for 100 hundred times. The service is a Singleton. The command is called through a dispatcher, it's sync so different calls are executed in sequence.

Do you think that this approach is right to limit the restarting of the service?

public class RecoverServiceCommand extends AbstractCommand {
    /**
     * Logger for this class
     */
    private static final Logger log = LoggerFactory
        .getLogger(RecoverServiceCommand.class);

    @Override
    public boolean isAsynch() {
    return false;
    }

    @Override
    public boolean postCondition(Object... arg0) {
    return true;
    }

    @Override
    public boolean preCondition(Object... arg0) {
    return true;
    }

    @Override
    public void undo() {
    }

    @Override
    protected void doExecute(Object... arg0) throws CommandException {
    long now = System.nanoTime();
    synchronized (RecoverServiceCommand.class) {
        if (now - Service.getInstance().getLastUpdate() > Utils.TimeSpan)
        Service.getInstance().restartService(now);
        else
        log.warn("Messaging queues not restarted because it was already restarted not so long ago");
    }
    }

}


texts: (Ab)using scanl to generate a random number stream, is there a better way?

texts:
Here is my code to do it:

import Random (randomR, Random, StdGen)

generateRandoms :: (Random a, Num a) => StdGen -> a -> a -> [b] -> [a]
generateRandoms gen min max = map fst . tail . scanl f (0, gen)
    where f (x, g) _ =  randomR (min, max) g

The problem I have with this is that I need to pass a list to it e.g., via:

generateRandoms initialgen min max [1..10]

The values of this list end up being ignored and are just there to drive the scanl function.

I'm wondering if there is  a better way to do this (e.g., is there something like scanl that doesn't need a list to make it generate values?


texts: Name-spaced JavaScript wrapped in self executing function

texts:
Is there any point in wrapping this code in the self executing function declaring window and undefined? I've read that it improves performance etc... (NOTE I will be making use of the window at some point).

(function (window, undefined) { // THIS BIT HERE!
  var App = {
    init: (function () {
      $(document).ready(function () {
        App.alertMessage('Hello world');
      });
    })(),
    alertMessage: function (message) {
      alert(message);
    }
  }
})(window); // end closure


texts:
I'm trying to conform to the Zend Coding Standard as well.

EDIT 2:

<?php

/**
 *    Input   :   Query request
 *    Output  :   A row or a list of rows
 *    Notes   :
 *
 *    Provides escaping and binding via PDO library
 *    Consolidates PDO to use a single calling mechanism
 *    Consolidates all queries to an associative array
 *    Mysqli available for those who wish to implement
 */

class Database extends OneDatabase
{
    private $dbResource;
    public function __construct()
    {
        $this->dbResource = oneDatabase::_get();
    }
    public function getResource()
    {
        return $this->dbResource;
    }
    protected $_sqlArray = array(
        "signin_pass" => "SELECT pass FROM cr WHERE email=?",
        "signin_validate" => "SELECT email,pass FROM cr WHERE email=? AND pass=?",
        "signin_flname" => "SELECT flname FROM cr WHERE email=?",
        "signup_check" => "SELECT * FROM cr WHERE email=?",
        "signup_insert" => "INSERT INTO cr VALUES (?,?,?)",
        "signup_site1" => "INSERT INTO bo VALUES ('Facebook','http://www.facebook.com','',?)",
        "signup_site2" => "INSERT INTO bo VALUES ('Twitter','http://www.twitter.com','',?)",
        "bookmark_delete" => "DELETE FROM bo WHERE name=? AND email=? LIMIT 1",
        "bookmark_insert" => "INSERT INTO bo VALUES (?, ?,'', ?)",
        "bookmark_model" => "SELECT * FROM bo WHERE email=? ORDER BY name ASC",
        "tweet_insert" => "INSERT INTO tw VALUES (?,?,?,?)",
        "tweet_model" => "SELECT * FROM tw ORDER BY time DESC LIMIT 7",
        "create_bookmark" => "CREATE TABLE bookmark(name VARCHAR(64), url VARCHAR(256), tag VARCHAR(256), id INT)",
        "create_credentials" => "CREATE TABLE credentials(id INT NOT NULL AUTO_INCREMENT, flname VARCHAR(60), email VARCHAR(32), pass VARCHAR(40), PRIMARY KEY(id))",
        "create_tweet" => "CREATE TABLE tweet(id INT NOT NULL AUTO_INCREMENT, flname VARCHAR(60), email VARCHAR(32), pass VARCHAR(40), PRIMARY KEY(id))"
    );
    public function _pdoQuery($fetchType, $queryType, $parameterArray)
    {
        $query=$this->_sqlArray[$queryType];
        eval("\$query = \"$query\";");
        if($parameterArray==0)
        {
            $results = oneDatabase::$_database->query($query);
            return $results;
        }
        oneDatabase::$_database->quote($query);
        $pdoStatement = oneDatabase::$_database->prepare($query);
        $pdoStatement->execute($parameterArray);
        if($fetchType=='none')
        {
            $results=NULL;
        }
        else if($fetchType=='single')
        {
            $results = $pdoStatement->fetch(PDO::FETCH_ASSOC);
        }
        else if($fetchType=='multiple')
        {
            $results = $pdoStatement->fetchAll();
        }
        return $results;
    }
    protected function _mysqliQuery($aquery)
    {
        return oneDatabase::$_database->query($query);
    }
}


texts:
I have a 3D data set made of a certain number of points (x,y,z) that cover a certain region of space. Using the scatteredInterpolant object I can interpolate this data set over a grid to produce a rectangular mesh. Note that the mesh may extend to regions that are not defined by the data set; in fact, after the mesh generation I need to remove the part of the mesh that is extrapolated away from the data set (replacing its values with NaN, for example) in order to retain only the mesh generated between the data points.

I came up with the following MATLAB script to solve this problem in a very naive way. Considering a single mesh point (xq,yq), I evaluate the minimum distance between this point and the data set; if this distance is greater than a certain threshold, then the corresponding interpolated value (zq) is set to NaN.

%% Data set (x,y,z)
x = [3 3 3 4 4 4 4 4 5 5 5 5 5]';
y = [1 2 3 0 1 2 3 4 0 1 2 3 4]';
z = [.5 .505 .51 .51 .51 .51 .51 .515 .535 .528 .53 .53 .53]';

%% Interpolant
F = scatteredInterpolant(x,y,z,'natural');

%% Mesh generation (xq,yq,zq)
delta = 0.5;
ti = 0:delta:5;
si = 0:delta:4;
[xq,yq] = meshgrid(ti,si);
zq = F(xq,yq);

%% Replacing undesired values with NaN
thresh = 1;
n = length(ti) * length(si);
m = length(x);
xqcol = reshape(xq,[n,1]);
yqcol = reshape(yq,[n,1]);
zqcol = reshape(zq,[n,1]);
tab = [xqcol yqcol zqcol];

for i = 1:n
   dmin = 10^32;
   for k = 1:m
      diffx = tab(i,1) - x(k);
      diffy = tab(i,2) - y(k);
      d = sqrt(diffx^2 + diffy^2);
      if d < dmin
         dmin = d;
      end
   end
   if dmin >= thresh
      tab(i,3) = NaN;
   end
end

zqwork = tab(:,3);
zq2 = reshape(zqwork,[size(zq,1),size(zq,2)]);

%% Plotting
figure
plot3(x,y,z,'.r','MarkerSize',10);   % data set
grid on; axis([0 5 0 4 0.46 0.54]);
hold on;
% mesh(xq,yq,zq); view(3);           % full mesh
mesh(xq,yq,zq2); view(3);            % mesh with undesired points removed

This code gets the job done (to my utter surprise, since I am not really proficient with Matlab!). Here you can find a full mesh, and here the same mesh after the undesired points are removed. In both pictures the red dots represent the initial data set the mesh is interpolated from.

My main concern here is that while this code works fine with a limited number of points in the starting data set, it gets incredibly cumbersome when the number of data points is in the order of hundreds of thousands, which is sadly my case. I can let it be if necessary, but I feel like I should make the code a bit more efficient, since I may have to run it many times. Do you have any suggestion on how to improve its efficiency? Any input will be greatly appreciated.

I am using MATLAB 2017a.


texts: Handling overwriting of unique Dictionary values

texts:
I am working in C# to write a scheduling application for operations in a factory. I have a custom class Workday, with properties to represent a Workday for the operations in the shop. I also have a class Timeline that contains a dictionary of DateTimes as keys (using DateTime.Date to make sure we don't have two Workdays on the same date) and a Workday with the same Date as Key.Date as the value. When writing getters/setters for the Dictionary in the Timeline class, is it better to allow for overwriting a Workday, or is it preferred to clear the properties of the Workday and repopulate those values with new data?

public class Workday
{
    private Dictionary<ShopOperation, List<BOMProject>> OperationProjectPairs = new Dictionary<ShopOperation, List<BOMProject>>();
    public DateTime DayStart { get; set; }
    public DateTime DayEnd { get; set; }

    public void SetProjects(ShopOperation key, List<BOMProject> value)
    {
        if (OperationProjectPairs.ContainsKey(key))
        {
            OperationProjectPairs[key] = value;
        }
        else
        {
            OperationProjectPairs.Add(key, value);
        }
    }

    public List<BOMProject> GetProjects(ShopOperation key)
    {
        List<BOMProject> result = null;

        if (OperationProjectPairs.ContainsKey(key))
        {
            result = OperationProjectPairs[key];
        }

        return result;
    }
}

Timeline with getter that allows for full overwrite:

public class Timeline
{
    private Dictionary<DateTime, Workday> ScheduledDays = new Dictionary<DateTime, Workday>();

    public Workday GetWorkday( DateTime date )
    {
        Workday result = null;

        foreach( KeyValuePair<DateTime, Workday> pair in ScheduledDays)
        {
            if( pair.Key.Date == date.Date)
            {
                result = pair.Value;
            }
        }

        return result;
    }

    public void SetWorkday( DateTime key, Workday value)
    {
        bool scheduled = false;

        foreach( KeyValuePair<DateTime, Workday> pair in ScheduledDays)
        {
            if( pair.Key.Date == value.DayStart.Date)
            {
                ScheduledDays[key] = value;
                scheduled = true;
                break;
            }
        }

        if(!scheduled)
        {
            ScheduledDays.Add(key, value);
        }
    }
}

Timeline that will throw an exception if you try to overwrite a Workday:

public class Timeline
{
    private Dictionary<DateTime, Workday> ScheduledDays = new Dictionary<DateTime, Workday>();

    public Workday GetWorkday( DateTime date )
    {
        Workday result = null;

        foreach( KeyValuePair<DateTime, Workday> pair in ScheduledDays)
        {
            if( pair.Key.Date == date.Date)
            {
                result = pair.Value;
            }
        }

        return result;
    }

    public void SetWorkday( DateTime key, Workday value) Throws WorkdayOverwriteException
    {
        foreach( KeyValuePair<DateTime, Workday> pair in ScheduledDays)
        {
            if( pair.Key.Date == value.DayStart.Date)
            {
                throw new WorkdayOverwriteException();
            }
        }

        ScheduledDays.Add(key, value);
    }
}


texts: Is this good approach to use debug functions for implementing features?

texts:
Just thinking if using code like this

<?php

abstract class helper
{
    private static $_cycles = array();

    public static function isOdd($v)
    {
        return (0 == ($v % 2)) ? false: true;
    }

    public static function isEven($v)
    {
        return !self::isOdd($v);
    }

    public static function cycle($odd, $even)
    {
        $trace = debug_backtrace();
        $trace = $trace[0];
        $cycle = crc32(serialize($trace));

        if (!isset(self::$_cycles[$cycle]))
        {
            self::$_cycles[$cycle] = 1;
        }

        return (self::isOdd(self::$_cycles[$cycle]++)) ? $odd : $even;
    }
}

for featues like this

<?php foreach ($data as $record): ?>
    <p class="<?php echo helper::cycle('oddCss', 'evenCss'); ?>"><?php echo $record; ?>

<?php endforeach; ?>

is not overcoded

PS
Easy of usage (by html/css coders) is more important then performance in this particular case

UPDATE:
As @Geoffrey mentioned i didn't tell before that same 'oddCss', 'evenCss' pair may be used several times on one page (so basically within one request)


texts:
I have a writeOnFile() method with too many fwrite().
I think it is not a good implementation because too many system calls may produce a high overhead.
What can I do?

Code
void writeOnFile()
{
    char cr[1] = {'\n'};    //Usefull characters
    char sp[1] = {' '};

    char header1[] = "Instant        ";             //Headers
    fwrite(header1, 1, strlen(header1), out);
    char header2[] = "Playing (1 yes, 0 no)    ";
    fwrite(header2, 1, strlen(header2), out);
    char header3[] = "Segment ID    ";
    fwrite(header3, 1, strlen(header3), out);
    char header4[] = "Encode level\n";
    fwrite(header4, 1, strlen(header4), out);

    char strNumber[50];                             //Data writing
    for (int i = 0; i < global_index; i++)
    {
        snprintf(strNumber, 50, "%f", instants[i]);
        fwrite(strNumber, 1, strlen(strNumber), out);
        //Adds spaces
        for (int i = 0; i < strlen(header1) - strlen(strNumber); i++)
            fwrite(sp, 1, 1, out);

        snprintf(strNumber, 50, "%d", playing[i]);
        fwrite(strNumber, 1, strlen(strNumber), out);
        for (int i = 0; i < strlen(header2) - strlen(strNumber); i++)
            fwrite(sp, 1, 1, out);

        snprintf(strNumber, 50, "%li", segment_index[i]);
        fwrite(strNumber, 1, strlen(strNumber), out);
        fwrite(sp, 1, 1, out);
        for (int i = 0; i < strlen(header3) - strlen(strNumber) - 1; i++)
            fwrite(sp, 1, 1, out);

        snprintf(strNumber, 50, "%d", encode_level_buff[i]);
        fwrite(strNumber, 1, strlen(strNumber), out);

        //Inserts a \n at the end of the row but not at the end of file
        if (i != global_index - 1)
            fwrite(cr, 1, 1, out);
    }
}

Output example


texts:
I run subprocesses with lot of output (compilation of Unity 3D projects).

I use log parsers to find known issues.

class LogParser(object):
    def __init__(self):
        self.report = []

    def __call__(self, output: bytes):
        for decoded_line in output.decode().splitlines():
            self.parse(line)

    def parse(self, line: str):
        # Find known issues (using regexes for instance)
        # and append to self.report
        pass

    @property
    def std_out_file(self) -> int:
        # default to stderr, subclass should overwrite
        return 2

I managed to use the Python 3 Protocol API where I inject my log parsers.  This is great.

class MyProtocol(asyncio.SubprocessProtocol):
    def __init__(self, log_parser: LogParser, future: asyncio.Future):
        self.done = future
        self._transport = None
        self._log_parser = log_parser

    def pipe_data_received(self, fd: int, data: bytes):
        if fd == self._log_parser.std_out_file:
            self._log_parser(data)

    def connection_made(self, transport: asyncio.transports.SubprocessTransport):
        self._transport = transport

    def process_exited(self):
        self._transport.close()
        self.done.set_result(self._log_parser.report)

Now I realize that on Windows there is no way to get the log of a Unity 3D to be written in stderr or stdout, only in a file on the file system.

In order to keep my API compatible, I add a condition for filenames in the protocol:

class MyProtocol(asyncio.SubprocessProtocol):
    def __init__(self, log_parser: LogParser, future: asyncio.Future):
        self.done = future
        self._transport = None
        self._log_parser = log_parser

        if self._log_parser.std_out_file not in (1,2):
            # If std_out_file is not 1 or 2, it should be a
            # file path.  We could set a fileno provided by caller
            # code, but I prefer to manage async I/O from this
            # module
            loop = asyncio.get_event_loop()
            loop.call_soon(asyncio.ensure_future(self.start_follow_file()))

    def pipe_data_received(self, fd, data):
        if fd == self._log_parser.std_out_file:
            self._log_parser(data)

    @asyncio.coroutine
    def start_follow_file(self):
        from pathlib import Path
        followed_file = Path(self._log_parser.std_out_file)
        f = yield from aiofiles.open(str(followed_file.resolve()))
        try:
            while True:
                line = yield from f.readline()
                # aiofiles returns decoded lines
                if not line and not self.done.done(): # self.done is a Future
                    break
                self._log_parser.parse(line)
        finally:
            yield from f.close()

I feel like now I have two distinct pipelines for the same things.  I have read through the StreamProtocol API and I can't figure a way to do it clean and simple.  Any idea ?


texts: Custom error/fatal error and exception handler in PHP

texts:
Introduction

I wrote three functions that aims to log errors and exceptions as well as show a user a generic error page. Would appreciate some feedback on it with regards to the PSR standards and if I have left out anything of value.

Memory issue:

I am aware that the memory issue has not been addressed in this code, i.e. if you run out of memory the errors will not be logged. However, this isn't an issue I'm looking to solve at the moment.

Code:

<?php
  // General error handling
  error_reporting(-1);
  ini_set('display_errors', 0);
  ini_set('log_errors', 1);

  // Custom error handler
  function errorHandler($type, $str, $file, $line) {
    // Sets path to error log
    $errorLog = "/home/ubuntu/errors.log";
    // Generic error structure
    $msg = $str . ' in ' . $file . ' on line ' . $line;
    // Checks error severity
    switch ($type) {
      // Notices
      case E_NOTICE:
      case E_USER_NOTICE:
      case E_DEPRECATED:
      case E_USER_DEPRECATED:
      case E_STRICT:
        // Logs notices to file
        $notice = 'NOTICE ' . $msg;
        file_put_contents($errorLog, $notice . PHP_EOL, FILE_APPEND);
        break;
      // Warnings
      case E_WARNING:
      case E_USER_WARNING:
        // Logs warnings to file
        $warning = 'WARNING ' . $msg;
        file_put_contents($errorLog, $warning . PHP_EOL, FILE_APPEND);
        break;
      // Unknown errors
      default:
        // Sets header and redirect user to generic error page
        header('HTTP/1.1 500 Internal Server Error', true, 500);
        require_once('500.php');
        // Terminates the script
        exit;
    }
  }

  // Custom exception handler
  function exceptionHandler($e) {
    // Sets path to exception log
    $exceptionLog = "/home/ubuntu/exception.log";
    // Logs exceptions to file
    file_put_contents($exceptionLog, $e->__toString() . PHP_EOL, FILE_APPEND);
    // Sets header and redirect user to generic error page
    header('HTTP/1.1 500 Internal Server Error', true, 500);
    require_once('500.php');
    // Terminates the script
    exit;
  }

  // Logs on shutdown caused by an error
  function fatalErrorHandler() {
    // Gets the last occured error
    $error = error_get_last();
    // Check if error exists
    if (!empty($error) && in_array($error['type'], array(E_ERROR, E_USER_ERROR))) {
      // Sets path to error log
      $fatalErrorLog = "/home/ubuntu/errors.log";
      // Generic fatal error structure
      $fatal = 'FATAL  ' . $error['message'] . ' in ' . $error['file'] . ' on line ' . $error['line'];
      // Logs fatal error to file
      file_put_contents($fatalErrorLog, $fatal . PHP_EOL, FILE_APPEND);
      // Sets header and redirect user to generic error page
      header('HTTP/1.1 500 Internal Server Error', true, 500);
      require_once('500.php');
      // Terminates the script
      exit;
    }
  }

  // Sets custom handler for errors, exceptions and fatal errors
  set_error_handler('errorHandler');
  set_exception_handler('exceptionHandler');
  register_shutdown_function('fatalErrorHandler');
?>


texts:
I've been trying to solve this problem on Codeforces:

  Challenge description:

  After a hard day Vitaly got very hungry and he wants to eat his
  favorite potato pie. But it's not that simple. Vitaly is in the first
  room of the house with n room located in a line and numbered starting
  from one from left to right. You can go from the first room to the
  second room, from the second room to the third room and so on — you
  can go from the (n - 1)-th room to the n-th room. Thus, you can go to
  room x only from room x - 1.

  The potato pie is located in the n-th room and Vitaly needs to go
  there.

  Each pair of consecutive rooms has a door between them. In order to go
  to room x from room x - 1, you need to open the door between the rooms
  with the corresponding key.

  In total the house has several types of doors (represented by
  uppercase Latin letters) and several types of keys (represented by
  lowercase Latin letters). The key of type t can open the door of type
  T if and only if t and T are the same letter, written in different
  cases. For example, key f can open door F.

  Each of the first n - 1 rooms contains exactly one key of some type
  that Vitaly can use to get to next rooms. Once the door is open with
  some key, Vitaly won't get the key from the keyhole but he will
  immediately run into the next room. In other words, each key can open
  no more than one door.

  Vitaly realizes that he may end up in some room without the key that
  opens the door to the next room. Before the start his run for the
  potato pie Vitaly can buy any number of keys of any type that is
  guaranteed to get to room n.

  Given the plan of the house, Vitaly wants to know what is the minimum
  number of keys he needs to buy to surely get to the room n, which has
  a delicious potato pie. Write a program that will help Vitaly find out
  this number.

  Input

  The first line of the input contains a positive integer n
  (2 ≤ n ≤ 105) — the number of rooms in the house.

  The second line of the input contains string s of length 2·n - 2.
  Let's number the elements of the string from left to right, starting
  from one.

  The odd positions in the given string s contain lowercase Latin
  letters — the types of the keys that lie in the corresponding rooms.
  Thus, each odd position i of the given string s contains a lowercase
  Latin letter — the type of the key that lies in room number
  (i + 1) / 2.

  The even positions in the given string contain uppercase Latin letters
  — the types of doors between the rooms. Thus, each even position i of
  the given string s contains an uppercase letter — the type of the door
  that leads from room i / 2 to room i / 2 + 1.

  Output

  Print the only integer — the minimum number of keys that Vitaly needs
  to buy to surely get from room one to room n.

I keep exceeding time limit on one of the test cases. I made several changes (i.e. using try/except instead of 'if a in b') to my program but it still can't pass that test.

My last version is this:

x = input()
pos = input()
keys = []
keys_short = []
toBuy = 0
for i in pos:

    if i.islower():
        keys.append(i)
        keys_short = list(set(keys))
    else:
        try:
            b = keys_short.index(i.lower())
        except ValueError:
            toBuy += 1
        else:
            keys.remove(i.lower())
            keys_short = list(set(keys))
print(toBuy)

Can you suggest any changes to make it faster?


texts: Creating class method using macro to accept Visitator for each of their fields

texts:
I had a lot of classes that used a macro with listed fields. The macro was used to serialization, more like MSGPACK_DEFINE. I need a substitution of this mechanism, but I like to used that also keep names of fields.

template< class Visitator>
static inline void runVisit(const char* , Visitator & obj){}

template< class Visitator, class T, class ...Args  >
static inline void runVisit(const char* s, Visitator& obj, T& value, Args&... t)
{
    int i=0;
    for(; s[0] == ' ' ; ++s)  if( s[0] == 0 ) return;
    for(; s[i] != ',' && s[i] != ' ' ; ++i)  if( s[i] == 0 ) return;
    obj.visit(std::string(s,i), value);
    for(; s[i] != ',' ; ++i)  if( s[i] == 0 ) return;
    runVisit(s+i+1, obj, t...);
}

#define ACCEPT_AUTO( ... ) \
    template <class Visitator> \
    void accept(Visitator & obj) {\
            runVisit( #__VA_ARGS__ ",",obj, __VA_ARGS__ );\
        }\

#define ACCEPT_AUTO_INH(INHERITED, ... ) \
    template <class Visitator> \
    void accept( Visitator & obj ) const{\
            INHERITED::accept(obj);\
            runVisit( #__VA_ARGS__ ",",obj, __VA_ARGS__ );\
        }

I don't know how this method is efficient, but it takes considerable small amount lines of code. I am interested, if runVisit function can be somehow "tail call" optimized. I don't like the #__VA_ARGS__ parsing, but I don't see simpler way.

Use case example:

Definition of accept method inside some class, that should be Visitable:

class SomeData
{
    int someField;
    std::string someAnotherField;
    SomeFooData fooField;
    std::vector<SomeBarData> barFieldList;

    ACCEPT_AUTO(someField,someAnotherField,fooField,barFieldList);
};

Can be used by many different visitators:

SomeData data;

SerializerVisitatorAdapter serializer(someStream);
serializer.visit(data);

PrinterVisitatorAdapter log(std::cout);
log.visit(data);

The only thing that Serializer and Printer should have their own implementation of overloaded visit method.


texts: Recursive File Search Using the Dir() Function

texts:
There are plenty of examples of using the FileSystemObject to recursively search for a file in subfolders.  I thought that it would be interesting to write one using the Dir() function.

I was wondering if there is a way to return the found file without using the extra FoundFile parameter?

Function FindFile(ByVal folderName As String, ByVal FileName As String, Optional ByRef FoundFile As String) As String
    Dim search As String
    Dim dirList As New Collection

    If Not Right(folderName, 1) = "\" Then folderName = folderName & "\"
    search = Dir(folderName & "\*", vbDirectory)
    While Len(search) > 0
        If Not search = "." And Not search = ".." Then
            If GetAttr(folderName & search) = 16 Then
                dirList.Add folderName & search
            Else
                If LCase(search) = LCase(FileName) Then
                    FoundFile = folderName & FileName
                    FindFile = FoundFile
                    Exit Function
                End If
            End If

        End If
        search = Dir()
    Wend

    Dim fld
    For Each fld In dirList
        If Len(FoundFile) > 0 Then
            FindFile = FoundFile
            Exit Function
        Else
            FindFile = FindFile(CStr(fld), FileName, FoundFile)
        End If
    Next

End Function


texts:
The following bit of code requires a string.maketrans table that is only used inside a single function.

I have written three versions of the program that place the table at different locations in the code. The differing placement of the table results in quite varying performance in the creation of DNA instances and calls to the to_rna method.

So, which one of these variants is preferable? Or is there even a different, better solution?

Version 1:

from string import maketrans

DNA_RNA_TRANSLATION_TABLE = maketrans('GCTA', 'CGAU')

class DNA(object):
    """Represent a strand of DNA."""

    def __init__(self, dna_string):
        self.dna_string = dna_string

    def to_rna(self):
        """Return the RNA complement of the DNA strand."""
        return self.dna_string.translate(DNA_RNA_TRANSLATION_TABLE)

Version 2:

from string import maketrans

class DNA(object):
    """Represent a strand of DNA."""

    __rna_translation_table = maketrans('GCTA', 'CGAU')

    def __init__(self, dna_string):
        self.dna_string = dna_string

    def to_rna(self):
        """Return the RNA complement of the DNA strand."""
        return self.dna_string.translate(self.__rna_translation_table)

Version 3:

from string import maketrans

class DNA(object):
    """Represent a strand of DNA."""

    def __init__(self, dna_string):
        self.dna_string = dna_string

    def to_rna(self):
        """Return the RNA complement of the DNA strand."""
        translation_table = maketrans('GCTA', 'CGAU')
        return self.dna_string.translate(translation_table)


texts:
I have this simple object setup in JavaScript - Full code on jsbin

I'll break it up below, but the question(s) -

Does it break? I mean, I'm sure we can find a interesting case where this would be broken, but how much work do we have to do before it breaks?
I started out thinking I needed to explicitly store a list of classes (variable _heap below; yes, calling it heap is rather overdone for what it is) to keep the inheritance tree and avoid memory leaks when an object is instantiated multiple times. I've got the feeling it's unnecessary but I haven't found how to not use it...
Any points on how this could be better really! Is this very contrived code?

I'm trying to allow common object creation technique like:

function FourLegged() {

   this.CRY = "ffffhhhh!";

  // method
   this.talk = function() {
         writeln( this.CRY);
      };
}

But also to have the class, constructor and inheritance in a one block, as OO languages usually do:

function Cat() {

   // inheritance
   this._parent = FourLegged;

   // constructor
   this.construct =
      function(n) {
         // private var defined in instance
         var name;
         name = n;
         // methods that use private var - Douglas Crockford nethod
         // avoid it, it wastes memory if there are multiple instances
         this.setName = function(n) { name = n; };
         this.getName = function() { return name; };
      };

   // methods will operate in instance context (ie "this" is the instance)
   this.talk =
      function() {
         writeln( this.getName() + " says " + this.CRY);
      };

}

So to do this, I wrap the creation of a new instance:

cat1 = new instance(Cat, "felix");

The wrapper processes the function so as to use the constructor and inheritance, but also maintains the _heap (the class list):

function instance() {
   var c = getConstructor(arguments[0]);
   var args = Array.prototype.slice.call(arguments, 1);
   return new c(args);
}

var _heap = {};

function getConstructor(cls) {
   var cons;
   // try to retrieve from _heap
   if (!(cons = _heap[cls])) {
      // if not already in heap
      var c = new cls();
      if (c._parent) {
         // set up class-superclass relation
         cls.prototype = new instance(c._parent);
         // class has changed, re-intantiate
         c = new cls();
      }
      if (!c.construct) {  // if there is no constructor
         c.construct = function() {}; // make one
      }

      cons =
         function(args) {
            return c.construct.apply(this, args);
         };
      cons.prototype = c;  // set up class-instance relation

      _heap[cls] = cons;
   }
   return cons;
}


texts:
I am a newbie to rust and wanted to know if this code is following idiomatic rust or can be improved.

use std::cmp::Ordering;

pub fn find(array: &[i32], key: i32) -> Option<usize> {
    if array.is_empty(){
        return None;
    }
    let mut start = 0;
    let mut end = array.len() - 1;
    let mut middle;

    loop {
        middle = (end - start) / 2;
        let middle_element = array[start + middle];
        match key.cmp(&middle_element){
            Ordering::Less => end -= middle,
            Ordering::Greater => start += middle,
            Ordering::Equal => {return Some(start+middle as usize);} ,
        }

        //The slicing syntax produces an unborrowed slice
        //(type: [i32]) which we must then borrow (to give a &[i32]),
        //even if we are slicing a borrowed slice.//More can be read at
        //https://github.com/nrc/r4cppp/blob/master/arrays.md
        if end - start <= 1 {
            break;
        };
    }

    if array[start] == key {
        return Some(start as usize);
    }

    if array[end] == key {
        return Some(end as usize);
    }

    None
}

It has passed all the tests listed on Exercism for binary_search problem.


texts: Should I use an object or type as trait?

texts:
Edit: Disclaimer: I am new to templates and traits.
I apologize in advance if this is a bad question.

I am refactoring two similar classes with small differences strewn all over them into one template class (or I am trying to anyway).
This is something I just wrote. (I hope I didn't make any mistakes renaming everything.)

// declaration - empty
template <typename SETTINGS>
struct SettingsTraits;

// specialization for type CFoo
template <>
struct SettingsTraits<CFoo>
{
  typedef CFooRelated RelatedType;
  typedef CAttribute<CFooRelated > & (CDataSource::*AttrGetter)();
  static CAttribute<CFooRelated > & (CDataSource::*GetAttr)();
};

SettingsTraits<CFoo>::AttrGetter SettingsTraits<CFoo>::GetAttr = &CDataSource::GetFooAttr;

// specialization for type CBar
template <>
struct SettingsTraits<CBar>
{
  typedef CBarRelated RelatedType;
  typedef CAttribute<CBarRelated> & (CDataSource::*AttrGetter)();
  static CAttribute<CBarRelated> & (CDataSource::*GetAttr)();
};

SettingsTraits<CBar>::AttrGetter SettingsTraits<CBar>::GetAttr = &CDataSource::GetBarAttr;

So that I can write something like this

CAttribute<SettingsTraits<SETTINGS>::RelatedType> attr = (datasource.*SettingsTraits<SETTINGS>::GetAttr)();

But now I am wondering if I shouldn't just have created two different structs and passed those as template parameters instead.

I imagine the calling code would end up looking like this:

CAttribute<FooTraits::RelatedType> attr = FooTraits::GetAttr(datasource);

So probably somewhat cleaner but I haven't tried it so I don't know if it will actually work.
(I should probably replace the function pointer with a simple one line function that calls the appropriate function for each type in any case.)

Which alternative should I chose? What are the benefits/drawbacks of each?

Does it even make sense to have functions in traits? Should I maybe just use free template functions instead?


texts:
This allows users to upload an file from the browser into my Rails app using the paperclip gem. Once the file is uploaded it gets saved into the filesystem. When the user then goes in and the "show" method or the "edit" method is evoked the image is shown to the user. This is fine for image files but for .csv and .txt files I don't want to show the preview in the browser. This code is clunky and I know there is a better way to do this.

<% if @user.image? %>
<%=filetype = @user.image.url %>

<%if filetype.include? ".jpeg" %>
    isJpeg
    <%= image_tag @user.image.url %>

    <%= link_to @user.image.url, @user.image.url  %>
<% end %>
<%if filetype.include? ".gif" %>
    isGif
    <%= image_tag @user.image.url %>

    <%= link_to @user.image.url, @user.image.url  %>
<% end %>
<%if filetype.include? ".png" %>
    isPNG
    <%= image_tag @user.image.url %>

    <%= link_to @user.image.url, @user.image.url  %>
<% end %>
<%if filetype.include? ".jpg" %>
    isJPG
    <%= image_tag @user.image.url %>

    <%= link_to @user.image.url, @user.image.url  %>
<% end %>
<%if filetype.include? ".csv" %>
    isCSV

Your file was a csv file and has no preview

    <%= link_to @user.image.url, @user.image.url  %>
<% end %>

<%= image_tag @user.image.url %>

<%= link_to @user.image.url, @user.image.url  %>
<% end %>


texts: Efficiently creating a menu consisting of multi-level structure

texts:
I was asked to modify existing code to allow multi-level page structure. Each page can have one parent, and one page can have multiple children.

I will present following code. My question is is there a more efficient way of doing this? I am hard-coding the number of levels that are reachable.

Is there easier way to do  this automatically without hard coding? Recursion perhaps?

function createMenu($parents) {
    foreach ($parents as $parent) {
        $parentName = $this->getPagefromID($parent);
        $kids = $this->areThereKids($parent);

        if ($kids == "yes") {
            echo "
\n";
            $query = "SELECT * FROM pages";
            $result = mysql_query($query) or die('Query failed: ' . mysql_error());
            while ($row = mysql_fetch_assoc($result)) {
                $thisparent = $row['Parent'];
                $name = $row['Name'];
                $id2 = $row['ID'];
                if ($thisparent == $parent) {
                    echo "
" . $name . "
\n";
                    if($this->areThereKids($id2) == "yes") {
                        $children = $this->getMyKids($id2);
                        foreach($children as $kid) {
                            $info = $this->getPersonInformation($kid);
                            $kidid = $info[0]["ID"];
                            echo "
" . $info[0]['Name'] . "
\n";
                            // more sub
                            if($this->areThereKids($kidid) == "yes") {
                                $children1 = $this->getMyKids($kidid);
                                foreach($children1 as $kid1) {
                                    $info1 = $this->getPersonInformation($kid1);
                                    $kidid1 = $info1[0]['ID'];
                                    echo "
-" . $info1[0]['Name'] . "
\n";
                                    if($this->areThereKids($kidid1) == "yes") {
                                        $children2 = $this->getMyKids($kidid1);
                                        foreach($children2 as $kid2) {
                                            $info2 = $this->getPersonInformation($kid2);
                                            $kidid2 = $info2[0]['ID'];
                                            echo "
--" . $info2[0]['Name'] . "
\n";
                                            // No need for 6 levels.
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            echo "
\n";
        }
        echo "
\n";
    }
}


texts: Building an email generator using abstract factory pattern

texts:
I'm trying to build a customer email generator in java using the abstract factory pattern. I understand how to use the factory method pattern; however, I'm a bit confused about the abstract factory pattern. I'm trying to generate an email based on customer type. Could you look at my code below and tell me if I'm using the abstract factory pattern correctly? My code works fine. I just want to make sure that I'm using the pattern correctly. Thank you

public abstract class EmailTemplate {
   public abstract String getHeader();
   public abstract String getBody();
   public abstract String getFooter();

   public String generateEmail(){
      return getHeader()+"\n"+getBody()+"\n"+getFooter();
   }
}
public interface EmailFactory {
    EmailTemplate createEmail();
}
public class BusinessEmail extends EmailTemplate {
  @Override
  public String getHeader() {
    return "Dear [business customer],";
  }

  @Override
  public String getBody() {
    return "Thank you for being our valued customer. We are so grateful for the pleasure of serving you and hope we met your expectations.";
  }

  @Override
  public String getFooter() {
    return "Best Regards," +
            "[name]";
  }
}
public interface EmailGeneratorFactory {
    EmailTemplate createEmail();
}
public class BusinessFactory implements EmailGeneratorFactory {
    @Override
    public EmailTemplate createEmail() {
        return new BusinessEmail();
    }
}
public class EMailGenerationSystem {
    private static EMailGenerationSystem EMailGenerationSystem = new EMailGenerationSystem();
    private EMailGenerationSystem(){};
    public static EMailGenerationSystem getInstance(){
        return EMailGenerationSystem;
    }
    public EmailTemplate getEmail(EmailGeneratorFactory factory){
        return factory.createEmail();
    }
}


texts: C/C++ code to do customized string comparing

texts:
It's an interview question, I was asked to compare 2 strings, and the number in the string are evaluated to integers when comparing.

I can use C/C++ and can not use stl or stdlib. Some test cases are showed in the code.

I submitted the code below but failed. The interviewer said that the code is not clean enough. Can anybody review the code?

#include <cstdio>
#include <cmath>
bool is_num(char x) {return (x>='0' && x<='9');}

int get_num(const char* s, int len)
{
    int j = 0;
    int ret = 0;
    while (len > 0)
    {
        ret += (s[j++] - '0') * pow(10, len-1);
        len --;
    }
    return ret;
}

int my_compare(const char* s1, const char* s2)
{
    while((*s1)&&(*s2))
    {
        int value1 = 0;
        int value2 = 0;
        bool is_t1_num = false;
        bool is_t2_num = false;
        int len_t1 = 0;
        int len_t2 = 0;
        const char*  t1;
        const char*  t2;
        if (is_num(*s1))
        {
            t1 = s1;

            while(is_num(*t1)&&(*t1))
            {
                len_t1 ++;
                t1++;
            }
            value1 = get_num(s1, len_t1);
            is_t1_num = true;
        }
        if (is_num(*s2))
        {
            t2 = s2;
            while(is_num(*t2)&&(*t2))
            {
                len_t2 ++;
                t2++;
            }
            value2 = get_num(s2, len_t2);
            is_t2_num = true;
        }

        if ((!is_t1_num) && (!is_t2_num))
        {
            if ((*s1) < (*s2)) return -1;
            if ((*s1) > (*s2)) return 1;
            s1++;
            s2++;
        }

        if ((is_t1_num) && (is_t2_num))
        {
            if (value1 < value2) return -1;
            if (value1 > value2) return 1;
            s1 += len_t1;
            s2 += len_t2;
        }

        if ((is_t1_num) && (!is_t2_num))
        {
            if (value1>0) return 1;
            s1 += len_t1;
        }

        if ((!is_t1_num) && (is_t2_num))
        {
            if (value2>0) return -1;
            s2 += len_t2;
        }
    }//end while
    if (!(*s1) && !(*s2)) return 0;
    if (!(*s1)) return -1;
    if (!(*s2)) return 1;
}

int main()
{
    //TEST CASE 0
    printf("%d\n", my_compare("ab", "1"));
    printf("%d\n", my_compare("123", "456"));
    printf("%d\n", my_compare("abc", "def"));
    printf("%d\n", my_compare("abc123def", "abc000def"));
    printf("%d\n", my_compare("ab", "abc"));

    //TEST CASE 1
    printf("%d\n", my_compare("abc000def", "abcdef"));
    printf("%d\n", my_compare("abc101def", "abcdef"));

    //TEST CASE 2
    printf("%d\n", my_compare("abc101def", "abceef"));
}


texts:
I am about to graduate with my Associates degree in Math and will soon go for my bachelors. I've decided with two years of school left its best if I start learning to program. I am starting with python.

I recently completed a beginners course on YouTube from free code camp. I completed novice programs that come with the course. (Guessing game)(mad Libs) & a(multiple choice quiz)

Now I am moving on to complete 3 programs outside of the lecture before I move to another python course. My ideas were (Dice game), (Hangman), (short game)

Below is my python code for the dice game. I planned on creating an array and looping through then selecting a random number from the loop. It's proving a little difficult. so far I just print a 3x3 matrix then select a random number. fyi the 3x3 is suppose to represent a 9 sided dice.

My question: Is this code good enough for me to move on to my next program or should I stick with it and code the dice game the way I originally planned. Thank you for the feedback.

#Create dice using matrix 9 sides
#Create function: Give user option to roll dice
#Return random dice number  1-9

from random import seed
from random import randint
dice = [

[[1],[2],[3]],
[[4],[5],[6]],
[[7],[8],[9]]
]

def diceroll():
  start = input("do you want to play dice Y/N ")
  if start == "Y" or start == "y":
   print(dice[0])
   print(dice[1])
   print(dice[2])
  x = input("Do you want to roll the dice: Y/N ")

  while x == "y" or x =="Y":
   if  x != "y" or x !="Y":
     for i in range(1):
       roll=randint(1,9)
       print(roll)
   x = input("Do you want to roll the dice again: Y/N ")
 else:
  print("GoodBye: ")


texts: Decomposing a matrix as a sum of two bitstrings

texts:
I chanced upon this question and came up with the following algorithm, looking for criticisms and advice on how to improve my algorithm efficiency.

  You are given 3 arguments:

  A & B are integers within the range (0 to 100,000)
  M is an array of integers within the range (0 to 2)

  Return an output (as a string) that describes matrix M in the
  following format:

  The first part of the string should contain a description of the upper row using only the 1 and 0 characters and should add up to
  the integer A
  The second part of the string should contain a description of the lowerrow using only the 1 and 0 characters and should add up to
  the integer B
  The sum of integers at K index of the output(string1, string2) should be equal to M[K] so like: string1[K] + string2[K] == M[K]

  So for example,

  Given A = 2, B = 2, M = [2, 0, 2, 0], your function should return a
  string like "1010, 1010"

  Given A = 3, B = 2, M = [2, 1, 1, 0, 1], your function should return
  "11001, 10100"

  Given A = 2, B = 3, M = [0, 0, 1, 1, 2], your function should return
  0, because no matrix can be constructed that satisfies such
  conditions.

def convert(A, B, M):
    if (A+B) != sum(M) or max(A, B) > len(M):
        return 0

'''
logic:

set 2 arrays
if value in matrix = 2, array1 & array2 at index where 2 occurs
will be [1] and [1]

if value in matrix = 0, array1 & array2 at index where 0 occurs will
be [0] and [0]

Then, we only need to handle 1s in matrix...
same logic as above,
however,
we handle position of 1 by checking whether A > B or vice versa
'''

    array1 = [""] * len(M)
    array2 = [""] * len(M)

    # first check for 2's and 0's:
    for index, value in enumerate(M):
        if value == 2:
            array1[index] = 1
            array2[index] = 1
            A -= 1
            B -= 1
        elif value == 0:
            array1[index] = 0
            array2[index] = 0

    # then check for 1's:
        elif value == 1 and A>B:
            array1[index] = 1
            array2[index] = 0
            A -= 1
        elif value == 1 and A<=B:
            array1[index] = 0
            array2[index] = 1
            B -= 1

    array1 = ''.join(str(x) for x in array1)
    array2 = ''.join(str(x) for x in array2)
    return array1 + ', ' + array2


texts:
I'm trying to come up with a script that will add license headers to certain files (depending on extension). My Bash is very average, so any guidance would be much appreciated.

I'm not quite sure what to ask for except for whether I'm making any gross mistakes.

#!/usr/bin/env bash

set -euo pipefail

shopt -s globstar nullglob extglob

lineone="Copyright (c) 2015 Acme Corp, LLC."
linetwo="Unauthorized copying of this file via any medium is strictly prohibited."
linethree="Written by John Doe <j@acme.com>, July 2015" # etc.

printf "// %s
// %s
// %s\n\n" "$lineone" "$linetwo" "$linethree" > "/tmp/$USER-license-go"

printf "{{/*
%s
%s
%s
*/}}\n\n" "$lineone" "$linetwo" "$linethree" > "/tmp/$USER-license-gohtml"

printf "# %s
# %s
# %s\n\n" "$lineone" "$linetwo" "$linethree" > "/tmp/$USER-license-shell"

typ=""
for f in **/*; do
    if [[ -f $f ]]; then
        if ! grep -q Copyright "$f"; then
            case "$f" in
                *.go             ) typ="go"      ;;
                *.gohtml         ) typ="gohtml"  ;;
                @(*.bash|*.conf) ) typ="shell"   ;;
                *                ) continue      ;;
            esac

            cat "/tmp/$USER-license-"$typ "$f" | sponge "$f"
        fi
    fi
done


texts:
I would like to ask your advice on my simple code to login and registration sessions.

In the User class, login function:

public function login($username, $password){
    $this->db->query("SELECT * FROM users WHERE username = :username AND status = :status LIMIT 1");
    $this->db->bind(':username', $username);
    $this->db->bind(':status', 1);
    $row = $this->db->single();
    $count = $this->db->rowCount();
        if ($count > 0) {
            if (password_verify($password, $row['password'])) {
                $_SESSION['session'] = [
                    'id' => $row['id'],
                    'username' => $row['username'],
                    'email' => $row['email'],
                    ];
                return true;
            } else {
                return false;
            }
        }
}

check logged:

public function isLoggedIn() {
    if (isset($_SESSION['session'])) {
    return true;
    }
}

And login page with check logged:

if ($user->isLoggedIn()) {
    header('Location: index.php');
    exit();
}

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

    //Retrieve the field values from our login form.
    $username = !empty($_POST['username']) ? trim($_POST['username']) : null;
    $password = !empty($_POST['password']) ? trim($_POST['password']) : null;

    if($user->login($username, $password)) {
        header('Location: index.php');
        exit();
    } else {
        $message[] = 'We found problems with the login, please try again.';
    }
}


texts:
I am implementing a library in C/C++11 and I have chosen to follow Google C++ Style Guide as I also use this style guide in my code.

As such all classes and types (including typedefs and using) start with a capital letter.

However I have reached a conflict when implementing some traits.

For instance I have a RemoveOptional trait:

template <class T>
struct RemoveOptional {
  using Type = T;
};

template <class T>
struct RemoveOptional<utils::Optional<T>> {
  using Type = T;
};

that I can use like this:

utils::RemoveOptional<utils::Optinal<int>>::Type

But for the traits like IsXXX I have chosen to inherit std::true_type or std::false_type in order to be used like the std traits:

template <class T>
struct IsOptional : std::false_type {
};

template <class T>
struct IsOptional<Optional<T>> : std::true_type {
};

so this trait is used like this:

utils::IsOptional<utils::Optional<int>>::value
utils::IsOptional<utils::Optional<int>>::value_type

And value_type conflicts with my naming conventions as it should be ValueType.

As far as I see I have 3 options:

Modify all of my traits to follow the std convention.

Advantages: my traits can be checked against the std::true_type and std::false_type.
Disadvantages: my library is inconsistent.

Discard the std::true_type and std::false_type and make all my traits following my convention.

Advantages: my library is consistent.
Disadvantages: my traits can't be checked against std::true_type and std::false_type.

Leave as it is now.

Advantages: my traits can be checked against std::true_type and std::false_type.
Disadvantages: my library is inconsistent (even my traits are inconsistent between each other).

What should I do?


texts:
I came across Java like Scala code that I am trying to refactor to make it functional and immutable.  The first obvious flaw is that it's violating thread safety by using mutable public class level collections.

Those methods (insText, insInt, etc) look unnecessary and can be removed with higher order function (where function takes in dd => Int, dd => String type of thing). Class DDType is wrong with all mutable variables.  Should I change class level mutable sets to private immutable sets?

Do you agree with those changes and overall refactoring approach?

class SaveObject extends Update with QueryFormatter {

  val keys    = mutable.Set[(DomainDictionary, Int   )]()
  val inserts = mutable.Set[(DomainDictionary, String)]()

  implicit def toInt(value:String) = value.toInt
  implicit def toDouble(value:String) = augmentString( value ).toDouble
  implicit def toBool(value:String) = value.toBoolean
  implicit def toTs(value:String) = {
  val date:Date = dateFormat.parse(value)
    new Timestamp(date.getTime)
}
implicit def toDate(value:String):Date = {
  dateFormat.parse(value)
}

def add(dd:DomainDictionary, value:String) = {
// check if its a key
getType(dd) match {
  case x if x.isKey    => id(dd, value)
  case x if x.isText   => insText(dd, value)
  case x if x.isInt    => insInt(dd, value)
  case x if x.isDouble => insDouble(dd, value)
  case x if x.isBool   => insBool(dd, value)
  case x if x.isTs     => insTs(dd, value)
  case x if x.isDate   => insDate(dd, toDate(value))
  case _               =>
    val msg = "Could not convert type for dd %s and value %s".format(dd.id, value)
    throw new Exception(msg)
 }
}
class DDType(dd:DomainDictionary) {
var isKey    = false
     var isText   = false
     var isInt    = false
     var isDouble = false
     var isBool   = false
     var isTs     = false
     var isDate   = false
 }
 def getType(dd:DomainDictionary):DDType = {
   val theType = new DDType(dd)
   val ns = dd.namespace
   val isKey = namespaceMatcher(ns,
   (ns,table,key)=>false.toString,
   (ns,table,key)=>false.toString,
   (ns,table,key)=>if(key == QueryPathfinder.ID) true.toString else false.toString
)

 if(toBool(isKey)){
   theType.isKey = true
 }
 else {
   val ddType = dd.domainDictionaryType
   ddType match {
     case "text" => theType.isText = true
     case "numeric" => theType.isInt = true
     case "alphanumeric" => theType.isText = true
     case "date" => theType.isDate = true
     case "timestamp" => theType.isTs = true
     case "boolean" => theType.isBool = true
     case "currency" => theType.isInt = true
     case _ => {} //this is wrong
   }
 }

theType
}
def id(dd:DomainDictionary, key:Int){
  keys += Tuple2(dd, key)
}
def insText(dd:DomainDictionary, value:String) = {
  inserts += Tuple2(dd,value)
}
def insInt(dd:DomainDictionary, value:Int) = {
    inserts += Tuple2(dd,value.toString)
}
def insDouble(dd:DomainDictionary, value:Double) = {
  inserts += Tuple2(dd,value.toString)
}
def insTs(dd:DomainDictionary, value:Timestamp) = {
  val date = new Date(value.getTime)
  inserts += Tuple2(dd,dateFormat.format(date))
 }
 def insDate(dd:DomainDictionary, value:Date) = {
    inserts += Tuple2(dd,dateFormat.format(value))
 }
  def insBool(dd:DomainDictionary, value:Boolean) = {
    inserts += Tuple2(dd,value.toString)
  }

}


texts:
I'm (re)building a Quantitative Trading Robot in Python.

Description:

This is my module for API Calls. The API documentation can be found here. This is the direct interface layer between my code and the exchange server. Any abstraction on top of the direct API calls is in a separate module.

Classes:

GDAXExchangeAuth - Authentication for restricted API Calls

Functions:

get_server_time - Retrieve the curent server time

get_account - Retrieve Account balances

get_book - Retrieve the order book for a specified currency pair

get_fills_after_order - Retrieve all filled orders that have occurred after some specific order id.

post_limit_order - Post an order to the exchange

get_price_history - Retrieve the price history for a specific currency pair

Areas of interest:

The usual, am I following conventions, how's my naming, how's my documentation, how well thought-out is my structure?

import json
import hmac
import hashlib
import requests
import base64
from requests.auth import AuthBase

API_KEY = 'redacted'
API_SECRET = 'redacted'
API_PASSPHRASE = 'redacted'
API_URL = 'https://api.gdax.com/'

class GDAXExchangeAuth(AuthBase):
    SIGNATURE_HTTP_HEADER = 'CB-ACCESS-SIGN'
    TIMESTAMP_HTTP_HEADER = 'CB-ACCESS-TIMESTAMP'
    KEY_HTTP_HEADER = 'CB-ACCESS-KEY'
    PASSPHRASE_HTTP_HEADER = 'CB-ACCESS-PASSPHRASE'

    def __init__(self, api_key, secret_key, passphrase, server_time):
        self.api_key = api_key
        self.secret_key = secret_key
        self.passphrase = passphrase
        self.server_time = server_time

    def __call__(self, request):
        epoch = self.server_time['epoch']
        timestamp = str(epoch)
        request.headers.update(
            {
                'CB-ACCESS-TIMESTAMP': timestamp,
                'CB-ACCESS-KEY': self.api_key,
                'CB-ACCESS-PASSPHRASE': self.passphrase,
                'Content-Type': 'application/json'
            }
        )

        message = timestamp + request.method + request.path_url + (request.body or '')
        message = message.encode()
        hmac_key = base64.b64decode(self.secret_key)
        signature = hmac.new(hmac_key, message, hashlib.sha256)
        signature_b64 = base64.b64encode(signature.digest())

        request.headers.update(
            {
                'CB-ACCESS-SIGN': signature_b64,
                'Content-Type': 'application/json'
            }
        )

        return request

def get_server_time():
    url = API_URL + 'time'
    r = requests.get(url)
    return r

def get_account(server_time):
    auth = GDAXExchangeAuth(API_KEY, API_SECRET, API_PASSPHRASE, server_time)
    url = API_URL + 'accounts'
    r = requests.get(url, auth=auth)
    return r

def get_book(product, level):
    # level 1 = Bid/Ask
    url = API_URL + '/products/' + product + '/book?level=' + str(level)
    r = requests.get(url)
    return r

def get_fills_after_order(server_time, order_id):
    # get all filled orders after the order id.
    # max 100 results returned
    auth = GDAXExchangeAuth(API_KEY, API_SECRET, API_PASSPHRASE, server_time)
    url = API_URL + 'fills?before=' + str(order_id)
    r = requests.get(url, auth=auth)
    return r

def post_limit_order(server_time, side, price, size, product_id):
    order_type = 'limit'

    order = {}
    order['side'] = side
    order['price'] = price
    order['size'] = size
    order['product_id'] = product_id
    order['type'] = order_type

    auth = GDAXExchangeAuth(API_KEY, API_SECRET, API_PASSPHRASE, server_time)
    url = API_URL + 'orders'
    data = json.dumps(order)
    r = requests.post(url, data=data, auth=auth)
    return r

def get_price_history(product_id, start, end, granularity):
    params = {}
    params['start'] = start
    params['end'] = end
    params['granularity'] = granularity

    url = API_URL + '/products/' + product_id + '/candles'
    r = requests.get(url, params=params)
    return r


texts:
I tried to prevent XSS attacks by adding

// prevent XSS
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

to the top of the .PHP File. It works, but I don't think that this is the best practice.

What I need to do is improve the way this code handles the data:

    if (empty($_POST['telefonnummer']) || !isset($_POST['telefonnummer'])) {
        $this->setStatusMessage($translator->translate('Bitte geben Sie Ihre Telefonnummer ein.'));
        $this->setStatus(KDatabase::STATUS_FAILED);

        return false;
    }else{
      $this->telefonnummer = $_POST['telefonnummer'];
    }


texts: Check if a string is a valid english word, and convert to a valid english word

texts:
This is an interview question.
For the purpose of the question, a valid English word is a string that begins with an uppercase English letter, and the rest of the string contains only lowercase English letters. I needed to implement two functions:

A function that receives a String and returns true if the String is a valid English word, and false otherwise.
A function that receives a String and convert it to a valid english word. That means that the function removes non-English characters from the string, and also lowercase\uppercase letters that are in the wrong place. Examples:

convertToValidString("A") = "A"
convertToValidString("a") = ""
convertToValidString("Ab") = "Ab"
convertToValidString("AB") = "A"
convertToValidString("Ab5eA") = "Abe"
convertToValidString("aAd") = "Ad"
convertToValidString("a6d") = ""

Below is the code I wrote, please tell me what do you think. My emphasis is mainly about efficiency (run time + short code), and less about coding conventions.

public static boolean isValidString(String s){
    int len = s.length();

    if (len == 0) return true;
    if ( (s.charAt(0) < 65) || (s.charAt(0) > 90) ) return false;
    for (int i = 1; i < len; i++){
        if ( (s.charAt(i) < 97) || (s.charAt(i) > 120) ) return false;
    }

    return true;
}

public static String convertToValidString(String s) {
    StringBuffer ans = new StringBuffer();
    int len = s.length();
    int i = 0;

    while ( (i < len) && ((s.charAt(i) < 65) || (s.charAt(i) > 90)) )
        i++;

    if (i < len){
        ans.append(s.charAt(i));
        i++;
        for (; i < len; i++){
            if ( (s.charAt(i) >= 97) && (s.charAt(i) <= 120) )
                ans.append(s.charAt(i));
        }
    }

    return ans.toString();
}


texts:
I am playing with the cifar-10 dataset (available here) and for now I would like to plot one of the images of a batch.

The images are represented as vectors when I get them from pickle:

  From the cifar-10 documentation:
  The first 1024 entries (of an image) contain the red channel values, the next 1024 the green, and the final 1024 the blue. The image is stored in row-major order, so that the first 32 entries of the array are the red channel values of the first row of the image.

What I came up with to plot an image is this:

import numpy as np
import matplotlib.pyplot as plt

# get the dataset
a = unpickle('./cifar-10/data_batch_1')
# get the first image
img = np.array(a[b'data'][0])
# transform it to a 3 x 1024 array, one row per color channel
# and transpose it to a 1024 x 3 array, one row per rgb pixel
img = img.reshape(3, 1024).T
# reshape it so we can plot it as a 32 x 32 image with 3 color channels
img = img.reshape(32, 32, 3)

# plot
plt.imshow(img)
plt.show()

It's my first attempt at matrix manipulation so even if this is concise, I feel like it could be simpler. What do you guys think?


texts: Synchronizing two scrollbars to work in unison

texts:
This synchronizes the document’s vertical scrollbar and a DIV’s horizontal scrollbar so they can work in unison controlling the content simultaneously.

The code is operable and behaves how I want. I want to know whether or not this code can be optimized any further.

Heads-up: the jsScroll0 and jsScroll1 flags stop either scrollbar from locking due to an infinite loop scenario upon each scrollbar trying to set each other’s values.

(function() {
    var jsScroll0, jsScroll1;
    var divScroller = document.getElementById('scrollP');

    document.onscroll = function () {
        if (jsScroll1) {
            jsScroll1 = false;
            return;
        }
        jsScroll0 = true;
        divScroller.scrollLeft = document.documentElement.scrollTop;
    };
    divScroller.onscroll = function () {
        if (jsScroll0) {
            jsScroll0 = false;
            return;
        }
        jsScroll1 = true;
        document.documentElement.scrollTop = divScroller.scrollLeft;
    };
})();


texts:
When you write a code in python code people always ask to make it more pythonic. I am not sure if there is a term for scala or not. However, I am pretty sure my following code use one or two scala feature.

Objective

Read a property file, which has location to XML file
Read source, destination and some other properties from property and XML File
Copy Data from one location to another location.

FileSystem.scala

bstract class FileSystem(flagFileURI: String){

  def getRecordCount(properties: Properties): String = {
    properties.getProperty("recordCount")
  }

  def getAuditID: String = {
    val instant: Instant = Instant.now
    val zoneId: ZoneId = ZoneId.of("Canada/Eastern")
    val auditIdFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")
    val auditId = ZonedDateTime.ofInstant(instant, zoneId).format(auditIdFormatter)
    auditId
  }

  def getSourcePath(properties: Properties): Path = {
    val dataFileURI: String = properties.getProperty("dataFileURI")
    val srcPath = new Path(dataFileURI)
    srcPath
  }

  def getMetaDataFileURI(properties: Properties): String = {
    properties.getProperty("metadataFileURI")
  }

  def getIDPDataDate(properties: Properties): String = {
    properties.getProperty("idpDataDate")
  }
  def getDestinationPath(properties: Properties, metaDataFileURI: String, IDPDataDate: String, dataFileName: String): Path = {
    val l0DirLocation: String = ConfigFactory.load().getString("sparkFramework.hdfs.l0dirlocation")

    val frameWorkUtils = new FrameworkUtils()
    val sourceSystem: SourceSystem = frameWorkUtils.getSourceSystem(metaDataFileURI)
    val schemaName: String = frameWorkUtils.getSchemaName(sourceSystem)
    val tableName: String = frameWorkUtils.getTableName(sourceSystem)

    val destPath = new Path(l0DirLocation + schemaName + "/" + tableName + "/idp_data_date=" + IDPDataDate + "/" + dataFileName)

    destPath
  }

  def getDataFileName(srcPath: Path, auditID: String): String = {
    val dataFileName: String = srcPath.getName + "_" + getAuditID
    dataFileName
  }

}

HDFileSystem.scala

class HDFileSystem(flagFileURI: String) extends FileSystem(flagFileURI) {

  def copyFromLocalFile: (String, String, String, String, String) = {

    val properties: Properties = new Properties()
    val source: InputStreamReader = Source.fromFile(flagFileURI).reader
    properties.load(source)

    val metaDataFileURI = getMetaDataFileURI(properties)
    val srcPath = getSourcePath(properties)
    val auditId = getAuditID
    val dataFileName = getDataFileName(srcPath, auditId)
    val IDPDataDate = getIDPDataDate(properties)
    val destPath = getDestinationPath(properties, metaDataFileURI, IDPDataDate, dataFileName)
    val recordCount = getRecordCount(properties)

    val hadoopConf = new Configuration()
    val hdfs = FileSystem.get(hadoopConf)
    hdfs.copyFromLocalFile(true,false,srcPath, destPath)
    (IDPDataDate,recordCount,auditId,metaDataFileURI,dataFileName)

  }
}

Main.scala

 val hdFileSystem = new HDFileSystem(flagFileURI = args(0))
    val (idpDataDate,count,auditId,metadataFileURI,fileName) = hdFileSystem.copyFromLocalFile