texts: Design of Experiments data structure with C++17

texts:
I've defined a data structure which represents a doe_model, providing two maps with a configuration_id as key and a configuration_model as value. The configuration_model is an unordered_map which has a knob_name as key and a knob_value as value. There are things I don't like very much about this but I can't get a grasp on how I should change them. For instance: using the next and get_next() trick I'm forced to add a copy constructor and an assignment operator in order to get rid of the undefined behavior I would get by shallow copying the next iterator member. But I don't know if there's a better way to achieve what I need, which is: since I have a thread pool which concurrently access the doe data structure, I have to provide them the next configuration to explore in a smart way. So if I'm reaching the end of the configurations (and there are still some to use) I have to return them from the begin, until I've exhausted all of them.
Here's the code:
using configuration_model = std::unordered_map<std::string, std::string>;

struct doe_model {

  doe_model() {}
  doe_model(const doe_model& doe)
  {
    required_explorations = doe.required_explorations;
    number_of_explorations = doe.number_of_explorations;
    next = required_explorations.end();
  }

  inline doe_model& operator=(const doe_model& ldoe)
  {
    required_explorations = ldoe.required_explorations;
    number_of_explorations = ldoe.number_of_explorations;
    next = required_explorations.end();
    return *this;
  }

  inline bool add_config(const std::string &config_id,
                         const configuration_model &config,
                         const int required_number_of_observations) {
    bool assignment_took_place =
        !required_explorations.insert_or_assign(config_id, config).second ||
        !number_of_explorations
             .insert_or_assign(config_id, required_number_of_observations)
             .second;
    next = required_explorations.end();
    return assignment_took_place;
  }

  inline void update_config(const std::string &config_id) {
    number_of_explorations.at(config_id)--;

    // remove the configuration in case we exausted all the explorations
    if (number_of_explorations.at(config_id) <= 0)
      remove_config(config_id);
  }

  inline void remove_config(const std::string &config_id) {
    required_explorations.erase(config_id);
    number_of_explorations.erase(config_id);
  }

  // this method returns the next configuration to explore
  // NOTE: the caller MUST check the pointer first.
  inline std::map<std::string, configuration_model>::iterator get_next() {
    // we may have an empty map or one with only a single configuration left
    if (required_explorations.empty() || next == required_explorations.end()) {
      next = required_explorations.begin();
      return next;
    }

    next++;

    return next;
  }

  // key is the configuration_id
  std::map<std::string, configuration_model> required_explorations;
  std::map<std::string, configuration_model>::iterator next;
  std::map<std::string, int> number_of_explorations;
};


texts:
One of the exercises I like to program when learning a new language is a chat client for the console. I've programmed it in many languages (Perl, Python, C, C++, JavaScript, ...). One of the versions I like most for its terseness is Ruby:

#!/usr/bin/ruby
require 'socket'

s = TCPSocket.new(ARGV[0], ARGV[1].to_i)
nick = ARGV[2]

# send nick to server
s.puts(nick)

# input thread
kbd = Thread.new {
    STDIN.each_line { |line|
        s.puts("\033[31m" + nick + "> " + "\033[0m" + line)
    }
    s.close_write
}

# output thread
con = Thread.new {
    s.each_line { |line|
        STDOUT.puts(line)
    }
}

kbd.join
con.join

The initial Rust equivalent would be something similar to:

use std::os;
use std::io;
use std::io::{TcpStream, BufferedReader};

fn main() {
    let args = os::args();
    let mut s = TcpStream::connect(args[1], from_str(args[2]));

    // send nick to server
    nick = args[3];
    s.write_line(nick);

    // input thread
    spawn(proc() {
        for line in io::stdin().lines() {
            s.write_str(format!("\x1b[31m{}> \x1b[0m{}", nick, line));
        }
        s.close_write();
    });

    // output thread
    spawn(proc() {
        for line in BufferedReader::new(s).lines() {
            io::stdout().write_str(line);
        }
    });
}

which obviously has some compile errors. The corrected version is:

use std::os;
use std::io;
use std::io::{TcpStream, BufferedReader};

fn main() {
    let args = os::args();
    let mut s = TcpStream::connect(args[1].as_slice(),from_str(args[2].as_slice()).unwrap()).unwrap();

    // send nick to server
    s.write_line(args[3].as_slice()).unwrap();
    let nick = args[3].clone();
    let mut sin = s.clone();

    // input
    spawn(proc() {
        for line in io::stdin().lines() {
            sin.write_str(format!("\x1b[31m{}> \x1b[0m{}", nick, line.unwrap().as_slice()).as_slice()).unwrap();
        }
        sin.close_write().unwrap();
    });

    // output
    spawn(proc() {
        for line in BufferedReader::new(s).lines() {
            io::stdout().write_str(line.unwrap().as_slice()).unwrap();
        }
    });
}

That's too verbose, isn't it?  Perhaps it's due to the fact that the compiler is still beta (0.12-nightly)?  Can this terseness be simplified?


texts: Counting duplicate tags in a string of many tags

texts:
I have a photo list page where each photo has multiple tags (as spaced words). I'm trying to display most of the tags on the page after:

Removing duplicate tags
Sorting tags by having most occurring tags first

The code looks like this:

$tags1 = "red blue green yellow colors";
$tags2 = "blue green grass tree garden";
$tags3 = "pink blue colors paint sky"

addTags($tags1);
addTags($tags2);
addTags($tags3);
echo (processTags());

private $tagsArray;
public function addTags($param) {
    if($param == ""){ // no tags
        return;
    }
    $explode = explode(" ",$param);
    $this->tagsArray = array_merge($this->tagsArray, $explode);
}

private function processTags(){
    $processedTags = array_count_values($this->tagsArray);
    arsort($processedTags);
    $count = 0;
    foreach($processedTags as $tag => $value) {
        if(++$count>50) break; // don't print more than 50 tags
        $output .= "$tag";
    }
    return $output;
}

Each photo can have dozens of tags and there can be hundreds of tags total. Is there any way to improve the code to make it more efficient? Could it be done with less code? The above code works just fine, but I'm just curious to know if there is a better way to go about it.


texts: Calculate the sum at a level of a binary tree represented in a String

texts:
Fair preface: This is an interview question I would like to improve my knowledge of. I got some rest, and re-solved the problem with a fresh/unpanicked mind.

Given input of the type (10(5(3)(12))(14(11)(17)))
which would represent the following tree

 n=0            10
 n=1       5         14
 n=2    3    12    11   17

My task is to find the summation of values at a particular tier, like \$5+14=19\$ which is the sum for \$n=1\$, or \$3+12+11+17=43\$ the sum for \$n=2\$.

Considering this is a binary tree, a recursive function seems appropriate.

My main utility functions are:

stripFirstLastParen – strips the first and last paren
getCurrentVal – retrieves the value of the current node
getChildren – retrieves the left and right nodes

var input =
"(10(5(3)(12))(14(11)(17)))";

function stripFirstLastParen(input){
  if(input[0] !== "(" || input[input.length - 1] !== ")"){
    console.error("unbalanced parens")
  }
  else{
    input = input.substr(1);
    input = input.substring(0, input.length - 1);
  }
  return input;
}

function getCurrentVal(input){
  var val = "";
  while(input[0] !== "(" && input[0] !== ")" && input.length){
    val += input[0];
    input = input.substr(1);
  }
  return {
    val,
    input
  }
}

function getChildren(input){
  var val = "";
  if(input.length == 0){
    return {
      left: "",
      right: ""
    }
  }
  if(input[0] !== "("){
    console.error("no open paren at start");
  }
  val += input[0];
  input = input.substr(1);
  var parenStack = 1;
  while(parenStack > 0){
    if(input[0] == ")"){
      parenStack--;
    }
    else if(input[0] == "("){
      parenStack++;
    }
    val += input[0];
    input = input.substr(1);
  }
  return {
    left: val,
    right: input
  }
}

function getValueForLevel(input, k){
  var totalValue = 0;
  input = stripFirstLastParen(input);
  var currentValue = getCurrentVal(input);
  var children = getChildren(currentValue.input);
  if(k > 0){
    if(children.left.length){
      totalValue += getValueForLevel(children.left, k-1);
    }
    if(children.right.length){
      totalValue += getValueForLevel(children.right, k-1);
    }
  }
  else if(k == 0){
    totalValue += JSON.parse(currentValue.val);
  }
  return totalValue;
}

var test = getValueForLevel(input, 2);
console.log(test);

My main concerns are:

String manipulation. How should I properly be passing the altered string throughout the recursive function? Callout for lines like

  var currentValue = getCurrentVal(input);
  var children = getChildren(currentValue.input);

Where the getChildren function relies on getCurrentVal removing the value from the string itself, that feels dirty.

Complexity. I'm having difficulty describing the complexity of my procedure, and would argue that it's somewhere between \$O(n)\$ and \$O(n^2)\$, so is it \$O(n^2)\$? Considering the parens and values are removed as they are parsed, that lends itself to \$O(n)\$, but I feel it's \$O(n^2)\$ because of the duplicate parsing in order to create the child nodes. Is that correct? Can it be improved?

I tried to keep the "spirit of the challenge" and re-completed this within the amount of time previously allotted (somewhere around 30-45 minutes). Suggestions and improvements need not consider this time restriction, but providing context is important.


texts:
K&R 1.8 exercise:

  Write a program to count blanks,tabs, and newlines.

Is this a viable solution to the problem and is it properly formatted? I have never programmed in C before, so I just wanted to see if this is proper c programming as it were.

#include <stdio.h>

/* count blanks,tabs and new lines*/

int main(void)
{
    /* initializes blank,tab,newline and c
    sets them all to 0*/
    int blank,tab,newline;
    int c;
    blank = 0;
    tab = 0;
    newline = 0;

    while((c = getchar()) != EOF)
        if (c =='\n')
            ++newline;
        if (c == ' ')
            ++blank;
        if (c == '\t')
            ++tab;
        printf("Blanks: %d\nTabs: %d\nLines: %d\n", blank, tab, newline);
        return 0;
}


texts:
This recursive calls reverseList on each node of the linked list. When returned from the function call, it changes the next link to the previous node.

public static Node reverseList(Node curNode , Node prevNode , Node reverseListHead)
{
    //empty list
    if(curNode == null)
    {
        return null;
    }
    //node with single element
    if(curNode.next == null)
    {
        curNode.next = prevNode;
        reverseListHead = curNode;
        return reverseListHead;
    }
    reverseListHead = reverseList(curNode.next, curNode, reverseListHead);
    curNode.next = prevNode;
    return reverseListHead;
}


texts:
Courtesy of a few posts around here I've discovered HackerRank. Poisonous Plants is one of their challenges.

Of course, skip the following if you'd like to try it yourself.

Challenge:

  There are \$N\$ plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any plant has more pesticide than the plant at its left, it dies.

  Given the initial values of pesticide in each plant, print the number of days after which no plant dies, i.e. the time after which there are no plants with more pesticide content than the plant to their left.

Input Format:

  The input consists of an integer \$N\$. The next line consists of N integers describing the array P where P[i] denotes the amount of pesticide in plant i.

Constraints:

  \$1 \le N \le 100000\$
  \$0 \le P[i] \le 10^9\$

Output Format:

  Output a single value equal to the number of days after which no plants die.

