texts:
I made a simple form validation. It's working alright. The thing is I want my code to be optimized. Can somebody show me some pointers to improve my code? Thanks in advance.

$(document).ready(function(){

$('.submit').click(function(){
     validateForm();
});

function validateForm(){
    var nameReg = /^[A-Za-z]+$/;
    var numberReg =  /^[0-9]+$/;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    var names = $('#nameInput').val();
    var company = $('#companyInput').val();
    var email = $('#emailInput').val();
    var telephone = $('#telInput').val();
    var message = $('#messageInput').val();

    var inputVal = new Array(names, company, email, telephone, message);

    var inputMessage = ["name", "company", "email address", "telephone number", "message"];

    var textId = ["#nameLabel", "#companyLabel", "#emailLabel", "#telephoneLabel", "#messageInput"];

     $('.error').hide();

        if($.trim(inputVal[0]) === ""){
            $('#nameLabel').after(' Please enter your ' + inputMessage[0] + '');

        }else if(!nameReg.test(names)){
            $('#nameLabel').after(' Letters only');
        }

        if($.trim(inputVal[1]) === ""){
            $('#companyLabel').after(' Please enter your ' + inputMessage[1] + '');
        }

        if($.trim(inputVal[2]) === ""){
            $('#emailLabel').after(' Please enter your ' + inputMessage[2] + '');

        }else if(!emailReg.test(email)){
            $('#emailLabel').after(' Please enter a valid email address');
        }

        if($.trim(inputVal[3]) === ""){
            $('#telephoneLabel').after(' Please enter your ' + inputMessage[3] + '');

        }else if(!numberReg.test(telephone)){
            $('#telephoneLabel').after(' Numbers only');
        }

        if($.trim(inputVal[4]) === ""){
            $('#messageLabel').after(' Please enter your ' + inputMessage[4] + '');
        }

    return false;

}

});


texts:
I've replaced the following horrendous Excel formula (values and names have been replaced):

=IF(AND(SourceTable[@Field1]="Value1",SourceTable[@Field2]="Value2"),"Result1",
    IF(SourceTable[@Field2]="Value3","Result2",
        IF(AND(SourceTable[@Field1]="Value4",SourceTable[@Field3]="Value5"),"Result3",
            IF(AND(SourceTable[@Field1]="Value6",OR(SourceTable[@Field3]="Value7",SourceTable[@Field3]="Value8")),"Value9",
                VLOOKUP(SourceTable[@Field1];MatchingTable;2;0)))))

With a VBA Function so it would be easier to read and supposedly faster:

Function CUSTOMFUNCTION(oRngField1 As Range, oRngField2 As Range, oRngField3 As Range) As String

    'If imbrication
    If (oRngField1 = "Value1" And oRngField2 = "Value2") Then
        CUSTOMFUNCTION = "Result1"
        Exit Function
    ElseIf oRngField2 = "Value3" Then
        CUSTOMFUNCTION = "Result2"
        Exit Function
    ElseIf oRngField1 = "Value4" Then
        If oRngField3 = "Value5" Then
            CUSTOMFUNCTION = "Result3"
            Exit Function
        ElseIf (oRngField3 = "Value6" Or oRngField3 = "Value7") Then
            CUSTOMFUNCTION = "Result4"
            Exit Function
        End If
    End If

    'Vlookup if no match before
    Dim sTableMatchingFieldLookup As String
    Dim sTableMatchingFieldResult As String
    sTableMatchingFieldLookup = "MatchingTable[Field1]"
    sTableMatchingFieldResult = "MatchingTable[Field2]"
    CUSTOMFUNCTION = Range(sTableMatchingFieldResult)(Application.Match(oRngField1, Range(sTableMatchingFieldLookup), 0))

End Function

I get the same result as the function however it does it two times longer than the formula when working with 2k rows. Why isn't the code faster than the Excel formula? Can it be improved? The file is expected to grow so it means the code will be of no use.

Edit: Using more arguments improved the macro, see my response below.


texts: Router Class In a Lightweight MVC Boilerplate

texts:
I'm trying to come up with a simple router class. I considered using a Request class, but I think that will turn something simple into something overly complex. That is why I did not consider creating one for my framework.

class Router {

    private $uri;
    private $controller;
    private $action;
    private $params;

    public function __construct($uri) {
        $this->uri = $uri;
        $this->action = 'index';
        $this->params = array();
    }

    public function map() {
        $uri = explode('/', $this->uri);
        if (empty($uri[0])) {
            $c = new Config('app');
            $this->controller = $c->default_controller;
        } else {
            $this->controller = array_shift($uri);
            if (!empty($uri[1]))
                $this->action = array_shift($uri);
            if(!empty($uri[2]))
                $this->params = $uri;
        }
    }

    public function getController() {
        return $this->controller;
    }

    public function getAction() {
        return $this->action;
    }

    public function getParams() {
        return $this->params;
    }
}

In the bootstrap, I did this to map the url:

$uri = filter_var(rtrim(isset($_GET['url']) ? $_GET['url'] : null, '/'), FILTER_SANITIZE_URL);
$router = new Router($uri);
$router->map();

What can I do to improve this?


texts: Process files in all subdirectories and save output to new files based on their current path

texts:
Sample files:

./data/foo/file1.xml
./data/foo/bar/file2.xml
./data/baz/file3.xml

Corresponding output:

./out/foo/file1.xml.xml2
./out/foo/bar/file2.xml.xml2
./out/baz/file3.xml.xml2

The subproblems are:

Find all xml files in data/
Construct the output path: replace data/ with out/ and add an additional extension
Create the output path if it doesn't exist
Execute a script, redirect to output file in new path

I've been experimenting with find and I have come up with a solution that works on my test files:

find data/ -name "*.xml" -exec bash -c \
    'out=${1/data/out}.xml2; mkdir -p $(dirname "$out"); ./testscript.sh > $out' - {} \;

(testscript.sh contains echo "Hello World".)

But I'm not that good with bash, and this seems overly verbose, and might contain hidden errors.

Things I've thought about:

mkdir silently fails if the dir exists, so it'll work for multiple
files in the same dir, but maybe this entire script should be done in a loop in order to only call mkdir once per new dir.
${1/data/out} only replaces the first occurence of data, which should always exist and be the outermost directory in the variable (since relative paths are used). I'd prefer it if this was done in a more automatic and safe way though, if possible.

Side-note: I have full permissions in the current dir and all subdirs, but not on the entire machine.


texts: classList fallback (IE & older browsers)

texts:
I'm trying to make some JS code more browser compatible. So I've written an alternative to JS's classList providing its .add(), .remove() and .toggle() functionality because it is not or just partially supported in IE.

(I know there are exiting polyfills, but I like to have a good overview regarding my code.)

My test were successful but before I use it extensively I wanted to check with someone if they see any issues.

    function classes(type, element, targetClass){
            var classArray = element.className.split(/\s/);
            var index = classIndex(classArray, targetClass);
            // if target class is in class list
            if(index !== null){
                // multiple classes
                if(classArray.length > 1){
                    if(type == "remove" || type == "toggle") {
                        classArray.splice(index, 1);
                        element.className = classArray.join(" ");
                    }
                }
                // single class
                else {
                    if(type == "remove" || type == "toggle") {
                        element.className = "";
                    }
                }
            }
            // if target class is not in class list
            else {
                if(type == "add" || type == "toggle") {
                    element.className += " " + targetClass;
                }
            }
            // check if target class is in class list (returns index or null)
            function classIndex(array, targetClass){
                for(i=0; i<array.length; i++){
                    if(array[i]==targetClass){
                        return i;
                    }
                    if(i==(array.length-1)){
                        return null;
                    }
                }
            }
        }

Usage:

classes("toggle", myElement, "classToToggle")


texts:
My intent is to use this object to cache data from web responses. The cache object should only be valid for the current data.

var myCache = {

        Cache: { Date: '', Data: [] },

        AddData: function(Name, Data){
            myCache.CheckCache();
            myCache.Cache.Data[Name] = Data;
        },

        GetData: function(Name){
            myCache.CheckCache();
            return myCache.Cache.Data[Name];
        },

        HasData: function(Name){
            myCache.CheckCache();
            var data = myCache.Cache.Data[Name];
            var val = true;
            if(typeof data === "undefined" || data == null || data === '') {
                val = false;
            }
            return val;
        },

        CheckCache: function(){

            var currentDate = myCache.GetCurrentDate();
            var CacheDate = myCache.Cache.Date;
            if(CacheDate != currentDate){
                console.log('Reset Cache');
                myCache.Cache.Data = [];
                myCache.Cache.Date = currentDate;
            }
        },

        GetCurrentDate: function(){
            var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth() + 1;
            var yyyy = today.getFullYear();
            if(dd < 10) {
                dd = '0' + dd;
            }
            if(mm < 10) {
                mm = '0' + mm;
            }
            var returnDate = yyyy + '-' + mm + '-' + dd;
            return returnDate;
        }
    };

When the main page loads I call

myCache.CheckCache();

When I get data in the application I use the cache object as

   var data;
   if(myCache.HasData('UserData')){
       data = myCache.GetData('UserData');
   } else{
       data = myWebApi.Get(Url);
   }

Is there a better way of creating a cache object? Or any suggestions of improvment


texts: Fetching lists and finding one with the right name, with fallback on error or no match

texts:
I have a simple function:

func getList() (sendgrid.RecipientList, bool, agerr.E) {
    lists, err := client.GetRecipientLists()
    if err == nil {
        for _, l := range lists {
            if l.Name == myList {
                return l, true, nil
            }
        }
    }
    return sg.RecipientList{}, false, err
}

but my colleagues ask my to rewrite it into:

func getList() (sendgrid.RecipientList, bool, agerr.E) {
    lists, err := client.GetRecipientLists()
    if err != nil {
        return sg.RecipientList{}, false, err
    }
    for _, l := range lists {
        if l.Name == myList {
            return l, true, nil
        }
    }
    return sg.RecipientList{}, false, err
}

They argue that errors should be returned as fast as possible. Is it really so big problem? What is your opinion?


texts: Can parallel_bulk compete with curl command for insert in ES?

texts:
I got some documents (size about 300o/doc) that I'd like to insert in my ES index using the python lib, I got huge time difference between the code and using curl it's obvious that it's normal, but I'd like to know if time can be improved (compared to the ratio of time)

curl option takes about 20sec to insert and whole time 10sec (for printing ES result but after 20sec data is inserted)

curl -H "Content-Type: application/json" -XPOST
        "localhost:9200/contentindex/doc/_bulk?" --data-binary @superfile.bulk.json

With python option, I reached 1min20 as minimum, using the setting 10000/16/16 (chunk/thread/queue)

import codecs
from collections import deque
from elasticsearch import Elasticsearch
from elasticsearch.helpers import parallel_bulk

es = Elasticsearch()

def insert_data(filename, indexname):
    with codecs.open(filename, "r", encoding="utf-8", errors="ignore") as fic:
        for line in fic:
            json_line = {}
            json_line["data1"] = "random_foo_bar1"
            json_line["data2"] = "random_foo_bar2"
            # more fields ...
            yield {
                "_index": indexname,
                "_type": "doc",
                "_source": json_line
            }

