texts: Filtering conversation by filter type and value

texts:
I have been assigned to developed a feature that filters a conversation. For example, I want to filter the conversation by user id then export it to something either JSON or text file. In this case, I created a class that handles the filters like this.

import java.util.ArrayList;
import java.util.List;

/**
 * Represents the filter that operates the filter functions for messages
 *
 * @author Muhammad
 */
public class Filter {

    String filterType;
    String argumentValue;

    //Constructor that takes a parameter of filter type and argument value.
    public Filter(String filterType, String argumentValue) {
        this.filterType = filterType;
        this.argumentValue = argumentValue;
    }

    //Method that filters a conversation by a specific user and return filterd conversation.
    public static Conversation filterByUser(Conversation conversation, String specificUser) {
        List<Message> messageList = new ArrayList<>();
        //Filter by used id
        for (Message message : conversation.messages) {
            if (message.senderId.equals(specificUser)) {
                messageList.add(message);
                Conversation filteredConversation = new Conversation(conversation.name, messageList);
                conversation = filteredConversation;
            }
        }
        return conversation;
    }

    //Method that filters a conversation that contains a specific keywod and returns filterd conversation.
    public static Conversation filterByWord(Conversation conversation, String specificWord) {
        List<Message> messageList = new ArrayList<>();
        //Filter by keyword
        for (Message message : conversation.messages) {
            if (message.content.contains(specificWord)) {
                messageList.add(message);
                Conversation filteredConversation = new Conversation(conversation.name, messageList);
                conversation = filteredConversation;
            }
        }
        return conversation;
    }

    //Method that hides a word in a conversation by a specificword
    public static Conversation hideWord(Conversation conversation, String specificWord) {
        List<Message> messageList = new ArrayList<>();
        //Filter by used id
        for (Message message : conversation.messages) {
            if (message.content.contains(specificWord)) {
                message.content = message.content.replaceAll(specificWord, "*redacted*");
                messageList.add(message);
                Conversation filteredConversation = new Conversation(conversation.name, messageList);
                conversation = filteredConversation;
            }
        }
        return conversation;
    }
}

In another class, I used it inside a method called filter like this.

private void filter(Filter filter, Conversation conversation, String outputFilePath) throws Exception {

        String filterType = filter.filterType; //used to get the type of filter
        String argumentValue = filter.argumentValue;

        //Filterers
        switch (filterType) {
            case "filteruser":
                conversation = Filter.filterByUser(conversation, argumentValue);
                this.writeConversation(conversation, outputFilePath);
                break;
            case "filterword":
                conversation = Filter.filterByWord(conversation, argumentValue);
                this.writeConversation(conversation, outputFilePath);
                break;
            case "hideword":
                conversation = Filter.hideWord(conversation, argumentValue);
                this.writeConversation(conversation, outputFilePath);
                break;
            default:
                this.writeConversation(conversation, outputFilePath);
                break;
        }

    }

This code works, however I'd like feedback on anyways that I can improve the code as I am just a graduate.


texts: Single MySQLI query to check for admin privileges

texts:
I have this script on top of all pages to check if user is admin otherwise we kick him. The problem is that I don't know if I am using double resources with a double query and results. Can I make this code to be only 1 query and 1 result? Please read the comments in code to understand:

<?php
session_start();
$identification = $_SESSION['session_name'];
include 'inc/database.php';
$query = "SELECT * FROM `members` WHERE `username` = '$identification' LIMIT 1";

// Here is the question about, we run first query to verify user

$result_1 = mysqli_query($database, $query);

// Now I am like obligated to query 2 times and get 2 results to make the While user_info $result_2 to work

$result_2 = mysqli_query($database, $query);

$privileges = mysqli_fetch_array($result_1, MYSQLI_ASSOC);
$user_level = $privileges["privs"];
if ($user_level=='ADMIN'){}
else {
header('Location: security.php?error=missing correct privileges. user is not admin');
exit();
}

// If I set here to $result_1 it just does not work, I feel obligated to query 2 times and use more resources

while($user_info = mysqli_fetch_assoc($result_2))
{
?>
<html>
<head>
<title>Zona de Pruebas</title>
</head>
<body>
Username: <?php echo $user_info['username']?>, can be here because is admin</div>
</body>
</html>
<?php
}
?>


texts:
I want to convert a large PDF file into individual text files with PDFBox using Python. This code takes lot of time to convert a PDF containing 1000 pages.

Is there anything I can do to improve it?

I cannot use any other library. My other code (Python - parsing of obtained text) works best with output of PDFBox.

import PyPDF2
import sys
import os
import subprocess

pdfFileObj = open('cpdf.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
tot = pdfReader.numPages
for i in range(1, tot+1):
    i = str(i)
    ffi = "out\\" + i + "-extracted.txt"
    command = "java -jar" + " " + "pdfbox-app-2.0.2.jar" + " " + "ExtractText" + " " + "cpdf.pdf" + " " + ffi + " " + "-startPage" + " " + i + " " + "-endPage" + " " + i
    subprocess.check_output(command, shell=True)
    print('Completed ' + str(i))

On the other hand, when I do this, it takes 10 seconds:

import subprocess

command = "java -jar pdfbox-app-2.0.2.jar ExtractText cpdf.pdf  out.txt -startPage 1 -endPage 3158"

subprocess.check_output(command, shell=True)


texts: Codeforces problem python code optimization

texts:
I have solved one problem on Codeforces and I guess the output is quite correct. However, it is slow for input in range of thousands. Since, I am learning Python now, it would be great help if one could help me optimise this code. Any notes, tips or suggestions on the sidelines are always welcome.

The question is a practice question and hence does not violate any contest rules.

import sys
import time

_no_of_ants, _no_of_queries = (input().split())
no_of_ants = int(_no_of_ants)
no_of_queries = int(_no_of_queries)

class ants_cord():
    def __init__(self,point,no_of_ants):
        self.co_ant = {point:no_of_ants}

    def ants_at_point(self,point):
        return self.co_ant[point]

    def move_ants(self,point):
        x1,y1 = point
        if (x1+1,y1) in self.co_ant.keys():
            self.co_ant[((x1+1),y1)] += 1
        else:
            self.co_ant[((x1+1),y1)] = 1
        if (x1,y1+1) in self.co_ant.keys():
            self.co_ant[((x1),y1+1)] += 1
        else:
            self.co_ant[((x1),y1+1)] = 1
        if (x1,y1-1) in self.co_ant.keys():
            self.co_ant[((x1),y1-1)] += 1
        else:
            self.co_ant[((x1),y1-1)] = 1
        if (x1-1,y1) in self.co_ant.keys():
            self.co_ant[((x1-1),y1)] += 1
        else:
            self.co_ant[((x1-1),y1)] = 1
        self.co_ant[point] -= 4

    def check_status(self):
        for key in self.co_ant.keys():
            if k.co_ant[key] >= 4:
                return key
        else: return False
start = time.time()
k = ants_cord((0,0),no_of_ants)
point = k.check_status()
while point:
    k.move_ants(point)
    point = k.check_status()
end = time.time()
print("Sec:{}".format(end-start))
while no_of_queries:
    _x,_y = input().split()
    x = int(_x)
    y = int(_y)
    if (x,y) in k.co_ant:
        print(k.co_ant[(x,y)])
    else:
        print('0')
    no_of_queries -= 1

EDIT: I updated the code according to suggestion. But I still get a TLE error in test case 4. Should I employ other algorithm then?


texts: Check if a binary tree is a binary search tree

texts:
Given a binary tree, I need to check if it satisfies the binary search tree property i.e. left child is less than or equal to the current node and right child is greater than or equal to the current node.

from collections import namedtuple

Node = namedtuple('Node', 'key, left, right')

def is_bst(node, key_min=None, key_max=None):
    """Checks is the subtree rooted at this node is a BST."""
    if node is None:
        return True # By definiton
    if key_max is not None and node.key >= key_max:
        return False
    if key_min is not None and  node.key <= key_min:
        return False
    return is_bst(node.left, None, node.key) and is_bst(node.right, node.key, None)

import unittest

class TestBst(unittest.TestCase):
    def test_none(self):
        self.assertTrue(is_bst(None))

    def test_left_skewed(self):
        root = Node(8, Node(3, Node(1, None, None), None), None)
        self.assertTrue(is_bst(root))

    def test_right_skewed(self):
        root = Node(8, None, Node(10, None, Node(14, None, None)))
        self.assertTrue(is_bst(root))

    def test_bst(self):
        root = Node(8, Node(3, None, None), Node(10, None, None))
        self.assertTrue(is_bst(root))

    def test_non_bst(self):
        root = Node(8, Node(10, None, None), Node(6, None, None))
        self.assertFalse(is_bst(root))

if __name__ == '__main__':
    unittest.main()

I want to know if I can convert it to an iterative version. If yes, then how?

Time complexity

The algorithm visits each node exactly once, hence the complexity should be \$\Theta(n)\$, where \$n\$ is the number of node in the tree.


texts:
I am implementing my own UnitOfWork for an EntityFramework-DataContext.

I want to call SaveChangesAsync and when this succeeds, clear a list. Is my approach with ContinueWith correct?

public async Task<int> CommitAsync(int? commandTimeout = null, bool ignoreCustomLogic = false)
{
    try
    {
        return await DataContext.SaveChangesAsync().ContinueWith((antecedent) =>
        {
            if (!antecedent.IsFaulted)
            {
                _addedEntities.Clear();
                _changedEntities.Clear();
                _deletedEntities.Clear();
            }
            return antecedent.Result;
        });
    }
    catch (DbEntityValidationException dbEx)
    {
        RethrowException(dbEx);
        return default(int);
    }
}

private void RethrowException(DbEntityValidationException dbEx)
{
    string message = "ValidationExceptions: " + Environment.NewLine;
    foreach (var validationResult in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationResult.ValidationErrors)
        {
            message += string.Format("Property: {0} Error: {1}{2}", validationError.PropertyName, validationError.ErrorMessage, Environment.NewLine);
        }
    }
    throw new Exception(message, dbEx);
}


texts:
What do you think about this piece of code? How would you design the builder pattern in this situation?

#ifndef CPP_URL
#define CPP_URL
#include<iostream>
#include<vector>
#include<map>
using std::string;

enum protocol  {
  HTTP,
  HTTPS
};

static string map(protocol scheme) {
  switch(scheme) {
    case HTTP:
      return "http";
    default:
      return "https";
  }
}

static int defaultPort(protocol scheme) {
  switch (scheme) {
    case HTTP:
      return 80;
    default:
      return 440;
  }
}

class url final {
private:
  using list = std::vector<std::string>;
  using pairs = std::map<std::string, std::string>;
  const list paths;
  const pairs queries;
  const protocol scheme;
  const string domain;
  const string fragment;
  const string username;
  const string password;
  mutable int port;
public:
  class builder {
   friend url;
   private:
      protocol scheme;
      pairs queries;
      list paths;
      string domain;
      string fragment;
      string username;
      string password;
      int port = -1;
   public:
     builder& setScheme(protocol);
     builder& setFragment(const string&);
     builder& setDomain(const string&);
     builder& setUsername(const string&);
     builder& setPassword(const string&);
     builder& setPort(int port);
     builder& addQuery(const string&, const string&);
     builder& addPath(const string&);
     url& build() const;
  };
  explicit url(const url::builder&);
  string build() const;
};

using builder = url::builder;

inline builder& builder::setScheme(protocol scheme) {
  this->scheme = scheme;
  return *this;
}

