texts: Restricting user to one open tab in browser

texts:
I had a requirement to restrict my web site's users to just one open tab in the browser. I am aware that this is not the best thing to do in terms of general user experience guidelines, but it's an internal application that doesn't play well with such a scenario so I had to do it.

The following is what I came up with:

function IsNewTab() {
  return $.cookie('TabOpen');
}

$(function() {
  if (!IsNewTab()) {
    $.cookie('TabOpen', "YES", {
      path: '/'
    });
    $(window).unload(function() {
      $.removeCookie('TabOpen', {
        path: '/'
      });
    });
  } else {
    alert('already some tab open')
      //OR
      //window.close()
  }
});

I'd like opinions on the above. Are there any loopholes (keeping in mind that the target audience isn't too technical and probably won't go hacking around with the browser console). Are there any possible improvements that can be made?


texts: Perl 6 oneliner to sum up all numbers in a text file

texts:
The task is to sum up scores mentioned in a text file. Scores are floating point numbers as defined by the regexp float immediately preceded by a * character to distinguish them from other numbers in the text. Scientific notation is not permitted.

Example input

Day 1:
  Task 1: *5 Task 2: *2,8
  Task 3 was the hardest, your score is *-1
…

The expected sum here is 5 + 2.8 - 1 = 6.8.

my $sum = 0;

my regex float {
                 (<[+-]>?)          # opt. sign
                 (\d+)              # whole part
                 [(<[.,]>)(\d*)]?   # opt. fractional part;
                                    #   comma is a valid separator
               }

for slurp.match( / \* <float> /, :g ) {
  my $f = $_<float>;
  # justification for the next line:
  #  +"5," Cannot convert string to number: trailing characters after number
  #  +"5." Cannot convert string to number: radix point must be followed by one or more valid digits
  $sum += +"$f[1]$f[2].$f[4]0"
}

say $sum;

The code works, but it prints out a large number of warning messages

use of uninitialized value of type Any in string context

I would like to hear suggestions how to write this in a more idiomatic Perl.

In addition, I would like to hear how to make it more an one liner since I guess the code might be written with significantly less lines and still be readable.


texts: Is my JavaScript test actually testing anything worthwhile here

texts:
Given a production module like this:

function ($) {
   var
    showForm = function () {
        $.get(url, function (html) {
            $('body').append(html);
        });
    };

   return {
       showForm: showForm
   };
});

I have written the following unit test:

it("calling showForm appends html to existing page", function () {

    var testPage = $('

');
    var expectedPage = $('

');
    var htmlToAppend = $('');

    var callback = function () { return testPage.append(htmlToAppend); }

    sinon.stub(presenter, "showForm").yields(testPage);

    presenter.showForm(callback);

    expect(testPage.html()).to.equal(expectedPage.html());
});

I am trying to test that when presenter.showForm is called, the returned html is appended successfully appended.  Problem is, I'm not usre if it's a valid test as pretty much everything is fake.

I'm toying with the idea of abstracting out the call to $('body').append(html); to another public function of the module or perhaps even to another module so that
the call presenter.showForm(callback); can use the real function but I'm not sure?

I hope that all makes sense.

Can someone review and advise please?


texts: Making a copy constructor more flexible for ADT queue

texts:
I have constructed a copy constructor for an ADT queue. The copy constructor works fine. I would want to improve my code, but I don't really know how to shorten it to make it more flexible.

template <typename T>
Queue <T>::Queue(const Queue & other)
{
    if (other.first == nullptr)
    {
        first = nullptr;
        nrOfElements = 0;
    }

   else
   {
    Node* saveFirst;
    Node* walker;
    first = other.first;
    walker = new Node(first->data);
    saveFirst = walker;
    while (first->next != nullptr)
    {
        walker->next = new Node(first->next->data);
        walker = walker->next;
        first = first->next;
    }
    walker->next = nullptr;
    first = saveFirst;
    }
this->nrOfElements = other.nrOfElements;
}

The class Queue also contains an inner private Node class which contains the pointers first, next, etc:

private:
    int nrOfElements;
    class Node
    {
    public:
        Node* next;
        T data;
        Node(T data)
        {
            this->data = data;
        }
    };
    Node* first;

So, I would appreciate any suggestions/examples of how the copy constructor code above could be improved, as I'm a bit lost on the task.


texts:
For a class, I need to ask the user for a double. To verify that the number can be safely passed to Double.parseDouble, I wrote the following function. I'd like to have it heavily scrutinized; including the comments.

Are my comments helpful? They're more directed towards the marker than a maintainer down the road. Should I phrase them this way if it's for a class, and not "real code" that will need to be maintained later?
Is my assertion about the nature of charAt correct? Should I be caching str.charAt(i) in the loop?
I was rather proud of the first validity check, but found it to be kind of ugly when I looked at it the next day. Is there any better way that it could be written?
Anything else that could be improved. Be critical please!

As @h.j.k pointed out, this would be entirely easier by just catching the exception that Double.parseDouble throws, but there's no fun in that! I wanted the exercise.

    import static java.lang.Character.*;

    public static boolean strIsNumeric(String str) {
        //If the string is empty, or if it isn't a '-' or digit, return false.
        //We need a check like this or a prefixed '-' will prevent it from
        // being recognized as a negative number.
        //This is safe because logical-OR "short-circuits", the right hand will only
        // evaluate if the left is false. If this wasn't the case, the calls to "charAt(0)"
        // would cause an exception on empty String.
        if ( str.isEmpty() || (str.charAt(0) != '-' && !isDigit(str.charAt(0))) ) {
            return false;
        }

        //We're skipping the first char since it was checked above.
        boolean foundADecimal = false;
        for (int i = 1; i < str.length(); i++) {
            //To avoid repeated evaluations
            char c = str.charAt(i);

            //Check to see if there's at most 1 decimal
            if ( !foundADecimal && c == '.' ) {
                foundADecimal = true;

                //We've "verified" this char already as a valid decimal point,
                // so we need to skip the next "isDigit" check.
                continue;
            }

            if ( !isDigit(c) ) {
                return false;
            }
        }

        return true;
    }


texts: Calculating which direction my enemy should face when moving

texts:
I have just implemented an algorithm which calculates the direction an enemy in my game should face when moving to a location.

This is a 2D game where characters can face in one of four directions: (Up, Down, Left, Right).

When navigating to a point, if the new point is further away on the X axis than the Y axis, the enemy should show it's left or right animation.  However, if the movement would take the enemy more along the Y axis than the X axis, the enemy should show it's up or down animations.

To put it visually, the center of the X in the following image illustrates the position of my enemy on an coordinate plane.  Depending on which quadrant his movement point is placed in, the respective animation for that quadrant should be shown.

Here is my implementation.  My questions are:

Does this algorithm accomplish what I am thinking it does? From watching it on my enemy, it looks good so far, however I could just be getting lucky!
Can this algorithm be improved in any way?

protected FacingDirections CalculateFacingDirection(Vector2 navPos)
{
    Vector2 curPos = transform.position;

    float xDiff = Mathf.Abs(navPos.x - curPos.x);
    float yDiff = Mathf.Abs(navPos.y - curPos.y);

    if(navPos.x > curPos.x) //we are moving left
    {
        if(navPos.y > curPos.y) //we are moving up
        {
            return xDiff > yDiff ? FacingDirections.Left : FacingDirections.Up; //are we moving more left or up?
        }

        return xDiff > yDiff ? FacingDirections.Left : FacingDirections.Down; //are we moving more left or down?
    }
    else //we are moving right
    {
        if (navPos.y > curPos.y) //we are moving up
        {
            return xDiff > yDiff ? FacingDirections.Right : FacingDirections.Up; //are we moving more left or up?
        }

        return xDiff > yDiff ? FacingDirections.Right : FacingDirections.Down; //are we moving more left or down?
    }
}


texts: How to code a minimization problem with constraints and indices into PSO within MATLAB?

texts:
I have a GAMS code that represent a mathematical model which depends delay (i,p) for each job i and the period of day p. So, I have indices for represent delay and objective is minimizing of summing these delays.
Constraints example..
The structure in GAMS:
constraint(this part means constraint covers each indice in this part)$(if condition structure)..
        (constraint function is here)

The model constraint example:
*jobstart, delay: variables
*readytime, distance_oven and speed_cookline: parameters

constraint1(i,j,u,p)$(param1(j,u)>0 and j=param2(i) and p = param3(i))..
     jobstart(i) = readytime(i) + (distance_oven(j,u)/(speed_cookline(j,u)))*3600 + delay1(i);

constraint2(i,i2,j,j2,u,u2)$(i<>k and j=param2(i) and n=param2(i2) and param1(j,u) = 1 and param1(j2,u2) = 1 and u=u2)..
     abs(jobstart(i) - jobstart(i2)) => 120

objective function: min sum(delay1(i,p))

Is there a ready-structure to solve the problem or do I have to code it as heuristic then implement this code into the PSO?
*I asked that because I define simulated annealing for another problem by approaching it as heuristic and then implement it into the simulated annealing. But, it is so exhaustive and not effective coding to control constraints for assigned random delays in the way of PSO coding.
Thanks,


texts:
I'm just wondering if the following is the best way to write a dao function.  Should I get the entity manager before the transaction and close it after the transaction every time?  Should I write transactions inside a dao?

public void sendBack(Long requestId,String comments){
    EntityManager em = getEntityManager();
    em.getTransaction().begin();
    String update = "update CsRequestReceivers set activeInd = :activeInd,sendBackComments=:comments where requestId = :requestId and activeInd = :oldActiveInd";
    em.createQuery(update).setParameter("activeInd", 0l)
                          .setParameter("comments", comments)
                          .setParameter("requestId", requestId)
                          .setParameter("oldActiveInd", 1l)
                          .executeUpdate();
    em.getTransaction().commit();
    em.close();
}


texts:
I just started with Elixir and this is what I have now. Is there an easier or better way to write this?

defmodule GroupBySum do
  def sum(col), do: sum(%{}, col)
  defp sum(r, [h|t]) do
    {k, v} = h
    r = r |> Dict.update(k, v, fn(val) -> val + v end)
    sum(r, t)
  end
  defp sum(r, []), do: r
end

list = [a: 1, b: 2, c: 3, a: 2, b: 1, c: 0]
IO.inspect GroupBySum.sum(list) #%{a: 3, b: 3, c: 3}


texts:
I was working on 3sum problem on leetcode
Question
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4]
A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

My Solution
var threeSum = function(nums) {
    let out = []
    let seen = {}
    for(let i = 0; i < nums.length; i++){
        remainingArr = nums.filter((d,id) => id != i);
        //Calling twoSum on remaining array
        twoSum(remainingArr, -nums[i], out, seen)
    }
    //Return in expected format by splitting strings and forming arrays
    return out.map(d => d.split(',')).filter(d => d.length > 0)
};

var twoSum = function(nums, target, out, seen){
    let myMap = {}
    for(let i = 0; i < nums.length; i++){
        if(myMap[target - nums[i]] != undefined){
            //If match found convert it to string so that we can test for dupicates
            let val = [target - nums[i], nums[i], -target].sort((a,b) => a - b).join(',');
            //Test for duplicates
            if(!seen[val]) {
                out.push(val)
                seen[val] = true
            }
        }
        myMap[nums[i]] = i;
    }
}

The above solution fails for last 2 very large test cases.
For the 2sum implementation I have used the hash map solution rather than 2 pointers.
According to solutions on leetcode I can see the best possible time complexity here is \$O(N^2)\$. But isn't my solution also \$O(N^2)\$ (as i'm using seen map inside the inner loop).
How can I optimize this further?


