texts: filter date for a specific hour and minute

texts:
selected_hour=12
dates=[]
date1 = datetime.datetime(2012, 9, 10, 11, 46, 45)
date2 = datetime.datetime(2012, 9, 10, 12, 46, 45)
date3 = datetime.datetime(2012, 9, 10, 13, 47, 45)
date4 = datetime.datetime(2012, 9, 10, 13, 06, 45)
dates.append(date1)
dates.append(date2)
dates.append(date3)
dates.append(date4)

for i in dates:
    if (i.hour<=selected_hour+1 and i.hour>=selected_hour-1):
        if not i.hour==selected_hour:
            if i.hour==selected_hour-1 and i.minute>45:
                print i
            if i.hour==selected_hour+1 and i.minute<=15:
                print i
        if i.hour==selected_hour:
            print i

Result is :

    2012-09-10 11:46:45
    2012-09-10 12:46:45
    2012-09-10 13:06:45

I want to filter my dates based on selected_hour. The output should be 15 minutes later and before of the selected_hour including all selected_hour's minutes. This codes does what I want but, i am looking for a nicer way to do that. How to get same results in a shorter and better way ?


texts: Improve performance for stanford-nlp in a "homemade" search engine

texts:
I am working on a javaproject for the Information Retrieval subject in my graduation. What I'm trying to do is to reduce the lines of code I have to write due to the lack of time. We're currently on the second checkpoint, where we have to implement the engine collector component. What I'm trying to do is to use the Jsoup lib to crawl the web. That part works at the moment, but now I must parse the fetched HTML documents to retrive entites (people and places) and store the relevant pages on the disk. For that, I'm trying to use Stanford's NLP. What I'm doing to test it on one single page, at the moment is this:

// assuming all needed imports are done

String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) "
        + "AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
String url = "https://www.example.com";
Document htmlDocument = Jsoup.connect(url).userAgent(userAgent).get();
String text = htmlDocument.body();
String model = "english.all.3class.distsim.crf.ser.gz";
AbstractSequenceClassifier<CoreLabel> classifier = CRFClassifier.getClassifier(model);
System.out.println(classifier.classifyToString(text));

This works rather fine, it prints |word in the text/category|, but that execution is very slow (around 6 minutes, more or less). Is there a way to speed that up? Do I have to use other classes rather than CRFClassifier? Is Jsoup the real dragger and not the NLP process?

My internet connection is already a bottleneck to the project. The parser can't become another one, considering that the engine must collect and store thousand of pages.


texts: Are these good examples of functions that do one thing only or am I getting a little carried away?

texts:
I'm reading Robert C. Martin's "Clean Code" and for the past few days I've been fiddling with its function writing guidelines. At first I thought the idea of functions being two/three lines long to be ludicrous, but I'm slowly getting the hang of it. The problem is, I'm pretty sure I'm overdoing it now.

These are the first lines of the module I decided to refactor using the advice from the book.

Public Sub ExportAvailabilityData()
  Dim aplicativo As Excel.Application
  Set aplicativo = CreateObject("Excel.Application")
  aplicativo.Visible = True

  Dim pastaDeTrabalho As Excel.Workbook
  Set pastaDeTrabalho = aplicativo.Workbooks.Add

  Do Until pastaDeTrabalho.Sheets.Count = DaysInMonth(Month(Date)) + 1
    pastaDeTrabalho.Sheets.Add
  Loop

  Dim day As Integer
  For day = 1 To DaysInMonth(Month(Date))
    pastaDeTrabalho.Sheets(day).Name = Format(day, "00") & "." & Format(Month(Date), "00")
  Next day

  pastaDeTrabalho.Sheets(DaysInMonth(Month(Date)) + 1).Name = "Summary " & UCase(MonthName(Month(Date)))
End Sub

Private Function DaysInMonth(ByVal month As Integer) As Integer
  DaysInMonth = Day(DateSerial(Year(Date), month + 1, 1) - 1)
End Function

And this is how it looks like today.

Public Sub ExportAvailabilityData()
  Dim aplicativo As Excel.Application
  Set aplicativo = CreateObject("Excel.Application")
  aplicativo.Visible = True

  Dim pastaDeTrabalho As Excel.Workbook
  Set pastaDeTrabalho = aplicativo.Workbooks.Add

  CreateSheets pastaDeTrabalho
  NameSheets pastaDeTrabalho
End Sub

Private Sub CreateSheets(ByRef pastaDeTrabalho As Excel.Workbook)
  CreateDailySheets pastaDeTrabalho, Month(Date)
  CreateSummarySheet pastaDeTrabalho
End Sub

Private Sub CreateDailySheets(ByRef pastaDeTrabalho As Excel.Workbook, ByVal month As Integer)
  Do Until pastaDeTrabalho.Sheets.Count = DaysInMonth(month)
    pastaDeTrabalho.Sheets.Add
  Loop
End Sub

Private Sub CreateSummarySheet(ByRef pastaDeTrabalho As Excel.Workbook)
  pastaDeTrabalho.Sheets.Add
End Sub

Private Function DaysInMonth(ByVal month As Integer) As Integer
  DaysInMonth = Day(DateSerial(Year(Date), month + 1, 1) - 1)
End Function

Private Sub NameSheets(ByRef pastaDeTrabalho As Excel.Workbook)
  NameDailySheets pastaDeTrabalho, Month(Date)
  NameSummarySheet pastaDeTrabalho, Month(Date)
End Sub

Private Sub NameDailySheets(ByRef pastaDeTrabalho As Excel.Workbook, ByVal month As Integer)
  Dim day As Integer
  For day = 1 To DaysInMonth(month)
    pastaDeTrabalho.Sheets(day).Name = AssembleDailySheetName(day, month)
  Next day
End Sub

Private Sub NameSummarySheet(ByRef pastaDeTrabalho As Excel.Workbook, ByVal month As Integer)
  Dim index As Integer
  index = GetSummarySheetIndex(month)
  pastaDeTrabalho.Sheets(index).Name = AssembleSummarySheetName(month)
End Sub

Private Function GetSummarySheetIndex(ByVal month As Integer) As Integer
  GetSummarySheetIndex = DaysInMonth(month) + 1
End Function

Private Function AssembleDailySheetName(ByVal day As Integer, ByVal month As Integer) As String
  AssembleDailySheetName = Format(day, "00") & "." & Format(month, "00")
End Function

Private Function AssembleSummarySheetName(ByVal month As Integer) As String
  AssembleSummarySheetName = "Summary " & UCase(MonthName(month))
End Function

When I considered replacing the "." constant inside AssembleDailySheetName() with a call to yet another function (GetDateSeparator() or something similar), I decided to stop and get some feedback.


texts:
How can I optimize this code to increase the performance of searching data?

public class TableRowInfo : IEquatable<GridRowInfo>
{
    #region Ctor

    public TableRowInfo(int rowIndex, object rowData, NodeEntry nodeEntry, bool isNewRow = false)
    {
        this.RowData = rowData;
        this.NodeEntry = nodeEntry;
        this.RowIndex = rowIndex;
        this.IsNewRow = isNewRow;
    }

    public TableRowInfo(int rowIndex, bool isNewRow)
    {
        this.RowData = null;
        this.NodeEntry = null;
        this.RowIndex = rowIndex;
        this.IsNewRow = isNewRow;
    }

    #endregion

    #region Properties

    public object RowData { get; private set; }

    public bool IsDataRow
    {
        get { return RowData != null; }
    }

    public bool IsNewRow
    {
        get;
        set;
    }

    public int RowIndex { get; internal set; }

    internal NodeEntry NodeEntry { get; private set; }

    #endregion

    public override int GetHashCode()
    {
        int rowDataHashCode = this.RowData == null ? 0 : this.RowData.GetHashCode();
        return rowDataHashCode ^ this.RowIndex;
    }

    #region IEquatable<TableRowInfo> Members

    public bool Equals(GridRowInfo other)
    {
        if (Object.ReferenceEquals(other, null)) return false;

        if (Object.ReferenceEquals(this, other)) return true;

        if (!this.IsDataRow == other.IsDataRow)
            return false;
        else if (this.IsDataRow)
            return this.RowData == other.RowData;
        else
            return this.RowIndex == other.RowIndex;
    }

    #endregion
}

public class TableSelectedRowsCollection : List<TableRowInfo>
{
    #region Ctor

    public TableSelectedRowsCollection()
    {
    }

    #endregion

    #region IList Members

    public bool Contains(TableRowInfo rowInfo)
    {
        if (rowInfo.IsNewRow)
            return Find(rowInfo.RowIndex) != null;
        else
            return Find(rowInfo.NodeEntry) != null;
    }

    public bool Contains(int rowIndex)
    {
        return Find(rowIndex) != null;
    }

    public bool Contains(object rowData)
    {
        return Find(rowData) != null;
    }

    public bool Contains(NodeEntry nodeEntry)
    {
        return Find(nodeEntry) != null;
    }

    #endregion

    #region Helper Methods

    internal TableRowInfo Find(NodeEntry nodeEntry)
    {
        if (nodeEntry != null && this.Count > 0)
        {
            return this.FirstOrDefault(rowInfo => rowInfo.NodeEntry == nodeEntry);
        }
        return null;
    }

    internal TableRowInfo Find(int rowIndex)
    {
        if (rowIndex > 0 && this.Count > 0)
        {
            return this.FirstOrDefault(rowInfo => rowInfo.RowIndex == rowIndex);
        }
        return null;
    }

    internal TableRowInfo Find(object rowData)
    {
        if (rowData != null && this.Count > 0)
        {
            return this.FirstOrDefault(rowInfo => rowInfo.RowData == rowData);
        }
        return null;
    }

    internal TableRowInfo Find(TableRowInfo rowInfo)
    {
        if (rowInfo != null && this.Count > 0)
        {
            return this.FirstOrDefault(item => item.NodeEntry == rowInfo.NodeEntry);
        }
        return null;
    }

    internal List<int> GetRowIndexes()
    {
        var rowIndexes = new List<int>();
        if (this.Count > 0)
        {
            this.ForEach(rowInfo => rowIndexes.Add(rowInfo.RowIndex));
        }
        return rowIndexes;
    }

    #endregion
}


texts: Simulating a scale, balancing weight from lists

texts:
I have simulated balancing a scale by having each side total the same weight.

The scale has two weights (left and right side) and some spare weights:

weights = [3, 4]
spare_weights = [1, 2, 7, 7]

A maximum of two weights can be used from the spare weights to balance the scale. The spare(s) may be on a single side or split between both.

The output should be the minimum number of weight needed to balance the scale.

import itertools

weights = [3, 4]
spare_weights = [1, 2, 7, 7]
c = enumerate([subset for l in range(0, 3) for subset in itertools.combinations(spare_weights, l)])

cc = cc = list(itertools.combinations(c, 2))

left, right = weights
qualifying_combos = []
for c in cc:
    l, r = c
    if sum(l[1]) + left == sum(r[1]) + right:
        qualifying_combos.append(list(l[1]) + list(r[1]))
    elif sum(l[1]) + right == sum(r[1]) + left:
        qualifying_combos.append(list(l[1]) + list(r[1]))
print(min(qualifying_combos, key=len))

output:

[1]

Is there a more elegant way to code this?


texts: A primitive folder listing implementation on Windows

texts:
I am a recent graduate in computer programming and failed so far to get an internship or a job in the business so I am trying my best to learn from online source.
I am trying to implement a dir-like command on Windows, going through a folder and list all files and folder.

What I've learned is to avoid using namespace std; and making the includes in alphabetical orders.