inline builder& builder::setUsername(const string& username) {
  this->username = username;
  return *this;
}

inline builder& builder::setPassword(const string& password) {
  this->password = password;
  return *this;
}

inline builder& builder::setFragment(const string& fragment) {
  this->fragment = fragment;
  return *this;
}

inline builder& builder::setDomain(const string& domain) {
  this->domain = domain;
  return *this;
}

inline builder& builder::setPort(int port) {
  this->port = port;
  return *this;
}

inline builder& builder::addQuery(const string& key, const string& value) {
  queries.insert(std::pair<string, string>(key, value));
  return *this;
}

inline builder& builder::addPath(const string& path) {
  paths.insert(paths.begin(), path);
  return *this;
}

inline url& builder::build() const {
  return *(new url(*this));
}

inline url::url(const builder& object)
    : paths(object.paths)
    , queries(object.queries)
    , scheme(object.scheme)
    , domain(object.domain)
    , fragment(object.fragment)
    , username(object.username)
    , password(object.password)
    , port(object.port)
    {}

string url::build() const {
  string url = map(scheme).append("://");
  if (!username.empty()) {
    url.append(username);
    if (!password.empty()) {
      url.append(":").append(password);
    }
    url.append("@");
  }
  url.append(domain);
  if (port == -1)
    port = defaultPort(scheme);
  url.append(":").append(std::to_string(port));
  for (string path : paths) {
    url.append("/");
    url.append(path);
  }
  auto it = queries.begin();
  if (it != queries.end()) {
    url.append("?").append(it->first)
      .append("=").append(it->second);
    for(it++; it != queries.end(); it++) {
      url.append("&").append(it->first)
        .append("=").append(it->second);

    }
  }
  if (!fragment.empty()) {
    url.append("#").append(fragment);
  }
  return url;
};

#endif

This is how we can use that:

   url url = url::builder()
    .setScheme(HTTPS)
    .setDomain(YOUTUBE_DOMAIN)
    .addPath(WATCH_PATH)
    .addQuery(CATEGORY, ITEM)
    .build();
  std::cout<<url.build()<<std::endl;


texts:
I've got some pretty simple validation that I'm working on, but it seems like I'm repeating myself a bunch of times. There has to be a better way of doing this. I'm simply checking if there is a value filled in for specific fields and apply a color if the value isn't filled in. There are also other areas where the validation is different where I'm checking a valid phone number. So I couldn't simply apply this to all inputs. Here's some of my code:

var x = $();
var pass = true;

function validateForm(){
        x = $('input#zip').val();
        if (x == null || x == "") {
            $('#ziplabel').css('color','#fff');
            pass = false;
        } else {
            $('#ziplabel').css('color','#444');
        }
        x = $('input#fname').val();
        if (x == null || x == "") {
            $('#fnamelabel').css('color','#fff');
            pass = false;
        } else {
            $('#fnamelabel').css('color','#444');
        }
        x = $('input#lname').val();
        if (x == null || x == "") {
            $('#lnamelabel').css('color','#fff');
            pass = false;
        } else {
            $('#lnamelabel').css('color','#444');
        }

}


texts: Computing the distribution of a Jonckheere-Terpstra statistic

texts:
I have the following C++ function which I'd like to speed up, if possible. This program will have many different users, so parallelization is not really an option.

The C++ function is wrapped by C code and then called from R, using:

R CMD SHLIB -o jonckterp.so wrapper.cpp inside.cpp

from the command line, then:

dyn.load("jonckterp.so")

from within R.

inside.cpp

#include <stdio.h>
#include <vector>
#include <iostream>
#include <R.h>
#include <Rmath.h>

extern "C" void jonckterp(int *x,int *c, int *ngrp, double *comb);

int *finalcountdown;
static int count;

static int *tabInit(int num){
  int *w;
  w = (int *) R_alloc(num, sizeof(int));
  memset(w, '\0', num * sizeof(int));
  return(w);
}

static int mannwhit(std::vector<int> c, std::vector<int> sizes){
  int Ustat=0;
  int start=0;
  size_t Ngroups=sizes.size();
   for(int i=0; i<Ngroups-1;i++){
    for(int j=start;j<(start+sizes[i]);j++){
      for(int k=start+sizes[i];k<c.size();k++){
    if(c[j]<c[k])
      Ustat+=1;
      }
    }
    start+=sizes[i];
  }
   return(Ustat);
    }

void allocate_to_groups_impl( std::vector<char>& usage, std::vector<int>& order, const           std::vector<int>& cumsum, int group, int place, int min )
{
std::vector<int> store(order.size());
std::vector<int> sizes(cumsum.size());
sizes[0]=cumsum[0];
for(int i=1;i<cumsum.size();i++)
sizes[i]=(cumsum[i]-cumsum[i-1]);
    if (place == cumsum[group]) {
    group++; min = 0;
    if (group == cumsum.size()) {
      int ij=0;
      for( std::vector<int>::iterator it = order.begin(); it != order.end(); ++it ){
store[ij]=*it;
    ij++;
  }
  finalcountdown[count]=mannwhit(store,sizes);
  count++;
  return;
    }
  }

  for( int v = min, max = usage.size() + place - cumsum[group]; v <= max; ++v ) {
    if (!usage[v]) {
    order[place] = v;
    usage[v] = 1;
    allocate_to_groups_impl(usage, order, cumsum, group, place+1, v+1);
  usage[v] = 0;
    }
  }
}

void allocate_to_groups( int *c, int Ngroups )
{
  size_t sum_of_c = 0;
  std::vector<int> cumsum_of_c;
  for( int* it = c; it < c + Ngroups; ++it ){
    cumsum_of_c.push_back(sum_of_c += *it);
  }
  std::vector<int> order(sum_of_c);
  std::vector<char> usage(sum_of_c);
  allocate_to_groups_impl(usage, order, cumsum_of_c, 0, 0, 0);
}

void jonckterp(int *x,int *c, int *ngrp, double *numcomb){
  count=0;
  float p=0;
  int d[*ngrp];
  for(int i=0; i< *ngrp; i++)
    d[i]=c[i];
  finalcountdown =tabInit(*numcomb);
  allocate_to_groups(d,*ngrp);
  for(int test=0;test<*numcomb;test++){
  if(finalcountdown[test]>=*x){
    p+=1;
}
}
*x=p;
}

wrapper.cpp

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern "C" {
void jonckterp(int *x,int *c, int *ngrp, double *numcomb);
}

jonckterp.R

early.fn<-function(stat,group.sizes){
numcomb<-factorial(sum(group.sizes))/prod(factorial(group.sizes))
.C("jonckterp",p=as.integer(stat),as.integer(group.sizes),as.integer(length(group.sizes)),as.double(numcomb))$p/numcomb
}


texts:
Let's say I want to write a super simple Python program to ask a user for their personal information and list it back out in a "pretty" format.
def get_info():
    first = input("enter your first name: ")
    while not first.isalpha():
        first = input("enter your first name: ")

    last = input("enter your last name: ")
    while not last.isalpha():
        last = input("enter your last name: ")

    age = input("enter your age: ")
    while not age.isnumeric():
        age = input("enter your age: ")
    age = int(age)

    has_pet = input("do you have a pet?: ").lower()
    while has_pet not in ["yes", "no", "y", "n"]:
        has_pet = input("do you have a pet?: ").lower()

    if "y" in has_pet:
        has_pet = True
    else:
        has_pet = False

    return [first, last, age, has_pet]

def print_info(info):
    first, last, age, has_pet = info
    print(f"Name: {first} {last}")
    print(f"Age: {age}")
    print(f"Has pet: {has_pet}")

print_info(get_info())

Clearly, I have violated DRY multiple times.
(1) Should I just throw the input() functions away and use arguments (with sys.argv)?
(2) The reason I can't use recursion is because I would have to ask the user for all of their information again if they mess up on, like, answering the pet question for example. Is there another way to clean up this code without sacrificing speed / resources?


texts: Reverse Polish Notation (RPN) Calculator

texts:
I am trying to solve a codewar challenge (link):

Your job is to create a calculator which evaluates expressions in Reverse Polish notation.
For example expression 5 1 2 + 4 * + 3 - (which is equivalent to 5 + ((1 + 2) * 4) - 3 in normal notation) should evaluate to 14.
For your convenience, the input is formatted such that a space is provided between every token.
Empty expression should evaluate to 0.
Valid operations are +, -, *, /.
You may assume that there won't be exceptional situations (like stack underflow or division by zero).

I have 2 problems, the first is that the code looks awful and I don't know how to improve it tbh,
I also want this code to be able to compute multiple digit numbers and i feel like i need to start from scratch if I want to add that.
Note : This is my first time writing a question so if there's anything wrong with it please tell me and I'll change it.
def calc(expr):
    stack = []
    for i in range(len(expr)):
        if expr[i].isdigit():
            stack.append(expr[i])
        if expr[i-1] == '.':
            stack.pop()
        if expr[i] == '.':
            stack.pop()
            stack.append(expr[i-1] +  expr[i] + expr[i+1])
        if expr[i] == '+':
            stack.append(float(stack[-2]) + float(stack[-1]))
            for i in range(2):
                del stack[-2]
        if expr[i] == '-':
            stack.append(float(stack[-2]) - float(stack[-1]))
            for i in range(2):
                del stack[-2]
        if expr[i] == '*':
            stack.append(float(stack[-2]) * float(stack[-1]))
            for i in range(2):
                del stack[-2]
        if expr[i] == '/':
            stack.append(float(stack[-2]) / float(stack[-1]))
            for i in range(2):
                del stack[-2]
    if stack == []:
        return 0
    else:
        return float(stack[0])


texts:
I created my own indexOf function. I was wondering if anyone could help me come up with a way to make it more efficient. I am practicing for interviews so the catch is that I cannot use any String methods. I believe the runtime of this method is O(n2) with space of O(n). Correct me if I am wrong.

Also, I want to ensure the program runs safely and correctly, the only test case I can think of it the length comparison.

public static int myIndexOf(char[] str, char[] substr) {
    int len = str.length;
    int sublen = substr.length;
    int count = 0;
            if (sublen > len) {
                return -1;
            }
    for (int i = 0; i < len - sublen + 1; i++) {
        for (int j = 0; j < sublen; j++) {
            if (str[j+i] == substr[j]) {
                count++;
                if (count == sublen) {
                    return i;
                }
            } else {
                count = 0;
                break;
            }
        }
    }
    return -1;
}


texts:
I have two snippets that are going to be used in a walkthrough and I'd like some feedback on which one is more easily understandable

1

    property int hours, minutes, seconds
    property real shift: 0.0
    property bool night

    function timeChanged() {
        var date = new Date();
        hours = date.getUTCHours() + Math.floor(clock.shift);
        minutes = date.getUTCMinutes() + (clock.shift % 1) * 60;
        seconds = date.getUTCSeconds();
        night = (hours < 7 || hours > 19);
    }

2

    property int hours, minutes, seconds
    property real shift
    property bool night

    function timeChanged() {
        var date = new Date;
        hours = shift ? date.getUTCHours() + Math.floor(clock.shift) : date.getHours()
        night = ( hours < 7 || hours > 19 );
        minutes = shift ? date.getUTCMinutes() + ((clock.shift % 1) * 60) : date.getMinutes()
        seconds = date.getUTCSeconds();
    }

I personally feel that instantiating the shift variable and skipping the ?: operator altogether is a better approach.