if __name__ == '__main__':
    pb = parallel_bulk(es, insert_data("superfile.bulk.json", "contentindex"),
                       chunk_size=10000, thread_count=16, queue_size=16)
    deque(pb, maxlen=0)

Facts

I got a machine with 2 processors xeon 8-core and 64GB ram
I tried multiple values for each [100-50000]/[2-24]/[2-24]

Questions

Can I still improve the time ?
If not, should I think of a way to write the data on a file and then use a process for curl command ?

—————————

If I try only the parse part it takes 15sec :

tm = time.time()
array = []

pb = insert_data("superfile.bulk.json", "contentindex")
for p in pb:
   array.append(p)
print(time.time() - tm)            # 15

pb = parallel_bulk(es, array, chunk_size=10000, thread_count=16, queue_size=16)
dequeue(pb, maxlen = 0)
print(time.time() - tm)              # 90


texts:
I wrote a simple quadratic equation solver with Ruby to help me solve quadratic equations. Please tell me what I did right or wrong, and what I can do to improve it.

#!/usr/bin/ruby

if ARGV.length != 3
        STDERR << "Usage: #{$0} <a> <b> <c>\n"
        exit 1
end

a = ARGV[0].to_i
b = ARGV[1].to_i
c = ARGV[2].to_i

disc = b**2 - 4*a*c
d_str = (disc >= 0) ? (Math.sqrt(disc) % 1 == 0) ? Math.sqrt(disc).to_i : "√#{disc}" : "√#{disc}"

s = "#{-b} ± #{d_str}"
d = "#{2*a}"
puts "\e[4m#{s}\e[0m"
#puts "─"*(s.length)
puts d.center s.length


texts: ELisp function to allow file renaming in Emacs

texts:
As a disclaimer, this is the first function I have EVER written in Lisp or ELisp. Please, bash it as much as you would any other piece, but don't judge me for it please! :)

So, I realized I wanted a way to rename files without all the hassle of reopening the file etc. I googled and found a function at https://stackoverflow.com/questions/384284/can-i-rename-an-open-file-in-emacs (credit Steve Yegge).

However, it did not seem to work well with uniquify. Which was a problem. Having two files open and trying to rename the first one to the same name as the second one (for example CMakeLists.txt, which there might be many of) caused it to bail since it only checked the name of the buffer (which wasn't unique yet, as uniquify doesn't do it's thing before something needs uniquifying).

The only way I found to force a "re-uniquification" was to close the previous buffer and open the new file. This seems very inelegant...

(defun is-unique-name-for-buffer (new-name)
  (let ((file-name (buffer-file-name))
    (dir-name (file-name-directory buffer-file-name)))
  (let ((new-complete-name (concat dir-name new-name)))
  (progn (not (string-equal file-name new-complete-name))))))

(defun rename-file-and-buffer (new-name)
  "Renames both current buffer and file it's visiting to NEW-NAME."
  (interactive "sNew name: ")
  (let ((name (buffer-name))
    (filename (buffer-file-name))
    (dir-name (file-name-directory (buffer-file-name))))
    (if (not filename)
    (message "Buffer '%s' is not visiting a file!" name)
      (if (not (is-unique-name-for-buffer new-name))
      (message "A buffer named '%s' already exists in that location!" new-name)
    (progn
      (rename-file (file-name-nondirectory filename) new-name 1)
      (kill-buffer)
      (set-buffer (find-file (concat dir-name new-name))))))))


texts:
I tried to literally convert recursive algorithm taught here to iterative, by simulating the recursive stack exactly as much as possible.

I have tested my code and it passed all test cases.

Please let me know if any more improvements are possible.

Here is my code:

public class Graph
{
    private int tv; //total vertices
    private int te; //total edges

    private ArrayList<ArrayList<Integer>> adjacencyList;

    public Graph(int tv)
    {
        this.tv = tv;

        adjacencyList = new ArrayList<ArrayList<Integer>>(tv);

        for (int i = 0; i < tv; i++)
        {
            adjacencyList.add(i, new ArrayList<Integer>());
        }
    }

    //adds edge for undirected graph
    //s - source, d - destination
    public void addEdge(int s, int d)
    {
        //need to check s & d are with in bounds

        adjacencyList.get(s).add(d);
        adjacencyList.get(d).add(s);

        te++;
    }

    public void dfsIterative()
    {
        boolean[] isVisited = new boolean[tv];

        for (int v = 0; v < tv; v++)
        {
            if (!isVisited[v])
            {
                dfsIterativeUtil(v, isVisited);
            }
        }
    }

    //sv - start vertex
    private void dfsIterativeUtil(int sv, boolean[] isVisited)
    {
        class Node
        {
            int v; //vertex in a graph
            int i; //current index of v's adjacency list

            Node(int v, int i)
            {
                this.v = v;
                this.i = i;
            }
        }

        Deque<Node> stack = new LinkedList<>();
        stack.push(new Node(sv, -1));

        while (!stack.isEmpty())
        {
            int cv = stack.peek().v; //cv - current vertex

            if (!isVisited[cv])
            {
                System.out.print(cv + " ");
                isVisited[cv] = true;
            }

            ArrayList<Integer> cvAdjList = adjacencyList.get(cv);

            int ci = ++stack.peek().i; //ci - current index in cvAdjList

            if (ci>=cvAdjList.size())
            {
                stack.pop();
            }
            else
            {
                int vtx = cvAdjList.get(ci);

                if (!isVisited[vtx])
                {
                    stack.push(new Node(vtx, -1));
                }
            }
        }
    }
}


texts: Creating an enumerable by calling a function returning enumerables

texts:
The purpose of the application is very simple.
PlantList is a object containing a list of PlantConfiguration.

Each PlantConfiguration has two schedules: HourlySchedule and DailySchedule, as well as a TimeZone.

The program reads a PlantList object, stored as a JSON file in the settings, and returns an enumerable of Schedule, containing all the HourlySchedules, and the DailySchedule if it is midnight in a plant's timezone.

In addition to general comments about the code, I am looking for a way to improve the loop. Indeed, using the Concat feature to smash together all schedules as they come feels sub-optimal, and I figure this is a good occasion to learn about a new pattern.

public class Program
    {
        private readonly static log4net.ILog log = LogHelper.GetLogger();

        public static void Main()
        {
            var container = new UnityContainer();
            container.RegisterType<IPlantRepository, JsonPlantRepository>();

            IPlantRepository serverRepository = container.Resolve<IPlantRepository>();
            var plantList = serverRepository.GetPlants(MySettings.Default.Servers);

            if (MySettings.Default.Disabled == true)
            {
                log.Fatal("Script disabled");
                return;
            }

            UpdateValues(plantList);
        }

        private static void UpdateValues(PlantList plantList)
        {
            DateTime utcTopHourDate = GetUtcTopHourDate();
            IEnumerable<KpiSchedule> schedulesToUpdate = new List<KpiSchedule>();
            foreach(PlantConfiguration plant in plantList.Plants)
            {
                schedulesToUpdate = schedulesToUpdate.Concat(GetScheduleList(utcTopHourDate,plant));
            }
            //... Do stuff with the schedule list
        }

        private static IEnumerable<KpiSchedule> GetScheduleList(DateTime utcTime, PlantConfiguration plant)
        {
            var localDate = TimeZoneInfo.ConvertTimeFromUtc(utcTime, server.TimeZone);
            List<KpiSchedule> returnList = new List<KpiSchedule>
            {
                plant.HourlySchedule
            };

            if (localDate.Hour == 0)
            {
                returnList.Add(plant.DailySchedule);
            }

            return returnList;
        }

        private static DateTime GetUtcTopHourDate(int ForceHour = -1)
        {
            return new DateTime(
                DateTime.UtcNow.Year,
                DateTime.UtcNow.Month,
                DateTime.UtcNow.Day,
                DateTime.UtcNow.Hour,
                0,
                0,
                DateTimeKind.Utc
            );
        }
    }
}


texts: How to attach click to header child without reusing the code?

texts:
How can I optimize my jQuery?  I remove the extra code to attach click event to the header tags.

$("#dnn_htmlPan1.htmlPan").find(":header").click(function () {
    $("#dnn_htmlPan1").find("p").slideToggle("slow");
});
$("#dnn_htmlPan2.htmlPan").find(":header").click(function () {
    $("#dnn_htmlPan2").find("p").slideToggle("slow");
});
$("#dnn_htmlPan3.htmlPan").find(":header").click(function () {
    $("#dnn_htmlPan3").find("p").slideToggle("slow");
});
$("#dnn_htmlPan4.htmlPan").find(":header").click(function () {
    $("#dnn_htmlPan4").find("p").slideToggle("slow");

});
$("#dnn_htmlPan5.htmlPan").find(":header").click(function () {
    $("#dnn_htmlPan5").find("p").slideToggle("slow");

});


texts:
I am an extreme novice in Java and thus trying to practise some online exercises. One of them involved creating a basic student record system.
This is what I've come up with but I think a lot of things are quite redundant in my code so any reviews are greatly appreciated.

Student.java

class Student {

    int rollno;
    String name;

    Student(int r, String n) {
        this.rollno = r;
        this.name = n;
    }
}

StudentDB.java

import java.util.Scanner;

class Main {

    public static void getStudents(Student ...students) {
        int i = 1;
        for (Student x : students) {
            System.out.println("Student Number : " + i);
            System.out.println("Name -> "+ x.name);
            System.out.println("Roll Number -> " + x.rollno + "\n");
            i++;
        }
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Number of students? ");
        int num = sc.nextInt();

        String[] name = new String[num];
        int[] rollno = new int[num];

        System.out.println("Enter those " + num + " students one by one");

        for (int i = 0; i < num; i++) {
            System.out.println("Enter details for student no. " + (i + 1));
            System.out.print("Enter Name: ");
            name[i] = sc.next();
            System.out.print("Enter Roll Number: ");
            rollno[i] = sc.nextInt();
            System.out.println("\n");
        }

        Student[] students = new Student[num];

        for (int i = 0; i < num; ++i) {
            students[i] = new Student(rollno[i], name[i]);
        }

        getStudents(students);
    }
}

I would really love it if someone could tell me as to how can I pass those name and rollno arrays directly to the vararg function getStudents without creating that Student[] object array.


texts:
This problem is from MIT Course and I have implemented it in C++. Please review and suggest improvements.

  There is a party to celebrate celebrities that you get to attend
  because you won a ticket at your office lottery. Because of the high
  demand for tickets you only get to stay for one hour but you get to
  pick which one since you received a special ticket. You have access to
  a schedule that lists when exactly each celebrity is going to attend
  the party. You want to get as many pictures with celebrities as
  possible to improve your social standing. This means you wish to go
  for the hour when you get to hob-nob with the maximum number of
  celebrities and get selfies with each of them.

  We are given a list of intervals that correspond to when each celebrity
  comes and goes. Assume that these intervals are [i, j), where i and j
  correspond to hours. That is, the interval is closed on the left hand
  side and open on the right hand side. This just means that the
  celebrity will be partying on and through the ith hour, but will have
  left when the jth hour begins. So even if you arrive on dot on the th
  hour, you will miss this particular celebrity.

  Here’s an example:

  When is the best time to attend the party? That is, which hour should
  you go to?

