texts: Get an array of currency exchange prices based on asset

texts:
Function getMarkets

Makes a call to get Cryptocurrency Exchange data based on asset (USD, USDC, USDT)

It calls the endpoint 3 times to return 3 arrays which are then returned to the callee.

I have an endpoint which hits gets exchange-markets/prices for any asset.

In my case I need to check all the paired cryptocurrency listings for USD, USDC and USDT.

At first I just tried calling getMarkets 3 times passing in the currency each time. I would then get an array of 3 responses from each call, however the last call would always replace the data for the 2 previous calls.

In order to fix that I had to use this ugly if statement indentation hell... which defeats the purpose of using async await. How should this be refactored to be cleaner, or is there a better way?

const nomicsAPI = 'https://api.nomics.com/v1/';
const nomicsKey = '8feb...;'

interface IParams {
  key: string;
  currency?: string;
}

interface IHeaders {
  baseURL: string,
  params: IParams
}

const headers: IHeaders = {
  baseURL: nomicsAPI,
  params: {
    key: nomicsKey
  }
};

const prepHeaders = (currency: string) => {
  headers.params.currency = currency;
  return axios.create(headers);
};

export const getMarkets = async (): Promise<any> => {
  try {
    let marketUSD;
    let marketUSDC;
    let marketUSDT;

    const nomicsUSD = prepHeaders('USD');
    marketUSD = await nomicsUSD.get('exchange-markets/prices');

    if (marketUSD) {
      const nomicsUSDC = prepHeaders('USDC');
      marketUSDC = await nomicsUSDC.get('exchange-markets/prices');

      if (marketUSDC) {
        const nomicsUSDT = prepHeaders('USDT');
        marketUSDT = await nomicsUSDT.get('exchange-markets/prices');

        return {
          marketUSD: marketUSD.data,
          marketUSDC: marketUSDC.data,
          marketUSDT: marketUSDT.data
        }
      }
    }
    else {
      throw new Error('USD Markets unavailable.');
    }
  } catch (err) {
    console.error(err);
  }
}

^ above produces the desired results:

And the actions file where this function is called from:

// Fetch USD, USDC & USDT markets to filter out Exchange List.
export const fetchMarketPrices = (asset: string) => (dispatch: any) =>
  getMarkets().then((res) => {
    console.log('res', res);

  // const combinedExchanges = res[0].data.concat(res[1].data).concat(res[2].data);
  // console.log('combinedExchanges', combinedExchanges);
  // const exchangesForAsset = combinedExchanges.filter((marketAsset: IMarketAsset) =>
  //   marketAsset.base === asset);
  // console.log('exchangesForAsset', exchangesForAsset);
  // return dispatch(actionGetMarketPrices(exchangesForAsset));
});


texts: Building nested object structures from CSV input

texts:
I'm reading big csv files and mashing the lines into hierarchical objects for analysis and display.  The csv might look like this:

YEAR,QUAD,SPEC,FIASP,COND,SZ2,SZ3,SZ4,SZ5,SZ6,SZ7,SZ8,SZ9
1984,4D1,1,129,1,1,0,1,1,0,1,3,0
1984,4D1,8,371,0,0,0,0,0,1,0,0,1
1984,4D1,9,375,1,0,0,0,0,0,0,1,0
1984,4D1,1,129,0,2,0,1,1,1,1,1,0
1984,4D1,3,012,0,0,1,0,3,1,0,0,0
...
2009,8I3,5,833,1,0,0,0,0,0,0,1,0
2009,8I3,7,316,1,0,0,0,0,0,0,0,1
2009,8I3,25,585,0,1,1,2,1,0,0,0,0
2009,8I3,7,316,0,0,0,0,0,1,1,0,1

My non-clever reading code works but I dislike it; it goes like this (could be typos from editing down):