In this code, I am obviously mixing c and c++, good or bad?
I am also using Digital Mars as a compiler, I'm trying to avoid installing heavy IDEs and compilers like VS.

All thoughts and critiques are welcome.

#include <iostream>
#include <io.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <windows.h>

bool DirectoryExists( const char* absolutePath ){

if( _access( absolutePath, 0 ) == 0 ){

    struct stat status;
    stat( absolutePath, &status );

    return (status.st_mode & S_IFDIR) != 0;
}
return false;
}

char* replace(const char *s){

char* p = new char[strlen(s)+1];
int i=0;

for (i=0;s[i];i++)
if (s[i]=='\\')
    p[i] ='/';
else
    p[i]=s[i];

if (p[i-1] == '/')
    p[i]='\0';
else
{
    p[i]='/';
    p[i+1]='\0';
}

return p;
}

void dirc (const char* destpath){

HANDLE hFind;
WIN32_FIND_DATA FindFileData;
char filename[256];
size_t i=1;

 if((hFind = FindFirstFile(destpath, &FindFileData)) != INVALID_HANDLE_VALUE)
 {
  do    {
        sprintf (filename, "echo %d-%s", i, FindFileData.cFileName);
        system (filename);
        i++;
        }
while(FindNextFile(hFind, &FindFileData));

FindClose(hFind);
}
}

int main(int argc, char**argv) {

const char* path = argv[1];
char* fspath;

if (argv[1] == NULL)
    {
    std::cout <<"No path provided"<<std::endl;
    return 0;
    }

else
    if ( DirectoryExists(path) )
        std::cout <<"Provided path is "<<path<<std::endl;
    else
        {
        std::cout <<"Path doesn't exist"<<std::endl;
        return 0;
        }
 fspath = replace(path);
 char* destpath = (char *) malloc (strlen(fspath)+6);
 destpath = strcat (fspath,"*.*");
 dirc (destpath);
 free (destpath);

return 0;
}


texts: Add Number to First Number on Each Line of File then Write to Another File - Python

texts:
Python program adds a value to the first number in a fixed width file of variable length. Normally one line header. Before user deletes original file and renames new file they need to check it.

How can the error handling be improved?

# Add number to first number on each line of file then write to another file
#
# Initialise
infile = 'egtxt.prn'
hdrln = 1
llen = 0
fw = 7  # Field width of first number on line
add = 80.0  # Add value to first number on line

print ('Processing {}, first number is {} characters wide, adding {} ...'.format(infile, fw, add))

ifile = open(infile, 'r')
tfile = open(infile+'.out', 'w')
# Skip header
line = ifile.readline()
tfile.write (line)

while True:
    line = ifile.readline()
    if not line:
        break
    llen = len(line) - fw
    tfile.write ('{:{sfw}.{sprec}f}{}'.format(float(line[:fw])+add, line[-llen:], sfw=str(fw), sprec='2'))

# Finalise
ifile.close()
tfile.close()
print (' done.')

Sample egtxt.prn follows:

ID      Name               Address                         Comment
   2.88 Barnett, Irene A.  P.O. Box 829, 4484 Aliquet Ave  viverra. Maecenas iaculis
  30.58 Irwin, Honorato X. Ap #446-1219 Nisi. Road         dui
3428.21 Talley, Bree S.    862-3586 Duis Ave               leo. Morbi
 176.12 Hensley, Kai T.    Ap #842-3806 Class Street       eu


texts:
I have built a generator that, using the GitHub API, creates a dictionary containing a tree of all the resources in any GitHub repo. It uses the function git_tree, which takes one argument, a repo-string (repo-author/repo-name). For example, this repo only contains one file, a README. If we pass in the repo-string, and format the end result, this is what we get:

>> json.dumps(git_tree("githubtraining/github-move"), indent=3)
{
   "github-move": {
      "files": [
         "README.md"
      ],
      "dirs": {}
   }
}

You can see that it returns a dict with a key/value pair of {repo_name: tree}. So the github_move item contains a list of all files in that directory, and a dict with more nested directories. Obviously, in this repository there aren't any other directories, so that dict is just blank.

For sake of purpose, here is the tree of this repo (it was too long to put in the post). You can see each directory and subdirectory has its own files list and dirs dict.

Here's the code (repl.it online program for testing):

import requests
from pprint import pprint
from functools import reduce
import operator
import json
from itertools import chain, repeat, islice

class GitError(Exception): pass

def intersperse(delimiter, seq):
  return list(islice(chain.from_iterable(zip(repeat(delimiter), seq)), 1, None))

def _get_from_dict(dataDict, mapList):
  return reduce(operator.getitem, mapList, dataDict)

def _append_in_dict(dataDict, mapList, value):
  _get_from_dict(dataDict, mapList[:-1]).append(value)

def _get_sha(author, repo):
  try:
    return requests.get('https://api.github.com/repos/{}/{}/branches/master'.format(author, repo)).json()['commit']['commit']['tree']['sha']
  except KeyError as ex:
    raise GitError("Invalid author or repo name") from ex

def _get_git_tree(author, repo):
  return requests.get("https://api.github.com/repos/{}/{}/git/trees/{}?recursive=1".format(author, repo, _get_sha(author, repo))).json()["tree"]

def git_tree(repostring):
  author, repo = repostring.split("/")
  tree = {repo: {"files": [], "dirs": {}}}
  for token in _get_git_tree(author, repo):
    if token["type"] == "tree" and "/" not in token["path"]:
      tree[repo]["dirs"].update({token["path"]: {}})
      tree[repo]["dirs"][token["path"]].update({"files": [], "dirs": {}})
    elif token["type"] == "tree" and "/" in token["path"]:
      temp_dict = {}
      a = list(reversed(token["path"].split("/")))
      for k in a[:-1]:
        temp_dict = {k: {"files": [], "dirs": temp_dict}}
      tree[repo]["dirs"][a[-1]]["dirs"] = temp_dict
    elif token["type"] == "blob":
      path = token["path"].split("/")
      if len(path) == 1:
        tree[repo]["files"].append(path[0])
      else:
        dict_path = [repo, "dirs"] + intersperse("dirs", path[:-1]) + ["files", path[-1]]
        _append_in_dict(tree, dict_path, dict_path[-1])
  return tree

print(json.dumps(git_tree("githubtraining/caption-this"), indent=3))

(The json.dumps is just there for easy viewing, it can be ommited).

My questions:

Is it too messy? I look back at this function and it looks a bit cluttered and all over the place. Is that the case, or am I just going crazy?
Do I have any unnecessary code in there?
Is there anything else you deem wrong with the program?


texts: Strongly-connected component for a graph

texts:
I implemented a strongly connected graph code in C++.

matrix_graph.h

#pragma once
#include "stdafx.h"

class matrix_graph
{
private:
    int** v;
    int vertexes;
public:
    matrix_graph(int**, int);
    ~matrix_graph(void);
    void reverse();
    int get_max_vertexes();
    bool is_connected(int i,int j);
};

matrix_graph.cpp

#include "stdafx.h"
#include <iostream>
#include "matrix_graph.h"

using namespace std;

matrix_graph::matrix_graph(int** g, int N)
{
    v = g;
    vertexes = N;
}

matrix_graph::~matrix_graph(void)
{}

void matrix_graph::reverse()
{
    for(int i=0;i<vertexes;i++)
        for(int j=0;j<vertexes;j++)
        {
            if(v[i][j] == 1 && v[j][i]==0){
                v[j][i] = -1;
                v[i][j] = 0;
            }
        }

    for(int i=0;i<vertexes;i++)
        for(int j=0;j<vertexes;j++)
        {
            if(v[i][j] == -1 )
                v[i][j] = 1;
        }
}

int matrix_graph::get_max_vertexes()
{
    return vertexes;
}

bool matrix_graph::is_connected(int i,int j)
{
        return (v[i][j]==1);
}

Main code:

enum Color {WHITE,GREY,BLACK};

void matrix_dfs_visit(matrix_graph m , int i , std::list<int>& q , Color* c)
{
    int N = m.get_max_vertexes();
    c[i] = GREY;
    for(int j=0;j<N;j++){
        if(i!=j){
            if( m.is_connected(i,j))
                if(c[j] == WHITE)
                  matrix_dfs_visit(m,j,q,c);
        }
    }
    c[i] = BLACK;
    q.push_front(i);
}

void dfs(matrix_graph m, std::list<int>& visited_vertexes_in_order )
{
    int N = m.get_max_vertexes();
    Color* c = new Color[N];
    for(int i=0;i<N;i++)
        c[i] = WHITE;
    for(int i=0;i<N;i++)
        if(c[i] == WHITE)
            matrix_dfs_visit(m,i,visited_vertexes_in_order ,c);
}

void dfs_transpose(matrix_graph &m , std::list<int> &visited_vertexes_in_order)
{
    int N = m.get_max_vertexes();

    Color* c = new Color[N];
    for(int i=0;i<N;i++)
        c[i] = WHITE;

    for(list<int>::iterator iter = visited_vertexes_in_order.begin();iter != visited_vertexes_in_order.end();iter++){
        int scc_head = *iter;
        if(c[scc_head] == WHITE){
            list<int> scc;
            matrix_dfs_visit(m,scc_head ,scc,c);
            print_scc(scc);
        }
    }
}

void print_scc(list<int> & l){
    cout << "Strongly Connected Component:";
    for(list<int>::iterator iter=l.begin(); iter !=l.end();iter++)
        cout<< " "<<*iter;
    cout<<"\n";
}

void get_strongly_connected_component(matrix_graph &m)
{
    list<int> visited_vertexes_in_order;
    dfs(m,visited_vertexes_in_order);
    m.reverse();
    dfs_transpose(m,visited_vertexes_in_order);
}

void process()
{

    int v[7][7] = {
        {0,1,0,0,0,0,0},
        {0,0,1,1,0,0,0},
        {1,0,0,0,0,0,0},
        {0,0,0,0,1,0,0},
        {0,0,0,0,0,1,0},
        {0,0,0,1,0,0,1},
        {0,0,0,0,0,0,0}
    };

    int* v_ptr[7] = {v[0],v[1],v[2],v[3],v[4],v[5],v[6]};
    matrix_graph m(&v_ptr[0],7);
    get_strongly_connected_component(m);
}

Please give any reviews, especially on the reverse function and the whole design. Naming convention here is also pretty weak I think.


texts: Extremely simple stack implementation using a vector

texts:
Please review my simple Stack:

template<class T>
class Stack {
public:
    Stack() = default;
    Stack(std::initializer_list<T> i) :n{} {
        for (auto& x : i) {
            elem.push_back(x);
            ++n;
        }
    }
    Stack(const Stack<T>&) = default;
    Stack(Stack<T>&&) = default;
    Stack& operator=(const Stack&) = default;
    Stack& operator=(Stack&&) = default;
    ~Stack() = default;
    int size() const {
        return n;
    }
    bool isEmpty() const {
        return (n == 0);
    }
    void push(T);
    T pop();
    T& peek();

private:
    std::vector<T> elem;
    int n;
};

template<class T>
void Stack<T>::push(T t) {
    elem.push_back(t);
    ++n;
}

template<class T>
T Stack<T>::pop() {
    if (isEmpty()) {
        throw std::out_of_range("underflow");
    }
    T t = *elem.erase(elem.end()-1);
    --n;
    return t;
}

template<class T>
T& Stack<T>::peek() {
    if (isEmpty()) {
        throw std::out_of_range("underflow");
    }
    return elem[n-1];
}

How can I make this code better and build more complicated data structures based on stacks?


texts: TCP retarder for network delay simulation