#include <iostream>
#include <vector>
#include <algorithm>

struct range
{
    int start = 0;
    int end = 0;

    range() = default;
    range(int start_time, int end_time):
        start(std::move(start_time)),
        end(std::move(end_time))
        {}
};

int celeb_density(std::vector<range>& schedule)
{
    //sort according to start_time
    auto by_start_time = [](const range &a, const range &b)
    {
        return a.start < b.start;
    };
    std::sort(schedule.begin(), schedule.end(), by_start_time);

    int party_start = schedule[0].start;   //Party start time
    int party_end = schedule[schedule.size()-1].end;  //Party end time
    int max_count = 0, curr_max = 0, best_time, curr_best_time;

    int i = party_start;
    while (i < party_end)
    {
        for (int j = 0; j < schedule.size(); ++j)
        {
            if (i == schedule[j].start)
            {
                curr_max++;
                curr_best_time = i;
            }
            else if (i < schedule[j].start)
            {
                break;
            }

            if (i == schedule[j].end)
            {
                curr_max--;
            }
        }
        if (curr_max > max_count)
        {
            max_count = curr_max;
            best_time = curr_best_time;
        }
        i++;
    }
    return best_time;
}

int main()
{
    std::vector<range> schedule;

    int number_of_celebs;
    std::cout << "Enter number of celebrities attending party: ";
    std::cin >> number_of_celebs;

    std::cout << "Enter entry time and exit time for a celebrity\n";
    for (int i = 0; i < number_of_celebs; ++i)
    {
        int s, e;
        std::cin >> s >> e;
        schedule.push_back(range(s, e));
    }

    int best_time = celeb_density(schedule);
    std::cout << "Best time to attend party is from " << best_time << " to " << best_time + 1 << "\n";
}


texts:
I did not add generics to my code because I am new to Java. I am on my way in learning data structures and algorithms. I just want to make sure that my code is clean and efficient.

package Double_LinkedList;

class Node{
    int data;
    Node prev;
    Node next;

    void setData(int data){
        this.data = data;
    }

    int getData(){
        return data;
    }

    void setPrev(Node prev){
        this.prev = prev;
    }

    void setNext(Node next){
        this.next = next;
    }

    Node getPrev(){
        return prev;
    }

    Node getNext(){
        return next;
    }

    Node(int data, Node prev, Node next){
        this.data = data;
        this.next = next;
        this.prev = prev;
    }

    Node(int data){
        this.data = data;
    }

    Node(){    }
}

public class DoubleLinkedList{

    private Node head = null;
    private Node tail;

    private int length;

    public Node getHead(){
        return head;
    }

    public Node getTail(){
        return tail;
    }

    public int getData(Node node){
        return node.getData();
    }
    public int getLength(){
        return length;
    }
    public void insertFront(int data){

        Node newNode = new Node(data, null, head);

        if(head != null){
            head.setPrev(newNode);
        }
        head = newNode;
        if(tail == null){
            tail = newNode;
        }
        length++;
    }

    public void insertEnd(int data){

        Node newNode = new Node(data);
        newNode.setNext(null);

        if(tail != null){
            tail.setNext(newNode);
            newNode.setPrev(tail);
            tail = newNode;
        }
        if(head == null){
            head = newNode;
        }

        length++;
    }

    public void removeFront(){

        if(head != null){

            head.getNext().setPrev(null);
            head = head.getNext();

        }else if(head == null){

            System.out.println("List is empty");
            return ;

        }
        length--;
    }

    public void removeEnd(){

        if(tail != null){

            System.out.println("Tail not null");
            Node temp = tail.getPrev();
            temp.setNext(null);
            tail = temp;

        }else{
            System.out.println("Tail is null");
        }
        length--;
    }

    public void printList(){
        Node temp = head;

        while(temp != null){
            System.out.print(temp.getData()+" ");
            temp = temp.getNext();
        }
        System.out.println("");
    }
}


texts:
This is my first program in C. Do you have any improvements to this program? The program allows you to guess a number and also returns the attempts.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
/*
 * Sophie
 * 21.03.2021
 */
void main() {
     int secret;
     int guess;
     int try = 1;

    time_t t;
    srand((unsigned ) time(&t));
    secret = rand() % 100+1;

    printf("Please Enter value:\n");
    scanf("%i", &guess);

    while (guess != secret){
        if (guess > secret)
            printf("Guess too high. \n");
        else
            printf("Guess too low. \n");

        printf("Please enter a new value:\n");
        scanf("%i", &guess);
        try++;
    }
    printf("You gussed the number! \n");
    printf("You needed %i Tries.", try);

    getch();
}


texts:
This question presents two rather small Java programs: the first one is a simple client that reads text from command line and sends it to the server (TextSender.java); the server does nothing more but echoes the received text on the command line (TextReceiver.java)

TextSender.java:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class TextSender {

    public static final int PORT = 1857;

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java Main IP");
            return;
        }

        try (Socket clientSocket = new Socket(args[0], PORT);
             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);) {
            Scanner scanner = new Scanner(System.in);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();

                if (line.trim().equals("quit")) {
                    break;
                }

                // Terminate the line so that the receiver process knows that
                // the end of input is occured.
                out.print(line + "\n");
                out.flush();
            }
        } catch (UnknownHostException ex) {
            System.err.println("[ERROR] Could not reach host \"" +
                               args[0] + "\".");
            System.exit(1);
        } catch (IOException ex) {
            System.err.println("[ERROR] IO failed on host \"" +
                               args[0] + "\".");
            System.exit(1);
        }
    }
}

TextReceiver.java:

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Logger;

public class TextReceiver implements Runnable {

    public static final int PORT = 1857;

    public static void main(String[] args) {
        new Thread(new TextReceiver()).start();
    }

    @Override
    public void run() {
        ServerSocket serverSocket = null;
        Socket clientSocket = null;
        BufferedReader in = null;

        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("[RECEIVER] Waiting for a client.");

            clientSocket = serverSocket.accept();

            in = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));

            System.out.println("[RECEIVER] A client connected.");

            Scanner scanner = new Scanner(in);

            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
        } catch (IOException ex) {
            Logger.getLogger("CONNECTION").severe(ex.getMessage());

            if (in != null) {
                close(in, clientSocket, serverSocket);
            } else if (clientSocket != null) {
                close(clientSocket, serverSocket);
            } else if (serverSocket != null) {
                close(serverSocket);
            }
        }

        close(in, clientSocket, serverSocket);
    }

    private void close(Closeable... closeables) {
        for (Closeable c : closeables) {
            try {
                c.close();
            } catch (IOException ex) {

            }
        }
    }
}

Please, tell me anything I could improve.


texts:
I've decided to implement Python's any in C++. I've gone about this using templates to allow multiple types of data to be passed, instead of overloading the function multiple times. This is my first time using templates so I would really like feedback about my usage of them. I'm also fairly new with references and pointers, so I would like some criticism about my use of them as well. Of course, anything else is on the table and appreciated.

While writing this program, I realized std::any_of existed. So yes, I do know there's already a built-in method for this.

any.hpp

#ifndef ANY_HPP_INCLUDED
#define ANY_HPP_INCLUDED

/**
 * @author Ben Antonellis
**/

#include <vector>
#include <iostream>

/**
 * Returns True if any of the elements meet the callback functions parameters.
 *
 * @param elements - A list of elements.
 * @param callback - Callback function to invoke on each element.
 *
 * @return bool - True if parameters are met, False otherwise.
**/
template <typename List, typename Function>
bool any(List &elements, Function *callback) {
    for (auto element : elements) {
        if (callback(element)) {
            return true;
        }
    }
    return false;
}

#endif

And here's how I'm testing this function:

main.cpp

/**
 * @author Ben Antonellis
**/

#include "Any.hpp"

int main() {

    std::vector<double> doubleElements = {-1.0, -2.0, -3.0};
    std::vector<std::string> stringElements = {"Hello", "Goodbye", "Testing 123"};

    auto doubleFunc = [] (double number) {
        return number < 0;
    };
    auto stringFunc = [] (std::string string) {
        return string.length() >= 5;
    };

    /* Test Any Implementation */
    if (any(doubleElements, *doubleFunc)) {
        std::cout << "(any) Double Success." << std::endl;
    }
    if (any(stringElements, *stringFunc)) {
        std::cout << "(any) String Success." << std::endl;
    }

    return 0;
}

If you would like to compile and run, below is the script I'm using to compile and run this program.

run.sh

# Compile c++ program to .o file #
g++ -std=gnu++2a -c main.cpp # gnu++2a = Working draft for ISO C++ 2020 with GNU extensions #

# Compile .o file to executable #
g++ main.o -o app

# Run the executable #
./app

# Delete executable and .o files after running #
rm app main.o


texts: A simple Insertion Sort implementation in Java

texts:
I've written a InsertionSort algorithm in Java and I want a review on these:

Performance improvements.
Code conventions.
Algorithm design improvements.
Cleaner approaches.

I would highly appreciate if you can review based on the points above, and I would prefer if you can add more points on top if it if you find necessary.

Here's the code:

package com.hassanalthaf.sortingalgorithms;

public class InsertionSort {
    private final int SECOND_NUMBER_INDEX = 1;

    public int[] sort(int[] numbers) {
        for (int iterations = this.SECOND_NUMBER_INDEX; iterations < numbers.length; iterations++) {
            int currentNumber = numbers[iterations];
            int newIndex = iterations;

            for (int comparisons = iterations; comparisons > 0; comparisons--) {
                if (currentNumber < numbers[comparisons - 1]) {
                    newIndex--;

                    numbers[comparisons] = numbers[comparisons - 1];
                }
            }

            numbers[newIndex] = currentNumber;
        }
        return numbers;
    }
}

Here's my main class calling the InsertionSort sort method:

package com.hassanalthaf.sortingalgorithms;

public class Main {

    public static void main(String[] args) {
        int[] numbers = {1, 20, 51, 12, 43, 2, 20};

        InsertionSort insertionSort = new InsertionSort();

        numbers = insertionSort.sort(numbers);

        for (int iterations = 0; iterations < numbers.length; iterations++) {
            System.out.println(numbers[iterations]);
        }
    }

}

This produces an output:

1
2
12
20
20
43
51


texts: PermMissingElem- find the missing element in a given permutation in C#

texts:
I just encountered this question in codility but apparently this question has been asked in java already  (here, here).

Task description

A zero-indexed array A consisting of \$N\$ different integers is given. The array contains integers in the range \$[1..(N + 1)]\$, which means that exactly one element is missing.

Your goal is to find that missing element.

Write a function:

class Solution { public int solution(int[] A); }

that, given a zero-indexed array A, returns the value of the missing element.

For example, given array A such that:

  A[0] = 2
  A[1] = 3
  A[2] = 1
  A[3] = 5

the function should return 4, as it is the missing element.

Assume that:

  \$N\$ is an integer within the range [0..100,000];

  the elements of A are all distinct; each element of array A is an
  integer within the range \$[1..(N + 1)]\$.

Complexity:

  expected worst-case time complexity is \$O(N)\$;
  expected worst-case space complexity is \$O(1)\$, beyond input storage (not counting the storage required for input arguments).
  Elements of input arrays can be modified.