Note that both these snippets are aimed at a tutorial for people who are new to QML, and therefore I am charged with picking the one that seems simplest and clearest to people who don't know a lot about QML.


texts: Load other files (from outside public_html) under index.php

texts:
I wanted to load every page under index.php with a simple index.php?do=login

For example when the link index.php?do=login or /login/ is opened, the file login.php is loaded (from outside public_html), and so everything is done under index.php instead of having a separate php file in public_html for each action!

This is what I've tried already, am I doing it okay? (I'm not sure if what I'm doing has any security vulnerabilities, so please kindly advise)

index.php

<?php

// application path (outside public_html)
define('FILESPATH', APP.'../application/actions/');

// Default file
$file_name = 'home_page';

// e.g. index.php?do=login or /login/
if(isset($_GET['do'])){
    $file_name = rtrim($_GET['do'],'/');
}

// Set file path
$fpath = FILESPATH."{$file_name}.php";

// Make sure user input has valid characters a-z 0-9 _
if(preg_match('/^[A-Za-z0-9_]+$/', $file_name) !== 1 OR ! file_exists($fpath)){
    // Error
    require_once('404.php');
    die();
}

// Load the do=file
require_once($fpath);

// Nothing more comes in index.php

login.php

<?php

// Load template file header
require_once('header_template.php');

//
// Stuff that happens in login.php
// Checking if $_POST['username'] has valid chars then searching for it with pdo in db,
// password_verify() for $_POST['password'], etc...
//

// Load login's html template
// (which includes the html form submitted to /login/)
require_once('login_template.php');

// Load template footer
require_once('footer_template.php');

.htaccess

To run with site.com/login/ etc instead of site.com?do=login

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond   %{REQUEST_FILENAME} !-d
    RewriteCond   %{REQUEST_FILENAME} !-f
    RewriteRule   ^((?s).*)$ index.php?do=$1 [QSA,L]
</IfModule>


texts: Script to create symlinks for dotfiles in a Git repository

texts:
I have a GitHub repository containing all my dotfiles for bash, tmux and neovim. I'm using a Mac and whenever I factory reset it I like to just pull repository from GitHub and link all the dotfiles to the one in the repo.

Now I wrote a script to automatically create these symlinks and handle possible errors on the way.

This is what I came up with:

#!/usr/bin/env bash

RED=`tput setaf 1`
GREEN=`tput setaf 2`
RESET=`tput sgr0`

custom_link() {
  file_loc="$1"
  symlink_loc="$2"

  # Check whether original file is valid
  if [[ ! -e "$file_loc" ]]; then
    echo "${RED}WARNING${RESET}: Failed to link $symlink_loc to $file_loc"
    echo "         $file_loc does not exist"
    return 1
  fi

  # Check whether symlink already exists
  if [[ -e "$symlink_loc" ]]; then
    if [[ -L "$symlink_loc" ]]; then
      if [[ "$(readlink $symlink_loc)" == "$file_loc" ]]; then echo "--> $symlink_loc -> $file_loc ${GREEN}exists${RESET}."; return 0; fi

      current_dest=$(readlink "$symlink_loc")
      echo "It seems like $symlink_loc already is symlink to $current_dest."
      read -p "Do you want to replace it? [Y/N] " -n 1 -r
      if [[ $REPLY =~ ^[Yy]$ ]]
      then
        echo
        echo "Removing current symlink..."
        unlink  $symlink_loc
        ln -s "$file_loc" "$symlink_loc"
        echo "Created a symlink $symlink_loc -> $file_loc"
        return 0
      fi
      echo
      return 2
    else
      echo "It seems like $symlink_loc already exists."
      read -p "Do you want to [d]elete, [m]ove (-> $HOME/.other/) or [k]eep $symlink_loc? " -n 1 -r
      if [[ $REPLY =~ ^[Dd]$ ]]
      then
        printf "\nDeleting $symlink_loc..."
        rm -rf "$symlink_loc"
        ln -s "$file_loc" "$symlink_loc"
        echo "Created a symlink $symlink_loc -> $file_loc"
        return 0
      elif [[ $REPLY =~ ^[Mm]$ ]]; then
        printf "\nMoving $symlink_loc to ~$HOME/.other..."
        mkdir "$HOME/.other"
        mv "$symlink_loc" "$HOME/.other"
        ln -s "$file_loc" "$symlink_loc"
        echo "Created a symlink $symlink_loc -> $file_loc"
        return 0
      else
        printf "\nKeeping $symlink_loc...\n"
        return 2
      fi
    fi
  fi

  symlink_dir=$(dirname "$symlink_loc")
  if ! mkdir -p "$symlink_dir" ; then
   echo "${RED}WARNING${RESET}: Failed to link $symlink_loc to $file_loc"
   echo "         Could not create folder $symlink_dir/"
   return 1
  fi

  ln -s "$file_loc" "$symlink_loc"
  echo "Created a symlink $symlink_loc -> $file_loc"
  return 0
}

custom_link "$HOME/.dotfiles/bash/.bashrc" "$HOME/.bash_profile"
custom_link "$HOME/.dotfiles/bash/.bashrc" "$HOME/.bashrc"
custom_link "$HOME/.dotfiles/nvim/init.vim" "$HOME/.config/nvim/init.vim"
custom_link "$HOME/.dotfiles/tmux/.tmux.conf" "$HOME/.tmux.conf"

It was my very first time writing a bash script and I just googled, whenever I had a specific question.

I choose the return codes as follows:
- 0 for successful creation
- 1 for failure
- 2 for cases, when the link was not created, because the user decided so.

My questions are:

How is my general bash programming style? Any important idioms I missed?
The script contains a lot of duplicate code (especially the three lines: ln -s "$file_loc" "$symlink_loc", echo "Created a symlink $symlink_loc -> $file_loc" and return 0. How can I reduce the number of duplicates?
How could I implement more successful return values?
I handles a lot of cases (the file already exists, etc.). Did I miss any important cases?
Currently the function custom_link displays a lot of text. How could I outsource this echoing to the outside of the function? The function should do the bare minimum (maybe connected to the question about useful return codes).


texts: Number of Occurrences of a word in a text file or group of text files

texts:
The question given to me was as follows :
WAP to take the input from the user a path and a word. If the path is a text file, search the word in the file and print the number of occurrences. If the path is a folder, read the files in the folder and print the number of occurrences in all the text files of the word.

Is what I did an effecient way of going about it? Please ignore indentations and lack of comments.

This was my code :

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class TestOccurances {

public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
String path, word;
System.out.println("Enter a path");
path = sc1.nextLine();
System.out.println("Enter the word");
word = sc1.nextLine();
sc1.close();
File f = new File(path);
BufferedReader br = null;
List<String> list = new ArrayList<String>();
try {
//Checking to see if its a .txt file
if(f.exists() && f.isFile() && f.getName().endsWith(".txt")){
    br  = new BufferedReader(new FileReader(path));
    String line;
    while((line=br.readLine())!=null) {
        String[] arr = line.split(" ");
        for(String str : arr)
        list.add(str);
        }
    System.out.println("Single text file, Frequency = "+Collections.frequency(list, word));
    }
//Checking to see if its a folder
if(f.exists() && f.isDirectory()) {
    File[] allfiles = f.listFiles();
    List<File>  files= new ArrayList<File>();
    for(File f1 : allfiles) {
        if(f1.getName().endsWith(".txt"))
            files.add(f1);
    }
    //Loop through each text file and do the same as above
    for(File file : files) {
        List<String> occurances = new ArrayList<String>();
        br = new BufferedReader(new FileReader(file.getPath()));
        String line;
        while((line=br.readLine())!=null) {
            String[] arr = line.split(" ");
            for(String str : arr)
            occurances.add(str);
            }
        System.out.println("File path :"+file.getName()+" , Frequency = "+Collections.frequency(occurances, word));
        }
    }
}catch(IOException e) {
    e.printStackTrace();
    }
finally {
    if(br!=null) {
        try {
            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
    }
}

}


texts: Using python classes to classify database records

texts:
I have a database, with tens of thousands of records, which I wish to represent in python. The python 2.x version has tables in which each record is an instance of a class and the values in the record are held in attributes of the object. Some of the attributes are terms which are used to classify records. The classifications in my database relate to some technical metadata structures, so here, to concentrate on the essential coding question.
If I have a collection of objects which are classified by, for example, colour and year, does it make sense to represent the colour and year as python super-classes (perhaps as illustrated below) rather than as attribute values?
In the following example I've created a potential implementation:
import time
## Cars will be classified Colour and Year

class Colour(type): pass

class Year(type):
    description = 'Year of purchase'

## A class for cars classified by year and colour
class Car(Colour,Year): pass

## colours for classification
#
# Duplication in specification of colour could be removed by using a factory to
# generate these classes from tabulated information.
#
Red = Colour( 'red', (object,), dict(description='The primary colour red',colour='red') )
Blue = Colour( 'blue', (object,), dict(description='The primary colour blue',colour='blue') )
Green = Colour( 'green', (object,), dict(description='The primary colour green',colour='green') )

# years for classification.
Y2015 = Year( '2015', (object,), dict(description='2015 AD' ) )
Y2016 = Year( '2016', (object,), dict(description='2016 AD' ) )
Y2017 = Year( '2017', (object,), dict(description='2017 AD' ) )
Y2018 = Year( '2018', (object,), dict(description='2018 AD' ) )

# for each
class CarRecord(object):
    def __init__(self,comment):
        self.record_date=time.ctime()
        self.comment=comment

#
# records are classified by the colour and year classes.
#
MyCar = Car( 'MyCar', (CarRecord,Blue,Y2018), dict( comment='car number 1' ) )
HisCar = Car( 'HisCar', (CarRecord,Green,Y2016), dict( comment='car number 2' ) )

## instantiation creates a specific metadata record, with timestamp
my_car = MyCar('A very good car')
his_car = HisCar("Someone else's car")

This example appears to work smoothly, but I have arrived at this point by trial-and-error and have some concerns that I may not fully understand the implications of some of the coding structures used.
Advantages

The categories Blue, Red etc are python objects and can carry additional descriptive information and helper methods as needed;
There is a clear separation between properties such as Colour, which are part of a classification scheme, and description, which is a free-text attribute;
Ability to add attributes and methods to categories (Red, Blue etc) and category groups (Colour, Year) in a transparent way;

Disadvantages

Could there be hidden performance overheads when expanding the number of category groups to 10 and the number of categories to hundreds?
Is there a better way of handling the relationship between concepts being categorised (the cars hers) and concepts being used for categorisation?


texts: Populating an unordered list from values in a JSON file

texts:
I have this view that populates an unordered list from values in a JSON file, which I am doing in Node.

Is there a better way to do this, or a more 'node-like' way? Can I load the JSON file without an Ajax call?

<!DOCTYPE html>

    <title>4&middot;pli -- news</title>
    <link rel='stylesheet' href='/stylesheets/style.css'/>

    <link href='http://fonts.googleapis.com/css?family=Didact+Gothic' rel='stylesheet' type='text/css'>

<% include shared/nav.ejs %>

<% include /shared/footer.ejs %>


texts: Cartesian product of two tuples - python

texts:
I'm solving exercise 4 from Discussion 3 of Berkley's CS 61A (2012) (see page 4):

Fill in the definition of cartesian_product. cartesian_product takes in two tuples and returns a tuple that is the Cartesian product of those tuples. To find the Cartesian product of tuple X and tuple Y, you take the first element in X and pair it up with all the elements in Y. Then, you take the second element in X and pair it up with all the elements in Y, and so on.
def cartesian_product(tup_1, tup_2):
    """Returns a tuple that is the cartesian product of tup_1 and tup_2.
    >>> X = (1, 2)
    >>> Y = (4, 5)
    >>> cartesian_product(X, Y)
    ((1, 4), (4, 1) (1, 5), (5, 1), (2, 4), (4, 2) (2, 5), (5, 2))
    """

My solution:
def cartesian_product_recursive(tup_1, tup_2):
    """Returns a tuple that is the cartesian product of tup_1 and tup_2

    >>> X = (1, 2)
    >>> Y = (4, 5)
    >>> cartesian_product(X, Y)
    ((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2))
    """
    length1 = len(tup_1)
    length2 = len(tup_2)
    def product(tup_1, tup_2, index1, index2):
        if index1 == length1:
            return ()
        elif index2 == length2:
            return product(tup_1, tup_2, index1 + 1, 0)
        else:
            return ((tup_1[index1], tup_2[index2]),) + ((tup_2[index2], tup_1[index1]), ) + product(tup_1, tup_2, index1, index2 + 1)
    return product(tup_1, tup_2, 0, 0)

I know that Python has a built-in function itertools.product, but at this point in the course, the only operations on tuples that we have studied are indexing [1] [-1], slicing [1:], and concatenation +, so my solution needs to restrict itself accordingly.
Can this solution be improved?


texts: Golang keep installation status for multiple installations process

texts:
Im fairly new to Golang and I appreciate any feedback about how to make the code cleaner.
The code is called by go-routine and should update status (fail/success etc) of several installation process.
package avss

import (
    "context"
    "sync"

    "helm.sh/helm/v3/pkg/release"

    "sigs.k8s.io/controller-runtime/pkg/client"

    avmv1alpha1 "github.vmp/avs/api/v1alpha1"
)

func GetUpdateStatus(ctx context.Context, log logr.Logger, cr client.Object, status *avmv1alpha1.ComponentStatusWithAggregation, statusClient client.StatusClient) func(chartStatus *avmv1alpha1.InstallStatus) error {
    var conditionMutex sync.Mutex

    return func(chartStatus *avmv1alpha1.InstallStatus) error {

        // prevent status update by subroutines at the same time, lock the access to prevent concurrent modification
        conditionMutex.Lock()
        defer conditionMutex.Unlock()
        status.ChartStatus = updateStatus(chartStatus, status.ChartStatus)
        status.Status = overallStatus(status.ChartStatus)
        err := statusClient.Status().Update(ctx, cr)
        return err
    }
}

func overallStatus(chartsStatus []avmv1alpha1.InstallStatus) string {
    overallStatus := ""
    for _, status := range chartsStatus {
        switch status.ReleaseStatus {
        case release.StatusFailed.String():
            overallStatus = "error"
        case release.StatusDeployed.String():
            if overallStatus == "" {
                overallStatus = "installed"
            }
        default:
            if overallStatus != release.StatusFailed.String() {
                overallStatus = "reconcile"
            }
        }
    }
    return overallStatus
}

func updateStatus(newStatus *avmv1alpha1.ChartStatus, cStatus []avmv1alpha1.InstallStatus) []avmv1alpha1.ChartStatus {
    found := false
    for i, status := range cStatus {
        if status.Name == newStatus.Name {
            found = true
            cStatus[i] = *newStatus
        }
    }
    if !found {
        cStatus = append(cStatus, *newStatus)
    }
    return cStatus
}

https://play.golang.org/p/9C8xGV2116O
The code is working! however, I guess it can be improved as this is my first Go program which should be run in production :-)
If the code is perfect,   please let me know


texts: Reading a certain pixels color from a window

texts:
I'm currently reading a certain pixels color from a process window like this:

[DllImport("gdi32.dll")]
private static extern int BitBlt(IntPtr srchDc, int srcX, int srcY, int srcW, int srcH,
                                 IntPtr desthDc, int destX, int destY, int op);

public static Color GetPixel(IntPtr hwnd, int x, int y)
{
    var screenPixel = new Bitmap(1, 1);

    using (Graphics gdest = Graphics.FromImage(screenPixel))
    {
        using (Graphics gsrc = Graphics.FromHwnd(MemoryHandler.GetMainWindowHandle()))
        {
            IntPtr hsrcdc = gsrc.GetHdc();
            IntPtr hdc = gdest.GetHdc();
            BitBlt(hdc, 0, 0, 1, 1, hsrcdc, x, y, (int)CopyPixelOperation.SourceCopy);
            gdest.ReleaseHdc();
            gsrc.ReleaseHdc();
        }
    }

    return screenPixel.GetPixel(0, 0);
}

It seems to be working.

I would like to know if I'm disposing everything that I use correctly to avoid memory leaks. If I inspect my app in the task manager I notice that the memory use is increasing a bit for each time i fetch a pixel, but I suppose the garbage collector will kick in when it's supposed to?

Also, is there any obvious "better" way of doing this?


texts:
I'm new to C# and OO programing.
I have an aspx page with 3 lists of checkboxes and I would like to generate them from the DB.
how should I structure my code?

Here is an example of what I did so far:

ASPX page

<asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList>
<asp:CheckBoxList ID="CheckBoxList2" runat="server"></asp:CheckBoxList>
<asp:CheckBoxList ID="CheckBoxList3" runat="server"></asp:CheckBoxList>

ASPX Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GenerateCheckBoxList1();
        GenerateCheckBoxList2();
    }
}

