texts: JavaScript Proxy: set DOM Element styles by chaining CSS setters

texts:
First time creating my own Proxy handler, instead of copy pasting code.
Goal is to chain CSS definitions: style(element).color("red").background("green")
and allow whole CSS objects:
style(element).CSS({color:"red",font:"12 px Arial"}).background("green")
Any optimizations?

let handler = {
  get: (target, prop) => val => // getter returns a function
    val ?
    (
      handler.set(target, prop, val), //process val parameter as setter
      new Proxy(target, handler) // and return new proxy for chaining
    )
    //else:
    : target[prop], // no parameter value, return property value

  set: (target, prop, val) => prop === "CSS" ? Object.assign(target, val) : target[prop] = val
}

let style = element => new Proxy(element.style, handler);

let el = document.body.appendChild(document.createElement("div"));

el.style.backgroundColor = "red"; // standard non-Proxy way of setting styles

style(el).fontSize = "30px"; // style property name as SETTER

// Proxy allows for chaining because each function returns a Proxy again:

style(el)
  .backgroundColor("green") // style property Name processed as function
  .CSS({ // custom function applies CSS
    width: "100px",
  })
  .CSS = { // custom SETTER applies CSS (last action in the chain)
    color: "gold",
    fontWeight: "bold",
    textAlign: "center"
  };

el.textContent = style(el).fontSize(); // GETTER as function notation!!

Update #1
I reduced the style()function definition to a one-liner:
let style = element => new Proxy(element.style, handler = {
  get: (target, prop, proxy) => val =>
    val ? (handler.set(target, prop, val), proxy) : target[prop],
  set: (target, prop, val) =>
    prop === "CSS" ? Object.assign(target, val) : target[prop] = val
});

any issues here?


texts:
I've written a more powerful version of the Sieve of Eratosthenes, this Sieve returns the number of factors of all the numbers below the limit.Sadly the running time is \$O(n^2)\$, so it is much slower than the ordinary sieve. Can you suggest a way to improve and optimize it?

import doctest

def factors_sieve(limit):
    """
    Returns the number of factors of all the numbers below the limit.
    For better convenience use list(enumerate(factors_sieve(limit)))

    >>> list(enumerate(factors_sieve(9)))
    [(0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (5, 2), (6, 4), (7, 2), (8, 4)]
    >>> factors_sieve(100000).count(2) # How many prime numbers below 100000?
    9592
    """
    sieve = [2]*limit
    sieve[0],sieve[1] = 0,1
    for number,number_of_divisors in enumerate(sieve):
        if number >= 2:
            for multiple in range(number*2, len(sieve), number):
                sieve[multiple] += 1

    return sieve

if __name__ == "__main__":
    doctest.testmod()


texts:
I have implemented PropertyInfo GetValue and Expression Cache GetValue by Logic from Reflection vs. compiled expressions vs. delegates - Performance comparison,but I'm sure that there are better ways to do every thing that I did. I would appreciate any feedback on this code, which does work according to spec:

MyLogic

  Asynchronous nonblocking, which does not block thread when adding a Cache
  Dictionary Key use propertyInfo GetHash()
  if dictionary cache containskey then use compiler expression function else use Reflection GetValue

My Class

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;

public class TestService
{
    private static Dictionary<int, object> ExpressionCache = new Dictionary<int, object>();

    public IEnumerable<string> Execute<T>(IEnumerable<T> enums)
    {
        var expressionCache = (enums);
        var props = typeof(T).GetProperties();
        foreach (var e in enums)
        {
            foreach (var p in props)
            {
                var func = GetOrAddExpressionCache<T>(p);
                var value = string.Empty;
                if (func == null)
                {
                    Debug.WriteLine("Use Reflection");
                    value = p.GetValue(e).ToString();
                }
                else
                {
                    Debug.WriteLine("Use Expression");
                    value = func(e);
                }
                yield return value;
            }
        }
    }

    private Func<T, string> GetOrAddExpressionCache<T>(PropertyInfo prop)
    {
        var key = prop.GetHashCode();
        if (ExpressionCache.ContainsKey(key))
        {
            var func = ExpressionCache[key] as Func<T, string>;
            return func;
        }else{
            Task.Run(()=>AddExpressionCacheAsync<T>(prop));
            return null;
        }
    }

    //Asynchronous nonblocking, which does not block a thread when adding a Cache
    private async Task AddExpressionCacheAsync<T>(PropertyInfo propertyInfo)
    {
        var key = propertyInfo.GetHashCode();
        if (!ExpressionCache.ContainsKey(key))
        {
            var func = GetValueGetter<T>(propertyInfo);
            ExpressionCache.Add(key, func);
        }
        await Task.Yield();
    }

    private static Func<T, string> GetValueGetter<T>(PropertyInfo propertyInfo)
    {
        var instance = Expression.Parameter(propertyInfo.DeclaringType);
        var property = Expression.Property(instance, propertyInfo);
        var toString = Expression.Call(property, "ToString", Type.EmptyTypes);
        return Expression.Lambda<Func<T, string>>(toString, instance).Compile();
    }
}

Demo

class Program{
    public static void Main(string[] args){
        var data = new[] { new { Name = "Henry", Age = 25 } };
        for (int i = 0; i < 2; i++)
        {
            var service = new TestService();
            var result = service.Execute(data).ToArray();
        }
    }
}

/* Console :
        Use Reflection
        Use Reflection
        Use Expression
        Use Expression
*/


texts:
I need multiple read access to some data which can be updated from time to time.
I created a class for managing lock-less access to the data. The class uses 2 counters, one for count of the acquired references and another one for the count of released references. The update function replaces the data pointer and then waits for the completion of the previous reads.

Can someone with more experience in lock-less programming comment on the correction and performance of the code?

template<typename T>
inline void IgnorePolicy(T* item) {}
template<typename T>
inline void DeletePolicy(T* item)
{
    delete item;
}
template<typename T>
inline void ReleasePolicy(T* item)
{
    if(item != NULL)
        item->Release();
}

template<typename T, void (* DestroyPolicy)(T* item) = IgnorePolicy>
class ReadUpdateData
{
    private:
        volatile int m_acquireCount, m_releaseCount;
        T* m_data;

        bool CheckReleaseCount(int limit) //wrap-safe check to see if release count has reached the required limit
        {
            int releaseCount = m_releaseCount;
            return (limit < 0 || releaseCount >= 0) ? limit <= releaseCount : limit >= 0 && releaseCount < 0;
        }

    public:
        ReadUpdateData() : m_acquireCount(0), m_releaseCount(0), m_data(NULL) {}
        ~ReadUpdateData()
        {
            assert(m_acquireCount == m_releaseCount);
            DestroyPolicy(m_data);
        }

        T* Acquire()
        {
            AtomicIncrement(&m_acquireCount);
            return m_data;
        }
        void Release()
        {
            AtomicIncrement(&m_releaseCount);
        }

        void Update(T* newData)
        {
            T* oldData = m_data;
            while(AtomicCompareExchangePtr(&m_data, newData, oldData) == oldData)
                oldData = m_data;

            int acquireCount = m_acquireCount;
            while(!CheckReleaseCount(acquireCount))
                Yield();

            DestroyPolicy(oldData);
        }
};


texts: Wet Boxes problem: counting points on a triangular grid

texts:
As a solution to the B. Wet Boxes problem :

  B. Wet Boxes

  Bob works in a warehouse which contains a large pile of boxes. The
  position of a box can be described with a pair of integers (x, y).
  Each box either stands on the ground (y = 0) or stands on top of two
  boxes with positions (x, y - 1) and (x + 1, y - 1) (see the figure).

  Sometimes the contents of a box leak out and the box gets wet. When a
  box becomes wet, so do the two boxes below it. Given a list of boxes
  that leak in succession, help Bob count how many dry boxes became wet
  after each leak. Don't include boxes that were already wet.

My solution is :

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

static int count;

typedef struct {
    int x;
    int y;
}Box;

Box* push(Box* memptr, int x, int y){
    int i;
    for (i = 0; i < count; i++){
        if ((memptr[i].x == x) && (memptr[i].y == y))
            return memptr;
    }
    count++;
    if (count == 1)
        memptr = (Box*)malloc(sizeof(Box));
    else
        memptr = (Box*)realloc(memptr, sizeof(Box) * count);
    memptr[count - 1].x = x;
    memptr[count - 1].y = y;

    return memptr;
}

Box* find_wet_boxes(Box* memptr, int x, int y){
    if ((x * y) < 0)
        return memptr;
    else {
        memptr = push(memptr, x, y);
        find_wet_boxes(memptr, x, y - 1);
        return find_wet_boxes(memptr, x + 1, y - 1);
    }
}

int main(){
    Box* memptr = NULL;
    // int i;
    memptr = find_wet_boxes(memptr, 1, 3);
    // memptr = find_wet_boxes(memptr, 3, 2);
    // memptr = find_wet_boxes(memptr, 0, 6);
    // memptr = find_wet_boxes(memptr, 1, 1);
    printf("count = %d\n", count);
    return 0;
}

This works fine for each individual box co-ordinates but when I try to run for all the 4 co-ordinates, it gives me time limit exceed error during submission. (Coordinates may be as large as 109.  There may be up to 105 leaking boxes.  Time limit is 0.7 seconds.) Clearly my algorithm is not good enough. Can someone please give me a better solution for this?

If it the answer is too broad and there could be many solution, then I expect at least one of them which will at least pass the runtime limit test

Possible Solution:

  So, a single leaked box covers a smaller triangle of boxes. In short,
  we maintain a set that contains the vertices of such triangles that
  have not been covered by any other triangle yet. When a box leaks
  (i.e., a new triangle is added), we find the vertices of the triangles
  that are inside the new one, and subtract the area that was first
  covered by this box and is inside the new triangle. Then we can remove
  them from the set and insert the new triangle vertex in the set. This
  results in \$O(n\ \log n)\$ solution (for each new triangle, there can be
  also two vertices that are not inside the new triangle, but overlap
  with it: these vertices remain in the set, but that does not change
  the complexity).

This is the possible solution as quoted by someone but I don't understand how to implement it or will that actually solve the problem.


texts: Function to calculate energy for wind turbines

texts:
This function is going to be part of a class which can determine the efficiency and max/average power that can be produced by specific wind turbines based on the location given by the user.  Is the documentation OK?

def WindEnergy_calc(density, surfaceArea, windspeed, powerCoefficient):

    """
    This function returns the value of wind energy given density of the air,

    surface area of blades, and windspeed.

    Args:

    * density (float or int) - the value represents the density of the air

    * surface area (float or int) - the value represents the total surface area of turbine

    * windspeed (float or int) - the value represents the windspeed in the area

    *Power Coeffecient of turbine (float) - value cannot exceed

    Returns:

    * total possible kinetic energy created by the wind on the turbine

    * P = 1/2*row*A*V^3*C

    """
    try:
        if powerCoefficient > 0.59:
            powerCoefficient = "Not Possible" #to break code
    except:
        print "Power Coefficient must be less than 0.59 due to Betz limit"
        return()

    half = 0.5
    windEnergy = float(half*density*surfaceArea*windspeed**3)
    return(windEnergy)


texts:
This is for heapsort and am wondering about the heapifyDown method. Here it is for review. I included relevant helper methods.

The heap is stored in array starting at index 1.