texts: Identifying the closest player to an internal 2D grid

texts:
I've written a function that returns which player is closer to a given 2D grid within a larger 2D grid. I would like to make the function shorter (in LOC) and better. I would appreciate any advice on this topic.
it gets location for both players(x and y) and same for the carpet(the smaller grid), and than calculate the distance b/w each player to the carpet. the reason it takes so much if's is because i'm calculating x from x and y from y, and if the player is on the far side of x/y i have to add size to compassion. that's why i have an if for every corner plus if player is in the range of y/x
public static int getWhoIsCloser(
      int xFirstPlayer,
      int yFirstPlayer,
      int xSecondPlayer,
      int ySecondPlayer,
      int xCarpet,
      int yCarpet,
      int size) {

    size = size - 1;
    int xFirstPlayerProximity = 0;
    int yFirstPlayerProximity = 0;
    int xSecondPlayerProximity = 0;
    int ySecondPlayerProximity = 0;
    int firstPlayerResult;
    int secondPlayerResult;

    if (xFirstPlayer >= xCarpet && xFirstPlayer <= xCarpet + size) {
      yFirstPlayer -= (yCarpet + size);
      firstPlayerResult = Math.abs(yFirstPlayer);
    } else if (yFirstPlayer >= yCarpet && yFirstPlayer <= yCarpet + size) {
      xFirstPlayer -= (xCarpet + size);
      firstPlayerResult = Math.abs(xFirstPlayer);
    } else {
      if (xFirstPlayer < xCarpet && yFirstPlayer < yCarpet) {
        xFirstPlayerProximity = xFirstPlayer - xCarpet;
        yFirstPlayerProximity = yFirstPlayer - yCarpet;
      } else if (xFirstPlayer < xCarpet && yFirstPlayer > yCarpet) {
        xFirstPlayerProximity = xFirstPlayer - xCarpet;
        yFirstPlayerProximity = yFirstPlayer - (yCarpet + size);
      } else if (xFirstPlayer > xCarpet && yFirstPlayer < yCarpet) {
        xFirstPlayerProximity = xFirstPlayer - (xCarpet + size);
        yFirstPlayerProximity = yFirstPlayer - yCarpet;
      } else if (xFirstPlayer > xCarpet && yFirstPlayer > yCarpet) {
        xFirstPlayerProximity = xFirstPlayer - (xCarpet + size);
        yFirstPlayerProximity = yFirstPlayer - (yCarpet + size);
      }
      firstPlayerResult = Math.abs(xFirstPlayerProximity) + Math.abs(yFirstPlayerProximity);
    }
    if (xSecondPlayer >= xCarpet && xSecondPlayer <= xCarpet + size) {
      ySecondPlayer -= (yCarpet + size);
      secondPlayerResult = Math.abs(ySecondPlayer);
    } else if (ySecondPlayer >= yCarpet && ySecondPlayer <= yCarpet + size) {
      xSecondPlayer -= (xCarpet + size);
      secondPlayerResult = Math.abs(xSecondPlayer);
    } else {
      if (xSecondPlayer < xCarpet && ySecondPlayer < yCarpet) {
        xSecondPlayerProximity = xSecondPlayer - xCarpet;
        ySecondPlayerProximity = ySecondPlayer - (yCarpet);
      } else if (xSecondPlayer < xCarpet && ySecondPlayer > yCarpet) {
        xSecondPlayerProximity = xSecondPlayer - (xCarpet);
        ySecondPlayerProximity = ySecondPlayer - (yCarpet + size);
      } else if (xSecondPlayer > xCarpet && ySecondPlayer < yCarpet) {
        xSecondPlayerProximity = xSecondPlayer - (xCarpet + size);
        ySecondPlayerProximity = ySecondPlayer - yCarpet;
      } else if (xSecondPlayer > xCarpet && ySecondPlayer > yCarpet) {
        xSecondPlayerProximity = xSecondPlayer - (xCarpet + size);
        ySecondPlayerProximity = ySecondPlayer - (yCarpet + size);
      }
      secondPlayerResult = Math.abs(xSecondPlayerProximity) + Math.abs(ySecondPlayerProximity);
    }

    if (firstPlayerResult > secondPlayerResult) {
      return 2;
    } else if (firstPlayerResult < secondPlayerResult) {
      return 1;
    } else {
      return 0;
    }
  }


texts:
I'm writing a byte array at the end of file. The code works fine, but can you please suggest performance improvements?

static void Main(string[] args)
    {
        string PathToFile = "C:\\myfile.m4a";
        WriteAaray(PathToFile, GetMyList());
    }
public static List<float> GetMyList()
    {
        // This list is dynamically generated can go upto 5000 points
        var mylist = new List<float> { 4, 90, 54, 6, 5324, 423, 432, 4353, 463, 5, 24, 32, 4, 32, 43, 3, 56, 3 };
        return mylist;
    }
public static bool WriteAaray(string originalFile, List<float> myFloatPoints)
    {
        FileStream inputFileStream = null;
        inputFileStream = new FileStream(originalFile, FileMode.Open);
        var length = inputFileStream.Length;
        inputFileStream.Seek(length, SeekOrigin.Begin);
        StringBuilder mystring = new StringBuilder();
        string myImpPoints = "[MYIMPPOINTS]";
        mystring.Append(myImpPoints);
        var points = string.Join(",", myFloatPoints.Select(f => f.ToString()));
        mystring.Append(points);
        byte[] byteArray = Encoding.ASCII.GetBytes(mystring.ToString());
        inputFileStream.Write(byteArray, 0, byteArray.Length);
        inputFileStream?.Close();
        return true;
}


texts:
This code works great, but I think it can be reduced.

@if (Session["Success"] != null)
{
    <text>

@Session["Success"]

    </text>
    Session.Remove("Success");
}
else if (Session["Error"] != null)
{
    <text>

@Session["Error"]

    </text>
    Session.Remove("Error");

}


texts: Make a MySQL SELECT and INNER JOIN faster

texts:
I have the following query which works as it should, but I'd like to know how I can make it run faster.

For info, tables cl, jo and mi all have column ref as the auto_inc primary key and ID as the main identification number.  Therefore, I use the refs to keep a history of changes for ID.  So, I use SELECT MAX(ref) FROM [xx] GROUP BY ID to get the most recent cl jo and mi.

SELECT mi.ref, jo.ID, mi.ID AS mID, mt.mi_type, jo.ref, jt.jo_type, cl.cl_name
FROM mi
INNER JOIN mt ON mt.ref = mi.mi_type
INNER JOIN jo ON jo.ID = mi.job
INNER JOIN cl ON cl.ID = jo.cl
INNER JOIN jt ON jt.ref = jo.jo_type
WHERE mi.ref IN (SELECT MAX(ref)
                    FROM mi
                    GROUP BY ID)
AND jo.ref IN (SELECT MAX(ref)
                    FROM jo
                    GROUP BY ID)
AND cl.ref IN (SELECT MAX(ref)
                    FROM cl
                    GROUP BY ID)
ORDER BY cl.cl_name, jt.jo_type, mt.mi_type ASC


texts: Ruby script on-all-nodes-run not only for teaching

texts:
I wrote the following Ruby script several years ago and have been using it often ever since on a Bioinformatics computer cluster.

It pulls out a list of hosts from the Torque queuing system qnodes. It ssh'es and runs a command on all the nodes. Then it prints the output and/or errors in a defined order (alphabetical sort of the hostnames).

A nice feature: results are printed immediately for the host that is next in the order.

I would like to use it as an example for a Ruby workshop. Could you please suggest best-practice and design pattern improvements?

#!/usr/bin/ruby

EXCLUDE = [/girkelab/, /biocluster/, /parrot/, /owl/]

require "open3"

# Non-interactive, no password asking, and seasonable timeouts
SSH_OPTIONS = ["-o PreferredAuthentications=publickey,hostbased,gssapi,gssapi-with-mic",
               "-o ForwardX11=no",
               "-o BatchMode=yes",
               "-o SetupTimeOut=5",
               "-o ServerAliveInterval=5",
               "-o ServerAliveCountMax=2"
              ].join(" ")

SSH    = "/usr/bin/ssh #{SSH_OPTIONS}"
MKDIR  = "/bin/mkdir"

raise "Pleae give this command at least one argument" if ARGV.size < 1
COMMAND = ARGV[0..-1].join(' ')

output_o = {}
output_e = {}

IO_CONNECTIONS_TO_REMOTE_PROCESSES = {}

def on_all_nodes(&block)
  nodes = []
  Kernel.open('|qnodes | grep -v "^ " | grep -v "^$"') do |f|
    while line = f.gets
      i = line.split(' ').first
      nodes.push(i) if EXCLUDE.select{|x| i =~ x}.empty?
    end
  end
  nodes.sort.each {|n| block.call(n)}
end

# Create processes
on_all_nodes do |node|
  stdin, stdout, stderr = Open3.popen3("#{SSH} #{node} \"#{COMMAND}\"")
  IO_CONNECTIONS_TO_REMOTE_PROCESSES[node] = [stdin, stdout, stderr]
end

has_remote_errors = false

# Collect results
on_all_nodes do |node|
  stdin, stdout, stderr = IO_CONNECTIONS_TO_REMOTE_PROCESSES[node]

  stdin.close

  e_thread = Thread.new do
    while line = stderr.gets
      line.chomp!
      STDERR.puts "#{node} ERROR: #{line}"
      has_remote_errors = true
    end
  end

  o_thread = Thread.new do
    while line = stdout.gets
      line.chomp!
      puts "#{node}      : #{line}"
    end
  end

  # Let the threads finish
  t1 = nil
  t2 = nil
  while [t1, t2].include? nil
    if t1.nil?
      t1 = e_thread.join(0.1) # Gives 1/10 of a second to STDERR
    end
    if t2.nil?
      t2 = o_thread.join(0.1) # Give 1/10 of a second to STDOUT
    end
  end

end

exit(1) if has_remote_errors


texts: Bundling JavaScript modules into a single file

texts:
I was just going through Modular Design Patterns in JavaScript and I came across bundlers like browserify and webpack. They solve an interesting problem of combining all dependencies into a monolithic file.

I was interested to see how I can flatten out multiple files say main.js, utils.js, core.js written in commonJSish format that uses require to load other modules which might recursively require other modules.

Can someone review this and give me some drawbacks and suggestions? It is commonJSish because it doesn't support export yet.

Currently, we are using the absolute path as the key. So a consumer has to write the absolute path. One solution would be to allow users to write relative path in the code and the bundler taking care of changing it to absolute paths.

// Goal: How to bundle multiple modules into a single file written in
// commonJSish syntax?

// Premise: I am trying to understand the "browserify" code. So I had to
// try something myself ...

// This is the core which provides "require".

__cache__ = {}