Solution:

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int[] garden = new int[input.nextInt()];
        for (int i = 0; i < garden.length; i++) {
            garden[i] = input.nextInt();
        }

        int days = 0;
        while(killCommand(garden)) {
            days++;
        }

        System.out.println(days);
    }

    private static boolean killCommand(int[] garden) {
        boolean plantDied = false;
        int lastIndex = garden.length - 1;
        int last = garden[lastIndex];

        for (int i = lastIndex - 1; i >= 0; i--) {
            if (garden[i] == -1) {
                continue;
            }
            int current = garden[i];
            if (current < last) {
                plantDied = true;
                garden[lastIndex] = -1;
            }
            last = current;
            lastIndex = i;
        }

        return plantDied;
    }
}

Sample Input:

  7
  6 5 8 4 7 10 9

Sample Output:

  2

My algorithm works and passes 21 of 23 test cases, but doesn't meet their allotted time for two. How can it be further optimized?


texts:
I coded this program as a challenge for /r/dailyprogrammer. Basically this program can convert any number from any base to another base including negative bases as long as the input is coherent. Did I follow the Python 3 standard or commit any obvious mistakes? I am also wondering if I can efficiently filter out nonsensical input without making explicit cases for  each one?

For example, if you input

  -15-10

...that's nonsense because you can't have a negative number if you're in a negative base, if I understand correctly.

The program is run by giving it 3 inputs:

The number
The base the number you just inputted is in
The base you'd like your output to be in

import sys

def convertToBase10(n, base):
    number = []
    negative = False

    # If n is a negative number (it's a string at this moment of the code)..
    # then replace the minus sign with a blank character to correctly convert string to int...
    # so the algorithm can continue.
    if n[0] == '-':
        n = n.replace('-', '')
        negative = True

    for i in n:
        number.append(int(i))

    number = number[::-1]
    if negative:
        for i in range(len(number)):
            number[i] = number[i] * -1
            number[i] = number[i] * (base ** i)
    else:
        for i in range(len(number)):
            number[i] = number[i] * (base ** i)

    return sum(number)

def convertToAnyBase(n, base):
    a = 0
    i = 0

    # Special case: If n is less than zero and base is greater than zero...
    #               then we have to take the absolute value of n before dividing it...
    #               using the // operator. Reason is because taking e.g. math.floor(-2.5)...
    #               returns -3.0 which is one off the actual value (we actually want -2 in this example).
    #               After we get the correct n, we can now negate it.
    if n < 0 and base > 0:
        while n < 0:
            remainder = n % base
            n = abs(n)
            n //= base
            n = -n

            # If the base is negative, remainder will be a negative number.
            # Add the absolute value of the base to the remainder and add one to n.
            # https://en.wikipedia.org/wiki/Negative_base#Calculation
            if remainder < 0:
                remainder += abs(base)
                n += 1

            a += remainder * (10 ** i)
            i += 1

        return -a

    while n != 0:
        remainder = n % base
        n //= base

        # If the base is negative, remainder will be a negative number.
        # Add the absolute value of the base to the remainder and add one to n.
        # https://en.wikipedia.org/wiki/Negative_base#Calculation
        if remainder < 0:
            remainder += abs(base)
            n += 1

        a += remainder * (10 ** i)
        i += 1
    return a

def main():
    x = sys.argv[1]
    baseIn = int(sys.argv[2])
    baseOut = int(sys.argv[3])

    if baseIn == 0 or baseOut == 0:
        print("Cannot have bases of 0. Exiting...")
        raise SystemExit

    print("You entered " + x + " in base " + str(baseIn) + ".")

    n = convertToBase10(x, baseIn)

    if baseOut == 1:
        ones = str(1) * n
        print("Your number in base " + str(baseOut) + " is " + str(ones) + ".")
    elif baseOut == -1:
        ones = str(1) * n
        print("Your number in base " + str(baseOut) + " is " + str('-' + ones) + ".")
    else:
        # If both bases are ten then we have already calculated its value.
        if abs(baseIn) == 10 and abs(baseOut) == 10:
            print("Your number in base " + str(baseOut) + " is " + str(n) + ".")
        else:
            print("Your number in base " + str(baseOut) + " is " + str(convertToAnyBase(n, baseOut)) + ".")

if __name__ == "__main__":
    main()


texts: API design for loading OpenGL textures asynchronously

texts:
What do you think about this API for loading OpenGL textures asynchronously?

My main concern is that the loader class executes code on the client io_service. This takes away some control from the user but should be convenient in most scenarios.

I'm also thinking about using a texture on the stack and a shared_ptr that can be disregarded when the texture is fully loaded. Not sure if this is necessary.

Criticism and suggestions of any sort are very welcome.

class loader {
public:
  using open_handler = function<void(error_code ec, shared_ptr<istream> is, image image)>;
  using read_handler = function<void(error_code ec)>;

  loader(io_service& client_service) : client_service_(client_service) {
    // Start a thread that creates a second OpenGL context and executes service_.run().
  }

  void open(filesystem::path path, open_handler handler) {
    service_.post([this, path(move(path)), handler(move(handler))]() mutable {
      shared_ptr<istream> is = make_shared<ifstream>(/* Open the image. */);
      image image({ 100, 100, GL_RGB, GL_UNSIGNED_BYTE }); /* Read the size/format information. */;
      on_open(error_code(), std::move(handler), std::move(is), std::move(image));
    });
  }

  void on_open(error_code ec, open_handler handler, shared_ptr<istream> is, image image) {
    client_service_.post([handler(move(handler)), is(move(is)), image(move(image))]() {
      handler(error_code(), move(is), move(image));
    });
  }

  void read(weak_ptr<texture> texture, GLenum format, GLenum type, shared_ptr<istream> is, read_handler handler) {
    service_.post([this, texture, format, type, is(move(is)), handler(move(handler))]() mutable {
      // Read the image, scaling and converting it. Update the texture with every new line of pixels.
      client_service_.post([handler(move(handler))]() {
        handler(error_code());
      });
    });
  }

private:
  io_service service_;
  io_service& client_service_;
};

class client {
public:
  client() : loader_(service_) {
  }

  void create() {
    // Create the main window OpenGL context.
    loader_.open("/path/to/file.png", [this](error_code ec, shared_ptr<istream> is, image image) {
      texture_ = make_shared<texture>(0 /* Create a new texture. */, image.cx / 2, image.cy / 2);
      // Create a VBO/VAO and assign the texture.
      loader_.read(texture_, GL_RGBA, GL_UNSIGNED_BYTE, move(is), [this](error_code ec) {
        throw runtime_error("...");  // will be thrown on service_.poll() call in draw().
      });
    });
  }

  void draw() {
    service_.poll();
    // Draw to the context and swap.
  }

private:
  io_service service_;
  loader loader_;
  shared_ptr<texture> texture_;
};

Here is a link to wandbox to play around with the code: http://melpon.org/wandbox/permlink/bEcpM340KgU6hY5V


texts: Comparing screen captures using unsafe / API calls

texts:
After a week of searching and testing each approach via Stopwatch,
I came to this method using the fastest way possible to capture screen into a bitmap  and then to a byte[].

Is it possible to make it any faster using parallel features or any idea I have not taken into account? (As I am a newbie, 4 months of self learning.)
I mixed two or three versions of the copying function (portion of screen to memory
then convert captured/crop into byte[]). I might have left unnecessary lines of code, I would like to refine it (if and where needed).

unsafe public static Bitmap NatUnsfBtmp(IntPtr hWnd, Size Ms)
{
    Stopwatch swCap2Byte = new Stopwatch();
    swCap2Byte.Start();
    WINDOWINFO winInfo = new WINDOWINFO();
    bool ret = GetWindowInfo(hWnd, ref winInfo);
    if (!ret)
    {
        return null;
    }

    int height = Ms.Height;
    int width = Ms.Width;
    if (height == 0 || width == 0) return null;

    Graphics frmGraphics = Graphics.FromHwnd(hWnd);
    IntPtr hDC = GetWindowDC(hWnd); //gets the entire window
    //IntPtr hDC = frmGraphics.GetHdc(); -- gets the client area, no menu bars, etc..

    System.Drawing.Bitmap tmpBitmap = new System.Drawing.Bitmap(width, height, frmGraphics);
    Bitmap bitmap = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap);
    Graphics bmGraphics = Graphics.FromImage(tmpBitmap);
    IntPtr bmHdc = bmGraphics.GetHdc();
    BitBlt(bmHdc, 0, 0, width, height, hDC, 0, 0, TernaryRasterOperations.SRCCOPY);

    swCap2Byte.Stop();
    string swCopiedFF = swCap2Byte.Elapsed.ToString().Remove(0, 5);
    swCap2Byte.Restart();
    #region <<=========== CopytoMem->ByteArr ============>>

    BitmapData bData = tmpBitmap.LockBits(new Rectangle(new Point(), Ms),
    ImageLockMode.ReadOnly,
    PixelFormat.Format24bppRgb);
    MyForm1.MyT.Cap.TestBigCapturedBtmp = tmpBitmap;
    // number of bytes in the bitmap
    int byteCount = bData.Stride * tmpBitmap.Height;
    byte[] bmpBytes = new byte[byteCount];

    // Copy the locked bytes from memory
    Marshal.Copy(bData.Scan0, bmpBytes, 0, byteCount);
    byte[] OrgArr = bmpBytes;//File.ReadAllBytes("testFcompScr.bmp");
    // don't forget to unlock the bitmap!!
    swCap2Byte.Stop();
    string SwFCFscr = swCap2Byte.Elapsed.ToString().Remove(0, 5);
    System.IO.File.WriteAllBytes(MyForm1.AHItemsInitialDir + "testBig4BenchViaChaos.bar", OrgArr);
    System.Windows.Forms.MessageBox.Show("   Copied @  " +swCopiedFF + Environment.NewLine+"Converted @ " + SwFCFscr);
    btmp.UnlockBits(bData);

    if(System.IO.File.ReadAllBytes(MyForm1.AHItemsInitialDir + "testBig4BenchViaChaos.bar")== OrgArr)
        System.Windows.Forms.MessageBox.Show("OK");
    else System.Windows.Forms.MessageBox.Show("Not same");

    if (BigOrsmall == "Big")
    {

        MyT.Cap.TestBigCapturedBtmp = btmp;
        MyT.CapSave.TestBigCaptSavedAsBar = OrgArr;
        File.WriteAllBytes(AHItemsInitialDir + "testBig4BenchViaChaos.bar", OrgArr);
    }
    else if (BigOrsmall == "Small")
    {
        MyT.Cap.TestSmallCapturedBtmp = btmp;
        File.WriteAllBytes(AHItemsInitialDir + "testSmall4BenchViaChaos.bar", OrgArr);
        MyT.CapSave.TestSmallCaptSavedAsBar = OrgArr;
    }
    TestedCap_DoPutInPicBox(PicBox_CopiedFromScreen);

    #endregion

    bmGraphics.ReleaseHdc(bmHdc);
    ReleaseDC(hWnd, hDC);

    return tmpBitmap;
}


texts: Fetch key from MySQL DB if doesn't exist in redis DB

texts:
This code gets data from a MySQL database, such that if a key doesn't exist in a Redis database, then fetching of data needs to be done from the MySQL database and then stored in Redis cache. As such, the next time the key exists, querying to the MySQL database will be avoided.