/*swaps node at i with biggest child if larger*/
private void heapifyDown(final int i) {
    while(!isLeaf(i)) {
        //find biggest child
        int biggestChldIndx;
        if(getRgtChldIndx(i) <= end) {//check if node has right child
            if(heap[getLftChldIndx(i)] > heap[getRgtChldIndx(i)]) {
                biggestChldIndx = getLftChldIndx(i);
            } else {
                biggestChldIndx = getRgtChldIndx(i);
            }
        } else {//only has left child so use it
            biggestChldIndx = getLftChldIndx(i);
        }
        //check if child is larger than parent
        if(heap[i] < heap[biggestChldIndx]) {
            //if it is, then swap
            swap(i, biggestChldIndx);
            i = biggestChldIndx;
        } else {
            break;
        }
    }
}

private boolean isLeaf(final int position) {
    return (2 * position > end);
}

private int getLftChldIndx(final int i) {
    return (i * 2);
}

private int getRgtChldIndx(final int i) {
    return (i * 2 + 1);
}

private final int[] heap;
private int end;//last used element


texts:
At my work, I need to use multiple versions of Java, depending on which project I work on. I've made a batch script to take care of this. There are several different actions that you can perform with the script.

You can change the current value of your JAVA_HOME from a version in your file. You can add new Java installation (pre-installed one), you can remove them and you can list them. You can echo your env variable, if you're not sure what's the value at the moment.

This is a script I'm using for myself for the time being, so there are a lot of things that are probably not robust or are not yet implemented. For example, you can use the program with non-existent version and it will not crash or warn you. The add and remove functions work but they output the command and can surely be played with. It does work when you know what to do.

This is the first time I'm writing a batch script, and I must say it is mostly been googling and hacking something together.

@ECHO OFF
if "%1"=="" goto empty
if "%1"=="echo" goto output
if "%1"=="e" goto output
if "%1"=="list" goto list
if "%1"=="l" goto list
if "%1"=="add" goto add
if "%1"=="a" goto add
if "%1"=="remove" goto remove
if "%1"=="r" goto remove

rem To escape '%' the sequence is '%%', so to not have to have an arg like %JAVA6%, the following will add % % on both end of the argument
SET java_version=%%%1%%

for /f "delims== tokens=1,2" %%a in (%~dp0java_versions.store) do (
   set "%%~a=%%b"
)
call :unquote JAVA_HOME %java_version%

for /f "delims== tokens=1,2" %%a in (%~dp0java_versions.store) do (
  set "%%a="
)

goto :EOF

:unquote
  set %1=%~2
  goto :output

:output
  ECHO "JAVA_HOME=%JAVA_HOME%"
  SET "java_version="
  goto :EOF

:list
  FOR /f "delims=" %%x IN (%~dp0java_versions.store) DO (
    echo "%%~x"
  )
  goto :EOF

:add
  if "%2"=="" (
    ECHO "Name of the entry missing"
    goto :EOF
  )
  if "%~3"=="" (
    ECHO "Path of the entry missing"
    goto :EOF
  )
  echo %~3
  IF EXIST %~3 (
    echo %2="%~3">> %~dp0java_versions.store
    ECHO %2="%~3" added
  ) ELSE (
    ECHO %3 is not an actual folder
  ) .
  goto :EOF

:remove
  if "%2"=="" (
    ECHO "Name of the entry missing as an argument of the batch"
    goto :EOF
  )
  set "found="
  for /f "delims== tokens=1,2" %%a in (%~dp0java_versions.store) do (
     if "%2"=="%%a" (
       set found=1
       echo found
     )
  )
  if defined found  (
    for /f "delims== tokens=1,2" %%a in (%~dp0java_versions.store) do (
      if NOT "%2"=="%%a" (
        echo %%~a=%%b>> %~dp0new_java_versions.store
      )
    )
    xcopy %~dp0new_java_versions.store %~dp0java_versions.store /y
    del %~dp0new_java_versions.store /f /q
    ECHO Entry %2 deleted
  )

  goto :EOF

:empty
  ECHO "Empty argument, please provide an argument"
  goto :EOF

Store file format :

JAVA8_11="C:\Program Files\Java\jdk1.8.0_11"
JAVA8="C:\Program Files\Java\jdk1.8.0_73"
JAVA7="C:\Program Files\Java\jdk1.7.0_51"


texts: Bash script for referencing git status output files

texts:
Whenever I do git status, I want to reference the files that were shown easily... whether it be so I can open it in vim, git add it, delete it, git checkout (to revert), etc. So after a bit of looking around, I couldn't find any existing script for this so I made my own. It works, but the code is not pretty, and being a beginner bash scripter (if that's even a noun), I feel like I can do so much better with this.

Here is the script:

#usage gits: sets env variables $m<n> $d<n> $u<n> $a (modified, deleted, untracked, added)
function gits {
    git status
    gitsall=$(git status -s)
    m=$(echo "$gitsall" | grep "^ M")
    d=$(echo "$gitsall" | grep "^ D")
    u=$(echo "$gitsall" | grep "^??")
    a=$(echo "$gitsall" | grep "^A ")
    s=$(echo "$gitsall" | grep "^M ")
    #i=0
    #while [[ -n "$(echo {m,d,u}$(($i)))" ]]; do
#   i=$(($i+1))
#   unset {m,d,u}$(($i))
#    done
    count=1
    while read -r tmpfilename; do
    tmpfilename=${tmpfilename:2}
    set m$(($count))="$(pwd)/$tmpfilename"
    count=$(($count+1))
    done <<< "$m"
    count=1
    while read -r tmpfilename; do
    tmpfilename=${tmpfilename:2}
    set d$(($count))="$(pwd)/$tmpfilename"
    count=$(($count+1))
    done <<< "$d"
    count=1
    while read -r tmpfilename; do
    tmpfilename=${tmpfilename:3}
    set u$(($count))="$(pwd)/$tmpfilename"
    count=$(($count+1))
    done <<< "$u"
    count=1
    while read -r tmpfilename; do
    tmpfilename=${tmpfilename:3}
    set a$(($count))="$(pwd)/$tmpfilename"
    count=$(($count+1))
    done <<< "$a"
    count=1
    while read -r tmpfilename; do
    tmpfilename=${tmpfilename:3}
    set s$(($count))="$(pwd)/$tmpfilename"
    count=$(($count+1))
    done <<< "$s"

    unset m d u a s tmpfilename gitsall
}

Basically, I call git status -s, save the output as a variable, then grep it to get lists of filenames of modified, deleted, untracked, and added.

I then parse each line individually and set $ to the respective file in absolute paths.

Now, much of the parsing is the same. Things that vary are env var prefix, substring location (2 or 3 so far), and file list var name. I feel like this can somehow be cleaned up nicely.

Note: I do know this is not going to cover everything. Namely, I only so far implemented it for " M" " D" "??" "A ", but I know others exist like "M ", "MM", etc. which I eventually plan to address. This script is still a WIP for me but I wanted to clean it up before I add all the change types.

I did look around google thinking someone has made something like this because I thought it'll be something people would find convenient. For those who have different workflows that work around my situation, it'll be nice if I can hear them too.

Example usage:

gits

Output of git status and set the appropriate vars

vim $m1

Opens first modified, untracked file in the list from git status


texts: Designing a dynamic array of Memory Streams

texts:
I'm working on a feature for work that requires me to combine a set number of memory streams based on specific conditions.

Previous Code

Before based on documentation/examples online. In order to create a PDF to print, you have to create a Memory Stream and save that document into a Memory Stream. Here lies my old code.

    PdfDocument testDocument1 = new PdfDocument(testParametersToDesignUniquePDF1);
    PdfDocument testDocument2 = new PdfDocument(testParametersToDesignUniquePDF2);
    PdfDocument testDocument3 = new PdfDocument(testParametersToDesignUniquePDF3);
    MemoryStream testDocument1Stream = new MemoryStream();
    MemoryStream testDocument2Stream = new MemoryStream();
    MemoryStream testDocument3Stream = new MemoryStream();
    testDocument1.Save(testDocument1Stream);
    testDocument2.Save(testDocument2Stream);
    testDocument3.Save(testDocument3Stream);

    Stream[] source = { testDocument1, testDocument2};

    if (testCondition)
    {
        source = { testDocument1Stream, testDocument2Stream, testDocument3Stream}
    }

As you can see its only a matter of time before my code gets chunkier as for every PdfDocument, I create I have to create a new memory stream. There's also a limitation of having a static array that I have to keep initializing a new array as more condition applies. I fixed this code with the following below.

New Code

My Code Refactor is to create a dynamic List that I can add x number of streams based on x conditions. Then convert back to a static size array after I'm done. It saves a lot of extra code creating memory streams and saving my documents on it.

    List<MemoryStream> memoryStreams = new List<MemoryStream>();

    memoryStreams.Add(ConvertToMemoryStream(new PdfDocument(testParametersToDesignUniquePDF1)));
    memoryStreams.Add(ConvertToMemoryStream(new PdfDocument(testParametersToDesignUniquePDF2)));

    if (testCondition)
    {
       memoryStreams.Add(ConvertToMemoryStream(new PdfDocument(testParametersToDesignUniquePDF3)));
    }

    //Convert dynamic linked list back to an array of steam.
    Stream[] source = memoryStreams.ToArray();

Method to convert PdfDocument to a stream.

 private MemoryStream ConvertToMemoryStream(PdfDocument document)
    {
        MemoryStream stream = new MemoryStream();

        document.Save(stream);

        return stream;
    }

I tested this code to have the same performance and output as the original code. However, the code has more flexibility adding more conditions and PDF's. It is also a lot more readable than the previous code. However, I am worried about a few things.

Deallocation - I might not be taking care of disposing my streams if I manipulate it this way.
Time of Deallocation - I'm worried that since I don't have a reference to my streams that it might get disposed on its own before actually using it when I Print the PDF's showing a blank PDF.


texts: MS Fakes Shims. Assert "was called" (by closures)

texts:
Is it a good or bad practice to use closures for asserting the method was called in such a way?

The method set a shim and return an Action wich both capture local mutable variable:

private static Action<bool> ShimCopy(FileInfo source, FileInfo destination)
{
    var wasCalled = false;
    ShimFileInfo.AllInstances.CopyToString = (info, destinationPath) =>
    {
        Assert.AreEqual(source.FullName, info.FullName, "Copy wrong file");
        Assert.AreEqual(destination.FullName, destinationPath, "Copy to wrong destination");
        Assert.IsFalse(wasCalled, "Redundant file copy");
        wasCalled = true;
        return destination;
    };
    return expected => Assert.AreEqual(expected, wasCalled);
}

So it could be used like this:

...
var assertWasCalled = ShimCopy(source, destination);
act();
assertWasCalled(true);
...

It looks convinient but I don't like impure funtions and here I have exactly the case with side effects and indeterministic results. But I've heard "Closures is a poor man's object"...

In addition returned action has no strict human readable signature describing parameter and function meaning. That could be solved by delegate, but delegate is an additional piece of complexity for the project.


texts: I feel as if my quicksort can be made more efficient, but what?

texts:
I just learned the quicksort algorithm and tried to implement it, but it feels dirty:

#include <iostream>

void quicksort(int list[], int low, int high)
{
    if(low >= high)
        return;
    else
    {
        int pivot = low, i = low, j = high;

        while(i < j)
        {
            while(list[i] <= list[pivot] && i < high)
            {
                i++;
            }

            while(list[j] > list[pivot] && j > low)
            {
                j--;
            }

            if(i > j)
                break;

            int temp = list[i];
            list[i] = list[j];
            list[j] = temp;
        }

        int temp = list[pivot];
        list[pivot] = list[j];
        list[j] = temp;

        quicksort(list, low, j-1);
        quicksort(list, j+1, high);

    }
}