function require(name){
    if(__cache__[name]){
        console.log("Retreiving from Cache");
    }
    else{
        console.log("Executing " + name + " Module")
        var module = {"exports": {}};
        map[name](module);
        __cache__[name] = module.exports;
    }
    return __cache__[name];
}

map = {}

// This is the module code. A parser can be used to generate this.

// 1. Each of these is a real file in the filesystem.
// 2. The function wrapper doesn't exist in the real file.
// 3. The order doesn't matter.

map['main.js'] = function(module) {
    var utils = require("utils.js");
    var core = require("core.js")
    module.exports.name = "main.js";
    module.exports.dependencies = [utils, core];
};

map['utils.js'] = function(module) {
    module.exports.name = "utils.js"
};

map['core.js'] = function(module) {
    module.exports.name = "core.js"
};

// The entry is just a "require" call.

require("main.js");


texts: Checking for a series of uniform non-zero digits

texts:
def standvastig(reeks):
    """
    Checks if the given input (list or number) is a series of one number (eg. 444444, 2222, etc.)
    Remark: raise an error if the input is a series of 0s or non-integers

    >>> standvastig(44444444)
    True
    >>> standvastig('44544444')
    False
    """
    if str(reeks).isdigit() == False or int(str(reeks)) == 0:
        raise AssertionError('ongeldig serienummer')# gives an error when the input is not a list of integers or 0s

    if any([str(reeks) == '1'*len(str(reeks)), str(reeks) == '2'*len(str(reeks)), str(reeks) == '3'*len(str(reeks)), str(reeks) == '4'*len(str(reeks)), str(reeks) == '5'*len(str(reeks)), str(reeks) == '6'*len(str(reeks)), str(reeks) == '7'*len(str(reeks)), str(reeks) == '8'*len(str(reeks)), str(reeks) == '9'*len(str(reeks))]):
        return(True)
    else: return(False)

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

Can this code be written more pythonic? Mainly the if condition.


texts: Checking if a number is divisible by 2-11

texts:
I am writing a Python class which checks if a given number is divisible by numbers 2-11. I am not using the __init__ method which in my opinion is not necessary in this case.

Questions:

How can I convert a given number in to abs(x) without using the __init__ method in every method at once?
How can I check if a number is divisible by 7 without using a recursive solution?

class Divisibility:
    """
    Program checks if given number is divisible
    by any number from 2 to 11
    """

    # Divisibe by 2 if last digit is divisible by 2
    def divisible_by_2(self, number):
        number = abs(number)
        if (number % 10) % 2 == 0:
            return True
        else:
            return False

    # Divisible by 3 if sum of its digits is divisible by 3
    def divisible_by_3(self, number):
        number = abs(number)
        n = number

        s = 0
        while n:
            s, n = s + n % 10, n // 10

        if s % 3 == 0:
            return True
        else:
            return False

    # Divisible by 4 if last two digits is divisible by 4
    def divisible_by_4(self, number):
        number = abs(number)
        if (number % 100) % 4 == 0:
            return True
        else:
            return False

    # Divisible by 5 if last digit is either 5 or 0
    def divisible_by_5(self, number):
        number = abs(number)
        if number % 10 == 0 or number % 10 == 5:
            return True
        else:
            return False

    # Divisible by 6 if number is divisible by 2 and 3
    def divisible_by_6(self, number):
        number = abs(number)
        if self.divisible_by_2(number) and self.divisible_by_3(number):
            return True
        else:
            return False

    def divisible_by_7(self, number):
        number = abs(number)
        if number % 7 == 0:
            return True
        else:
            return False

    # Divisible by 8 if last three digits is divisible by 8
    def divisible_by_8(self, number):
        number = abs(number)
        if (number % 1000) % 8 == 0:
            return True
        else:
            return False

    # Divisible by 9 if the sum of its digits is divisible by 9
    def divisible_by_9(self, number):
        number = abs(number)
        s = 0
        while number:
            s, number = s + number % 10, number // 10

        if s % 3 == 0:
            return True
        else:
            return False

    # Divisible by 10 if last digit is 0
    def divisible_by_10(self, number):
        number = abs(number)
        if number % 10 == 0:
            return True
        else:
            return False

    # Divisible by 11 if the difference between
    # the sum of numbers at even possitions and odd
    # possitions is divisible by 11
    def divisible_by_11(self, number):
        number = abs(number)
        n = number
        nn = number // 10
        total = 0

        while n:
            total += n % 10
            n //= 100

        while nn:
            total -= nn % 10
            nn //= 100

        if abs(total) % 11 == 0:
            return True
        else:
            return False

if __name__ == '__main__':

    D = Divisibility()
    print(D.divisible_by_2(-6))
    print(D.divisible_by_3(6))
    print(D.divisible_by_4(6))
    print(D.divisible_by_5(60))
    print(D.divisible_by_6(6))
    print(D.divisible_by_7(616))
    print(D.divisible_by_8(82453))
    print(D.divisible_by_9(9512244))
    print(D.divisible_by_10(-571288441))
    print(D.divisible_by_11(121))


texts: SFTP Ruby script for downloading files from server

texts:
I have written this Ruby script to download some file from server using SFTP. Help me improve this one.
Find the original script at this link

#This script is used to download file from the server to your local machine
#The implementation is based on pure Ruby implementation of SFTP using gem Net SFTP
#To install this on your local machine please run the following command in your terminal 'gem install net-sftp'
#Author : Ashish Wadekar <ashishawadekar@gmail.com>
#Date : 18 December 2016

#This is the gem / library required for the SFTP connection management
require 'net/sftp'

#The host address
HOST = "www.example.com"

#User for connection
USER = "admin"

#The location of the authentication key in pem format
SERVER_KEY_LOC = "/location/of/serverauthenticationkey.pem"

#The location on server where DB backups are done
SERVER_BACKUP = "/location/of/file/on/server"

#The location on local machine where the db has to be downloaded
LOCAL_BACKUP = "/location/on/local/machine/where/file/needs/to/be/downloaded"

#Array to hold the file names for easier sorting
files = Array.new

#Array to hold the file details for easier sorting
files_details = Array.new

#Inititalising the connection
Net::SFTP.start(HOST, USER, :keys => [SERVER_KEY_LOC]) do |sftp|
  puts "Connection to Server successful"
  entries = sftp.dir.entries([SERVER_BACKUP]).sort_by(&:name) #Sorting the files by name as timestamp is used as filename
  entries.each do |entry|
    files << entry.name
    files_details << entry.longname
  end

  download_size = files_details[-1].split(' ')[4].to_i

  puts "Total #{(files.size.to_i) - 2} backups found on server."
  puts "The latest file is : #{files[-1]}, Size : #{(download_size)/1048576} MB"
  puts "Now donwloading the file to your local machine at path : #{LOCAL_BACKUP}"

  sftp.download!(SERVER_BACKUP+files[-1], LOCAL_BACKUP+files[-1]) do |event, downloader, *args|
    case event
    when :open then
      # args[0] : file metadata
      puts "Starting download from server: #{args[0].remote} -> #{args[0].local}"
      puts "Perhaps you can sip a coffee till then!"
    when :get then
      # args[0] : file metadata
      # args[1] : byte offset in remote file
      # args[2] : data that was received
      STDOUT.write "Downloading complete: #{args[1].to_i/1048576}MB, #{args[1].to_i}bytes of #{download_size} bytes, #{((args[1].to_i / download_size) * 100.0)}% \r" unless args[1].to_i == 0

    when :close then
      # args[0] : file metadata
      puts "Done! Closing connection to server."
    when :mkdir then
      # args[0] : local path name
      puts "Creating directory #{args[0]}"
    when :finish then
      puts "Backup download complete!"
    end
  end
end


texts: Extract string between first occurring set of parenthesis

texts:
I have this function and need to refactor it
Please refactor the code below to make it more concise, efficient and readable with good logic flow
function findFirstStringInBracket($str){
    if(strlen($str) > 0){
        $firstbracket = strstr($str, '(');
        if($firstbracket){
            $firstbracket = ltrim($firstbracket, '(');
            return strstr($firstbracket, ')', true);
        }else{
            return '';
        }
    }else{
        return '';
    }
}


texts:
I'm writing a lot of R in my spare time and am trying to get into good habits by using TidyVerse as much as possible. A large part of this has required reading entire directories of dated log files into R for processing. The volumes of data are well into the GBs so I won't post one here and it shouldn't matter so long as you have filenames matching "./accounts_20180217.csv" or "./symbols_20180217.csv" in the working or data directory.

Example file contents is:

./accounts_20180217.csv

 16 109=18A
175 109=1FN
 10 109=ABP
  6 109=ABW
787 109=ACI
226 109=ACL
163 109=AD
644 109=AGM
 79 109=AGN
 40 109=AIG
  2 109=AJT
991 109=ALG
  4 109=ALGR
 14 109=AM1
 17 109=AN1
 34 109=AP1
136 109=APA
267 109=APJ
160 109=ARE
 64 109=ARX
329 109=AS1

I've been using the following to read in and categorise the file data:

library(tidyverse)
library(stringr)

all_data <- tibble(
              filename = list.files(
                   "./", pattern = "^(accounts|symbols)_201[7-9][0-9]{2}[0-9]{2}\\.csv$"
               , full.names = TRUE
              )
            ) %>%
            mutate(
              date = str_extract(filename, "201[7-9][0-9]{4}")
              , type = str_extract(filename, "(accounts|symbols)")
              , data = map2(
                      filename
                      , date
                      , ~read.csv(
                           .x
                           , header = FALSE
                           , sep = "="
                           , as.is = TRUE
                           , col.names = c("count", "names")
                           , colClasses = c("integer", "character") ))
  )

My question is whether this is a good and Tidy way to achieve this or is there a "better" or "Tidier" way?


texts:
I've been reading Cracking the Coding Interview and at the very beginning I got to the strange statement that the next complexity will be \$O(n^2)\$.

public String makeSentence(String[] words){
 String sentence = "";
 for (String w:words){
     sentence+=w;
 }
 return sentence;
}

I can't get it. Why is it \$O(n^2)\$? Here I found another article on this topic.


texts:
Given a set, generate all permutations:

(permutations #{1 4 5}) => ((5 4 1) (4 5 1) (5 1 4) (1 5 4) (4 1 5) (1 4 5))

Here's what I cobbled together:

(defn perm-r [allPerms currentPerm input i]
  (cond
    (empty? input) (conj allPerms currentPerm)
    (< i 0) allPerms
    :else (perm-r
            (perm-r
              allPerms
              (conj currentPerm (nth input i))
              (remove (fn [x] (= x (nth input i))) input)
              (dec
                (count
                  (remove
                    (fn [x] (= x (nth input i)))
                    input))))
            currentPerm
            input
            (dec i))))

(defn permutations [a-set]
  (perm-r `() `() (seq a-set) (dec (count a-set))))

I thought my solution was awful, so I went to look for other solutions and found this:

(defn rotations [a-seq]
  (distinct (map concat (tails a-seq) (inits a-seq))))

(defn permutations [a-set]
  (if (empty? a-set)
    (list ())
    (apply concat (map (fn [x] (map cons (repeat (first x))
                                         (permutations (rest x))))
                  (rotations a-set)))))

It looks so elegant! I'm not used to functional programming, so I find the execution flow immensely difficult to follow. In particular, I don't understand what's being concatenated. Is the result of the first map call (which represents what exactly?) to every rotation of a-set?

Any tips on improving my thought process so that I could come up with a solution like that on my own? I'm used to programming imperatively and I don't find functions like map or apply intuitive. Is there a way to make this function more readable or improve it further in other ways?


texts:
Please review my pointer class.

template<typename T>
class Ptr {
public:
    Ptr(T* t, int s = 1) {
        sz = s;
        p = new T[sz];
        for (int i = 0; i < sz; ++i) {
            p[i] = t[i];
        }
    }

    Ptr(const Ptr&) = delete;
    Ptr& operator=(const Ptr&) = delete;

    Ptr(Ptr &&t) :p{t.p}, sz{t.sz} {
        t.p = nullptr;
        t.sz = 0;
    }

    Ptr& operator=(Ptr &&t) {
        std::swap(t.p,p);
        std::swap(t.sz,sz);
        return *this;
    }

    T& operator*() {
        check_range();
        return *p;
    }

    T& operator[](int i) {
        check_range(i);
        return p[i];
    }

    Ptr& operator+=(int i) {
        check_range(index+i);
        index += i;
        p+= i;
        return *this;
    }

    Ptr& operator-=(int i) {
        check_range(index-i);
        index -= i;
        p -= i;
        return *this;
    }

    Ptr& operator+(int i) {
        Ptr old{*this};
        return old+=1;
    }

    Ptr& operator-(int i) {
        Ptr old{*this};
        return old-=1;
    }

    Ptr& operator++() {
        return operator+=(1);
    }

    Ptr operator++(int) {
        Ptr<T> old{p};
        operator++();
        return old;
    }

    Ptr& operator--() {
        return operator-=(1);
    }

    Ptr operator--(int) {
        Ptr<T> old{p};
        operator--();
        return old;
    }

    ~Ptr() {
        while (index < sz-1) {
            operator++();
        }
        while (index != 0) {
            delete p;
            operator--();
        }
        delete p;
    }

private:
    T* p;
    int sz;
    int index = 0;
    void check_range(int i) {
        if (i < 0 || i > sz-1) {
            throw std::out_of_range("out of range");
        }
    }
    void check_range() {
        if (p == nullptr) {
            throw std::out_of_range("null pointer");
        }
    }
};


texts: Speed and ID concerns converting DOM object into JQuery objects

texts:
First of all, I am not using JQuery but Cheerio. I have never actually used JQuery in "real life" -- I started with Cheerio, which is a subset and doesn't actually work in a browser environment.

(Note: I don't have enough reputation here to create tags, somebody might want to tag this question as "cheerio" and delete this sentence...)

Here is my code. Questions are inline:

$ = cheerio.load( self.formPage.toString() );

$( 'form' ).each( function( index, form ){

  // *****************
  // QUESTION:
  // Is this the right way to do this?
  // I am "converting" each found "DOM" object into a "JQuery" object (although
  // it's not real DOM, and it's not real JQuery either).
  // But, if there is no ID set for form, for example, is this _guaranteed_ to always find
  // the right one?
  var $form = $( form );

  // Work out fullAction, which is the form's action relative to the fetched URL
  var action;
  var baseUrl = self.config.url.substr(0, self.config.url.lastIndexOf("/") + 1);
  var action = $form.attr( 'action' );
  var fullAction = require( 'path' ).normalize( baseUrl + action );
  console.log("FULL ACTION:", fullAction );

  stores.workspacesNinjaFormCodes.apiGetQuery( { filters: { workspaceId: self.workspaceId }, skipHardLimitOnQueries: true }, function( err, codesData ){

  //stores.workspacesNinjaFormCodes.dbLayer.select( { conditions: { and: [ { field: 'workspaceId', type: 'eq', value: self.workspaceId } ] } }, { skipHardLimitOnQueries: true }, function( err, codesData ){

    codesData.forEach( function( codeData ){
      var code = codeData.code;
      var dataSubmitHash = {};

      // *****************
      // QUESTION:
      // Is this the right way to do this? I want to find all 'input' fields
      // in this particular form. So, I pass $form as context and look for
      // all 'input' tags. Is this what you are meant to do?
      // ******************
      $( "input", $form ).each( function( index, inputField ){

        // *****************
        // QUESTION:
        // Once again, will this always work, regadrless of IDs etc.? I am passing `form` as the
        // context.
        // ******************
        var $inputField = $( inputField, form );

        // See if the field name is already assigned
        var fieldValue = $inputField.val() ? $inputField.val() : code;

        // Assign values
        dataSubmitHash[ $inputField.attr('name') ] = fieldValue;
      });

      console.log("dataSubmitHash:", dataSubmitHash );
    });

  });

});

Questions are inline, and they are focused on this: how expensive is the "conversion" of cheerio's "DOM" objects into Cheerio "JQuery" objects? And is it always guarantee to get the right one?


texts:
I'm currently learning python and created a simple music quiz. the rules of the game are as follows:

The user has two chances to guess the name of the song If the user guesses the answer correctly the first time, they score 3 points. If the user guesses the answer correctly the second time they score 1 point.The game repeats.The game ends when a player guesses the song name incorrectly the second time.

I developed the following but the I wasn't very pleased with the update leaderboard function as the indexing of the 2d list was confusing to code. is there an easier way to do the same thing?

start_quiz returns two variables and is there a way to sort of 'unpack' what's returned?

# 21:23 5th dec 2019
from Resources.songs import songs
from Resources.users import users
import random
import pickle

def main():
    username = login()
    print('hello', username, 'welcome to the music quiz')
    guessed_wrong_twice = False
    result = None
    while not guessed_wrong_twice:
        result = start_quiz()
        guessed_wrong_twice = result[1]
    score = result[0]
    print('you scored', score)
    leaderboard = leaderboard_updating(username, int(result[0]))
    print('The leaderboard:\n', leaderboard)

main()

def login():
    logged_in = False
    entered_username = None
    while not logged_in:
        entered_username = input("please enter username: ")
        if entered_username in users:
            entered_password = input('please enter password: ')
            if entered_password == users[entered_username]:
                logged_in = True
        else:
            print("password or username incorrect try again")
            logged_in = False

    return entered_username

def start_quiz():
    score = 0
    guessed_wrong_twice = False
    song_chosen = choosing_song()
    print('artists name is', song_chosen[1])
    first_letter = song_chosen[0][0]
    guess = input("the song begins with" + first_letter)
    if guess.lower == song_chosen[0]:
        score += 3
    else:
        guess = input("the song begins with " + first_letter)
        if guess.lower == song_chosen[0]:
            score += 1
        elif guess != song_chosen[0]:
            guessed_wrong_twice = True
    return score, guessed_wrong_twice

def choosing_song():
    song_chooser = random.randint(1, 3)
    song_artist = songs[song_chooser][1]
    song_name = songs[song_chooser][0]
    return song_name, song_artist

# index 0 of each 'sub list' is the users name index 1 is their highest score

def leaderboard_updating(username, score=0):

    leaderboard = pickle.load(open("leaderboard.pickle", "rb"))

    index_row_list = [leaderboard.index(row) for row in leaderboard if username in row]
    index_row = int(index_row_list[0])
    if leaderboard[index_row][1] < score:
        leaderboard[index_row][1] = score

    leaderboard = sorted(leaderboard, key=lambda x: x[1])

    pickle.dump(leaderboard, open("leaderboard.pickle", "wb"))
    return leaderboard


texts: Project Euler 46: Finding a counterexample to a Goldbach conjecture

texts:
I'm working on problem 46 from project euler:

  It was proposed by Christian Goldbach that every odd composite number
  can be written as the sum of a prime and twice a square.

9 = 7 + 2×1^2
15 = 7 + 2×2^2
21 = 3 + 2×3^2
25 = 7 + 2×3^2
27 = 19 + 2×2^2
33 = 31 + 2×1^2

  It turns out that the conjecture was false. What is the smallest odd
  composite that cannot be written as the sum of a prime and twice a
  square?

My code is so ridiculously inefficient and it takes minutes before an answer pops up. (Boundary numbers are just rough estimates)

numbers = [(2*x**2) for x in list(range(1, 1000))]
normal = list(range(1, 10000000))

#produces primes under n
def primes(n):
    sieve = [True] * n
    for i in range(3, int(n**0.5) + 1, 2):
        if sieve[i]:
            sieve[i * i:: 2 * i] = [False] * int((n - i * i - 1)/(2 * i) + 1)
    return [2] + [i for i in range(3, n, 2) if sieve[i]]

primes = primes(1000)
final = []

#add the two lists in every way possible
added = [x + y for x in numbers for y in primes]

#if it does not appear in a normal number line send it to final
for x in added:
    if x not in normal:
        final.append(x)

print(min(final))

I also lack the knowledge to use any mathematical tricks or algorithms. Where can I start learning code efficiency/performance and simple algorithms to use in my code?


texts:
I am looking for best practice on how I may write this function more efficiently.

  var d = new Date(),
      time = d.getHours(),
      day  = d.getDay();

  if (day > 0 || day < 7){
    if (time > 18 || time < 8){
      // execute code

    }
  }


texts: Project Euler #2 with a fibSequence and result

texts:
I have a background in Linguistics and my journey as an aspiring developer has just begun.

I was hoping you could give me a feedback on the solution I have come up with for the second challenge of Project Euler, and maybe explain me why many of the other solutions I have come across were wrapped inside a single function.

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

let fibSequence = [0, 1];
let result = 0;

function fibonacci(array) {
  return array[array.length - 1] + array[array.length - 2];
}

while(fibSequence[fibSequence.length - 1] < 4e+6) {
  fibSequence.push(fibonacci(fibSequence));
}

fibSequence.forEach(function (number) {
  if(number % 2 === 0) {
    result += number;
  }
});

console.log(result);


texts:
I have two sieves that I wrote in python and would like help optimizing them if at all possible. The divisorSieve calculates the divisors of all numbers up to n. Each index of the list contains a list of its divisors. The numDivisorSieve just counts the number of divisors each index has but doesn't store the divisors themselves. These sieves work in a similar way as you would do a Sieve of Eratosthenes to calculate all prime numbers up to n.

Note: divs[i * j].append(i) changed from divs[i * j] += [i] with speed increase thanks to a member over at stackoverflow. I updated the table below with the new times for divisorSieve. It was suggested to use this board instead so I look forward to your input.

def divisorSieve(n):
    divs = [[1] for x in xrange(0, n + 1)]
    divs[0] = [0]
    for i in xrange(2, n + 1):
        for j in xrange(1, n / i + 1):
            divs[i * j].append(i) #changed from += [i] with speed increase.
    return divs

    def numDivisorSieve(n):
        divs = [1] * (n + 1)
        divs[0] = 0
        for i in xrange(2, n + 1):
            for j in xrange(1, n / i + 1):
                divs[i * j] += 1
        return divs

#Timer test for function
if __name__=='__main__':
    from timeit import Timer
    n = ...
    t1 = Timer(lambda: divisorSieve(n))
    print n, t1.timeit(number=1)

Results:

 -----n-----|--time(divSieve)--|--time(numDivSieve)--
    100,000 |  0.333831560615  |  0.187762331281
    200,000 |  0.71700566026   |  0.362314797537
    300,000 |  1.1643773714    |  0.55124339118
    400,000 |  1.63861821235   |  0.748340797412
    500,000 |  2.06917832929   |  0.959312993718
    600,000 |  2.52753840891   |  1.17777010636
    700,000 |  3.01465945139   |  1.38268800149
    800,000 |  3.49267338434   |  1.62560614543
    900,000 |  3.98145114138   |  1.83002270324
  1,000,000 |  4.4809342539    |  2.10247496423
  2,000,000 | 9.80035361075    |  4.59150618897
  3,000,000 | 15.465184114     |  7.24799900479
  4,000,000 | 21.2197508864    |  10.1484527586
  5,000,000 | 27.1910144928    |  12.7670585308
  6,000,000 | 33.6597508864    |  15.4226118057
  7,000,000 | 39.7509513591    |  18.2902677738
  8,000,000 | 46.5065447534    |  21.1247001928
  9,000,000 | 53.2574136966    |  23.8988925173
 10,000,000 | 60.0628718044    |  26.8588813211
 11,000,000 | 66.0121182435    |  29.4509693973
 12,000,000 |   MemoryError    |  32.3228102258

 20,000,000 |   MemoryError    |  56.2527237669
 30,000,000 |   MemoryError    |  86.8917332214
 40,000,000 |   MemoryError    |  118.457179822
 50,000,000 |   MemoryError    |  149.526622815
 60,000,000 |   MemoryError    |  181.627320396
 70,000,000 |   MemoryError    |  214.17467749
 80,000,000 |   MemoryError    |  246.23677614
 90,000,000 |   MemoryError    |  279.53308422
100,000,000 |   MemoryError    |  314.813166014

Results are pretty good and I'm happy I was able to get it this far, but I'm looking to get it even faster. If at all possible, I'd like to get 100,000,000 at a reasonable speed with the divisorSieve. Although this also brings into the issue that anything over 12,000,000+ throws a MemoryError at divs = [[1] for x in xrange(0, n + 1)]) in divisorSieve. numDivisorSieve does allow the full 100,000,000 to run. If you could also help get past the memory error, that would be great.

I've tried replacing numDivisorSieve's divs = [1] * (n + 1) with both divs = array.array('i', [1] * (n + 1)) and divs = numpy.ones((n + 1), dtype='int') but both resulted in a loss of speed (slight difference for array, much larger difference for numpy). I expect that since numDivisorSieve had a loss in efficiency, then so would divisorSieve. Of course there's always the chance I'm using one or both of these incorrectly since I'm not used to either of them.

I would appreciate any help you can give me. I hope I have provided enough details. Thank you.


texts:
I am trying to implement the Wikipedia definition of a MultiSet and need feedback on the implementation.

class MultiSet
  include Enumerable

  attr_reader :members

  def initialize enum={}
    @members = {}
    raise_error unless enum.class.include? Enumerable
    enum.each do |item|
      if @members.include?(item)
        @members[item] += 1
      else
        @members[item] = 1
      end
    end
  end

  def each(&blk)
    @members.each(&blk)
  end

  def == other
    members.to_h == other.to_h
  end

  def eql? other
    self == other
  end

  def to_h
    members.dup
  end

  def to_set
    Set.new @members.keys
  end

  def remove item
    if @members.include?(item)
      @members[item] = @members[item] - 1
      if @members[item] < 1
        @members.delete(item)
      end
    end
    self
  end

  def add item
    if @members.include?(item)
      @members[item] += 1
    else
      @members[item] = 1
    end
    self
  end

  def empty!
    @members.clear
  end

  def multiplicity item
    @members[item] == 0 ? nil : @members[item]
  end

  def include? item
    @members.include? item
  end

  def cardinality
    return 0 if @members.empty?
    @members.values.reduce(:+)
  end

  def | other
    other.each do |k,v|
      if members.include? k
        members[k] = multiplicity(k) + other.multiplicity(k)
      else
        add k
      end
    end
    self
  end

  def & other
    members.each do |k,v|
      if other.include? k
        members[k] = [multiplicity(k), other.multiplicity(k)].min
      else
        remove k
      end
    end
    self
  end

end


texts:
Here is my Python code for finding the permutation index of a given digits and a target number. And by permutation index I mean, for example, given digits [1, 2, 3, 4]. find the index of 3124, meaning the position of 3124 in all permutations. This code finds that. However I have suspicions about it efficiency and implementation. Please review my code.

def perm_ind(numbers, target, length):
    """
    Finding the position of a single permutation in all permutations.
    Using the mathematic formula.
    """

    ranks = sorted(numbers) # For keeping the index even after some numbers are placed and removed.
    ind = 0
    for step in reversed(xrange(length)):

        num = (target / 10 ** step) # These two lines are used to get
        target %= 10 ** step        # the left-most digit in each iteration

        times = ranks.index(num) # Find the rank of the currect digit.

        ind += factorial(length - 1) * times # Add to result
        ranks.remove(num) # Remove the used(Placed) number
        length -= 1 # Decrease length

    return ind

# Example usages
print perm_ind([1, 2, 3], 123, 3)
print perm_ind([1, 2, 3], 132, 3)
print perm_ind([1, 2, 3], 213, 3)


texts: Inserting multiple elements at known locations in a vector

texts:
Goal
In the vector x, I would like to insert the elements of the vector values at indices stored in vector positions. Note that the vector positions is not sorted.
For example, from the following input
std::vector<char> x = {'H','e','l','l','W','o','l','d'};
std::vector<char> values = {'r','o'};
std::vector<size_t> positions = {6,4};

I expect the following output
std::vector<char> x = {'H','e','l','l','o','W','o','r','l','d'};

My implementation
The idea is first to sort positions and reorder values accordingly. Then, I resize the vector x so that it can welcome the new elements. Finally, I iterate through the vector x from its last index to the lowest position of insertion by asking at each step what element should go there and move this element (whether it comes from a lower index in x of from values).
#include <iostream>
#include <vector>
#include <numeric>

//// Print a vector
template <typename T>
void print(std::vector<T>& x)
{
    for (auto& e : x) std::cout << e << " ";
    std::cout << "\n";
}

//// Return the indices to inform on how to sort the inputted vector
template <typename T>
std::vector<uint32_t> sort_indices(const std::vector<T> &v)
{

  // initialize original index locations
  std::vector<uint32_t> idx(v.size());
  std::iota(idx.begin(), idx.end(), 0);

  // sort indexes based on comparing values in v
  std::sort(idx.begin(), idx.end(),
       [&v](uint32_t i1, uint32_t i2) {return v[i1] < v[i2];});

  return idx;
}

//// reorder vector based on indices
template <typename T>
void reorder(std::vector<T>& v, std::vector<uint32_t>& order)
{
    auto v2 = v;
    for (uint32_t i = 0 ; i < v.size() ; i++)
    {
        v[i] = v2[order[i]];
    }
}

//// Insert multiple elements at specified positions into vector
template<typename T>
void insertAtPositions(std::vector<T>& x, std::vector<T>& values, std::vector<size_t>& positions)
{
  // assert values and positions are the same size
  assert(values.size() == positions.size());

  // Special case - values is empty
  if (values.size() == 0) return;

  // sort the values and the positions where those values should be inserted
  auto indices = sort_indices(positions);
  reorder(positions, indices);
  reorder(values, indices);

  // Special case - x is empty
  if (x.size() == 0)
  {
      x.swap(values);
      return;
  }

  // Allocate memory to x
  x.resize(x.size() + values.size());

  // Move things to make room for insertions and insert
  int pos_index = positions.size()-1;
  for (size_t i = x.size()-1 ; pos_index >= 0 ; --i)
  {
    if (i == positions[pos_index] + pos_index)
    {
      // A new value should go at index i
      x[i] = std::move(values[pos_index]);
      --pos_index;
    } else
    {
      // The value from index 'i-pos_index-1' must go to index 'i'
      x[i] = std::move(x[i-pos_index-1]);
    }
  }
}

int main()
{
  std::vector<char> x = {'H','e','l','l','W','o','l','d'};
  std::vector<char> values = {'r','o'};
  std::vector<size_t> positions = {6,4};

  print(x);
  insertAtPositions(x,values,positions);
  print(x);

}

It prints, as expected
H e l l W o l d
H e l l o W o r l d

Are there faster (or better in some other respect) implementations?
Note that

in practice, x's size typically ranges from 0 to 10^7 and positions (and values)'s size typically ranges from 0 to 50.
I have good reasons for using a vector and not a deque despite this insertion.


texts: Max-Heap arraylist based priority queue written in Java

texts:
I have a program that I'm writing that needs to use a priority queue as part of an algorithm. I specifically need to order (String, Integer) pairs for example (Bread, 3), (Beer, 5), (Eggs,2), etc.

I'd appreciate any comments on my code style and how I've written my class.

import javafx.util.Pair;
import java.util.ArrayList;
import java.util.Collections;

public class FPPriorityQueue implements PriorityQueue {

private ArrayList<Pair<String, Integer>> heapArray;

public FPPriorityQueue(){
    super();
    heapArray = new ArrayList<Pair<String, Integer>>();
}

public boolean empty(){
    return true;
}

private Integer getParentData(int index){
    int parentIndex = index/2;
    Pair<String, Integer> parentData = heapArray.get(parentIndex);
    return parentData.getValue();
}

private void swap(Integer old, Integer knew){
    Collections.swap(heapArray,old,knew);

}

private void shiftUp(int index){

    int parentIndex;

    if(index != 1){
        parentIndex = index/2;
        int childData = heapArray.get(index).getValue();
        int parentData = getParentData(index);

        if(parentData < childData){
            swap(parentIndex,index);
            shiftUp(parentIndex);
        }
    }
}

private void shiftDown(int index){

    if(heapArray.size()> (index*2)+1) {
        int leftChildValue = heapArray.get(index * 2).getValue();
        int rightChildValue = heapArray.get((index * 2) + 1).getValue();

        int indexValue = heapArray.get(index).getValue();

        if(indexValue < leftChildValue || indexValue < rightChildValue)
        {
            if(leftChildValue > rightChildValue){
                int leftChildIndex = index*2;
                swap(index,leftChildIndex);
                shiftDown(leftChildIndex);
            }
            else{
                int rightChildIndex = (index*2)+1;
                swap(index,rightChildIndex);
                shiftDown(rightChildIndex);
            }
        }
    }

}

public void insert(String key, Integer value){

    Pair<String, Integer> element = new Pair<String, Integer>(key,value);
    Pair<String, Integer> nullElement = new Pair<String, Integer>("NULL",0);
    //add the element to the last position in the list
    if(heapArray.isEmpty()){
        heapArray.add(0,nullElement);
        heapArray.add(1,element);
    }
    else{
        heapArray.add(heapArray.size(), element);
        shiftUp(heapArray.size()-1);
    }

}

public Pair<String, Integer> removeMax(){

    Pair<String, Integer> returnValue = heapArray.remove(1);
    Collections.swap(heapArray,heapArray.size()-1,1);
    shiftDown(1);

    return returnValue;

}
}


texts: A simple cipher that uses the sums of previous characters

texts:
I'm fairly happy with the code itself, but I'd like you to tear it apart.

def sumcipher(inpt, o=0, encrypt=True):
    if not isinstance(inpt, str):
        raise TypeError("Input must be a string")
    if encrypt:
        return ''.join([chr(((sum([ord(i) - 32 for i in inpt[j::-1]]) + (o % 96)) % 96) + 32) for j in range(len(inpt))])
    else:
        L = ""
        for i in range(len(inpt)):
            L += chr((((ord(inpt[i]) - 32) - sum([ord(j) - 32 for j in L])) % 96) + 32)
        return L

I'm mostly looking for ways to make it more elegant/simple.

PS: I'm very inexperienced with asking questions.


texts: Determine if input word can be created from a list of letters

texts:
I am looking for a more elegant way to validate in an input word can be created from a list of letters.

# Necessary variables (change as needed to test your code).
user_word = 'BANANA'
letters = ['N', 'B', 'N', 'A', 'A', 'P', 'M', 'S', 'A']

# This function checks whether a word entered by the user contains appropriate letters.
# It receives the letters and the word as parameter values, and returns True or False.
def validate_word(word, letters):
    from collections import Counter
    Count = Counter(letters)
    for letters in word:
        if not Count[letters]:
            return False
        Count[letters] -= 1
    return True

# Print the return value of the function to test it.
print(validate_word(user_word, letters))

As commented the function needs to return True if all the letters in the word are in the list, False otherwise.


texts: Adding a Node to the Linked List is taking a longer Time when using a reference to the Tail Node

texts:
I am trying to add two numbers in the form of linked List and return their result in a Linked List as given in https://leetcode.com/problems/add-two-numbers/

Question:

  You are given two non-empty linked lists representing two non-negative
  integers. The digits are stored in reverse order and each of their
  nodes contain a single digit. Add the two numbers and return it as a
  linked list.

  You may assume the two numbers do not contain any leading zero, except
  the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807, my solution has solved all the test cases but after refactoring, it is taking longer than the original code

Solution 1:

//public class ListNode
//{
//    public int val;
//    public ListNode next;
//    public ListNode(int x) { val = x; }
//};

public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int first = 0,
            second = 0;
            if (l1 != null) {
                first = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                second = l2.val;
                l2 = l2.next;
            }
            int Digit = first + second;
            if (carry != 0) {
                Digit = Digit + carry;
                carry = 0;
            }
            if (Digit > 9) {
                carry = Digit / 10;
                Digit = Digit % 10;
            }
            AddLastNode(Digit, ref l3);
        }
        if (carry != 0) {
            AddLastNode(carry, ref l3);
            carry = 0;
        }
        return l3;
    }

    /// In here I am looping through the Linked List every time,to find the tail node
    private static void AddLastNode(int Digit, ref ListNode l3) {
        if (l3 != null) {
            AddLastNode(Digit, ref l3.next);
        }
        else {
            l3 = new ListNode(Digit);
        }
    }
}