My approach is shown below:

  public static int permMissingElement(int [] elements)
            {
                if (elements.Length == 0)
                {
                return 0;
            }

            else if (elements.Length == 1)
            {
                return elements.First();
            }
            else
            {
                Array.Sort(elements);
                List<int> listOfElementsInTheArray = elements.ToList<int>();
                IEnumerable<int> missingNumber = Enumerable.Range(listOfElementsInTheArray.First(), listOfElementsInTheArray.Count).Except(listOfElementsInTheArray);

               return missingNumber.Count() == 0 ? 0 : missingNumber.First();

            }
        }

 static void Main(string[] args)
        {
            Console.WriteLine(permMissingElement(new int [] {2,3,1,5}));
            Console.ReadLine();
        }

Explanation: My approach was to display 0 if the array doesn't contain an element and return the element if it contains 1 . In addition, if the array contains 2 or more elements, it is sorted and converted to a list. Once its a list , i generate a complete sequence of the same list and remove any list that exists in the previous. I return the missing number afterwards . But surprising codility grades me in terms of correctness 20% and performance 80% and in general 50%. I know this can be better improved, any suggestions would be appreciated.


texts:
I wrote this code and it works fine for my purpose, to look for some values and copy paste the result to another sheet (online for selected column). I want to know the opinion from this community regarding my code.  I just learned the VBA for 1 week.

Option Explicit

Sub Analysis_ClientRating()
    Dim lastrow As Long, i As Long, rowppt As Long, colppt As Long
    Dim rowppt1 As Long, colppt1 As Long, rowppt2 As Long, colppt2 As Long
    Dim rowppt3 As Long, colppt3 As Long

    lastrow = ShNote.Range("C" & Rows.Count).End(xlUp).Row
    rowppt = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
    colppt = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
    rowppt1 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
    colppt1 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
    rowppt2 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
    colppt2 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
    rowppt3 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
    colppt3 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row

    Call Entry_Point

    For i = 6 To lastrow
        Select Case ShNote.Cells(i, 5).Value
            Case Is = 20
            ShNote.Cells(i, 3).Copy
            ShPPT.Cells(rowppt + 6, 3).PasteSpecial xlPasteValues
            ShNote.Cells(i, 5).Copy
            ShPPT.Cells(colppt + 6, 4).PasteSpecial xlPasteValues
            rowppt = rowppt + 1
            colppt = colppt + 1

            Case Is >= 17
            ShNote.Cells(i, 3).Copy
            ShPPT.Cells(rowppt1 + 6, 6).PasteSpecial xlPasteValues
            ShNote.Cells(i, 5).Copy
            ShPPT.Cells(colppt1 + 6, 7).PasteSpecial xlPasteValues
            rowppt1 = rowppt1 + 1
            colppt1 = colppt1 + 1

            Case Is >= 15
            ShNote.Cells(i, 3).Copy
            ShPPT.Cells(rowppt2 + 6, 9).PasteSpecial xlPasteValues
            ShNote.Cells(i, 5).Copy
            ShPPT.Cells(colppt2 + 6, 10).PasteSpecial xlPasteValues
            rowppt2 = rowppt2 + 1
            colppt2 = colppt2 + 1

            Case Is >= 11
            ShNote.Cells(i, 3).Copy
            ShPPT.Cells(rowppt3 + 6, 12).PasteSpecial xlPasteValues
            ShNote.Cells(i, 5).Copy
            ShPPT.Cells(colppt3 + 6, 13).PasteSpecial xlPasteValues
            rowppt3 = rowppt3 + 1
            colppt3 = colppt3 + 1
        End Select
    Next i

    Call Exit_Point
End Sub


texts:
I wrote John Conway's Game of Life in Java:

class GameOfLife {
    static int countSurrounding(int[][] board, int a, int b) {
        int count = 0;
        int[][] surrounding = {{a - 1, b - 1},
                               {a - 1, b    },
                               {a - 1, b + 1},
                               {a    , b - 1},
                               {a    , b + 1},
                               {a + 1, b - 1},
                               {a + 1, b    },
                               {a + 1, b + 1}};
        for (int i[]: surrounding) {
            try {
                if (board[i[0]][i[1]] == 1) {
                    count++;
                }
            }
            catch (ArrayIndexOutOfBoundsException e) {}
        }
        return count;
    }

    static void printBoard(int[][] board) {
        for (int[] i: board) {
            for (int j: i) {
                if (j == 1) {
                    System.out.print("#");
                }
                else {
                    System.out.print(".");
                }
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[][] nextBoard = {{0, 0, 0, 0, 0, 0, 0, 0, 0},
                              {0, 0, 0, 1, 0, 0, 0, 0, 0},
                              {0, 1, 0, 1, 0, 0, 0, 0, 0},
                              {0, 0, 1, 1, 0, 0, 0, 0, 0},
                              {0, 0, 0, 0, 0, 0, 0, 0, 0},
                              {0, 0, 0, 0, 0, 0, 0, 0, 0},
                              {0, 0, 0, 0, 0, 0, 0, 0, 0},
                              {0, 0, 0, 0, 0, 0, 0, 0, 0},
                              {0, 0, 0, 0, 0, 0, 0, 0, 0}};
        int[][] board = new int[nextBoard.length][nextBoard[0].length];
        for (int gen = 0; gen < 25; gen++) {
            for (int i = 0; i < nextBoard.length; i++) {
                for (int j = 0; j < nextBoard[i].length; j++) {
                    board[i][j] = nextBoard[i][j];
                }
            }
            printBoard(board);
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[i].length; j++) {
                    if (board[i][j] == 1 && !(countSurrounding(board, i, j) == 2 || countSurrounding(board, i, j) == 3)) {
                        nextBoard[i][j] = 0;
                    }
                    else if    (board[i][j] == 0 && countSurrounding(board, i, j) == 3) {
                        nextBoard[i][j] = 1;
                    }
                }
            }
        }
    }
}

How can I improve and optimize it?


texts:
I have employed an AES algorithm in order to encrypt files within a GUI. I was wondering if my algorithm is secure. Could I change anything to improve it? Is my IV secure and is it producing different random numbers each time? Am I transferring the salt successfully?

I know that I could improve this by making separate classes for the different methods however I am just doing this within the main for now. I'm quite new to cryptography so any feedback would be greatly appreciated!
    // author @Alex Matheakis
    public class AESFileEncryption {

// password to encrypt the file - how long should password be?
private static final String password = "UxIpOqSdNmSTuxZaShPu";

public static void main(String args[]) throws Exception {

    // file to be encrypted
    FileInputStream inF = new FileInputStream(GUI.AESinFile); // 'AESinFile' is a JFileChooser method from my GUI class

    // encrypted file
    FileOutputStream outF = new FileOutputStream("encrypted_file.des");

    // generate and write the salt
    SecureRandom sr = new SecureRandom();
    byte[] salt = new byte[16];
    sr.nextBytes(salt);
    outF.write(salt);

    // generate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); // salt, iteration count, key strength
    SecretKey tmp = skf.generateSecret(keySpec);
    SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); // returns key

    // initialise the cipher with secure padding
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    AlgorithmParameters p = cipher.getParameters();

    // iv used when initializing the cipher to make text more random

    byte[] iv = p.getParameterSpec(IvParameterSpec.class).getIV();
    outF.write(iv);

    // file encryption
    byte[] input = new byte[64];
    int bytesRead;

    while ((bytesRead = inF.read(input)) != -1) {
        byte[] output = cipher.update(input, 0, bytesRead);
        if (output != null)
            outF.write(output);
    }

    byte[] output = cipher.doFinal();
    if (output != null)
        outF.write(output);
        System.out.println("file encrypted");

    inF.close();
    outF.flush();
    outF.close();
    // inputScanner.close();

}

}


texts: Assembly beginner exercise: Calculate the square numbers from 1 to n

texts:
I try to learn (flat-, FASM-) Assembly currently.

For to become more familiar with the concept of branching I made a tiny program. Inspired by an exercise I had to do once in school when learning PHP.

"Write a program which takes an integer given by the user. The program then calculates and prints the square numbers from 1 to the given number."

Here my source code.
I have added comments in the code. Trying to explain my thoughts and motivations.

format PE console
entry start

include 'win32a.inc'

; ===========================================
; = Displays the square number from 1 until =
; =  number n. n is given by the user.      =
; = @param [ integer ] n - The upper        =
; =  limit. The last integer to calculate   =
; =  the square number of.                  =
; ===========================================

; - Example --------------------------------
; 100 // User have entered 100.
; 1
; 4
; 9
; 10  // 16 in base 10
; 19  // 25 in base 10
; 24  // 36 in base 10
; 31  //   ...
; 40
; 51
; 64
; 79

section '.text' code readable executable

start:
    call    read_hex ; Provided by teacher. Reads in a hexadecimal number from stdin.

    mov     ecx, eax
    mov     ebx, 1 ; First number ...

    cmp eax, 1000000 ; When the number received is smaller the upper limit ...
    jle createSquareNumbers ; ... then you do not have to override it.

    mov     ecx, ebp ; ... otherwise you override it with the upper limit.

createSquareNumbers:
    mov edx, 0
    mov eax, ebx
    mul ebx ; Multiply the number with itself.

    call print_eax ; ; Provided by teacher. Prints eax to stdin.

    inc ebx ; Go to the next integer.

    cmp ebx, ecx
    jle createSquareNumbers

    push    0
    call    [ExitProcess]

include 'training.inc'

It seems to work as expected.

But I'm sure there's a lot of room for improvements ...

So therefore: Hints and comments from more experienced Assembly programmers very appreciated. :)


texts: Simulation study in R with two variables and 10000 iterations

texts:
The generic version of what I am trying to do is to conduct a simulation study where I manipulate a few variables to see how that impacts a result. I'm having some speed issues with R. The latest simulation worked with a few iterations (10 per experiment). However, when I moved to a large-scale version (10k per experiment), the simulation takes too long (it has been running for 14 hours and is still going).

Below is the code (with comments) that I am running. Being a rookie with R, I am struggling to optimize the simulation. My hope is to learn from the comments and suggestions provided here to optimize this code and use the code future simulation studies.

Let me say a few things about what this code is supposed to do. I am manipulating two variables: effect size and sample size. Each combination is run 10k times (i.e., 10k experiments per condition). I initialize a data frame to store my results (called Results). I loop over three variables: Effect size, sample size, and iterations (10k).