Please see whether this can optimized or let me know if something needs to be changed.

somefile.js

var express = require('express');
var Promise = require("bluebird");
var getSqlConnection = require('../common/database');
var redisModules = require("../common/redismodule");

function getSettings(request, response)
{
    if (redisModules.IsRedisConnectionOpened() == true)
    {
        return GetData();
    }
    else
    {
        response.status(500).send();
        return;
    }

    function GetData()
    {
        redisModules.GetRedisValue("key")
        .then(function (result)
        {
            if (!result)
                return new SetData();
            else
                return result;
        })
        .catch(function (e)
        {
            response.status(500).send();
        })
        .then(function (result)
        {
            response.status(200).send({ value : result });
        });
    }

    function SetData()
    {
        return Promise.using(getSqlConnection(), function(connection)
        {
            return connection.query('select url from blog')
            .then(function(results)
            {
                var data = "";
                // some code
                return data;
            })
            .then(function (result)
            {
                return new redisModules.SetRedisValue("key", result);
            });
        });
    }
}

database.js

File for handling database connections

var mysql = require('promise-mysql');

pool = mysql.createPool({
  host: '',
  user: '',
  password: '',
  database: '',
  connectionLimit: 4
});

function getSqlConnection() {
  return pool.getConnection().disposer(function(connection) {
    pool.releaseConnection(connection);
  });
}

module.exports = getSqlConnection;

redismodule.js

File for handling redis get, set concepts

var Promise = require('bluebird');
var constants = require('../common/contants');

var redisClient;        // Global (Avoids Duplicate Connections)

module.exports =
{
    OpenRedisConnection : function()
    {
        if (redisClient == null)
        {
            redisClient = require("redis").createClient(6379, 'localhost');
        }
    },
    IsRedisConnectionOpened : function()
    {
        if (redisClient && redisClient.connected == true)
        {
            return true;
        }
        else
        {
            if(redisClient)
                redisClient.end();  // End and open once more

            module.exports.OpenRedisConnection();
            return true;
        }
    },
    GetRedisValue: function (key)
    {
        return new Promise(function (resolve, reject)
        {
            redisClient.get(key, function (error, result)
            {
                if (error)
                {
                    reject(error);
                }
                else
                {
                    if (result == null)
                        resolve();    // Key not present so create
                    else
                        resolve(result);
                }
            });
        });
    },
    SetRedisValue: function (key, value)
    {
        return new Promise(function (resolve, reject)
        {
            redisClient.set(key, value, 'EX', 1000,
            function(err,reply)
            {
                if (reply == 'OK')
                    resolve(value);         // Send the value
                else
                    reject(err);
            });
        });
    }
};

The execution starts when getSettings function is called.

I have just included all the code so that if it's correct it might be useful for others.


texts:
I'm trying to read certain values from an object.  What would be the best practice to do so?

$jira_object = json_decode(trim($jira_value->data));
$this->_displayName = $jira_object->user->displayName;
$this->_issueID = $jira_object->issue->id;
$this->_issueKey = $jira_object->issue->key;
$this->_issueFieldSummary = $jira_object->issue->fields->summary;
$this->_issueFieldProgress = $jira_object->issue->fields->progress;
$this->_issueFieldType = $jira_object->issue->fields->issuetype;
$this->_issueFieldUpdated = $jira_object->issue->fields->updated;
$this->_issueFieldCreated = $jira_object->issue->fields->created;
$this->_issueFieldPriority = $jira_object->issue->fields->priority;
$this->_issueFieldStatus = $jira_object->issue->fields->status;
$this->_issueFieldAssignee = $jira_object->issue->fields->assignee;
$this->_issueFieldProject = $jira_object->issue->fields->project;

How could I make this shorter?


texts: Overriding default animation parameters with custom values

texts:
Using JavaScript ES5, I would like to know if you could suggest me a more "elegant" and succinct way to overriding defaults variable when User pass custom values.

In the following example, an animation is executed using _defaultOptions, a developer can change the default behavior passing only some properties to a function, example:

animate(dom, {duration: 2000}); // overriding only duration, rest as default

Notes:

I need also to support IE 11.
optionsArg is optional, so animate(dom) is allowed

var dom = document.getElementById('logo');

var _defaultOptions = {
  duration: 1000,
  delay: 0,
  iterations: 1,
  direction: 'normal',
  fill: 'both'
};

var animate = function(dom, optionsArg) {
  // code to be improved here
  var options = {
    duration: optionsArg && 'duration' in optionsArg ? optionsArg.duration : _defaultOptions.duration,
    delay: optionsArg && 'delay' in optionsArg ? optionsArg.delay : _defaultOptions.delay,
    iterations: optionsArg && 'iterations' in optionsArg ? optionsArg.iterations : _defaultOptions.iterations,
    direction: optionsArg && 'direction' in optionsArg ? optionsArg.direction : _defaultOptions.direction,
    fill: optionsArg && 'fill' in optionsArg ? optionsArg.fill : _defaultOptions.fill,
  };
  dom.animate([{
    opacity: 1
  }, {
    opacity: 0
  }], options);
};

animate(dom, {duration: 2000});
<img id="logo" src="https://upload.wikimedia.org/wikipedia/commons/e/e5/NASA_logo.svg">


texts:
I have implemented an Array class using templates. I have used a std::allocator object for memory allocation. Will it be better to use operator new along with placement new for memory allocation?

array.h

#ifndef ARRAY_H
#define ARRAY_H

#include <memory>
#include <cstddef>

template <typename T> class Array;

template<typename T> void swap(Array<T> &first, Array<T> &second);

template <typename T> class Array {
    friend void swap <> (Array<T> &first, Array<T> &second);
public:
    typedef T *iterator;
    typedef const T *const_iterator;
    typedef std::size_t size_type;
    typedef T value_type;

    explicit Array(size_type size, const T& value = T());
    Array(const_iterator range_begin, const_iterator range_end);
    Array(const Array&);

    Array& operator=(const Array);

    size_type size() const;

    T& operator[](size_type i);
    const T& operator[](size_type i) const;

    iterator begin();
    const_iterator begin() const;

    iterator end();
    const_iterator end() const;

    ~Array();
private:
    iterator data; // points to the first element of the array
    iterator limit; // points to one past the last element
    iterator avail; // points to one past the allocated memory

    std::allocator<T> alloc; // for memory allocation
};

// implementation
#include <algorithm>

template<typename T> void swap(Array<T> &first, Array<T> &second)
{
    using std::swap;

    swap(first.data, second.data);
    swap(first.limit, second.limit);
    swap(first.avail, second.avail);
}

template<typename T> Array<T>::Array(size_type size, const T& value):
    data(alloc.allocate(size)), limit(data), avail(data + size)
{
    while (limit < data + size)
        alloc.construct(limit++, value);
}

template<typename T> Array<T>::Array(const_iterator range_begin,
        const_iterator range_end):
    data(alloc.allocate(range_end - range_begin)), limit(data),
    avail(data + range_end - range_begin)
{
    const_iterator it = range_begin;
    while (limit < data + range_end - range_begin) {
        alloc.construct(limit++, *it);
        ++it;
    }
}

template<typename T> Array<T>::Array(const Array &original):
    data(alloc.construct(original.size())), limit(data),
    avail(data + original.size)
{
    iterator it = original.begin();
    while (it != original.limit()) {
        alloc.construct(limit++, *it);
        ++it;
    }
}

template<typename T> Array<T>& Array<T>::operator=(const Array rhs)
{
    swap(*this, rhs);

    return *this;
}

template<typename T> typename Array<T>::size_type Array<T>::size() const
{
    return limit - data;
}

template<typename T> T& Array<T>::operator[](size_type i)
{
    return data[i];
}

template<typename T> const T& Array<T>::operator[](size_type i) const
{
    return data[i];
}

template<typename T> typename Array<T>::iterator Array<T>::begin()
{
    return data;
}

template<typename T> typename Array<T>::const_iterator Array<T>::begin() const
{
    return data;
}

template<typename T> typename Array<T>::iterator Array<T>::end()
{
    return limit;
}

template<typename T> typename Array<T>::const_iterator Array<T>::end() const
{
    return limit;
}

template<typename T> Array<T>::~Array()
{
    while (limit != data)
        alloc.destroy(--limit);

    alloc.deallocate(data, avail - data);
}
#endif


texts: JavaScript - prototype, getters, setters, functions

texts:
I'm just getting to know the whole prototype world, and now I'm trying to do in JS what is normally done in OO languages, namely classes and DAO classes.

I'd be grateful for any comments on whether the code is written in accordance to JS best practices and whatnot. More specifically, I didn't implement getters or setters per se, is my approach still sound?

function Person(obj) {
  this.id = obj.id;
  this.name = obj.name;
  this.surname = obj.surname;
}

Person.prototype.toString = function(){
  return "["+this.id+"] name: " + this.name + ", surname: " + this.surname;
};

/*
Field.prototype = {
    get value(){
        return this._value;
    },
    set value(val){
        this._value = val;
    }
};
*/

function PersonDAO(){
   this.arrayOfPeople = [];
}

PersonDAO.prototype = {
  save:function(personObj){
    this.arrayOfPeople.push(personObj);
  },
  getAll:function(){
    return this.arrayOfPeople;
  }
};

var John = new Person({
  id: 1,
  name: "John",
  surname: "Smith"
});

var Bob = new Person({
  id: 2,
  name: "Bob",
  surname: "Doe"
});

var pDAO = new PersonDAO();
pDAO.save(John);
pDAO.save(Bob);
console.log(pDAO.getAll()[0].toString());


texts: PHP snippet to create image gallery from folders with jpgs

texts:
I would like to receive input from more experience coders regarding the potential improvements this piece of code might have. I am new to PHP development and I am sure this code looks horrible behind the eyes of someone more competent. It works, but I think there's plenty of room for improvement.

I have an images folder with several sub-directories, and inside them, different images are stored. The goal of this PHP snippet is to output HTML code in this format for each folder and files in my images folder:

examplefolder

examplefilename

examplefilename2

Here's said snippet:

<?php
    $folders = glob('images/otros/*', GLOB_ONLYDIR);
    foreach($folders as $folder) {
        echo "

".basename($folder)."

".PHP_EOL;
            $files = glob("images/otros/".basename($folder)."/*.{jpg}", GLOB_BRACE);
            foreach($files as $file) {
                echo "
".PHP_EOL."
".basename($file, ".jpg")."
".PHP_EOL."    ".PHP_EOL."
".PHP_EOL;
            }
        echo "
";
    }
?>

In particular, this one gets all folders with images inside images/otros.

Would you please offer any tips regarding best practices, or how to make my code look more readable?
Have I used any deprecated functions?
Is PHP_EOL the best way to add a newline character in order to make the output HTML look better?


texts: Generating an array of unique values of a specific property in an object array

texts:
Given a table represented as a javascript array of objects, I would like create a list of unique values for a specific property.

var table = [
  {
    a:1,
    b:2
  },
  {
    a:2,
    b:3
  },
  {
    a:1,
    b:4
  }
];

var groups = _.groupBy(table, "a");
var array = [];
_.forOwn(groups, function(value, key){
  array.push(key);
});

console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
Check your console

The problems with this code is that the groupBy keep track of the values, which I really don't care about, and I need to iterate over the entire list generated by group again so I can yank out the keys. It seems pretty inefficient to me and Im wondering if there is a smarter way to do this without reinventing the wheel (or perhaps if I should just bite the bullet and reinvent the wheel).