texts:
I would like to simulate delay over network, for that I have implemented a simple retarder (=introduce random delay while maintaining order of messages) using Boost to handle sending itself. It appears to work as intended. However, since parallel programming is not trivial especially when coupled with networking, I would like to hear feedback more experienced C++ programmer. Mostly, I am concerned about the parallelization(deadlocks, resource leaks) and possible side effects on the communication I might have missed.

class SendRetarder
{
    typedef std::pair<session_ptr, message_t> args_t;//to whom and what
    std::queue<args_t> message_queue;//messages to be sent
    std::mutex m;
    std::condition_variable cv;
    const size_t max_wait = 10000;

    void send_loop()
    {
        while (true)
        {
            boost::system::error_code ec;
            args_t args;
            size_t wait;
            {
                std::unique_lock<std::mutex> lk(m);
                cv.wait(lk, [&] { return !message_queue.empty(); });
                wait = (rand() % max_wait) / message_queue.size();//to prevent unchecked growing
                args = message_queue.front();
                message_queue.pop();
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
            boost::asio::write(args.first->socket_, boost::asio::buffer(&args.second, sizeof(message_t)), ec);
            if (ec) std::cerr << ec.message().c_str() << std::endl;
        }
    }

public:
    SendRetarder() {
        std::thread(&SendRetarder::send_loop, this).detach();
    }

    void async_send(session_ptr client, message_t& msg)
    {
        {
            std::lock_guard<std::mutex> lk(m);
            message_queue.push(args_t(client, msg));
        }
        cv.notify_one();
    }
};

where message_t is the contents of the message consisting of integer types and session_ptr is a smart pointer wrapper around socket shared with client itself:

struct message_t {
    msg_id_t message_id;
    tag_t message_tag;
    sender_t sender_id;
    union { uint32_t value; bool success; } data;
}

typedef std::shared_ptr<Session> session_ptr;
class Session : public std::enable_shared_from_this<Session> {
    tcp::socket socket_;
    sender_t name_;
    //...
}


texts: Retrieve filename and ID with Google Drive API in C#

texts:
I am trying to retrieve filename and ID list with Google Drive API (the latest Drive API version v3 is used here) as a first step in order to analyze and manipulate these files on Google Drive. The experimental implementation is as below. (Note: credentials.json file is needed and the step to generate this file is here. )
The experimental implementation
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GoogleDriveFileManager
{
    class Program
    {
        static string[] Scopes = { DriveService.Scope.DriveReadonly };
        static string ApplicationName = "GoogleDriveFileManager";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine($"Credential file saved to: {credPath}");
            }

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 1000;
            listRequest.Fields = "nextPageToken, files(id, name)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            Console.WriteLine("Files:");
            Console.WriteLine($"file.Name{new String('\t', 6)}file.Id{new String('\t', 8)}file.ModifiedTime");
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    Console.WriteLine(
                        $"{file.Name.PadRight(56)}{file.Id.PadRight(36)}{file.ModifiedTime}"
                        );
                }
            }
            else
            {
                Console.WriteLine("No files found.");
            }
            Console.Read();
        }
    }
}

If there is any possible improvement about potential drawback or unnecessary overhead, please let me know.


texts:
This is my naive approach on implementing a Sudoku solver, which is okay for simple Sudokus like this:

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

However, it is rather slow for hard Sudokus like this:

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

The challenge description is:

  Write a function that will solve a 9x9 Sudoku puzzle. The function
  will take one argument consisting of the 2D puzzle array, with the
  value 0 representing an unknown square.

  The Sudokus tested against your function will be "insane" and can have
  multiple solutions. The solution only needs to give one valid solution
  in the case of the multiple solution sodoku.

  It might require some sort of brute force.

  Tests: 100 random tests and 5 assertions per test

  Time limit: 12sec

My code:

def sudoku(board):
    (x, y) = find_empty_cell(board)
    if (x, y) == (-1, -1):
        return True

    for i in {1,2,3,4,5,6,7,8,9}:
        if valid(x,y,i,board):
            board[x][y] = i
            if sudoku(board):
                return board
            board[x][y] = 0

def valid(x,y,n,board):
    #check row and column
    for i in range(9):
        if board[x][i] == n or board[i][y] == n:
            return False

    #check box
    new_x = x//3 * 3
    new_y = y//3 * 3
    for i in range(3):
        for j in range(3):
            if board[new_x + i][new_y + j] == n:
                return False

    return True

def find_empty_cell(board):
    for i in range(9):
        for j in range(9):
            if board[i][j] == 0:
                return (i,j)

    return (-1,-1)

I am trying to succeed in passing a coding challenge in a competitive platform, which my specific code times out.


texts: What could be bad from using this form of dependancy injection?

texts:
I have a custom framework that I am not sure if certain things I have applied are wrong and if so, just why.

I am not well versed in any framework, so I was forced to use mine.

Here is an example of a controller found in /app/controllers/UserProfile.php

<?php

    class UserProfile
    {
       public function showUserProfile($import)
       {
         // get view object
         $view =  $import["load"]::view();
         // get orm object
         $db   =  $import["load"]::orm();
         // get form builder object
         $form =  $import["load"]::formBuilder();
         //  extract username & id from current url. i.e. dev.foo.com/john/11
         list($userName, $id) = $import["args"];
         // get view object, for loading templates
         $view::header();   // ~ require  .. view/header.php
         // DATABASE QUERY.
         $users = $db->table("users");
         // SELECT username, age, country from users where username = $username AND id = $id;
         $select = $users->read(["username, age, country", [$username, $id]]);
         $view::body(["select"=>$select]);
       }
    }
?>

And if you are wandering how the DI is being handled, here is how:

<?php

class ServiceProvider
{

    function service($getService)
    {

        switch ($getService) {
            case 'orm':
                return new \foo\bar\orm(new \pdo('....'))
                break;

            case 'view':
                $views_dir = __DIR__.'../path/to/views/dir';
                return new \foo\bar\viewCreatror($views_dir);
                break;

            case 'formBuilder':
                return new \foo\bar\formBuilder('..');
                break;

            default:
                # code...
                break;
        }

    }
}
?>

Now, since I also need to get the URL fragments like :blog-title/:id.
I allow my router to handle that like this.

<?php
namespace foo\bar;
class Router
{
    function add(){}
    function get()
    {
        $service = new \foo\bar\ServiceProvider;
        $url     = $this->getExplodedUrl;
        // IF URL matches, and controller + method exists.
        return (new $controller)->$method(["load"=>$service, "args"=>$url]);
    }
}

The thing is, that everything works well, but to improve it, I need to know which parts need the most urgent attentions.


texts:
I am trying to reverse the lines of a file by reading the file through an array.

Is there a more efficient and quicker way of achieving this?

import java.util.Scanner;
import java.io.*;

class ReverseNumbers {

    public static void main(String[] args) throws FileNotFoundException {

        File file = new File("numbers.txt");
        Scanner Scan = new Scanner(file);

        int numoflines = 0;
        while(Scan.hasNextLine()) {
            Scan.nextLine();
            numoflines++;
        }
        Scan.close();
        Scan = new Scanner(file);

        int buffer[] = new int[numoflines]; //size

        for(int i=0; i<buffer.length; i++) {
            buffer[i] = Scan.nextInt();
        }

        for(int i=buffer.length-1; i>=0; i--) {
            int reverse = buffer[i];
            System.out.println(reverse);
        }
    }
}


texts:
I'm trying to implement union from the standard Data.List library. I know it's reinventing the wheel, but reimplementing functions is how I learn things. Any feedback at all would be helpful!

union' :: (Eq a) => [a] -> [a] -> [a]
union' [] _ = []
union' _ [] = []
union' xs ys = nub' $ xs ++ ys where
    nub' [] = []
    nub' (x:xs)
        | not $ x `elem` xs = x : nub' xs
        | otherwise = nub' xs

This code works, but it strikes me as verbose. union is the opposite of intersect, which does not require a helper where statement:

intersect' :: (Eq a) => [a] -> [a] -> [a]
intersect' [] _ = []
intersect' _ [] = []
intersect' (x:xs) list
    | x `elem` list = x : intersect' xs list
    | otherwise = intersect' xs list

How can I make my union function resemble the elegance of my intersect function?

Revision here


texts: Subclass of AtomicReference with atomic function application

texts:
Update: Now that https://github.com/bionicspirit/scala-atomic is available, I have less of a need for this.

Am I doing anything bad? I wrote this class to allow modifying an atomic reference with the assurance that two threads modifying it will not step on each other's toes. To illustrate:

val x = new AtomicRef(List.empty[String])
def compute(s: String) = { Thread.sleep(1000); s }
def updateX(s: String) = x.transform(strings => compute(s) :: strings)

The idea is to guarantee that if two threads call updateX many times, all the strings passed to updateX will wind up in x.

run is like transform but it lets you return a value to the caller other than the value you're setting into the reference.

Here is the class:

/**
 * A subclass of java.util.concurrent.atomic.AtomicReference[A]
 * that adds the ability to atomically modify its value relative to itself.
 */
class AtomicRef[A](init: A) extends java.util.concurrent.atomic.AtomicReference[A](init) {
  /**
   * Update the value atomically by applying a function to it.
   * Uses `compareAndSet` and will keep trying until it succeeds.
   */
 final def transform(f: A => A): A = run { a =>
    val ret = f(a)
    (ret, ret)
 }
  /**
   * Update the value atomically by applying a computation to it.
   * The computation returns a pair of values, of which the
   * `AtomicRef` is updated to the first.
   * Uses `compareAndSet` and will keep trying until it succeeds.
   * @return the second value of the computation
   */
  @annotation.tailrec final def run[B](f: A => (A, B)): B = {
    val a = get
    val (a2, b) = f(a)
    if(compareAndSet(a, a2)) b
    else {
      Thread.sleep(10)
      run(f)
    }
  }
}

To put it in different terms, this sort of abstracts over doing something like this (in Java; List here is a fictional immutable list):

AtomicReference<List<String>> ref = new AtomicReference<List<String>>(new List());
void update(String s) {
  while(true) {
    List<String> a = ref.get;
    // now do "f(a)"
    Thread.sleep(1000); // pretend it takes a long time to run the computation
    List<String> b = a.prepend(s);
    if(compareAndSet(a, b)) return b;
    else {
      Thread.sleep(10);
      // loop the while instead of tail recursion
    }
  }
}


texts:
[NOTE] This question can be depreciated in favor of version 0.2.

The purpose of this code is to produce a universe of points, randomly generated around predetermined centroids, provided as a vector of vector. The final product is a file of sample points, to be used for fake data analysis in another program. The objective here was brevity and speed - I feel the code could be vastly concisified, but it is working.

Detailed description of the primary algorithm parameters is in the .h.

// clustergen.h

#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <random>
#include <chrono>

#ifndef CLUSTERGEN_H
#define CLUSTERGEN_H

// POINT GENERATION - COMMON USER DEFINED VARIABLES
double const PT_BOUND = 10;   // Defines the +/- around a centroid for point generation if UNIFORM
double const PT_SD = 5;       // Defines the stddev around a centroid for point generation if NORMAL

// PRIMARY ALGORITHM
void clustergen(unsigned int k, std::vector<std::vector<double>> &c, std::string file_out, std::string file_rpt, bool csv, bool norm);
// Produces [k] points in [file_out]; all points are separated by line breaks
// If [csv] = 0, dimensions for each point are whitespace-separated
// If [csv] = 1, dimensions for each point are comma-separated
// If [norm] = 0, points will be UNIFORMLY generated around centroids
// If [norm] = 1, points will be NORMALLY generated around centroids
// [c] is a vector of vectors; it's size is the number of centroids
// The first insertion in [c] sets dimensional precedence; dimensional mismatches are always omitted/avoided.