So  to avoid looping through all the Nodes,in the below solution I am using a reference for the Tail Node

Solution 2:

public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = null;
        ListNode tailNode = null;
        int remainder = 0;
        while (l1 != null || l2 != null) {
            int sum = 0;
            if (l1 != null) {
                sum = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            if (remainder != 0) {
                sum += remainder;
            }
            if (sum > 9) {
                remainder = sum / 10;
                sum = sum % 10;
            }
            else {
                remainder = 0;
            }
            ///In here I am using tailNode has reference for adding new node to the end of Linked List
            if (tailNode == null) {
                l3 = new ListNode(sum);
                tailNode = l3;
            }
            else {
                tailNode.next = new ListNode(sum);
                tailNode = tailNode.next;
            }
        }
        if (remainder != 0) {
            tailNode.next = new ListNode(remainder);
        }
        return l3;
    }
}

Since I got a tail node for the end of Linked List instead of going through entire Linked List,I thought the solution 2 will have better performance.But it is still taking more time to execute than the first solution ,Any code changes would be appreciated

Solution 1 is taking 108 ms to execute while Solution 2 is taking 140 ms


texts: Userscript to redirect insecure pages to HTTPS

texts:
I am developing a userscript that redirects insecure pages (HTTP) to the https: version.

// ==UserScript==
// @name         Secure Redirect
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  A simple userscript that redirects pages to https:.
// @author       You
// @match        *
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    window.onload=()=>{
        if (location.protocol != "https:") {
            window.location.href = "https:" + window.location.href.substring(window.location.protocol.length);
        }
    };
})();