Within the loops, I initialize four NULL components: p.test, p.rep, d.test, and d.rep. The former two capture the p-value of the initial t-test and the p-value of the replication (i.e., replicated under similar conditions). The latter two calculate the effect size (Cohen's d).

I generate my random data from a standard normal for the control condition (DVcontrol), and I use my effect size as the mean for the experimental condition (DVexperiment). I take the difference between the values and throw the result into the t-test function in R (paired-samples t-test). I store the results in a list called Trials and I rbind this to the Results data frame. This process is repeated 10k times until completion.

# Set Simulation Parameters
## Effect Sizes (ES is equal to mean difference when SD equals Variance equals 1)
effect_size_range <- seq(0, 2, .1) ## ES
## Sample Sizes
sample_size_range <- seq(10, 1000, 10) ## SS
## Iterations for each ES-SS Combination
iter <- 10000

# Initialize the Vector of Results
Results <- data.frame()

# Set Random Seed
set.seed(12)

# Loop over the Different ESs
for(ES in effect_size_range) {

  # Loop over the Different Sample Sizes
  for(SS in sample_size_range) {

    # Create p-value Vectors
    p.test <- NULL
    p.rep <- NULL
    d.test <- NULL
    d.rep <- NULL

    # Loop over the iterations
    for(i in 1:iter) {

      # Generate Test Data
      DVcontrol <- rnorm(SS, mean=0, sd=1)
      DVexperiment <- rnorm(SS, mean=ES, sd=1)
      DVdiff <- DVexperiment - DVcontrol
      p.test[i] <- t.test(DVdiff, alternative="greater")$p.value
      d.test[i] <- mean(DVdiff) / sd(DVdiff)

      # Generate Replication Data
      DVcontrol <- rnorm(iter, mean=0, sd=1)
      DVexperiment <- rnorm(iter, mean=ES, sd=1)
      DVdiff <- DVexperiment - DVcontrol
      p.rep[i] <- t.test(DVdiff, alternative="greater")$p.value
      d.rep[i] <- mean(DVdiff) / sd(DVdiff)
    }

    # Results
    Trial <- list(ES=ES, SS=SS,
                  d.test=mean(d.test), d.rep=mean(d.rep),
                  p.test=mean(p.test), p.rep=mean(p.rep),
                  r=cor(p.test, p.rep, method="kendall"),
                  r.log=cor(log2(p.test)*(-1), log2(p.rep)*(-1), method= "kendall"))
    Results <- rbind(Results, Trial)
  }
}


texts: forever.sh - should keep a process alive forever

texts:
This script's only responsibility is to keep a process alive. Forever.
It's sole dependencies shall be bash and coreutils. I'm not sure if it would be compatible with sh, that would be even better.

#!/bin/bash
#
# (c) Netcetera AG
# Author:  Christian Mäder
date="10.07.2015"
version="1.0"
#

respawn() {
    while true; do
        $myprocess
        exit_code=$?

        now=`date +"%Y-%m-%dT%H:%M:%S%z"`

        if [ $exit_code -ne 0 ] || [ $force -eq 1 ]; then
            if [ $quite -eq 0 ]; then
                echo "$now | service $myprocess crashed with code $?. Restarting after ${timeout}s." >&2
            fi
            sleep $timeout
        else
            break
        fi
    done
}

help() {
    echo "Usage: $1 [-f] [-q] [-t #] \"command\""
    echo "       $1 -v"
    echo "       $1 -h"
    echo
    echo "  -v             : Shows the version of this tool."
    echo "  -h             : Shows this help text."
    echo "  -f             : Restart the program even if it exited with an exit"
    echo "                   status of 0."
    echo "  -q             : If set, this script won't write anything to stdout or stderr."
    echo "  -t #           : Seconds for how long the script should wait until"
    echo "                   the restart happend."
    echo "  command        : The command to execute continuously until it exits"
    echo "                   gracefully or forever if -f is set."
    echo
    echo "Example: $1 -f -t 2 \"echo hello, see you again in two.\""
}

about() {
    echo "Respawns a process which dies. Hence it keeps it runnig forever."
    echo "Version $version from $date."
}

while true; do
    case "$1" in
        "--help")
            help $0
            break
            ;;
        "-h")
            help $0
            break
            ;;
        "-v")
            about
            break
            ;;
        "-q")
            quite=1
            shift
            ;;
        "-f")
            force=1
            shift
            ;;
        "-t")
            if [[ $2 =~ '^[0-9]+$' ]]; then
                timeout=$2
                shift
            fi
            shift
            ;;
        *)
            if [ $# -eq 0 ]; then
                about
                echo
                help $0
            else
                quite=${quite-0}
                force=${force-0}
                timeout=${timeout-"1"}
                myprocess=$1
                respawn
            fi
            break
            ;;
    esac
done

For everyone's reference have I created a gist with an updated version which incorporated the feedback.


texts:
I am trying to learn OOP using PHP5 and I wrote a simple MySQL connection class. Please take a look and give me some feedback on better practices, critical errors, and any other feedback you can provide.

Note: in the verifyDatabaseConnection method, I used an @ symbol to curb the error I was receiving.

<?php
class Mysql
{
        private $user;
        private $pass;
        private $data;
        private $host;

        public function __construct($user,$pass,$data,$host)
        {
                $this->user = $user;
                $this->pass = $pass;
                $this->data = $data;
                $this->host = $host;
                $this->verifyNullFields();
        }
        private function verifyNullFields()
        {
                if($this->user == NULL)
                {
                        print('mysql error : username is null');
                }
                if($this->data == NULL)
                {
                        print('mysql error : database name is null');
                }
                else if($this->host == NULL)
                {
                        print('mysql error : host name is null');
                }
                else
                {
                        $this->verifyDatabaseConnection();
                }
        }
        private function verifyDatabaseConnection()
        {

                $link = @mysql_connect($this->host,$this->user,$this->pass);
                if(!$link)
                {
                        die('mysql error : databse connection issue');
                }
                else
                {
                        $this->verifyDatabaseExist();
                }
        }
        private function verifyDatabaseExist()
        {
                $db = mysql_select_db($this->data);
                if(!$db)
                {
                        die('mysql error : database selection issue');
                }
        }

}
?>

<?php
$m = new Mysql("root","","test","localhost");
 ?>


texts: Dynamic insert function for PDO (for any case)

texts:
I created a dynamic insert function for PDO.

It does work, but I want to be sure that it is secure and well coded.

function insertNewRows($pdo, $table, $fields, $placeholders, $values=''){

    if($values){
        $result = $pdo->prepare("INSERT INTO $table ($fields) VALUES ($placeholders)");
        $result->execute($values);
    }else{
        $result = $pdo->query("INSERT INTO $table ($fields) VALUES ($placeholders)");
    }

}

Using positional placeholders:

$session_id = '1000000001';
$createdBy  = 12;

$fields = "session_id, username, createdBy";
$placeholders = "?, 'boss 21', ?";

$values = array($session_id,  $createdBy);

insertNewRows($pdo, 'web_statistics', $fields, $placeholders, $values);

Not using positional placeholders:

$fields = "session_id, username, createdBy";
$placeholders = "'abc', 'boss 25', 3";

insertNewRows($pdo, 'web_statistics', $fields, $placeholders);

I want to use the same tactic for UPDATE and SELECT functions, so am I good to do so with the code I have written?


texts:
I tried to develop a new way to check if a number is divisible by 9. I have written my code and it is working fine. I'm not allowed to use *,/ and %.

int isDivby9(int x)
{
    int status = 0;
    int divby8 = 0;

        int orgx = x;
        if(x>=9)
        {
            divby8 = x >> 3;
            int olddivby8 = divby8;
            while(divby8 >= 9)
            {
                divby8 = divby8 - 9;
            }
            if(divby8 == (orgx - (olddivby8 << 3)))
            {
                status = 1;
            }
            else{
                status = 0;
            }
            x = divby8;
        }

    return status;
}

Can someone please check if this is a good way to check if a number is divisibility by 9? Is it too complex? Is there any better way to perform the same? I also referred to the logic given in geeksforgeeks.


texts:
I'm trying to use riverpod for login with a Laravel backend. Right now I'm just returning True or False from the repository. I've set a form that accepts email and password. The isLoading variable is just to show a circle indicator. I've run the code and  it works but not sure if I'm using riverpod correctly.
Is there a better way to do it?
auth_provider.dart
class Auth{
  final bool isLogin;
  Auth(this.isLogin);
}
class AuthNotifier extends StateNotifier<Auth>{
  AuthNotifier() : super(Auth(false));
  void isLogin(bool data){
    state = new Auth(data);
  }
}
final authProvider = StateNotifierProvider((ref) => new AuthNotifier());

auth_repository.dart
class AuthRepository{
  static String url = "http://10.0.2.2:8000/api/";
  final Dio _dio = Dio();
  Future<bool> login(data) async {
    try {
        Response response = await _dio.post(url+'sanctum/token',data:json.encode(data));
        return true;
    } catch (error) {
        return false;
    }
  }
}

login_screen.dart
void login() async{
  if(formKey.currentState.validate()){
    setState((){this.isLoading = true;});
    var data = {
      'email':this.email,
      'password':this.password,
      'device_name':'mobile_phone'
    };
    var result = await AuthRepository().login(data);
    if(result){
        context.read(authProvider).isLogin(true);
        setState((){this.isLoading = false;});
    }else
      setState((){this.isLoading = false;});
  }
}


texts:
I wrote this program to backup everything in document root and the MySQL database in Linux environments. It is aimed for Debian/Ubuntu environments to say the least.

zip -r /var/www/html/html-$(date +\%F-\%T).zip /var/www/html -x "*/cache/*"

mysqldump -u root -p --all-databases > /var/www/html/db-$(date +\%F-\%T).sql
zip /var/www/html/db-$(date +\%F-\%T).zip /var/www/html/db-*.sql
rm /var/www/html/db-*.sql

zip -r /var/www/html/html-$(date +\%F-\%T).zip /db-$(date +\%F-\%T).zip /var/www/html/all_zipped.zip
rm -rf db-$(date +\%F-\%T).zip html-$(date +\%F-\%T).zip

I make the assumption that the document root is under /var/www/html/. In the past it was /var/www/ but I don't think the change is going to be reverted or changed in the next 10 years...


texts:
I just did an interview where the last challenge was to write a function that reads a minesweeper matrix from a file and marks how many bombs there are around each cell. I had 20 min and had a < comparison that should have been <=. My main question is how I could have done it faster since it only took me 5 min to locate the bug and fix it. The other thing I would like to know is what a reviewer probably would think about it.

Here's my hacky code (the only requirement was to produce the correct output):

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

void read_matrix(char* dest, char const* file)
{
  FILE* input = fopen(file, "r");
  char temp[128];
  int d= 0;

  fread(temp, 1, sizeof temp, input);

  for(int i = 0; i < 128; ++i){
    if(' ' != temp[i] && '\n' != temp[i]){
      dest[d++] = temp[i];
    }
  }
  fclose(input);
}

char _grid_at(char const* grid, int x, int y)
{
  return grid[y * 8 + x];
}

int _surround_count(char const* grid, int x, int y)
{
  int count = 0;
  int x0 = x;
  int x1 = x;
  int y0 = y;
  int y1 = y;

  if(x > 0){
    x0 = x - 1;
  }
  if(x < 7){
    x1 = x + 1;
  }
  if(y > 0){
    y0 = y - 1;
  }
  if(y < 7){
    y1 = y + 1;
  }

  // here's where the problem was
  for(x = x0; x <= x1; ++x){
    for(y = y0; y <= y1; ++y){
      if('X' == _grid_at(grid, x, y)){
        count += 1;
      }
    }
  }

  return count;
}

void mark_field(char* dest, char const* src)
{
  for(int x = 0; x < 8; ++x){
    for(int y = 0; y < 8; ++y){
      if('X' != src[y*8+x]){
        dest[y*8 + x] = '0' + _surround_count(src, x, y);
      }
      else {
        dest[y*8 + x] = 'X';
      }
    }
  }
}

void print_field(char const* field)
{
  for(int i = 0; i < 64; ++i){
    putchar(field[i]);
    if((i & 7) == 7){
      putchar('\n');
    }
  }

}

int main(int argc, char* argv[])
{
  char matrix[64];

  read_matrix(matrix, argv[1]);
  print_field(matrix);
  puts("------------");

  char count[64];
  mark_field(count, matrix);
  print_field(count);

  return 0;
}

Input:

X O O X X X O O
O O O O X O X X
X X O X X O O O
O X O O O X X X
O O X X X X O X
X O X X X O X O
O O O X O X O X
X O X X O X O X

Output:

X 1 1 X X X 3 2
3 3 3 5 X 5 X X
X X 3 X X 5 5 4
3 X 5 5 6 X X X
2 4 X X X X 6 X
X 3 X X X 5 X 3
2 4 5 X 6 X 5 X
X 2 X X 4 X 4 X


texts: Mapping a user input string to a corresponding block of code

texts:
My idea is I can define a block of code (inline) that corresponds to an input string then can call that block of code when given that input.

I'm used to this sort of structure in JavaScript like so:

var lookup = {
  "foo": function() { ... },
  "bar": function() { ... },
};

lookup["foo"];

And I'm looking for a C# equivalent. So far I've come up with the following and it seems to work, but I don't know if it could be simplified or improved upon.

class CortanaFunctions
{
        /*
        This is the lookup of VCD CommandNames as defined in
        CustomVoiceCommandDefinitios.xml to their corresponding actions
        */
        public readonly static Dictionary<string, Delegate> vcdLookup = new Dictionary<string, Delegate>{

            /*
            {<command name from VCD>, (Action)(async () => {
                 <code that runs when that commmand is called>
            })}
            */

            {"OpenToDoList", (Action)(async () => {
                StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"ToDo.doc");
                await Launcher.LaunchFileAsync(file);
            })},

            {"OpenReddit", (Action)(async () => {
                 Uri website = new Uri(@"http://www.reddit.com");
                 await Launcher.LaunchUriAsync(website);
             })},

        };

        /*
        Register Custom Cortana Commands from VCD file
        */
        public static async void RegisterVCD()
        {
            StorageFile vcd = await Package.Current.InstalledLocation.GetFileAsync(
                   @"CustomVoiceCommandDefinitions.xml");
            await VoiceCommandDefinitionManager
                   .InstallCommandDefinitionsFromStorageFileAsync(vcd);
        }

        /*
        Look up the spoken command and execute its corresponding action
        */
        public static void RunCommand(VoiceCommandActivatedEventArgs cmd)
        {
            SpeechRecognitionResult result = cmd.Result;
            string commandName = result.RulePath[0];
            vcdLookup[commandName].DynamicInvoke();
        }

 }