texts: Validate that a given email address has a whitelisted domain and the address has not already been registered

texts:
This is a remote validation method for a registration form, fired when the user enters an email address. It checks that the domain portion exists in a given list of valid domains, and then also checks the email address has not already been registered.

    [AllowAnonymous]
    [AcceptVerbs("Get", "Post")]
    public async Task<JsonResult> CheckEmail(string Email)
    {
        bool validDomain = false;
        string s = Email; //e.g. myname@my.org
        int idx = s.LastIndexOf('@');
        Console.WriteLine(s.Substring(0, idx)); //local half (not needed) e.g myname
        string domain = s.Substring(idx + 1).ToLower();    //domain half e.g. my.org

        IEnumerable<Organisation> organisations = _context.Organisations.ToList();

        foreach (var organisation in organisations)
        {
            if (domain == organisation.EmailDomain)
            {
                validDomain = true;
                break;
            }
        }

        if (validDomain == false)
        {
            return Json(
                data: "" + domain + " accounts cannot be used");
        }

        var result = await _userManager.FindByEmailAsync(Email);
        if (result == null)
        {
            return Json(data: true);
        }
        return Json(data: $"Email address already registered</a>");

    }

I also tried to use this line instead of the foreach loop but wouldn't get it to work:

//string result = organisations.FirstOrDefault(o => o.Contains(domain));

I got "symbol Contains cannot be resolved."

Would appreciate feedback on improving the rest of the code if possible.


texts: Recursively reading a directory in node.js

texts:
I made a function for recursively reading a directory and it just seems kind of long and complicated. If you could take a look and tell me what's good or bad about it, that would be great.

Reading the directory synchronously is not an option.

var dutils = require('./dutils');
module.exports = {
    getIndex: function(ignore, cb) {
        var root = this.root;
        var cbs = 1;
        var index = {};

        // recursive function for walking directory
        (function walk(dir) {
            fs.readdir(dir, function(err, files) {
                if (err) return cb(err);

                files.forEach(function(fileName) {
                    // prepare
                    var filePath = path.join(dir, fileName); // filePath with root
                    var relFilePath = path.relative(root, filePath); // filePath without root

                    // if the file is on our ignore list don't index it
                    if (dutils.globmatch(filePath, ignore)) return;

                    var stats = fs.statSync(filePath);
                    var isDir = stats.isDirectory();

                    index[relFilePath] = {
                        isDir: isDir,
                        mtime: stats.mtime
                    };

                    // if the file is a directory, walk it next
                    if (isDir) {
                        // count the number of callbacks that are running concurrently
                        cbs++;
                        walk(filePath);
                    }
                });

                // our callback was completed
                cbs--;

                // if all callbacks were completed, we've completely walked our directory
                if (cbs === 0) cb(null, index);
            });
        })(root);
    }
}


texts:
I have written a method to tokenize HTTP request paths such as /employee/23/edit:

protected void compile(String path){
    int mark=0;
    for(int i=0; i<path.length(); ++i){
        if(path.charAt(i)==DELIM){
            if(mark!=i)
                tokens.add(path.substring(mark,i));
            mark=i+1;
        }
        else if(path.length()==i+1){
            tokens.add(path.substring(mark,i+1));
        }
    }
}

And a method to tokenize the consumer of these paths such as /employee/[id]/edit:

protected void compile(String path){
    int mark=0;
    boolean wild=false;
    for(int i=0; i<path.length(); ++i){
        if(!wild){
            if(path.charAt(i)==DELIM){
                if(mark!=i)
                    tokens.add(path.substring(mark,i));
                mark=i+1;
            }
            else if(path.length()==i+1){
                tokens.add(path.substring(mark,i+1));
            }
            else if(path.charAt(i)=='['){
                wild=true;
            }
        }
        else if(path.charAt(i)==']'){
            tokens.add("?");
            wild=false;
            mark=i+1;
        }
    }
}

The idea here is that there will be an implicit variable called id with the value 23. However, that isn't here nor there. How does my approach look? Can it be improved? Also: DELIM = '/'.

This is more-or-less an exercise in writing a parser, which is why I didn't use String#split().


texts:
I want you to pick my code apart and give me some feedback on how I could make it better or more simple. This code will traverse peripheri  (clock and anticlockwise) in \$O(n)\$ just traversing the tree once.

public class PeriPheri {

    private TreeNode root;

    private static class TreeNode {
        TreeNode left;
        TreeNode right;
        int item;

        TreeNode(TreeNode left, TreeNode right, int item) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    private void printChild (TreeNode node) {
        if (node == null) {
            return;
        }

        if (node.left == null && node.right == null) {
            System.out.print(node.item + " ");
        }

        if (node != null) {
            printChild (node.left);
            printChild (node.right);
        }
    }

    private void leftAntiClock(TreeNode node) {
        if (node != null) {
            System.out.print(node.item +  " ");
            leftAntiClock (node.left);
            printChild (node.right);
        }
    }

    private void rightAntiClock(TreeNode node) {
        if (node != null) {
            printChild (node.left);
            rightAntiClock (node.right);
            System.out.print(node.item + " ");
        }
    }

    public void antiClockwise() {
        if (root == null) {
            return;
        }

        System.out.print (root.item + " ");
        leftAntiClock (root.left);
        rightAntiClock (root.right);
    }

    private void rightClock(TreeNode node) {
        if (node != null) {
            System.out.print(node.item + " ");
            rightClock(node.right);
            printChild(node.left);
        }
    }

    private void leftClock(TreeNode node) {
        if (node != null) {
            printChild(node.right);
            printChild(node.left);
            System.out.print(node.item + " ");
        }
    }

    public void clockwise() {
       if (root == null) {
          return null;
        }
        System.out.print(root.item + " ");
        rightClock (root.right);
        leftClock (root.left);
    }

}


texts: Longest word in dictionary that is a subsequence of a given string

texts:
I am trying out the following former Google interview question.

  The Challenge Given a string S and a set of words D, find the longest
  word in D that is a subsequence of S.

  Word W is a subsequence of S if some number of characters, possibly
  zero, can be deleted from S to form W, without reordering the
  remaining characters.