int main()
{
    int arr[10] = { 12, 2, 24, 32, 5, 1203, 7, 123, 2354, 2 };
    quicksort(arr, 0, 9);

    for(int i = 0; i < 10; i++)
    {
        std::cout << arr[i] << " ";
    }
}

The break condition in the while loop feels really cheap; as if I did something wrong and needed to put it there...

What can I improve?


texts: Getting count value for matched document

texts:
I have a list of keywords and I want to count the number of records in a db which contain any one of these keywords. From each record, I want to consider only title and description to be checked.

Is this correctly written?

self.keyword_list = ['Buzz', 'Heard on the street', 'familiar with the development', 'familiar with', 'enters race', 'mull', 'consider', 'final stage', 'final deal', 'eye', 'eyes', 'probe', 'vie for', 'detects', 'allege', 'alleges', 'alleged', 'fabricated', 'inspection', 'inspected', 'to monetise', 'cancellation', 'control', 'pact', 'warning', 'IT scanner', 'Speculative', 'Divest', 'Buzz', 'Heard on the street', 'familiar with the development', 'familiar with the matter', 'Sources', 'source', 'Anonymous', 'anonymity', 'Rumour', 'Scam', 'Fraud', 'In talks', 'Likely to', 'Cancel', 'May', 'Plans to ', 'Raids', 'raid', 'search', 'Delisting', 'delist', 'Block', 'Exit', 'Cheating', 'Scouts','scouting', 'Default', 'defaulted', 'defaulter', 'Calls off', 'Lease out', 'Pick up', 'delay', 'arrest', 'arrested', 'inks', 'in race', 'enters race', 'mull', 'consider', 'final stage', 'final deal', 'eye', 'eyes', 'probe', 'vie for', 'detects', 'allege', 'alleges', 'alleged', 'fabricated', 'inspection', 'inspected', 'monetise', 'cancellation', 'control', 'pact', 'warning', 'IT scanner', 'Speculative', 'Divest']
fetch_record = self.collection1.find()
for record in fetch_record:
    count2 += 1
    for item in self.keyword_list:
        if item.lower() in u'{} {}'.format(record['title'], record['description']).lower():
            #print "Matched for item : ", item
            count1 += 1
            break
print "Matched records are : ", count1
print "Total records are : ", count2


texts: Firefox profile specs to speed up web scraping

texts:
I am scraping a pool of URLs with a python/selenium framework using Firefox and Geckodriver.

For each URL, all I am doing is to find one element by class name and save it to disk. In order speed this up as much as possible, I am creating a custom Firefox profile with the specs defined below in firefox_profile.set_preference.

The challenge is that testing all combinations of all Firefox profile parameters in order to know which specs are best for speed is laborious. Therefore, I am hoping to get some input.

Are there any preferences parameters beyond the ones mentioned below that also would speed up Firefox?
Is any of those preference parameters mentioned below not suitable to speed up Firefox?

def create_driver():
        firefox_profile = webdriver.FirefoxProfile()
        firefox_profile.set_preference('browser.download.animateNotifications', False)
        firefox_profile.set_preference('browser.fullscreen.animate', False)
        firefox_profile.set_preference('browser.preferences.animateFadeIn', False)
        firefox_profile.set_preference('browser.tabs.animate', False)
        firefox_profile.set_preference('browser.cache.use_new_backend', 1)
        firefox_profile.set_preference('browser.sessionhistory.max_total_viewers', 0)
        firefox_profile.set_preference('browser.safebrowsing.enabled', False)
        firefox_profile.set_preference('browser.shell.checkDefaultBrowser', False)
        firefox_profile.set_preference('browser.startup.page', 0)
        firefox_profile.set_preference('layout.animated-image-layers.enabled', False)
        firefox_profile.set_preference('extensions.checkCompatibility', False)
        firefox_profile.set_preference('extensions.checkUpdateSecurity', False)
        firefox_profile.set_preference('extensions.logging.enabled', False)
        firefox_profile.set_preference('extensions.update.autoUpdateEnabled', False)
        firefox_profile.set_preference('extensions.update.enabled', False)
        firefox_profile.set_preference('print.postscript.enabled', False)
        firefox_profile.set_preference('toolkit.storage.synchronous', 0)
        firefox_profile.set_preference('image.animation_mode', 'none')
        firefox_profile.set_preference('images.dither', False)
        firefox_profile.set_preference('content.notify.interval', 1000000)
        firefox_profile.set_preference('content.switch.treshold', 100000)
        firefox_profile.set_preference('nglayout.initialpaint.delay', 1000000)
        firefox_profile.set_preference('network.dnscacheentries', 200)
        firefox_profile.set_preference('network.dnscacheexpiration', 600)
        firefox_profile.set_preference('network.prefetch-next', False)
        firefox_profile.set_preference('permissions.default.image', False)
        firefox_profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', False)
        firefox_profile.set_preference('dom.ipc.plugins.flash.disable-protected-mode', False)
        firefox_profile.set_preference('app.update.enabled', False)
        firefox_profile.set_preference('app.update.service.enabled', False)
        firefox_profile.set_preference('app.update.auto', False)
        firefox_profile.set_preference('app.update.staging', False)
        firefox_profile.set_preference('app.update.silent', False)
        firefox_profile.set_preference("javascript.enabled", False)
        driver = webdriver.Firefox(firefox_profile = firefox_profile)
    return driver


texts: Extend number of arguments in std::hypot

texts:
I would like to call std::hypot with many arguments (not just 2 or 3).

Mandatory requirements:

fast
run at compile time when possible

Non-mandatory requirement:

avoid overflow

#include <cmath>
#include <iostream>

template <typename T>
constexpr T sum2(const T v) {
  return v * v;
}

template<typename T1, typename... Ts>
constexpr T1 sum2(const T1 v1, const Ts... rest)
{
  return v1 * v1 + sum2(rest...);
}

template <typename T1, typename... Ts>
constexpr T1 qsum(const T1 v1, const Ts... v)
{
  return sqrt(sum2(v1, v...));
}

int main()
{
  double a = 10.;
  std::cout << qsum(1., a) << std::endl;
}

One bad thing is when I ask qsum(1, 1.) since the first argument is int and so the output. I would like that in this case the inputs are cast to the safer common type.


texts:
This toy code uses MPI I/O to read from a binary file.

It goes through reading:

an ASCII header
the first 10 doubles from an array of 100 doubles
another ASCII header
another 10 doubles from another array

It works, but probably isn't good for more than one process, so I will work on that.  What I am wondering about is positioning the file pointer at the beginning of each new read.  I am making two calls with each read - MPI_File_get_position and MPI_File_get_byte_offset - just to get an offset to put into the MPI_File_set_view call.  I've marked these with: \*"DO I REALLY HAVE TO DO ALL THIS"\*.

It seems pretty inefficient and clunky, but it's all I've been able to come up with. Is there a better way?

#include <stdio.h>
#include "mpi.h"

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

   int myid;
   double a[10];
   int n, fulldim = 100, slctdim = 10, offset=0;
   char header[7];

   MPI_Datatype selector;
   MPI_File infile;
   MPI_Status statmpi;
   MPI_Offset foffset, current_file_pos;

   MPI_Init(&argc, &argv);
   MPI_Comm_rank(MPI_COMM_WORLD, &myid);

   offset = slctdim*myid;

   /* creat datatype for access to file */
   MPI_Type_create_subarray(1, &fulldim, &slctdim, &offset,
                            MPI_ORDER_C, MPI_DOUBLE, &selector);
   MPI_Type_commit(&selector);

   MPI_File_open(MPI_COMM_SELF, "bindatahdr.dat", MPI_MODE_RDONLY,
                 MPI_INFO_NULL, &infile);
   MPI_File_set_view(infile, 0, MPI_CHAR, MPI_CHAR, "native", MPI_INFO_NULL);
   MPI_File_read(infile, header, 6, MPI_CHAR, &statmpi);
   printf("%s\n",header);
   MPI_File_set_view(infile, 6, MPI_DOUBLE, selector, "native", MPI_INFO_NULL);
   MPI_File_read(infile, a, 10, MPI_DOUBLE, &statmpi);

   for (n=0;n<10;n++) {
      printf("%d   %lf\n", myid, a[n]);
   }

/* DO I REALLY HAVE TO DO ALL THIS: */
   MPI_File_get_position(infile, &foffset);
   MPI_File_get_byte_offset(infile, foffset, &current_file_pos);
   MPI_File_set_view(infile, current_file_pos, MPI_CHAR, MPI_CHAR, "native", MPI_INFO_NULL);
   MPI_File_read(infile, header, 6, MPI_CHAR, &statmpi);
   printf("%s\n",header);

/* DO I REALLY HAVE TO DO ALL THIS: */
   MPI_File_get_position(infile, &foffset);
   MPI_File_get_byte_offset(infile, foffset, &current_file_pos);
   MPI_File_set_view(infile, current_file_pos, MPI_DOUBLE, selector, "native", MPI_INFO_NULL);
   MPI_File_read(infile, a, 10, MPI_DOUBLE, &statmpi);

   for (n=0;n<10;n++) {
      printf("%d   %lf\n", myid, a[n]);
   }

   MPI_File_close(&infile);

   MPI_Finalize();

}


texts:
I am learning data structures, and have written an algorithm for insertion sort after learning from some sources. But I am confused which implementation is more correct or appropriate.
Code #1 This implementation takes an element and sorts itself with all the elements to its left, one by one, like bubble sort I think. I am just sorting and I think I can not say I am inserting an element to its correct location.

public static int[] insertionSortAsc(int[] elemArr){
    int len = elemArr.length;
    int temp;
    for (int i=0; i<= (len-2); i++){
        for (int j=(i+1); j>0; j--){
            if (elemArr[j] < elemArr[j-1]){
                //swap
                temp = elemArr[j];
                elemArr[j] = elemArr[j-1];
                elemArr[j-1] = temp;
            }
        }
    }
    return elemArr;
}

Code #2 This implementation takes an element into a 'temp' variable, compares it with left elements in the array and sorts them by comparing with the 'temp' element. When sorting stops, which means that the left side is sorted corresponding the 'temp' element, then this is element is put into that last location.

public static int[] insertionSort(int[] elements) {
        for (int i=1; i<elements.length; i++) {
            int j, elem_i = elements[i];
            for (j=i; j>0 && elements[j-1] > elem_i; j--) {
                elements[j] = elements[j-1];
            }
            elements[j] = elem_i;
        }
        return elements;
    }

I also have another idea though I have not written the code which I think matches my thought about the meaning of insertion sort.

Create an array, sortArr, of same size as that of input array.
Find the minimum element, and put that to sortArr[0]. If more elements with same value, put them into successive locations and maintain the count, means the index to which value is filled into sortArr. Put this minimum element to some tempMin variable.
Now check for another element in the original array which is just greater than tempMin, if found, replace the value of tempMin with this value, and then copy this to sortArr according to the filling count variable, increase the count thereby.
Repeat steps 2 and 3, until filling count variable reaches array length.
Exit.

I might be wrong but that is my thought. Please suggest algorithm modifications or my thinking if I am wrong.


texts: Is this an good OOP Design in MVC PHP for getting User Details?