private void GenerateCheckBoxList1()
{
    CBLists cbl = new CBLists();
    CheckBoxList1.DataSource = cbl.GetCheckBoxList1();
    CheckBoxList1.DataTextField = "name";
    CheckBoxList1.DataValueField = "id";
    CheckBoxList1.DataBind();
}

private void GenerateCheckBoxList2()
{
    CBLists cbl = new CBLists();
    CheckBoxList2.DataSource = cbl.GetCheckBoxList2();
    CheckBoxList2.DataTextField = "country";
    CheckBoxList2.DataValueField = "country_id";
    CheckBoxList2.DataBind();
}

a class file to handle the connection to the db and return the DataSet:

public class CBLists
{
    private SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CONN"].ConnectionString);
public DataSet GetCheckBoxList1()
{
    try
    {
        DataSet ds = new DataSet();
        string cmdstr = "select * from table1 where id<>999 order by id";
        SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conn);
        adp.Fill(ds);
        return ds;
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        conn.Close();
    }

}

public DataSet GetCheckBoxList2()
{
    try
    {
        DataSet ds = new DataSet();
        string cmdstr = "select * from table2";
        SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conn);
        adp.Fill(ds);
        return ds;
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        conn.Close();
    }
}

Is this the "correct" way to do it? multiple methods in a separate file?


texts: use of FTP URI to copy file from FTP server to Local Disk have Delay

texts:
i have this php Script:

function GetFTPFile($iFile) {
        echo '
';
        $StartTime   = microtime(true);
        $FTP         = [];
        $FTP['SMG']  = '';
        $FTP['st']   = 0;
        $FTP['time'] = 0;
        $nuevo_path  = $iFile['lfile'];
        $remote      = $iFile['sfile'];
        echo $P_Path      = 'ftp://' . FTP_USER . ':' . FTP_PASSWORD . '@' . FTP_HOST . $remote;
        echo '
';
        $FTP['test'] = $P_Path;
        $result      = file_exists($P_Path);
        if ($result == true) {
            $resultfile = copy($P_Path, $nuevo_path);
            if ($resultfile == true) {
                $FTP['SMG'] = 'Copy Successfull';
                $FTP['st']  = 1;
            } else {
                $FTP['SMG'] = 'Copy Fail!!!';
                $FTP['st']  = 0;
            }
        } else {
            $FTP['SMG'] = 'Conection Error!!!';
            $FTP['st']  = 0;
        }
        $EndTime     = microtime(true);
        echo 'Copy time via FTP:
';
        echo $FTP['time'] = $EndTime - $StartTime;
        echo '
';
        return $FTP;
    }

and this create a FTP URI Like this

ftp://user:secretpass@xxx.xxx.xxx.xxx/dir1/dir2/repository/test.txt

And try to copy a txt File around 85 Kb from the FTP Server (UNIX) to local Disk (Linux Ubuntu Server 18.04)

the issues is that this is taken around 20 second to run the script over the file with the native function copy().

i try to make the connection over FTP client Filezilla to get the log and get this, i dont know if its relation to this:

11:16:08 Status: Connecting to xxx.xxx.xxx.xxx:21 ...
11:16:08 Status: Connection established, waiting for the welcome message ...
11:16:22 Status: Server not secure, does not support FTP over TLS.
11:16:22 Status: The server does not allow non-ASCII characters.**
11:16:22 Status: Registered at
11:16:22 Status: Retrieving the directory listing ...
11:16:22 Status: Directory "/ usr / intlu" listed correctly

which is what I am omitting, how can I decrease this delay or how to solve it?


texts: Get average of each nested array in dynamic object

texts:
I'm iterating this JSON using a for loop:

var movieObj = {
    "cat": {
        "moveName": "Breath",
        "rating": [4, 5, 4, 3]
    },
    "cat1": {
        "moveName": "shallow",
        "rating": [5, 5, 5, 5, 4]
    }
}

Is there any way to improve this code?

var sum;

Array.prototype.getSum = function (ele) {
    sum = ele.reduce(function (a, b) {
        return a + b
    });
    return sum / ele.length
}

for (var key in movieObj) {
    var b = movieObj[key];

    if (Array.prototype.getSum(b['rating']) < 5) {
        console.log(b['moveName']);
    }
}


texts:
Usually the socket.io's on method is like this:

socket.on('/msg', function(data){});

But in Angular that callback has to be wrapped inside its $rootScope.$apply() method otherwise anything that happens in the callback (like changing $scope properties) doesn't update in Angular.

Here's a simple way to do that:

function socketFactory($rootScope) {
    return {
        emit: socket.emit.bind(socket),
        on: function(msg, callback) {
            socket.on(msg, function() {
                var args = arguments;
                $rootScope.$apply(function(){
                    callback.apply(socket, arguments)
                });
            });
        },
    };
};

I was able to shorten this a little bit:

on: function(msg, callback) {
    socket.on(msg, function() {
        $rootScope.$apply(callback.apply(socket, arguments));
    });
},

I'm not sure if it'll go any further but I tried:

on: function(msg, callback) {
    socket.on(msg, $rootScope.$apply.apply(null, callback));
},

which threw an error:

  Uncaught TypeError: Cannot read property 'apply' of undefined socket.io.js:1194

I'm guessing $apply.apply doesn't work.


texts: Load from dictionary or database if not found

texts:
Today I have coded a simple function that will get a room model, if its already been loaded in to the dictionary then it will just return it, if its not in the dictionary if will try its best to load it from the database. I just wondered is this the best way I can do ths? or is there a better way...