VCD file:

<?xml version="1.0" encoding="utf-8" ?>

<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.2">
  <CommandSet xml:lang="en-us" Name="CustomCommands">
   <CommandPrefix> listen here </CommandPrefix>
    <Example> open to do list, open reddit</Example>

    <Command Name="OpenToDoList">
      <Example> open to do list </Example>
      <ListenFor> open to do list</ListenFor>
      <Feedback> opening your to do list</Feedback>
      <Navigate/>
    </Command>

    <Command Name="OpenReddit">
      <Example> open reddit </Example>
      <ListenFor> open reddit </ListenFor>
      <Feedback> opening reddit </Feedback>
      <Navigate/>
    </Command>
  </CommandSet>
</VoiceCommands>


texts:
Here's a little command-line utility written in Rust that connects to a Denon AV receiver and sends a command, then receives the response. It's a simple TCP client that takes its command from the first argument.

extern crate encoding;

use std::env;
use std::io::prelude::*;
use std::net::TcpStream;
use encoding::{Encoding, EncoderTrap};
use encoding::all::ASCII;

const HOST: &'static str = "10.21.39.30:23";

fn main() {
    let command = match env::args().nth(1) {
        Some(cmd) => cmd,
        None => {
            let my_name = env::args().nth(0).unwrap();
            panic!("Usage: {} [command]", my_name)
        }
    };
    let mut command_bytes = ASCII.encode(&command, EncoderTrap::Strict).unwrap();
    command_bytes.push('\r' as u8);
    let mut stream = TcpStream::connect(HOST).unwrap();
    stream.write_all(&command_bytes).unwrap();
    let mut response = String::new();
    stream.read_to_string(&mut response).unwrap();
    println!("{}", response);
}

Is there a better way to handle this stuff? My questions are mostly:

Is there an alternative to all of these unwrap() calls?
It seems better (to me) to add the '\r' to the end of the command, making command_bytes mutable, than to call stream.write() another time. Think so?
The response will be ASCII, so stream.read_to_string() seems appropriate. It also seems like a bad idea for a network client to read with no size limits. Any good way to deal with this?
Any other structural stuff here that is glaringly bad? I'm starting to understand coding in Rust, I think, but haven't yet developed my own style. Early corrections would be greatly appreciated.


texts: Optimization for SQLite result set parsing

texts:
I am retrieving information from an SQLite database that gives me back around 20 million rows that I need to process. This information is then transformed into a dict of lists which I need to use. I am trying to use generators wherever possible.

What optimizations can be done?

I am either getting a “Killed” message or it takes a really long time to run. The SQL result set part is working fine. I tested the generator code in the Python interpreter, and it doesn’t have any problems. I am guessing the problem is with the dict generation.

Update for clarity:

I have 20 million rows in my result set from my SQLite database. Each row is of the form:

(2786972, 486255.0, 4125992.0, 'AACAGA', '2005’)

I now need to create a dict that is keyed with the fourth element ‘AACAGA’ of the row. The value that the dict will hold is the third element, but it has to hold the values for all the occurences in the result set.

So, in our case here, ‘AACAGA’ will hold a list containing multiple values from the SQL result set. The problem here is to find tandem repeats in a genome sequence. A tandem repeat is a genome read (‘AACAGA’) that is repeated at least three times in succession.

For me to calculate this, I need all the values in the third index as a list keyed by the genome read, in our case ‘AACAGA’. Once I have the list, I can subtract successive values in the list to see if there are three consecutive matches to the length of the read. This is what I aim to accomplish with the dictionary and lists as values.

#!/usr/bin/python3.3
import sqlite3 as sql

sequence_dict = {}
tandem_repeat = {}

def dict_generator(large_dict):
     dkeys = large_dict.keys()
     for k in dkeys:
         yield(k, large_dict[k])

 def create_result_generator():
     conn = sql.connect('sequences_mt_test.sqlite', timeout=20)
     c = conn.cursor()
     try:
         conn.row_factory = sql.Row
         sql_string = "select * from sequence_info where kmer_length > 2"
         c.execute(sql_string)
     except sql.Error as error:
         print("Error retrieving information from the database : ", error.args[0])
     result_set = c.fetchall()
     if result_set:
         conn.close()
         return(row for row in result_set)

 def find_longest_tandem_repeat():
     sortList = []
     for entry in create_result_generator():
         sequence_dict.setdefault(entry[3], []).append(entry[2])

     for key,value in dict_generator(sequence_dict):
         sortList = sorted(value)
         for i in range (0, (len(sortList)-1)):
             if((sortList[i+1]-sortList[i]) == (sortList[i+2]-sortList[i+1])
                 == (sortList[i+3]-sortList[i+2]) == (len(key))):
                   tandem_repeat[key] = True
                   break

     print(max(k for k, v in tandem_repeat.items() if v))

 if __name__ == "__main__":
     find_longest_tandem_repeat()


texts:
I'm very new to VBA and have put together a macro that currently does exactly what I want: copy cells from one worksheet to another, clear the cells copied, refresh my pivot tables and save the file.

Here is what I am using for it:

Sub Copyinfo()

    On Error GoTo Err_Execute

    Sheet1.Range("A17:R17").Copy
    Sheet2.Range("A2").Rows("2:2").Insert shift:=xlDown
    Sheet2.Range("A2").Rows("2:2").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

    Sheet1.Range("C5:I16, Q5:R5").ClearContents
Err_Execute:
    If Err.Number = 0 Then MsgBox "Copied Data", vbInformation Else _
    MsgBox Err.Description

    ThisWorkbook.RefreshAll

    ThisWorkbook.Save
End Sub

What I want to know is whether this macro will be stable as I continue to add lines of data to it in the future. Essentially I want to minimize the risk of the file crashing or my data being erased. Otherwise, would anyone have any suggestions to offer me to improve this? Thank you.


texts: Converting raw thesaurus data into nice JSON file

texts:
I'm trying to improve my dirty data wrangling code into something nice, readable & reliable.

I believe I've done fairly well here, although maybe I should have some docstrings on my functions. Still, I believe it's fairly readable without them.

I'd love some feedback on ways to improve! This script parses raw data from Gray Ward's fantastic public-domain thesaurus into a more readable JSON file.

import sys
import os
import json

# Parses Grady Ward's public-domain thesaurus, available at
# ftp://svr-ftp.eng.cam.ac.uk/pub/comp.speech/dictionaries/moby/

def main():
    database = {}

    if len(sys.argv) < 3:
        print("Usage: make_database <input filename> <ouput filename>")
        sys.exit(1)

    filename = sys.argv[1]

    if not os.path.exists(filename):
        print(f"File {filename} doesn't exist.")
        sys.exit(1)

    # Read file into database
    with open(filename, "r") as file:
        try:
            parse_file(file, database)
            print("Finished reading the file.")
        except Exception as err:
            print(f"Failed to read file {filename} with error {err}")
            sys.exit(1)

    # Write database to output file as JSON
    output_filename = sys.argv[2]
    with open(output_filename, "w+") as file:
        try:
            data = json.dumps(database)
            file.write(data)
            print(f"Finished writing to file {output_filename}")
        except Exception as err:
            print(f"Failed to read write to file {output_filename} with error {err}")
            sys.exit(1)

def parse_file(file, database):
    for line in file:
        (word, thesaurus) = parse_line(line)
        database[word] = thesaurus

def parse_line(line):
    words = line.strip().split(",")
    return (words[0], words[1:])

if __name__ == '__main__':
    main()

I'm still a student -- I'm trying to improve my code readability & maintainability.

It is a commandline utility that can be called like:

make_database <input filename> <output filename>


texts: Using reference to head node while reversing linked list using recursion

texts:
Referring to my previous post, should I consider using current pointers for this code snippet for reversing a linked list using recursion?

public static List ReverseRecursion(List head){

        List newHead;
        List current = head;

        if(current == null){
            return null;
        }
        if(current.next == null){
            head = current;
            return head;
        }
        newHead = ReverseRecursion(current.next);
        current.next.next = current;
        current.next = null;
        return newHead;

    }

Or should I consider the solution without using current node as someone pointed out in their solution like this?

public static List ReverseRecursion(List head){
    List newHead;

    if(head == null){
        return null;
    }
    if(head.next == null){
        return head;
    }

    newHead = ReverseRecursion(head.next);
    head.next.next = head;
    head.next = null;
    return newHead;
}


texts: Generic sequence splitter in Common Lisp

texts:
I wrote a function split-seq-by-n which accepts a sequence and a number and splits the sequence into subsequences of length n (the last subsequence getting the remaining elements). It works on all subclasses of 'sequence, among others 'string, 'cons, 'vector etc.

;; Splits sequence into subsequences of length n
(defun split-seq-by-n (seq n)
  (labels ((seq-split (seq n &optional acc orig-n)
         (cond ((zerop (length seq)) (nreverse acc))
           ((zerop n) (seq-split seq
                          orig-n
                          (cons (subseq seq 0 0) acc)
                          orig-n))
           (t (seq-split (subseq seq 1)
                      (1- n)
                      (cons (concatenate (class-of seq)
                             (if acc (car acc) (subseq seq 0 0))
                             (list (elt seq 0)))
                        (cdr acc))
                      orig-n)))))
    (seq-split seq n nil n)))

Any comments, improvements, critiques welcome.


texts:
I have a private function in PHP that takes a given URL string and just leave the Alpha or numeric and certain punctuation left. I need the stripping of string due to having it match against ElasticSearch and ElasticSearch doesn't take it too kindly for special characters when it comes to exact match.

The following function so far is working fine.

protected function stripSpecialCharater($string)
{
    $string = iconv("Windows-1252","UTF-8",urldecode($string));
    $string = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $string);
    return preg_replace('/[^a-zA-Z0-9Ã§&-©‚Âƒâ€˜\s]/', '', $string);
}