Please tell me if it works and what I can improve on. My GitHub repo for this project is here.


texts: Deserialize an email header into key-value pairs

texts:
I've created a function that will deserialize an email header into a list of key-value pairs. I've run numerous tests using MS Office Outlook 2010 and MS Office 14.0 Object Library, all of which were successful.

However, I'd still like to know if this function could be optimized/improved.

Note

I didn't use the Dictionary(Of TKey, TValue) class because a key can appear multiple times.
The reason as to why I wrote this RegEx pattern is because a value can also contain a new line and/or :.

Public Shared Function Deserialize(header As String) As List(Of KeyValuePair(Of String, String))

    Const pattern As String = "(\n|^)[a-z|A-Z|-]*:\s"

    If (header Is Nothing) Then Throw New ArgumentNullException("header")

    Dim result As New List(Of KeyValuePair(Of String, String))
    Dim matches As MatchCollection = Regex.Matches(header, pattern)

    If ((Not matches Is Nothing) AndAlso (matches.Count > 0)) Then

        Dim endIndex As Integer = header.Length
        Dim startIndex As Integer = Nothing
        Dim item As Match = Nothing
        Dim key As String = Nothing
        Dim value As String = Nothing

        For index As Integer = (matches.Count - 1) To 0 Step -1
            item = matches.Item(index)
            startIndex = (item.Index + item.Length)
            key = item.Value.Trim().Replace(":", "")
            value = header.Substring(startIndex, (endIndex - startIndex))
            result.Insert(0, New KeyValuePair(Of String, String)(key, value))
            endIndex = item.Index
        Next

    End If

    Return result

End Function


texts:
I'm trying to improve my JavaScript (I'm usually a copy/paste guy but can do basic DOM stuff with jQuery too), so I decided to try and make a function to validate an email address without using Regex.

The code seems to work, but I'm interested in hearing how it could be improved.

I'll include the code below, but you can run/fork it on Codepen.

HTML

<input id="email" type="text">
<input id="submit" type="submit" value="Validate">

JS

// Function: valid email address without regex
function isvalidemail(email) {

    // Get email parts
    var emailParts = email.split('@');

    // There must be exactly 2 parts
    if(emailParts.length !== 2) {
        alert("Wrong number of @ signs");
        return false;
    }

    // Name the parts
    var emailName = emailParts[0];
    var emailDomain = emailParts[1];

    // === Validate the parts === \\

    // Must be at least one char before @ and 3 chars after
    if(emailName.length < 1 || emailDomain.length < 3) {
        alert("Wrong number of characters before or after @ sign");
        return false;
    }

    // Define valid chars
    var validChars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','.','0','1','2','3','4','5','6','7','8','9','_','-'];

    // emailName must only include valid chars
    for(var i = 0; i < emailName.length; i += 1) {
        if(validChars.indexOf(emailName.charAt(i)) < 0 ) {
            alert("Invalid character in name section");
            return false;
        }
    }
    // emailDomain must only include valid chars
    for(var j = 0; j < emailDomain.length; j += 1) {
        if(validChars.indexOf(emailDomain.charAt(j)) < 0) {
            alert("Invalid character in domain section");
            return false;
        }
    }

    // Domain must include but not start with .
    if(emailDomain.indexOf('.') <= 0) {
        alert("Domain must include but not start with .");
        return false;
    }

    // Domain's last . should be 2 chars or more from the end
    var emailDomainParts = emailDomain.split('.');
    if(emailDomainParts[emailDomainParts.length - 1].length < 2) {
        alert("Domain's last . should be 2 chars or more from the end");
        return false;
    }

    alert("Email address seems valid");
    return true;
}

document.getElementById('submit').onclick = function() {
    var email = document.getElementById('email').value;
    isvalidemail(email);
};

One thing I know could be improved is where I repeat basically the same code twice to validate the characters in each section. I am more interested in hearing if the way I've structured the function and sections could be done better, as the exercise for me was more about writing well-structured JavaScript and getting familiar with some of the built-in functions than about writing a perfect validator (which is also the reason I didn't use Regex).


texts: Best way to replace a beginning and end character in Perl using Regular Expression?

texts:
I'm wondering if there is a simplier regex I could use in my code to remove the beginning and ending char in a line. Maybe combine some regex's? In this instance, it's a comma at the beginning and ending of a line. My output should be the fields seperated into CSV format.

#!/usr/local/bin/perl

use strict;
use warnings;

parse_DPCRS();

sub parse_DPCRS {
    open ( FILEIN, 'txt_files/AKR_DPCRS.txt' );
    open ( FILEOUT, '>txt_files/AKR_DPCRS.csv' );
    while (<FILEIN>) {
        next if /^(\s)*$/;          #skip blank lines
        next if /^\>/;              #skip command line that start with >
        next if /^\s+POINT\sCODE/;  #skip header
        next if /^\s+NODE\sNAME/;   #skip header
        next if /^\s+\=+/;          #skip header
        next if /^\s+CCS\sDPCRS/;   #skip pageination footer
        chomp;                      #removing trailing newline character
        s/\s+/,/g;                  #replace white space with a comma
        s/^,//;                     #replace beginning comma with empty
        s/,$//;                     #replace ending comma with empty
        my (
            $nodeName, $pointCodeDec ) =  split( "," );
        print FILEOUT ($nodeName . "," . $pointCodeDec . "\n");
        #print "$_\n";
    }
};
close (FILEOUT);
close (FILEIN);
exit;

Here's a slice of the text file I'm parsing

>DISP CCS DPCRS ALL 0

                 POINT CODE  POINT CODE  TYPE OF  ROUTESET  NOTIFY   NODE
   NODE NAME      DECIMAL        HEX      ROUTE    MASTER    SCCP  LOCATION
   ===========  ===========  ==========  =======  ========  ====== ========
   PBVJPRCO01T  1-1-1          010101    FULL PC      119     NO    NON-ADJ
   ROCHNYXA06T  1-6-1          010601    FULL PC       58     NO    NON-ADJ
   NYCNNYDRW17  1-6-2          010602    FULL PC       58     NO    NON-ADJ
   SYRCNYSW01T  1-6-3          010603    FULL PC       22     NO    NON-ADJ
   SYRCNYSWDS0  1-6-15         01060F    FULL PC       58     NO    NON-ADJ
   ROCHNYFEDS0  1-6-17         010611    FULL PC       58     NO    NON-ADJ
   NYCMNYHD01T  1-9-11         01090B    FULL PC       22     NO    NON-ADJ
   NWRKNJ1001T  1-9-14         01090E    FULL PC       22     NO    NON-ADJ
   BSTNMABL01T  1-9-16         010910    FULL PC       22     NO    NON-ADJ


texts: Opening a workbook and copying pages to master workbook

texts:
I have this code which opens 2 workbooks, copies a sheet and paste then to the master workbook. It is currently taking 3 minutes.  Can this be done quicker (i.e. without opening each workbook to copy)?