#endif //CLUSTERGEN_H

// clustergen.cpp

#include "clustergen.h"

void clustergen(unsigned int k, std::vector<std::vector<double>> &c, std::string file_out, std::string file_rpt, bool csv, bool norm) {

    std::ofstream fout, rout;
    fout.open(file_out);
    rout.open(file_rpt);

    rout << "CLUSTERGEN STATUS REPORT FOLLOWS...\n";

    unsigned int ct = 0;
    unsigned int cl_ct = 0;

    for (std::vector<std::vector<double>>::iterator c_iter = c.begin(); c_iter != c.end(); ++c_iter) {
        unsigned int subsec;
        std::default_random_engine gen(std::chrono::system_clock::now().time_since_epoch().count());

        (k % c.size() == 0) ? (subsec = (k + ct) / c.size()) : (subsec = 1 + ((k + ct) / c.size()));
        k -= subsec;

        for (unsigned int i = 0; i < subsec; i++) {
            std::vector<double>::iterator d_iter = (*c_iter).begin();
            while (d_iter != (*c_iter).end()) {
                double num;
                if (norm) {
                    std::normal_distribution<double> distr((*d_iter), PT_SD);
                    num = distr(gen);
                } else {
                    std::uniform_real_distribution<double> distr((*d_iter) - PT_BOUND, (*d_iter) + PT_BOUND);
                    num = distr(gen);
                }
                fout << num;
                std::vector<double>::iterator temp_d_iter = d_iter;
                std::vector<std::vector<double>>::iterator temp_c_iter = c_iter;
                if (++temp_d_iter != (*c_iter).end()) {
                    (csv == 0) ? (fout << " ") : (fout << ",");
                } else if ((i != subsec - 1) || (++temp_c_iter != c.end())) {
                    fout << "\n";
                }
                ++d_iter;
            }
            ++ct;
        }
        rout << "\n" << div << " points ";
        (norm) ? (rout << "normally") : (rout << "uniformly");
        rout << " distributed around centroid " << ++cl_ct << " ...";
    }
    rout << "\n\n" << ct << " total points assigned.";
}

// main.cpp
#include "clustergen.h"

int main() {

    std::vector<std::vector<double>> v = {{0,0}, {50,30}, {100,120}};
    clustergen(110, v, "clustergen_out.dat", "clustergen_report.dat", 1, 0);

}


texts:
A few days ago I found myself learning lolcode. It turns out it's (almost) a real language and capable of handling (pseudo-)serious problems. So, let's try some (pseudo-)serious code this time.

Project Euler 14

A Collatz sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using this rule, a sequence can be generated.

Which starting number, under one million, produces the longest chain?

OBTW
    WHICH STARTIN NUMBR, UNDR WAN MILLION, PRODUCEZ TEH LONGEST CHAIN?
TLDR

HAI 1.3

  HOW IZ I collatz YR currentNumber
    I HAS A cowntr ITZ 1
    IM IN YR collatzLoop
      BOTH SAEM 0 AN MOD OF currentNumber AN 2, O RLY?
        YA RLY, currentNumber R QUOSHUNT OF currentNumber AN 2
        NO WAI, currentNumber R SUM OF PRODUKT OF currentNumber AN 3 AN 1
      OIC
      cowntr R SUM OF cowntr AN 1
      BOTH SAEM currentNumber AN 1, O RLY?
      YA RLY, FOUND YR cowntr, OIC
    IM OUTTA YR collatzLoop
  IF U SAY SO

  HOW IZ I longestCollatz YR maxNumber
    VISIBLE maxNumber
    I HAS A maxLengthFound ITZ 0
    I HAS A currentLength ITZ 0
    I HAS A longestAtValue ITZ 0
    I HAS A cowntr ITZ 1
    IM IN YR maxCollatzLoop
      currentLength R I IZ collatz YR cowntr MKAY
      DIFFRINT currentLength AN SMALLR OF currentLength AN maxLengthFound, O RLY?
      YA RLY, maxLengthFound R currentLength, longestAtValue R cowntr, OIC
      cowntr R SUM OF cowntr AN 1
      BOTH SAEM cowntr AN maxNumber, O RLY?
      YA RLY, FOUND YR longestAtValue, OIC
    IM OUTTA YR maxCollatzLoop
  IF U SAY SO

  VISIBLE I IZ longestCollatz YR 1000000 MKAY

KTHXBYE

Took only 3 minutes to execute on my machine, lightning fast!

Of-course, in any real language with a real implementation, this should take under 5 seconds. But lolcode isn't very fast and it's lacking a lot of performance constructs. For example, usually you'd memoization or recursion. I'm pretty sure the latter can't be done and the former would get very ugly very fast.

How can I take advantage of the features that are available in this language to the fullest extent to improve the performance of my program?


texts:
Many implementations of Sieve of Eratosthenes (used to find prime numbers up to a given n) use a temporary mutable array to keep track of which numbers are composites. I'm looking to write a purely functional version that has the same runtime complexity:

(define (primes-up-to n)
  (cons 2 (unfold null?
                  car
                  (compose remove-odd-multiples car+cdr)
                  (iota (quotient (- n 1) 2) 3 2))))