texts:
I was given a API project by my co-worker to work on half created a system in slim PHP. The project consists of the Models and controllers. When the route is called it calls the Controller with the necessary function in the Controller, then query data from the database in Model functions and get back the response.

I want to know is this the correct way to implement OOP in PHP API applications? If not what are the changes and components I have to do to make it OOP MVC app?

User Controller -> UserController.php

public function getUser($request, $response, $args)
{
    $userId= $request->getAttribute('id');

    $user = $this->User->getUserById($userId);

    if (!$user) {
        return $response->withJSON([
          "error" => true,
          "message" => "cannot get user info",
          "data" => null
        ]));
    }

    return $response->withJSON([
        "error" => false,
        "message" => "cannot get user info"
        "data" => $user
    ]);
}

User Model -> User.php

public function getUserById($userId)
{
    $sql = "SELECT id, name, email
            FROM users
            WHERE id= :id";

    try {
        $stmt = $this->db->prepare($sql);
        $result = $stmt->execute([
            'id' => $userId
        ]);
        if ($result && $stmt->rowCount() == 1) {
            return $stmt->fetchAll()[0];
        } else {
            return false;
        }
    } catch (\PDOException $e) {
        $this->logger->info("cannot get user by id from DB " . $e);
        return false;
    }
}


texts:
Let's consider following function that return some risk levels enum type:

func calculateRiskLevel()-> ResultFirstLevels
{
    let result = self.result
    if result < 1
        {
            return .Level1
        }
    else if result >= 1 && result < 5
        {
            return .Level2
        }
    else if result >= 5 && result < 10
        {

            return .Level3
        }
    else
        {
            return .Level4
        }

}

I'm pretty sure there is a more clever way to achieve that.

I was thinking about a dictionary with some key-value coding, but how can I incorporate conditional statements within keys?

Could you suggest some "more professional" way to deal with such parsing with conditional statements?


texts: Scala code that loops through Java annotations decorating Scala classes

texts:
I have code written in Scala that reads annotations decorating other Scala classes. These annotations are written in Java. The sticking point is that annotations don't allow advanced data structures, and one of these annotations is a wrapper that contains an array of other annotations. This is where Scala starts throwing a fit. The following is my solution:

import java.util

import scala.collection.JavaConversions._
import scala.collection.mutable
import scala.io.Source

val line = "package.structure.leading.to.annotated.Class"
val anns = AnnotationUtils.getAllAnnotationsInheritted(Class.forName(line).newInstance.getClass)

var attributesMap = mutable.Map[String, Map[String, String]]()

for (ann <- anns) {
    if (ann.annotationType == classOf[Attributes]) {
      for (attr <- List(ann.asInstanceOf[Attributes].value)) {

        val i = new util.ArrayList[Attribute](asJavaCollection(attr))
        for (a <- i) {
          attributesMap += a.attributeName -> Map(
            "type" -> a.attributeType,
            "description" -> a.attributeDescription,
            "optional" -> a.attributeDescription(),
            "pattern" -> a.valueMatchPattern,
            "default" -> a.defaultValue,
            "options" -> asJavaCollection(a.attributeOptions).mkString(", "),
            "excludes" -> asJavaCollection(a.excludesAttributes).mkString(", "),
            "requires" -> asJavaCollection(a.requiresAttributes).mkString(", "),
            "someOf" -> asJavaCollection(a.someOfTheseAttributes).mkString(", "))
          println(asJavaCollection(a.attributeOptions).mkString(", "))
        }
      }
    }
  }

Most of the actual processing has been removed to highlight the part I'm finding really ugly.

The Attributes class is the wrapper annotation, and is declared like this:

@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Attributes {
    Attribute[] value();
}

Attribute is the class with the actual information and is defined like this:

@Repeatable(Attributes.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface Attribute {
    String attributeName();
    String attributeType();
    String attributeDescription();
    String valueMatchPattern() default ".*";
    String optional() default "false";
    String defaultValue() default "N/A";
    String [] attributeOptions() default {};
    String [] excludesAttributes() default {};
    String [] requiresAttributes() default {};
    String [] someOfTheseAttributes() default {};
}

I find the constant switching back and forth between Scala and Java datatypes to be terrible code and difficult to read. Is there a better way to do this?


texts:
I want to improve my code. Is it possible to get the plot without repeating the same instructions multiple lines?

The data comes from a Pandas' dataframe, but I am only plotting the last column (Total Acc.)

e=df['Total Acc'].round(4)*100

#The repetitions start:
row_awa = e.loc['AWA']
row_rem = e.loc['REM']
row_s1 = e.loc['S1']
row_s2 = e.loc['S2']
row_sws = e.loc['SWS']
row_stades = e.loc['stades']

#More repetitions
row_awa.plot()
row_rem.plot()
row_s1.plot()
row_s2.plot()
row_sws.plot()
row_stades.plot()

myLegend=plt.legend(bbox_to_anchor=(0., 1.2, 1., .102), prop ={'size':10}, loc=10, ncol=4,  #left, bottom, width, height
            title=r'TOTAL ACCURACY FOR MANY K-FOLD')                    #loc='center'
myLegend.get_title().set_fontsize('20')


texts:
Since the resources I found to learn are generally out-of-date, I'm having to read a lot of documentation, which makes the learning process somewhat haphazard. The module makes a simple character stack which can be read and written to by multiple processes.

#include<linux/init.h>
#include<linux/module.h>

#include<linux/fs.h>
#include<linux/types.h>
#include<linux/kdev_t.h>
#include<linux/cdev.h>

#include<linux/mutex.h>

#include<asm/uaccess.h>

#define MHELLO_STACK_SIZE 20

static int major;
static dev_t dev;
static struct cdev my_cdev;
static int count;
static DEFINE_MUTEX(lock);
static char stack[MHELLO_STACK_SIZE];
static int head;

static ssize_t hello_read(struct file* f,char* buf,size_t count,loff_t * offset)
{
    unsigned int res;
    printk(KERN_ALERT"R\n");

    mutex_lock(&lock);

    if(head<0)
    {
        mutex_unlock(&lock);
        return 0;
    }
    res=copy_to_user(buf,stack+head,1);
    head--;

    mutex_unlock(&lock);
    return 1;
}
static ssize_t hello_write(struct file* f,const char* buf,size_t count,loff_t * offset)
{
    unsigned int res;
    printk(KERN_ALERT"W\n");

    mutex_lock(&lock);

    if(head >= MHELLO_STACK_SIZE-1)
    {
        mutex_unlock(&lock);
        return -ENOSPC;
    }
    head++;
    res=copy_from_user(stack+head,buf,1);

    mutex_unlock(&lock);
    return 1;
}

static int hello_open(struct inode* inode,struct file* f)
{
    mutex_lock(&lock);
    count++;
    printk(KERN_ALERT"O %d\n",count);
    mutex_unlock(&lock);
    return 0;
}
static int hello_release(struct inode* inode,struct file* f)
{
    mutex_lock(&lock);
    count--;
    printk(KERN_ALERT"C %d\n",count);
    mutex_unlock(&lock);
    return 0;
}
const struct file_operations fops=
{
    .owner=THIS_MODULE,
    .read=hello_read,
    .write=hello_write,
    .open=hello_open,
    .release=hello_release
};

static int hello_init(void)
{
    int result=-1;

    mutex_init(&lock);
    mutex_lock(&lock);

    count=0;
    head=-1;

    result=alloc_chrdev_region(&dev,0,1,"mhello");

    if(result<0)
        printk(KERN_ALERT"Can't allocate major.\n");

    major=MAJOR(dev);
    printk(KERN_ALERT"Hello, my major no. is %d.\n",major);

    cdev_init(&my_cdev,&fops);
    my_cdev.owner=THIS_MODULE;

    cdev_add(&my_cdev,dev,1);

    mutex_unlock(&lock);
    return 0;
}
static void hello_exit(void)
{
    mutex_lock(&lock);
    unregister_chrdev_region(dev,1);
    cdev_del(&my_cdev);
    mutex_unlock(&lock);
    printk(KERN_ALERT"Goodbye world\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("foo");


texts: List replication problem from Hacker rank

texts:
Problem:

Given a list, repeat each element in the list n amount of times.

Solution:

def listReplication(num:Int,arr:List[Int]):List[Int] = {
      arr.flatMap(each => (1 to num).map(n => each))
}

Need review.


texts:
I need your help in OpenCV. I'm a student and am working on a project in which involves a little autonomous car. I use Python for the main programming language.

I have some problem with my meanshift.  When I run the program, I want the camera fixed on an area on the floor and stay on this area.  I would like for the car to drive alone while following the floor, and I don't want that meanshift to find another object different from the floor.

The program works well, but not optimally for the floor.  Do you have a solution or a way to proceed?

def camshift(frame1,frame2,trackWindow) :
    points=[]
    size1=frame1.shape[0] #width
    size2=frame1.shape[1] #length
    #hsv referentiel
    hsv = cv2.cvtColor(frame1, cv2.COLOR_BGR2HSV)
    #Mask
    mask = cv2.inRange(hsv,np.array((0., 60.,32.)), np.array((180.,255.,255.)))
    x0, y0, w, h = trackWindow

    trackWindow1=[x0,y0,w,h]
    x1 = x0 + w -1
    y1 = y0 + h -1

    hsv_roi = hsv[y0:y1, x0:x1]
    mask_roi = mask[y0:y1, x0:x1]
    #compute histogram for that area
    hist = cv2.calcHist( [hsv_roi], [0], mask_roi, [16], [0, 180] )
    #Normalisation
    cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX);
    hist_flat = hist.reshape(-1)
    points.append(hsv)
    prob = cv2.calcBackProject([hsv,cv2.cvtColor(frame2, cv.CV_BGR2HSV)],[0],hist_flat,  [0,180],1)
    prob &= mask
    term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
    #checking conditions not to go out of bounds
    if (trackWindow[0] < 0) :
        trackWindow[0] = 0
    if (trackWindow[1] < 0) :
        trackWindow[1] = 0
    if (trackWindow[0]+trackWindow[3] >= size1) :
        trackWindow1.append(size1-y0)
        w=trackWindow1[4]
        trackWindow1.pop()
    if (trackWindow[0]+trackWindow[2] >= size2) :
        trackWindow1.append(size2-x0)
        h=trackWindow1[4]
        trackWindow1.pop()
    x0, y0, w, h = trackWindow
    if (trackWindow[0]+trackWindow[2])<100 :
        trackWindow = (125,125,200,100)
    if (trackWindow[1]+trackWindow[3])<100 :
        trackWindow = (125,125,200,100)
    # self.ellipse, trackWindow = cv2.CamShift(prob, trackWindow, term_crit)

    new_ellipse, track_window = cv2.CamShift(prob,trackWindow, term_crit)
    #we draw the rectangle on the relevant area
     cv2.rectangle(frame1, (trackWindow[0],trackWindow[1]), (trackWindow[0]+trackWindow[2],trackWindow[1]+trackWindow[3]), color=(255,0,0))

    cv2.imshow("mask",mask)
    return track_window


texts: javascript for controllers of multiple audio tags

texts:
I am trying to learn to create controllers for my own HTML5 audio tags, which I often have several of on the same page. The js.jQuery code below is a simple beginning to this; it works to apply a play/pause button to each corresponding audio tag with a class of my_audio.

I'm a new coder though, so I imagine there are problems to my approach. Can anyone point out those problems, or suggest a more efficient way to do this?

(Btw, yes I know about jPlayer, etc. Just wanting to learn to do it myself :^)

$(document).ready(function(){

    $(".my_audio").each(function(index){
        $( this ).attr('id', "audioId" + index);
        var playPauseId = "playPause" + index;
        $( this ).after(
            '<div class="audio_controls_bar">\
                <button id="' + playPauseId + '">Pause</button>\
            </div>'
        );
        doAudios(index);
    });

});

function doAudios(index) {
    var audio, playbtn;
    function initializePlayer(){
    //set object references
        audio = document.getElementById("audioId"+index);
        console.log(audio);
        playbtn = document.getElementById("playPause"+index);
        console.log(playbtn)
    // add event listeners
        playbtn.addEventListener("click", playPause, false);
    }
    initializePlayer();

    function playPause(){
        if(audio.paused){
            audio.play();
            playbtn.innerHTML = "Pause";
        } else {
            audio.pause();
            playbtn.innerHTML = "Play";
        }
    }

}


texts: Program that prints out repetitions of 3 and 5

texts:
This works in my Eclipse, but I think there is a better way to do it.

public static void main(String args[]) {

       for(int i = 1; i < 101; i++)
       {
           if(i%3 == 0)
           {
           System.out.println("repetitive of 3");
           }

           else if(i%5 == 0)
           {
           System.out.println("repetitive of 5");
           }

           else{
               System.out.println(i);
           }

       }

   }

}


texts: reformatting string to two string values in javascript

texts:
I have the following code that converts a string that looks like aaa-bbb|ccc-ddd|eee-fff to two strings that look like aaa|ccc|eee and bbb|ddd|fff.

var id = "HEL-CAS|MAD-STO|XXX-YYY"
var splittedId = id.split('|');
var from = "", to = "";
$(splittedId).each(function(a,b) {
    from = from + b.split("-")[0]+"|";
    to = to + b.split("-")[1] + "|";
});
from = from.substring(0,from.length-1);
to = to.substring(0,to.length-1);

The code works fine, but I am wondering if it's possible to do this in fewer operations / or with faster runtime.


texts:
In this code, I'm getting the json from backend.  Once I find the json availability, I loop and make 5 columns.  Once the columns are made, I append after the legend of my form.

Can this be improved any further?

if(data.hasOwnProperty("allLocales")){

            var col0 = $("<fieldset />"),
                col1 = $("<fieldset />"),
                col2 = $("<fieldset />"),
                col3 = $("<fieldset />"),
                col4 = $("<fieldset />");

            $.map(data["allLocales"], function(value, i){

                var name = value.name;

                if(i % 5 === 0 ){
                    col0.append($("<label />").text(name).prepend($("<input type='checkbox' />").attr("value", name)));
                }else if(i % 5 === 1){
                    col1.append($("<label />").text(name).prepend($("<input type='checkbox' />").attr("value", name)));
                }else if(i % 5 === 2){
                    col2.append($("<label />").text(name).prepend($("<input type='checkbox' />").attr("value", name)));
                }else if(i % 5 === 3){
                    col3.append($("<label />").text(name).prepend($("<input type='checkbox' />").attr("value", name)));
                }else if(i % 5 === 4){
                    col4.append($("<label />").text(name).prepend($("<input type='checkbox' />").attr("value", name)));
                }

            })

            $("form legend").after(col0,col1,col2,col3,col4).end().find("span.submit").css({display:"block"});
        }


texts:
def getRandomNumbers(count, min, max)
  array = []

    while array.length < count
      tmp = rand(max) + min
      if array.include?(tmp)
        next
      else
        array.push(tmp)
      end
    end

  return array
end

def prettyPrint(someArray)
  string = ""
  someArray.each do |item|
    string += item.to_s + "\t"
  end
  puts string
end

array = getRandomNumbers(6, 1, 49)
prettyPrint(array)

I'm just learning Ruby and wrote this little two functions just to play around and get a feel for Ruby syntax etc.
I wanted a function that generates a given amount of random numbers within certain limits. In this example for 6 lottery numbers, therefore each number should only occur once. The second method is pretty self explanatory.

The code runs and does what he is supposed to do. However, what are nice tweaks and tricks to make this code nicer and utilizing the abilities of Ruby?


texts: Python algorithm to return all two-tuple permutations of numbers up to n

texts:
I have a Python function like so:
def get_values(n: int) -> list:
    """
    :param n: the maximum absolute value
    :return: sorted list of all the positive and negative permutations up to size n
    """
    if n < 0:
        return []

    if n == 0:
        return [(0, 0)]

    out = set()
    for i in range(0, n + 1):
        for j in range(0, i + 1):
            out.add((i, j))
            out.add((-i, j))
            out.add((i, -j))
            out.add((-i, -j))
    return sorted(out, key=lambda t: abs(t[0]))

The sorted at the end is important for my use case.
The issue is this uses a large amount of memory, presumably because it appends 4 values for every j. So as n becomes large, this set becomes very large.
I used a set rather than a list since I gathered it should take less memory by avoiding duplicates (I may be wrong :))
I would like to reduce the memory of this so can be large, up to 10,000 would be ideal but the bigger the better. Speed isn't really an issue here but faster is better!