public bool TryGetModel(string modelName, out RoomModel model)
{
    if (_roomModels.ContainsKey(modelName))
    {
        _roomModels.TryGetValue(modelName, out model);
        return true;
    }

    using (var mysqlConnection = Sahara.GetServer().GetMySql().GetConnection())
    {
        mysqlConnection.SetQuery("SELECT id,door_x,door_y,door_z,door_dir,heightmap,public_items,club_only,poolmap,`wall_height` FROM `room_models` WHERE `custom`");
        var modelRow = mysqlConnection.GetRow();

        if (modelRow == null)
        {
            model = null;
            return false;
        }

        model = new RoomModel(Convert.ToInt32(modelRow["door_x"]), Convert.ToInt32(modelRow["door_y"]),
            Convert.ToDouble(modelRow["door_z"]), Convert.ToInt32(modelRow["door_dir"]),
            Convert.ToString(modelRow["heightmap"]), Convert.ToString(modelRow["public_items"]),
            Convert.ToInt32(modelRow["club_only"]).ToString() == "1", Convert.ToString(modelRow["poolmap"]),
            Convert.ToInt32(modelRow["wall_height"]));

        _roomModels.Add(Convert.ToString(modelRow["id"]), model); // save it for next time!!
        return true;
    }
}


texts: Extracting the longest line from standard input

texts:
I'm reading the K&R book and I'm interested in a program which finds the longest line on the input. I've written the same code as in the book, but I wanted to do it myself. I tried to write my own code to do same thing. I think it's working, but my question is whether my code is "good" or if it's written in a "bad way" and can be written easily.

K&R Code:

#include <stdio.h>
#define MAXLINE 1000

int getline(char line[], int maxline);
void copy(char to[], char from[]);

main () {

 int len;
 int max;
 char line[MAXLINE];
 char longest[MAXLINE];

 max = 0;

 while ((len = getline(line, MAXLINE)) > 0) {

   if(len > max) {

     max = len;
     copy(longest, line);

   }

 }

 if(max > 0) printf("%s", longest);

 return 0;
}

int getline (char line[], int limit) {

 int i, c;

 for (i = 0;  i < limit - 1 && (c = getchar()) != EOF && c != '\n';  i++) line[i] = c;

 if (c == '\n') {

  line[i] = c;
  i++;

 }

 line[i] = '\0';

 return i;
}

void copy(char to[], char from[]) {

  int i;

  i = 0;
  while((to[i] = from[i]) != '\0')
    i++;
}

My code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 1000

int main()
{
    int ch; //char input
    int length; //length of the line
    int max=0; //length of the longest line
    int j=0;
    int i=0;
    char line[MAX_LINE]; //line input
    char help [MAX_LINE];
    char longest [MAX_LINE]; //longest line

    while ((ch=getchar())!='\n'){ //first line
        longest[i]=ch;
        ++i;
    }

    max=i;
    i=0;
    length=0;
    while ((ch=getchar())!=EOF){
        line[i]=ch;
        help[j]=ch;
        ++j;
        ++i;
        ++length;
        if (ch=='\n'){
                help[j]='\0';
            if (length-1>max){
                max=length-1;
                j=0;
                printf("Longest -> %s",help);
                }
            else {
                memset(help,0,100); //erase elements
            }
            length=0;
        }

    }
    return 0;
}


texts: Filtering with multiple inclusion and exclusion patterns

texts:
I have a requirement to be able to filter a list of strings by both inclusion and exclusion patterns (using fnmatch-style wildcards), of which there can be many.

For example, given the set of values:

['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']

And these inclusion filters:

['a*', 'b*']

It should return:

['a1', 'a2', 'a3', 'b1', 'b2', 'b3']

It should also support using exclusion filters, e.g. ['c*'] to get the same result.

Lastly, using both inclusion and exclusion filters, the exclusion filters should take precedence in case of a conflict.

Here is my code and tests:

extrafilters.py

import fnmatch

def superFilter(names, inclusion_patterns=[], exclusion_patterns=[]):
    """Enhanced version of fnmatch.filter() that accepts multiple inclusion and exclusion patterns.
    If only inclusion_patterns is specified, only the names which match one or more patterns are returned.
    If only exclusion_patterns is specified, only the names which do not match any pattern are returned.
    If both are specified, the exclusion patterns take precedence.
    If neither is specified, the input is returned as-is."""
    included = multiFilter(names, inclusion_patterns) if inclusion_patterns else names
    excluded = multiFilter(names, exclusion_patterns) if exclusion_patterns else []
    return set(included) - set(excluded)

def multiFilter(names, patterns):
    """Generator function which yields the names that match one or more of the patterns."""
    for name in names:
        for pattern in patterns:
            if fnmatch.fnmatch(name, pattern):
                yield name

extrafilters_test.py

import unittest
from extrafilters import superFilter, multiFilter

class multiFilterTests(unittest.TestCase):
    def setUp(self):
        self.names = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']

    def test_patterns(self):
        patterns = ['a*', 'b*']
        expected = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3']
        self.assertItemsEqual(list(multiFilter(self.names, patterns)), expected,
            'should include only the names which match one or more of the patterns')

class superFilterTests(unittest.TestCase):
    def setUp(self):
        self.names = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']

    def test_no_patterns(self):
        expected = self.names
        self.assertItemsEqual(superFilter(self.names), expected,
            'should be the same as the input')

    def test_inclusion(self):
        include = ['a*', 'b*']
        expected = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3']
        self.assertItemsEqual(superFilter(self.names, include), expected,
            'should include only the inclusions')

    def test_exclusion(self):
        exclude = ['c*']
        expected = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3']
        self.assertItemsEqual(superFilter(self.names, exclusion_patterns=exclude), expected,
            'should include all but the exclusions')

    def test_inclusions_and_exclusions(self):
        include = ['a*', 'b*']
        exclude = ['b*']
        expected = ['a1', 'a2', 'a3']
        self.assertItemsEqual(superFilter(self.names, include, exclude), expected,
            'should include the inclusions minus the exclusions')

if __name__ == "__main__":
    unittest.main()

What corner cases will break this, and how is the clarity of the code (function names, docstrings, etc.)? Are the unit tests complete and detailed enough or perhaps too much? Any other style or quality tips are also appreciated.


texts: Transform poor CSS into a more beatiful form in Dart

texts:
I have this script that opens a file containing (possibly) bad CSS, lexes the content of it and creates a new file with the same code in a more pleasant way to look at. It formats it and sorts the properties alphabetically.

I would love to hear some very critical feedback on coding style, best practises and how I can make it cleaner.

Some concerns I have right now are the global variables (like i and iSort), the hard coded file path and the use of while loops.

I am trying to make it as easy as possible for others to read, but to me it seems as if passing around file[i] and other variables makes it more cluttered than it should be.

The exception handling seems unnecessary, but without it, the index overflows at some point and the program execution just stops. Is there a way I can avoid it in this case?

import 'dart:io';
import "dart:core";

class Token {
  String identifier;
  String value;
  Token(this.identifier, this.value);
}

List<Token> tokens = [];

void main() {
  String rootPath = "C:/Users/User/Desktop/Datein/AlphaCSS/bin/";
  String originalFilePath = "samplecss.css";

  new File(rootPath + originalFilePath).readAsString().then((String file) {
    List<Token> tokens = getTokensFromFile(file);
    List<Token> sortedTokens = getSortedTokens(tokens);
    new File(rootPath + "newcss.txt").writeAsStringSync(reconstructCSS(sortedTokens));
  });
}

int i = 0;

List<Token> getTokensFromFile(file){
  String value = "";
  while (i < file.length-1){
    value = "";
    if (isValidStart(file[i])){
      value = getTokenContent(file);
      addTokenBasedOnType(file[i], value);
    }
    else if (isEndOfSelector(file[i])){
      addTokenBasedOnType(file[i], "");
    }
    i++;
  }
  return tokens;
}

bool isValidStart(String char){
  RegExp regex = new RegExp(r"[a-zA-Z0-9#.]");
  return (regex.hasMatch(char)) ? true : false;
}

bool isEndOfSelector(String char){
  return (char == "}") ? true : false;
}

String getTokenContent(String file){
  String content = "";
  while (file[i] != "{" && file[i] != ";"){
    content += file[i];
    i++;
  }
  return content;
}

void addTokenBasedOnType(String char, String value){
  if (char == "{"){
    tokens.add(new Token("SELECTOR", value));
  }
  else if (char == "}"){
    tokens.add(new Token("END", ""));
  }
  else {
    tokens.add(new Token("PROPERTY", value));
  }
}

int iSort = 0;

List<Token> getSortedTokens(tokens){

  List<Token> sortedTokens = [];
  try {
    while (iSort < tokens.length){
      if (tokens[iSort].identifier == "PROPERTY"){
        List<Token> toSort = getAllPropertiesInSelector();
        iSort--;
        toSort.sort((current, next) => current.value.compareTo(next.value));
        for (var elem in toSort){
          sortedTokens.add(elem);
        }
      }
      else {
        sortedTokens.add(tokens[iSort]);
      }
      iSort++;
    }
  }
  catch(ex) { }
  return sortedTokens;
}

List<Token> getAllPropertiesInSelector(){
  List<Token> properties = [];
  try {
    while (tokens[iSort].identifier == "PROPERTY"){
      properties.add(tokens[iSort]);
      iSort++;
    }
  }
  catch(ex) { };
  return properties;
}

String reconstructCSS(List<Token> sortedTokens) {
  String finalString = "";

  for (var elem in sortedTokens){
    if (elem.identifier == "SELECTOR"){
      finalString += "${elem.value}{\n";
    }
    else if (elem.identifier == "END"){
      finalString += "}\n\n";
    }
    else if (elem.identifier == "PROPERTY"){
      finalString += "  ${elem.value};\n";
    }
  }
  return finalString;
}


texts: Would it be better with try except imbricated?

texts:
What do you think of this code?  I want to keep an unified interface (treat filepath or image interchangeably) but i have heard try except is the prefered way, how would you do?
def rotate_img(imageref, deg):
"""
Rotate from [deg] degree the input image
param imageref: can be imagepath or ndarray image
param deg: number of rotation degree desired
"""
if isinstance(imageref,np.ndarray):
    from scipy import ndimage
    img = imageref
    img_rt = ndimage.rotate(img, deg, reshape=False)
elif isinstance(imageref,str):
    img = Image.open(imageref)
    img_rt = img.rotate(deg, expand=1)
else:
    raise('Unknown Type')
return img_rt


texts:
I decided to subclass SKSpriteNode for a game test in Swift today and soon realised that it was not as simple as my Objective-C background suggested. After a little hunting around and a bit of testing in Playgrounds I have come up with the following (See below). I have not tested this in a project as I am just starting out on my next game but thought I would add this here to see if I am on the right track with this, does what I have done look right, any suggestions or comments would be most helpful.

I am pretty happy with this, but I was just curious if there was anything I was not doing, or something that I was doing that I should not be.

// ------------------------------------------------------------------- **
// SKSpriteNode subclass, NSCoding not implemented
// ------------------------------------------------------------------- **

class SimpleSprite: SKSpriteNode {
    var simpleName: String
    var simpleType: Double

    init(simpleName: String, simpleType: Double) {
        self.simpleName = simpleName
        self.simpleType = simpleType
        let spriteColor = SKColor.redColor()
        let spriteSize = CGSize(width: 10.0, height: 10.0)
        super.init(texture: nil, color: spriteColor, size: spriteSize)
    }

    required init?(coder aDecoder: NSCoder) {
        // Class does not want to be NSCoding-compatible
        fatalError("init(coder:) has not been implemented")
    }
}

let simpleSprite = SimpleSprite(simpleName: "SimpleRabbit", simpleType: 22.1)
simpleSprite.simpleName
simpleSprite.color

// ------------------------------------------------------------------- **
// SKSpriteNode subclass, NSCoding-compatible
// ------------------------------------------------------------------- **

class CodedSprite: SKSpriteNode {
    var simpleName: String
    var simpleType: Double