(define (remove-odd-multiples n xs)
  (let recur ((xs xs)
              (i (* n n)))
    (cond ((null? xs) '())
          ((< (car xs) i) (cons (car xs) (recur (cdr xs) i)))
          ((< i (car xs)) (recur xs (+ i n n)))
          (else (recur (cdr xs) (+ i n n))))))

(Should work on any Scheme implementation that supports SRFI 1. If your implementation doesn't provide compose, use (lambda (x) (remove-multiples (car x) (cdr x))) instead.)

What I'm hoping reviewers can help with: Is there a way to make remove-odd-multiples¹ less verbose (perhaps using higher order functions) or more efficient², without increasing the runtime complexity (so any kind of filter or remove involving non-constant-time predicates is no go)?

¹ Since xs does not contain even numbers, there's no point dropping even multiples, hence remove-odd-multiples. The only difference from a more general remove-multiples is that it advances i by 2n instead of n each time.

² I've done some casual timing tests on (primes-up-to 100000) on DrRacket 6.5 and the right-folding version you see above is faster than a left-folding version. (I mention this preemptively because many Scheme answerers on Stack Overflow lean towards left-folding solutions.) Here's the left-folding version I time-tested with:

(define (primes-up-to n)
  (reverse (unfold-right null?
                         car
                         (compose remove-odd-multiples car+cdr)
                         (iota (quotient (- n 1) 2) 3 2)
                         '(2))))

(define (remove-odd-multiples n xs)
  (let loop ((result '())
             (xs xs)
             (i (* n n)))
    (cond ((null? xs) (reverse result))
          ((< (car xs) i) (loop (cons (car xs) result) (cdr xs) i))
          ((< i (car xs)) (loop result xs (+ i n n)))
          (else (loop result (cdr xs) (+ i n n))))))


texts:
the problem is to find total number of sub-lists from a given list that doesn't contain numbers greater than a specified upper bound number say right and sub lists max number should be greater than a lower bound say left .Suppose my list is: x=[2, 0, 11, 3, 0] and upper bound for sub-list elements is 10 and lower bound is 1 then my sub-lists can be [[2],[2,0],[3],[3,0]] as sub lists are always continuous .My script runs well and produces correct output but needs some optimization

def query(sliced,left,right):
    end_index=0
    count=0
    leng=len(sliced)
    for i in range(leng):
        stack=[]
        end_index=i

        while(end_index<leng and sliced[end_index]<=right):

            stack.append(sliced[end_index])
            if max(stack)>=left:
                count+=1
            end_index+=1

    print (count)

origin=[2,0,11,3,0]
left=1
right=10
query(origin,left,right)

output:4


texts: Split string in half and change case accordingly

texts:
I found the following challenge online:

Create a function that takes a string and returns that string with the first half lowercased and the last half uppercased.
eg: foobar == fooBAR
If it is an odd number then 'round' it up to find which letters to uppercase.

That sounded easy enough but I found the last requirement a little tricky. Eventually this is what I came up with:

def sillycase(silly):
    length=len(silly)
    firstHalf = silly[:length / 2 + (length % 2)].lower()
    secondHalf = silly[length / 2 + (length % 2):].upper()
    return firstHalf + secondHalf

but that seems repetitive and inefficient.
What could I have done to make it slicker, without sacrificing readability? I was actually a little surprised python didn't have a built in method to split a string in half.


texts:
I have created a simple array-based Stack class with some methods like the actual Stack in Java.

I am testing this for mistakes, but since I am learning Java, my tests may not be as comprehensive as they should.

import java.util.*;

public class SJUStack<E> {
    // Data Fields
    private E[] theData;
    private int topOfStack = -1;
    private static final int INITIAL_CAPACITY = 10;
    private int size = 0;
    private int capacity = 0;

    // Constructors
    public SJUStack(int initCapacity) {
        capacity = initCapacity;
        theData = (E[]) new Object[capacity];
    }

    public SJUStack() {
        this(INITIAL_CAPACITY);
    }

    // Methods
    public E push(E e) {
        if(size == capacity) {
            reallocate();
        }
        theData[size] = e;
        size++;
        topOfStack++;

        return e;
    } // End push(E e) method

    public E peek() {
        if(empty()) {
            throw new EmptyStackException();
        }
        return theData[topOfStack];
    } // End peek() method

    public E pop() {
        E result = peek();
        theData[topOfStack] = null;
        size--;
        topOfStack--;
        if(size <= (capacity/4) && capacity >= INITIAL_CAPACITY) {
            shrink();
        }
        return result;
    } // End pop() method

    public boolean empty() {
        return size == 0;
    } // End empty() method

    private void reallocate() {
        capacity *= 2;
        theData = Arrays.copyOf(theData, capacity);
    } // End reallocate() method

    private void shrink() {
        capacity /= 2;
        theData = Arrays.copyOf(theData, capacity);
    } // End shrink() method

    public String toString() {
        return Arrays.toString(theData);
    } // End toString() method

    public int size() {
        return size;
    } // End size() method
}


texts:
I'm creating a Mongoose model for a web service. I have a secondary index on facultyId because majority of the reads would want to search by facultyId. I've included some statics on the model in order to make it simple for people to query.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

mongoose.Promise = global.Promise;

const GAPFApplicationSchema = new Schema({
  facultyId: { type: Number, index: true },
  created: Number, // use UNIX time stamps for all dates
  lastModified: Number,
  status: { type: String, enum: ["SUBMITTED", "BUDGET_ALLOCATED"] },
  attachedDocuments: [
    {
      name: String,
      link: String,
      attachedDate: Number
    }
  ]
});

GAPFApplicationSchema.static("findByFacultyId", function(facultyId, callback) {
  return this.findOne()
    .where("facultyId")
    .equals(facultyId);
});

GAPFApplicationSchema.static("submit", function(gapf, callback) {
  return this.findOneAndUpdate(
    { facultyId: gapf.facultyId },
    gapf,
    { upsert: true }, // create it if doesn't exist
    callback
  );
});

const GAPFApplication = mongoose.model(
  "GAPFApplication",
  GAPFApplicationSchema
);

export { GAPFApplication };

I haven't used Mongoose before, so I was hoping to get some review on the approach taken here. The code is pretty short, so I didn't think there would be much to address.


texts: Eassily create a logger in python for many modules with loglevel set according to command line arguments

texts:
I'm trying to learn writing python programs in a modular way as much as possible. One of the issues I've had difficulty to solve is parsing command line arguments (with argparse) and having a logger object in all my modules which it's name will be the __name__ of the module and it's log level identical across all modules.

I've even posted a question on Sstack Overflow where I describe the problem more thoroughly but I would like to gain some confidence with the solution I've constructed before posting an answer to my own question.

This is the scheme I've come up with:

core/__init__.py:

from .argpconf import Argpconf

import logging
argpconf = Argpconf()
_loglevel = argpconf.get_loglevel()
class Logger(logging.Logger):
    def __init__(self, name, level=_loglevel):
        self.name = name
        logging.Logger.__init__(self, name, level)
        self.addHandler(argpconf.get_loghandler())

core/argpconf.py:

from argparse import ArgumentParser
import logging

class Argpconf():
    def __init__(self):
        """
        Define command line arguments parser
        """
        self.argp = ArgumentParser(
            description="Generator for shell, ranger and vim commands for fzf based shortcuts"
        )
        self.argp.add_argument(
            '-v', '--verbose',
            dest='verbosity',
            default=2,
            action='count',
            help='increase verbosity, use multiple times to increase more'
        )
        self.args = vars(self.argp.parse_args())
    def get_loglevel(self):
        # Convert logging level to the proper scale
        logging_level = self.args['verbosity'] * 10
        # make sure a level higher then 50 won't be passed to setLevel
        logging_level = min(logging_level, 50)
        # reverse the numbers of so a higher verbosity will set a higher log level
        logging_level = 60 - logging_level
        return logging_level
    def get_logformat(self):
        if self.args['verbosity'] > 2:
            return logging.Formatter('%(name)s - %(levelname)s - %(message)s')
        else:
            return logging.Formatter('%(message)s')
    def get_loghandler(self):
        handler = logging.StreamHandler()
        handler.setFormatter(self.get_logformat())
        return handler

Every other file that would like to use a logger:

from core import Logger
logger = Logger(__name__)

...

Notes

The Logger class defined in core/__init__.py is based on this.
The function get_logformat from Argpconf sets a different format for the messages so in debugging modes the __name__ and levelname will be included, according to the verbosity set in the command line.


texts:
I would like a class to store a default string, and also store translated values for that string. The results will be stored in json. I'm looking for a peer review on how this could be improved.

My biggest problem with this is to get the string value from the class you have to use the concrete type, using var will return the object.

Translatable String Class

namespace OpenPartsBook
{
    [Serializable()]
    public class TranslatableString
    {
        [JsonProperty]
        private string Text;
        public List<Translation> Translations { get; set; }

        public TranslatableString()
        {
            Translations = new List<Translation>();
        }
        public TranslatableString(string value)
        {
            Translations = new List<Translation>();
            Text = value;
        }

        /// <summary>
        /// Get a translation for the string by walking up the translation hierarchy
        /// if the requested language is not found it returns the default
        /// uses ISO 3166/ISO 3166-2
        /// </summary>
        /// <param name="LanguageCode">string - language code</param>
        /// <returns>string</returns>
        public string ToTranslatedString(string LanguageCode)
        {
            string temp = String.Empty;

            int i = LanguageCode.Length;

            if (this.Translations.Any(t => t.LanguageCode.ToLower().Equals(LanguageCode.ToLower())))
            {
                temp = this.Translations.First(t => t.LanguageCode.ToLower().Equals(LanguageCode.ToLower())).Text;
            }
            else
            {

                while ((i = LanguageCode.LastIndexOf("-", i)) != -1)
                {
                    var code = LanguageCode.Substring(0, i).ToLower();

                    if (this.Translations.Any(t => t.LanguageCode.ToLower().Equals(code.ToLower())))
                    {
                        temp = this.Translations.First(t => t.LanguageCode.ToLower().Equals(code.ToLower())).Text;
                        break;
                    }

                    --i;
                }
            }

            if (String.IsNullOrEmpty(temp)) temp = Text;

            return temp;
        }

        public static implicit operator TranslatableString(string s)
        {
            return s == null ? null : new TranslatableString(s);
        }

        public static implicit operator string(TranslatableString s) { return s.ToString(); }

        public override string ToString() { return Text; }

    }
}

Translation Class

namespace OpenPartsBook
{
    [Serializable()]
    [DataContract]
    public class Translation
    {
        [DataMember(Name = "languageCode", IsRequired = true)]
        public string LanguageCode { get; set; }
        [DataMember(Name = "text", IsRequired = true)]
        public string Text { get; set; }

        public Translation()
        {

        }
    }
}

Resulting Json:

"Title": {
    "Text": "Radiator",
    "Translations": [
      {
        "languageCode": "es",
        "text": "radiador"
      },
      {
        "languageCode": "fr",
        "text": "radiateur"
      }
    ]
  }


texts: JavaScript async functions queue approach

texts:
I wrote this queue object to handle async functions in JavaScript.
I'm not sure if this is a correct approach.
Is this steady enough to run on nodeJS or it may fail/fault?

var queue = {
    callbacks: [],
    start: function(){
        this.returnVal = this.callbacks.shift()();
    },
    next: function(returnVal){
        try{
            queue.returnVal = queue.callbacks.shift()( returnVal );
        } catch(e) { console.error("oops, this function failed..:", e)}
    },
    add: function( newCallback ){ // adds new funcion to the end of the queue
        this.callbacks.push(newCallback);
    }
}

/* generic functions */

function f1(param1){
    console.log('running f1');
    console.log('param1 is:', param1);
    queue.next('this string was returned from f1'); // return
}
function f2(param1){
    console.log('running f2');
    console.log('param1 is:', param1);
    setTimeout(function(){ // simulate async
        console.log('adding f9 function to the queue');
        queue.add(f9);
        queue.next('this string was returned from f2 after adding f9 to the queue'); // f2 return
    }, 1000);
}
function f3(param1){
    console.log('running f3');
    console.log('param1 is:', param1);
    queue.next(); // f3 return
}

function f9(){
    console.log('running f9');
    queue.next('f9 returns');
}

queue.callbacks.push(f1, f2, f3);
queue.start();

the output is:

running f1
param1 is: undefined
running f2
param1 is: this string was returned from f1
adding f9 function to the queue
running f3
param1 is: this string was returned from f2 after adding f9 to the queue
running f9
oops, this function failed..: [TypeError: queue.callbacks.pop(...) is not a function]

Note that the last line error is due to queue is now empty.
Can the try catch there save nodeJS from crashing?


texts:
I'm a complete beginner of Factor, but I just managed to solved Euler Problem #1 using it, and would love to have the code reviewed. Anything that can be improved? In particular I'm wondering if there is a cleaner or more idiomatic way to write the mult3or5? word.

USING: math kernel sequences math.ranges prettyprint ;
IN: euler1

: mult? ( x y -- ? ) rem 0 = ;

: mult3? ( x -- ? ) 3 mult? ;
: mult5? ( x -- ? ) 5 mult? ;

: mult3or5? ( x -- ? ) dup mult3? swap mult5? or ;

: sumMultsOf3or5 ( seq -- n ) [ mult3or5? ] filter sum ;

: solveEuler1 ( -- ) 0 1000 (a,b) sumMultsOf3or5 . ;


texts: Counting and scoring two- and three-word phrases

texts:
I am writing a function to take a list of words and score 2 and 3 word phrases based on occurrence while removing any phrase occurrences with a score of less than 3.

As someone kinda new to python, i'm wondering if there is a better way to write this to do the same thing (the code works)

The resulting dictionary looks something like this...

{ ( "lorem ipsum", 4 ), ("quick brown fox", 3), (...) }

## -words- is a list of words
## -phrases- is the resulting dictionary with the phrase as a key and score as a value

words = ("lorem","ipsum","lorem","ipsum","quick","brown","fox")
phrases = dict()

for i, w in enumerate(words):

    w = re.sub('[^0-9a-zA-Z]+', '', w).lower()

    try:
        w1 = " " + re.sub('[^0-9a-zA-Z]+', '', words[ i + 1 ]).lower()
    except:
        w1 = ""

    try:
        w2 = " " + re.sub('[^0-9a-zA-Z]+', '', words[ i + 2 ]).lower()
    except:
        w2 = ""

    if w!="" and not w.isdigit() and len(w)>1:

        p = w + w1
        p2 = w + w1 + w2

        try:
            phrases[p] = phrases[p] + 1
        except:
            phrases[p] = 1

        try:
            phrases[p2] = phrases[p2] + 1
        except:
            phrases[p2] = 1

phrases = { k:v for k, v in phrases.items() if v > 2 }

rc = sorted(phrases.items(), key=lambda x: x[1], reverse = True)


texts:
Although it's a well-known algorithm, I thought to implement it from the perspective of a coding interview. I want to know if I can improve my code somehow. So, given the time constraint, is this a good enough solution to impress the interviewer?

class MyQueue {
    private Stack<Integer> s1;
    private Stack<Integer> s2;

    MyQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }

    public void enqueue(int item) {
        s1.push(item);
    }

    private void move() {
        if (s1.isEmpty()) {
            throw new NoSuchElementException();
        } else {
            while (!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }

    }

    public int peek() {
        if (s2.isEmpty()) {
            move();
        }
        return s2.peek();
    }

    public int dequeue() {
        if (s2.isEmpty()) {
            move();
        }
        return s2.pop();
    }
}

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();
        MyQueue q = new MyQueue();
        for (int i = 0; i < N; i++) {
            int op = s.nextInt();
            switch (op) {
                case 1:
                    int item = s.nextInt();
                    q.enqueue(item);
                    break;
                case 2:
                    q.dequeue();
                    break;
                case 3:
                    System.out.println(q.peek());
                    break;
                default:
                    System.out.println("Invalid option");
            }
        }

    }
}


texts: Javascript obj assignment/mutation in for-loops

texts:
I have a working function achieving what I want to do, but, I feel that there is a better, concise, and appropriate way to achieve this but I can't quite put my finger on how.

Given an object with (n) recipients, duplicate the message so that there is only ever one recipient and every recipient receives a unique message-id.

here is how I achieved it:

const uuidGenerator = () => Math.random();

const message = {
  message: 'hello',
  recipients: ['John', 'Susie', 'Christian'],
}

function split(obj) {
  const messages = [];
  const recipients = obj.recipients;
  let copy = obj;

  for (let i = 0; i < recipients.length; i++) {
    copy.id = uuidGenerator(),
    copy.recipient = recipients[i];
    copy.message = obj.message
    messages.push(copy);
    copy = {}
  }
  return messages;
}

const arrOfMessages = split(message)
console.log(arrOfMessages)

precisely I am not a fan of how at the end of each loop I am reassigning an obj. I feel... dirty, and it feels like the bigger an object could be the more expensive it could be... what if the message had Base64 video file within it? copying and reassigning feels like this could become more expensive (n2) in big O notation?

any help and clarification would be well appreciated!


texts: Javascript speed of an animated object (planet orbiting sun)

texts:
So I am pretty new to JavaScript and I thought I might make an animation demonstrating a planet orbiting  a sun in an elliptical orbit using Kepler's laws.
I am struggling to get the speed right. So I want the speed of the planet to be slower further away from the sun, and faster closer to the sun.
Within this method I use Keplers laws to calculate the x and y coordinate. I have also calculated the (real) velocity at each point in its trajectory (this may need to be scaled appropriately as I hope to use real astronomical data).
I tried to use a scaled version of the velocity. The velocity values produced were in the range of 10,000 to 80,000 - so I thought of using that to update theta using the following:
  this.speed = function(){
    this.theta += this.velocity/10000 ;
  }

However this didn't work and the planet disappears.
I've got full code is below:
HTML:
<canvas id="mybox"></canvas>

CSS:
canvas {
  border: 2px solid #000;
  background-color: #102233;
}

JS:
var canvas = document.getElementById('mybox');
canvas.width = window.innerWidth ;
canvas.height = window.innerHeight ;

var ctx = canvas.getContext('2d');

function sun(){
// Draws Sun at center
  ctx.beginPath() ;
  ctx.fillStyle = "orange";
  ctx.arc(canvas.width/2, canvas.height/2, 40, 0, Math.PI*2);
  ctx.fill();
};

function planet(M, G, T, e) {
  this.x = 0 ;
  this.y = 0 ;
  this.radius = 20 ;
  this.theta = 0 ;
  this.dtheta = 0.5 ;
  this.vel = 0 ;

  this.updateTheta = function() {
    if (this.theta > Math.PI){
      this.theta += this.dtheta ;
      this.dtheta += 0.001 ;

    }
    else if (this.theta < Math.PI){
      this.theta +=this.dtheta ;
      this.dtheta -= 0.001 ;
    }
    if(this.theta>=2*Math.PI || this.theta < 0) {
      this.theta = 0;
    }
  }

  this.position = function(theta) {
// Calculates position
    var R = Math.pow(((Math.pow(T,2))/((4*Math.pow(Math.PI, 2))/(G*M))),(1/3)) ;
    var a = R/(1-e) ;
    var radius = a*(1-Math.pow(e,2))/(1+e*Math.cos(theta)) ;
    this.x = radius*Math.cos(theta)*10e-10 + canvas.width/2 ;
    this.y = radius*Math.sin(theta)*10e-10 + canvas.height/2;
    this.vel = Math.sqrt(G*M*((2/radius)-(1/a))) ;
  }

  this.draw = function() {
    ctx.beginPath();
    ctx.fillStyle = 'green';
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
    ctx.fill();

    this.position(this.theta) ;
    this.updateTheta() ;
  }

}

// Values to display elliptical orbit
var G = 6.e-11;
var M = 5e+30;
var T = 1e+7;
var e = 0.6;

function update(){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  sun();
  earth.draw();
}

let earth = new planet(M, G, T, e)
setInterval(update, 50);

Any help or comments will be appreciated. Thanks!


texts:
The following code is used to show/hide components in an AngularJS app:

var vm = this;

var hideComponents = function()
{
   vm.showRegions = false;
   vm.showAccounts = false;
   vm.showOrders = false;
   vm.showInvoices = false;
   vm.showWarehouses = false;
}

vm.showComponent = function(componentName)
{
   hideComponents();
   switch (componentName) {
      case "Regions":
         vm.showRegions = true;
         break;
      case "Accounts":
         vm.showAccounts = true;
         break;
      case "Orders":
         vm.showOrders = true;
         break;
      case "Invoices":
         vm.showInvoices = true;
         break;
      case "Warehouses":
         vm.showWarehouses = true;
         break;
      default:
   }
}

Is there a more concise way to achieve this functionality?

I was thinking something along these lines:

var setComponentVisibility = function (componentName = null)
{
   var bool = false;
   var map = {
       'Regions': vm.showRegions = bool,
       'Accounts': vm.showAccounts = bool,
       'Orders': vm.showOrders = bool,
       'Invoices': vm.showInvoices = bool,
       'Warehouses': vm.showWarehouses = bool
   }
   if (componentName != null)
   {
      // code to set bool to true only for that componentName in map
      // is this even possible?
      // if so, how?
   }
}

However, being new to AngularJS, I'm not sure the above is possible.


texts:
I have to read a int8_t from a buffer, read a uint8_t from the camera's current settings, add them together, keep new value within the bounds 0 to 100 and write the new value to the camera's current settings. This seems quite easy to me, and yet here I have a rather large bit of code.

The brace style is company-mandated.

Is there a way to remove some of the complexity from this code?

Ranges:
plusZoomPercentage: full range of int8_t.
currentZoomPercentage and getZoomPercentage(): 0 to 100, 0 and 100 included.
newZoomPercentage: To be between 0 and 100, 0 and 100 included.

Header file:

/*Zooms to the provided percentage of maximum zoom level.*/
void zoomToPercentage(uint8_t percentage);

/*Retrieves the current targeted percentage of maximum zoom level (if the camera is currently at 50% zoom, but is zooming towards 60%, return 60.)*/
uint8_t getZoomPercentage();

Calling implementation:

int8_t plusZoomPercentage;
if (!unabto_query_read_int8(readBuffer, &plusZoomPercentage))
{
    return AER_REQ_TOO_SMALL;
}
if (plusZoomPercentage == 0)
{
    return AER_REQ_RESPONSE_READY;
}
uint8_t currentZoomPercentage = getZoomPercentage();
uint8_t newZoomPercentage = currentZoomPercentage + plusZoomPercentage;
if (plusZoomPercentage > 0)
{
    /*Check for overflow or otherwise going out of bounds*/
    if (newZoomPercentage > 100 || newZoomPercentage < currentZoomPercentage)
    {
        zoomToPercentage(100);
    }
    else
    {
        zoomToPercentage(newZoomPercentage);
    }
}
else
{
    if (newZoomPercentage > currentZoomPercentage)
    {
        zoomToPercentage(0);
    }
    else
    {
        zoomToPercentage(newZoomPercentage);
    }
}
return AER_REQ_RESPONSE_READY;


texts:
I'm building an option panel for a Wordpress theme. I'm just learning PHP and I wonder if there is any better (shorter) way to generate the social media links. Here's what I came up with and even tho it works, I think there are cleaner way to write it

<?php if ( of_get_option('mm_sm_vimeo') ) { ?>

<a href="<?php echo of_get_option('mm_sm_vimeo'); ?>"><img src="<?php echo  get_template_directory_uri(); ?>/images/socials/ico_vimeo.png" alt="Vimeo"/>Vimeo

<?php } ?>

<?php if ( of_get_option('mm_sm_gplus') ) { ?>

<a href="<?php echo of_get_option('mm_sm_gplus'); ?>"><img src="<?php echo get_template_directory_uri(); ?>/images/socials/ico_gplus.png" alt="Google Plus"/>Google Plus

Etc... etc... over 20 times.

Maybe a loop or something? The problem is that I have a different Option name for each and I don't know how to handle it.


texts:
I would like to select some information I have stored in my MySQL DB.

I have 2 tables named gameTable and playerTable. Now I want to get the gameTable and get the names and levels of these players.

This is what I got so far, it works but I'm not sure this is the most efficient way. Do I really need to create a join for every referred row?

<?php

include ('connect.php');

 $result = mysqli_query($connect,
        "SELECT gameTable.id,
            playerTable1.name AS name1, playerTable1.level AS level1,
            playerTable2.name AS name2, playerTable2.level AS level2,
            playerTable3.name AS name3, playerTable3.level AS level3,
            playerTable4.name AS name4, playerTable4.level AS level4
         FROM gameTable
            JOIN playerTable AS playerTable1 ON gameTable.P1_id = playerTable1.id
            JOIN playerTable AS playerTable2 ON gameTable.P2_id = playerTable2.id
            JOIN playerTable AS playerTable3 ON gameTable.P3_id = playerTable3.id
            JOIN playerTable AS playerTable4 ON gameTable.P4_id = playerTable4.id
        ");

    while ($record = mysqli_fetch_array($result))
    {
        echo $record['id']  . " - "
            . $record['name1'] . " - " . $record['level1'] . " - "
            . $record['name2'] . " - " . $record['level2'] . " - "
            . $record['name3'] . " - " . $record['level3'] . " - "
            . $record['name4'] . " - " . $record['level4'] . "<br>";
    }

?>

As a secondary question, my database is set to MyISAM. Would it be helpful to change it  to InnoDB? Or is this only useful for update delete etc. In your database and not for fetching data?


texts: TSQL query to gather amounts for an employees, spouses, and children in one row

texts:
I have a query that works as intended, kind of pulling from multiple records in a table, and flattening the data into one row. I am wondering if there is a faster/more semantically correct way to do this than multiple derived tables?

ID      Name      Relationship      Amount
-------------------------------------------
1       James     Employee           2000
1       James     Spouse             5000
1       James     Child             10000
2       Mary      Employee           2000
3       Pete      Employee           2000
3       Pete      Child             10000
3       Pete      Child             10000

And turning it into:

ID      Name      EmployeeAmt      SpouseAmt      ChildAmt
----------------------------------------------------------------------------
1       James     2000             5000           10000
2       Mary      2000             NULL           NULL
3       Pete      2000             NULL           10000

Here is the query:

CREATE TABLE #Source
(
   EmpID varchar(2) NULL
   ,Name varchar(20) NULL
   ,Relationship varchar(20) NULL
   ,Amount varchar(10) NULL
)

INSERT INTO #Source
VALUES( '1', 'James', 'Child', 10000)
     ,('1', 'James', 'Spouse', 5000)
     ,('1', 'James', 'EE', 2000)
     ,('2', 'Mary', 'EE', 2000)
     ,('3', 'Pete', 'EE', 2000)
     ,('3', 'Pete', 'Child', 10000)
     ,('3', 'Pete', 'Child', 10000)

SELECT DISTINCT A.EmpID, A.Name, A.EEAmount, B.SpouseAmount, C.ChildAmount
FROM (
          SELECT EmpID, Name, Relationship, Amount AS 'EEAmount'
          FROM #Source
          WHERE Relationship = 'EE'
     ) AS A

     LEFT JOIN

    (
          SELECT EmpID, Name, Relationship, Amount AS 'SpouseAmount'
          FROM #Source
          WHERE Relationship = 'Spouse'
    ) AS B ON A.EmpID = B.EmpID

    LEFT JOIN

    (
          SELECT EmpID, Name, Relationship, Amount AS 'ChildAmount'
          FROM #Source
          WHERE Relationship = 'Child'
    ) AS C ON A.EmpID = C.EmpID

SELECT * FROM #Source
DROP TABLE #Source


texts: sorting a map by converting it to vector

texts:
I have a map that I want to print out sorted by value, I convert it to vector and sort the vector. Is this code correct?

#include <map>
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
int main()
{
    std::map<char, int> freq;
    std::string text;
    std::getline(std::cin, text);
    std::vector<std::pair<char, int>> items;
    for(auto & ch: text)
            freq[ch]++;

    for(auto [key, value]: freq)
        items.push_back(std::make_pair(key, value));

    std::sort(items.begin(), items.end(),

              [](auto a, auto b)
                { return a.second > b.second;});

    for(auto [key, value]: items)
       std::cout << key << " " << value << std::endl;
    return 0;

}


texts: Validating user input in C# coming from XAML controls

texts:
I have page where I am inserting some data into Entry fields. For each Entry I have written in XAML different controls with parameters. One of them is Formated parameter where I am giving a string which I am checking on C# logic code. The problem which I figure out that some one could insert wrong string or string but for example with lower case. How can I improve this code for any wrong input scenarios ?

This is my xaml code:

<ContentPage.Content>

    <StackLayout Padding="7,7,7,7" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Spacing="0">

      <cv:LabelEntryView x:Name="Name" LabelText="some text 4" ColorBg="White" MaxLength="20" Placeholder="some text 4" Formated="NameValidation" Keyboard="Text" >
      </cv:LabelEntryView>

      <cv:LabelEntryView x:Name="CardNr" LabelText="some text 3" ColorBg="White" MaxLength="20" Placeholder="some text 3" Formated="CardNrValidation" Keyboard="Numeric"  >
      </cv:LabelEntryView>

      <cv:LabelEntryView x:Name="ExpDate" LabelText="some text 2" ColorBg="White" MaxLength="5" Placeholder="some text 2" Formated="ExpDate" Keyboard="Numeric" >
      </cv:LabelEntryView>

      <cv:LabelEntryView x:Name="SecurNr" LabelText="some text" ColorBg="White" MaxLength="3" Placeholder="some text" Keyboard="Numeric" >
      </cv:LabelEntryView>

    </StackLayout>

  </ContentPage.Content>

and here is my C# code with if statement checking string:

private void Entry_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (Formated == "NameValidation")
            {
                Entry ent = (Entry)sender;
                ToUpper(ent);
            }
            else if (Formated == "CardNrValidation")
            {
                Entry ent = (Entry)sender;
                CardNumberValidation(ent);
            }
            else if (Formated == "ExpDate")
            {
                Entry ent = (Entry)sender;
                ExpDate(ent,e);
            }
}

Maybe I have to assign type for each if check? If yes, how can I do it?
Thank you for your reviews.


texts:
This code is working, please find below the before and after data that i need to split as per criteria 1st column with data will be 6 chr, 2nd column 5 chr, 3rd column 4 chr, 4th column 2 chr.

Sub splitStyleFabricColourSize()

Dim cellRow As Range
Dim mergedCells As Range
Dim cellInfo As Long

On Error GoTo ErrorHandler

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Set mergedCells = Selection

For Each cellRow In mergedCells.Cells
cellRow.Select

cellInfo = ActiveCell.Characters.Count
Debug.Print cellInfo

If cellInfo = 15 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth, _
        FieldInfo:=Array(Array(0, 1), Array(6, 1), Array(11, 1))

ElseIf cellInfo = 17 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth _
        , FieldInfo:=Array(Array(0, 1), Array(6, 9), Array(7, 1), Array(12, 9), Array(13, 1))

ElseIf cellInfo = 18 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth _
        , FieldInfo:=Array(Array(0, 1), Array(6, 9), Array(8, 1), Array(13, 9), Array(14, 1))

ElseIf cellInfo = 22 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth _
        , FieldInfo:=Array(Array(0, 1), Array(6, 9), Array(7, 1), Array(12, 9), Array(13, 1), _
        Array(17, 9), Array(20, 1))

ElseIf cellInfo = 23 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth, _
        FieldInfo:=Array(Array(0, 1), Array(6, 9), Array(7, 1), Array(12, 9), Array(13, 1), _
        Array(17, 9), Array(21, 1))

ElseIf cellInfo = 24 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth, _
        OtherChar:="/", FieldInfo:=Array(Array(0, 1), Array(6, 9), Array(7, 1), Array(12, _
        9), Array(13, 1), Array(17, 9), Array(22, 1))

ElseIf cellInfo = 25 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth _
        , OtherChar:="/", FieldInfo:=Array(Array(0, 1), Array(6, 9), Array(7, 1), Array( _
        12, 9), Array(13, 1), Array(17, 9), Array(23, 1))

ElseIf cellInfo = 26 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth _
        , OtherChar:="/", FieldInfo:=Array(Array(0, 1), Array(6, 9), Array(7, 1), Array( _
        12, 9), Array(13, 1), Array(17, 9), Array(22, 1))

ElseIf cellInfo = 27 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth _
        , OtherChar:="/", FieldInfo:=Array(Array(0, 1), Array(6, 9), Array(8, 1), Array( _
        13, 9), Array(14, 1), Array(18, 9), Array(23, 1))

ElseIf cellInfo = 29 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth, _
        OtherChar:="/", FieldInfo:=Array(Array(0, 1), Array(6, 9), Array(8, 1), Array(13, _
        9), Array(14, 1), Array(18, 9), Array(25, 1))

ElseIf cellInfo = 52 Then
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlFixedWidth _
        , FieldInfo:=Array(Array(0, 1), Array(6, 9), Array(7, 1), Array(12, 9), Array(13, 1), _
        Array(17, 9), Array(20, 1), Array(42, 9))

End If

Next cellRow
Application.ScreenUpdating = True
Application.DisplayAlerts = True

Exit Sub
ErrorHandler:
Debug.Print "Error number: " & Err.Number & " " & Err.Description

End Sub


texts: Shell script to count chess game outcomes

texts:
I came across this blog post by Adam Drake from around a year ago which is now making the rounds again.

I made some improvements to his code, but wish to see if there are additional tweaks that could be made to make it run even faster.

The task is to extract chess game results from PGN files.  The files contain sequences of games, where each has a header which contains a "Result" line like this:

[Result "1-0"]
[Result "0-1"]
[Result "1/2-1/2"]

These three results indicate a white win, a black win, and a draw, respectively.  The task is to simply collect and report a summary of these results.

Here is my solution to be reviewed:

find . -type f -name '*.pgn' -print0 |
 xargs -0 mawk -F '[-"]' '/Result/ { ++a[$2]; }
   END { print a["1"]+a["0"]+a["1/2"], a["1"], a["0"], a["1/2"] }'

I was skeptical of using find over just listing the files in the reference data set, but my timings indicate that this is actually faster than a shell wildcard (Bash 4.3.11(1)-release).

tripleee@xvbvntv:ChessData$ time find . -type f a-name '*.pgn' | wc -l
3025

real    0m0.014s
user    0m0.008s
sys     0m0.011s

tripleee@xvbvntv:ChessData$ time printf '%s\n' */*.pgn | wc -l
3025

real    0m0.037s
user    0m0.032s
sys     0m0.010s

The optimization I originally had in mind was to close the data file after reading the Result line, but as it turns out, the reference data set files contain multiple games, and thus multiple results (and the game portion is a lot smaller than I thought it would be).

tripleee@xvbvntv:ChessData$ time find . -type f -name '*.pgn' -print0 |
> xargs -0 mawk -F '[-"]' '/Result/ { ++a[$2]; }
>   END { print a["1"]+a["0"]+a["1/2"], a["1"], a["0"], a["1/2"] }'
6829065 2602614 1974505 2251946

real    0m50.232s
user    0m19.820s
sys     0m2.542s

This is as far as I got.  (An earlier version, based on the blog post, attempted parallel processing, but removing that was the biggest performance improvement I made.) I don't think switching from Awk to a "bigger" language would buy me any serious benefits -- one of the strengths of Awk is that it's quick to write, parse, and execute. (Compiled code would probably be a tad faster, but I don't think I want to go there; let's try to keep a realistic cost/benefit ratio.)  Are there any additional improvements to be made, to make it go even faster?

Here is the data set referenced in the blog, which I used to obtain my results.

(Another, slightly smaller data set is available from here.)

Sadly, the Hadoop experiment which is linked from Adam's blog is now a 404.  He quotes the original author as clocking 26 minutes to process the (smaller?) data set on seven c1.medium instances.  His own code took 12 seconds, but I was unable to reproduce that -- with this data set, it took 2 minutes and 30 seconds on my computer, so I have improved over that by some 60%.


texts: Kadane's Algorithm Variant (Start Index and End Index with Sub Array returned even for all negative numbers)

texts:
Here is an attempt to extend the Kadane's Algorithm to return the sub array itself instead of the sum of maximum sub array.  This must work irrespective of the original array having all positive or negative numbers.

public class MaxSubArray {

    public static void main(String[] args) {
        int array[] = {10, -9, 4, 5, 90, -19, 19}; // Max sum is 100
        //int array[] = {4, -3, 6}; // Max Sum is 7
        //int array[] = {-1, -2, -3}; // Max Sum is -1
        //int array[] = {1, -2, -3}; // Max Sum is 1
        //int array[] = {-4, -3, -6}; // Max Sum is -3
        //int array[] = {-6, 0, 5}; // Max Sum is 5
        //int array[] = {0, 0, 0}; // Max Sum is 0
        int[] maxSubArray = getMaxSubArray(array);
        System.out.println(Arrays.toString(maxSubArray));
    }

    // Kadane's Alorithm Variant (Start Index and End Index of Sub Array even for all negative numbers)
    private static int[] getMaxSubArray(int[] array) {
        if (array == null || array.length == 0) {
            return array;
        } else {
            int startIndex = 0, endIndex = 0;
            int maxSoFar = array[0], maxEndingHere = array[0];
            for (int i = 1; i < array.length; i++) {
                if(maxSoFar < array[i] && array[i] >= maxEndingHere + array[i]) {
                    maxEndingHere = array[i];
                    startIndex = i;
                    endIndex = i;
                } else {
                    maxEndingHere += array[i];
                }
                if(maxEndingHere > maxSoFar) {
                    maxSoFar = maxEndingHere;
                    endIndex = i;
                }
            }
            return Arrays.copyOfRange(array, startIndex, endIndex + 1);
        }
    }
}


texts: Class to share data between two threads implemented as FIFO with std::queue

texts:
I am trying to improve my code that involves a thread (threadA) handling some UDP communication and another thread (threadB) that works with the output of that communication.
My basic idea is to .push() new data into a std::queue within threadA.
threadB is looking for new data periodically - if it gets new data it processes it. Then .pop is called and the data is deleted.
Implementation:

threadA will call addNewElement() any time new UDP data arrives.

threadB will call getNewestPtr() to access the data.

when done with the data, threadB will call doneWithNewest().

I am managing the access to the data (which comes in the form of std::array) through the use of std::shared_ptr. I know that the shared_ptr will manage the access to the pointer in a thread safe manner, but the underlying object is not going to be managed. Here lies my problem - in my implementation of the class, I am not sure where to put in memory locks, to ensure thread safety. My implementation already works, I have been testing it for a few days without problems, but I have the feeling I am doing something wrong, as I have not used any std::mutex. Anyway, here is my code:
commbufferfifo.h
#ifndef COMMBUFFERFIFO_H
#define COMMBUFFERFIFO_H

#include <queue>
#include <array>
#include <memory>

const size_t COMMLENGTH = 56;

/**
 * @brief The commbufferfifo class
 * @details used to safely share data between the comm thread and the visu thread
 */
class commbufferfifo
{
public:
    commbufferfifo();

    /**
     * @brief getNewestPtr  only accessed in visu thread
     * @return returns nullptr if fifo is empty!
     */
    std::shared_ptr<std::array<int16_t, COMMLENGTH>> getNewestPtr();///< @brief

    void doneWithNewest();///< @brief call when newest object can be deleted

    void addNewElement(const std::array<int16_t, COMMLENGTH> &commBuffer);  ///< @brief only accessed in comm thread

private:
    std::queue<std::shared_ptr<std::array<int16_t, COMMLENGTH>>> m_fifo;
};

#endif // COMMBUFFERFIFO_H

commbufferfifo.cpp
#include "commbufferfifo.h"

commbufferfifo::commbufferfifo()
{

}

std::shared_ptr<std::array<int16_t, COMMLENGTH> > commbufferfifo::getNewestPtr()
{
    if (m_fifo.empty())
        return nullptr;
    else
        return m_fifo.front();
}

void commbufferfifo::doneWithNewest()
{
    if (m_fifo.empty())
        return;
    else
        m_fifo.pop();
}

void commbufferfifo::addNewElement(const std::array<int16_t, COMMLENGTH> &commBuffer)
{
    m_fifo.push(std::make_shared<std::array<int16_t, COMMLENGTH>>(commBuffer));
}

some pseudo usage:
main.cpp
#include "includes/commbufferfifo.h"

#include <unistd.h>

void threadA(std::shared_ptr<commbufferfifo> myPointer){
    std::array<int16_t, COMMLENGTH> arr;
    for (int iteration = 0; iteration < 1000; iteration++){
        arr.at(0) = iteration;
        myPointer->addNewElement(arr);
        usleep(100);
    }
}

int main()
{
    auto sharedFifo = std::make_shared<commbufferfifo>();
    std::thread tA(&threadA, sharedFifo);

    usleep(10000);
    for(;;){
        if (sharedFifo->getNewestPtr() == nullptr)
            break;
        std::cout << "sharedFifo->getNewestPtr()->at(0) = " << sharedFifo->getNewestPtr()->at(0) << "\n";   //use data
        sharedFifo->doneWithNewest();                                                                       //data will be deleted
        usleep(1000);
    }

    tA.join();

    std::cout << "------------------------------------\n";
    std::cout << "done" << std::endl;
    return 0;
}
```


texts:
In my journey of learning Rails, I'm wondering if I should test model validations. If so, is this a correct way to do it?
require 'test_helper'

class ShippingAddressTest < ActiveSupport::TestCase

  test "shipping addresses validations" do
    s = ShippingAddress.create
    assert_not s.valid?, "Address was valid without any data"
    assert s.errors.include? :name
    assert s.errors.include? :phone
    assert s.errors.include? :address
    assert s.errors.include? :user
    assert s.errors.include? :city

    s.name = "Some"
    s.phone = "8296964737"
    s.address = "Calle #1"
    s.user_id = 1

    # Test Inclusion of city
    s.city = "Santo"
    assert_not s.valid?, "Address was valid with incorrect city"

    s.city = "Santo Domingo"
    assert s.valid?, "Address not valid with everything filled"
  end

end

I just found out while reading Testing Rails guide about this:

3.3 What to Include in Your Unit Tests
Ideally, you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.

In this case, what would be the correct way to add a test for a single validation?


texts:
I'm new to testing in Meteor, so I'm worried if my implementation is not going in the right directions. I've written a unit test for my send method which sends a message to a room only if the user is logged in.

import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import { Rooms } from '../rooms/rooms.js';
import { Chats } from '../chats/chats.js';
import { assert } from 'meteor/practicalmeteor:chai';
import './chats.js';

if (Meteor.isServer) {
  describe('send chat method', function () {
    let rid;
    before(() => {
      Meteor.users.remove({});
      Rooms.remove({});
      Chats.remove({});

      const createUser = Meteor.server.method_handlers['registerUser'];
      let user1 = {
        username: 'user1'
      };
      createUser.apply({}, [user1]);

      let user2 = {
        username: 'user2'
      };
      createUser.apply({}, [user2]);

      // create a room before
      let room = {
        _id: Random.id(),
        h: 'o',
        users: [user1.username, user2.username],
        members: [{
          uh: user1.username,
          isOwner: true,
          isAdmin: true
        }, {
          uh: user2.username
        }],
        mc: 0,
        ts: Date.now()
      };
      rid = Rooms.insert(room);
      assert.equal(Rooms.find().count(), 1);
    });

    it('can inset a chat message between two users', () => {
      let msg = {
        msg: 'test message',
        rid: rid,
        u: 'test1',
        ts: new Date(),
        lts: '1848484468',
        incog: '0',
        n: 0
      };
      Chats.insert(msg);
      assert.equal(Chats.find().count(), 1);
    });
  });
}

I'm not sure if I've written a unit test or an integration test. Do I have to write each module inside the send method as a test, or is this fine?


texts: Getting a min birth year and max death year from a list of years

texts:
A very simple problem here (I'm learning Python) - given a list of tuples which represent (year of birth, year of death) for a group of people, I want to find the minimum "year of birth" and the maximum "year of death". Here's how I did it:

def testmax():
    years = [(1804, 1884), (1885,1997), (1902,1975), (1900,1989)] # sample data

    endyr = max([deathyr for (birthyr,deathyr) in years])
    startyr = min([birthyr for (birthyr,deathyr) in years])
    print(startyr, endyr) # correctly returns 1804 1997

As you can see, I use list comprehensions to go through the years list twice. Time complexity O(2N) = O(N).

I can improve this with a simple function that is longer but does it through one iteration of the years list — I simply track (min, max) as my return variables that I keep checking on every iteration to get the min and max years that I need, in one iteration. Time complexity = O(N). What I don't like here is writing longer code (perhaps in a test/interview where time is limited).

My question: is there a better/cleaner/more Pythonic way you would do this? Would a lambda function work here, if so how? Even if you still do it in 2 iterations, I'd appreciate it if you could demo/explain any variations of the code (perhaps using lambda) that you would have used.


texts: Convert Persian and Arabic digits to English

texts:
I use the following utility method to convert Persian and Arabic digits to English using regex:

convertNumbers2English: function (string) {
    return string.replace(/[٠١٢٣٤٥٦٧٨٩]/g, function (c) {
        return c.charCodeAt(0) - 1632;
    }).replace(/[۰۱۲۳۴۵۶۷۸۹]/g, function (c) {
       return c.charCodeAt(0) - 1776;
   });
}


texts:
My code works in that it compiles, and when executed writes out a log file using a buffered writer.

But I wonder whether:

I am correct in assuming that this actually winds up deferring a .Close that is always called
a package variable is the idiomatic way of doing this in Go

I realise that I could just have createLogger return the file pointer, and defer on that ... but that seems even weirder, to have createLogger set a package variable on log, then return the file pointer to be treated as a local ...

I'm still struggling with an idiom here.

package main

import (
    "bufio"
    "log"
    "os"
)

var logFile *os.File

func main() {
    createLogger()
    defer logFile.Close()

    // do some stuff
}

func createLogger() {
    logFile, err := os.OpenFile("log/app.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("error opening file: %v", err)
        os.Exit(-1)
    }
    log.SetOutput(bufio.NewWriter(logFile))
}


texts: Function to show or hide validation error messages

texts:
I'm a bit clumsy at writing JavaScript.  I have some nice code like this:

(function($){
    $.fn.forceNumeric = function(){
        return this.each(function(){
            $(this).keyup(function(){
                if (!/^[0-9]+$/.test($(this).val())){
                    $(this).val($(this).val().replace(/[^0-9]/g, ''));
                }
            });
        });
    };
})(jQuery);

I know what it does and how it works. I can call the function and I see why it works.

For the life of me, I cannot figure out how to use that same elegant style/approach for my Neanderthal function:

function showHideErrorBox(theFriendlyName, check){
     var topLevelDiv,
        numDivsAfter;

        if(check === 0){
        // REMOVE THE OLD ERROR MESSAGE IN THE ERROR BOX
            $('.form-validation-errors').find('div').each(function(){
                if( $(this).html().indexOf(theFriendlyName) != -1 ){
                    $(this).remove();
                }
            });
        }

        //  CHECK WHETHER THE ENTIRE MESSAGE BOX CAN BE REMOVED NOW
        topLevelDiv = document.getElementById('alert-form-errors');
        numDivsAfter = topLevelDiv.getElementsByTagName('div').length;

        if(check === 0){
            if(numDivsAfter <= 1){
                $('#alert-form-errors').hide();
            }

        }else if(check === 1){

            if(numDivsAfter >= 1){
                $('#alert-form-errors').show();
            }
        }
}

Can anyone help me out? Where do I start? I have Google'd for tutorials, but I have not been able to find something suitable for my needs.


texts: Neo4j traversal algorithm to find dense nodes

texts:
I am trying to get familiar with traversals algorithms implementations in Neo4j and to practice I am implementing classic graph algorithms (not judging if is the best approach or not, just for the sake of practising).

I implemented this find dense nodes class, but i am not completely happy with it, I feel it can be improved but I don't know how.

public class DenseNodesTraverser {

    private GraphDatabaseService db;

    private Log logger;

    public DenseNodesTraverser(GraphDatabaseService db, Log logger) {
        this.db = db;
        this.logger = logger;
    }

    public List<Node> traverse(Node node) {
        DenseNodeEvaluator eval = new DenseNodeEvaluator();
        Traverser traverser =
                            db
                            .traversalDescription()
                            .depthFirst()
                            .relationships(Rels.Weight)
                            .uniqueness(Uniqueness.NODE_GLOBAL)
                            .evaluator(eval)
                            .traverse(node);

        for (Path current : traverser) {
            System.out.println("Path " + current);
        }
        return eval.getDenseNodes();
    }

    private class DenseNodeEvaluator implements Evaluator {

        List<Node> denseNodes = new ArrayList<>();

        @Override
        public Evaluation evaluate(Path path) {
            Node lastNode = path.endNode();

            int numberOfRelationships = Iterators.size(lastNode.getRelationships().iterator());

            if (numberOfRelationships >= 3) {
                denseNodes.add(lastNode);
            }

            return Evaluation.INCLUDE_AND_CONTINUE;
        }

        public List<Node> getDenseNodes() {
            return denseNodes;
        }

    }

}


texts:
I read the solution to this question, which seems to be the same target. My solution is (I'm sure) not the quickest, but some test case is apparently taking longer than 4s. I did a test case with 10,000 random integers and it completed in just over .33 seconds, so I'm trying to find what would result in this code hanging.

Here are the requirements:

  Given an array a that contains only numbers in the range from 1 to
  a.length, find the first duplicate number for which the second
  occurrence has the minimal index. In other words, if there are more
  than 1 duplicated numbers, return the number for which the second
  occurrence has a smaller index than the second occurrence of the other
  number does. If there are no such elements, return -1.

  Example

  For a = [2, 1, 3, 5, 3, 2], the output should be firstDuplicate(a) =
  3.

  There are 2 duplicates: numbers 2 and 3. The second occurrence of 3
  has a smaller index than the second occurrence of 2 does, so the
  answer is 3.

  For a = [2, 4, 3, 5, 1], the output should be firstDuplicate(a) = -1.

My solution:

def firstDuplicate(a):
    currentdupe = -1
    dist = len(a)
    if len(a) == 0: return -1
    if len(a) == 1: return -1
    if len(a) == 2 and a[0] == a[1]: return a[0]
    else:
         #new list
         b = list(a)
         b.sort()

         #check each double in the sorted range
         for x in (range(len(b)-1)):
             if b[x] == b[x+1]:
                 #if distance is less than last found, use this one
                 if a[a.index(b[x])+1:].index(b[x]) < dist:
                     dist = a[a.index(b[x])+1:].index(b[x])
                     currentdupe = b[x]
         return currentdupe

Even in a worst case of 9,998 values of '1' and 2 values of '2', it still ran in just over .5s. When it runs a test case I get "Program exceeded the 4s time limit." How can this be?


texts:
Rewrite readlines to store lines in an array supplied by main, rather than calling alloc() to maintain storage. How much faster is the program?

Here is my solution:

int readlines(char **lineptr, char *storage, int maxlines, int storage_size) {

    int len;
    int nlines;

     nlines = 0;
     while((len = _getline(storage, MAXLEN))) {
        if(nlines >= maxlines || !(storage_size - len)) {
            return -1;
        }
         else {
            storage[len - 1] = '\0';
            lineptr[nlines] = storage;

            storage += len; // next free space in the buffer supplied by main
            storage_size -= len;
            nlines++;
        }
    }
    return nlines;
}

Now, the function takes 2 more arguments: a pointer to the array that will store all the read lines and its size. There is no need now to use another array to store the line temporary, I just can pass portions of the storage to getline.

The condition !(storage_size - len) verifies if there is enough space in storage to store the line that was just read. At each iteration storage is incremented to point to the next free space in the array and the value of the variables storage_size is reduced.

(This exercise can be found at page 124 in K&R.)