texts: Looking for all numbers where each digit is bigger than the previous digit

texts:
This is the "Increasing Number problem", where we are looking for all numbers with \$n\$ digits where each digit is bigger than the digit before it. Or in Mathematical therms where:

$$\mathit{IncreasingNumber} = c_n \times 10^n + c_{n-1} \times 10^{n-1} + \cdots + c_1 * 10 + c_0$$

and \$c_i < c_{i-1}\$.

Examples: 123456789 or 123 or 569 or 139 or 45 or 12379. Goal: Give out all numbers that fullfill these properties depending on the number of digits \$n\$. This is my brute force code:

Sub AllIncreasingNumbers(N As Integer)
Dim Number As Long
Dim i As Long
Dim j As Integer
Dim lastdig As Integer
Dim remainder As Long
Dim thisdig As Integer

For i = (1 * 10 ^ (N - 1)) To 10 ^ (N)
    remainder = i
    lastdig = 0
    For j = (N - 1) To 0 Step -1
        thisdig = (remainder \ (10 ^ j))
        If Not (lastdig < thisdig) Then
        GoTo NotPass
        End If
        lastdig = thisdig
        remainder = remainder Mod (10 ^ j)
    Next j
    Debug.Print i
NotPass:
Next i
End Sub

If you haven't guessed it, it functions as following: go through all Numbers with N digits and check if they are increasing Numbers, if yes print them.

For \$n\$ = 2 to 6 it is reasonably fast but for \$n\$ = 8 or 9 it is really slow despite \$n=9\$ only having one solution 123456789. I think there could be a recursive algorithm to solve this but I can't figure it out. I used VBA because thats the language I am most familiar with but actually I am more intrested in the recursive algorithm to solve this. As soon as I have the algorithm I am able to implement it.


texts:
I read about how markov-chains were handy at creating text-generators and wanted to give it a try in python.

I'm not sure if this is the proper way to make a markov-chain.  I've left comments in the code.  Any feedback would be appreciated.

import random

def Markov(text_file):

    with open(text_file) as f:    # provide a text-file to parse
        data = f.read()

    data = [i for i in data.split(' ') if i != '']     # create a list of all words
    data = [i.lower() for i in data if i.isalpha()]    # i've been removing punctuation

    markov = {i:[] for i in data}    # i create a dict with the words as keys and empty lists as values

    pos = 0
    while pos < len(data) - 1:    # add a word to the word-key's list if it immediately follows that word
        markov[data[pos]].append(data[pos+1])
        pos += 1

   new = {k:v for k,v in zip(range(len(markov)), [i for i in markov])}    # create another dict for the seed to match up with

    length_sentence = random.randint(15, 20)    # create a random length for a sentence stopping point

    seed = random.randint(0, len(new) - 1)    # randomly pick a starting point

    sentence_data = [new[start_index]]     # use that word as the first word and starting point
    current_word = new[start_index]

    while len(sentence_data) < length_sentence:
        next_index = random.randint(0, len(markov[current_word]) - 1)    # randomly pick a word from the last words list.
        next_word = markov[current_word][next_index]
        sentence_data.append(next_word)
        current_word = next_word

   return ' '.join([i for i in sentence_data])


texts:
I have created a video/article slider. It works fine, but I have a feeling it's not quite a standard solution.

I would appreciate it if someone could review my code, so that if there are mistakes, I could learn from them.

Article 0

Article 1

Article 2

Article 3


texts: Setting controller, action, and values based on the number of URL chunks

texts:
Is there any way to improve this code? It looks a bit ugly for me.

if($url_chunks_num == 1) {
    $this->controller = $this->pageData[0];
} elseif($url_chunks_num == 2) {
    $this->controller = $this->pageData[0];
    $this->action = $this->pageData[1];
} elseif($url_chunks_num > 2) {
    $this->controller = $this->pageData[0];
    $this->action = $this->pageData[1];
    $this->values = array_slice($this->pageData, 2);
}

I thought about nested conditions, but this option is ugly as well.


texts:
I have this very ugly piece of code which runs ethtool and then parses the output (Lilex is just a static class encapsulating subprocess and is not relevant to the question. I'm looking for someone to suggestions to shorten the string manipulation.

        bash_command = "/sbin/ethtool -P " + identifier

        output = Lilex.execute_command(bash_command)

        mac_address = str(output)

        mac_address = mac_address.replace("Permanent address: ", "")
        mac_address = mac_address.replace("\\n", "")
        mac_address = mac_address.replace("'", "")
        mac_address = mac_address[1:].strip()

This is example output that is produced by ethtool -P:

Permanent address: 12:af:37:d0:a9:c8

I'm not sure why I'm replacing single quotes with nothing, but I'm sure I've seen the command output single quotes before, so that part needs to stay.

An alternative suggestion (which is actually not much different):

mac_address = mac_address \
                          .split(":")[1]\
                          .replace("\\n","") \
                          .replace("'","") \
                          .strip()


texts: Method to read the number of lines in a web page

texts:
Needing a way to read the number of lines on a web page for the purpose of a progress bar the following method is created:

private static int countPageLines(String url) throws IOException {
        URL page = null;
        BufferedReader in = null;
        int count = 0;

        try {
            page = new URL(url);
            in = new BufferedReader(new InputStreamReader(page.openStream()));

            while ((in.readLine()) != null) {
                count++;
            }
        } catch(IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
        }

        return count;
    }

Now, of course, it works but is it optimal? Can anything be done to improve the speed?
Java 8 is available, if pertinent.


texts:
I decided to make a random string generator for fun, and it works for the most part. Since I'm an amateur at programming, I thought I would post the code to get some feedback on it, and hopefully improve any bad habits.

#include <iostream>
#include <string>
#include <ctime>

typedef unsigned int uint;

std::string randomString(uint l = 15, std::string charIndex = "abcdefghijklmnaoqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
{
    // l and charIndex can be customized, but I've also initialized them.

    uint length = rand() % l + 1;
    // length of the string is a random value that can be up to 'l' characters.

    uint ri[15];
    /* array of random values that will be used to iterate through random
      indexes of 'charIndex' */

    for (uint i = 0; i < length; ++i)
        ri[i] = rand() % charIndex.length();
    // assigns a random number to each index of "ri"

    std::string rs = "";
    // random string that will be returned by this function

    for (uint i = 0; i < length; ++i)
        rs += charIndex[ri[i]];
    // appends a random amount of random characters to "rs"

    if (rs.empty()) randomString(l, charIndex);
    // if the outcome is empty, then redo the generation (this doesn't work, help?)
    else return rs;
}

int main()
{
    srand(time(NULL));
    std::cout << randomString() << std::endl;
}


texts:
I'm new to Susy and I'm loving it. I've been learning and trying a simple example - a simple grid that contains two columns at a fixed resolution of 320 pixels. One test would be to have two side by side columns (#x and #y) with gutter space in-between and another would be another two side by side columns (#a and #b) but without any gutter space in-between and they're both .

For the susy map, I've used .1334 for gutters and it all adds up to 320.01 pixels.

Questions

Is there a better way of defining the gutter space? having some decimals in 320.01 seems odd.
Is there a better way of getting #a and #b to be half widths without setting it to 160px and using no-gutters?
Is there an overall better way of writing this whole thing (maps, layouts, settings)?

The code

html {
    box-sizing: border-box;
}
*, *:before, *:after {
    box-sizing: inherit;
}

$susy: (
  math: static,
  columns: 2,
  gutters: .1334,
  column-width: 150px,
  global-box-sizing: content-box,
  debug: (
      image: show,
      color: rgba(#66f, .25),
   output: background
  ),
  use-custom: (
      box-sizing: true
  )
);

main {
    @include container(320px);
}

#x,
#y,
#a,
#b {
    border: solid 1px #000;
    float: left;
}

#x {
    @include span(1 of 2);
}

#y {
    @include span(1 of 2 last);
}