function makePlotData() {
if(ground.reader.readyState==4) {
    var lines = ground.reader.responseText.split(/\r\n?/);
    for (var i=0; i<lines.length; i++) {
        if (lines[i].match(/^\d\d\d\d,/)) {     // then it's a regular csv line
            var fieldsArr = lines[i].split(',');
            var [year, quad, spec] = [fieldsArr[0],fieldsArr[1],fieldsArr[2]];
            ground[quad] = ground[quad] || {};
            ground[quad][year] = ground[quad][year] || {};
            ground[quad][year][spec] = ground[quad][year][spec] || {};
            ground[quad][year][spec].sum = ground[quad][year][spec].sum || 0;
            ground[quad][year][spec].sizes = ground[quad][year][spec].sizes || [];
            var sizeArr = fieldsArr.slice(5).map(Number);
            if (ground[quad][year][spec].sizes.length) {  // already have a size classes Arr
                for(var s=0;s<sizeArr.length;s++){  // ...so add to it
                    ground[quad][year][spec].sizes[s] += sizeArr[s];}
            } else {ground[quad][year][spec].sizes = sizeArr;}
        } // ... continue with assignments and doing stuff

My objection is to that series of statements like ground[quad] = ground[quad] || {}; , which do what I need but seem like a lot of unnecessary assigning and reassigning; I bet it doesn't matter but it gives me a feeling of wasted cycles and room for errors; it's also ungainly and a nuisance to modify.  Is there any idiom or anything that manages this more efficiently or is this as good as it gets with this kind of structure?


texts: Prime Number Generator (6n + 1 or 6n - 1)

texts:
This generator is like most where it brute forces an integer: it see whether the integer is divisible by any of the primes; if so, then it's not a prime and vice versa. This though only compares values 6n + 1 and 6n - 1 starting with n as 1 as all primes larger than 3 can be written as 6n + 1 or 6n - 1 where n is a positive integer.

Examples: 7 is 6(1) + 1 (n = 1) and 17 is 6(3) - 1 (n = 3).

Code:

primes = [2, 3]
limit = 0
n = 1
is_prime = True

while True:
    try:
        limit = int(raw_input("Enter a positive integer larger than 3: "))
    except ValueError:
        print "Please enter a positive integer larger than 3!"
    else:
        if limit <= 3:
            print "Please enter a positive integer larger than 3!"
        else:
            break

while True:
    minus_prime = 6*n - 1
    plus_prime = 6*n + 1

    if minus_prime < limit:
        for x in primes:
            if minus_prime % x == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(minus_prime)
        is_prime = True
    elif minus_prime > limit:
        print primes
        break

    if plus_prime < limit:
        for x in primes:
            if plus_prime % x == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(plus_prime)
        is_prime = True
    elif plus_prime > limit:
        print primes
        break

    n += 1

Basically, given preset primes 2 and 3, find all primes that are less than limit by producing numbers with 6*n + 1 and 6*n - 1 (n increases by one every loop) and checking first if they are over the limit. If so, stop the loop and print out the primes (as a list). If not, brute force through primes to see if the number is prime. If so, add to primes. Else, continue. limit is checked in the first while loop to ensure validity.

I am wondering how to improve the performance of my program, improve its structure, and make it more Pythonic. Try it here


texts: Which of my string indexing functions in Kotlin is semantically closer to my Java one?

texts:
I have a working string indexing method in Java and did convert in Kotlin.
All methods shown below produce the same result but as I am really new to the Kotlin language I wanted to ask which of my two Kotlin implementations is semantically "more equal" to my Java code.
Here is my Java code where "copiedList" is an ArrayList:
public static Map<String, Integer> count(List<String> copiedList) {

        Map<String, Integer> map = new HashMap<>();

        for (String string : copiedList) {
            String lowerString = string.toLowerCase();
            if (!map.containsKey(lowerString)) {
                map.put(lowerString, 1);
            } else {
                int integer = map.get(lowerString);
                map.put(lowerString, integer + 1);
            }
        }

        return map;
    }

My Kotlin implementation 1:
fun countWords(splittedArray: Array<String>): Map<String, Int> {
        return splittedArray.asSequence().filterNot { it.isBlank() }.map { it.toLowerCase() }. groupingBy { it }.eachCount()
}

or Kotlin implementation 2:
fun countWordsSeq(textSequence: Sequence<String>): Map<String, Int> {
        return textSequence.filterNot { it.isBlank() }.map { it.toLowerCase() }. groupingBy { it }.eachCount()
}


texts: Creating controls on a page which differ slightly depending on an external state

texts:
I've got a part of my application which deals with tracking the dates a particular item is worked on. It is a single aspnet page, which displays controls to either start or stop tracking, depending on the state of the work item.

There are up to three controls on the page. A calendar to enter the date that work was stopped/started. A dropdown to select a reason the work item was stopped. A text area to enter a comment.

Because a similar set of controls will be created on both possible work item states (either started or stopped), I've decided to create a single set of controls, and modify them depending on the state of the work item.

The markup I use for the controls is below:

    <asp:Calendar id="DatePickerControl" runat="server"></asp:Calendar>

    <asp:DropDownList id="DropdownControl" runat="server"></asp:DropDownList>

    <textarea id="TextReasonControl"></textarea>

And the code behind to initialise:

void Page_Load(Object sender, EventArgs e)
{
    if (this.WorkItemIsStopped())
    {
        this.SetupStartControls();
    }
    else
    {
        this.SetupStopControls();
    }
}

void SetupStartControls()
{
    this.DatePickerLabel.InnerText = "Start date";

    this.DropdownContainer.Visible = false;

    this.TextReasonLabel.InnerText = "Start comment";
}

void SetupStopControls()
{
    this.DatePickerLabel.InnerText = "Stop date";

    this.DropdownLabel.InnerText = "Stop Reason";
    this.DropdownControl.DataSource = this.CreateDropdownDataSource();

    this.TextReasonLabel.InnerText = "Stop comment";
}

Is this a reasonable approach? The alternative would be to create two similar but separate sets of controls in the markup, and simply hide the set which are not relevant to the current state of the work item.


texts:
I have the following functions that for the most part are utilizing much of the same code (except for the actual message). What are the possibilities, if there are any, for combining / reducing these functions so that there isn't so much redundancy?

    // ACCOUNT DISABLED FUNCTION

    function accountDisabled() {
        if (!$('.accountautologoff').length) {

            $('.content').append('
Your account has been disabled
Contact the system administrator
');

            $('body').addClass('disabled');
            $('html').removeClass('loading');
            $('.accountautologoff').hide().fadeTo(600, 1, 'swing');
            $(document).bind('mousewheel', function (e) { e.preventDefault(); });
            $('.content-home, .content-search').fadeTo(600, 0.5, 'swing');
        };
    };

    // ACCOUNT DELETED FUNCTION

    function accountDeleted() {
        if (!$('.accountautologoff').length) {

            $('.content').append('
Your account has been removed
Contact the system administrator
');

            $('body').addClass('disabled');
            $('html').removeClass('loading');
            $('.accountautologoff').hide().fadeTo(600, 1, 'swing');
            $(document).bind('mousewheel', function (e) { e.preventDefault(); });
            $('.content-home, .content-search').fadeTo(600, 0.5, 'swing');
    };
};


texts:
I found a way to use the JLS as a tree-structure (at least in let the parent-field disappear).

Please ignore the main-method.

It works, but from OOD would you say this is ok?

/*
 * Copyright (c) 2016, Peter Rader. All rights reserved.
 * http://www.gnu.org/licenses/gpl-3.0.html
 */
package blablabla;

import java.awt.BorderLayout;
import java.awt.Container;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.TreeNode;

/**
 * A abstract kind of a node who can contain other nodes.
 *
 *

 * The textual-representation is readonly.
 */
public abstract class Node implements TreeNode {

    /**
     * A non-root node.
     *
     *

     * Auto-inject the parent.
     */
    public class NodeImpl extends Node {
        public NodeImpl(String text) {
            super(text);
            Node.this.children.add(this);
        }

        @Override
        public final TreeNode getParent() {
            return Node.this;
        }
    }

    /**
     * Root-node who has no parent.
     */
    public static class Root extends Node {
        private static final TreeNode NULL_NODE = null;

        /**
         * Creates a new tree.
         *
         * @param text
         *            The root-name.
         */
        public Root(String text) {
            super(text);
        }

        /**
         * A root of a tree has no parent.
         */
        @Override
        public TreeNode getParent() {
            return NULL_NODE;
        }

    }

    public static void main(String[] args) {
        final JFrame jf = new JFrame("");
        jf.setBounds(200, 200, 400, 300);
        final Container cp = jf.getContentPane();
        cp.setLayout(new BorderLayout());
        final Root root = new Root("Root");
        root.new NodeImpl("Trunk").new NodeImpl("Branch").new NodeImpl("Leaf");
        final JTree tree = new JTree(root);
        cp.add(tree, BorderLayout.CENTER);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
    }

    /**
     * The textual representation of this node.
     *

     * If the node is a root-node and the {@link JTree#setRootVisible(boolean)}
     * is set to false, you will not see the textual representation of this
     * root-node.
     */
    protected final String text;

    /**
     * All relative children.
     *

     * Empty if this node {@link #isLeaf() is a leaf}.
     */
    private final LinkedHashSet<TreeNode> children = new LinkedHashSet<TreeNode>();

    /**
     * Creates this node.
     *
     * @param text
     *            The textual representation.
     */
    protected Node(String text) {
        this.text = text;
    }

    public Enumeration<TreeNode> children() {
        return new Vector<TreeNode>(children).elements();
    }

    public boolean getAllowsChildren() {
        return true;
    }

    public TreeNode getChildAt(int childIndex) {
        return (TreeNode) children.toArray()[childIndex];
    }

    public int getChildCount() {
        return children.size();
    }

    public int getIndex(TreeNode node) {
        return new Vector<TreeNode>(children).indexOf(node);
    }

    public abstract TreeNode getParent();

    public boolean isLeaf() {
        return children.isEmpty();
    }

    @Override
    public String toString() {
        return text;
    }
}


texts:
I'm curious about Object.defineProperty.  It seems awfully verbose for not doing much more than what you can already do in the constructor.  What's the point of it?  Would it be 'bad code' to not use it?  I know you have more control over read/write and enumerability with defineProperty, is that enough to use this verbose syntax?

function Person(age, name) {
  this.name = name;
  this.age  = age;
};

Object.defineProperty(Person.prototype, "age", {
  get: function() {
    return this._age;
  },

  // Added a few things to demonstrate additional logic on the setter
  set: function(num) {
    num = parseInt(num, 10);
    if(num > 0) {
      this._age = num;
    }
  }
});


texts:
I often create new accounts or virtual machines, and then have to load my SSH public key/signature in to the authorized keys on that account. That process can be tedious, so I created this script that pushes my authorization on the remote machine. So, typically when you ssh to a remote machine you have to enter your password, etc. To automate jobs, though, you often don't want to do that, and key-based authentication allows you to authenticate without the password.

There are other ways to push keys around, but this makes it simple to fix things after the fact, or to initialize new accounts, etc.

I am looking for a review of any and all aspects, including the way that SSH is set up, and so on.

Here's an example transcript of what the script outputs:

panabox:~/bin> loadkey sol@solarium
Installing Key...
sol@solarium's password:
Checking Key ...
Great!
panabox:~/bin> loadkey sol@solarium
Already Works!
panabox:~/bin>

And here is the script:

#!/bin/bash

if [ "$#" -ne 1 ]
then
  echo "Must supply user@hostname:   loadkey <user@hostname>"
  exit 1
fi

host=$1

ssh -2 -o BatchMode=yes $host "echo hi" >& /dev/null && echo Already Works! && exit 0

echo Installing Key...
install="mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat - >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
cat ~/.ssh/id_rsa.pub | ssh -2 $host $install

echo Checking Key ...
ssh -2 -o BatchMode=yes $host "echo hi" >& /dev/null && echo Great! && exit 0

echo Failed to install key.
exit 2


texts: Laravel Dependency Injection : Perfomace Issue And Architecture Style

texts:
I have a TransportationController which uses six repositories. The repositories are injected to the controller via constructor and method.

TransportationController.php

use Illuminate\Http\Request;
use App\Repositories\TransportationRepository;
use App\Repositories\TruckRepository;
use App\Repositories\AccountRepository;
use App\Repositories\SiteRepository;
use App\Repositories\EmployeeRepository;
use App\Repositories\EmployeeWageRepository;
use App\Http\Requests\TransportationRegistrationRequest;
use App\Http\Requests\TransportationFilterRequest;
use \Carbon\Carbon;

class TransportationController extends Controller
{
    protected $transportationRepo;
    public $errorHead = 5, $noOfRecordsPerPage = 15;

    public function __construct(TransportationRepository $transportationRepo)
    {
        $this->transportationRepo = $transportationRepo;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(TransportationFilterRequest $request, TruckRepository $truckRepo, AccountRepository $accountRepo, SiteRepository $siteRpepo, EmployeeRepository $employeeRepo)
    {
        //some filtering stuff

        $transportations = $this->transportationRepo->getTransportations($params, $noOfRecords);

        return view('transportations.list', [
                'accounts'          => $accountRepo->getAccounts(),
                'sites'             => $siteRpepo->getSites(),
                'trucks'            => $truckRepo->getTrucks(),
                'drivers'           => $employeeRepo->getEmployees(),
                'materials'         => $this->transportationRepo->getMaterials(),
                'transportations'   => $transportations,
                'rentTypes'         => $this->transportationRepo->rentTypes,
                'params'            => $params,
                'noOfRecords'       => $noOfRecords,
            ]);
    }
}

Is there any architecture faults in injecting many(about 5 or 6)
repositories to a controller?
Is there any performance issue related to injecting many(about 5 or 6)
repositories to a controller?
What are the difference in injecting repositories through constructor
vs injecting through method?
What about injecting repositories in another repositories


texts:
I created a morse converter from a .txt file.

I'm learning java and I created a simple morse converter. Convert only A to Z and 0 to 9 chars. Space char remain for split words in morse-code.
At the beginning I used a big switch for any letters or number but it was no good.

public static String toMorse(byte[] bytes) {
    String text = new String(bytes);
    String morseText = "";
    text = text.toLowerCase();
    String[] morseChar
            = {".-",
                "-...",
                "-.-.",
                "-..",
                ".",
                "..-.",
                "--.",
                "....",
                "..",
                ".---",
                "-.-",
                ".-..",
                "--",
                "-.",
                "---",
                ".--.",
                "--.-",
                ".-.",
                "...",
                "-",
                "..-",
                "...-",
                ".--",
                "-..-",
                "-.--",
                "--.."};
    String[] morseNumber
            = {".----",
                "..---",
                "...--",
                "....-",
                ".....",
                "-....",
                "--...",
                "---..",
                "----.",
                "-----"};

    for (int i = 0; i < text.length(); i++) {
        if (text.charAt(i) >= 'a' && text.charAt(i) <= 'z') {
            morseText = morseText + morseChar[text.charAt(i) - 'a'];
        } else if (text.charAt(i) >= '0' && text.charAt(i) <= '9') {
            morseText = morseText + morseNumber[text.charAt(i) - '0'];
        } else if (text.charAt(i) == ' ') {
            morseText = morseText + text.charAt(i);
        }
    }
    return morseText;
}


texts: Preorder traversal of binary tree to produce formatted string

texts:
Given a complete binary tree returns the following format (Parent ( leftchild (leftchild, rightchild), rightchild(leftchild,rightchild) ). Looking for code review, optimizations and best practices.

public final class PreOrderList {

    private TreeNode root;

    /**
     * Constructs a binary tree in order of elements in an array.
     * The input list is treated as  BFS representation of the list.
     * Note that it is the clients responsibility to not modify input list in objects lifetime.
     *
     */
    PreOrderList(List<String> items) {
        create (items);
    }

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

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

    private void create (List<String> items) {
        root = new TreeNode(null, items.get(0), null);

        final Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;  // http://stackoverflow.com/questions/21156774/unit-testing-complicated-methods-what-to-test-and-what-to-assume

                if (items.get(left) != null) {
                    current.left = new TreeNode(null, items.get(left), null);
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode(null, items.get(right), null);
                    queue.add(current.right);
                }
            }
        }
    }

    /**
     * Returns the string representation of the format
     * (Parent ( leftchild (leftchild, rightchild), rightchild(leftchild,rightchild) )
     * It needs a complete balanced tree, else invalid format is be returned.
     *
     * @return  the String representation.
     */
    public String getPreorderList() {
        if (root == null) {
            throw new NoSuchElementException("The element cannot be null.");
        }

        final StringBuilder sb = new StringBuilder();
        sb.append("(");
        sb.append(root.item);
        preOrder(root, sb);
        sb.append(")");

        return sb.toString();
    }

    private void preOrder(TreeNode node, StringBuilder sb) {
            if (node.left != null) {
                sb.append("(");
                sb = sb.append(node.left.item);
                preOrder(node.left, sb);
            }

            if (node.right != null) {
                sb.append(",");
                sb = sb.append(node.right.item + "");
                preOrder(node.right, sb);
                sb.append(")");
            }
    }

    public static void main(String[] args) {
        PreOrderList pol = new PreOrderList(new ArrayList<String>(Arrays.asList("1", "2", "3", "4", "5", "6", "7")));
        assertEquals("(1(2(4,5),3(6,7)))", pol.getPreorderList());
    }
}


texts: Could this ExecuteScalar call be written better?

texts:
I came across this code in our project today.  Where possible I'm trying to leave the code base in a better shape than I found it, as I go along, and this method jumped out at me for a number of reasons, mainly the sql string and the try/catch block.  I feel there's a less expensive way to do it.

Original Code:

public bool CheckSomething(string paramA, int paramB)
{
    using (var conn = new SqlConnection(Connection))
    {
        conn.Open();
        string sqlCommand = "SELECT ColumnA FROM OurTable WHERE ColumnB = '" + paramA +
                                "' AND ColumnC = " + paramB;

        using (var dbCommand = new SqlCommand(sqlCommand, conn))
        {
            int noOfRecords = -1;
            try
            {
                noOfRecords = (int)dbCommand.ExecuteScalar();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                dbCommand.Dispose();
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }

                return noOfRecords > 0;
            }
        }
    }
}

I was thinking of re-writing it as this, but I still think it could be improved further, one of which would be to create an procedure for the sql, but that's unlikely.  Was aiming to improve it purely from the code point of view.  I'd appreciate thoughts.

Rewritten version:

public bool CheckSomething(string paramA, int paramB)
{
    using (var conn = new SqlConnection(Connection))
    {
        conn.Open();
        string sqlCommand = string.Format("SELECT ColumnA FROM OurTable WHERE ColumnB = '{0}' and ColumnB = {1}", paramA, paramB);

        using (var dbCommand = new SqlCommand(sqlCommand, conn))
        {
            object noOfRecords = dbCommand.ExecuteScalar();
            dbCommand.Dispose();

            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }

            return noOfRecords != null;
        }
    }
}


texts: C++ how to use std::any_cast and avoid else if statements

texts:
I have created a Node class that I am using for various projects in my data structures class(at school) and I am overloading the insertion operator <<. I am using std::any for my container datatype inside Node class and am using std::any_cast to insert this data into a stream whenever possible. Std::any_cast requires that I know the datatype beforehand, and so I've come up with a hacky way to get this information by detangling the value typename into a string and then using a ton of else if statements to compare this string, as you can see in my code below... I'm looking for a different solution or even some advice about why this approach is fundamentally wrong and how to go about making better programming decisions. Lay it on me, I need help and can take it!

friend std::ostream& operator << (std::ostream& out, Node& n){

    std::string t;
    t = abi::__cxa_demangle(n.value.type().name(), 0, 0, 0);;

    if (t.find("string") != std::string::npos) { out << std::any_cast<std::string>(n.value); }
    else if (t == "unsigned long long int") { out << std::any_cast<unsigned long long int>(n.value); }
    else if (t == "unsigned long int") { out << std::any_cast<unsigned long int>(n.value); }
    else if (t == "long long int") { out << std::any_cast<long long int>(n.value); }
    else if (t == "long int") { out << std::any_cast<long int>(n.value); }
    else if (t == "unsigned short int") { out << std::any_cast<unsigned short int>(n.value); }
    else if (t == "short int"){ out << std::any_cast<short int>(n.value); }
    else if (t == "int") { out << std::any_cast<int>(n.value); }
    else if (t == "long double") { out << std::any_cast<long double>(n.value); }
    else if (t == "double") { out << std::any_cast<double>(n.value); }
    else if (t == "float") { out << std::any_cast<float>(n.value); }
    else if (t == "bool") { out << std::any_cast<bool>(n.value); }
    else if (t == "unsigned char") { out << std::any_cast<unsigned char>(n.value); }
    else if (t == "signed char") { out << std::any_cast<signed char>(n.value); }
    else if (t == "char") { out << std::any_cast<char>(n.value); }
    else { out << t; };

    return out;
};


texts:
I'm new at scripting, but I thought it would be handy to have a script that would change the extensions of selected files in Finder.  I run this script from an automator service so that batch changing extensions in Finder is always just a right click away.

So far, it has worked as I expect, but since this is one of my first scripts, my question is: is there a cleaner way to obtain this functionality?  Can anyone point out a case I haven't thought of in which this would fail?

What this script does:

Asks the user for a new extension.
Adds the new extension to any files that don't already have one.
Changes the extension in other files even if it's a hidden file or has multiple points.

A test case that does not function correctly:

The selected file's name has multiple points, but no extension. Here, my script replaces the text after the last point with the new extension.

Here's the code:

# Ask user for new extension to be used
set newExt to the text returned of (display dialog "Enter extension:" default answer "Do not include first point")

tell application "Finder"

    # Make a list of the selected files in Finder
    set selFiles to selection as list

    set TID to AppleScript's text item delimiters

    repeat with eachFile in selFiles

        # Make a text item list of the file name delimited by points
        set filePath to eachFile as text
        set AppleScript's text item delimiters to {":"}
        set fileName to last text item of filePath
        set AppleScript's text item delimiters to {"."}
        set textItems to text items of fileName

        # Handle case where there is currently no extension, but one should be added.
        if number of textItems is 1 then
            set name of eachFile to fileName & "." & newExt

        # If an extension does already exist...
        else

            set newName to ""
            set numItems to number of items in textItems
            set n to 1

            repeat numItems times

                # If the current text item is not the extension, add it & "." to the new file name.  No need here to consider the last text item since it's the old extension and we want to get rid of it.
                if n is not numItems then
                    set newName to newName & item n in textItems & "."
                    set n to n + 1
                end if

            end repeat

            set name of eachFile to newName & newExt

        end if

    end repeat

    # Is this line necessary?  I just saw it at the end of someone else's script that had earlier set TID to AppleScript's text item delimiters.
    set AppleScript's text item delimiters to TID

end tell

Feel free to use this if it would be useful for you.


texts: Queue for distributing tasks between threads

texts:
I implemented the following class to dispatch std::function<void(void)> objects to a thread pool. Multiple threads will block on the pop call until a task is available.

I am using the C++14 standard.

#pragma once

#include<memory>
#include<queue>
#include<mutex>
#include<condition_variable>

namespace alpha {

    template<typename T>
    class AsyncQueue {
        private:
            std::shared_ptr<std::queue<T>> queue;
            std::shared_ptr<std::mutex> mutex;
            std::shared_ptr<std::condition_variable> cond;

        public:
            /* Big 5 */
            AsyncQueue(const AsyncQueue& other) = default;
            AsyncQueue(AsyncQueue&& other) = default;
            AsyncQueue& operator=(const AsyncQueue& other) = default;
            AsyncQueue& operator=(AsyncQueue&& other) = default;
            virtual ~AsyncQueue() = default;

            /**
             * @brief Default constructor
             */
            AsyncQueue() :
                queue(new std::queue<T>()),
                mutex(new std::mutex),
                cond(new std::condition_variable()) {
            }

            /**
             * @brief Push a value to the async queue
             */
            void push(const T& object) {
                {
                    std::lock_guard<std::mutex> lock(*mutex);
                    queue->push(object);
                }
                cond->notify_one();
            }

            /**
             * @brief Push a value to the async queue (move variant)
             */
            void push(T&& object) {
                {
                    std::lock_guard<std::mutex> lock(*mutex);
                    queue->push(object);
                }
                cond->notify_one();
            }

            /**
             * @brief Pop a value from the queue
             */
            T&& pop() {
                std::unique_lock<std::mutex> lock(*mutex);
                while(queue->empty()) {
                    cond->wait(lock);
                }
                T object = std::move(queue->front());
                queue->pop();
                return std::move(object);
            }
    };
}

Specific questions:

Is there a way to keep both implementations of push DRY? The only difference is the type of the argument.
Is this safe? I tested it multiple times with true; while [[ $? == 0 ]]; do ./test; done, but i'd feel a lot better if someone told me that my idea of thread-safety is correct.
pop returns a rvalue-reference, which seems to cause problems when passing it directly to a function with the argument type const T&. Assigning it to a local variable first solves that, but is there a way to make push return a rvalue-reference only when it is needed? I am asking because i know C++ compilers implicitly move a lot.

EDIT:
The version that has the suggestions included can be found here. I applied the BSD 3-clause license to it.


texts:
I want to check if a variable is nan with Python.

I have a working method value != value gives True if value is an nan. However, it is ugly and not so readable. Plus, sonarcloud considers it as a bug for the reason "identical expressions should not be used on both sides of a binary operator".

Do you have a better/elegant solution? Thanks.

import math
import numpy as np

v1 = float('nan')
v2 = math.nan
v3 = np.nan

def check_nan(value) -> bool:
    is_nan =  value != value
    return is_nan

v1_is_nan = check_nan(value=v1)
v2_is_nan = check_nan(value=v2)
v3_is_nan = check_nan(value=v3)

print(v1_is_nan)  # printed True
print(v2_is_nan)  # printed True
print(v3_is_nan)  # printed True


texts: Random C++ STL-only password generator for education

texts:
This is some code I wrote five years ago and I'm now using it partially as instructional material. I think there are some things that are 'off' about it, namely the top of the main function being the definition of a few variables instead of the argument parsing, and the actual generation not being split into its own function.

#include <chrono>
#include <functional>
#include <iostream>
#include <random>
#include <string>

static void show_usage(std::string name)
{
    std::cerr << "Usage: " << name << " <option(s)>\n"
              << "Options:\n"
              << "\t-h,--help\t\tShow this help message\n"
              << "\t-l,--length LENGTH\tSpecify the password length\n"
              << "\t-s,--seed SEED\t\tUse a unique seed for the random engine\n"
              << "\t-v,--version\t\tOutput the program version\n";
}

int main (int argc, char *argv[])
{
    std::string charset ("abcdefghijklmnopqrstuvwxyz"
                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                         "1234567890!@#$%^&*()");
    int length = 16;
    std::default_random_engine generator;
    std::uniform_int_distribution<int> distribution (0, (int) charset.size() - 1);
    generator.seed (std::chrono::system_clock::now().time_since_epoch().count());

    if (argc >= 2) {
        for (int i = 1; i < argc; i++) {
            std::string arg = argv[i];
            if ((arg ==  "-l") || (arg == "--length")) {
                if (i + 1 < argc) {
                    length = atoi(argv[++i]);
                } else {
                    std::cerr << "-l,--length takes one argument" << std::endl;
                    return 1;
                }
            } else if ((arg == "-s") || (arg == "--seed")) {
                if (i + 1 < argc) {
                    std::string str (argv[++i]);
                    std::seed_seq seed (str.begin(), str.end());
                    generator.seed (seed);
                } else {
                    std::cerr << "-s,--seed takes one argument" << std::endl;
                    return 1;
                }
            } else if ((arg == "-h") || (arg == "--help")) {
                show_usage(argv[0]);
                return 0;
            } else if ((arg == "-v") || (arg == "--version")) {
                std::cout << "Version 0.0.1" << std::endl;
                return 0;
            }
        }
    }

    auto randchar = std::bind (distribution, generator);
    std::string password;
    password.resize(length);

    for (int i = 0; i < length; i++) {
        password.at(i) = charset.at(randchar());
    }

    std::cout << password << std::endl;
    return 0;
}


texts:
I am using this code to display all the permutations of a given input string. Any advice/solution will be very helpful.

#include<iostream>
using namespace std;

/* Function to swap two characters */
void swap(char& a, char& b)
{
 char temp;
temp = a;
a = b;
b = temp;
}
/* Function to obtain permutations of string characters */
void permutation(string s,int i,int n)
{
int j;
if (i == n)
    cout << s << "\t";
else
  {
    for (j = i; j < s.length(); j++)
    {
        swap(s[i],s[j]);
        permutation(s, i + 1, n);
        swap(s[i],s[j]);
    }
  }
}
int main()
{
 string s;
 cout << "Enter the amino acid string : ";
 cin >> s;
 cout << endl << "The permutations of the given string : " << endl;
 permutation(s, 0, s.length() - 1);
 cout << endl;
}


texts:
This is not, strictly speaking, code review, but I think my question can be asked here.

This is a request to find out what seems to be the cleanest. This project is a blog engine that uses the file system.  There are still many things to do to improve the code (it's not great).  I have such a class article at initialization that will parse actual items and store it in a structure and CHI a cache system.  In CHI, I store a table of hash:

 push(
     @articles,
     {
         title   => $title,
         tags    => \@tags,
         date    => $dt,
         content => $content,
         link    => $url
     }
 );

I wonder if it would not be better to make a class item and store it in my cache as an object list:

 package MahewinBlogEngine::Article;

 use Moo;

 use Type::Params qw( compile );
 use Type::Utils;
 use Types::Standard qw( Object Str Int ArrayRef );

 has title => (
     is       => 'rw',
     isa      => Str,
     required => 1,
 );

 has tags  => (
     is       => 'rw',
     isa      => ArrayRef,
     required => 1,
 );

 has date  => (
     is       => 'rw',
     isa      => Object,
     required => 1,
 );

 has content => (
     is       => 'ro',
     isa      => Str,
     required => 1,
 );

 has link => (
    is       => 'ro',
    isa      => Str,
    required => 1,
 );

 1;

And:

 my $article =  MahewinBlogEngine::Article->new(
     title   => $title,
     tags    => \@tags,
     date    => $dt,
     content => $content,
     link    => $url
);

push(@articles, $article);

This makes objects more maneuverable, powerful and extensible.  It also allows you to add methods such as formatting or other things.  But at the moment, I see no specific methods.  It will simply be a class with attributes and accessors. So, I wonder what is best in terms of quality, performance and memory.

Another question: I think CHI already compresses, but do you think it would be wise to use Sereal and compress before storing in the CHI system cache?


texts:
I was hoping to get a quick review of a script I wrote for retrieving AWS VPC Subnet information.  Any and all ideas welcome. I am looking specifically for logic enhancements, and optimizations to make the code more pythonic. Also, I was initially constructing a dictionary, however I had to adjust since many of the aws values have "-" hyphens. :-(

One note - I am using two spaces vs. four due to internal standards.

#!/usr/bin/env python
# encoding: utf-8

import argparse
import logging
import string
import sys

from boto import vpc, exception

from lib.aws_location import LocationData
from lib.aws_util import check_config

def get_subnets(connection, vpc_id):
  """Function that returns all subnets within a given AWS VPC.
  :connection: AWS Connection.
  :vpc_id: VPC Identifier.

  """
  return connection.get_all_subnets(filters={'vpc_id': vpc_id})

def format_data(region, vpc_id, vpc_subnet, subnets):
  """Function that outputs region data based on template.

  :region: EC2 Region.
  :vpc_id: VPC Identifier.
  :vpc_subnet: Subnet allocated to VPC.
  :subnets: Subnets defined within VPC.

  todo:: Serialization. (yaml/json)
  """
  with open('vpc_subnets.tmpl') as f:
    templ = string.Template(f.read())

  region_dict = {}
  region_dict['region'] = region
  region_dict['vpc_id'] = vpc_id
  region_dict['vpc_subnet'] = vpc_subnet
  region_dict['subnets'] = ', '.join(subnets)

  print templ.safe_substitute(region_dict)

def parse_args():
  parser = argparse.ArgumentParser(
      description='Script for obtaining VPC Subnet information.')

  group = parser.add_mutually_exclusive_group()

  group.add_argument("-d", "--debug",
      help="Enable debug messages",
      action="store_true")

  group.add_argument("-v", "--verbose",
      help="Enable verbose messages",
      action="store_true")

  args = parser.parse_args()

  if args.debug:
    logging.basicConfig(level=logging.DEBUG)
  elif args.verbose:
    logging.basicConfig(level=logging.INFO)
  else:
    logging.basicConfig(level=logging.CRITICAL)

def main():
  parse_args()

  try:
    check_config()
  except EnvironmentError as e:
    print("Error: Could not open config file: {}".format(e))
    sys.exit(1)

  loc = LocationData()

  for region in loc.get_regions():
    try:
      connection = vpc.connect_to_region(region)
      for vpc_raw in loc.get_vpcs_raw(connection):
        vpc_id = str(vpc_raw).split(':')[1]
        subnets = []
        for subnet_id in get_subnets(connection, vpc_id):
          subnets.append(subnet_id.cidr_block)
      format_data(region, vpc_id, vpc_raw.cidr_block, subnets)
    except exception.EC2ResponseError as e:
      logging.error("EC2Error: {}".format(e))
      continue

if __name__ == '__main__':
  main()


texts: Calculator with four arithmetic operations

texts:
#include <iostream>

using namespace std;

class Math
{
private:
    int answer;
public:
    /*void getAn()
    {
        cout << answer;
    }*/
    int add(int x, int y)
{
    cout << "Add two numbers:\n";
    cin >> x;
    cin >> y;
    answer = x + y;
    return answer;
}
    int sub(int x, int y)
{
    cout << "Subtract one number from the other:\n";
    cin >> x;
    cin >> y;
    answer = x - y;
    return answer;
}
    int multi(int x, int y)
{
    cout << "Multiply two numbers:\n";
    cin >> x;
    cin >> y;
    answer = x * y;
    return answer;
}
    int divi(int x, int y)
{
    cout << "Divide two numbers:\n";
    cin >> x;
    cin >> y;
    answer = x / y;
    return answer;
}
};

int main()
{
    int choice;
    int x,y;
    int learning = 1;
    Math doMath;
    cout << "This is a calculator!\n" << endl;
    while(learning==1)
    {
        //doMath.getAn();
        cout << endl;
        cout << "Menu:\n1) Addition\n2) Subtraction\n3) Multiplication\n4) Division\n5) Quit\n" << endl;
        cout << "Choose your option.\n";
        cin >> choice;
        if(choice==1)
        {
            cout << doMath.add(x,y) << endl;
        }else if(choice==2)
        {
            cout << doMath.sub(x,y) << endl;
        }else if(choice==3)
        {
            cout << doMath.multi(x,y) << endl;
        }else if(choice==4)
        {
            cout << doMath.divi(x,y) << endl;
        }else if(choice==5)
        {
            learning = 0;
        }else
        {
            cout << "THAT WASN'T A CHOICE, YOU LITTLE SHIT!!!" << endl;
            learning = 0;
        }
    }
    return 0;
}


texts:
I wrote the following that tries to crack a message that was encrypted via a simple Caesar cipher through brute force. I'm fairly new to Haskell, so any and all input is appreciated.
Because there are infinite ways that something could have been encrypted, it assumes very simple "offset" encryption; like what decShift uses. It also doesn't assume any "wrapping" if an offset character goes out of range.

It works fine (from my testing), I'd just like any input on how it could be made more readable, idiomatic, or generally better.

Use:

simpDec "Encrypted Message", which returns a list of tuples where the first element is the key used to obtain the decryption, and the second is the decrypted message (it returns a list because it's possible for it to return more then one possible decryption).

decUpper = 127 --Upperbound of normal characters
decLower = 32 --Lowerbound of normal characters
decRange = decUpper - decLower --Total range

type Message = String

--Checks if the char is in range
isInRange :: Char -> Bool
isInRange char = ichar <= decUpper && ichar >= decLower
    where ichar = ord char

--Makes sure all chars in the Message are in range
isPossible :: Message -> Bool
isPossible [] = False
isPossible m = null [letter | letter <- m, not $ isInRange letter]

--Returns a list > 0 if it finds consecutive symbols
conSymList :: Message -> Char -> [Char]
conSymList [] _ = []
conSymList (x:xs) lastChar
    | isSym x && isSym lastChar = x : conSymList xs x
    | otherwise = conSymList xs x
    where isSym c = isSymbol c || isPunctuation c

--Checks if a string has 2 symbols beside each other (meaning its improbable)
isProbable :: Message -> Bool
isProbable [] = False
isProbable m = null $ conSymList m 'a'

--Shifts all characters by n
decShift :: Message -> Int -> Message
decShift [] _ = []
decShift (x:xs) n
    | iNewChar > 0 = chr iNewChar : decShift xs n
    | otherwise = x : decShift xs n
    where iNewChar = ord x + n

--Returns a list of tuples of the offset used, and the shifted Message
getCombos :: Message -> [(Int,Message)]
getCombos m = [(off,decShift m off) | off <- [decRange * (-1)..decRange]]

--Returns a list of tuples of possible decryptions (KeyUsed,Message)
simpDec :: Message -> [(Int, Message)]
simpDec m = [(key,try) | (key,try) <- getCombos m, isPossible try && isProbable try]


texts: Compare two files and save the result into a pickle file

texts:
My code should compare two vectors saved as dictionary (two pickle files) and save the result into a pickle file too. This works but very slowly. For one compare result I'm waiting about 7:20 min. Because I have a lot of videos (exactly 2033) this prog will run about 10 days. This is too long. How can I speed up my code for Python 2.7?

import math
import csv
import pickle
from itertools import izip

global_ddc_file = 'E:/global_ddc.p'
io = 'E:/AV-Datensatz'
v_source = ''

def dot_product(v1, v2):
    return sum(map(lambda x: x[0] * x[1], izip(v1, v2))) # izip('ABCD', 'xy') --> Ax By

def cosine_measure(v1, v2):
    prod = dot_product(v1, v2)
    len1 = math.sqrt(dot_product(v1, v1))
    len2 = math.sqrt(dot_product(v2, v2))
    if (len1 * len2) <> 0:
        out = prod / (len1 * len2)
    else: out = 0
    return out

def findSource(v):
    v_id = "/"+v[0].lstrip("<http://av.tib.eu/resource/video").rstrip(">")
    v_source = io + v_id
    v_file = v_source + '/vector.p'
    source = [v_id, v_source, v_file]
    return source

def getVector(v, vectorCol):
    with open (v, 'rb') as f:
        try:
            vector_v = pickle.load(f)
        except: print 'file couldnt be loaded'
        tf_idf = []
        tf_idf = [vec[1][vectorCol] for vec in vector_v]
    return tf_idf

def compareVectors(v1, v2, vectorCol):
    v1_source = findSource(v1)
    v2_source = findSource(v2)
    V1 = getVector(v1_source[2], vectorCol)
    V2 = getVector(v2_source[2], vectorCol)
    sim = [v1_source[0], v2_source[0], cosine_measure(V1, V2)]
    return sim

#with open('videos_av_portal_cc_3.0_nur2bspStanford.csv', 'rb') as dataIn:
with open('videos_av_portal_cc_3.0_vollstaendig.csv', 'rb') as dataIn:
#with open('videos_av_portal_cc_3.0.csv', 'rb') as dataIn:
    try:
        reader = csv.reader(dataIn)

        v_source = []
        for row in reader:
            v_source.append(findSource(row))
        #print v_source

        for one in v_source:
            print one[1]
            compVec = []
            for another in v_source:
                if one <> another:
                    compVec.append(compareVectors(one, another, 3))
            compVec_sort = sorted(compVec, key=lambda cosim: cosim[2], reverse = True)

            # save vector file for each video
            with open (one[1] + '/compare.p','wb') as f:
                pickle.dump(compVec_sort,f)

    finally:
        dataIn.close()


texts: Console-like printing of message JavaScript

texts:
I'm learning JavaScript and I've made a very simple little document-modifying script that prints a message as if it was someone typing into a console. It practices recursion and in my opinion, I feel a bit iffy about the number of if-cases in the code. My main concern is the JavaScript though I know there's still a lot I have to learn about CSS animations.

var text = document.getElementById('text');
var greeting = ['Hello. I am a console wannabe.',
                'All systems are functioning.',
                'I like pie.'];
text.innerHTML = '▮';

(function greet() {
    if (greeting.length > 0 && greeting.length < 3) {
        text.insertBefore(document.createElement('br'), text.lastChild);
    }
    var line = greeting.shift();
    if (!line) {
        return;
    }
    line = line.split('');
    (function type() {
        var character = line.shift();
        if (!character) {
            return setTimeout(greet, 2000);
        }

        text.insertBefore(document.createTextNode(character), text.lastChild);
        setTimeout(type, 300);
    }());
}());
body{
    background-color: #000000;
    color: #99ffcc;
    font-family: Courier;
}

i{
    font-style: unset;
    font-size: 1em;
    animation: blink 1100ms linear infinite;
}

@keyframes blink {
    49% {
        opacity: 1;
    }
    50% {
        opacity: 0;
    }
    89% {
        opacity: 0;
    }
    90% {
        opacity: 1;
    }
}

I would like as many opinions as you can have about my simple little script. Does it look like I have a small grasp of JavaScript?


texts: Function to combine arrays of associative arrays

texts:
I recently create a function to combine some arrays of associative arrays in a single array in response to a stackoverflow question, where you can found more details about this.

The function works as expected, but I think their description is very obscure. In addition, i choose constant T_OBJECT_CAST as option to convert each rows as object: someone can suggest a better predefined constants?

Goal:

As requested from another user (edited):

  I've these two arrays:

  1) [0=>['title1'=>'Title 1'],  1=>['title2'=>'Title 2']];

  2) [0=>['contn1'=>'Content 1'],1=>['contn2'=>'Content 2']];

  How can I combine/merge them that they look like this?

  [

  0=>['title1'=>'Title 1','contn1'=>'Content 1'],

  1=>['title2'=>'Title 2','contn2'=>'Content 2']

  ]

Explanation:

(Globish here, i'm sorry)

To allow not predetermined arguments, I don't format function as multiArrayCombine( $arg1, $arg2, ... ), I use instead the func_get_args() function, that "allow user-defined functions to accept variable-length argument lists".

First of all, I check if the last argument is the predefined constant T_OBJECT_CAST: if it is, I set $asObject to True, then I pop-it off the end of arguments array; now in the $args variable I have an array with each passed arrays.

Next step: I retrieve the max key value of all passed arrays; i choose this way instead of more comfortable foreach( $array1 as $row ) to avoid to omit values if one of the other arrays have more rows than the first. Eventually not numeric keys are omitted.

Then, the main loop: I process each row of originals arrays and I add their keys and values to row that will added to returned array. If there are duplicated keys, only the last is returned.

After processing each array, i add the obtained row (converted to object if this option is passed) to returning array.

The function:

/*   Groups passed arrays in an array of associative arrays with same keys and values
 *
 *   @example          $array1 = array( array('a'=>'val1'),array('a'=>'val2') );
 *                     $array2 = array( array('b'=>'val3'),array('b'=>'val4') );
 *                     $array3 = array( array('c'=>'val5'),array(),array('c'=>'val6') );
 *                     multiArrayCombine( $array1, $array2, $array3 );
 *                     return: array
 *                     (
 *                        0 => array('a'=>'val1','b'=>'val3','c'=>'val5'),
 *                        1 => array('a'=>'val2','b'=>'val4'),
 *                        2 => array('c'=>'val6')
 *                     )
 *
 *   @param   array    $array1[, $array2[, $array3...]]
 *
 *   @option  const    T_OBJECT_CAST cast returned assoc arrays as stdObject
 *
 *   @return  array
 */
function multiArrayCombine()
{
    /* Get all passed parameters and T_OBJECT_CAST option: */
    $args     = func_get_args();
    $asObject = ( T_OBJECT_CAST == $args[count($args)-1] );
    if( $asObject ) array_pop( $args );

    $retval = array();          # Init array to be returned

    /* Retrieve highest passed arrays key: */
    $max = 0;
    foreach( $args as $array ) $max = max( $max, max( array_keys($array) ) );

    /* Loop for each arrays key: */
    for( $i=0; $i<=$max; $i++ )
    {
        /* Init associative array to add:  */
        $add = array();

        /* Process actual key ($i) of each passed array:  */
        foreach( $args as $array )
        {
            /* If the key ($i) exists, add  each passed array:  */
            if( is_array($array[$i]) )
            {
                foreach( $array[$i] as $key => $val )
                { $add[$key] = $val; }
            }
        }

        /* Add the obtained associative array to return array */
        if( $asObject ) $retval[] = (object) $add;
        else            $retval[] = $add;
    }

    return $retval;
}


texts:
ids contains 100 ids that are comma delimited.  Is it fine or does it need improvement?

 def getFriendPoints(ids: String) = {
    DB.withConnection { implicit c =>
      try {
        var pointMap:scala.collection.immutable.Map[String,String]=Map()
        var i=ids.split(",")
        for(pos<-0 to i.size){
        val result = SQL("SELECT  point,privacy FROM `tableName` WHERE id={user}").on("user" -> i(pos)).apply().head
        val point = if (result[Boolean]("privacy")) { result[Double]("point").toString } else { "0" }
        pointMap+=("id"+pos -> i(pos), "point" -> point)
        }
        pointMap
      } catch {
        case e: Exception =>
          Map("result" -> "error")
      }
    }
  }


texts:
I'm using this technique for highlighting current links (e.g. how the "Questions" link is highlighted on this very page you're looking at). I changed the code a little bit and came up with this extension method:

    public static MvcHtmlString MenuLink(
        this HtmlHelper helper,
        string content, string action, string controller)
    {
        var routeData = helper.ViewContext.RouteData.Values;
        var currentController = routeData["controller"];
        var currentAction = routeData["action"];

        var builder = new TagBuilder("li")
        {
            InnerHtml = content
        };
        if (String.Equals(action, currentAction as string,
                  StringComparison.OrdinalIgnoreCase)
            &&
           String.Equals(controller, currentController as string,
                   StringComparison.OrdinalIgnoreCase))
        {
            builder.AddCssClass("active");
            return MvcHtmlString.Create(builder.ToString());
        }
        return MvcHtmlString.Create(builder.ToString());
    }

It works fine, But that’s some ugly code. I use the extension method this way:

@Html.MenuLink("Ticket Page", "MainPage", "Ticket")

As you can see, part of that isn't strongly typed.

Do you have any ideas to improve the extension method?


texts:
I currently have a design that is used to store user/selected options in a database, but I am not sure what I am doing is good or not. I need some opinion, suggestion and criticise on the design.

Pre-Condition:

The option is not always going to change
A lot of options is going to be used

Database Design:

Let's say I have a column named "country" in my user table and I store this data as an integer instead of a string (the country name). Then I use mapping to map the value to the country name in the code when I want to use it.

The reason I am doing this is because I am thinking that storing the value as an integer and retrieving the value from the integer is faster compared to a string. Furthermore, it is more or less on storage consumption.

The above is just an example; I wouldn't do this if I only need to store the user's country. I'm actually got plenty of tables that are required to store the user's option. Some of the options contain long strings such as 20 - 50 chars.

Code Mapping Design:

I created 2 Enum class: one is the base class and the other is the particular option class and I will implement the base class that help me to do the mapping.

Base Class:

abstract class BaseEnum {

    private static $constCacheArray = NULL;

    private static function getConstants() {
        if (self::$constCacheArray == NULL) {
            self::$constCacheArray = array();
        }
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$constCacheArray)) {
            $reflect = new ReflectionClass($calledClass);
            self::$constCacheArray[$calledClass] = $reflect->getConstants();
        }
        return self::$constCacheArray[$calledClass];
    }

    public static function getAllOptions() {
        $options = array();
        foreach (self::getConstants() as $key => $value) {
            $options[substr($key, 1)] = $value;
        }
        return $options;
    }

    public static function getValue($key) {
        $key = '_' . $key;
        if(isset(self::getConstants()[$key])) {
            return self::getConstants()[$key];
        }
        return FALSE;
    }

    public static function isKeyExist($key) {
        $key = '_' . $key;
        if(isset(self::getConstants()[$key])) {
            return TRUE;
        }
        return FALSE;
    }

}

Country Class:

class Country extends BaseEnum {
    const _1 = 'Afghanistan';
    const _2 = 'Albania';
    const _3 = 'Bangladesh';
    const _4 = 'Brazil';
    const _5 = 'Denmark';
    const _6 = 'United Kingdom';
    ...

}

When the time I want to use to display the option into HTML, I do this:

<?php
    ...
    $options = Country::getAllOptions();
    foreach($options as $key => $value) {
        echo '<option value="'.$key.'">'.$value.'</option>'
    }
    ...
?>

When I want to display user-selected value, I do this:

 <?php
        ...
        $user = new User();
        $options = Country::getAllOptions();
        foreach($options as $key => $value) {
            if($user->getCountry() == $key) {
                echo '<option value="'.$key.'" selected="selected">'.$value.'</option>';
            } else {
                echo '<option value="'.$key.'">'.$value.'</option>';
            }

        }
        ...
    ?>

Is there any wrong with this design? Or is it better to maintain all these options in the DB? Or is there other any other better ways to do this?


texts:
I am writing a flask app that I will deploy it on Heroku to test it. There is a page that will generate daily photos and information based on a JSON file. The view is valid for 24 hours beginning from 00:00 to 23:59 of everyday.

I am thinking about using a cache, otherwise the app will consume unnecessary resources.

import ..

TODAY = date.today()

 app = Flask(__name__)
 app.jinja_env.auto_reload = False
 cache = Cache(config={'CACHE_TYPE': 'simple', 'CACHE_ARGS' : TODAY})
#This function reads a json file, filter the daily data to process and render a html template with photos and text .

# 3600 *  24 = 86400
@cache.cached(timeout=86400)
@app.route('/inf')
def inf():
    input_file = open(os.path.join(__location__, 'json/output.json'));
    j = json.loads(input_file.read().decode("utf-8-sig"))
    etc ..

    return render_template('inf.html',
                        title = title,
                        config={'environment_args':{'autoescape':False}},
                        zipped =zipped)

if __name__ == '__main__':
    if TODAY != cache.config['CACHE_ARGS'] :
        with app.app_context():
            cache.clear()
    port = int(os.environ.get('PORT', 33507))
    app.run(debug = True, host='0.0.0.0', port=port)

I am not sure if this is the best solution to cache the view for a day.  That's why I am asking here for more suggestions.


texts:
Purpose: Educational
Requirement: Given 64KB of memory, implement your own malloc and free
Method: First-Fit

struct Header
{
    unsigned short next; //in blocks of sizeof(Header)
    unsigned short size; //in blocks of sizeof(Header)
};

static Header* _dBuffer;
static Header* _dTail;

static public void dInit()
{
    _dBuffer = getMemBlock(64 * 1024);
    _dTail = _dBuffer;
}

static public void* dMalloc(unsigned short nbytes)
{
    if (_dTail == NULL) //empty free list
        return NULL;

    Header* prev = NULL;
    Header* current = _dTail;

    // below is equivalent to ceil((nbytes + sizeof(Header)) / sizeof(Header))
    int nblocks = (nbytes + sizeof(Header) - 1) / sizeof(Header) + 1;
    while (current->next != 0 && current->size < nblocks)
    {
        prev = current;
        current = _dBuffer + current->next;
    }

    if (current->size < nblocks)
        //we've reached the end of the free list without finding a chunk big enough
        return NULL;

    if (current->size == nblocks)
    {
        //we've found an exact match, remove the chunk from the free list
        if (prev == NULL) //remove the first chunk
            _dTail = NULL;
        else
            prev->next = current->next;
        return current + 1;
    }

    //current->size > nblocks
    current->size -= nblocks;
    current+= current->size;
    current->size = nblocks;
    return current + 1;
}

static bool coalesce(Header* block)
{
    Header* nextBlock = _dBuffer + block->next;
    if (block + block->size != nextBlock)
        return false;

    block->size += nextBlock->size;
    block->next = nextBlock->next;
    return true;
}

static public void dFree(void* p)
{
    Header* released = (Header*)p - 1;
    Header* before = NULL;
    Header* after = _dTail;

    if (_dTail == NULL) //the free list is empty
    {
        released->next = 0;
        _dTail = released;
        return;
    }

    //find where released is located in the free list
    while (after->next != 0 && after < released)
    {
        before = after;
        after = _dBuffer + after->next;
    }

    if (after < released) //released chunk after the end of the free list
    {
        released->next = 0;
        after->next = released - _dBuffer;
        coalesce(after);
        return;
    }

    if (before == NULL) //released chunk before the beginning of the free list
    {
        released->next = _dTail - _dBuffer;
        _dTail = released;
        coalesce(released);
        return;
    }

    //released chunk is somewhere in the middle of the list
    released->next = before->next;
    before->next = released - _dBuffer;
    if (coalesce(before)) //before was coalesced with released
        coalesce(before); //now try to coalesce it with after
    else
        coalesce(released); //otherwise, try coalescing released with after
}


texts: C++ Implementation of a dictionary data structure

texts:
I am quite new to C++ and would like some feedback on my implementation of a dictionary data structure. The code is below.

#ifndef DICTIONARY_H_INCLUDED
#define DICTIONARY_H_INCLUDED

#include <initializer_list>
#include <algorithm>
#include <vector>

template <typename T, typename U>
class Dictionary{
    private:
        std::vector<T> keys;
        std::vector<U> values;
    public:
        Dictionary();
        Dictionary(std::initializer_list<std::pair<T,U>>);
        bool has(T) const;
        void add(T,U);
        T* begin();
        T* end();
        U operator[](T);
};

template <typename T, typename U>
T* Dictionary<T,U>::begin(){
    return &(keys[0]);
}

template <typename T, typename U>
T* Dictionary<T,U>::end(){
    return &(keys[keys.size()-1])+1;
}

template <typename T, typename U>
Dictionary<T,U>::Dictionary (std::initializer_list<std::pair<T,U>> store){
    for (std::pair<T,U> object : store){
        keys.push_back(object.first);
        values.push_back(object.second);
    }
}

template <typename T, typename U>
bool Dictionary<T,U>::has(T targetKey) const{
    for (T currentKey : keys){
        if (currentKey == targetKey){
            return true;
        }
    }
    return false;
}

template <typename T, typename U>
void Dictionary<T,U>::add (T key, U value){
    keys.push_back(key);
    values.push_back(value);
}

template <typename T, typename U>
U Dictionary<T,U>::operator[] (T key){
    unsigned int pos = std::find(keys.begin(), keys.end(), key) - keys.begin();
    return values[pos];
}

#endif // DICTIONARY_H_INCLUDED


texts:
I want to use the WeakReference approach to not leak memory with my AsyncTask. I found examples online and on Stackoverflow, but they only get the reference in onPostExecute and I am unsure how to correctly use it in all 3 of the UI methods.
My current approach is like this, but I have no clue if I can get rid of some redundancy. Why can't I just call activityReference.get() in the constructor and then only check for null in each of the UI methods? Why do the examples online call get right before using the WeakReference?

private static class ExampleAsyncTask extends AsyncTask<Integer, Integer, String> {
    private WeakReference<MainActivity> activityReference;

    ExampleAsyncTask(MainActivity context) {
        activityReference = new WeakReference<>(context);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        MainActivity activity = activityReference.get();
        if (activity == null || activity.isFinishing()) {
            return;
        }

        activity.progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected String doInBackground(Integer... integers) {
        for (int i = 1; i < integers[0]; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            publishProgress((i * 100) / integers[0]);
        }

        return "Finished";
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

        MainActivity activity = activityReference.get();
        if (activity == null || activity.isFinishing()) {
            return;
        }

        activity.progressBar.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        MainActivity activity = activityReference.get();
        if (activity == null || activity.isFinishing()) {
            return;
        }

        activity.progressBar.setProgress(0);
        activity.progressBar.setVisibility(View.INVISIBLE);
        Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
    }
}


texts:
This is the "Queue Reconstruction by Height" problem from leetcode.com:

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.
Note: The number of people is less than 1100.

Suppose I take only the tallest persons, all having the same maximum height. Their second values must be 0, 1, 2, 3... with no gaps at all, because they only count each other. Therefore, if there were no other persons at all, their second value must be their final index. What about the persons with second maximum height then? Suppose there are only tallest persons and just one more person who has slightly smaller height. What would be his position? Well, since he obviously only count tallest persons, his position would still be his second value. The next person of the same height counts only the previous person and all the tallest ones, but since they are all already in the queue, his second value would also be his index.
import collections

class Solution(object):
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        d = collections.defaultdict(list)
        for height, count in people:
            d[height] += [count]

        recon_q = []
        for height, counts in sorted(d.items(), key = lambda x:x[0], reverse=True):
            for count in sorted(counts):
                recon_q.insert(count, [height, count])
        return recon_q

Is there any better data structure that can be used? I feel there must be a better way to do sorting here.
Note that the Solution class is required by LeetCode, even though it has no other function.


texts: (sort of) casting types in Ruby: changing class of an instance

texts:
I defined the class Rectangle:

class Rectangle
  attr_reader :b, :h
  def initialize(b, h)
    @b = b
    @h = h
  end
  def area
    @b*@h
  end
  def to_s
    "Rectangle #{@b}x{@h}"
  end
end

and its subclass Square:

class Square < Rectangle

  attr_reader :s
  def initialize(s)
    @s = s
    super(@s, @s)
  end
  def to_s
    "Square of side #{@s}"
  end
end

Now, let's say I defined a Rectangle object r = Rectangle.new(5, 5), but actually it should be a Square because I'd like r.to_s to return "Square of side 5".

I can define a to_square method in the Rectangle class that returns a Square object equivalent to r, but, is it possible to write a to_square! method that would actually change the r class to Square without returning another object, so that r.class would now return Square instead of Rectangle?

And, what if I'd like:

Square(r)

to return the Square equivalent object of r, just like:

Integer("3")

which returns the Integer 3?

Is that possible? And, if so, how?


texts: Verify if the element is readonly or disabled

texts:
I have written a function where it checks if the field is read-only or disabled. However, first it check if that element field is present

This is my working function, but i feel like this is too messy:

def verifyReadOnly(self):
        if self.driver.find_element_by_xpath("//input[@id='cname']"):
            self.driver.find_element_by_xpath("//input[@id='cname' and @readonly='readonly']")
        elif self.driver.find_element_by_xpath("//input[@id='address']"):
            self.driver.find_element_by_xpath("//input[@id='address' and @readonly='readonly']")
        elif self.driver.find_element_by_xpath("//input[@id='address2']"):
            self.driver.find_element_by_xpath("//input[@id='address2' and @readonly='readonly']")
        elif self.driver.find_element_by_xpath("//input[@id='city']"):
            self.driver.find_element_by_xpath("//input[@id='city' and @readonly='readonly']")
        # country
        elif self.driver.find_element_by_xpath("//input[@id='country']"):
            self.driver.find_element_by_xpath("//input[@id='country']/../select[@disabled='disabled']")
        elif self.driver.find_element_by_xpath("//input[@id='state']"):
            self.driver.find_element_by_xpath("//input[@id='state' and @readonly='readonly']")
        elif self.driver.find_element_by_xpath("//input[@id='zip']"):
            self.driver.find_element_by_xpath("//input[@id='zip' and @readonly='readonly']")
        # EIN Custom field
        elif self.driver.find_element_by_xpath("//input[@id='cf_2698238']"):
            self.driver.find_element_by_xpath("//input[@id='cf_2698238' and @readonly='']")


texts: Bookmarklet to go to YouTube channel RSS feed

texts:
I've written a simple bookmarklet to go to the YouTube channel RSS feed URL from at least any video or channel page:

javascript:(function () {
    var newLocation = function () {
        var url;
        Array.prototype.slice.call(document.getElementsByTagName('link')).forEach(function (element) {
            if (element.getAttribute('type') === 'application/rss+xml') {
                console.log('Found direct feed link');
                url = element.getAttribute('href');
            }
        });
        if (!url) {
            Array.prototype.slice.call(document.getElementsByTagName('meta')).forEach(function (element) {
                if (element.getAttribute('itemprop') === 'channelId') {
                    console.log('Found channel ID');
                    url = 'https://www.youtube.com/feeds/videos.xml?channel_id=' + element.getAttribute('content');
                }
            });
        }
        return url;
    }();
    if (newLocation === undefined) {
        console.log('Could not find a channel RSS feed from ' + location.href);
    } else {
        location.href = newLocation;
    }
})();

Some questions which come to mind:

Is this the simplest way to find an element with a specific attribute value?
Does this work with recent browsers other than Firefox?
Does it use any non-standard/deprecated features?
Are there any YouTube pages this does not work on, where it should?


texts: Leetcode 17 : Letter Combinations of a Phone Number

texts:
Problem Statement

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example 1:

Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:
Input: digits = ""
Output: []

Example 3:
Input: digits = "2"
Output: ["a","b","c"]

My Solution
A simple DFS based approach. Ignore some comments that are for my learning purposes (for similar problems to able to code it fast).
#include <array>
#include <string>
#include <vector>

class Solution {
private:
  // any auxilliary fields to help us (the "fluff" in the problem)

  std::array<std::string_view, 10> mappings = {
      "0",   "1",    "abc", "def", "ghi", "jkl",
      "mno", "pqrs", "tuv", "wxyz"}; // note that 0 and 1 have the digits since
                                     // that makes the most sense

  // private functions that (may) do the heavy lifting
  std::string_view getLettersMapping(char digit) {
    return mappings[digit - '0'];
  }

  void dfs(std::vector<std::string> &combinations, std::string_view digits,
           std::string &s, size_t curr_idx, const size_t &N) {
    //    base case
    if (curr_idx == N) {
      // last digit's combination has already been explored, so simply append it
      // to our set of combinations and return
      combinations.push_back(s);
      return;
    }

    // determine current mapping digit
    auto letters = getLettersMapping(digits[curr_idx]);

    // for that particular digit, generate all the possible combinations by
    // recursing for each possible digit in the next index.
    for (const auto &ch : letters) {
      // note that passing the string s by reference saves space,
      // but now we need to modify it by adding the letter and then removing the
      // latest added later after the  recursive call
      s.push_back(ch);
      dfs(combinations, digits, s, curr_idx + 1, N);
      s.pop_back();
    }
  }

public:
  std::vector<std::string> letterCombinations(std::string digits) {
    //   in the main function, we develop the answer, call the "magic"
    //   recursion/DFS function, and return the answer
    std::vector<std::string> ans;
    if (digits.empty() || digits.size() == 0) {
      return ans;
    }
    std::string s;
    dfs(ans, digits, s, 0, digits.size());
    return ans;
  }
};

Any suggestions for my code? Also, I'm still learning the more "modern" features of C++ (anything from C++17 onwards), so any such advice would be very welcome :)


texts: Spreadsheet to increment two levels of data indices

texts:
I'm posting this after reviewing the Meta Q&A, Non-code formula spreadsheet, and I believe I've got something here that meets the criteria there.

Edit: I've added documentation of the formulas below to make them easier to review.

Occasionally I find myself analyzing data that I need to turn into a spreadsheet with two levels of indices. For example, from the mock data:

Authors and their books
Sam Jones
    How to write comedy
    How to write mystery
Jim Smith
    How to avoid writing
    The pleasures of procrastination
    The book I didn't write
Bill Bailey
Sally Ames
    The art of sleeping

I want to generate the following spreadsheet:

In words, I want to have one row for each title and I want an incrementing index for authors and another for each author's titles.

To do this, the first step is to turn the data into the following spreadsheet:

Doing that is simple and straightforward, and I don't need to explain how I did that. The challenge is to use the data of sheet "sample 1" to generate sheet "sample 2". Obviously, it would be easy to manipulate these data manually into that form, but the challenge is when I have a data set with hundreds or thousands of rows in the structure of "sample 1", to convert it to the structure of "sample 2".

The formulas I have developed to do that are, in sheet "sample 2":

A5: =A4 + 1
B5: =IF(B4 = "", "", IF(ISTEXT(B4), 1, IF(H4 < G4, B4, IF(B4 = 'sample 1'!B$3, "", B4 + 1))))
C5: =IF(B5 = B4, "", B5)
D5: =IF(C5 = "", "", MATCH(C5, 'sample 1'!H$5:H$75, 0) + ROW('sample 1'!H$4))
E5: =IF($D5 = "", "", INDEX('sample 1'!B:B, $D5))
F5: =IF($D5 = "", "", INDEX('sample 1'!I:I, $D5))
G5: =IF(B5 = "", "", IF(F5 = "", G4, F5))
H5: =IF(B5 = "", "", IF(F5 = 0, "", IF(F5 = "", H4 + 1, 1)))
I5: =IF(H5 = "", "", INDEX('sample 1'!C:C, MATCH(1, INDEX((B5 = 'sample 1'!G:G) * (H5 = 'sample 1'!J:J), 0, 1), 0)))

That's the code I'd like reviewed. Is there a simpler or more efficient way to do this?

Documentation of what each formula does, to make them easier to review:

A5: Simple incrementing of a number for each data row.
B5: Author index:

Empty if the previous row's value is empty.
If the previous row's value is text, meaning that this is the first data row, then 1.
If the previous row's title index is less than the number of titles for this author, then repeat the previous row's value of the author index.
If the previous row's title index is equal to the number of titles for this author, then we have listed all the titles for that author. So:
If the previous row's author index equals the number of authors, then we're finished. Return empty.
Otherwise, increment the author index.

C5: Show the author index if it is different from that in the previous row.
D5: If the author index is shown in the previous column, then get the row number of that author index in sheet "sample 1".
E5: Author's name: If there's a value in the previous column, then get the author's name from sheet "sample 1".
F5: Number of titles: If there's a value in D5, then get the number of this author's titles from sheet "sample 1".
G5: Fill in this author's number of titles for rows where it's empty in the previous column. (This is used in the calculation of the next row's author index (B6).)
H5: Title index: If the number of titles is 0, then empty. Otherwise, if this is the first title for this author, then 1, otherwise increment from the previous row's value.
I5: Title: If there is a title index, then get the row number of the row in sheet "sample 1" with the same author index and title index, and then get the title from that row.

In order to understand the formula for I5, you also need one formula from sheet "sample 1" because its values are hidden by its narrow column width:

'sample 1'!G5: =N(G4) + IF(B5 = "", 0, 1)

Documentation of that: Column 'sample 1'!G:G provides the author index of each book.


texts:
Trying to write a substring function in Clojure. I am sure there is a more idiomatic way. Can anyone enlighten me?

Otherwise, here is my version. Thoughts?

(defn substring?
  "is 'sub' in 'str'?"
  [sub str]
  (if (not= (.indexOf str sub) -1)
    true
    false))


texts: Calling variable methods to handle ajax requests

texts:
I made a controller.php file to handle ajax requests, with $_POST parameters action and module

if (isset($_POST["action"])) {
    $action = strtolower($_POST["action"]);

    if ($action === "get_notification") {
        //  return session notification messages
       //...

    } elseif (isset($_POST["module"])) {
        require_once("libraries/class.module.php");
        $module = new Module;

        $moduleName = strtolower($_POST["module"]);

        //  check if module-name is valid
        if ($module->verify($moduleName)) {
            // load  $modulename class
            require_once("libraries/class.".$moduleName.".php");

            //  factory used to create instance of $moduleName
            require_once("libraries/class.factory.php");

            // note: moduleName class extends Module class
            $module = $Factory->create($moduleName);

            //  verify method of $moduleName verifies action/method parameter
            //  using method_exists and cross-checking against a permitted methods list

            if ($module->verify($action)) {
                $message = $module->$action();
                echo json_encode($message);

            } else {
                //  handle invalid requests
                echo json_encode(["0", "Invalid request received"]);
            }

        } else {
            //  handle invalid requests
            echo json_encode(["0", "Invalid request received"]);
        }

    } else {
        //  handle invalid requests
        echo json_encode(["0", "Invalid request received"]);
    }

} else {
    //  handle invalid requests
    echo json_encode(["0", "No request received"]);
}

But I read this post on Stack Overflow which advises against using variable methods. Should I replace mine with a switch case that checks each $action and calls corresponding method.


texts: Exporting a UserForm from the VBE... and working around API bugs

texts:
Rubberduck has been using an extension method to export code files, notably for source control purposes.

While testing source control, I ran into a weird bug in the VBIDE API, which caused UserForm modules to perpetually be treated as "modified", because every time we exported them, the VBIDE API would add an empty line at the beginning of the code-behind.

So I had to modify our ExportAsSourceFile extension method to work around that glitch:

Export the form to a temporary file
Read the contents of the file
Locate the last line of the file heading (attributes that are now showing in the VBE)
Determine if we have an extraneous empty line, and remove it
Write the modified content into the intended export folder

Modifying the file directly in the export folder wasn't an option, because then Git would have considered it as modified anyway.

For context/reference, here's what a UserForm code file looks like:

VERSION 5.00
Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} UserForm1
   Caption         =   "UserForm1"
   ClientHeight    =   3165
   ClientLeft      =   45
   ClientTop       =   390
   ClientWidth     =   4710
   OleObjectBlob   =   "UserForm1.frx":0000
   StartUpPosition =   1  'CenterOwner
End
Attribute VB_Name = "UserForm1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Option Explicit 'first line of actual user code visible in the VBE

Notice the VB_PredeclaredId attribute is always the last one specified: my fix relies on that detail.

Here's the extension method in question:

/// <summary>
/// Exports the component to the directoryPath. The file is name matches the component name and file extension is based on the component's type.
/// </summary>
/// <param name="component">The component to be exported to the file system.</param>
/// <param name="directoryPath">Destination Path for the resulting source file.</param>
public static string ExportAsSourceFile(this VBComponent component, string directoryPath)
{
    var path = Path.Combine(directoryPath, component.Name + component.Type.FileExtension());
    if (component.Type == vbext_ComponentType.vbext_ct_Document)
    {
        var lineCount = component.CodeModule.CountOfLines;
        if (lineCount > 0)
        {
            var text = component.CodeModule.get_Lines(1, lineCount);
            File.WriteAllText(path, text);
        }
    }
    else if(component.Type == vbext_ComponentType.vbext_ct_MSForm)
    {
        // VBIDE API *sometimes* inserts an extra newline when exporting a UserForm module.
        // this issue causes forms to always be treated as "modified" in source control, which causes conflicts.
        // we need to remove the extra newline before the file gets written to its output location.
        var tempFile = component.ExportToTempFile();
        var contents = File.ReadAllLines(tempFile);
        var vbExposedAttributeLine = 0;
        for (var i = 0; i < contents.Length; i++)
        {
            if (contents[i].StartsWith("Attribute VB_Exposed = "))
            {
                vbExposedAttributeLine = i;
                break;
            }
        }
        if (contents.Length > vbExposedAttributeLine && contents[vbExposedAttributeLine + 1].Replace(Environment.NewLine, string.Empty).Trim() == string.Empty)
        {
            // first line in module is empty - assume it wasn't in the VBE
            var edited = contents.Take(vbExposedAttributeLine).Union(contents.Skip(vbExposedAttributeLine + 1)).ToArray();
            File.WriteAllLines(path, edited);
        }
    }
    else
    {
        // other module types can just be exported directly
        component.Export(path);
    }

    return path;
}

public static string ExportToTempFile(this VBComponent component)
{
    var path = Path.Combine(Path.GetTempPath(), component.Name + component.Type.FileExtension());
    component.Export(path);
    return path;
}

Is there a better way to do this? It works.. but is there anything that could go wrong with it?


texts:
I'm trying to become more proficient in Python and have decided to run through the Project Euler problems.

In any case, the problem that I'm on (17) wants me to count all the letters in the English words for each natural number up to 1,000. In other words, one + two would have 6 letters, and so on continuing that for all numbers to 1,000.

I wrote this code, which produces the correct answer (21,124). However, I'm wondering if there's a more pythonic way to do this.

I have a function (num2eng) which translates the given integer into English words but does not include the word "and".

for i in range (1, COUNTTO + 1):
    container = num2eng(i)
    container = container.replace(' ', '')
    print container
    if i > 100:
        if not i % 100 == 0:
            length = length + container.__len__()  + 3 # account for 'and' in numbers over 100
        else:
            length = length + container.__len__()
    else:
        length = length + container.__len__()
    print length

There is some repetition in my code and some nesting, both of which seem un-pythonic.

I'm specifically looking for ways to make the script shorter and with simpler loops; I think that's my biggest weakness in general.


texts: Simple animation method with requestAnimationFrame code structure

texts:
I'm writing a animate method to perform DOM animations. I know there are a lot of libraries out there that already does that (and I use some ideas of them) but I usually prefer writing my own code to pinpoint my problem.

The code below is working perfectly, but something with the structure is making me uncomfortable. I think it is because I use references to itself just before the objects dies, so I'm not sure if I'm reusing the animation object or creating new ones. Apparently there is no memory leak.

Can someone give it a look? Fell free to suggest code modifications even if they are unrelated with the memory leak.

window.animate = function(options) {

    var fps = options.fps || 30;
    var x = options.x || null;
    var y = options.y || null;
    var duration = Math.ceil((options.duration / 1000) * fps);
    var onProgress = options.onProgress || null;
    var onComplete = options.onComplete || null;
    var easing = easing || 'easeInOutQuad';

    var animation = {
        fps: fps,
        x: x,
        y: y,
        duration: duration,
        onProgress: onProgress,
        onComplete: onComplete,
        easing: easing,
        _id: null,
        _iteration: 1,
        _lastFrameOccurrence: 0,
        _draw: function() {

            var $this = this;

            var now = Date.now();
            var delta = now - $this._lastFrameOccurrence;
            var interval = 1000 / $this.fps;

            if (delta > interval) {

                $this._lastFrameOccurrence = now - (delta % interval);

                var response = {};
                var factor = window.w.easing[$this.easing]($this._iteration, $this.duration);
                for (var i in $this.x)
                    if ($this.x.hasOwnProperty(i))
                        response[i] = $this.x[i] + ($this.y[i] - $this.x[i]) * factor;

                if ($this.onProgress instanceof Function)
                    $this.onProgress(response);

                $this._iteration++;

                if ($this._iteration > $this.duration)
                    if ($this.onComplete instanceof Function)
                        $this.onComplete();

            };

            if ($this._iteration <= $this.duration) {
                $this._id = requestAnimationFrame(function() {
                    $this._draw();
                });
            } else {
                cancelAnimationFrame($this._id);
            };

        }
    };

    animation._draw();

};

                w.animate({
                    x: { opacity: 1 },
                    y: { opacity: 0 },
                    duration: 500,
                    onProgress: function(r) { console.log(r); },
                    onComplete: function() {}
                });


texts: Classifying counts of repeat visits per user for a website

texts:
I am trying to get number of times (or sessions) a user re-visited the website.

What I'm trying to find out-

Get the total number of users, number of sessions in the last 30days. I need to a pie chart ultimately where it shows people who revisited-

more than 100 times,
50-100 times,
less than 50 times

The problem with the current implementation I see is -

The whole set of data(like 100million rows) are being computed every time(for each query with different condition)

SELECT COUNT(A.sess) as acount, SUM(A.sess) as asum, AVG(A.sess) as aavg
FROM
(SELECT ipaddress,
        COUNT(*) AS sess
   FROM analytics
   WHERE trunc(datecreated) > getdate() - interval '30 days'
   GROUP BY trunc(datecreated), ipaddress
   HAVING COUNT(*) >= 100) AS A

UNION ALL

SELECT COUNT(B.sess) as bcount, SUM(B.sess) as bsum, AVG(B.sess) as bavg
FROM
(SELECT ipaddress,
        COUNT(*) AS sess
   FROM analytics
   WHERE trunc(datecreated) > getdate() - interval '30 days'
   GROUP BY trunc(datecreated), ipaddress
   HAVING COUNT(*) < 100 AND COUNT(*) >=50 ) AS B

UNION ALL

SELECT COUNT(C.sess) as ccount, SUM(C.sess) as csum, AVG(C.sess) as cavg
FROM
(SELECT ipaddress,
        COUNT(*) AS sess
   FROM analytics
   WHERE trunc(datecreated) > getdate() - interval '30 days'
   GROUP BY trunc(datecreated), ipaddress
   HAVING COUNT(*) < 50 ) AS C

How do I optimize the query?


texts: Alternate method of iterating than os.walk

texts:
Recently, I became tired of how slowly os.walk seems to run (really, it should be called os.crawl), and made something recursive which moves much faster.  I was using it to take directories I wanted and add them to an array, but this time I need to add all files to an array that aren't in an 'exclude array.' Does anyone have any advice?

import os

exclude_folders = ['excludefolder1', 'excludefolder2']
product_path_names = ['folder1', 'folder2', 'folder3']
# This function replaces the os.walk, it is faster and stops scanning subdirectories
# when it find a good folder name.
def findDir(path):
    for directory in os.listdir(path):
     # If it's a folder that we want to scan, go for it.
        if(os.path.isdir(os.path.join(path, directory))):
            # If folder is a product name, add it.
            if(directory.lower() in product_path_names):
                print os.path.join(path, directory)
                product_dirs.append(os.path.join(path, directory))
                with open(event_log_path, "a") as log:
                    log.write(os.path.join(path, directory) + "\n")
                break
            # If folder is not a product name, scan it.
            else:
                #print os.path.join(path, directory)
                if(directory.lower() not in exclude_folders):
                    findDir(os.path.join(path, directory))


texts:
For lack of better things to do I went on coderbyte and did one of the simple challenges since I have not written code for a little while.

The problem was stated as following:

Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty.

Few notes to TL;DR the comments:

I would have used const std::string& but function definition was given by CoderByte
string[string.length()] is guaranteed to return '\0' since C++11.
My code does not look for any terminating zeroes.

I'm looking for more discussion regarding the structure, the approach to the problem and general look & feel.

This is my solution:

// The function definition was given by CoderByte, I would have used
// const std::string& if it was up to me
string LongestWord(string sen) {
  // code goes here
  int start = -1;
  int bstart = -1;
  int blen = 0;

  // lequal since std string is compatible with c strings, it will have \0 at
  // the end, saving a special case after the loop.
  for (int i = 0; i <= sen.length(); ++i)
  {
      if (start == -1 && isalpha(sen[i]))
      {
          start = i;
      }
      else if (!isalpha(sen[i]))
      {
          if (start >= 0 && i - start > blen)
          {
               blen = i - start;
               bstart = start;
               start = -1;
          }
      }
  }

  return sen.substr(bstart, blen);
}

I ran the test cases and all was well, so I figured I'd check the top solution on the website:

string LongestWord(string sen) {

  // code goes here
  string sen2 = "";
  for(int i=0;i<sen.length();i++)
  {
    if(isalpha(sen[i])||sen[i]==' '||'0'<=sen[i]&&sen[i]<='9')
    {
      sen2.append(sen.substr(i,1));
    }
  }
  char* sench = (char*)sen2.c_str();
  string longest = "";
  int longestLen = 0;
  for(const char* pch=strtok(sench," ");pch;pch=strtok(NULL," "))
  {
    if(strlen(pch)>longestLen)
    {
      longest = pch;
      longestLen=strlen(pch);
    }
  }
  return longest;
}

From my point of view my solution is less complicated, has fewer moving parts, is easier to digest and at first glance I expect it to perform better due to less looping(although I have not tested this).

I feel like I am missing something, this happens with some frequency where I notice people use more complex solutions and I wonder if I'm basically writing tutorial code or something. Is this just me doubting myself or have I missed something?


texts: Setting output width with ostream_iterator

texts:
I'd like to display a vector (implemented in my custom Vector class) and have the output width of the elements be configurable. I've done this by creating a simple wrapper for the element being displayed which stores the desired width in a static field. I'm not sure if this is the best approach.

/** A struct for formatting doubles with a fixed width. */
struct FixedWidthDouble {
  FixedWidthDouble(double x) : x_(x) {}
  double x_;
  static int width_;
};

/** Apply a fixed width manipulator to a double for display. */
std::ostream& operator<<(std::ostream& out,
    const FixedWidthDouble &fixedWidthDouble) {
  return out << std::setw(fixedWidthDouble.width_) << fixedWidthDouble.x_;
}

Here's an example of it being applied:

/** Convert a Vector into a stream suitable for display. */
std::ostream& Vector::Print(std::ostream& out, int width) const {
  out << "[" << std::setprecision(1) << std::fixed;
  FixedWidthDouble::width_ = width;
  std::copy(begin(), end(), std::ostream_iterator<FixedWidthDouble>(out, " "));
  return out << " ]";
}

Is there a cleaner way to do this?

Proposed Solution

Based on feedback from Begemoth this is the solution I decided to go with. Does this look reasonable?

template<int width>
struct FixedWidthDouble {
  FixedWidthDouble(double x) : x_(x) {}
  double x_;
};

/** Apply a fixed width manipulator to a double for display. */
template <int width>
std::ostream& operator<<(std::ostream& out,
    const FixedWidthDouble<width> &fixedWidthDouble) {
  return out << std::setw(width) << fixedWidthDouble.x_;
}

/** Convert a Vector into a stream suitable for display. */
template <int width>
std::ostream& Vector::Print(std::ostream& out) const {
  out << "[" << std::setprecision(1) << std::fixed;
  std::copy(begin(), end(),
      std::ostream_iterator<FixedWidthDouble<width> >(out, " "));
  return out << " ]";
}