It takes roughly 3 minutes to do.

Sub Load()
    Dim masterWB As Workbook
    Dim dailyWB As Workbook
    Dim lastweekWB As Workbook
    Dim R As Range
    Dim B As Range
    Dim C As Range
    Dim Lrow As Long

    Application.DisplayAlerts = False

    'Set Current Workbook as Master
    Set masterWB = Application.ThisWorkbook
    'Set some Workbook as the one you are copying from
    Set dailyWB = Workbooks.Open(Sheets("Control Manager").Range("O2"))

    'Copy the Range from dailyWB and Paste it into the MasterWB
    dailyWB.Sheets("Summary1").Range("A1:BJ200").Copy masterWB.Sheets("Summary").Range("A1").Rows("1:1")
    'formatting and paste as values
    masterWB.Activate
    Worksheets("Summary").Select
    'trim values
    Columns("A:BJ").Select
    Selection.Columns.AutoFit
    Selection.Copy
    Selection.PasteSpecial xlPasteValues

    'repeat for next Sheet
    dailyWB.Sheets("risk1").Range("A1:BB200").Copy masterWB.Sheets("risk").Range("A1").Rows("1:1")
    'formatting and paste as values'
    masterWB.Activate
    Worksheets("risk").Select
    Columns("A:BB").Select
    With Application.WorksheetFunction
        For Each B In Intersect(Columns("A:BB"), ActiveSheet.UsedRange)
            B.Value = .Trim(B.Value)
        Next B
    End With
    Selection.Columns.AutoFit
    Selection.Copy
    Selection.PasteSpecial xlPasteValues

    'repeat for CS sheet
    dailyWB.Sheets("CS today").Range("A1:L3").Copy masterWB.Sheets("CS").Range("A1").Rows("1:1")
    'formatting and paste as values
    masterWB.Activate
    Worksheets("CS").Select
    Columns("A:L").Select
    'trim cells to exclude spaces.
    With Application.WorksheetFunction
        For Each R In Intersect(Columns("A:L"), ActiveSheet.UsedRange)
            R.Value = .Trim(R.Value)
        Next R
    End With
    Selection.Columns.AutoFit
    Selection.Copy
    Selection.PasteSpecial xlPasteValues

    ''''''''''''Get Last Week Data''''''''''''''''''''''

    Set lastweekWB = Workbooks.Open(Sheets("Control Manager").Range("O3"))

    'repeat for next risk Sheet
    lastweekWB.Sheets("risk2").Range("A1:BB200").Copy masterWB.Sheets("risk_lastweek").Range("A1").Rows("1:1")
    'formatting and paste as values

    masterWB.Activate
    Worksheets("risk_lastweek").Select
    Columns("A:BB").Select
    With Application.WorksheetFunction
        For Each B In Intersect(Columns("A:BB"), ActiveSheet.UsedRange)
            B.Value = .Trim(B.Value)
        Next B
    End With
    Selection.Columns.AutoFit
    Selection.Copy
    Selection.PasteSpecial xlPasteValues

    Application.DisplayAlerts = True

    'Close the Workbook without saving
    dailyWB.Close False
    lastweekWB.Close False
    'Clear the Variables
    Set dailyWB = Nothing
    Set masterWB = Nothing
    Set lastweekWB = Nothing
End Sub


texts: Upload a directory, in parallel, to an artifact repository

texts:
This code uploads an entire directory and allows for its reparenting on a remote server (an artifact repository).

Three concerns:

Copying the files locally takes a lot of space. Ideally, I could use inotify and as soon as my wget -m had a file I could begin immediately uploading and then deleting. These repositories can be hundreds of gigs
For performance reasons I fork/join everything. This definitely improves overall job performance but I get an error upload.sh: fork: retry: Resource temporarily unavailable which is the OS telling me I can't have more sub processes. My concern is that some of these processes will terminate without doing their job because of this.
Lastly, and I can't be sure of this, but several of the larger files that upload seem to never complete when I use a fork. But when I do a 1-off they finish in an appropriate time

First I run:

wget --user cbongiorno --password abc123 --mirror --no-parent https://artifactory.stback.com/artifactory/BIF-Releases &>  my.logs

Then I do the upload. It would be nice to upload and delete files as they come in

#!/usr/bin/env bash

[[ -z "$1" ]] && echo "no resource directory supplied" && exit -1
[[ -z "$2" ]] && echo "no destination repository supplied" && exit -1

upload() {
    local local_repo="$1"
    local remote_repo="$2"
    local ct
    local user=${3:-${USER:-$(read -p "Username: "  user && [ -n "${user}" ] && echo ${user})}}
    local pwd=$(read -s -p "Password: "  pwd && [ -n "${pwd}" ] && echo ${pwd})
    echo ""
    declare -a pids
    for art in $(find "${local_repo}" -not -path '*/\.*' -type f -not -name 'index.html' | sed -n 's;./\(.*\);\1;p'); do

#        file extension
        case "$(echo ${art} | rev | cut -d'.' -f1 | rev)" in
            jar)
                ct="application/java-archive"
            ;;
            md5)
                ct="application/x-checksum"
            ;;
            pom)
                ct="application/x-maven-pom+xml"
            ;;
            sha1)
                ct="application/x-checksum"
            ;;
            txt)
                ct="text/plain"
            ;;
            xml)
                ct="application/xml"
            ;;
        esac
        (
            echo "${art} -> ${remote_repo}/${art}"
            curl -v -u "${user}:${pwd}" -X PUT -d "@$art" -H "Content-Type: $ct" "$remote_repo/$art" 2&>1 &&
            curl -I -u "${user}:${pwd}" "$remote_repo/$art" 2&>1
        )  &

        pids[${i}]=$!

    done
    for pid in ${pids[*]}; do
        wait ${pid}
    done
}
upload "$@"


texts: rock paper scissors game simplify in Python

texts:
I wrote rock paper scissors game using what I have learnt yet.It is while,for statements,list,tuple,dictionary and such simple things only.So I am interested how can I simplify this code using only what I have learnt(simple things)

Here is code

    k = input("Hello guys what are you names: ")
    j = input("and yours? ")
    print(f"""ok {k} and {j} let the game begin!"
    P.s. Type exit to quit game""")
    list = ["rock","paper","scissors"]
    while True:

        a_player = input(f"{k} choose: rock, scissors, paper : ").lower()
        if a_player == "exit":
            break
        b_player = input(f"{j} choose: rock, scissors, paper: ").lower()
        if b_player == "exit":
            break
        for type in list:
            if a_player == type and b_player==type:
                print("  Draw guys, draw")
                break
        if b_player != list[1] and b_player!=list[0] and b_player!=list[2] or (a_player != list[1] and a_player != list[0] and a_player != list[2]) :
            print("Please type correctly")

        if a_player == list[1]:
            if b_player == list[0]:
                print(f" {k} wins: paper beats rock")
            elif b_player ==list[2] :
                print(f"{j} wins: scissors beat paper")

        elif a_player == list[2]:
            if b_player == list[0]:
                print(f"{j} wins: rock beats scissors")
            elif b_player == list[1]:
                print(f"{k} wins: scissors beat paper")

        elif a_player == list[0]:
            if b_player == list[2]:
                print(f"{k} wins: rock beats scissors")
            elif b_player==list[1]:
                print(f"{j} wins: paper beats rock")


texts:
I got bored on my long weekend so I decided to have my coding exercise. And I successfully made a program that let you input the day and the month then it gives you the day of given date. But sadly it's only for 2014 calendar.

import java.io.*;

public class DaysToYears{
public static void main(String[] args) throws ArrayIndexOutOfBoundsException{
  BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
  try{
    String []yearName = {"January","February","March","April","May","June","July","August","September","October","November","December"};
    String []days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
    int []yearsCode = {6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
    int firstCase = 0;
    int secondCase = 0;
    String inputMonth = new String();
    int inputDate = 0;
      System.out.print("Enter your month: ");
        inputMonth = dataIn.readLine();
      System.out.print("Enter your date:  ");
        inputDate = Integer.parseInt(dataIn.readLine());
          for(int nodeCount=0;nodeCount<yearName.length;nodeCount++){
              if(inputMonth.equalsIgnoreCase(yearName[nodeCount])){
                if(inputDate < 7){
                    firstCase = (yearsCode[nodeCount] + inputDate + 3) % 7;
                    System.out.println(yearName[nodeCount] + " " + inputDate + " is " + days[firstCase]);
                    }else{
                      secondCase = (yearsCode[nodeCount] + inputDate + 3) % 7;
                      System.out.println(yearName[nodeCount] + " " + inputDate + " is " + days[secondCase]);
                      }
                    }
                  }
    }catch(IOException e){
      System.out.println("Error getting input!");
    }
  }
}


texts: System to handle the short lived async task

texts:
I'm developing an application in which there are many short-lived tasks which are run in separate threads. I've developed a generic and reusable system to handle such a requirement. The code snippet given below is using this system code plus the example client code to show how to use the system's API.

package com.demo;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

import java.util.concurrent.TimeUnit;

////////////////////////API to handle short lived async task///////////////////////////////////////////

/*
 * This class holds the threadpool executor instance and provide the submit method which in turn submit the task
 * to executor
 */

class AsyncTaskManager
{
    private ExecutorService service;

public AsyncTaskManager(ExecutorService service){
    this.service = service;
}

public <T> Future<T>  submit(Callable<T> callable){
    Future<T> result = service.submit(callable);
    return result;
}

public void shutdown(){
    service.shutdown();
    try {
        service.awaitTermination(60, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        service.shutdownNow();
    }
    service.shutdownNow();
}

}

/**
 * This is a wrapper class on Task object to make it async
 * @author jayesh
 *
 * @param <T>
 * @param <V>
 */

class AsyncTask<T extends Task<V>, V> implements Callable<V>{
private Task<V> task;

public AsyncTask(Task<V> task){
    this.task = task;
}

@Override
public V call() throws Exception {
    return task.doTask();
}

}

/**
 * Client will implement this interface to perform the task
 * @author jayesh
 *
 * @param <V>
 */

interface Task<V>{
    public  V doTask();
}

/////////////////////////////////////////End of API ////////////////////////////////////////

//////////////////////Use of API by client code /////////////////////////////////////////////

public class AsyncTaskManagerDemo {

public static void main(String[] args) throws InterruptedException, ExecutionException {

    AsyncTaskManager taskManager = new AsyncTaskManager(Executors.newCachedThreadPool());

    Task<String> urlLoader = new UrlLoaderTask("http://www.google.com");
    Task<Integer> wordCounter = new WordCounterTask("/var/tmp/test.txt");

    AsyncTask<Task<String>, String> asyncUrlLoader = new AsyncTask<Task<String>, String>(urlLoader);
    AsyncTask<Task<Integer>, Integer> asyncWordCounter = new AsyncTask<Task<Integer>, Integer>(wordCounter);

    Future<String> urlLoaderResult = taskManager.submit(asyncUrlLoader);
    System.out.println(urlLoaderResult.get());

    Future<Integer> wordCounterResult = taskManager.submit(asyncWordCounter);
    System.out.println(wordCounterResult.get());

    taskManager.shutdown();
}
}

/**
 * Task implementation which do the  task and returns result
 * @author xxx
 *
 */

class UrlLoaderTask implements Task<String>
{
private String url;
public UrlLoaderTask(String url){
    this.url = url;
}
@Override
public String doTask(){
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "returning content of url - " + url;
}
};

/**
 * Task implementation which do the  task and returns result
 * @author xxx
 *
 */

class WordCounterTask implements Task<Integer>
{
private String filePath;
public WordCounterTask(String filePath){
    this.filePath = filePath;
}
@Override
public Integer doTask(){
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return 1000; //returning no of words in a file
}
};

I am looking for a review on my system and its API.


texts: Javascript: Mapping combinations of input and possible suffix arrays leads to repetitive if statements

texts:
I am writing a program to combine the basic form of a word with suffix arrays following the choices from a form group (Angular 9) to receive the declination.

This is the flow:

The user inputs a word.
The user chooses the predefined grammar categories of the word (genus, class, animacy and others).
According to the choices of the user the input is mapped with an array of the corresponding suffixes.

Now, my problem is that I can not wrap my head around the problem to find a more dynamic solution than writing an if-statement for every possible combination of choices and the corresponding array of suffixes.

Right now I compare the values array from the user choices with every predefined combination array.
You will see in a second that this solution leads to a lot of repetitive code and I ask you to help me to find a better solution.

Two (of many possible) predefined conditions of choices plus the fitting suffix arrays

conditionOne = ['inanimate', 'm', '2', 'hard'];
conditionOneSuffixes = ['', 'а', 'у', 'а', 'ом', 'е', 'ы', 'ов', 'ам', 'ов', 'ами', 'ах'];
conditionTwo = ['animate', 'm', '2', 'hard'];
conditionTwoSuffixes = ['', 'а', 'у', 'а', 'ом', 'е', 'ы', 'ов', 'ам', 'ов', 'ами', 'ах'];

My first function to save the choices as values from angular reactive forms

setValues($event: string) {
    this.values = [];
    this.values = Object.values(this.substantiveFormGroup.value); // the user choices from the form group saved to an array
    this.setDeclination(this.values);
  }

My second function to map the fitting suffix array on the input (only two possible if statements)

setDeclination(values) {
    if (
      this.conditionOne.every(i => values // the predefinded array of choices
        .includes(i))) {
      this.declination = this.conditionOneSuffixes.map( // the corresponding suffix array
        suffixes => this.substantiveFormGroup.get("input").value + suffixes
      );
    }
    else if (
      this.conditionTwo.every(i => values // another predefinded array of choices
        .includes(i))) {
      this.declination = this.conditionTwoSuffixes.map( // the corresponding suffix array
        suffixes => this.substantiveFormGroup.get("input").value + suffixes
      );
    }
// else if (another condition) { and so on...}
    else this.declination = [];
  }

What would be a better, less repetitive solution?

Thank you for your time.


texts:
I'm currently learning Haskell, and as one of my first "proper" programs have created a mathematics quiz. It works like this:

A question is generated, with two numbers from 1 to 10 which need to be either added, multiplied or subtracted, for example 3 * 6.
The question is presented to the user, and they can write their answer and press Enter.
If the user's answer is the same as the actual answer to the question, they get one point towards their score. If the answer is incorrect their points stay the same.
This repeats 10 times, and the user's points are shown to them at the end.

I've implemented the operator part of question generation using an Operator data type with a Random instance. The numbers are generated with a randomSensibleInts x gen function, which generates x random numbers between 1 and 10.

The askQuestion function uses IO to get the user's answer, returning True if the answer was correct and False otherwise. Finally, in main, the askQuestion function is called 10 times, returning a [Bool]. fromEnum is then used to count True as one point and False as zero, which combined with sum creates a point total.

My code is as follows:

import System.Random

randomSensibleInts :: Int -> StdGen -> [Int]
randomSensibleInts quantity = take quantity . randomRs (1, 10)

data Operator = Add | Subtract | Multiply deriving (Eq, Enum)

instance Show Operator where
  show op = case op of
             Add -> "+"
             Subtract -> "-"
             Multiply -> "*"

instance Random Operator where
  random gen = case randomR (0, 2) gen of
                 (item, gen') -> (toEnum item, gen')

  randomR (lo, hi) gen = case randomR (fromEnum lo, fromEnum hi) gen of
                           (item, gen') -> (toEnum item, gen')

genQuestion :: StdGen -> (Int, Operator, Int, StdGen)
genQuestion gen = (numbers !! 0, operator, numbers !! 1, gen')
                  where numbers = randomSensibleInts 2 gen
                        (operator, gen') = random gen :: (Operator, StdGen)

askQuestion :: (Int, Operator, Int, StdGen) -> IO Bool
askQuestion (i1, o, i2, gen) = do
  putStrLn $ unwords ["Enter the answer to", show i1, show o, show i2] ++ ": "
  userAnswer <- getLine
  let trueAnswer = case o of
                     Add -> i1 + i2
                     Subtract -> i1 - i2
                     Multiply -> i1 * i2
  if (show trueAnswer) == userAnswer then do
    putStrLn "Well done!"
    return True
  else do
    putStrLn $ "Wrong - the answer was " ++ show trueAnswer
    return False

main = do
  gens <- mapM (const newStdGen) [1..10]
  let questions = map genQuestion gens
  answers <- mapM askQuestion questions
  putStrLn $ "Your score was " ++ show (sum $ map fromEnum answers)

Please let me know if my code can be made more "Haskell-like", for example if there are builtins to replace any of my custom functions. I'm also interested in pointfree style, so please let me know if any of my functions can be improved to use this. I'm also fairly certain this code can be shortened drastically.


texts: Use Symfony5 native rate-limiter to build a GuzzleRateLimiter middleware

texts:
By reading this post https://symfony.com/doc/current/rate_limiter.html I had an idea to use the Symfony rate_limiter as a GuzzleRateLimiterMiddleware.
What do you think about it? Do you think it is a good idea or not at all?
I had the idea to use that because existing rate limiter middleware for Guzzle (i.e. https://github.com/spatie/guzzle-rate-limiter-middleware) does not manage "shared rate limiter" across several processes running in same time in parallel. Seems symfony/rate-limiter manages that natively. I tested and seems it works but I would like feedback from experts :-).
The code of the RateLimiterMiddleware for guzzle:
<?php
namespace App\GuzzleMiddleware\RateLimiterMiddleware;
use Closure;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\RateLimiter\RateLimiterFactory;
class RateLimiter
{
    /** @var RateLimiterFactory */
    protected $guzzleRateLimiter;
    /**
     * RateLimiter constructor.
     * @param RateLimiterFactory $guzzleRateLimiter
     */
    public function __construct(RateLimiterFactory $guzzleRateLimiter)
    {
        $this->guzzleRateLimiter = $guzzleRateLimiter;
    }
    /**
     * @param callable $handler
     * @return Closure
     */
    public function __invoke(callable $handler): Closure
    {
        return function (RequestInterface $request, array $options) use ($handler) {
            $limiter = $this->guzzleRateLimiter->create('custom-guzzle-rate-limiter');
            while(!$limiter->consume()->isAccepted()){
                sleep(1);
            }
            return $handler($request, $options);
        };
    }
}

The yaml config to add the middleware above to guzzle (inside services.yaml):
GuzzleMiddleware\GuzzleLimiterMiddleware\RateLimiter:
        class: App\GuzzleMiddleware\RateLimiterMiddleware\RateLimiter

    GuzzleHttp\HandlerStack:
        class: GuzzleHttp\HandlerStack
        factory: [ 'GuzzleHttp\HandlerStack', create ]
        calls:
            - [ push, [ '@log_middleware', 'log' ] ]
            - [ push, [ '@GuzzleMiddleware\GuzzleLimiterMiddleware\RateLimiter' ] ]

Thanks in advance for any feedback.


texts: Listing the playlists on which each song appears

texts:
I created a way to export my Google Play playlists to a text file and also a way to export all of my songs in Google Play to a text file. Now I have both the song list (in an array format) and playlist data (in object and array format) in their respective text files. Here is a simplified version of the files:

[
    "song 1 name",
    "song 2 name",
    "song 3 name"
]

and

{
    "playlist 1": [
        "song 1",
        "song 3"
    ],
    "playlist 2": [
        "song 1"
    ]
}

When I run them in my script, it works correctly and creates the following output:

{
    "song 1": [
        "playlist 1",
        "playlist 2"
    ],
    "song 2": [],
    "song 3": [
        "playlist 1"
    ]
}

Here's my code:

var songInput = document.getElementById("songInput"),
    playlistInput = document.getElementById("playlistInput"),
    result = document.querySelector("textarea");

var songList,
    playlistData;

function loadData(id, elem) {
    if(elem.files
    && elem.files[0]) {
        let myFile = elem.files[0];
        let reader = new FileReader();

        reader.addEventListener('load', function (e) {
            if(id === "songInput")
                songList = JSON.parse(e.target.result);

            if(id === "playlistInput")
                playlistData = JSON.parse(e.target.result);

            checkBothAdded();
        });

        reader.readAsBinaryString(myFile);
    }
}

function checkBothAdded() {
    if(songList
    && playlistData) {
        getSongPlaylistData();
    }
}

var songData = {};
function getSongPlaylistData() {
    for(let song of songList) {
        let playlistsItsIn = [];

        Object.keys(playlistData).forEach(function(key) {
            if(playlistData[key].includes(song)) {
                playlistsItsIn.push(key);
            }
        });

        songData[song] = playlistsItsIn;
    }

    result.value = JSON.stringify(songData, null, '\t');
}

songInput.addEventListener("change", function() {
    loadData("songInput", this);
});

playlistInput.addEventListener("change", function() {
    loadData("playlistInput", this);
});
Song text file (generated from this answer): <input type="file" id="songInput">

Playlist text file (generated from this answer): <input type="file" id="playlistInput">

<textarea style="width: 500px; height: 200px;"></textarea>

It works on this small set of data I hand-wrote, but it freezes the browser page when I run it on my ~4,000 song list and substantial playlist file.

How can I do this same thing while helping it perform better so it doesn't freeze my browser tab?

I'm theorizing that it would work faster if I keep them as text files and try to parse each of the playlist names if the song is found, but I'm curious if I can speed up/reduce the memory of this object approach somehow.


texts: How should I set a daily method as executed, from inside or from outside?

texts:
I have the following code:

static void TimerElapsed(object sender, ElapsedEventArgs e)
{
    foreach (BIGService bigService in runningServices)
    {
        if (!bigService.ExecutedToday)
        {
            int executionResult = bigService.Execute();
            string serviceName = bigService.ToString();
            if (executionResult == 0)
            {
                EventLogger.WriteToEventLog("Success");
            }
            else
            {
                EventLogger.WriteToEventLog("Failure");
            }
        }
    }
}

where BIGService is an Abstract class, that has 5 descendants (5 individual service classes with this common parent).  The enclosing timer's interval is 7200. So it elapses in every 2 hours.

All services must be run only once a day. Therefore I created a bool ExecutedToday property and void SetAsExecuted method.

My question is: where do you recommend I should call the SetAsExecuted method? Which way is more subservient?  In the end of the Execute() method itself or in my copied code at the end of the if clause?

(Similar situations have happened to me several times, I just now have the time to ask other's opinion)