Can it be better? is there a lib that does this better? I've used Laravel Validation service where you can specify alpha_dash but this is not for validation but rather I need the left over to see if there is a match to the Database Storage for a search.


texts: Printing dynamic ascii-art shapes based on user input


texts: Calculator for area and perimeter of a window

texts:
This program calculates wood length and area of glass required for the window.
I am a beginner in C# and I want to know how professional programmers will write program like this.

        double width, height, woodLength, glassArea;
        const double MAX_WIDTH = 5.0;
        const double MIN_WIDTH = 0.5;
        const double MAX_HEIGHT = 3.0;
        const double MIN_Height = 0.75;
        string widthString, heightString;
        Console.WriteLine("please enter width of the window");
       widthString = Console.ReadLine();
        width = Convert.ToDouble(widthString);
        if (width < MIN_WIDTH)
        {
            Console.WriteLine("you enter vaule less than min width \n"+ "using mininium one");
            width = MIN_WIDTH;
        }
        if (width>MAX_WIDTH)
        {
            Console.WriteLine("you entered value grater than MaX width\n" + "using maxuimum one");

            width = MAX_WIDTH;
        }
        Console.WriteLine("please enter your height of the window");
        heightString = Console.ReadLine();
        height = double.Parse(heightString);
        if (height<MIN_Height)
        {
            Console.WriteLine("you enter vaule less than min width \n" + "using mininium one");
            height = MIN_Height;

        }
        if (height > MAX_HEIGHT)
        {
            Console.WriteLine("you enter value grater than Max height\n" + "using maxuimum one");
            height = MAX_HEIGHT;
        }
        woodLength = 2 * (width+height);
        glassArea =  (width * height);
        Console.WriteLine("the lenth of the wood is "+woodLength+"feet");
        Console.WriteLine("the area of the glass is " + glassArea +"m^2");