    init(simpleName: String, simpleType: Double) {
        self.simpleName = simpleName
        self.simpleType = simpleType
        let spriteColor = SKColor.whiteColor()
        let spriteSize = CGSize(width: 10.0, height: 10.0)
        super.init(texture: nil, color: spriteColor, size: spriteSize)
    }

    required init?(coder aDecoder: NSCoder) {
        self.simpleName = aDecoder.decodeObjectForKey("SIMPLE_NAME") as String
        self.simpleType = aDecoder.decodeDoubleForKey("SIMPLE_TYPE")
        super.init(coder: aDecoder)
    }

    override func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.simpleName, forKey: "SIMPLE_NAME")
        aCoder.encodeDouble(self.simpleType, forKey: "SIMPLE_TYPE")
        super.encodeWithCoder(aCoder)
    }

}

let codedSprite = CodedSprite(simpleName: "CodedRabbit", simpleType: 22.1)
codedSprite.simpleName
codedSprite.color


texts:
I recently suggested this method for emulating the Unix utility split in Python.

Is there a more elegant way of doing it?

Assume that the file chunks are too large to be held in memory. Assume that only one line can be held in memory.

import contextlib

def modulo(i,l):
    return i%l

def writeline(fd_out, line):
    fd_out.write('{}\n'.format(line))