#a {
    @include span(160px no-gutters);
}

#b {
    @include span(160px last);
}

#z,
#c {
    @include span(2 of 2);
    border: solid 1px #000;
}

x

y

z

a

b

c

http://sassmeister.com/gist/d4b0d898d4a6c987f947


texts: HackerRank - Filter huge list for elements that occur more than a given number of times

texts:
I'm trying to solve this problem on HackerRank, which basically requires the solution to read an input like this (comments are mine)
3                      # the number of cases, each of which consists of a pair of lines below
9 2                    # case 1, the two numbers are N and K
4 5 2 5 4 3 1 3 4      # case 1, the N numbers; filter out those that occur less than K times
9 4                    # case 2
4 5 2 5 4 3 1 3 4      # case 2
10 2                   # case 3
5 4 3 2 1 1 2 3 4 5    # case 3

and the desired output is
4 5 3
-1
5 4 3 2 1

where the second line signifies that there's no number in case 2 which occurs 4 times or more, first and third lines list those elemnts of cases 1 and 3 which all occur the prescribed number of times or more (in this case the threshold is 2 for both case 1 and case 2).
I came up with an algorithmically correct solution, but apparently it has poor performance, as it fails for timeout on this input (expected output)
import Control.Monad (liftM2)
import Data.List (sort,groupBy)
import Data.List (foldl')
main :: IO()
main = do
  nCasesStr <- getLine
  let nCase = read nCasesStr :: Int
  sequence_ $ replicate nCase $ do
    firstLine <- getLine
    secondLine <- getLine
    let [_,k] = asInts $ firstLine
    let list  = asInts $ secondLine      -- LINE A
    let outList = processList k list
    if null outList
      then putStr $ show (-1)
      else mapM_ (putStr . (++" ") . show) outList -- LINE B
    putStrLn ""
    where
      asInt :: String -> Int
      asInt s = read s :: Int
      asInts :: String -> [Int]
      asInts = map asInt . words

processList :: Int -> [Int] -> [Int]
processList k = map fst . filter ((>= k) . snd) . foldl' step []
  where
    step acc@((n,c):ac) val
      | n == val = (n,c + 1):ac
      | otherwise = (n,c):step ac val
    step _ val = [(val,1)]

I'm especially worried about the lines marked as -- LINE A ad -- LINE B: they both traverse the full long input and output lines respectively; then the processList function traverses the input too. Traversing the input only once while spitting out output, however, would not change the BigO complexity, but just reduce it by a factor of 3, am I right?
As regards the processList function, I'm quite happy I had the idea of using a fold (the three of them don't seem to have a consistent difference in performances, as regards the bulk test cases), but maybe I've chosen the wrong stepping function?
Or maybe folding is not the right tool in this case?


texts: IComparable implementation for a class representing a version

texts:
I have an UpdateId class which represents some kind of version (like AssemblyVersion). UpdateId has three int values (listed in their compare priorities order): Year, ReleaseNumber and Revision.

How can I make my CompareTo method better? It looks clumpy to me.

public int CompareTo(object obj)
{
   if(obj == null) return 1;

   var updateId = obj as UpdateId;
   if (updateId != null)
   {
       int yearCompare = this.Year.CompareTo(updateId.Year);
       if (yearCompare == 0)
       {
           int releaseNumberCompare = this.ReleaseNumber.CompareTo(updateId.ReleaseNumber);
           if (releaseNumberCompare == 0)
           {
               return this.Revision.CompareTo(updateId.Revision);
           }

           return releaseNumberCompare;
        }

        return yearCompare;
    }
    else
    {
        throw new ArgumentException("Object is not an UpdateId");
    }
}


texts: Simple Sinatra app that acts as a webhook for an api.ai chatbot

texts:
I'm in the process of learning Ruby which I never used. I've built quite a few web applications in different languages, but this is my first time using Ruby. Things work, I enjoy writing Ruby, but I feel I might be missing some of its idioms.

This is a simple Sinatra app that acts as a webhook for an api.ai chatbot. The correctness of the code is probably irrelevant, I'd be interested in finding out possibilities of making the code more "Ruby like".

This is just the code for the webhook, I hope (?) the imported methods and classes are self-explanatory.

# frozen_string_literal: true
require 'json'
require 'sinatra'
require 'sinatra/json'
require './lib/helpers'
require './lib/database'
require './lib/config'

db_client = Database::Client.new
wakeup_response = Config::WakeupResponse.new

post '/:bot/webhook' do |bot|
  protected!

  session_id = params.fetch('sessionId', nil)
  if session_id.nil?
    return [400, 'No sessionId present in payload.']
  end

  user = db_client.find_one(bot, session_id)
  speech = infer_speech(params)

  if user && (currently_active?(params) || reset_intent?(params))
    db_client.update_one(
      bot,
      session_id,
      lastContext: params.fetch('result', {}).fetch('contexts', [])
    )
  elsif user
    speech = wakeup_response.get(bot)
  else
    db_client.insert_one(bot, session_id)
  end

  user = db_client.find_one(bot, params['sessionId'])

  json(
    speech: speech,
    displayText: speech,
    contextOut: user.fetch('lastContext', []),
    source: Config.source_name
  )
end

post '*' do
  [404, json(error: 'Not found')]
end

get '*' do
  [404, "I'm a bot, so what?"]
end


texts: Performing calculations with a catalog of stars

texts:
The point of my code is to:

Read in the observed data from the a catalog of stars (whitespace separated table).
Do some unit conversions on the observed data (math stuff).
Apply an interstellar correction factor to the observed data (more math).
Compare the scaled observed data to the DUSTY model data using the BC table, using a least-squares approach (comparison of observed data to theoretical models found in a large table).
Find the best fit models for the observed data (should be obvious).

I'm trying to rewrite 'spaghetti code' I was handed, that doesn't function quickly, nor does it allow for easy updating (adding different statistical calculations, etc.). I'm pretty new to Python, so I'm struggling with the idea of classes and this is my attempt at it.

class Stellar_setup:
    Fbol=5.01333e-10
    c=2.99792458e+8
    L=1000
    star_list=[]
    dusty_models=np.array([]) #Array of all the dusty models
    incoming_stars='' #List of incoming stars

    def __init__(self):
        """Initiates the below modules."""
        self.star_catalog()
        self.InputKey()

    def star_catalog(self):
        """Imports the star catalog"""
        try:
            star_catalog=raw_input('Input pathname of stellar catalog: ')
            star_list=[]
            with open(star_catalog) as incoming_stars:
                for line in incoming_stars.readlines():
                    x=[item for item in line.split()]
                    star_list.append(x) #Appends the individual star-IDs to the empty array star_list.
            print 'Stars imported successfully.'
        except IOError:
            print 'Star import unsuccessful. Check that the star catalog file-path is correct. Program exiting now.'
            sys.exit()

    def InputKey(self):
        """Imports the Input (.inp) file. Historically, InputUt.inp.
        Allows for definition of parameters which are utilized later in the script."""
        input_script=raw_input('Pathname of .inp file: ')
        InputKey=[]
        try:
            with open(input_script) as input_key:
                for line in input_key.readlines():
                    x=[item for item in line.split()]
                    InputKey.append(x)
            if InputKey[0][0]=='1' or InputKey[0][0]=='2':  #Checks to see if .inp file is valid or not by checking the first row/column which should be 1 or 2.
                print 'Your .inp file was successfully imported'
            else:
                print 'Your .inp file import failed. Check the validity of your file.\n Program exiting now.'
                sys.exit()
        except IOError:
            print 'The .inp file import was unsuccessful. Check that your file-path is valid.\n Program exiting now.'
            sys.exit()

    # You probably need to put a module here that pulls in the DUSTY tables.

if __name__=='__main__':
    Stellar_setup()

I was thinking about making about three other classes that:

Identify necessary attributes from the tables (pulling data from columns/rows)
Do analysis of information, and model/data comparison to find the best theoretical models that match up with the observed data. This uses a least-squares approach.