texts:
I'm creating a 2D game in JS, and I've made the generic class that all objects in the game will be (I've decided they are all circular for now).

An object has motion and angMotion array properties which contain the 0th, 1st and 2nd derivatives of the object's (angular) motion.

I've also introduced aliases for each of these derivatives (like acc for acceleration, etc).

Upon initialization, the default for all derivatives should be 0.

I'm satisfied with how the class works as it is now as long as it remains 2 dimensional and I don't need higher derivatives of (angular) motion.

However, I feel that my code is repetitive in some places which would require changes in multiple places supposing I want to change how it works slightly.

Eg. I've considered the possibility of wanting to include higher derivatives of motion (without introducing more aliases like jerk) or changing the dimension I'm working in (ignore angular motion in this case).

Note: I wanted the derivatives of (angular) motion to be stored in arrays so that I can loop over them to simulate Physics using Taylor's Expansion as shown below. The simulatePhysics function works regardless of the number of derivatives or dimension.

I'm also wondering from a design point of view - would it be a better idea to put simulatePhysics as a method of the game instead of the object?

class Game2DObject {
  constructor(options) {

    if (options) {

      this.motion = options.motion || []
      this.angMotion = options.angMotion || []

      this.dis = options.dis || [0, 0]
      this.vel = options.vel || [0, 0]
      this.acc = options.acc || [0, 0]

      this.angDis = options.angDis || 0
      this.angVel = options.angVel || 0
      this.angAcc = options.angAcc || 0

      this.radius = options.radius || 0
      this.mass = options.mass || 0

    } else {

      this.motion = [[0, 0], [0, 0], [0, 0]]
      this.angMotion = [0, 0, 0]
      this.radius = 0
      this.mass = 0
    }
  }
  //motion
  get dis() {
    return this.motion[0]
  }

  set dis(x) {
    this.motion[0] = x
  }

  get vel() {
    return this.motion[1]
  }

  set vel(x) {
    this.motion[1] = x
  }

  get acc() {
    return this.motion[2]
  }

  set acc(x) {
    this.motion[2] = x
  }
  //angMotion
  get angDis() {
    return this.angMotion[0]
  }

  set angDis(x) {
    this.angMotion[0] = x
  }

  get angVel() {
    return this.angMotion[1]
  }

  set angVel(x) {
    this.angMotion[1] = x
  }

  get angAcc() {
    return this.angMotion[2]
  }

  set angAcc(x) {
    this.angMotion[2] = x
  }

  simulatePhysics(dt) {
    function taylor(arr) {
      return arr.reduceRight((acc, cur, i) => acc * dt / (i + 1) + cur, 0)
    }

    for (var dim = 0; dim < this.motion[0].length; dim++) {
      for (var deriv = 0; deriv < this.motion.length; deriv++) {
        this.motion[deriv][dim] = taylor(this.motion.slice(deriv).map((cur) => cur[dim]))
      }
    }

    for (var deriv = 0; deriv < this.angMotion.length; deriv++) {
      this.angMotion[deriv] = taylor(this.angMotion.slice(deriv))
    }
  }
}

//*DEBUG

var a = new Game2DObject({acc: [-6, 0], angVel: 9})
console.log(a)
console.log(a.dis[0] = 1)
console.log(a.dis[1] = 5)
console.log(a.acc[1] = -2)
console.log(a)

a.simulatePhysics(1)
console.log(a)
a.simulatePhysics(1)
console.log(a)
a.simulatePhysics(1)
console.log(a)

Output:


texts:
I wanted to build a Inverse Document Frequency function, because in my opinion was not easy to do with scikit and I wanted also to show how it works for educational reasons.
Also reading this question on stack.
So I build this function.
It works, not sure about the efficency of my solution.
Let me know what do you think.
def idf(corpora,term="None"):
  """A function for calculating IDF, it takes a list of list as corpora, a term "t"
  and returns the relative IDF"""

  occurences=sum([ 1 for sublist in test for x in sublist if term in x])
  tot_doc=len(corpora)
  if occurences==0:
    print("Error")
  else:
    idf=round(1+np.log(tot_doc/occurences),3)
    return idf

test=[['I like beer'],['I like craft beers'],['I like ALE craft beers'],
      ['If I have to choose a craft beer, I will take the IPA craft beer']]

beer=idf(corpora=test,term='beer')
craft_beer=idf(corpora=test,term='craft')
ipa=idf(corpora=test,term='IPA')
print(beer)
print(craft_beer)
print(ipa)

Output:
  1.0
  1.288
  2.386


texts:
What is considered to be a good programming practice for returning value from the function? For example, if we have a function in C named list* after( list *node), which returns the node which is after the node pointer.

First option:

node *after(node *first_ptr, node *nod_ptr)
{

    if (!(is_last(first_ptr, nod_ptr)) && !( first_ptr==NULL) && nod_ptr != NULL ) {

        while (first_ptr != nod_ptr && first_ptr != NULL){

            first_ptr = first_ptr->next;

        }

        return first_ptr != NULL ? first_ptr->next : NULL;

    }

     return NULL;

}

Second option:

node *after(node *first_ptr, node *nod_ptr)
{

    node *temp=NULL;
    if (!(is_last(first_ptr, nod_ptr)) && !( first_ptr==NULL) && nod_ptr != NULL ) {

        while (first_ptr != nod_ptr){

            first_ptr = first_ptr->next;
            temp = first_ptr;
            if(temp == NULL){

              break;
            }
            temp = temp->next;
        }

    }

     return temp;

}

Here node is typedef structure and next is a pointer to next element in the list and is_last(node *,node *) checks whether the second argument pointer is the last element in the list having start pointer as the first argument.

I'm wondering, in general, if big functions are necessary. Which seems nicer to understand?


texts: Quick estimation for empirical permutation and correlation test in R

texts:
I have two matrices (a, b), each including 3 genes and 6 observations. I have estimated the Spearman correlation for gene pairs (rcorr.observed). Then I want to do an empirical permutation (1000 times) and estimate the correlation for each time, then achieve a Pval_estim file. Since I have a very huge datasets (23000*23000), the script is very slow. I wonder if you could help me to speed it up. I have also used some code from (+).

a<-structure(c(7.284640193, 8.386102403, 10.27187091, 6.56612737,
8.969982518, 10.03221978, 7.193522121, 7.358283395, 10.92117745,
7.162802801, 8.297228578, 11.36980277, 7.865611714, 7.999185693,
10.33028086, 6.831671275, 8.953536984, 8.826461297), .Dim = c(3L,
6L), .Dimnames = list(c("DDR1_MIR4640", "RFC2", "HSPA6"), c("a_1", "a_2", "a_3",     "a_4", "a_5", "a_6")))

b<-structure(c(9.1048886, 6.4114527, 5.7281808, 9.4302985, 6.2576226,
4.871274, 9.187927, 5.9036324, 4.3635891, 8.6896685, 6.6680496,
5.5445622, 8.9274641, 6.4394849, 5.5175364, 7.8629553, 8.4304969,
6.1402062), .Dim = c(3L, 6L), .Dimnames = list(c("FAM174B", "SV2B",
"RBPMS2"), c("b_1", "b_2", "b_3", "b_4", "b_5", "b_6")))

rcorr.observed<- structure(c(0.00309597514569759, -0.0526315793395042,                 -0.108359135687351,
NA, -0.0567595474421978, -0.0299277603626251, NA, NA, -0.116615064442158
), .Dim = c(3L, 3L))

library(Hmisc)
Pval_estim<-matrix(nrow = 3, ncol = 3)
number_of_permutations = 1000
diff.random = NULL
for(i in 1:nrow(a))
  {
  for(j in 1:nrow(b))
  {
    if(i>=j)#selecting only lower part of the symmetric matrix
      {
    combined<-as.numeric(t(c(a[i,], b[j,])))
for (k in 1 : number_of_permutations)
  {
    shuffled = sample (combined, length(combined))
    a.random = shuffled[1 : 6]
    b.random = shuffled[7 : length(combined)]
    diff.random[k] = rcorr(a.random, b.random, type="spearman")$r[1,2]
}
Pval_estim[i,j] = sum(abs(diff.random) >= abs(rcorr.observed[i,j])) /             number_of_permutations
}}
print(i)
}


texts: Merges given list of integer entries acccordingly

texts:
I am developing a 2048 program in Python. As a part of that project, I am working on merging method that merges the given integer entries.

I am interested in some suggestion to improve my code.

def creating_resulting_list(length_line):
    """
    Function that create a resulting_list with equal number of \
    zeros as length of line
    """
    from itertools import repeat
    return list(repeat(0, length_line))

#BEGIN Test
#print creating_resulting_list(2) == [0, 0]
#print creating_resulting_list(0) == []
#END Test

def moving_non_zeros(line, resulting_list):
    """
    Function that moves non zero entries in line \
    to left most in resulting_list
    """
    if not all(line):
        index_resulting_list = 0
        for dummy_value in line:
            if dummy_value:
                resulting_list[index_resulting_list] = dummy_value
                index_resulting_list += 1
    else:
        resulting_list = line[:]
    return resulting_list

#BEGIN Test
#result_list = moving_non_zeros([4, 0, 4, 4], creating_resulting_list(4))

#result_list = moving_non_zeros([16, 16, 4, 4], creating_resulting_list(4))
#END Test

def locating_same_values(result_list):
    """
    Function that locates and merges the same values
    """
    for dummy_index, dummy_value in enumerate(result_list):
        if dummy_index+1 < len(result_list) and dummy_value == result_list[dummy_index+1]:
            result_list[dummy_index] += result_list[dummy_index+1]
            result_list[dummy_index+1] = 0
            if not len(result_list[dummy_index+1:]) > 2:
                return moving_non_zeros(result_list, creating_resulting_list(len(result_list)))
    return result_list

#BEGIN Test

print locating_same_values([16, 16, 4, 4])
print locating_same_values([2, 2, 2, 2, 2])
#END Test

def merge(line):
    """
    Function that merges a single row or column in 2048.
    """
    result_list = creating_resulting_list(len(line))
    result_list = moving_non_zeros(line, result_list)
    return locating_same_values(result_list)


texts: Poker deck class /w generator function and list comprehensions

texts:
There are multiple aspects in the code I do not really like. [card for card in ...] looks really lame, also [x.pop() for i in range(y)]. I'm looking forward for any recommendation.

from random import shuffle

class Deck(object):
    suits = range(4)
    ranks = range(13)

    @classmethod
    def generator(cls, suits, ranks):
        for suit in suits:
            for rank in ranks:
                yield({'suit': suit, 'rank': rank})

    def __init__(self):
        self.cards = [card for card in Deck.generator(Deck.suits, Deck.ranks)]
        shuffle(self.cards)

    def deal(self, amount):
        return [self.cards.pop() for i in range(amount)]

print Deck().deal(5)


texts:
I have one file with indexes.  For example, they are:

1    Fruit
2    Meat
3    Fish
4    Salmon
5    Pork
6    Apple

And a dictionary, because I want to match entries that I choose:

similar = {'1' : '6', '2' : '5'}

Since they are on the same file, my program scans for the '1' on the file, and then re-scans from the beginning looking for the '6'. Same with all the numbers, always re-scanning.

It's a very large file with a lot of numbers.

similar = { '4719' : '4720c01' }

for aline in invFormatted:
    lines = aline.split("\t") #Splits the CSV file on every tab.
    lotID = lines[0]
    partNO = lines[1] #Splits and gets the part that would be the "index"
    if similar.has_key(partNO):
        for alines in invFormatted:
            liness = alines.split("\t")
            lotIDmatch = liness[0]
            partNOmatch = liness[1]
            if liness[1] == similar[partNO]:

Would there be a way to make it so it only scans it once?  Or any other ideas to put better this program?

There is a text file formatted this way:

51689299  4719    Medium Azure    Riding Cycle
51689345  4720c01 Trans-Clear Wheel & Tire Assembly

In real life, it would have thousands of entries.

Then, my Python file 'knows' that the part number 4719 matches the part number 4720c01 via the similar dictionary:

similar = { '4719' : '4720c01' }

Now, what I think does:

invFormatted = open('export.txt', 'r') #Opens the file with the part numbers

with open ('upload.txt', 'a') as upload:

    upload.write("<INVENTORY>") #Something that would be on the export

    for aline in invFormatted:
        lines = aline.split("\t") #Splits the text file on every tab
        lotID = lines[0] #The lot ID is the first word
        partNO = lines[1] #Part number the second one
        if partNO in similar: #Sees if the part number in question has a match, if YES
            for alines in invFormatted: #Searchs my inventory file again to see if the match is in my inventory
                liness = alines.split("\t")
                lotIDmatch = liness[0]
                partNOmatch = liness[1]
                if liness[1] == similar[partNO]: #if YES, prints out what I want it to print, and goes back to the first step
                    upload.write("blabla")

    invFormatted.close()

    upload.write("\n</INVENTORY>")


texts: Get Next Working Date, skip weekends and holidays

texts:
The object is to be able to pass some dates (start date, holiday) and the number of days you want to skip. We only want to skip working days, not weekends and holidays.

Just let me know what you'd do different than what I have. The code works, but I was told there are issues with it, but not told what issues they are.

function getWDays($startDate,$holiday,$wDays){

$d = new DateTime( $startDate );
$t = $d->getTimestamp();
$h = strtotime($holiday);

// loop for $wDays days
for($i=0; $i<$wDays; $i++){

    // 1 day = 86400 seconds
    $addDay = 86400;

    $nextDay = date('w', ($t+$addDay));
    if($nextDay == 0 || $nextDay == 6) {
        $i--;
    }
    $t = $t+$addDay;
    if ($t == $h) {
        // lets make sure the holiday isn't one of our weekends
        if(!$nextDay == 0 || !$nextDay == 6) {
            $t = $t+$addDay;
        }
    }
}

$d->setTimestamp($t);

return $d->format( 'Y-m-d' );

}

echo getWDays("2013-08-29","2013-09-02", 3)


texts:
I am doing a code challenge of codesignal.com which ask for following things:
Given an array of integers, sort its elements by the difference of their largest and smallest digits. In the case of a tie, that with the larger index in the array should come first.

Example

For a = [152, 23, 7, 887, 243], the output should be
digitDifferenceSort(a) = [7, 887, 23, 243, 152].

Here are the differences of all the numbers:

152: difference = 5 - 1 = 4;
23: difference = 3 - 2 = 1;
7: difference = 7 - 7 = 0;
887: difference = 8 - 7 = 1;
243: difference = 4 - 2 = 2.

23 and 887 have the same difference, but 887 goes after 23 in a, so in the sorted array it comes first.
I wrote following code using python3 and it passes all normal tests but it cannot pass execution time tests. How can I improve my code to decrease it's execution time for list with considerable amount of elements?

def digitDifferenceSort(a):
    diff = []
    for i in a:
        i = list(str(i))
        diff.append(i)

    for i in range(len(diff)):
        for j in range(i+1, len(diff)):
            if int(max(diff[i])) - int(min(diff[i])) > int(max(diff[j])) - int(min(diff[j])):
                diff[j], diff[i] = diff[i], diff[j]
            elif int(max(diff[i])) - int(min(diff[i])) == int(max(diff[j])) - int(min(diff[j])):
                diff[i], diff[j] = diff[j], diff[i]
    new_list = []
    for i in diff:
        b = ''
        for j in i:
            b = b + j

        new_list.append(int(b))

    return new_list


texts:
I would like to gather ideas on how to refactor the JavaScript/NodeJS controller code below to be more aesthetic. The code is using the koa framework thus I use yield commands. I also use mongoose (I'm waiting for 3.9.2 which will support promises).

As a Ruby on Rails developer, I'm searching for a Rails-style way on writing NodeJS programs.

'use strict'

/*
 * Model dependencies
 */

var _ = require('lodash')
var parse = require('co-body')
var db = require('mongoose-glue')

/*
 * User controller.
 */

module.exports = {

  /*
   * Lists available users.
   */

  index: function*(id) {
    var skip, limit
    skip = Math.max(0, this.query.skip)
    limit = Math.min(10, this.query.limit)
    this.body = yield db.model('user').find().skip(skip).limit(limit).exec()
  },

  /*
   * Displays user with an id.
   */

  show: function*(id) {
    this.body = yield db.model('user').findById(id).exec()
    this.status = this.body ? 200 : 404
  },

  /*
   * Creates a new user.
   */

  create: function*() {
    var data
    try {
      data = yield formData(this, 'name')
      this.body = yield createUser(data)
      this.status = 201
    } catch(e) {
      this.body = e
      this.status = 403
    }
  },

  /*
   * Updates user with an id.
   */

  update: function*(id) {
    var data
    try {
      data = yield formData(this, 'name')
      this.body = yield updateUser(id, data)
    } catch(e) {
      this.body = e
      this.status = 403
    }
  },

  /*
   * Removes user with an id.
   */

  destroy: function*(id) {
    var item
    try {
      item = yield destroyUser(id)
      this.status = item ? 200 : 404
    } catch(e) {
      this.body = e
      this.status = 403
    }
  },

}

/*
 * Create user thunk
 */

function createUser(data) {
  return function(next) {
    db.model('user').create(data, next)
  }
}

/*
 * Update user thunk.
 */

function updateUser(id, data) {
  return function(next) {
    db.model('user').findByIdAndUpdate(id, data, next)
  }
}

/*
 * Create user thunk
 */

function destroyUser(id) {
  return function(next) {
    db.model('user').findByIdAndRemove(id, next)
  }
}

/*
 * Returns form data.
 */

function *formData(ctx) {
  var data
  data = yield parse.form(ctx)
  data = _.any(arguments) ? _.pick(data, arguments) : data
  return data
}


texts: Extract list of selected contractors by matching serialized array in Rails

texts:
I'm working on an application where I have a Company model setup as follows:

class Company < ActiveRecord::Base
  has_many :employee_roles
  has_many :employees
  validates :company_name, uniqueness: true
  serialize :contractors, Array

end

Contractors is related to the company as a serialized array and saves the data in the db as ["2", "1"] where 2 and 1 are the id's of the contractors.

My code to extract the list of selected contractors from this is:

def coach_list
  @contractors = Contractor.where({ verified: true,
                        validated: true })
              .where('membership_type != ?', Contractor.membership_types["no_membership"])
  @company = Company.find(contractor_company_params[:company_id])
  @selected_contractors = @company.contractors.map { |c| Contractor.find(c.to_i) }
  @unselected_contractors = @contractors - @selected_contractors
end

I'm not sure if this is the best way to extracted @selected_contractors and @unselected_contractors


texts: Executing a task at a particular time in the morning using ScheduledExecutorService

texts:
I have a task which I need to run every 6 in the morning. I have the below code which does the job and uses ScheduledExecutorService.

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

int hour = calendar.get(Calendar.HOUR_OF_DAY);
int delayInHour = hour < 6 ? 6 - hour : 24 - (hour - 6);

System.out.println("Current Hour: "+hour);
System.out.println("Comuted Delay for next 5 AM: "+intDelayInHour);

scheduler.scheduleAtFixedRate(new MyTask(), intDelayInHour, 24, TimeUnit.HOURS);

I am opting for code review to see whether it can be improved or not.