file_large = 'large_file.txt'
l = 30*10**6  # lines per split file
with contextlib.ExitStack() as stack:
    fd_in = stack.enter_context(open(file_large))
    for i, line in enumerate(fd_in):
        if not modulo(i,l):
           file_split = '{}.{}'.format(file_large, i//l)
           fd_out = stack.enter_context(open(file_split, 'w'))
        fd_out.write('{}\n'.format(line))

I ran the Unix utility time and the Python module cProfile. Here is what I found (methods not comparable, as I was running other processes, but gives a good indication of slow parts of code):

Ugo's method:

tottime filename:lineno(function)
473.088 {method 'writelines' of '_io._IOBase' objects}

485.36 real       362.04 user        58.91 sys

My code:

tottime function
243.532 modulo
543.031 writeline
419.366 {method 'format' of 'str' objects}
1169.735 {method 'write' of '_io.TextIOWrapper' objects}

3207.60 real      2291.42 user        44.64 sys

The Unix utility split:

1676.82 real       268.92 user      1399.16 sys


texts:
I wrote an isPermute method. Can I get some tips and advice on better coding style?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

bool isPermute(char*, char*);
char* sort(char*);

int main(int argv, char **argc)
{
  printf("%s and %s are %spermutations of each other. \n", argc[1], argc[2], isPermute(argc[1], argc[2]) ?
    "" : "not ");

  return 0;
}

bool isPermute(char* s1, char* s2)
{

  int size1 = strlen(s1);
  int size2 = strlen(s2);

  //default cases
  if((size1 != size2) || (size1 == 0) || (size2==0))
    return false;

  if(strcmp(sort(s1), sort(s2)))
    return false;

  else
    return true;
}

char* sort(char* str1)
{
  int d=0, size = strlen(str1);
  char character;
  char *original = str1;

  char *result = (char *)malloc(size);

  for ( character = 'a' ; character <= 'z' ; character++ )
  {
     int i;
     for ( i = 0 ; i < size ; i++ )
     {
        if ( str1[i] == character )
        {
           result[d] = str1[i];
           d++;
        }
     }
     str1 = original;
  }
  return result;
}


texts: Finding .txt files that exist in one directory but not the other

texts:
I need to check a condition, and based on the condition perform a very similar for-loop.

import os

folder = r'path'
folder_list = os.listdir(folder)
folder2 = r'path/folder2'
args = True

the_list = []

if args is True:

    for x in folder_list:

        if x.endswith('.txt'):

            if not os.path.exists(os.path.join(folder2, x)):
                full_path = os.path.join(folder, x)
                the_list.append(full_path)
else:

    for x in folder_list:

        if x.endswith('.txt'):
                full_path = os.path.join(folder, x)
                the_list.append(x)

I would like to avoid having the redundant for-loop code if possible.
I originally had the following, which I wasn't happy with because args was being checked every single iteration, which is unnecessary.

import os

folder = r'path'
folder_list = os.listdir(folder)
folder2 = r'path/folder2'
args = True
the_list = []

for x in folder_list:

    if x.endswith('.txt'):
        full_path = os.path.join(folder, x)
        if args['i'] is True:

            if not os.path.exists(os.path.join(folder2, x)):
                the_list.append(full_path)

        else:
            the_list.append(full_path)


texts: Create HTML page to document contents of directory

texts:
I often work on embedded system projects in which I have a number of documentation files, such as microprocessor datasheets, schematics, bills of materials, etc.  I find it convenient to create a simple little HTML file that contains the file descriptions and a hyperlink to each file.  I used to create these all by hand, but I now have an automated script that does that for me.  I still have to edit the file to include the descriptions of the files, but this creates both an index.html and style.css file as a start.  I'd be interested in a review of both the Python code and the HTML and Javascript and CSS that it creates.  The code is intended solely for use on a Linux box.

Invocation and use

This is designed to placed in the path and invoked from the command line from within the directory to be documented.  Then the resulting HTML file is invoked in the same way as with firefox index.html.  Although it doesn't make much difference in this case, the intent is that the HTML file is not served from a web server but simply interpreted from the file system so that the entire project, with documentation, can be put on a CD or DVD (or other read-only media) and used without having to run a web server.

docdir.py

#! /usr/bin/python3
from os import walk

style = '''\
body
{
    font-style:normal;
    font-family:sans-serif,Georgia, Helvetica, Arial, sans-serif;
        background-color:white;
    color:black;
    margin-left:5%;
}
div.navbar
{
    text-align:center;
}
h1
{
    text-indent:1em;
    color:white;
    background-color:navy;
}
h2
{
    text-indent:2em;
    color:white;
    background-color:navy;
}
h3
{
    margin-left:1em;
    margin-right:1em;
    text-indent:2em;
    color:white;
    background-color:navy;
}
div.trailer table
{
    width:100%;
    border-style:none;
    padding-left:0;
}
table
{
    border-style:solid;
}
td
{
    padding-left:20px;
}
caption
{
    font-style:oblique;
}'''

index_tail='''\
];

function loadLinks() {
    var table = document.getElementById("docTable");
    links.reverse();
    links.forEach(function(element, index, array) {
        var row = table.insertRow(0);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        cell1.innerHTML = "" + element.name + "";
        cell2.innerHTML = element.desc;
    });
}
</script>

Documents

These directories may contain proprietary and confidential information.

Document list

&nbsp;

    index.html

this file

'''

if __name__=="__main__":
    title="Documents"
    index_head=f'''\
<!DOCTYPE html>

<title>{title}</title>
<link rel="stylesheet" href="style.css">


texts: Number to words in left to right direction

texts:
I have faced this question in an interview:

If we enter a number it will convert into individual strings and display in same order.
Ex: If I enter 564 then the output should be FIVE SIX FOUR.

I have written the following working code (of course it has some limitations).  Suggest any possible ways of optimizing this code.
public class NoToWord {

    public static void main(String[] a)
    {
        int no = 0;
        String[] words= new String[]{"ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};
        String[] word=new String[10];

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            no = Integer.parseInt(br.readLine());
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int i,j;
        j=0;
        while(no>0){
            i = no%10;
            no /= 10;
            word[j] = words[i];
            j++;
        }
        for(int k= word.length;k>0;k--)
        {
            System.out.println(word[k-1]+" ");
        }
    }
}


texts: Print total occurrences of a char in a string

texts:
Scenario: Count the total number of times a char occurs in a word.

For instance, "aaabbcccdddaaaa" should print out "a7b2c3d3".

Can you please  critique my code?

import java.util.HashMap;
import java.util.Map;

public class Demo {

    public static void main(final String[] args) {
        final Demo d = new Demo();
        final String name = "aaabbcccdddaaaa";
        System.out.println(d.countNoOfInteger(name));
    }

    public String countNoOfInteger(final String str) {
        if (str.equals(null)) {
            throw new IllegalArgumentException();
        }
        if (str.isEmpty()) {
            return "";
        }

        final Map<Character, Integer> map = new HashMap<>();
        int count = 0;
        final char[] charArray = str.trim().toCharArray();

        for (final char element : charArray) {
            if (map.get(element) != null) {
                count = map.get(element);
                map.put(element, ++count);
            } else {
                count = 0;
                map.put(element, ++count);
            }
        }

        int total;
        char ch;
        final Map<Character, Boolean> visited = new HashMap<>();
        final StringBuilder sb = new StringBuilder();
        for (final char element : charArray) {
            if ((visited.get(element) == null)) {
                ch = element;
                sb.append(ch);
                total = map.get(element);
                sb.append(total);
                visited.put(element, true);
            }
        }
        return sb.toString();
    }
}


texts:
I was recently tasked to write an implementation of the Berlekamp–Massey algorithm (for GF2) from a given inductional proof and decided to fresh up on my Haskell, since converting a proof by induction into a recursive algorithm should be quite straight-forward.

The variable names have been taken from the given proof (and thus can't be changed, although they differ from other notations or are rather short); here's a map:

ks: the input bit stream
len: the length of ks
n: degree of the current annihilating polynomial
phi: said polynomial, where a "bit" set at position \$i\$ indicates that the the \$i\$-th power is "part" of the polynomial, ie.:
$$
      \varphi(X) = \sum_{i=0}^n \text{phi}[i] \cdot X^i
  $$
s, psi: analogously the degree and the polynomial itself of the last iteration that had different values
r: the maximum length of the prefix of ks that psi annihilates successfully
dl: the discrepancy between the annihilation by phi and the \$l\$-prefix of ks
eta: The new polynomial, calculated as:
$$
      \eta(X) = \varphi(X) + X^{l-r} \cdot \psi(X)
  $$

data State = State { n :: Int
                   , phi :: [Int]
                   , s :: Int
                   , psi :: [Int]
                   , r :: Int
                   }
    deriving Show

discr :: Int -> [Int] -> Int -> [Int] -> Int
discr l ks n phi = foldr (\ a k -> (a+k) `mod` 2) 0
    (zipWith (*) (take (n+1) phi) (reverse $ take (n+1) $ drop (l-n) ks))

buildEta :: [Int] -> [Int] -> Int -> Int -> Int -> [Int]
buildEta phi psi l r s
    = (take (l-r) phi) ++
      (zipWith (\ c b -> (c+b) `mod` 2) (take (s+1) $ drop (l-r) phi) (take (s+1) psi)) ++
      (drop (l-r+s+1) phi)

bk' :: Int -> [Int] -> State
bk' (-1) ks = State 0 (1:lenzeroes) 0 (1:lenzeroes) (-1)
    where lenzeroes = replicate (length ks) 0
bk' l ks
    | dl == 0   = State n phi s psi r
    | n*2 <= l  = State (l+1-n) eta n phi l
    | otherwise = State n eta s psi r
    where State n phi s psi r = bk' (l-1) (ks)
          dl = discr l ks n phi
          eta = buildEta phi psi l r s

bk :: [Int] -> (Int,[Int])
bk ks = (n,phi)
    where State n phi _ _ _ = bk' (length ks) ks

I'm not quite happy with the result though, especially the buildEta function and the use of length.  I think the latter could be improved by reversing ks and then giving only the tail to the recursive call, but somehow I still need to build the phi and psi lists correctly, which I fail to do "nicely".

Style aside, the code works (as far as I know), eg.:

*Main> bk [1, 0, 1, 0, 0, 1, 1, 0, 1]
(5,[1,0,1,0,1,1,0,0,0])

Which means that the degree of the polynomial is \$n\$ and it has the following form:
$$
\varphi = X^0 + X^2 + X^4 + X^5
$$
Or, as an LSFR, A=[1,1,0,1,0] which indeed generates ks with [1, 0, 1, 0, 0] as initialization sequence.

Edit: Had someone review my code offline and did some minor style fixes already:

some point-free style where appropriate
replacing some lambda with just (*)
replacing sum ()mod2 with foldr and lambda
found a way to rewrite the if-then-else into nice guards
replaced the list-comprehension for zeroes with replicate
line breaks :-)


texts: QPlainTextEdit subclass function to indent lines in selection

texts:
I am, primarily for learning purposes, working on creating an editor component in C++ with Qt. As a first step, to begin getting familiar with editing a document via QTextCursor, I wrote this function on my subclass of QPlainTextEdit to indent multiple selected lines:

void MyEditor::increaseSelectionIndent()
{
    QTextCursor curs = textCursor();

    // Do nothing if we don't have a selection.

    if(!curs.hasSelection())
        return;

    // Get the first and count of lines to indent.

    int spos = curs.anchor(), epos = curs.position();

    if(spos > epos)
    {
        int hold = spos;
        spos = epos;
        epos = hold;
    }

    curs.setPosition(spos, QTextCursor::MoveAnchor);
    int sblock = curs.block().blockNumber();

    curs.setPosition(epos, QTextCursor::MoveAnchor);
    int eblock = curs.block().blockNumber();

    // Do the indent.

    curs.setPosition(spos, QTextCursor::MoveAnchor);

    curs.beginEditBlock();

    for(int i = 0; i <= (eblock - sblock); ++i)
    {
        curs.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);

        curs.insertText("\t");

        curs.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor);
    }

    curs.endEditBlock();

    // Set our cursor's selection to span all of the involved lines.

    curs.setPosition(spos, QTextCursor::MoveAnchor);
    curs.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);

    while(curs.block().blockNumber() < eblock)
    {
        curs.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor);
    }

    curs.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);

    // Done!

    setTextCursor(curs);
}

I'm interested in any feedback on whether or not I'm following "best practices" with QTextCursor - am I doing anything weird, or that can be simplified or improved?


texts:
I wrote this code, called arrayHistogram, that would generate a random number within a set range, and print it in an array randomIntArray. It would then make another array arrayHist that would count how many times each number in randomIntArray occurred. The program works, but, I feel I have a few semantic errors in the syntax, that's not printing arrayHist correctly. I would like to review it and see where the errors are so I can correct them. Also, If you feel like you can offer me a more efficient methods, and means for this code, feel free to do so, I'll take it into consideration.

{
    public static void main(String[] args){
                int[] array=randomIntArray(30);//declares the dimensions of the array     "randomIntArray"
                System.out.println("Scores:");
                printArray(array);//calls the scoreHist method to print the "array variable
                System.out.println("\n"+"count: ");
                printArray(arrayHist(array));//calls score hist, to call arrayHist, to count "array"
                System.out.println();
    }

        public static int randomInt(int low, int high){//the prng
                double e;
                double x=Math.random();
                    e=low+x*(high-low);
                return (int)e;}

        public static int[] randomIntArray(int n){//generates an array of random numbers based on an upper and lower bound
                int[] a=new int[n];
                for(int i=0;i<a.length;i++)
                    {a[i]=randomInt(-5,15);}//"-5&15 are the lower and upper bounds of the random number array
                return a;}

        public static int inRange(int[] a, int low, int high){//checks if the numbers of the random number array are in certain constraints.
                int count=0;
                for(int i=0;i<a.length;i++)
                    {if(a[i]>=low&&a[i]<=high)count++;}
                return count;}

        public static int[] arrayHist(int[] scores){//counts how many of each number occurs in "randomIntArray"
                int[] counts=new int[11];
                for(int i=0;i<10;i++)
                    {counts[i]=inRange(scores,i,i++);}
                return counts;}

        public static void printArray(int[] a){//prints any array, with only one traversal.
                for(int i=0;i<a.length;i++)
                    {System.out.print(" "+a[i]);}
            }
}

My goal is to not use any of the array methods Java provides (to challenge myself), so please don't offer them up.


texts:
In rust fp-core crate there is a compose function, but it is very limited for my liking.
So I made a macro which uses the function composition syntax of Haskell.
I would like to know why fp-core didn't do something like this in the first place?

What advice would you give me since this is the first macro I ever wrote in rust.

Here is my code:

#[macro_export]
macro_rules! compose {

    // end
    (@inner . $g:ident $e:expr) =>
    {
        $g($e)
    };

    (@inner . ( $g:ident $($param:expr),+ )  $e:expr) =>
    {
        $g ( $( $param ),+ , $e )
    };

    // middle
    (@inner . ( $f:ident $($param:expr),+ )  $( $gs:tt )* ) =>
    {
        $f( $( $param ),+ , compose!{ @inner $( $gs )* } )
    };

    (@inner . $f:ident $( $gs:tt )* ) =>
    {
        $f( compose!{ @inner $( $gs )* } )
    };

    //start
    ( $f:ident $( $tokens:tt )* ) =>
    {
        $f(compose!{ @inner $( $tokens )* } )
    };

    ( ( $f:ident  $( $param:expr ),+ ) $( $tokens:tt )* ) =>
    {
         $f( $( $param ),+ , compose!{ @inner $( $tokens )* } )
    };

}

#[cfg(test)]
mod compose_tests {

    fn add_3(x:u32) -> u32 {
        x + 3
    }

    fn double(x:u32) -> u32 {
        x * 2
    }

    fn my_add(x :u32, y :u32) -> u32
    {
        x + y
    }

    #[test]
    fn simple_test() {
        assert_eq!(compose!{double . add_3 2}, 10);
    }

    #[test]
    fn double_a_lot() {
        assert_eq!(compose!{double . double . double . double . double . double . double 1}, 128);
    }

    #[test]
    fn simple_partial_app() {
        let mut x = compose!{double . (my_add 2) 1};
        assert_eq!(x, 6);
        x = compose!{(my_add 2) . double 1};
        assert_eq!(x, 4);
        x = compose!{double . (my_add 2) . double 1};
        assert_eq!(x, 8);
        x = compose!{(my_add 2) . double . double 1};
        assert_eq!(x, 6);
        x = compose!{double . double . (my_add 1) 1};
        assert_eq!(x, 8);
        x = compose!{(my_add 2) . (my_add 2) . double 1};
        assert_eq!(x, 6);
        x = compose!{(my_add 2) . (my_add 2) . (my_add 1) 1};
        assert_eq!(x, 6);
    }
}


texts: Least Recently Used Cache Daily Coding Practice

texts:
I have the following challenge problem for which I was able to get a solution working, but not in \$O(1)\$ time as the problem asks for.  Could someone point me in the right direction to optimize this? I am also open to other criticisms of my coding style.

QUESTION:

  Implement an LRU (Least Recently Used) cache. It should be able to be initialized with a cache size n, and contain the following methods:

  set(key, value): sets key to value. If there are already n items in the cache and we are adding a new item, then it should also remove the least recently used item.
  get(key): gets the value at key. If no such key exists, return null.

  Each operation should run in \$O(1)\$ time.

CODE:

class LRUcache():

    def __init__(self,n):
        self.vals = dict()
        self.max_size = n

    def set(self,key,value):
        if key in self.vals:
            del self.vals[key]
            self.vals[key] = value
        else:
            if(len(self.vals) < self.max_size):
                self.vals[key] = value
            else:
                del self.vals[list(self.vals)[0]]
                self.vals[key] = value

    def get(self,key):
        if key in self.vals:
            tempval = self.vals[key]
            del self.vals[key]
            self.vals[key] = tempval
            return self.vals[key]
        return None


texts: Rendering plain text with paragraphs and line breaks as HTML

texts:
I have text inside a variable that I need to separate in paragraphs, and at the same time respect the manual breaklines.

This is my code:

    {description.split('\n\n').map(paragraph => (

            {paragraph.split('\n').map(
                (line, index) =>
                    index > 0 ? (

                            {line}

                    ) : (
                        line
                    )
            )}

    ))}

I am not specially happy with the code. It is not very readable. Any ideas how to improve it?


texts: Setting every element in an array to a given value

texts:
Given the length of an array and a char, I would like to replace every element in a char array with that given char.

Using a for loop, I'm changing each element to that char. Is there a better way to do it, or a specific method for that?

using System;
using System.Collections.Generic;

namespace TestProject
{
    class Solution
    {
        static void TestMethod()
        {
            //lines of code
            int lengthOfArray = int.Parse(Console.ReadKey());
            char charReplace = Console.ReadKey().KeyChar;

            char[] arrayChar = new char[lengthOfArray];
            for (int i = 0; i < lengthOfArray; i++)
            {
                arrayChar[i] = charReplace;
            }
        }
    }
}


texts: SSE Assembly vs GCC Compiler - Dot Product

texts:
I am currently taking an introductory course in computer architecture.
Our goal was to write a dot-product function in x86 Assembly which would use SSE and SIMD (without AVX).

I am not to that confident with my solution:

#include <time.h>
#define NUM 25600
//Example: scalarProduct using SIMD
extern float scalarProduct(float *, float *, int size);

float vsC(float * a, float * b, int size){
    float sum = 0;
    for(int i = 0; i < size; i++){
        sum += b[i]*a[i];
    }
    return sum;
}
int main(int argc, char ** argv){
    float * a = malloc(NUM * sizeof(double));
    float * b = malloc(NUM * sizeof(double));
    for(int i = 0; i < NUM; i++){
        a[i] = 1;
        b[i] = 1.0/(i+1);
    }
    clock_t start, end;
        double cpu_time_used;

         start = clock();
     float sum = scalarProduct(a,b,NUM);
         end = clock();
     cpu_time_used = ((double) (end - start))/CLOCKS_PER_SEC;
     printf("%.15f\n", cpu_time_used);
     printf("Solution %.15f\n", (double)(sum));
     start = clock();
     sum = vsC(a,b,NUM);
     end = clock();
     cpu_time_used = ((double) (end - start))/CLOCKS_PER_SEC;
     printf("%.15f\n", cpu_time_used);
     printf("Solution %.15f\n", (double)(sum));
}

Assembly File

.intel_syntax noprefix
.text
.global scalarProduct

scalarProduct:
        mov rax, rdx
        xorps xmm0, xmm0
        mov rcx, 0
start:
        cmp rax, 4
        jl end
        movdqu xmm3, [rsi + rcx]
        movdqu xmm2, [rdi + rcx]
        vmulps xmm1, xmm2, xmm3
        haddps  xmm7, xmm1
        haddps xmm7, xmm7
        psrldq xmm7, 4 //Shift to pos0
        addss xmm0, xmm7
        xorps xmm7, xmm7
        sub rax, 4
        add rcx, 16
        jmp start
end:
        cmp rax, 0
        je ret
        dec rax
        movss xmm1, [rsi + rcx]
        movss xmm2, [rdi + rcx]
        mulss xmm1, xmm2
        addss xmm0, xmm1
        add rcx, 4
        jmp end
ret:
        ret

Obviously, this Assembly - Code is far from perfect. How could I do better using basic SIMD and SSE?

The second thing which made me wonder is, I indeed outperformed GCC on a Xeon processor, which is irritating.

Compiling the code with:

gcc -o main -O7 main.c scalarProduct.S

Shows the following result:

./main
0.000015000000000
Solution 10.727574348449707
0.000026000000000
Solution 10.727569580078125

How would I have to improve my C Code so that GCC can step up?

DISCLAIMER:

My homework does not affect my grades and its editing is optional.


texts: HackerRank Code "Determining DNA Health"

texts:
I am working on this problem: https://www.hackerrank.com/challenges/determining-dna-health/problem passing some test cases and time-out on others (no wrong answers).

The code is here:

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        String[] genesItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        Map<Integer, String> genes = new HashMap<>();
        for (int i = 0; i < n; i++) {
            genes.put(i, genesItems[i]);
        }

        String[] healthItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        Map<Integer, String> health = new HashMap<>();
        for (int i = 0; i < n; i++) {
            health.put(i, healthItems[i]);
        }

        int s = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        long min = Long.MAX_VALUE;
        long max = Long.MIN_VALUE;

        for (int sItr = 0; sItr < s; sItr++) {
            String[] firstLastd = scanner.nextLine().split(" ");

            int first = Integer.parseInt(firstLastd[0]);
            int last = Integer.parseInt(firstLastd[1]);
            String d = firstLastd[2];

            long sum = 0;
            for (int i = first; i <= last; i++) {
                for (int index = d.indexOf(genes.get(i)); index >= 0; index = d.indexOf(genes.get(i), index + 1)) {
                    sum += Integer.parseInt(health.get(i));
                }
            }
            if (sum < min) {
                min = sum;
            }
            if (sum > max) {
                max = sum;
            }
        }

        System.out.println(min + " " + max);
        scanner.close();
    }
}


texts: Adding arbitrarily long integers C++ (string represented)

texts:
I'm working through some Project Euler problems using C++ and some of the numbers in question are starting to get quite large (21000 for Problem 16) and I need to add some of these large numbers together, so I quickly threw together a string represented (positive) integer adder:

#include <vector>
#include <string>

std::string AddStringNumbers(std::string n1, std::string n2) {
    while (n1.length() < n2.length()) {
        n1 = "0" + n1;
    }
    while (n2.length() < n1.length()) {
        n2 = "0" + n2;
    }

    std::vector<int> sums = std::vector<int>(n1.length(), 0);
    for (int i = 0; i < n1.length(); i++) {
        sums[i] = (n1[i] - '0') + (n2[i] - '0');
    }

    for (int i = sums.size() - 1; i > 0; i--) {
        while (sums[i] > 9) {
            sums[i] -= 10;
            sums[i - 1] += 1;
        }
    }
    if (sums[0] > 9) {
        sums.insert(sums.begin(), 0);
        while (sums[1] > 9) {
            sums[1] -= 10;
            sums[0] += 1;
        }
    }

    std::string o = "";
    for (int i = 0; i < sums.size(); i++) {
        o += (char)('0' + sums[i]);
    }
    return o;
}

Once this was implemented, the solution was simple:

int Problem016(int n) {
    std::string num = "1";
    for (int64_t i = 0; i < n; i++) {
        num = AddStringNumbers(num, num);
    }

    int sum = 0;
    for (int i = 0; i < num.length(); i++) {
        sum += num[i] - '0';
    }
    return sum;
}

Called with:

Problem016(1000);

Is there anything that I can do to improve my AddStringNumbers function? I'm especially interested in the use of storage types other than std::string and what the advantages of doing so would be. It should also be noted that I do have an intention of doing something like this in a class however, as this was quickly thrown together for the solution that's parked for the time being.

I'm less interested in my method of solving Problem 16, however any comments on that would also be appreciated.


texts: Graph (adjacency list) and DFS (topological sort)

texts:
The vertices on the graph are numbers from 0 to |V| - 1 for convenience. I was thinking later to use a template wrapper for the graph.

Graph.h:

#pragma once
#include <unordered_set>
#include <vector>

class Graph
{
public:
    using size_type = std::size_t;
    using adj_list = std::unordered_set<size_type>;
private:
    std::vector<adj_list> list;
    size_type edges;
    void check_range(size_type) const;
public:
    using size_type = std::size_t;
    Graph(size_type v);
    ~Graph();

    void add_vertex();
    void add_edge(size_type, size_type);

    const adj_list& adj(size_type) const;
    Graph reverse() const;

    size_type E() const;
    size_type V() const;
};

Graph.cpp:

#include "Graph.h"

Graph::Graph(size_type v)
    : list(std::vector<adj_list>(v, std::unordered_set<size_type>())) {
}

Graph::~Graph() {
}

void Graph::add_vertex() {
    list.push_back(std::unordered_set<size_type>());
}

void Graph::add_edge(size_type v, size_type w) {
    check_range(v);
    check_range(w);

    list[v].insert(w);
    ++edges;
}

const typename Graph::adj_list & Graph::adj(size_type v) const {
    check_range(v);
    return list[v];
}

Graph Graph::reverse() const {
    Graph g(list.size());
    for (size_type v = 0, size = list.size(); v < size; ++v) {
        for (auto w : list[v]) {
            g.add_edge(w, v);
        }
    }
    return g;
}

void Graph::check_range(size_type v) const {
    if (v >= list.size()) {
        throw std::out_of_range("vertex out of range");
    }
}

typename Graph::size_type Graph::E() const {
    return edges;
}

typename Graph::size_type Graph::V() const {
    return list.size();
}

DFS.h:

#pragma once
#include "Graph.h"
#include <deque>
#include <stack>

class DFS
{
    enum vertex_state { on_stack, undiscovered, done };

    std::vector<vertex_state> vertices;
    std::deque<Graph::size_type> topo_sort;

public:
    using iterator = std::deque<Graph::size_type>::iterator;
    using reverse_iterator = std::deque<Graph::size_type>::reverse_iterator;

    DFS(const Graph&);

    bool DFS_visit(const Graph& graph, Graph::size_type, std::stack<std::pair<Graph::size_type, bool>> &);

    bool DAG();

    iterator begin() { return topo_sort.begin(); }
    iterator end() { return topo_sort.end(); }

    reverse_iterator rbegin() { return topo_sort.rbegin(); }
    reverse_iterator rend() { return topo_sort.rend(); }

};

DFS.cpp:

#include "DFS.h"

DFS::DFS(const Graph& G)
    : vertices(std::vector<vertex_state>(G.V(), undiscovered)),
      topo_sort(std::deque<Graph::size_type>()) {

    std::stack<std::pair<Graph::size_type, bool>> stack;
    for (auto v = 0; v < G.V(); ++v) {
        if (vertices[v] == undiscovered
               && !DFS_visit(G, v, stack)) {
            break;
        }
    }
    //while(v < G.V() && (marked(x) || DFS_visit(G, v++)))
}

bool DFS::DFS_visit(const Graph& graph, Graph::size_type v,
                                 std::stack<std::pair<Graph::size_type, bool>> &stack) {

    stack.push(std::make_pair(v, false));
    while (!stack.empty()) {
        auto &current = stack.top();
        auto v        = current.first;

        if (current.second) {
            topo_sort.push_front(v);
            vertices[v] = done;
        }
        else switch (vertices[v]) {

        case undiscovered:
            current.second = true;
            vertices[v]    = on_stack;
            for (auto w : graph.adj(v)) {
                stack.push(std::make_pair(w, false));
            }
            continue;

        case on_stack:
            topo_sort.clear();
            return false;
        }
        stack.pop();
    }
    return true;
}

bool DFS::DAG() {
    return !topo_sort.empty();
}


texts: Wrapping a function in other function to generate Json Patches

texts:
I have a view that is dynamically generated from a JSON file on Angular, and I am using JSON-Patch (RFC6902) to generate patches when the user modifies its values.

I start observing the JSON since the very beginning of the application and stop when the user want to submit the changes. My problem is that on the meantime there will be some internal operations with the object I don't want to capture.

So whenever this situation occurred, I created another observer on a part of the object to capture what I do not want to send and ignore it, so far so good. But this situations become more common than what I thought, so I tried to generalize it. I've used a bit of this link to base myself.

I designed this function on the service responsible for observing the JSON and generating patches, it basically saves the operations I don't want in a blacklist to remove them after.

this.ignoreThisOperations = function (objToObserve, func) {
    var observer = jsonpatch.observe(objToObserve);

    func.apply(this, arguments);

    var trashPatch = jsonpatch.generate(observer);

    if (!_.isEmpty(trashPatch)) {
        this.addToBlackList(trashPatch);
    }
};

And whenever I need to ignore an operation I use it like:

patchGenerationService.ignoreThisOperations(obj, function () {
     obj.entries = []
});

It works perfectly and helped me on organizing the code. But I don't know how good this is, or if there a better/simpler way.

Also, I didn't use anything from angular to implement this, is there anything that could help me? I searched a bit but maybe I did not dig enough to find anything.


texts: Double LinkedList Deep Copy in Kotlin with Generics and Thread Safety

texts:
Goal

Return a deep copy of a double LinkedList.
Each node also contains an additional random pointer, potentially to any node or null.

Code to start
data class Node<T>(
    var data: T?,
    var previous: Node<T>? = null,
    var next: Node<T>? = null,
    var random: Node<T>? = null

class LinkedList {
    // TODO: Implement deep copy here.
}

Questions

Generics - Is there a better approach to handle the generic variance as to not need as T when passing in a generic type? i.e. linkedList.add(data = 1 as T)
Add thread-safety for operations - Are there any specific recommendations on thread-safety for this solution or broader topics to research to understand thread-safety considerations further?

Implement
See the full code on GitHub.
LinkedList.kt
class Node<T>(
        var prev: Node<T>? = null,
        var next: Node<T>? = null,
        var rand: Node<T>? = null,
        var data: T
)

class LinkedList<T>(
        var first: Node<T>? = null,
        var last: Node<T>? = null,
        val randMap: HashMap<Node<T>?, Node<T>?> = hashMapOf()
) {
    // Add Node to the end of LinkedList
    fun add(data: T): Node<T> {
        val temp = last
        val newNode = Node(prev = temp, data = data)
        last = newNode
        if (temp == null)
            first = newNode
        else
            temp.next = newNode
        return newNode
    }

    fun deepCopyWithoutRandoms(prev: Node<T>?, node: Node<T>?): Node<T>? {
        return if (node == null)
            null
        else {
            val newNode = Node(data = node.data)
            if (node.rand != null) {
                newNode.rand = node.rand
                randMap.put(node.rand, null)
            }
            newNode.prev = prev
            newNode.next = deepCopyWithoutRandoms(newNode, node.next)
            if (randMap.containsKey(node))
                randMap.put(node, newNode)
            return newNode
        }
    }

    fun updateRandoms(node: Node<T>?): Node<T>? {
        if (node != null) {
            if (node.rand != null)
                node.rand = randMap.get(node.rand!!)
            updateRandoms(node.next)
            return node
        } else return null
    }

    fun clear() {
        var node = first
        while (node != null) {
            node.prev = null
            node.next = null
            node.rand = null
            node.data = 0 as T
            node = node.next
        }
    }

    fun toString(first: Node<T>?): String {
        var output = ""
        var node = first
        while (node != null) {
            output += String.format("(prev:%s next:%s data:%s random:%s)\n", node.prev, node.next, node.data, node.rand)
            node = node.next
        }
        return output
    }
}