  Note: D can appear in any format (list, hash table, prefix tree, etc.

  For example, given the input of S = "abppplee" and D = {"able", "ale",
  "apple", "bale", "kangaroo"} the correct output would be "apple"

  The words "able" and "ale" are both subsequences of S, but they are
  shorter than "apple". The word "bale" is not a subsequence of S
  because even though S has all the right letters, they are not in the
  right order. The word "kangaroo" is the longest word in D, but it
  isn't a subsequence of S. Learning objectives This question gives you
  the chance to practice with algorithms and data structures. It’s also
  a good example of why careful analysis for Big-O performance is often
  worthwhile, as is careful exploration of common and worst-case input
  conditions

My approach uses a greedy algorithm.

Sort D in descending order(longest word first)
Find the index of first character in a word
Scan S from indexOfFirstCharacter to find other characters in the word
If we reach to the end of string and there are still characters remaining to be seen in a word then the word is not found
Repeat 2-4 until we find a word

from collections import deque
D = ["able","ale", "apple", "bale", "kangaroo"]
"""
TC : DlogD
"""
if len(D) > 1:
  D.sort(key=len,reverse=True)

S = "abppplee"
s_dict_first = {}
"""
TC : O(S)
"""
for i,s in enumerate(S):
  if s not in s_dict_first: s_dict_first[s] = i

"""
TC : O(1)
"""
#return first index of char
def getindex(char):
  if char in s_dict_first:
    return s_dict_first[char]
  return -1

"""
TC : O(w + w +S) = O(w + s)
"""
def isSubstringPresent(startIndex,word):
  #word is too big to be found in S
  if len(word) - 2 > len(S) - 1 - startIndex:
    return False
  remaining_chars = list(word[1:])
  char_queue = deque()
  for char in remaining_chars:
    char_queue.append(char)
  for i in range(startIndex,len(S)):
    if len(char_queue) == 0:return True
    if S[i] == char_queue[0]:
      char_queue.popleft()
  return len(char_queue) == 0

"""
TC : O(DlogD + D(w + s))
"""
for word in D:
  first_char = word[0]
  indexStart = getindex(first_char) + 1
  if indexStart == 0:continue
  if isSubstringPresent(indexStart,word):
     print(word)
     break;

I am open to suggestion in improving the code / any bug in my time/space complexity analysis or  any other useful comments.


texts: Find the common characters between two strings without using set operations

texts:
Below are two implementations of the problem "find the characters in common between two strings" - in Clojure without using collections / set operations.

Are these approaches sufficiently idiomatic and could the be more concise? (aside from using collections functions).

Also, is there a Clojure library that wraps or provides an alternative to java.util.BitSet?

;; Approach #1 BitSets
;; - use a bitsets for each string,
;; - flip the bit for each character in each string
;; - then "and" the two bitsets. Theoretically O(N + M) performance

(defn string-to-charbits [s]
  (loop [[f & rest] s
          bits (java.util.BitSet.)]
    (if f (recur rest (do (.set bits (int f)) bits))
           bits)))

(defn process-bitset [bitset]
   (loop [bitset bitset
          count 0
          result '[]]
     (if (< count (.length bitset))
       (recur bitset
              (inc count)
              (if (.get bitset count) (conj result (char count)) result))
       result)))

(defn find-matching-chars [s1 s2]
  (let [b1 (string-to-charbits s1)
        b2 (string-to-charbits s2)]
    (do
      (.and b1 b2)
      (process-bitset b1))))

;; Approach #2 - Brute Force
;; For each character in string 1, linear search (via .indexOf) of string 2
;; Theoretically O(N * M) performance

(defn find-matching-chars-brute [s1 s2]
  (loop [[f & rest] s1
         s2 s2
         result []]
    (if f
      (if (> (.indexOf s2 (int f)) -1)
        (recur rest s2 (conj result f))
        (recur rest s2 result))
      (distinct result))))

;; Might need to sort the results of each function call to make this pass
(assert (= (find-matching-chars "abcd" "cde")
            (find-matching-chars-brute "abcd" "cde"))
         "expected [\\c \\d]")


texts:
This is stripped down from a project I'm working on:

let userFields = {
    id: {
        dbFields: 'id',
    },
    email: {
        dbFields: 'email',
    },
    first_name: {
        dbFields: 'first_name',
    },
    last_name: {
        dbFields: 'last_name',
    },
    name: {
        dbFields: ['first_name', 'last_name'],
        resolve: user => [user.first_name, user.last_name].filter(n => n.length).join(' '),
    }
};

let selectFields = ['name', 'first_name', 'email'];

let dbFields = new Set();
selectFields.forEach(f => {
    if(userFields[f].dbFields) {
        if(userFields[f].dbFields instanceof Array) {
            userFields[f].dbFields.forEach(x => dbFields.add(x));
        } else {
            dbFields.add(userFields[f].dbFields);
        }
    }
});

console.log(Array.from(dbFields)); // [ 'first_name', 'last_name', 'email' ]

I don't like that big selectFields.forEach or the fact that Set doesn't appear to have an addMany method.

Is there any way I can compact this a bit more?

You can run this with babel-node if you need to (npm install -g babel).


texts:
There have been already many similar questions to this one (e.g. this and this, just to point two), but I did not find any for clojure.

The goal is to compress a string in a RLE-like way: i.e. each character "run" is replaced by the character and the count of the run. Some examples:

aaaabbccc       -->      a4b2c3
b               -->      b1
aaaaaaaaaaaa    -->      a9a3

Some remarks:

For now, I do not care about the possible optimisation that runs with the length of 1 can omit the count. (E.g. the output could be b instead of b1.)
If there are more than n > 9 characters in a run, then it is split up into two or more runs, like 9 + 9 + 9 + ... + k = n, where k <= 9.
For now, I do not care if the "compressed" string will be longer than the original one (this is the case e.g. for an input containing only single characters, like: abcde --> a1b1c1d1e1).

That said, please see my implementation below:

Source

(defn countrepetitions [s]
      (if (empty? s) 0
          (loop [acts (vec s) ch (first acts) cnt 1]
                (if (= ch (first(rest acts)))
                   (recur (rest acts) ch (inc cnt))
                    cnt))))

(defn mycompress [s]
      (loop [acts s encoded "" cnt1 (countrepetitions acts)]
            (if (= 0 cnt1)
                encoded
                (let [cnt2 (if (< cnt1 10) cnt1 9)]
                     (recur (subs acts cnt2) (str encoded (first acts) cnt2) (countrepetitions (subs acts cnt2)))))))

Tests

(deftest a-test
  (testing "compressor"
    (is (= "" (mycompress "")))
    (is (= "a2" (mycompress "aa")))
    (is (= "a1b8a1c7a3" (mycompress "abbbbbbbbacccccccaaa")))
    (is (= "b9b3" (mycompress "bbbbbbbbbbbb")))))

Questions

In particular, I would be interested in the following, but any other remark/suggestion is also welcome:

Is there a more efficient way (either in terms of readability or speed) to implement countrepetitions, or maybe leave it out completely?
Are there any other tests worth adding? Or can you find a "counter-example" (i.e. a test case, for which the implementation does not work correctly)?


texts:
Here is my code for checking to see if two strings are anagrams. This seems a little short. Am I missing anything? Both time and space complexity seem to be \$O(1)\$.

//Determine if a string is an anagram
//Time complexity: O(1)
//Space complexity: O

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

bool anagram(string one, string two)
{

    if (one.length() != two.length())
    {
        return false;
    }

    //sorting the strings
    sort(one.begin(), one.end());
    sort(two.begin(), two.end());

    return (one == two);

}

int main() {

    string one;
    string two;

    cout << "please enter in a string: ";
    cin >> one;
    cout << "please enter in another string: ";
    cin >> two;

    cout << anagram(one, two) <<endl;

    return 0;

}


texts: Linked list where user replace a chosen number in the list with a number chosen by user - how can it be improved?

texts:
I'm quite new to C programming so I'm trying to learn the basics. I've made a program that creates a linked list of numbers, then ask user for which number he/she wants to replace and then what number should come instead.

I finally got it to work, but since I'm learning this on my own no one is there to say when my style is bad or if I use bad methods for solving my problems. So I kindly ask if you see something that's done in an unwise way to let me know.

So here's the code:

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

struct node {
    int val;
    struct node* next;
};

typedef struct node node_t;

// Function that evaluate the value in the nodes of the linked list and replace it.
void replace(node_t ** head, int replacement_value, int new_value) {
    node_t **tracer = head;

    while ((*tracer)->next != NULL && (*tracer)->val != replacement_value) {
        (*tracer) = (*tracer)->next;
    }
    (*tracer)->val = new_value;

}

// Function that prints out the linked list.
void printlist(node_t *head) {
    node_t *temporary = head;

    while (temporary != NULL) {
        printf("%d - ", temporary->val);
        temporary = temporary->next;
    }
    printf("\n");
}

// The following creates nodes in the linked list.
node_t *create_new_node(int val) {
    node_t *result = malloc(sizeof(node_t));
    result->val = val;
    result->next = NULL;
    return result;
}

int main(){

    node_t *head = NULL;
    node_t *tmp;

    // The following creates the linked list.
    for (int i=0; i<25; i++) {
        tmp = create_new_node(i);
        tmp->next = head;
        head=tmp;
    }

    printf("First print:\n");
    printlist(head);

    int replacement_value;
    int new_value;

    printf("Which number do you wish to replace?\n");
    scanf("%d", &replacement_value);
    printf("What number do you want to replace it with?\n");
    scanf("%d", &new_value);

    node_t *temphead;
    temphead = head;
    replace(&temphead, replacement_value, new_value);

    printf("Modified print:\n");
    printlist(head);

    return(0);
}


texts: The FizzBuzz challenge in Java 8 written in a short, readable and interesting way

texts:
I decided to take on the FizzBuzz challenge with as twist that I would use Java 8 concepts to make it a bit modular, yet still let it be a short, readable and understandable program.

This in contrary to some gem I found on the net: FizzBuzzEnterpriseEdition

The problem description:

  Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"

Here's my code:

public class FizzBuzz {
    private static Stream<String> fizzBuzz(final int min, final int max) {
        if (min < 0) {
            throw new IllegalArgumentException("min is negative: min = " + min);
        }
        if (min > max) {
            throw new IllegalArgumentException("min > max: min = " + min + " / max = " + max);
        }
        return IntStream.rangeClosed(min, max)
                .mapToObj(FizzBuzz::fizzBuzzify);
    }

    private static String fizzBuzzify(final int value) {
        StringBuilder stringBuilder = new StringBuilder();
        boolean toDefault = true;
        if (value % 3 == 0) {
            stringBuilder.append("Fizz");
            toDefault = false;
        }
        if (value % 5 == 0) {
            stringBuilder.append("Buzz");
            toDefault = false;
        }
        return (toDefault) ? String.valueOf(value) : stringBuilder.toString();
    }

    public static void main(String[] args) {
        fizzBuzz(1, 100).forEach(System.out::println);
    }
}

I'm still looking for a nicer way to write fizzBuzzify, my intention however is to not hardcode the if (value % 15 == 0) similarly if (value % 3 == 0 && value % 5 == 0), because it creates a sort of illogical operation precedence, being that you absolutely need to write the if (value % 15 == 0) case up front, followed by the 3-case and the 5-case (or vica versa).


texts:
As part of a first year university course in computer architecture some time ago we were tasked with learning 8086 ASM.  The final course work required creating a small animation of shapes moving around the screen changing colours and the like.

As I would not expect anyone to review 720 lines of assembler I'm just going to provide my implementation of Bresenham's Line Algorithm.

Note that this is not the entire program but a single macro from the working program.

Also note that at the time of writing I had little to no experience with 8086 ASM (I still don't in fact), but I'm very interested in knowing how I did and how it could have been improved upon.

If anyone is interested in reviewing the rest of the project as well (it can be done in small parts) then let me know.

;=========================================================================================================
;                       BRESENHAM LINE ALGORITHM (lx1,ly1)-(lx2,ly2)
;=========================================================================================================
line macro lx1, ly1, lx2, ly2
    local ldxsetup1, ldxsetup2, ldysetup1, ldysetup2
    local lxisetup1, lxisetup2, lxisetupexit, lyisetup1, lyisetup2, lyisetupexit
    local numsetup1, numsetup2, numsetupexit
    local lloopstart, lloopif, lloopifexit, lloopend
    pushall
    mov ax, lx2
    sub ax, lx1
    cmp ax, 0
    jge ldxsetup2
ldxsetup1:
    mov bx, -1
    mul bx
ldxsetup2:
    mov ldx, ax
    mov ax, ly2
    sub ax, ly1
    cmp ax, 0
    jge ldysetup2
ldysetup1:
    mov bx, -1
    mul bx
ldysetup2:
    mov ldy, ax
    mov ax, lx1
    mov lx, ax
    mov ax, ly1
    mov ly, ax
    mov ax, lx2
    cmp ax, lx1
    jge lxisetup1
    jmp lxisetup2
lxisetup1:
    mov ax, 1
    jmp lxisetupexit
lxisetup2:
    mov ax, -1
lxisetupexit:
    mov lxi1, ax
    mov lxi2, ax
    mov ax, ly2
    cmp ax, ly1
    jge lyisetup1
    jmp lyisetup2
lyisetup1:
    mov ax, 1
    jmp lyisetupexit
lyisetup2:
    mov ax, -1
lyisetupexit:
    mov lyi1, ax
    mov lyi2, ax
    mov ax, ldx
    mov bx, ldy
    cmp ax, bx
    jge numsetup1
    jmp numsetup2
numsetup1:
    mov ax, 0
    mov lxi1, ax
    mov lyi2, ax
    mov ax, ldx
    mov lden, ax
    mov lnumpix, ax
    shr ax, 1
    mov lnum, ax
    mov ax, ldy
    mov lnumadd, ax
    jmp numsetupexit
numsetup2:
    mov ax, 0
    mov lxi2, ax
    mov lyi1, ax
    mov ax, ldy
    mov lden, ax
    mov lnumpix, ax
    shr ax, 1
    mov lnum, ax
    mov ax, ldx
    mov lnumadd, ax
numsetupexit:
    mov ax, lnum
    mov dx, 0
lloopstart:
    cmp dx, lnumpix
    jg lloopend
    plot lx, ly
    add ax, lnumadd
    cmp ax, lden
    jge lloopif
    jmp lloopifexit
lloopif:
    sub ax, lden
    mov bx, lx
    add bx, lxi1
    mov lx, bx
    mov bx, ly
    add bx, lyi1
    mov ly, bx
lloopifexit:
    mov bx, lx
    add bx, lxi2
    mov lx, bx
    mov bx, ly
    add bx, lyi2
    mov ly, bx
    inc dx
    jmp lloopstart
lloopend:
    popall
endm
;=========================================================================================================

Here's the definitions of pushall and popall:

;=========================================================================================================
;                       PUSH ALL DATA TO STACK
;=========================================================================================================
pushall macro
    push ax
    push bx
    push cx
    push dx
endm
;=========================================================================================================
;=========================================================================================================
;                       POP ALL DATA FROM STACK
;=========================================================================================================
popall macro
    pop dx
    pop cx
    pop bx
    pop ax
endm
;=========================================================================================================


texts:
I built a simple counter in React. I'm using Redux for state management and Redux-Saga for async calls.

I'm looking for feedback on directory structure, coding style and pretty much everything else.

Demo

GitHub

import React, { Component } from 'react'
import {connect} from 'react-redux'
import buttons from './buttons'
import {
    increment,
    decrement,
    asyncrement } from '../store/actions'
import './counter.css'

const mapStateToProps = (state)=> {
    return {
      score: state.score
    }
}
const mapDispatchToProps = (dispatch)  => ({
        increment: () => dispatch(increment()),
        decrement: () => dispatch(decrement()),
        asyncrement: () => dispatch(asyncrement())
});

const displayCounter = score =>(

      Score: {score}

)

class Counter extends Component {
    render(){
        const {
            score,
          increment,
          decrement,
          asyncrement } = this.props
        return(

            {displayCounter(score)}
            {buttons(increment, decrement, asyncrement)}

        )
    }
}
const counter = connect(
    mapStateToProps,
    mapDispatchToProps)(Counter)
export default counter


texts:
This is my first attempt at writing code that moves files at the end of the day, from my local work folder to an network archive.

The program works but, any tips, tricks, or ideas to make this code better would be most appreciated.

import shutil, os, datetime, time, sys

os.system('TASKKILL /F /IM FlashRen.exe')

newFolderName = datetime.datetime.now()
newFolder = newFolderName.strftime('%m%d%Y')

src = ('C:\\AEC Work\\' + newFolder)
dst = ('\\\qnap01\\Data Service\\AARON\\' +
           newFolderName.strftime('%Y\\') +
           newFolderName.strftime('%m. %B\\').upper() + newFolder)

for file in os.listdir(src):
    src_file = os.path.join(src, file)
    dst_file = os.path.join(dst, file)
    shutil.move(src, dst)


texts: Function to conect to Firebase Rest API via Access VBA

texts:
This is the application for small school, which will store students' info in Firebase and also retrieve data from Firebase. I am using JSON Parser to parse the data and save the same in Access tables.

I am using this function in MS Access to connect to the Firebase. Please tell me if I am doing anything in an inefficient manner.

Function:

'---------------------
'#### FUcntion to make all web request and get data ####
Public Function ApiFirebaseCall(ByVal apiURL As String, _
                                ByVal Method As String, _
                                Optional ByVal apiBody As String) As String
'On Error GoTo Sub_Err

    Dim reader As New XMLHTTP60

    Debug.Print Method & " = " & apiURL
    Debug.Print "BODY" & Nz(apiBody)

    'Open URL of API
    reader.Open Method, apiURL

    If IsNull(apiBody) Or apiBody = "" Then
    'In case of GET
        reader.send
    Else
    'In case of POST, PATCH, DELETE
        reader.send (apiBody)
    End If

    'Using since is was mentioned in SO. Don't know the reason why
    Do Until reader.ReadyState = 4
        DoEvents
    Loop

    If reader.Status = 200 Then
    'The API was sucessful
        If reader.responseText <> "null" Then
        'Now check if the response contains data
            ApiFirebaseCall = reader.responseText
        Else
            MsgBox reader.responseText
            ApiFirebaseCall = "Error"
        End If
    Else
    'The API Call was not sucessful
        MsgBox reader.responseText
        ApiFirebaseCall = "Error"
    End If

    'Debug.Print "Reader Response - " & reader.responseText

'Error Catching
Sub_Exit:
    Exit Function
Sub_Err:
    ApiFirebaseCall = "Error"
    MsgBox Error$
    Resume Sub_Exit

End Function

Example function call:

Dim apiURL, response As String
apiURL = apiBaseURL & "/d.json?auth=" & apiAuthKey
response = ApiFirebaseCall(apiURL, "GET")

'Forward processing to next function, if API Call was sucessfull
If response <> "Error" Then
    JsonParser (response)
End If


texts: Comparing random number of bits (followup)

texts:
This is a follow-up of Comparing random number of bits.

I have a function that compares bits from a binary representation string and a chunk of memory and returns true if they are equal.

This is the function (which works as expected): I'll explain with comments what some external methods are supposed to do, accept that they work as expected for the sake of this question.

bool Bits::compareBinary(const char *string, size_t check_n_bits, size_t skip_n_bits){
    bool match = true;

    size_t bytes = (check_n_bits + 7) / 8;
    size_t bytes_with_skip = (check_n_bits + skip_n_bits + 7) / 8;

    if(this->canMoveForward(bytes_with_skip) == false) return false;

    Bits *data = this->readBits(check_n_bits, skip_n_bits);

    unsigned char *bin_string = Utils::removeSpaces(string);
    size_t len = strlen((const char *) bin_string);
    if(Utils::isValidBinString(bin_string) || len < check_n_bits) return false;

    char tmp_bin_repr[9];

    for(size_t i = 0; i < bytes; i++) {
        int chars_to_compare = i + 1 == bytes ? check_n_bits % 8 : 8;
        chars_to_compare = chars_to_compare == 0 ? 8 : chars_to_compare;

        uint8_t c = data->read_uint8();
        sprintf(tmp_bin_repr, BYTETOBINARYPATTERN, BYTETOBINARY(c));

        if(memcmp(tmp_bin_repr, &bin_string[i * 8], chars_to_compare) != 0) {
            match = false;
            break;
        }
    }
}

Helper macro:

#define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d"
#define BYTETOBINARY(byte) \
    (byte & 0x80 ? 1 : 0), \
    (byte & 0x40 ? 1 : 0), \
    (byte & 0x20 ? 1 : 0), \
    (byte & 0x10 ? 1 : 0), \
    (byte & 0x08 ? 1 : 0), \
    (byte & 0x04 ? 1 : 0), \
    (byte & 0x02 ? 1 : 0), \
    (byte & 0x01 ? 1 : 0)

Let's call this function:

compareBinary(const char *string, size_t check_n_bits, size_t skip_b_bits)

As there are a couple of methods and a class I can't post here (for the sake of this question), you're free to explore the entire code here.
How is this function used? The function is a method of an object that contains some data. When this method is called, it compares as many bits from a binary string representation of data as we pass it with the data contained in the object.

Example:

mObj->compareBinary("01010101 11110100 00", 18, 0);

This will compare 18 bits in total with the data that is hold in the object. First 8 chars of the passed string will be taken and the first byte of the data hold by the object will be converted to a string (using the helper macro). Then both will be compared. Second 8 chars, the same. Then we'd get the last 00 chars, take the third byte, convert it to a 8 chars binary representation, but only the first two chars will be compared.

This lets me compare a random number of bits with a simple binary representation of the data.

While the function works as expected and it's passing multiple unit tests, I believe it can be refactored and optimized. Can you give me any tips how to do it?


texts: I've finally found a satisfactory way to create classes on JavaScript. Are there any cons to it?

texts:
Depending on external OO libraries is really bad, using prototypes/new has some limitations, using only hashes has others. Dealing with classes was always a pain in JavaScript and it didn't help that every library has it's own way to deal with ti. But since some time I've finally "set" with this design:

function my_class(extend,init){
    var self = extend || {};

    var private = 5;
    self.public = 5;
    self.get_private = function(){
        return private;
    };

    for (var key in init) self[key] = init[key];
    return self;
};

Tests:

var instance = my_class();

// publics and privates
console.log(instance.public);
console.log(instance.get_private());

// methods never lose context
(function(method){
    console.log(method());
})(instance.get_private);

// multiple inheritance trivial
var random_obj = {a:1,b:2,c:3};
my_class(random_obj); // now random_obj inherits my_class

// serializable, store in a DB and recover it with:
var serialized = JSON.stringify(instance);
var instance = my_class({},JSON.parse(serialized));
console.log("Instance: ",instance);

I'm surprised how this simple design solves all the problems of the other approaches. Prototypes make multiple inheritance hard, hashes won't allow privates, there's no more the "this" binding issue, instances are JSON-serializable, all that without depending on external libraries. Is there any cons to this method, or something that is hard to do with it - or can I just go and start preaching about it?


texts: Function that shortens a String based on a term/abbreviation mapping

texts:
I have a function that takes a description as a String and returns a shortened version of the description.

The shortening is done by checking if a word matches the key of the HashMap<String,String> map and replaces the word by its abbreviation defined as the value in the HashMap. If the word cannot be found it in the HashMap it will not be replaced (it stays the same). If the value of a word is <remove> the word will be removed from the new description.

There can be multiple abbreviations for the same word.

Example:

  AUTOMATIC GAIN CONTROL --> AGC

  CONTROL --> CTRL

In any case the function should always take the abbreviation which takes the most words.

Consider this example mapping:

  AUTOMATIC GAIN CONTROL --> AGC

  CONTROL --> CTRL

  IDENTIFIER --> ID

  THE --> <remove>

The input String:

  The Automatic Gain Control identifier value

will result in the output String:

  AGC ID value

The String's in the HashMap are all uppercase and the abbreviation in the output String should also be uppercase. However, any word that was not found in the HashMap should stay the same as it was in the input String.

My function seems to do the task correctly but I'm not sure if it could have been written better and/or more efficiently.

private static HashMap<String,String> map = new HashMap<String, String>();

public static String shortenText(String input){

    ArrayList<String> listUpperCase = new ArrayList<String>(Arrays.asList(new String(input).toUpperCase().split(" ")));
    ArrayList<String> list = new ArrayList<String>(Arrays.asList(input.split(" ")));

    //Remove any words that map to <remove>
    for (int i=0;i<list.size();i++){
        String value = map.get(listUpperCase.get(i));
        if (value!=null){
            if(value.equals("<remove>")){
                list.remove(i);
                listUpperCase.remove(i);
            }
        }
    }
    //Replace words by their abbreviation
    StringBuilder builder = new StringBuilder();
    for (int i=0;i<list.size();i++){
        StringBuilder tempBuilder = new StringBuilder();
        String longestStringToShort="";
        int count=0;
        //Find abbreviations for terms with multiple words
        for(int k=0;k<list.size()-i;k++){
            tempBuilder.append(" "+listUpperCase.get(i+k));
            if(k==0) tempBuilder.deleteCharAt(0);
            String value = map.get(tempBuilder.toString());
            if (value!=null){
                longestStringToShort = value;
                count = k;
            }
        }
        if (!longestStringToShort.equals("")){
            builder.append(" "+longestStringToShort);
            i=i+count;
        }
        else builder.append(" "+list.get(i));

    }

    builder.deleteCharAt(0);
    return builder.toString();

}


texts: JavaScript multiple ajax calls but can either be one or two

texts:
I'm writing a piece of JavaScript to make one or two ajax calls. There will always be one ajax call fired but it might be two based on cookie setting. If user is logged in then we call another service to get the data. I would want this to fire async that's why I didn't put the second ajax call in the callback of the first call. We don't use jQuery just vanilla JS.

'use strict';

import Cookie from 'js-cookie';
const _ = require('../helpers');

module.exports = function(cb) {
  let number_of_calls = 1;
  window._g = window._g || {};

  const uid = Cookie.get('uid');
  if (uid) {
    number_of_calls += 1;
  }

  function setG(fds) {
    --number_of_calls;
    const out = JSON.parse(fds);
    window._g.context = out;

    if (number_of_calls === 0) {
      cb({});
    }
  };

  function setUser(user) {
    --number_of_calls;
    const out = JSON.parse(user);
    window._g.user = out;
    if (number_of_calls === 0) {
      cb({});
    }
  }

  _.ajax({url: '//some_service/content?url=' + _.url}).done(setG);

  if (uid) {
    _.ajax({url: '//another_service/user?uid=' + uid}).done(setUser);
  }
};


texts: Factory method to create two kinds of cars based on an enum

texts:
I am implementing the factory method approach. My intention is to know if my approach is correct for factory method. Any modifications to be done to align with the approach?

First  I am creating an interface IAuto.

 //IAuto.cs
    namespace TestDesignPatterns.Auto
    {
        public interface IAuto
        {

            void start();
            void stop();
        }
    }

Create a class that implements the IAuto.

    //clsBMW.cs
    namespace TestDesignPatterns.Auto
    {
        public class clsBMW : IAuto
        {
            public void start()
            {
                Console.WriteLine("BMW started");
            }

            public void stop()
            {
                Console.WriteLine("BMW stopped");
            }
        }
    }

Create another concrete class for Audi implementing IAuto.

namespace TestDesignPatterns.Auto
{
    public class clsAudi : IAuto
    {
        public void start()
        {
            Console.WriteLine("Audi started");
        }

        public void stop()
        {
            Console.WriteLine("Audi stopped");
        }
    }
}

Create an Interface of factory which creates the model.

//IautoFactory.cs
public interface IAutoFactory
    {
       IAuto createModel(ModelType m);
    }

concrete factory class.

//clsAutofactory.cs
 public class clsAutoFactory : IAutoFactory
    {
        public IAuto createModel(ModelType m)
        {
            IAuto instance = null;
            switch (Convert.ToInt32(m))
            {
                case 0:
                    instance = new clsBMW();
                    break;

                case 1:
                   instance =  new clsAudi();
                    break;
                default:
                    break;

            }

            return instance;
        }
    }

Main Program

 public enum ModelType
    {
        BMW=0,
        Audi=1
    }
//program.cs

            IAutoFactory factory = new clsAutoFactory();
            IAuto model = factory.createModel(ModelType.Audi);
            model.start();
            model.stop();
            Console.ReadKey();


texts: Defining many HTTP request methods in a class using partialmethods

texts:
I am using an object that expects a keyword argument for every call, but I never intend to change it. In this case a timeout of 10. What is the best way to add a partialmethods for each attributes.

In my example I want to set a timeout for my session requests http methods.

I could monkeypatch Session.request with a partialmethod. This works fairly well because all of the session methods go through request. Session().post is actually going through Session.request('post', <inputs>).

from requests import Session

Session.request = partialmethod(Session.request, timeout=10)

However, what about use cases where there isn't a single method I can fix or I simply don't want to do something potentially dangerous like monkeypatching.

I have a session helper object that configures the auth and the adapter (omitted here) for the client, but I want different default timeouts for different methods. I can't even monkeypatch the method in that case.

I could do it after standard definition of the class in a loop.

from functools import partialmethod
from requests import Session

class SeshTester:
    def __init__(self):
        self.s = Session()

    def request(self, method, *args, **kwargs):
        return self.s.request(method, *args, **kwargs)

for r_method in ['delete', 'get', 'head', 'options']:
    setattr(SeshTester, r_method, partialmethod(SeshTester.request, r_method, timeout=7))

for r_method in ['connect', 'put', 'push']:
    setattr(SeshTester, r_method, partialmethod(SeshTester.request, r_method, timeout=13))

# this call is equivalent to self.s.request('get', 'http://google.com', timeout=7
print(SeshTester().get('http://google.com'))

I don't think this is very legible, but am unaware how to do this inside of standard class definition. SeshTester object obviously isn't reference-able before it is made, but I don't want to repeat myself by doing post = partialmethod(request, 'post', timeout=13) for every possible http method.

I would like to perform this loop in the class, but don't know how to reference the object before it's fully defined.


texts:
I have created keyboard shortcuts menu,same as like this stackoverflow keyboard shortcuts.In multilevel.

  Scenario

In first level i have assigned functions for only key A.

In the second level i have assigned functions for B & C keys

I have controlled key events B & c in the first level with a variable.

Its working fine.I would like to know is there any better way of doing it.

var level= 0;
$('body').keypress(function(e){
  level == 1 ?(
(((e.keyCode == 66 || e.keyCode == 98)  && level==1 )? (alert("B"),level=2,$('#screen3').show()) : ""),
(((e.keyCode == 67 || e.keyCode == 99)  && level==1 )? (alert("c"),level=2,$('#screen3').show()) : "")
):"";
level == 0 ?((e.keyCode == 65 || e.keyCode == 97) ? level = 1 : level =0):"";
level == 1 ?($('#screen1').hide(),$('#screen2').show()):(level =2 ?$('#screen2').hide():(level= 0));
});
#screen1,#screen2,#screen3 {
background-color: black;
background-color: rgba(0, 0, 0, .8);
position: fixed;
left: 10px;
top: 10px;
padding: 10px;
text-align: left;
border-radius: 6px;
z-index: 1000;
  color:white ;
}

:matches(#screen1,#screen2) pre kbd {
display: inline-block;
font-family: monospace;
}
kbd {
padding: .1em .6em;
border: 1px solid #ccc;
font-size: 11px;
  background-color: #f7f7f7;
color: #333;
  box-shadow: 0 1px 0 rgba(0,0,0,0.2),0 0 0 2px #fff inset;
  border-radius: 3px;
  margin: 0 .1em;
text-shadow: 0 1px 0 #fff;
line-height: 1.4;
white-space: nowrap;
  }

Keyboard shortcuts:
A alert

Keyboard shortcuts:
B alert Key - B
C alert Key - C

Thats it Folks!!


texts:
This is my current code to check list of urls for response code within same domain.
I would like to know if there's a way where i can improve my code performance more better.
import argparse
import logging
import os
import smtplib
import time

import httpx
import trio
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import tabulate

logger = logging.getLogger('MyLog')
logger.setLevel(logging.INFO)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)-5.5s - %(message)s', "%Y-%m-%d %H:%M:%S")
file_handler = logging.FileHandler(
    'MyLog.log', 'a', encoding='utf-8')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

year, month = time.strftime('%Y:%m').split(":")

def validfile(parser, fn):
    if not os.path.isfile(fn):
        parser.error(f"File {fn} Doesn't Exist")
    else:
        return fn

result = []

async def checker(channel):
    async with channel:
        async for client, ticker in channel:
            while True:
                try:
                    r = await client.head(f"https://www.hiddenurl.com/{year}/{month}/{ticker}")
                    break
                except httpx.RequestError as e:
                    logger.error('Url: {:75}, Reason: {}'.format(
                        r.url, type(e).__name__))
                    continue

            status = "Url: {:75}, Status: {}".format(r.url, r.status_code)
            logger.info(status)
            if r.status_code == 200:
                print(status)
                result.append(r.url)

async def mailer():
    myemail = "my@my.com"
    HTML = tabulate(result, tablefmt='html')
    msg = MIMEMultipart("alternative", None, [MIMEText(HTML, 'html')])
    msg['Subject'] = f'We Got {len(result)} Result!'
    msg['From'] = myemail
    msg['To'] = "hidden@hidden.com"

    try:
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
            smtp.login(myemail, 'mypass')
            smtp.send_message(msg)
            logger.info('Email Sent! ---> {}'.format(result))
            print(f"Yay! Email Sent With {len(result)} Records!")
    except (smtplib.SMTPException, smtplib.socket.error) as e:
        status = 'Unable To Send Email Due To --> {}'.format(type(e).__name__)
        logger.error(status)
        print(status)

async def main(links):
    headers = {
        'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
    }
    async with httpx.AsyncClient(timeout=None) as client, trio.open_nursery() as nurse, await trio.open_file(links) as f:
        client.headers.update(headers)
        sender, receiver = trio.open_memory_channel(0)

        async with receiver:
            for _ in range(50):
                nurse.start_soon(checker, receiver.clone())

            async with sender:
                async for ticker in f:
                    ticker = ticker.lower().rstrip()
                    if ticker and not ticker.startswith('#'):
                        await sender.send([client, ticker])
    if result:
        await mailer()
    else:
        logger.info('No Active Ticker Detected!')

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='Checking Tickers Response Code')
    parser.add_argument('tickers', help='File Include Tickers',
                        type=lambda x: validfile(parser, x))
    trio.run(main, parser.parse_args().tickers)
```


texts:
Inspired by a previous question, I was looking into converting a table to a sorted list (ascending) -

Resulting in this -

I used a very simple bubble-sort, but I don't know how efficient that would be with larger data sets, either in records or if I wanted to sort on more than one condition. Basically, this was an exercise in using arrays when built-in excel tools would be better.

Option Explicit

Public Sub GetBids()
    Dim i As Long
    Dim j As Long
    Dim customer As String
    Dim counter As Long
    Dim size As Long
    Dim sortedBids As Variant
    counter = 1

    Dim lastRow As Long
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    Dim lastColumn As Long
    lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
    size = WorksheetFunction.Count(Range(Cells(2, 2), Cells(lastRow, lastColumn)))

    Dim arrayOfBids As Variant
    ReDim arrayOfBids(1 To size, 1 To 2)
    For i = 2 To lastRow
        customer = Cells(i, 1)
        For j = 2 To lastColumn
            If Not IsEmpty(Cells(i, j)) Then
            arrayOfBids(counter, 1) = Cells(i, j)
            arrayOfBids(counter, 2) = customer
            counter = counter + 1
            End If
        Next
    Next

    sortedBids = BubbleSort(arrayOfBids)
    Range(Cells(1, 6), Cells(size, 7)) = sortedBids

End Sub

Private Function BubbleSort(ByVal arrayOfBids As Variant) As Variant
    Dim temporaryArray As Variant
    Dim i As Integer
    Dim exchangeMade As Boolean
    ReDim temporaryArray(1 To 1, 1 To 2)

    Do
        exchangeMade = True
        For i = 1 To UBound(arrayOfBids) - 1
            If arrayOfBids(i, 1) > arrayOfBids(i + 1, 1) Then
                exchangeMade = False
                temporaryArray(1, 1) = arrayOfBids(i, 1)
                temporaryArray(1, 2) = arrayOfBids(i, 2)
                arrayOfBids(i, 1) = arrayOfBids(i + 1, 1)
                arrayOfBids(i, 2) = arrayOfBids(i + 1, 2)
                arrayOfBids(i + 1, 1) = temporaryArray(1, 1)
                arrayOfBids(i + 1, 2) = temporaryArray(1, 2)
            End If
        Next i
    Loop While Not (exchangeMade)

    BubbleSort = arrayOfBids
End Function


texts:
Three questions: is there a more performant way, is there a more suscinct, strike that, a way of expressing this where if you read just the body it is immediately apperent what the alorithm does, and should I be returning and IEnumerable of an IEnumerable, I mean what would be the point over and IEnumerable of IList?

public static IEnumerable<IEnumerable<T>> IntoBatches<T>(this IEnumerable<T> list, int size)
{
    if (size < 1)
    {
        yield return list;
    }
    else
    {
        var count = 0;
        var batch = new List<T>();
        foreach (var item in list)
        {
            batch.Add(item);
            if (size == ++count)
            {
                yield return batch;
                batch.Clear();
            }
        }
        if (batch.Count > 0) yield return batch;
    }
}


texts:
I have implemented a message queue for inter thread communication just like POSIX message queue. I want to know whether there is any scope for performance improvement and also any bugs which need to be corrected. This is my code:
#include <iostream>
#include <cstring>
#include <list>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mu;
std::condition_variable cv;
std::list<std::vector<char>> msg_queue;

void recv() {
    char buff[2048];

    while(true) {
        std::unique_lock<std::mutex> ul { mu };

        while(msg_queue.empty())
            cv.wait(ul);

        std::vector<char>& queue_msg = msg_queue.front();
        if(queue_msg.size() < sizeof(buff)) {
            std::memcpy(buff, queue_msg.data(), queue_msg.size());
            buff[queue_msg.size()] = '\0';
        }

        msg_queue.pop_front();

        ul.unlock();

        std::cout << buff << std::endl;
    }
}

int32_t main() {
    const char *data = "Hello world!";
    std::thread th(recv);

    while(true) {
        mu.lock();

        msg_queue.emplace_back(std::vector<char>(data, data + strlen(data)));
        cv.notify_one();

        mu.unlock();

        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    th.join();

    return EXIT_SUCCESS;
}


texts: Reusing StringBuilder or creating a new one?

texts:
Given that it is better to reuse objects than create new ones when developing with Android, is it worth while deleting the contents of a StringBuilder and reusing it?

StringBuilder b = new StringBuilder();
//build up a string
b.delete(0, b.length());
//reuse it

Compared to:

StringBuilder b1 = new StringBuilder();
//build up a string
StringBuilder b2 = new StringBuilder();
//create a new one


texts:
I'm working on a database migration script written in python, which will take data from a MySQL database and insert them into a PostgreSQL database with a different Schema (different table structures, different datatypes and so on).

Performances does matter, since I will have to handle with sizable databases.

I use mysql.connector and psycopg2 adapters in order to make python talks with the two databases.

My problem is that I need performance, but also the power of modifying/converting mysql data before inserting rows in the new fresh database. I will give you an example in order to show why there actually is a conflict of interest.

Following is a snippet of code without performance optimization, but at least, where transformation/conversion of data was possible:

cur_msql.execute("SELECT customer_id, customer_name, contact_name, address, city, postal_code, country FROM mysqlcustomers")

for row in cur_msql:

  # /!\ checking if customer_name is NULL (NOT NULL field in destination database)
  if row['customer_name'] == NULL:
    row['customer_name'] = row['contact_name']

  try:
    cur_psql.execute("INSERT INTO psqlcustomers (customer_id, customer_name, contact_name, address, city, postal_code, country) \
                      VALUES (%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)", row)
  except psycopg2.Error as e:
    print "cannot execute that query", e.pgerror
    sys.exit("leaving early the script")

As you can see here I have the possibility to make an if statement for each row retrieved from mysql, to e.g. put the value of a field inside another field (or casting field datatype and so on...). Which is something that I really need to do in my scenario (elaboration of db row).

Meanwhile, I have found out that performing many insert statement as above (each mysql row is inserted separately) is killing the performance.

So I'm thinking to switch to something like that, which prepares all the blocks of statements, and then insert it all in one block:

cur_msql.execute("SELECT customer_id, customer_name, contact_name, address, city, postal_code, country FROM mysqlcustomers")

args_str = ','.join(cur_psql.mogrify("(%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)", x) for x in cur_msql)

try:
  cur_psql.execute("INSERT INTO psqlcustomers (customer_id, customer_name, contact_name, address, city, postal_code, country) \
                    VALUES " + args_str)
except psycopg2.Error as e:
  print "cannot execute that query", e.pgerror
  sys.exit("leaving early the script")

With this approach the script can be about 100x faster! But the problem with this is, that I can no more elaborate the data (transformation/conversion/casting...) because all the rows get inserted into an object and I'm not able to iterate through it anymore...

Is it possible to approach the problem in a way where I can:

Not kill the performance
Still elaborate/transform the data of each row?


texts: Selecting all posts created by user that actual user follows

texts:
I have a view that displays posts created by users that actual logged in user follows. It works, by I think the way I've done it isn't good.

BTW, UserProfile is my default user model.

UserFollower model

class UserFollower(models.Model):
    followed = models.OneToOneField(UserProfile, related_name="followed")
    followers = models.ManyToManyField(UserProfile, related_name="followers", blank=True)

Post model

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL)
    body = models.CharField(max_length=140)

My page view

class MyPage(ListView):
    model = Post

    def get_queryset(self):
        posts = []
        for user in self.request.user.followers.all():
            for post in Post.objects.filter(author=user.followed):
                posts.append(post)

        return posts


texts:
I have been given a change to rewrite an old framework we use, and to implement the repository and unit of work patterns, but in an attempt to not rewriting all queries I have ended up with a weird combination of Linq queries and Linq lambdas.

I was hoping someone could explain to me a better way of doing this, or advice what to do.

First off, the generic repository has a method Get() defined as

public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")

and the old code would use a context directly like this:

Arrival arrival =
    (from a in DataContextPortX.Arrival
         where a.I_ARRIVALNO == arrivalNo
     select a).SingleOrDefault();

And now, since the class no longer has direct access to the context I can choose to keep the old code with the Get() method mixed in like this:

Arrival arrival =
    (from a in Get()
        where a.I_ARRIVALNO == arrivalNo
        select a).SingleOrDefault();

or I can rewrite the whole query to lambda like this:

var arrival = Get(a => a.I_ARRIVALNO == arrivalNo).SingleOrDefault();

I would of course prefer to rewrite all queries but there are a lot of them, and this was the shortest I could find, others are like really long.

But I am worried about first using Get() and then iterating of that, but for all I know it doesn't matter.


texts:
I wanted to implement a bubble sort in Scala following the steps described in: http://www.bbc.co.uk/education/guides/z22wwmn/revision/3

import scala.collection.mutable.MutableList

val result = bubbleSort(List(3,2,4,1,5))

def bubbleSort(list: List[Int]): (List[Int]) = {
  def doIteration(list: List[Int]): (List[Int], Boolean) = {
    val mutableList = MutableList(list: _*)
    val numberOfPairs = 0 until mutableList.length - 1
    for (pair <- numberOfPairs) {
      if (list(pair) > list(pair + 1)) {
        val tempOld = list(pair + 1)
        mutableList(pair + 1) = list(pair)
        mutableList(pair) = tempOld
      }
    }
    val hasSwaps = list != mutableList.toList
    (mutableList.toList, hasSwaps)
  }

  var result = doIteration(list)
  while(result._2){
    result = doIteration(result._1)
  }
  result._1
}

I am aware I have used a few things which are not idiomatic in Scala such as:

MutableList
while loop
var

I would appreciate suggestions for incremental improvements to make the code more functional and idiomatic Scala.


texts:
I have written a script that:

connects to an IIS server
stops a website
copies its files to a backup folder (on the remote machine)
copies files from my local machine to replace the ones on the remote IIS server
then relaunches IIS.

The script works, but I would love to make it cleaner (I pieced this together). Any suggestions?

@echo off

C:\Users\me\Documents\PSTools\PsExec \\10.45.12.12 -u "mydomain\myuser" -p "mypwd" %windir%\system32\inetsrv\appcmd stop sites "test.mysite.com"

sleep 5

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"

NET USE \\10.45.12.12 /u:mydomain\myuser "mypwd"

rem moves files and directories then del source
robocopy /e /move \\10.45.12.12\C$\inetpub\wwwroot\test.mysite.com \\10.45.12.12\C$\Users\me\Desktop\OLD_web_builds\test.mysite\%fullstamp%

rem copy vs published files to remote server. exclude the UL_LK folder
robocopy C:\Users\me\Desktop\_REPOS\invwebops\InvWebOps\bin\Release\netcoreapp2.2\publish \\10.45.12.12\C$\inetpub\wwwroot\test.mysite.com /e /XD "C:\Users\me\Desktop\_REPOS\invwebops\InvWebOps\bin\Release\netcoreapp2.2\publish\wwwroot\UL_LK"

rem restart test.mysite
C:\Users\me\Documents\PSTools\PsExec \\10.45.12.12 -u "mydomain\myuser" -p "mypwd" %windir%\system32\inetsrv\appcmd start sites "test.mysite.com"

set /p DUMMY=Hit ENTER to continue...


texts: Redraw text on change, with automatic zooming, using fabric.js

texts:
My code works, but I think that my code is non-standard, not optimized, and has poor logic.  I want to improve my coding skills, so please suggest how to improve my code.

var canvas = new fabric.Canvas('editor');
// Fabricjs
var textbox = new fabric.Text('Your Text', {
  left: 100,
  top: 0,
  width: 800,
  textAlign: 'center',
  fontFamily: "Impact",
  fontSize: 76,
  radius: 230,
  rotate: 0,
  selectable: false,
  hasControls: false,
  effect: "STRAIGHT",
  charSpacing: 10,
  spacing: 40
});
canvas.add(textbox).renderAll();
canvas.setActiveObject(canvas.item(canvas.getObjects().length - 1));

// Apply selected Text on change
jQuery("#Eletter").keyup(function() {
  $Eletter = jQuery("#Eletter").val();
  var obj = canvas.getActiveObject();
  //alert(isFloat(obj.getWidth()));
  if (obj) {
    // $priceHight = calcu();
    var widc = obj.getWidth().toFixed(0);
    //console.log(parseInt(widc));
    var letterins = jQuery("#Eletter").val();
    var letterLenghts = letterins.length;
    var LetteringL = jQuery("#LetteringL").val();
    if (letterLenghts > LetteringL) {
      if (widc >= 400.00 && widc <= 430.00) {
        // alert("am working");
        canvas.setZoom(canvas.getZoom() / 1.1);
      } else if (widc >= 600 && widc <= 630.00) {
        canvas.setZoom(canvas.getZoom() / 1.1);
      } else if (widc >= 800 && widc <= 830.00) {
        canvas.setZoom(canvas.getZoom() / 1.2);
      } else if (widc >= 1000 && widc <= 1030.00) {
        canvas.setZoom(canvas.getZoom() / 1.2);
      } else if (widc >= 1200 && widc <= 1230.00) {
        canvas.setZoom(canvas.getZoom() / 1.2);
      } else if (widc >= 1400 && widc <= 1430.00) {
        canvas.setZoom(canvas.getZoom() / 1.1);
      } else if (widc >= 1600 && widc <= 1630.00) {
        canvas.setZoom(canvas.getZoom() / 1.1);
      } else if (widc >= 1800 && widc <= 1830.00) {
        canvas.setZoom(canvas.getZoom() / 1.1);
      } else if (widc >= 1200 && widc <= 1230.00) {
        canvas.setZoom(canvas.getZoom() / 2.1);
      }
    } else {

      if (widc >= 400.00 && widc <= 430.00) {
        //alert("am working");
        canvas.setZoom(canvas.getZoom() * 1.1);
      } else if (widc >= 600 && widc <= 630.00) {
        canvas.setZoom(canvas.getZoom() * 1.1);
      } else if (widc >= 800 && widc <= 830.00) {
        canvas.setZoom(canvas.getZoom() * 1.2);
      } else if (widc >= 1000 && widc <= 1030.00) {
        canvas.setZoom(canvas.getZoom() * 1.2);
      } else if (widc >= 1200 && widc <= 1230.00) {
        canvas.setZoom(canvas.getZoom() * 1.2);
      } else if (widc >= 1400 && widc <= 1430.00) {
        canvas.setZoom(canvas.getZoom() * 1.1);
      } else if (widc >= 1600 && widc <= 1630.00) {
        canvas.setZoom(canvas.getZoom() * 1.1);
      } else if (widc >= 1800 && widc <= 1830.00) {
        canvas.setZoom(canvas.getZoom() * 1.1);
      } else if (widc >= 1200 && widc <= 1230.00) {
        canvas.setZoom(canvas.getZoom() * 2.1);
      }
    }
  }
  //  canvas.setHeight(obj.getHeight() + 200);
  // obj.set("top", 0);
  canvas.getActiveObject().setText($Eletter);

  canvas.renderAll();
  jQuery("#LetteringL").val(letterLenghts);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<div class="wrapper-canvas">
  <canvas class="" id="editor" width="1000" height="auto"></canvas>
</div>

<input class="text-input" type="text" id="Eletter" value="Your Text">

<input id="LetteringL" type="hidden" value="">

This example is also available as a Fiddle.