From what I understand classes can 'inherit' attributes from other classes. The way I think I understand this is that my class Stellar_setup will be inherited by my class Attribute_Identification (which haven't been written yet), and so on. I'm not sure if I'm going about this the right way, can anyone clear things up for me.


texts: Algebraic Effect Monad to separate pure and impure code

texts:
I want to write my C# code in a way which makes effects (state, I/O, etc) explicit in the type signature. I have started to understand monads, and have some acquaintance with algebraic effects, though not deeply so. I have attempted to implement a monad for working with algebraic effects in C#. The purpose is to allow you to provide an impure function which is an interpreter over an algebraic representation of your effects at the time that you run the monad, but not before. In theory this allows you to write all of your code in a pure way, and even pass a pure function in for the effects for the sake of unit testing etc. The monad is intended to be generic with respect to what types you use to represent your effects, and it is built with a struct in order to not be nullable.

public struct Eff<TOut, TIn, TReturn>
{
    private readonly Func<Func<TIn, TOut>,TReturn> _wrappedParameter;

    private Eff(Func<Func<TIn, TOut>, TReturn> wrappedParameter)
    {
        _wrappedParameter = wrappedParameter;
    }

    public static Eff<TOut,TIn,TReturn> Return(TReturn obj)
    {
        return new Eff<TOut,TIn,TReturn>(_ => obj);
    }

    public static Eff<TOut,TIn,TReturn> Do(TIn input, Func<TOut,TReturn> continuation)
    {
        return new Eff<TOut, TIn,TReturn>(f => continuation(f(input)));
    }

    public TReturn Run(Func<TIn, TOut> f)
    {
        return _wrappedParameter(f);
    }

    public Eff<TOut, TIn, TReturn2> Map<TReturn2>(Func<TReturn, TReturn2> g)
    {
        var wrappedParameter = _wrappedParameter;
        return new Eff<TOut, TIn, TReturn2>(f => g(wrappedParameter(f)));
    }

    public Eff<TOut,TIn,TReturn2> Bind<TReturn2>(Func<TReturn, Eff<TOut,TIn,TReturn2>> continuation)
    {
        var wrappedParameter = _wrappedParameter;
        return new Eff<TOut, TIn, TReturn2>(f => continuation(wrappedParameter(f)).Run(f));
    }
}

There are several things that could be brought up here (he concepts are so new with me that I have named things poorly; I haven't yet figured out how it would look to have multiple effect types playing together in your program; etc), but there's one thing in particular I am concerned about, which is that I am nervous that if an entire program were written inside this monad, it would have the potential to overflow the .NET stack. This is where I am most interested in getting a review. I believe that if you implement a computation expression in F# it ends up executing in a trampoline monad to keep the stack from overflowing. I am particularly concerned about this in a somewhat resource-constrained environment, say an old Windows CE device running Compact Framework 3.5 (which is actually a target platform for me).


texts: RxJS BehaviorSubject with asynchronous initial value

texts:
I am using RxJS to fetch a data structure from a server and cache it, but I also need to be able to overwrite the value locally (specifically, a user operation can change the server state, and the change takes effect locally without waiting for a round-trip communication)

Eventually I came up with this solution, where I am creating a pseudo-Subject object (AjaxSubject) which wraps a ReplaySubject with custom subscribe behaviour (specifically: loading the data from the server if no data exists locally yet).

I'm not particularly happy with it. Specifically I'm wondering if there is a better way to handle the use case of a BehaviorSubject with an asynchronous initial value (where as usual the request is not triggered until something subscribes).

I think the error handling also isn't great; I wrap data and errors in an object so that subscribers can get successful values after an initial failure (e.g. after a retry or setting it locally with next), but this seems clunky.

Can this be done using the RxJS standard operators? Or at least are there ways I can tidy it up?

import { ReplaySubject, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

function makeHttpError({ status }) {
  return (status >= 400) ? 'error ' + status : 'connection failed';
}

class AjaxSubject {
  constructor(url) {
    this.url = url;
    this.subject = new ReplaySubject(1);
    this.loaded = false;
  }

  next(data) {
    this.subject.next({ data, error: null });
    this.loaded = true;
  }

  subscribe(...args) {
    if (!this.loaded) {
      this.loaded = ajax(this.url)
        .pipe(
          map((data) => ({ data: data.response, error: null })),
          catchError((data) => of({ data: null, error: makeHttpError(data) })),
        )
        .subscribe((state) => {
          if (!state.error || this.loaded !== true) {
            this.subject.next(state);
            this.loaded = !state.error;
          }
        });
    }

    return this.subject.subscribe(...args);
  }
}

Update:

I found an alternative way to implement (almost) the same thing using RxJS builtins, but I don't know how I would (externally) trigger a retry with this one if loading from the server fails. I'm also not happy about the double-buffering (use of a BehaviorSubject and shareReplay).

import { BehaviorSubject, of } from 'rxjs';
import { switchMap, shareReplay, map, catchError } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

function makeHttpError({ status }) {
  return (status >= 400) ? 'error ' + status : 'connection failed';
}

function load(url) {
  return ajax(url).pipe(
    map((data) => ({ data: data.response, error: null })),
    catchError((data) => of({ data: null, error: makeHttpError(data) })),
  );
}

function ajaxSubject(url) {
  const subject = new BehaviorSubject(undefined);
  const observable = subject.pipe(
    switchMap((v) => ((v === undefined) ? load(url) : of(v))),
    shareReplay(1),
  );
  return { subject, observable };
}


texts:
Since hashing algorithms isn't something to mess around with as a beginner. Several howto's explain that one should use already made solutions.
Examples of such pages:

https://crackstation.net/hashing-security.htm
https://owasp.org/www-project-cheat-sheets/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2

So I opted for ready-made solutions from java.security and java.crypto library packages.
But I feel there is still room for messing up, especially with regard to the parameters in PBEKeySpec(password, salt, iterations, keyLength).

According to some HOWTOs, salt should be as long in bytes as the output from the hash function. So I chose 64, since SHA-512 outputs (64*8=512 bits) 64 bytes. (Although, it seems I can get larger output simply by increasing keyLength argument above 512, which makes me wonder).

So basically. Do you guys/girls find this code reasonable? Especially in regards to the arguments passed?
If not, please tell me what to change, how and why.

package my.application;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.apache.commons.codec.binary.Hex;

public class PasswordHasher {
    private int ammountOfBytes = 64;
    private int keyLength = 512;
    private int iterations = 100000;
    private byte[] salt;
    private byte[] hash;
    private char[] password;
    private String saltHex;
    private String hashHex;

    public void hash(String rawPassword) {
        makeSalt();
        password = rawPassword.toCharArray();
        PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keyLength);
        SecretKey key;
        try {
            SecretKeyFactory generator = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
            key = generator.generateSecret(spec);
            hash = key.getEncoded();
            hashHex = Hex.encodeHexString(hash);
            spec.clearPassword();
            key = null;
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }

    }

    public void destroy() {
        saltHex = null;
        hashHex = null;
        Arrays.fill(password, (char) 0);
        Arrays.fill(salt, (byte) 0);
        Arrays.fill(hash, (byte) 0);
    }

    private String makeSalt() {
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            salt = new byte[ammountOfBytes];
            random.nextBytes(salt);
            saltHex = Hex.encodeHexString(salt);
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return saltHex;

    }

    public String getSaltHex() {
        return saltHex;
    }

    public String getHashHex() {
        return hashHex;
    }

}


texts:
I'm currently taking an algorithm course in college. To find the maximum and minimum elements in an array, I'm using a divide and conquer algorithm. Please offer suggestions for this code snippet.  I get a headache reading only comments, so please give explanation with sample code.

#include<stdio.h>

#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))

int tempmax, tempmin;

/*
 * return a 2 element array
 * First element is highest of list
 * Second elements is lowest of list
 *
 */
int* maxmin(const int list[], const int low, const int high, int max, int min)
{
    int mid,max1,min1;
    static int maxAndMin[2]; // to hold the max and min value of list

    // list has only one element
    // so make max and min that element
    if (low == high)
    {
        max = list[low];
        min = list[low];
    }

    // list has two elements then
    // check for which one is greater or smaller
    // and check it with temp values and update
    else if (low == high-1)
    {
        if (list[low] < list[high])
        {
            tempmax = getMax(tempmax, list[high]);
            tempmin = getMin(tempmin, list[low]);
        }
        else
        {
            tempmax = getMax(tempmax, list[low]);
            tempmin = getMin(tempmin, list[high]);
        }
    }

   else
   {
       // if list is not small, divide list into sub-problems
       // Find where to split the set
       mid = (low + high) / 2;
       // Solve the sub-problems
       max1 = list[mid+1];
       min1 = list[mid+1];
       maxmin(list, low, mid, max, min);
       maxmin(list, mid+1, high, max1, min1);
       // Combine the solutions
       tempmax = getMax(tempmax, max1);
       tempmin = getMin(tempmin, min1);
   }

    maxAndMin[0] = tempmax;
    maxAndMin[1] = tempmin;
    return maxAndMin;
}

/*
 * returns the highest element between first and second
 *
 */
int getMax(int first, int second)
{
    return first > second ? first : second;
}

/*
 * returns the lowest element between first and second
 *
 */
int getMin(int  first, int second)
{
    return  first < second ?  first : second;
}

int main(void)
{
    int list[] = {10, 23, 24, 56, 67, 78, 90};
    int *values;
    int size = ARRAY_SIZE(list);

    tempmax = tempmin = list[0];
    values = maxmin(list, 0, size-1, list[0], list[0]);

    printf("The maximum value is = %2d \n", *values);
    printf("The minimum value is = %2d \n", *(values+1));
    return 0;
}


texts:
The calculator supports the basic operators (Add,Substract,Divide,Multiply).
At the moment,

It only works with positive integers
I do not validate my user input
My division rounds up if it isn't an integer

This is a work in progress. It is my first Python application so I want to get feedback before I keep on working on it.
Here is an example of how my calculator parses/processes an equation :

Given 3+3+9/3-4*2

Computing multiplications : 3+3+9/3-8 (Note that 4*2 is now 8)

Then divisions : 3+3+3-8 (9/3 = 3)

Then additions : 9-8 (3+3+3 = 9)

Finally substractions : 1 (9-8 = 1)

import operator

priorizedOperators = operator.getPriorizedOperators()

def calculate(args):
    return _calculate(args,0)

def _calculate(equation, operatorArrayIndex):

    if len(priorizedOperators) == operatorArrayIndex:
        return equation;

    arithmeticOperator = priorizedOperators[operatorArrayIndex]
    copiedEquation = equation

    try:
        operatorLocation = copiedEquation.index(arithmeticOperator.getStringSign())

        while True:
            leftBound = _findLeftBound(equation,operatorLocation)
            rightBound = _findRightBound(equation,operatorLocation)

            leftValue = int(copiedEquation[leftBound:operatorLocation])
            rightValue = int(copiedEquation[operatorLocation+1:rightBound])

            temp = arithmeticOperator.operate(leftValue,rightValue)

            #Replaces the part of the equation we just computed by the result
            copiedEquation = copiedEquation[:leftBound] + str(temp) + copiedEquation[rightBound:]

            #This will throw an exception if index doesn't find the operator, which ends the while loop
            operatorLocation = copiedEquation.index(arithmeticOperator.getStringSign())
    finally:
        return _calculate(copiedEquation, operatorArrayIndex + 1)

def _findLeftBound(equation ,operatorIndex):
    for leftBoundSearchIndex in reversed(range(0,operatorIndex)):
        if not _isNumber(equation[leftBoundSearchIndex]):
            return leftBoundSearchIndex + 1

    return 0

def _findRightBound(equation, operatorIndex):
    for rightBoundSearchIndex in range(operatorIndex+1, len(equation)):
        if not _isNumber(equation[rightBoundSearchIndex]):
            return rightBoundSearchIndex

    return len(equation)

def _isNumber(char):
    return ord("0") <= ord(char) <= ord("9")

def main():
    equation = input("Enter equation : ")
    print(calculate(equation))

if __name__ == "__main__": main()

Content of the operator.py
class PlusOperator():
    def getStringSign(self):
        return "+"

    def operate(self,left,right):
        return left + right

class MinusOperator():
    def getStringSign(self):
        return "-"

    def operate(self,left,right):
        return left - right

class MultiplyOperator():
    def getStringSign(self):
        return "*"

    def operate(self,left,right):
        return left * right

class DivideOperator():
    def getStringSign(self):
        return "/"

    def operate(self,left,right):
        return left // right

def getPriorizedOperators():
    return [MultiplyOperator(),DivideOperator(),PlusOperator(),MinusOperator()]

I'm looking to know if my python is okay and if my algorithm makes sense.


texts:
I created a script to automate the task of uploading a CSV file to Box. I have a couple of files a Box client and a MySQL client. I create an instance of both on the function.rb file which is the one below. I wonder if there is anything to improve? if there are principles I'm not following or if I'm breaking best practices.
Is there anything that can be improved?
require 'json'
require 'date'
require 'dotenv/load'
require 'fileutils'
require 'csv'
require 'logger'
require './my_sql'
require './box_api'
require 'pry'

begin
  year = ARGV[0]
  month = ARGV[1]
  day = ARGV[2]

  search_timestamp = Time.new(year, month, day).utc

  db_client = MySQL.new(search_timestamp)

  emails = db_client.get_emails_from_db
  return 'No new emails found' if emails.entries.empty?

  box = BoxApi.new(ENV['BOX_USER_ID'])

  date = DateTime.now.strftime("%m-%d-%Y").to_s
  file_name = "access-emails-#{date}"

  CSV.open("./tmp/#{file_name}.csv", "wb") do |csv|
    emails.entries.each do |entrie|
      csv << [entrie.values[0], entrie.values[1]]
    end
  end

  box.upload_file_to_box("./tmp/#{file_name}.csv", file_name, ENV['BOX_FOLDER_ID'])

  FileUtils.rm("./tmp/#{file_name}.csv")

  puts "successfully uploaded CSV file to Box"
rescue StandardError => e
  logger = Logger.new(STDOUT)
  logger.level = ENV.fetch('LOG_LEVEL', Logger::INFO)
  logger.datetime_format = '%Y-%m-%d %H:%M:%S '
  logger.error("msg: #{e}, trace: #{e.backtrace.join("\n")}")
end


texts:
This code is a chunk of big project, so I am sorry in advance for not adding everything as it's just not possible.

[DataContract]
public class Companionship
{
    [DataMember]
    public int ID;
    [DataMember]
    public string ClientID;
    [DataMember]
    public string UserSID;
    [DataMember]
    public string Role;
    [DataMember]
    public string Status;
    [DataMember]
    public string StartDate;
    [DataMember]
    public string EndDate;
    [DataMember]
    public bool AddedInBP;

    public int Add(Companionship pC)
    {
        int clientID = -1;
        var gda = new USDataAccess();
        if (string.IsNullOrEmpty(pC.ClientID))
            clientID = new gDataAccess().GetClientByURL(SPContext.Current.Web.Site.Url).ClientID;
        else
            clientID = Convert.ToInt32(pC.ClientID);

        pC.Status = "Active";
        DateTime? dtEnd = string.IsNullOrEmpty(pC.EndDate) ? (DateTime?)null : DateTime.Parse(pC.EndDate);
        DateTime dtStart = string.IsNullOrEmpty(pC.StartDate) ? DateTime.Now : DateTime.Parse(pC.StartDate);
        gda.AddCompanionship(clientID, pC.UserSID, pC.Role, pC.Status, dtStart, dtEnd);
        new DirectoryGroup().Add(clientID, pC.UserSID, "ChangeMe In Companionship");

        var cDetails = new Company().Get(clientID);
        if (cDetails != null && !string.IsNullOrEmpty(cDetails.CompanyID) && pC.AddedInBP)
        {
            SendApprovalRequest();
        }

        return 1;
    }

    public int AddCollection(Companionship[] pCs)
    {
        foreach (var c in pCs)
            this.Add(c);

        return 1;
    }

    private void SendApprovalRequest()
    {
        string url = "https://portal.gov.com/CompanyManagement/_vti_bin/sync/sync.svc";
        ICSync ws = Utils.GetProxy<ICSync>(url);

        var user = Utils.ADUserToObject(ADUser.LoadBySid(this.UserSID));
        user.Companionships[0] = this;
        var dd = Utils.UserToDirectoryGroupDetails(user);

        ws.AddDirectoryGroup(SPContext.Current.Web.Site.Url, SPContext.Current.Web.CurrentUser.Email, dd);
    }
}

This code is in a utilities project, it's called from WCF services to interact with Companionships, it adds them to the database with some business logic and sends a message to another web service.

Looking at the structure I think this can be improved.

I am calling it like this:

 new Companionship().AddCollection(pCPs);

I am more worried about the way I am interacting with Companionship class.


texts: Converting a double to a std::string without scientific notation

texts:
Problem

I need to convert a double to a std::string which contains no scientific notation and no unnecessary fillers.

Using std::fixed with iostream yielded ugly results - extra fillers (0's).  The closest working code I could get was to using sprintf("%g",...) and then dealing with exponentials, should they appear (beyond 6 places).

I am looking for improvements in robustness or clarity/simplicity in the implementation.

Details/Elaboration (addition)

I realize that the conversion between double and std::string and back can be expected to be lossy.  So I am not looking for an implementation that works for all cases.  For example, I don't expect to be able to convert "0.2000" to double and then get the same back (getting "0.2" back would be fine).  Similarly with "+0.2000": getting "0.2" back is ok.

I have attempted solutions involving sprintf("%g",...), but the result is automatic conversion to scientific notation when we go beyond six significant digits.  There appears to be no way to configure that setting.  Alternatively, sprintf("%f",...) requires that we manually set or calculate the exact precision that we want - which I don't know how to do if that information is lost inside a double.  Note that what I have found here seems to equally apply to most simple solutions involving  std::iostream and std::fixed.

#include <iostream>
#include <cstring>
#include <string>
#include <cassert>

static std::string
to_string( double d )
{
  char s[64];
  sprintf( s, "%g", d );

  char* e = std::strchr( s, 'e' );
  if ( e==nullptr )
    return s;
  char* p = std::strchr( s, '.' );

  // eg 2.4e-07
  int exp   = atoi( e+1 );   // -7
  int extra = 0;

  // snip period eg 24
  if ( p!=nullptr ) {
    extra = e-p-1;
    memmove( p, p + 1, strlen(s) - (p-s));
  }

  int coeff = atoi( s );
  // std::cerr << "DEBUG  = " << s << " coeff = " << coeff << " exp = " << exp << "\n";
  if ( exp<0 ) {
    sprintf( s, "0.%0*d", -exp+extra, coeff);
    return s;
  }

  // eg 7.3e+09
  sprintf( s, "%d%0*d", coeff, exp-extra, 0 );
  return s;
}

static void
test_string_conversion( std::string const& s )
{
    assert( to_string( atof( s.c_str() ))==s );
}

int main()
{
   test_string_conversion( "1.5203" );
   test_string_conversion( "-1.025" );
   test_string_conversion( "3.1415" );
   test_string_conversion( "-38271" );
   test_string_conversion( "0.8382" );
   test_string_conversion( "-0.8382" );
   test_string_conversion( "7" );
   test_string_conversion( "-3" );
   test_string_conversion( "0.0000024" );
   test_string_conversion( "7300000000" );
   return 0;
}


texts: Crossover and Mutation functions for Genetic Algorithm

texts:
I'm writing a decryption algorithm using GA with crossover and mutation. My performance is (very) poor, often stagnating early or converging to the incorrect solution. I just want some other people to look at my crossover and mutation methods to see if something is amiss.

Note: crossRate and mutatRate are the crossover and mutation rates respectively and are within the range of [0.00, 1.00]. options is a string of valid genes.

/**
 * method to perform crossover on chromosome
 * @param m - the first parent
 * @param f - the second parent
 * @return - a crossovered chromosome string
 */
private String crossChromosome(String m, String f) {
    StringBuilder chrString = new StringBuilder();
    // if crossover procs
    if (rnd.nextInt(100) < crossRate*100) {
        /**
         * to avoid full reduplication of chromosome
         * set the bound to 2..len-2 otherwise you could
         * get duplication of parent, bypassing crossover entirely
         */
        int crossPoint = rnd.nextInt(m.length()-2)+2;
        // when 2P is used, need a second pivot
        int nextCrossPoint = rnd.nextInt(m.length()-crossPoint)+crossPoint;
        boolean condition;
        for (int i = 0; i < f.length(); i++) { // for each gene
            if (crType == 1) {
                /**
                 * if one point crossover, find one point
                 * in the chromosome where genes before that
                 * point are from parent1 and after, from parent2
                 */
                condition = (i < crossPoint);
            } else {
                /**
                 * if two point, however, find two pivot points
                 * and go F,M,F based on the pivot points
                 */
                condition = (i < crossPoint || i >= nextCrossPoint);
            }
            if (condition) {
                chrString.append(f.charAt(i));
            } else {
                chrString.append(m.charAt(i));
            }
        }
    } else {
        // if no crossover is happening, random parent is used
        return (rnd.nextInt(2) == 1) ? f : m;
    }
    // return the crossovered chromosome
    return chrString.toString();
}

/**
 * method to mutate a chromosome with random genes
 * @param k - the input chromosome
 * @return - the mutated chromosome
 */
private String mutateChromosome(String k) {
    StringBuilder chrString = new StringBuilder();
    for (int i = 0; i < k.length(); i++) { // for each gene
        // if mutation procs
        if (rnd.nextInt(100) < mutatRate*100) {
            // assign a random gene as mutation
            chrString.append(options.charAt(rnd.nextInt(27)));
        } else {
            // otherwise, use verbatim
            chrString.append(k.charAt(i));
        }
    }
    return chrString.toString();
}

There's option of 1-point and 2-point crossover in there.


texts: Rails thin controller method to change account plan and fire slack message via a service object

texts:
I'm a beginner with Rails and am trying to figure out how to keep my controllers clean and thin, and how to work with service objects. I am building an internal tool to manage our SaaS customers, and the specific feature I'm building is to allow admins to change a customer's plan.

In accounts_controller.rb, I have the following method:

def change_plan
  account = Account.find(params[:id])

  old_plan = account.plan
  new_plan = Plan.find(params[:account][:plan_id])

  account.change_plan!(params[:account][:plan_id])

  SlackService.new.plan_change(current_user, account, old_plan, new_plan).deliver
  redirect_to action: "show", id: params[:id]
end

My first question is around the lines 2 and 3 of the method. Is there some place I should be moving this logic? Some sort of SlackService container object? Or should the SlackService method itself be handling the retrieval of the old_plan and new_plan? I realize this is fairly trivial but would love to build it properly.

Here's the code for the SlackService itself, heavily inspired by this article:

require 'net/http'

class SlackService
  NAME_AND_ICON = {
    username: 'Dashboard',
    icon_emoji: ':bat:'
  }

  SLACK_WEBHOOK_URL =  "https://hooks.slack.com/services/###/###/###"
  SLACK_WEBHOOK_CHANNEL = Rails.env.production? ? "###" : "###"

  def initialize(channel = SLACK_WEBHOOK_CHANNEL)
    @uri = URI(SLACK_WEBHOOK_URL)
    @channel = channel
  end

  def plan_change(user, account, old_plan, new_plan)
    params = {
      attachments: [
          {
            author_name: "#{user.first_name} #{user.last_name}",
            text: "Account: #{account.name} (#{account.id})",
            title: 'Dashboard Plan Change',
            fields: [
              {
                title: 'Old Plan',
                value: "#{old_plan.name} (#{ActionController::Base.helpers.number_to_currency(old_plan.price)})",
                short: true
              },
              {
                title: 'New Plan',
                value: "#{new_plan.name} ($#{ActionController::Base.helpers.number_to_currency(new_plan.price)})",
                short: true
              },
            ]
          }
        ]
    }
    @params = generate_payload(params)
    self
  end

  def deliver
    begin
      Net::HTTP.post_form(@uri, @params)
    rescue => e
      Rails.logger.error("SlackService: Error when sending: #{e.message}")
    end
  end

  private

  def generate_payload(params)
    {
      payload: NAME_AND_ICON
        .merge(channel: @channel)
        .merge(params).to_json
    }
  end
end

It seemed that I had to require net/http here in the service, but wasn't sure if that was the proper place for it.
I think the SLACK_WEBHOOK_URL and SLACK_WEBHOOK_CHANNEL constants should be defined here.
I see many examples of services where the methods are class level, but it seemed to make sense to keep it instance level so you can define the channel on instantiation.
Tying in with the above, the plan_change method accepts 4 params, but not sure if there's a cleaner way.
Wasn't sure if my approach to loading the NumberHelper is correct.