texts: Simple UDP server/client written in Python to report back IP address

texts:
I'd like to get some feedback/criticism on my attempt to write a simple client/server application that reports back the (client's) global IP address.

It would be nice if you could comment on the UDP socket setup, general security or any other drawbacks you were able to spot. Since this is my first attempt in writing Python network code (or Python in general other than tinkering) please be harsh!

#! /usr/bin/env python

# grip 0.0.1, external IP address lookup utility.
# usage: grip hostname [port]
#        grip -l [hostname] [port]
#        grip -h

from __future__ import print_function

import sys
from socket import *

MODE_SERVER = 0
MODE_CLIENT = 1

READ_BUFFER = 15
NULL_BUFFER = 1

DEFAULT_HOST = ''
DEFAULT_PORT = 20815

EXIT_SUCCESS = 0
EXIT_FAILURE = 1
EXIT_SYNTAX  = 2

USAGE = '''\
grip 0.0.1, external IP address lookup utility.
usage: grip hostname [port]
       grip -l [hostname] [port]
       grip -h

Options:
  -h        display this help message and exit
  -l        run in listen mode, to report back remote hosts' IP addresses

Request mode:
  The hostname may be provided in either IP address or DNS format.
  The port number - if unspecified - defaults to 20815.

Listen mode:
  In listen mode the program will try to serve requests on all
  available interfaces unless explicitly told not to.\
'''

def num(n):
  try:
    return int(n)
  except ValueError:
    return None

class Server:
  """Reports back the remote host's IP address"""
  def __init__(self, socket):
    self.socket = socket

  def listen(self, host, port):
    self.socket.bind((host, port))

    try:
      while 1:
        data, address = self.socket.recvfrom(NULL_BUFFER)
        self.socket.sendto(address[0], address)
    except KeyboardInterrupt:
      pass

    return EXIT_SUCCESS

class Client:
  """xyz"""
  def __init__(self, socket):
    self.socket = socket

  def request(self, host, port):
    code = EXIT_SUCCESS

    self.socket.sendto('', (host,port))
    self.socket.settimeout(2)

    try:
      data, saddr = self.socket.recvfrom(READ_BUFFER)
      print(data)
    except:
      code = EXIT_FAILURE;
      print('Error: Request timed out', file=sys.stderr)

    self.socket.close()
    return code

def main():
  args   = list(sys.argv[1:])
  argsno = len(args)

  mode = MODE_CLIENT

  hostname = DEFAULT_HOST
  port = DEFAULT_PORT

  # Mere invocation is NOT supported
  if argsno == 0:
    print(USAGE, file=sys.stderr)
    sys.exit(EXIT_SYNTAX)

  # Display a helpfull message when asked
  if '-h' in args:
    print(USAGE)
    sys.exit(EXIT_SUCCESS)

  if '-l' in args:
    mode = MODE_SERVER

    args.remove('-l')
    argsno -= 1

  if mode == MODE_SERVER:
    if argsno > 1:
      hostname = args[0]
      port = num(args[1])

    if argsno == 1:
      if num(args[0]) is not None:
        port = num(args[0])
      else:
        hostname = args[0]

    try:
      serv = Server(socket(AF_INET, SOCK_DGRAM))
      retval = serv.listen(hostname, port)
    except:
      sys.exit(EXIT_FAILURE)

  if mode == MODE_CLIENT:
    hostname = args[0]

    if argsno > 1:
      port = num(args[1])

    try:
      cl = Client(socket(AF_INET, SOCK_DGRAM))
      retval = cl.request(hostname, port)
    except:
      sys.exit(EXIT_FAILURE)

  sys.exit(retval)

if __name__ == "__main__":
  main()


texts:
Can I make this program that extracts text data from a file (size in MBs) even better performance-wise?  I need to reduce the execution time.

import java.io.*;

public class ReadData {

    public static void main(String[] args) {

        FileReader input = null;
        BufferedReader br = null;

        try {

            input = new FileReader("C:/Projects/Test/HPCamDrv.log");
            br = new BufferedReader(input);
            String str;

            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
        }

        catch (IOException e) {
            e.printStackTrace();
        }

        finally {

            try {
                input.close();
                br.close();
            }

            catch (IOException x) {
                x.printStackTrace();
            }

        }
    }
}


texts: knockout js refresh observable array from ajax

texts:
The following code refreshes an observable array of Run objects by calling an api method every 5 seconds. This code is working, but it seems like there's probably a utility method I'm missing that would handle merging the array from the ajax response with the existing observable array. Any suggestions are appreciated.

...
var that = this
that.Active = ko.observableArray()
that.refreshActive = function() {
  $.get('/DataCon/GetActiveRuns')
    .done(function(data) {
      var deleted = []
      ko.utils.arrayForEach(that.Active(), function(item) {
        if (!data.find(x => x.Id === item.Id())) deleted.push(item)
      })
      that.Active.removeAll(deleted)
      data.forEach(run => {
        var match = ko.utils.arrayFirst(that.Active(), function(item) {
          return item.Id() === run.Id
        })
        if (match) {
          ko.mapping.fromJS(run, match)
        } else {
          that.Active.push(ko.mapping.fromJS(run))
        }
      })
    })
    .fail(function() {
      toastr.error('failed to refresh active runs')
    })
}
...

vm.refreshActive()
setInterval(vm.refreshActive, 5000)


texts: Integration of data using Simpson's rule

texts:
I wrote a Python program that performs an integration of data using Simpson's rule. The program takes the areas to be integrated from a foo.ref file, with the following syntax:

# peak          m/z             charge  window
LAG_H4N4F1S1    4244.829467     1+      0.06
LAG_H4N4F1S1    4245.832508     1+      0.06
LAG_H4N4F1S1    4246.835549     1+      0.06
LAG_H4N4F1S1    4247.838590     1+      0.06

The data that the program parses is taken from all the .xy files in the current directory, with the following syntax:

3497.7552 0
3497.7619 410646
3497.7685 397637
3497.7752 363672
3497.7819 321723
3497.7886 286960

The program's final output is a tab seperated file that can be opened directly in excel, the performance is ... a lot worse than I was expecting however and I was wondering if anyone could offer some tricks to increase that (and also to have a general look at the code, if it is correct Python).

#! /usr/bin/env python
import glob
import os
import fileinput
print "<SimpInt.py> a script to quickly calculate the area for a set"
print "of analytes. Written by Bas Jansen, Leiden University Medical"
print "Center, March 20th 2013."
print ""

# Simpson's rule
def integrate(y_vals,h):
  i=1
  total=y_vals[0]+y_vals[-1]
  for y in y_vals[1:-1]:
    if i%2 == 0:
      total+=2*y
    else:
      total+=4*y
    i+=1
  return total*(h/3.0)

# Reads the reference file
ref=[]
for refs in glob.glob("*.ref"):
  fr=open(refs)
  for line in fr.readlines():
    parts=line.rstrip('\n').split('\t')
    ref.append(parts)
  fr.close()

# Initialize the output file
f=open('output.xls','w')
for i in range(1,len(ref)):
  f.write(ref[i][0]+"\n")
f.close()

# Find XY files in current directory
xy_files=[]
for files in glob.glob("*.xy"):
  xy_files.append(files)
  x=[]
  area=[]
  print "Parsing: "+files
  fh=open(files)
  for line in fh.readlines():
    y=[float(i) for i in line.split()]
    x.append(y)
  fh.close()

  # Pick the XY window
  print "Progress indicator:"
  print "0%"
  for i in range(1,len(ref)):
    obs=[]
    vals=0
    low=float(ref[i][1])-float(ref[i][3])
    high=float(ref[i][1])+float(ref[i][3])
    # Progress indicator
    if i %(len(ref)/10) == 0:
      print str(i/(len(ref)/10))+"0%"
    for j in range(0,len(x)):
      if x[j][0] > low and x[j][0] < high:
        coords=[float(l) for l in x[j]]
        obs.append(coords)
        vals+=1
    if obs:
      y_vals=[]
      h=(obs[len(obs)-1][0]-obs[0][0])/len(obs)
      for k in range(0,len(obs)):
        y_vals.append(obs[k][1])
      area.append(integrate(y_vals,h))

  # Neat trick to append the area from other input files
  l = 0
  for line in fileinput.input('output.xls',inplace=1):
    print "%s\t%s\n" % (line.rstrip(),area[l]),
    l+=1

# Display the legend (& filenames) at bottom of output file
f=open('output.xls','a')
legend = "Peak"
for m in range(0,len(xy_files)):
  legend+="\t"+str(xy_files[m])
legend+="\n"
f.write(legend)
f.close()

# Being polite
raw_input("Finished, press any key to exit")

I have performed some various tests today with disabling chunks of the code and seeing what causes the biggest increase in processing time and that appears the searching of the lists.


texts: C program to "monitor" NGINX status with AF_INET

texts:
I'm trying to implement a simple "monitoring" tool in C to be used on our servers to check NGINX status, executed periodically with a cron task.

This is my very first attempt to use C instead of bash or (lovely) Python - just for some practice.

So I googled code for "socket open" and used some code in the socket_get() function which does exactly NGINX's check.

The second function send_alarm() is just send email with system() (had no time to take libcurl closer).

#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define HOST_ADDR "127.0.0.1"
#define HOST_PORT 80

int socket_get(int i_addr, int i_port) {

    int socket_desc;
    struct sockaddr_in server;

    socket_desc = socket(AF_INET , SOCK_STREAM , 0);

    if (socket_desc == -1) {
        return 1;
    }

    server.sin_addr.s_addr = inet_addr(HOST_ADDR);
    server.sin_family = AF_INET;
    server.sin_port = htons(HOST_PORT);

    if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0) {
        return -1;
    }

    return 0;
}

void send_alarm() {

    char cmd[100];
    char to[20] = "user@domain.kiev.ua";

    char hostname[1024], from_host[24];
    gethostname(hostname, 1024);

    // we have two NGINX hosts - the "master" and the "secondary"
    // here set from_host value depending on the $HOSTNAME
    if (strcmp(hostname, "lj3hwzghi6ibg000000") ==0) {
         strncpy(from_host, "Master", 24);
    } else if (strcmp(hostname, "lj3hwzghi6ibg000001") ==0) {
        strncpy(from_host, "Secondary", 24);
    } else {
        exit(1);
    }

    // concatanate all to the $cmd variable
    sprintf(cmd, "echo NGINX is in DOWN state on the host %s! | /usr/bin/mailx -s \"ALARM from %s\" %s", from_host, from_host, to);
    system(cmd);

}

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

    if (socket_get(atoi(HOST_ADDR), HOST_PORT) == 0) {
        printf("NGINX up and running\n");
    } else {
        printf("Can't connect to local NGINX service!\n");
        send_alarm();
    }

}


texts: Variables, references and pointers - Write the function set (…) so that the following code works correctly

texts:
I have following homework exercise from lecture "Variables, references and pointers":

Write the function set (...) so that the following code works
correctly:
int x = 3;
set(x) = 3;
cout << x << endl;  // writes 0
set(x) = 4;
cout << x << endl;  // writes 3
set(x) = 5;
cout << x << endl;  // writes 4

This is my solution:
#include <iostream>

using namespace std;

int & set(int & num);

int main(void) {
    int x = 3;
    set(x) = 3;
    cout << x << endl;  // wypisze 0
    set(x) = 4;
    cout << x << endl;  // wypisze 3
    set(x) = 5;
    cout << x << endl;  // wypisze 4
    return 0;
}

int & set(int & num) {
    static int tmp;
    int & ret = tmp;
    num = ret;
    return ret;
}

What do you think about it?


texts: Sending an email every half hour if a certain condition is met

texts:
This will be called every minute from the background thread. If my unauthorizedCount and badRequestCount is not equal to zero, then I send out an email.

private void callMetrics() {

    // .. some other code

    // send an email for unauthorized count
    if (Integer.parseInt(unauthorizedCount) != 0) {
        // send an email here
    }

    // send an email for bad request count
    if (Integer.parseInt(badRequestCount) != 0) {
        // send an email here
    }
}

For example, if my unauthorizedCount is non-zero, then it will be non-zero at least for an hour. That means it will keep on sending out an email every minute for an hour, so our email will get flooded up with this. That's what I don't want to have, same thing with badRequestCount.

Now what I want to do is, as soon as unauthorizedCount is non-zero, it will send out its first email. If it is non-zero again continuously for half an hour, then I would like to send another email after half an hour. If it is non-zero continuously, but suppose if the first time it was non-zero, I will send out an email. Next time it is non-zero, I won't send another email, but if the third time it was zero, then I will reset the counter so that it sends out an email instantly.

I basically want to send out my first email whenever unauthorizedCount is non-zero but if it is non zero again in the next minute, then I don't want to send out another email and will send out another email if unauthorizedCount is non-zero after half an hour.

private static long lastUnauthorizedSent = -1;
private static long lastBadRequestSent = -1;

private void callMetrics() {

    // .. some other code

    long now = new Date().getTime();

    // send an email for unauthorized count
    if (Integer.parseInt(unauthorizedCount) != 0 && satisfiesUnauthorizedSinceLast(now)) {
        // send an email here
        lastUnauthorizedSent = now;
    } else {
        lastUnauthorizedSent = -1;
    }

    // send an email for bad request count
    if (Integer.parseInt(badRequestCount) != 0 && satisfiesBadRequestSinceLast(now)) {
        // send an email here
        lastBadRequestSent = now;
    } else {
        lastBadRequestSent = -1;
    }
}

private void satisfiesUnauthorizedSinceLast(long now) {
    return lastUnauthorizedSent == -1 || now - lastUnauthorizedSent > 30*60*1000;
}

private void satisfiesBadRequestSinceLast(long now) {
    return lastBadRequestSent == -1 || now - lastBadRequestSent > 30*60*1000;
}


texts:
I'm looking to get some advice on whether or not I am building/structuring my application the correct way. The program has a few key components:

Calculate the fine based on how fast over the limit a driver was travelling
Generate a fine letter address to the driver
Update a file with a driver's registration details and the fine

So that being said, I have the following classes:

DriverDetails
DriverManager
Fine
FineCalculator
FineType

Here is the idea:

When I want to work out the fine:

FineCalculator object is created
The speed limit is set
The speed of the car is set and then the calculateFine() method is called
The calculateFine() method will return a Fine object, which is a data object which contains an amount, and a string (the result), the points if any, a FineType

This is one side of the application.

The other part is to be done after a fine has been generated. The user will enter the driver details, a DriverDetails object will be created, for the user to then generate any form of documentation it will use the DriverManager object which will take a DriverDetails object when constructed.

The FineCalculator class:

public class FineCalculator {

    private int speedlimit;

    private int carspeed;

    public FineCalculator(int speedlimit, int carspeed) {

        this.speedlimit = speedlimit;
        this.carspeed = carspeed;
    }

    public Fine calculateFine() {

        Fine fine = new Fine();

        int milesover = carspeed - speedlimit;

        if(milesover < 1) {

            fine.result = "The user was not going above the speed limit, no actions will be taken.";
        }

        else if(milesover < 5) {

            fine.result = "No fine issued, no points gained but a warning will be issued to the driver.";
            fine.finetype = FineType.WARNING;
        }

        else if(milesover > 4 && milesover < 10) {

            fine.result = "A fine of £50.00 will be issued to the driver. 0 points gained.";
            fine.amount = 50.00;
            fine.finetype = FineType.FIFTY;

        }

        else if(milesover > 9 && milesover < 15) {

            fine.result = "A fine of £100.00 will be issued to the driver. 0 points gained.";
            fine.amount = 100.00;
            fine.finetype = FineType.ONE_HUNDRED;

        }

        else if(milesover > 14 && milesover < 20) {

            fine.result = "A fine of £150.00 will be issued to the driver. 3 points gained.";
            fine.amount = 150.00;
            fine.points = 3;
            fine.finetype = FineType.THREE_POINTS_ONE_FITY;
        }

        else if(milesover > 19) {

            fine.result = "A fine of 1000.00 will be issued to the driver, and they will be disqualified.";
            fine.finetype = FineType.DISQUALIFIED;
        }

        return fine;

    }
}

The Fine class:

public class Fine {

    public Double amount;
    public String result;
    public int points;
    public FineType finetype;

}

The DriverDetails class:

public class DriverDetails {

    public String firstname, surname, address, city, postcode;
    public int drivernumber;

}

The DriverManager class:

public class DriverManager {

    private DriverDetails driverdetails;
    private Fine fine;

    public DriverManager(DriverDetails driverdetails, Fine fine) {

        this.driverdetails = driverdetails;
        this.fine = fine;
    }

    public void generateFineLetter() {

    }

    public void updateDriverDetailsWithFine() {

    }
}

And finally, the simple enum class:

public enum FineType  {

    WARNING, FIFTY, ONE_HUNDRED, THREE_POINTS_ONE_FITY, DISQUALIFIED

}

My biggest concern is the fact that I'm not using the getters/setters inside the DriverDetails and Fine data classes. I mean, it doesn't feel like the getters and setters are completely necessary. Am I wrong? I know what I'm doing goes completely against encapsulation, but in this scenario is that bad? Can I have any advice here as to what to improve or if I'm structuring this wrong?


texts:
So far I have attempted to find the inorder successor through recursion and it seems to be working right. Can someone review the code and give suggestions?

struct node
{
    int data;
    struct node* left;
    struct node* right;
};

struct node * inOrderSuccessor(struct node *root, struct node *n)
{
    if(root == NULL)
        return NULL;

    static node *successor = NULL;
    if(root->data >= n->data)
    {
        successor = root;
        successor->data = root->data;
    }

    if(root->right !=NULL && n->data >= root->data)
        return inOrderSuccessor(root->right,n);

    if(root->left != NULL && n->data < root->data)
        return inOrderSuccessor(root->left ,n);

    return successor;
}

    struct node* newNode(int data)
    {
        struct node* node = (struct node*)malloc(sizeof(struct node));
        node->data   = data;
        node->left   = NULL;
        node->right  = NULL;

        return(node);
    }

    int main()
    {
        struct node *temp, *succ,*successor=NULL;
        struct node *root = newNode(20);
        root->left        = newNode(8);
        root->left->left  = newNode(4);
        root->right       = newNode(22);
        root->left->right = newNode(12);
        root->left->right->left=newNode(10);
        root->left->right->right=newNode(14);

        temp = root->left->left;

        succ =  inOrderSuccessor(root, temp);
        if(succ !=  NULL)
            printf("\n Inorder Successor of %d is %d ", temp->data, succ->data);
        else
            printf("\n Inorder Successor doesn't exit");

        getchar();
        return 0;
    }


texts:
I have a query that outputs a list of products with some fields from other tables. That query works fine.
Now, I'm attempting to retrieve the available stock for each product in that list. I'm not sure if I'm doing it correctly or in the most performant way. Here's what I've got working so far.
select distinct
p.id,
p.name
if(coalesce(x.in - x.out, 0) = 0, 0, 1) as quantity,
[other fields from joined tables]
from products p
[a bunch of inner joins]
left join (
    select
    s.id_products,
    sum(case when s.type = 'in' then s.quantity else 0 end) as 'in',
    sum(case when s.type = 'out' then s.quantity else 0 end) as 'out'
    from stock s
    group by s.id_products
) x on x.id_products = p.id_products
group by id

EDIT: I made a mistake in the query the if statement in the select is just for a flag display. Please replace the following.

if(coalesce(x.in - x.out, 0) = 0, 0, 1) as quantity,

(x.in - x.out, 0) as quantity,


texts:
I wrote a Python script to download files using multiple (source) IP addresses -- kindly suggest any improvements.

import cgi
import os
import posixpath
import Queue
import threading
import urllib
import urlparse
import random
import re
import shutil
import time

import requests
import requests_toolbelt

def get_IPs():
    """Returns all available IP addresses in a list."""
    # TODO: Windows only. Other options?
    out = []
    for i in os.popen('ipconfig'):
        i = i.strip()
        if i.startswith('IP'):
            out.append(i.rsplit(' ', 1)[-1])

    return out

def get_info(url):
    """Returns name and size of file to be downloaded."""
    try:
        resp = requests.head(url, allow_redirects=True)
        name = cgi.parse_header(resp.headers['content-disposition'])[1]['filename']
    except KeyError:
        path = urlparse.urlsplit(url).path
        name = posixpath.basename(path)
    name = urllib.unquote_plus(name)
    size = int(resp.headers['content-length'])
    return name, size

def worker(url, session, ud, part, size):
    """Downloads a part of the file specified by 'part' parameter."""
    # TODO: optimal tries, timeout?
    for _ in xrange(2):
        try:
            open('%s/%04d' % (ud, part), 'wb').write(
                session.get(url, timeout=(2, 7), headers={'range': 'bytes=%s-%s' % (
                    part*chunk, min(size, part*chunk + chunk - 1))}).content)
            break
        except:
            pass
    else:
        worker(url, sessions_queue.get(), ud, part, size)

    sessions_queue.put(session)

def summary(name, size, elapsed):
    """Prints summary of the download after it is completed."""
    print (
        '--\n'
        '%s download completed.\n'
        'Time elapsed: %.2fs\n'
        'Average download speed: %.2f MB/s\n'
        '--' % (name, elapsed, size/elapsed/2**20))

def download(url):
    """Downloads the file pointed to by 'url' parameter."""
    start = time.clock()
    name, size = get_info(url)
    # random id of length 20
    ud = '%0x' % random.getrandbits(80)
    os.mkdir(ud)
    threads = []
    for i in xrange(size/chunk + (size%chunk != 0)):
        t = threading.Thread(target=worker, args=(url, sessions_queue.get(), ud, i, size))
        threads.append(t)
        t.start()

    # characters \/:*?"<>| not allowed in filenames in Windows
    name = re.sub(r'[\\/:*?"<>|]', '_', name)
    # TODO: check if a file is already present with same name
    out = open(name, 'ab')
    for i, t in enumerate(threads):
        t.join()
        out.write(open('%s/%04d' % (ud, i), 'rb').read())

    summary(name, size, time.clock() - start)
    shutil.rmtree(ud)

def main():
    IPs = get_IPs()
    print len(IPs), 'IPs available.'
    for ip in IPs:
        adapter = requests_toolbelt.adapters.SourceAddressAdapter(ip)
        session = requests.Session()
        session.mount('http://', adapter)
        session.mount('https://', adapter)
        sessions_queue.put(session)

    while True:
        threading.Thread(target=download, args=(raw_input(),)).start()

if __name__ == '__main__':
    sessions_queue = Queue.Queue()
    KB = 1024
    MB = 1024*KB
    # TODO: optimal size?
    chunk = 100*KB
    main()

I am using it with about 100 IP addresses on my Ethernet -- each with about 100 KB/s speed. What'd be optimal configuration? (numbers of threads, chunk size)


texts:
I have this Java class for producing rotations of an input string:

StringRotator.java

package net.coderodde.util;

import java.util.Objects;

/**
 * This class implements a data type for rotating strings.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Mar 24, 2016)
 */
public class StringRotator {

    /**
     * The source string. All rotations will be produced from this string.
     */
    private final String string;

    /**
     * Caches the length of the source string in order to by a little of
     * efficiency.
     */
    private final int length;

    /**
     * Caches the current rotation. This field is set to {@code null} after
     * every effective rotation. Whenever the user requests the rotated string,
     * if this field is not {@code null}, the cached string is returned.
     * Otherwise, a rotated string is built and set to this field, and finally
     * returned.
     */
    private String cachedString;

    /**
     * Index of the first logical character component in the source string.
     */
    private int finger;

    public StringRotator(String string) {
        this.string = Objects.requireNonNull(string,
                                             "The input string is null.");
        this.length = string.length();
    }

    public void rotate(int offset) {
        int oldFinger = finger;
        finger += offset;
        finger %= string.length();

        if (finger != oldFinger) {
            cachedString = null;
        }
    }

    @Override
    public String toString() {
        if (cachedString != null) {
            return cachedString;
        }

        return cachedString = buildString();
    }

    private String buildString() {
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; ++i) {
            sb.append(string.charAt((finger + i) % length));
        }

        return sb.toString();
    }

    public static void main(final String... args) {
        StringBuilder sb = new StringBuilder();

        for (char c = 'a'; c <= 'z'; ++c) {
            sb.append(c);
        }

        String input = sb.toString();

        for (int i = 0; i < input.length(); ++i) {
            StringRotator string = new StringRotator(input);
            string.rotate(i);
            System.out.println(string);
        }
    }
}

Please, tell me anything that comes to mind.


texts: Place Ajax request on completion of Ajax Request

texts:
I have an Ajax request which in turn on completion make another Ajax request:

$.ajax({
          url: '<?php echo BASE_URL.'Dashboard/GetMyTrackList' ?>',
          type: 'GET',
          success: function (response) {

              var list = JSON.parse(response);
              $.each(list, function (k, v) {
                  MarkLocation(parseFloat(v["Longitude"]),parseFloat(v["Latitude"]), v["UserId"]);
              });
          },
          complete: function(){
              $(".icon").click(function(evt){
                  debugger;
                  $(container).css("display","block");
                  var value = $(this).attr("alt");
                  $.ajax({
                      url:'<?php echo BASE_URL.'Dashboard/GetProfile' ?>',
                      data:'id='+value,
                      type:'GET',
                      success:function(response){
                          var user = JSON.parse(response);
                          $(container).find("#content").find("#username").text(user["Username"]);
                          $(container).find("#content").find("#email").text(user["Email"]);

                          map.addOverlay(new ol.Overlay({
                              position: ol.proj.transform(
                                  [parseFloat(user["Longitude"]),parseFloat(user["Latitude"])],
                                  'EPSG:4326',
                                  'EPSG:3857'
                              ),
                              element: container
                          }));

                      }
                  });

              });
          }
      });

Element with an icon class is created in the MarkLocation function:

 function MarkLocation(lon, lat, alt) {
          $userid = '<?php echo $_SESSION["UserID"];?>';
          if(alt==$userid)
              var marker = $('<img class="icon" src="<?php echo BASE_URL.'includes/images/location/mylocation.png'  ?>">');
          else
              var marker = $('<img class="icon" src="<?php echo BASE_URL.'includes/images/location/marker.png'  ?>">');
          map.addOverlay(new ol.Overlay({
              position: ol.proj.transform(
                  [lon, lat],
                  'EPSG:4326',
                  'EPSG:3857'
              ),
              element: marker
          }));
          $(marker).attr("alt", alt);
      }

Previously, I had an icon click event placed outside (i.e. not in the complete function of ajax). In that case, an element with an icon class was not clickable, maybe because of a binding issue. Then I placed the click event in the complete function and it works. Is this a good way? Or what approach would you suggest?


texts: Sorting almost sorted array with a minimum heap

texts:
I'm currently looking into the quickest way to sort an almost sorted array:

  Given an array of \$n\$ elements, where each element is at most \$k\$ away
  from its target position, devise an algorithm that sorts in \$O(n \log k)\$
  time.

I've implemented a sorting function which "slides" through an input list, pushes the element from a sliding window into a min heap (using the heapq built-in module), pops the minimum element which is collected in the result list:

from typing import List
from heapq import heappush, heappop

def sort_almost_sorted(a: List[int], k: int) -> List[int]:
    if not a:
        return []

    length = len(a)
    if k >= length:
        return sorted(a)  # apply built-in "timsort", designed to be quick on almost sorted lists

    result = []
    min_heap = []  # maintain a min heap for a sliding window
    for slice_start in range(0, length, k + 1):  # sliding window
        # push the next slice to min heap
        for index in range(slice_start, min(slice_start + k + 1, length)):
            heappush(min_heap, a[index])

        result.append(heappop(min_heap))

    # put the rest of the heap into the result
    for _ in range(len(min_heap)):
        result.append(heappop(min_heap))

    return result

It works on my sample inputs.

Do you think I'm using the minimum heap appropriately and this implementation is \$O(n \log k)\$? What would you improve code-quality or code-organization wise?


texts: Given an element, returning the inorder rank of it an in a binary search tree with only two parameters

texts:
I have a solution here, but I'm not too fond of it because I feel like it can be done better.

template <typename Comparable>
bool AugmentedBinarySearchTree<Comparable>::Rank(const Comparable& x, BinaryNode* t, int* nodesVisited) const {
  if (t == NULL) {
    return false;
  }
  if (Rank(x, t->m_left, nodesVisited)) {
    return true;
  }
  *nodesVisited += 1;
  if (t->m_element == x) {
    return true;
  }
  return Rank(x, t->m_right, nodesVisited);
}

My biggest stumbling block was finding way to both confirm the node actually existed and also returning its rank.

I started with this method signature

int BinarySearchTree<Comparable>::Rank(const Comparable& x, BinaryNode* t) const {

but in the end I had to make the method return a bool and add an extra parameter to keep track to where the program was in the traversal.

Is there any way to do this without the nodesVisited parameter?


texts:
Is this orthogonal?

#ifndef TOKENIZER_H
#define TOKENIZER_H

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

class StringTokenizer
{
private:
        std::vector<std::string> tokens;
        unsigned int index;

public:
    StringTokenizer(std::string const & str, const char delim)
    {
        index = 0;
        // Populate the token vector...
        std::istringstream stream(str);
        std::string token;
        while (std::getline(stream, token, delim))
        {
            tokens.push_back(token);
        }
    }
    ~StringTokenizer(void) { };

    bool HasMoreTokens() { return index < tokens.size(); };
    std::string NextToken() { return TokenAtIndex(index++); };
    std::string PreviousToken() { return TokenAtIndex(index--); };
    std::string TokenAtIndex(int x)
    {
        std::string token = "";
        try
        {
            token = tokens.at(x);
        }
        catch (const std::out_of_range& range_error)
        {
            std::cerr << "[!!] Out of Range: " << range_error.what() << std::endl;
        }
        return token;
    }
    void Clear() { index = 0; };
};

#endif


texts: Auto re-connecting to a VPN on OS X and pointing Squid accordingly

texts:
We need to tunnel certain applications over a VPN at work. Ideally we would use a dedicated firewall/network appliance for this but the only permanent infrastructure we have are Mac Pro's running Squid.

This means that if our VPN connection drops or anything happens to the link, we have to manually click "Connect VPN" and then update squid.conf to point to the new VPN IP. I decided to write an AppleScript task that runs as a cronjob, then depending on whether a disconnect had occurred, squid would then be reconfigured.

AutoReconnectVPN.scpt (AppleScript)

global gAttempts

tell application "System Events"
    tell current location of network preferences
        repeat 10 times
            set myConnection to the service "VPN"
            if myConnection is not null then
                if current configuration of myConnection is not connected then
                    connect myConnection
                    set gAttempts to gAttempts + 1
                else
                    -- Return 0 if theres no need to reconfigure squid
                    return gAttempts
                end if
            end if
            delay 5
            end
    end tell
end tell

SetProxyIP.sh (bash script)

#!/bin/bash

# Sets tcp_outgoing_address in squid.conf to point to IP of ppp0
# Ensure tcp_outgoing_address already exists in squid.conf!

export VPNIP=''
CONFDIR=~/Library/Preferences/squid.conf

for i in 1 2 3 4 5; do
        export VPNIP="$(ifconfig ppp0 | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')"
        echo "GETTING VPN IP" $VPNIP
        if [[ $VPNIP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]];
        then
                sed -i .bak 's/.*tcp_outgoing_address.*.*/tcp_outgoing_address '$VPNIP'/' $CONFDIR
                # Would have used squid -k reconfigure, fails with error in our environment?
                kill -9 `cat /tmp/squid.pid` || :
                /usr/local/squid/sbin/squid -f $CONFDIR

                break
        fi
        sleep 1
done

Then a cronjob to run every minute

*/1 * * * * osascript ~/vpnscripts/AutoReconnectVPN.scpt; if [ "$?" -eq "0" ] ; then ~/vpnscripts/SetProxyIP.sh; fi

Perhaps a continual daemon process would be more elegant and remove the possible 1 minute downtime between checks, but this is acceptable for our purposes.

This is my first experience with sed so I'm expecting there could be room for improvement there. My main hope is that someone could stumble upon this and find it useful.


texts:
I've started solving Project Euler problems. Is the code completely optimized?

Question:

  If we list all the natural numbers below 10 that are multiples of 3 or
  5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below N.

My solution:

import java.util.LinkedList;
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int testCases = sc.nextInt();
        for (int i = 0; i < testCases; i++) {
            int input = sc.nextInt();
            System.out.println(calculate(input));
        }

    }

    public static boolean isMulThree(int input) {

        if (input % 3 == 0)
            return true;
        else
            return false;
    }

    public static boolean isMulFive(int input) {
        int val = input % 10;
        if (val == 5 || val == 0)
            return true;
        else
            return false;
    }

    public static int calculate(int input) {
        LinkedList<Integer> al = new LinkedList<>();
        int sums = 0;
        for (int i = 1; i < input; i++) {
            if (isMulThree(i) || isMulFive(i)) {
                al.add(i);

            }
        }
        for (int count : al) {
            sums = sums + count;
        }
        return sums;
    }
}


texts: Parses XML to return the bus times at specified bus stop

texts:
The code uses the XML-based OC Transpo data feed to create a list of the bus name, where it's headed, and the times. Keep in mind that I am a beginner at python so any advice at all is appreciated.

import subprocess, pprint
from bs4 import BeautifulSoup

def format_set(result_set):
    new_set = []
    for el in result_set:
        new_set.append(str(el.get_text()))
    return new_set

def get_stop_number():
    print('Please enter your desired stop number (or \'quit\'):')
    stop_numb = raw_input('> ')
    try:
        return int(stop_numb)
    except:
        print('Exiting...')
        return 'quit'

def get_stop_info(stopNo):
    try:
        output = subprocess.check_output(('curl -d "appID=ba91e757&apiKey=…'
            '&stopNo={}&format=xml" https://api.octranspo1.com/v1.2/GetNextTripsForStopAllRoutes').format(stopNo), shell=True)
        soup = BeautifulSoup(output, 'xml')
    except:
        print('An error occured!')
        return None
    summary = []
    for el in soup.find_all('Route'):
        routeNo = int(el.find('RouteNo').get_text())
        routeHeading = str(el.find('RouteHeading').get_text())
        times = format_set(el.find_all('TripStartTime'))
        x = [routeNo, routeHeading, times]
        summary.append(x)
    return summary

def is_empty(any_structure):
    if any_structure:
        return False
    else:
        return True

if __name__ == '__main__':
    while True:
        stop_number = get_stop_number()
        if stop_number == 'quit':
            break
        summary = get_stop_info(stop_number)
        pprint.pprint(summary)

Sample output:

Please enter your desired stop number (or 'quit'):
> 3058
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  7756  100  7679  100    77   4654     46  0:00:01  0:00:01 --:--:--  4656
[[92, 'St-Laurent', ['11:30', '12:00', '12:30']],
 [92, 'Stittsville', []],
 [96, 'St-Laurent', ['10:51', '11:21', '11:51']],
 [96, 'Terry Fox', ['10:09', '10:39', '11:09']],
 [118, 'Hurdman', ['11:20', '11:40', '12:00']],
 [118, 'Kanata', []],
 [162, 'Stittsville', ['11:55', '12:55', '13:55']],
 [162, 'Terry Fox', []],
 [168, 'Bridlewood', ['11:35', '12:05', '12:35']],
 [168, 'Terry Fox', []]]
Please enter your desired stop number (or 'quit'):
> quit
Exiting...


texts:
I have a JSON file like

{
    "Changes": [{
        "Action": "UPSERT",
        "ResourceRecordSet": {
            "Name": "RESOURCE_NAME",
            "Type": "A",
            "TTL": 60,
            "ResourceRecords": [{
                "Value": "RESOURCE_HOSTS"
            }]
        }
    }]
}

where I need to replace .Changes[].ResourceRecordSet.Name and .Changes[].ResourceRecordSet.ResourceRecords[] dynamically.

So, I wrote a script to replace required values with jq.

#!/bin/bash -xe

RESOURCE_NAME="example.com"
RESOURCE_HOSTS="1.1.1.1,2.2.2.2,"

cat resource-changes.json | \
jq '.Changes[].ResourceRecordSet.Name=env.RESOURCE_NAME' | \
jq 'del(.Changes[].ResourceRecordSet.ResourceRecords[])' \
> resource-changes.$$.json && \
mv resource-changes.$$.json resource-changes.json

for host in $(echo "$RESOURCE_HOSTS" | tr "," "\n"); do
  cat resource-changes.json | \
  jq --arg theHost $host '.Changes[].ResourceRecordSet.ResourceRecords |= (. + [{"Value":$theHost}])' \
  > resource-changes.$$.json
  mv resource-changes.$$.json resource-changes.json
done

jq '.' resource-changes.json

Which works fine and I can get required replacements. Though the script looks quite long and complicated IMO. Also, I do not really like joggling with temporary files. I'm looking for a way to simplify the script. Appreciate any comments!


texts:
I recently began learning Clojure for fun, and after completing the koans, I decide that project Euler would provide my next challenge. Here is the problem statement:

(If someone knows how to put this in spolier tags with out breaking the formatting, please feel free to edit or comment and let me know how to fix it.)

  Counting Sundays Problem 19

  You are given the following information, but you may prefer to do some research for yourself.

  1 Jan 1900 was a Monday.
  Thirty days has September,
  April, June and November.
  All the rest have thirty-one,
  Saving February alone,
  Which has twenty-eight, rain or shine.
  And on leap years, twenty-nine.
  A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

  How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

This is the code I used to arrive at the solution. Note that I purposely avoided the date/time APIs so I could try more of the language features out.

(ns euler.n19)

(def week-days (cycle [:mon :tue :wed :thr :fri :sat :sun]))

(defn leap-year?
  ([year] (if (= 0 (mod year 100))
            (= 0 (mod year 400))
            (= 0 (mod year 4)))))

(def months [:jan :feb :mar :apr :may :jun :jul :agu :sep :oct :nov :dec])
(def month-length {:jan 31 :feb 28 :mar 31 :apr 30
                   :may 31 :jun 30 :jul 31 :agu 31
                   :sep 30 :oct 31 :nov 30 :dec 31})
(def leap-year-month-length (assoc month-length :feb 29))

(def years (->> (range 1901 2001)
               (map (fn [yr] (if (leap-year? yr)
                               leap-year-month-length
                               month-length)))))

(defn zip
  ([coll-1 coll-2] map list coll-1 coll-2))

(defn count-number-of-times-day-on-nth-of-month
  ([day date]
   (->> years
        (map (fn [month-len] (map #(% month-len) months)))
        (flatten)
        (reduce (fn [[week-days num-occurrences] curr-month-len]
                  [(drop curr-month-len week-days)
                   (if (= day (nth week-days date))
                     (inc num-occurrences)
                     num-occurrences)])
                [(drop 1 week-days) 0])
        (second))))

(defn main ([]  println (count-number-of-times-day-on-nth-of-month :sun 0)))

In particular, I'm wondering how the reduce in count-number-of-times-day-on-nth-of-month could be clarified since it looks very messy to me.

(As an aside, after a few hours of pouring over this and the koans, I noticed that it is now very hard to type my other code correctly :)


texts: Inherited class calls initialization code in base class

texts:
I am interested in hearing your opinion on the approach I have taken to have inherited classes initialize their base class.

Here's a Machines collection class from that maintains a list of Machine objects. Each Machine needs to be able to inform its parent, using a delegate, of something they do but they do not have a reference to the parent:

Public Delegate Sub MachineDelegate(ByRef item As Machine)

Public MustInherit Class Machines

    Private _items As New List(Of Machine)

    Public Function Create() As Machine
        Dim item As Machine = CreateItem()
        _items.Add(item)
        PostCreationHandler(item)
        Return item
    End Function

    ' Create derived object
    Public MustOverride Function CreateItem() As Machine

    Public Sub ChildMachineDidSomething(ByRef item As Machine)
        ' Handle child object event
        Debug.Print("Machine did something")
    End Sub

    ' Called once object has been created
    Protected Overridable Sub PostCreationHandler(ByRef item As Machine)
        item.MachineDelegate = AddressOf ChildMachineDidSomething
    End Sub

End Class

Public Class Machine
    Public MachineDelegate As MachineDelegate

    Public Sub DoMachineThing()
        If Not MachineDelegate Is Nothing Then MachineDelegate(Me)
    End Sub

End Class

The child objects will use a MachineDelegate to inform their parent, passing themselves as a reference.

Inherited Cars and Car classes would look like this and have their own delegate to handle Car-related notifications:

Public Delegate Sub CarDelegate(ByRef item As Car)

Public Class Cars
    Inherits Machines

    ' Create derived object
    Public Overrides Function CreateItem() As Machine
        Dim item As Car = New Car
        CreateItem = item
    End Function

    Public Sub ChildCarDidSomething(ByRef item As Car)
        ' Handle child object event
        Debug.Print("Car did something")
    End Sub

    ' Called once object has been created
    Protected Overrides Sub PostCreationHandler(ByRef item As Machine)
        Dim car As Car = item

        MyBase.PostCreationHandler(item)

        car.CarDelegate = AddressOf ChildCarDidSomething

    End Sub

End Class

Public Class Car
    Inherits Machine

    Public CarDelegate As CarDelegate

    Public Sub DoCarThing()
        If Not CarDelegate Is Nothing Then CarDelegate(Me)
    End Sub

End Class

I create an overridable PostCreationHandler where object-specific initialization is to be handled once an object is created and I am using MyBase.PostCreationHandler to make sure the object gets properly initialized at every level in the inheritance chain.

My goal is to avoid giving child objects a reference to their parent.

My question is is this OK and is there a better approach to doing this?


texts: Is this an efficient/correct way to get largest Prime factor?

texts:
Is this an efficient way to get the largest prime factor of a given number? Other solutions I found involved nested algorithms.
function largestPrimeFactor(number) {
  const factors = []
  for(let i = 2; i <= number; i++){
    if(number % i === 0){
      factors.push(i);
      number = number / i;
      i = 1;
    }
  }
  return factors.pop()
}


texts: Rearrange String such that similar characters are placed at least 'K' distance apart

texts:
So I was asked this in an interview, and I had to write this code on a white board. Sadly I couldn't complete the code :( .

I've realized that writing code on white board is completely different from typing it on an editor. Firstly because, I type way faster than I write and secondly I can't keep adding lines in between, so the first line has to be my best line of code.

What are some of the things I should keep in mind before I write my code, so that I make sure I make minimal changes once I write?

// The idea is to calculate frequencies of characters, and create the
// string by putting highest frequency characters one after another into it
// for 'K' times, and repeat the process.
/* Example:
* S = AAABBBCC, K = 3
* Result : ABCABCAB (all 'A's are 3 distance apart, similarly with B's and C's)
*/
class Node implements Comparable<Node>{
    char c;
    int frequency;

    public Node(char c, int f) {
        this.c = c;
        this.frequency = f;
    }

    public int compareTo(Node other) {
        if (this.frequency > other.frequency)
            return -1;
        if (this.frequency < other.frequency)
            return 1;
        if (this.c < other.c)
            return -1;
        if (this.c > other.c)
            return 1;
        return 0;
    }
}

public String rearrange(String s, int k) {
    StringBuilder sb = new StringBuilder();
    // calculate frequency
    Map<Character, Integer> map = new HashMap<Character, Integer>();
    for (Character c : s.toCharArray()) {
        if (map.containsKey(c)) {
            map.put(c, map.get(c) + 1);
        } else {
            map.put(c, 1);
        }
    }
    // create frequency based heap, if duplicate frequency, order alphabetical
    PriorityQueue<Node> heap = new PriorityQueue<Node>();

    for (Character c : map.keySet()) {
        heap.add(new Node(c, map.get(c)));
    }

    int len = 0;
    // keep removing k elements from heap
    // add them to result string
    // decrease frequency and add back to heap
    while (len < s.length()) { // (n/k) * k log(n) == n log(n)

        int tempK = 0;
        Deque<Node> tempList = new LinkedList<Node>();

        while (tempK < k && !heap.isEmpty()) { // k log(n)
            Node node = heap.remove();
            sb.append(node.c);
            node.frequency--;
            if (node.frequency != 0) {
                tempList.add(node);
            }
            tempK++;
        }
        while (!tempList.isEmpty()) { //k log(n)
            heap.add(tempList.remove());
        }
        len = len + k;
    }
    return sb.toString();
}


texts: How to reformat this code so I don't use 'Exit Try' and 'Exit For'?

texts:
I use SonarQube to help me try and become a better programmer to program along with 'best-practice' standards.

There are business rules when a user is submitting data they enter in a datagridview that I encompass in a Try Catch block. I think the comments in the code describe fairly well what should be happening.

The problem: When I submit my project to SonarQube, it says "Exit Statements should not be used." I do not know what to use in lieu of the Exit statements, when they do exactly what I need. Can anyone point me in the right direction?

A visual representation of the Data Grid View:

Must be between 0-85             Must total to 100
+------------------+-------------+-----------------+--------------+
| Bonus Percentage | Fund Option | Fund Percentage | Election Date|
+------------------+-------------+-----------------+--------------+
|       85         |     2       |     50          |    3/20/2014 |
+------------------+-------------+-----------------+--------------+
|       85         |     5       |     50          |    3/20/2014 |
+------------------+-------------+-----------------+--------------+

Code:

tot = CInt(BonusDGV.Rows(0).Cells(0).Value)

'Business Rules Try/Catch block
Try
    'Ensure, for all rows, Fund amount totals 100 and Bonus Percentage is between 0-85%.
    For i As Integer = 0 To BonusDGV.Rows.Count - 1
        'don't count rows that contain no data
        If BonusDGV.Rows(i).Cells(0).Value = Nothing Then
            Exit For
        End If
        fundTot = fundTot + CInt(BonusDGV.Rows(i).Cells(2).Value)
        If tot <> CInt(BonusDGV.Rows(i).Cells(0).Value) Then
            MessageBox.Show("Percentage Must Be Between 0-85%.", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Error)
            'Stop looping, there has been a violation in user entry (Bonus Percentage)
            Exit Try
        End If
    Next
    'Bonus Percentage must be between 0-85% // \\ Double check
    If tot > 85 Or tot < 0 Then
        MessageBox.Show("Percentage Must Be Between 0-85%.", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Exit Try
        'Total of fun amounts must = 100
    ElseIf fundTot <> 100 Then
        MessageBox.Show("Fund Total Must Add to 100%.", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Exit Try
        'Met all the business requirements, proceed to insert record
    Else
        For i As Integer = 0 To BonusDGV.Rows.Count - 1
            'Make sure there is actually data in the row
            If BonusDGV.Rows(i).Cells(0).Value = Nothing Then
                Exit For
            End If
            cmd.Parameters("@BonusPct").Value = BonusDGV.Rows(i).Cells(0).Value
            cmd.Parameters("@FundID").Value = CInt(BonusDGV.Rows(i).Cells(1).Value)
            cmd.Parameters("@DefPct").Value = BonusDGV.Rows(i).Cells(2).Value
            cmd.Parameters("@ElectDT").Value = BonusDGV.Rows(i).Cells(3).Value
            'nonquery because we don't expect a return value
            cmd.ExecuteNonQuery()
        Next
    End If
Catch ex As Exception
    MessageBox.Show("Invalid Entry. Make sure Bonus Percentage is between 0-85% and Fund Percentage total = 100.", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
'dispose of the connection
conn.Close()


texts:
I have a function that is able to return the factors of a number that are prime.

For example: The prime factors of 13195 are 5, 7, 13 and 29.

The function works great, and I was even able to improve it by dividing by just prime numbers instead of all numbers. The problem is it still isn't efficient enough because at 100,000,000 the program takes 10 seconds to finish and the number I need to run through this is 600,851,475,143 which will take more than 6000 times longer to finish.

In the spirit of the challenge, I don't want to be given the answer, but some guidance.

There are also issues with just how large the number is. If I use xrange() it will still give me an overflow error but this isn't a huge problem (I can google answers for that).

def getPrimesM(integer, start=4):
  primes = [2,3]
  for num in range(start, integer):
    if integer % num == 0:
      for i, prime in enumerate(primes):
        if num % prime == 0:
          break
        if i >= len(primes) - 1:
          primes.append(num)

  return primes


texts:
This was the first game I made not too long ago (2018), and while I'm working on another, more complex version, I want to know how good or bad I did this one and what can be improved.

Note: the change of players and detection of free spaces are the things I did with help of a friend, everything else I did it myself.

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

int printBoard();
int clear(int h, int w);
int freeSpace();
int player();
int checkLine(int x, int y, int z);
int winner();

int player_input;
char board[9] = {' ', ' ', ' ',
                 ' ', ' ', ' ',
                 ' ', ' ', ' '};

int player_num = 1;
char symbol = 'X';

int main(void)
{
    char start;

    clear(24, 80);

    printf("\nTotito game on a 3x3 board:\n");
    printf("Enter number from 1 to 9 to mark the respective spaces in the board.\n");
    printf("Press a number to start the game: ");
    scanf("%c", &start);

    clear(24, 80);
    printBoard();

    while (true)
    {
        player();
        clear(24, 80);
        printBoard();
        winner();

        player_num = (player_num == 1)? 2: 1;
        symbol = (player_num == 1)? 'X': 'O';
    }
}

int printBoard() // 3x3 board
{
    int lines = 7;
    int columns = 7;
    int n = 0;

    for (int i = 1; i <= lines; i++)
    {
        printf("    ");

        for (int j = 0; j < columns; j++)
        {
            if (i % 2 != 0)
            {
                if (j % 2 == 0)
                {
                    printf("+");
                }

                else
                {
                    printf("---");
                }
            }

            else
            {
                if (j % 2 == 0)
                {
                    printf("|");
                }

                else
                {
                    printf(" %c ", board[n]);
                    n++;
                }
            }
        }

        printf("\n");
    }
}

int clear(int h, int w)
{
    printf("\033[0;0H");

    for (int i = 0; i < w; i++)
    {
        for (int j = 0; j < h; j++)
        {
            printf(" ");
        }
    }

    printf("\033[0;0H");
}

int freeSpace()
{
    for (int i = 0; i < sizeof(board); i++)
    {
        if (board[i] == ' ')
        {
            return true;
        }
    }
}

int player()
{
    printf("Player %d: ", player_num);

    if (freeSpace())
    {
        scanf("%d", &player_input);
    }

    while (board[player_input - 1] != ' ')
    {
        printf("\033[1APlayer %d: Not empty, try again: ", player_num);
        scanf("%d", &player_input);
    }

    board[player_input - 1] = symbol;
}

int checkLine(int x, int y, int z)
{
    if ((board[x] == symbol) && (board[x] == board[y]) && (board[y] == board[z]))
    {
        printf("Player %d wins!\n", player_num);
        exit(0);
    }
}

int winner()
{
    checkLine(0, 1, 2); //first horizontal

    checkLine(3, 4, 5); //second horizontal

    checkLine(6, 7, 8); //third horizontal

    checkLine(0, 3, 6); //first vertical

    checkLine(1, 4, 7); //second vertical

    checkLine(2, 5, 8); //third vertical

    checkLine(0, 4, 8); //first diagonal

    checkLine(2, 4, 6); //second diagonal
}


texts:
I had to sort a list of objects - {name:'name', email:'email} by their keys, ex. by email, so they all be rendered with email key/value pair as a first key/value pair and I was surprised about the solution i came up to - Object.assign() when i loop through array and assign email key/value pair to each object:

objects = [{name: 'name1', phone: 'phone1', email: 'email1'},
            {name: 'name1', phone: 'phone1', email: 'email1'},
            {name: 'name1', phone: 'phone1', email: 'email1'}]

sort(val) {
  for (let i=0; i < this.objects.length; i++) {
    let temp = {};
    temp[val] = null;
    this.objects[i] = Object.assign(temp, this.objects[i])
  }
}

The rest is done by Angular's ChangeDetection. Are there better ways or can you tell any possible issues with this? (I still don't feel very proficient in Javascript, so just wondering)

Here is a StackBlitz's DEMO


texts:
Here is my code to reverse link list in using recursion:

       Node n = null;

    private void ReverseList(Node temp)
    {
        if (temp == null)
            return;

        ReverseList(temp.nextNode);

        Node newNode = temp;
        newNode.nextNode = null;
        if (n == null)
        {
            n = newNode;
        }
        else
        {

            Node TempNode = n;

            while (TempNode.nextNode != null)
            {
                TempNode = TempNode.nextNode;
            }
            TempNode.nextNode = newNode;
             head=n;
        }

    }

Is this the preferred way of doing this? What modifications can I make to optimize this code?


texts: Compute angular distances between data points in a matrix

texts:
I am having a hard time speeding up a function that I use to compute angular distances between data points in a matrix. More precisely, I want to compute $$\sum_{r=1}^n|\pi - \arccos\left(\frac{(X_{i}-X_{j})'(X_j-X_r)}{|X_{i}-X_{j}|\ |X_j-X_r|}\right)  \times \frac{\pi^{(0.5k - 1)}}{\Gamma(0.5k + 1)}| $$… where \$X_i\$ is a a \$k\$-dimensional vector.

Speeding this up is somehow crucial for me when sample size is around 10,000.

omega_w <- function(X){
  X <- as.matrix(X)
  n <- dim(X)[1]
  kdim <- dim(X)[2]
  omega <- matrix(0, nrow = n, ncol = n) # n x n

  for (j in 1:n){
    for (l in 1:j){
      for (r in 1:n){
        x.jr <- ((X[j,])-(X[r,]))
        x.lr <- ((X[l,])-(X[r,]))
        if (l==r && j==r){
          omega[j,l] <- omega[j,l] + 2*pi }
        else if ((l==r || j==r) && j!=l){
          omega[j,l] <- omega[j,l] + pi }
        else if (l==j && j!=r){
          omega[j,l] <- omega[j,l] + pi }
        else {
          omega[j,l] <- omega[j,l] + abs(pi - acos(cor(x.jr,x.lr)))
        }
      }
    }
  }
  omega <- (omega + t(as.matrix(Matrix::tril(omega,-1)))) * pi^(kdim/2-1)/gamma(kdim/2 +1)
  return(omega)
}

x <- as.matrix(rnorm(10000*20),n,20)
w <- omega_w(x)

I would really appreciate any guidance on to make this function "better" and more computationally efficient. I am not really that worried about large matrices, as I will use this with sample sizes approximately the same as the one in the example.


texts:
The task

  You're given strings J representing the types of stones that are
  jewels, and S representing the stones you have.  Each character in S
  is a type of stone you have.  You want to know how many of the stones
  you have are also jewels.

  The letters in J are guaranteed distinct, and all characters in J and
  S are letters. Letters are case sensitive, so "a" is considered a
  different type of stone from "A".

  Example 1:

  Input: J = "aA", S = "aAAbbbb" Output: 3

  Example 2:

  Input: J = "z", S = "ZZ" Output: 0

  Note:

  S and J will consist of letters and have length at most 50. The
  characters in J are distinct.

My functional solution

const findNumberOfJewels = (j,s) =>  [...s].reduce((num, x) => [...j].includes(x) ? num + 1 : num , 0);

console.log(findNumberOfJewels("aA", "aAAbbbb"));

My imperative solution

function findNumberOfJewels2(j,s) {
  let res = 0;
  const set = new Set(j);
  for (const x of s) {
    if (set.has(x)) { ++res; }
  }
  return res;
};

console.log(findNumberOfJewels2("aA", "aAAbbbb"));


texts: turning the digits of a number into an array

texts:
int main()
{
    int x,numDigits,i,y,a,diff;
    scanf("%d",&x);

    a=x;
    int result = 1;
    int base=10;
    numDigits=0;

    do
    {
        ++numDigits;
        x = x / 10;
    } while ( x>0 );

    for(result=1;numDigits>0;--numDigits){
        result *= base;
        i=result;

        y=a%i;
        while(y>10){
            y=y/10;
        }
        printf(" %d",y);
    }
    return 0;
}

I manage to seperate integer's digits one by one. But I was not able to collect them in an array. Even though with limited numbers without taking input from user it is easier, I also want to process these numbers but I got stuck.


texts: Python script to read CSVs and regroup it into the data types I need

texts:
This code does the following:

Read CSV file and determine sub_type based on series_desc.
Turn row into dictionaries new_person and new_subscriptions.
Check list people for the new_person and add the person if it is actually new.
Check each person in the list people for the new_subscription and add it if it is not there.

My desired output is a list of dictionaries called people. A dictionary in people might look like this:

{'id': group_id, 'subscriptions': [sub_dict1, sub_dict2]}

where a sub_dict looks like this:

{'id': sub_id, 'season': season_desc, 'sub_type': sub_type}

The code:

import csv

people = []

#open csv file
csv_file = csv.reader(open(filename, 'rb'))

#read CSV file into a list of people
for record in csv_file:
    sub_id = record[0]
    group_id = record[6]
    season_desc = record[11]
    series_desc = record[12]
    price = record[13]

    if "MW" in series_desc:
        sub_type = "Masterworks"
    elif "Pops" in series_desc:
        sub_type = "Pops"
    elif "Chamber" in series_desc:
        sub_type = "Chamber"

    new_person = {'id': group_id}
    new_subscription = {'id': sub_id, 'season': season_desc, 'sub_type': sub_type}

    #if this is the first time through the loop
    if len(people) == 0:
        new_person['subscriptions'] = []
        new_person['subscriptions'].append(new_subscription)
        people.append(new_person)

    #if this is not the first time through the loop
    else:
        #check if this person has already been recorded
        if any(person['id'] == new_person['id'] for person in people) == True:
            #check if this subscription has already been added to this person
            #use enumerate to get a key to search people
            for i in enumerate(people):
                if i[1]['id'] == new_person['id']:
                    key = i[0]

                    if any(sub['id'] == new_subscription['id'] for sub in people[key]['subscriptions']) == True:
                        pass
                else:
                    people[key]['subscriptions'].append(new_subscription)

        #if not, add the subscription to them and save the person
        else:
            new_person['subscriptions'] = []
            new_person['subscriptions'].append(new_subscription)
            people.append(new_person)

The challenge: It is REALLY slow.

I have for/if/else loops nested inside for/if/else loops, so I am sure that is the cause. What can I do differently?


texts:
This my program to change the formatting of sheets in different folders. I have over 5000 files in one folder and it is taking up to three hrs for one folder and there are multiple subfolders in the main folder. I want to cut down this time to 10 mins or as fast as possible.

Sub loopAllSubFolderSelectStartDirectory()

'Another Macro must call LoopAllSubFolders Macro to start to procedure
Call LoopAllSubFolders("D:\HTTP\")

End Sub
'Don’t run the following macro, it will be called from the macro above:

'List all files in sub folders
Sub LoopAllSubFolders(ByVal folderPath As String)

Dim fileName As String
Dim fullFilePath As String
Dim numFolders As Long
Dim folders() As String
Dim i As Long

Set wc = ActiveWorkbook
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
fileName = Dir(folderPath & "*.*", vbDirectory)

While Len(fileName) <> 0

    If Left(fileName, 1) <> "." Then

        fullFilePath = folderPath & fileName

        If (GetAttr(fullFilePath) And vbDirectory) = vbDirectory Then
            ReDim Preserve folders(0 To numFolders) As String
            folders(numFolders) = fullFilePath
            numFolders = numFolders + 1

        Else

Set wb = Workbooks.Open(fullFilePath)
Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant

fnd = "<*>"
rplc = ""

For Each sht In wb.Worksheets
On Error GoTo 0
  sht.Cells.Replace what:=fnd, Replacement:=rplc, _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
    Next sht

Workbooks("New file to be saved.xlsm").Sheets("Sheet1").Range("A1:T1").Copy

'Now, paste to y worksheet:
wb.ActiveSheet.Range("A1").PasteSpecial
Range("G2:H100").Cut Range("Q2:R100")
Range("B2:F100").Cut Range("F2:J100")
wb.ActiveSheet.Cells.EntireColumn.AutoFit

'With wb.ActiveSheet.Range("A1:T1").Interior
'        .Pattern = xlSolid
'        .PatternColorIndex = xlAutomatic
'        .ThemeColor = xlThemeColorDark1
'        .TintAndShade = -0.149998474074526
'        .PatternTintAndShade = 0
'    End With
'    With wb.ActiveSheet.Range("A1:T1").Font
'        .ThemeColor = xlThemeColorLight2
'        .TintAndShade = 0
'    End With
'    Range("A1:T1").Font.Bold = True

    wb.SaveAs Replace(wb.FullName, ".csv", ".xls"), FileFormat:=xlExcel8
wb.Close True
Kill fullFilePath
            'Insert the actions to be performed on each file
            'This example will print the full file path to the immediate window
            'Debug.Print folderPath & fileName

        End If

    End If
fileName = Dir()

Wend

For i = 0 To numFolders - 1

    LoopAllSubFolders folders(i)

Next i

End Sub


texts: Search utility that searches through source code files

texts:
I'm working on a search utility that searches through source files. It's only the beginning of the project. It lacks a lot of features, but a backbone of the project works and it would be great if you can take a look at it.

path, keyword = ARGV if ARGV.length == 2

if ARGV.length != 2
  puts "Not enough argumetns. Type 'finder --help' for help"
  abort if ARGV.length != 2
end

IGNORED_DIRS = ['..', '.', '.git', 'blib', '_build', '.bzr', '.cdv', 'cover_db',
                '__pycache', 'CVS', '_darcs', '~.dep', '~.dot', '.hg', '~.nib', '.pc', '~.plst', 'RCS', 'SCCS',
               '_sgbak', '.svn', '.tox','.metadata', '.cover']

# colorize output
class String
  def black;          "\033[30m#{self}\033[0m" end
  def red;            "\033[31m#{self}\033[0m" end
  def green;          "\033[32m#{self}\033[0m" end
  def brown;          "\033[33m#{self}\033[0m" end
  def blue;           "\033[34m#{self}\033[0m" end
  def magenta;        "\033[35m#{self}\033[0m" end
  def cyan;           "\033[36m#{self}\033[0m" end
  def gray;           "\033[37m#{self}\033[0m" end
  def bg_black;       "\033[40m#{self}\033[0m" end
  def bg_red;         "\033[41m#{self}\033[0m" end
  def bg_green;       "\033[42m#{self}\033[0m" end
  def bg_brown;       "\033[43m#{self}\033[0m" end
  def bg_blue;        "\033[44m#{self}\033[0m" end
  def bg_magenta;     "\033[45m#{self}\033[0m" end
  def bg_cyan;        "\033[46m#{self}\033[0m" end
  def bg_gray;        "\033[47m#{self}\033[0m" end
  def bold;           "\033[1m#{self}\033[22m" end
  def reverse_color;  "\033[7m#{self}\033[27m" end
end

# convert given path to full path
# which can be used in 'Dir.chdir()'
def expand_path(path)
  case path
  when '.'
    Dir.pwd
  when /~(\/[a-zA-Z\w]*)+/
    File.expand_path(path, __FILE__)
  when /\.\/[a-z]*/
    Dir.pwd + path[1..-1]
  when /\/[a-z]*/
    Dir.pwd + path
  else
    puts "Wrong path name"
  end
end

def search_in_file(path_to_file, keyword)
  f = open(path_to_file)

  flag = true

  f.each_with_index do |line, i|
    if line.include? keyword

      # print file name and path
      if flag
        puts ""
        puts path_to_file.bold.blue
        flag = false
      end
      puts "#{i+1}:".bold.gray + " #{line}".sub(keyword, keyword.bg_red)
    end
  end
end

def file_finder(path, keyword)
  Dir.chdir(path)

  entries = Dir.entries('.')

  entries.each do |item|
    unless IGNORED_DIRS.include?(item)
      if File.file?(path + "/" + item)
        search_in_file(path + "/" + item, keyword)
      else
        file_finder(path + "/" + item, keyword)
      end
    end
  end
end

file_finder(expand_path(path), keyword)


texts:
The Wikipedia article on the union find problem gives a very simple implementation, which I ported to C# and tested.

I know that the code should be, in the aggregate, asymptotically almost linear. But is it a practical implementation? Are there optimizations I should have used? Is there a way to cut down on the worst-case complexity of single operations?

using System;

/// <summary>
/// A UnionFindNode represents a set of nodes that it is a member of.
///
/// You can get the unique representative node of the set a given node is in by using the Find method.
/// Two nodes are in the same set when their Find methods return the same representative.
/// The IsUnionedWith method will check if two nodes' sets are the same (i.e. the nodes have the same representative).
///
/// You can merge the sets two nodes are in by using the Union operation.
/// There is no way to split sets after they have been merged.
/// </summary>
public class UnionFindNode {
    private UnionFindNode _parent;
    private uint _rank;

    /// <summary>
    /// Creates a new disjoint node, representative of a set containing only the new node.
    /// </summary>
    public UnionFindNode() {
        _parent = this;
    }

    /// <summary>
    /// Returns the current representative of the set this node is in.
    /// Note that the representative is only accurate untl the next Union operation.
    /// </summary>
    public UnionFindNode Find() {
        if (!ReferenceEquals(_parent, this)) _parent = _parent.Find();
        return _parent;
    }

    /// <summary>
    /// Determines whether or not this node and the other node are in the same set.
    /// </summary>
    public bool IsUnionedWith(UnionFindNode other) {
        if (other == null) throw new ArgumentNullException("other");
        return ReferenceEquals(Find(), other.Find());
    }

    /// <summary>
    /// Merges the sets represented by this node and the other node into a single set.
    /// Returns whether or not the nodes were disjoint before the union operation (i.e. if the operation had an effect).
    /// </summary>
    /// <returns>True when the union had an effect, false when the nodes were already in the same set.</returns>
    public bool Union(UnionFindNode other) {
        if (other == null) throw new ArgumentNullException("other");
        var root1 = this.Find();
        var root2 = other.Find();
        if (ReferenceEquals(root1, root2)) return false;

        if (root1._rank < root2._rank) {
            root1._parent = root2;
        } else if (root1._rank > root2._rank) {
            root2._parent = root1;
        } else {
            root2._parent = root1;
            root1._rank++;
        }
        return true;
    }
}


texts: Is dynamically generating routes from Model enum safe?

texts:
I am generating routes and responding to it dynamically by looking at the enum defined in the model. Is this safe and is there more proper method?

# Place
enum post_type: [:restaurant, :bar, :chill]

# routes
scope '/places' do
    get '/:category', to: 'places#index', constraints: { category: Regexp.new( Place.post_types.keys.join("|") ) }
  end

# places_controller
def index
    if Place.respond_to? parmas[:category]
      @places = Place.send(params[:category]).order(:created_at).limit(10)
    end
end


texts: Dynamic Programming: Fibonacci-like recurrence relation

texts:
This is a problem from my Introduction to Algorithms textbook.

  Consider the inﬁnite sequence of numbers An|n>0 = (1,1,3,4,8,11,...) deﬁned recursively as follows.

$$
A_n = \left\{\begin{aligned}
&1 && n = 1,2\\
&B_{n-1}+A_{n-2} && n > 2
\end{aligned}
\right. \\
B_n = \left\{\begin{aligned}
&2 && n = 1,2\\
&A_{n-1}+B_{n-2} && n > 2
\end{aligned}
\right.
$$

  Write a recursive method to compute the nth value of A, for any given integer n.
  Write a “bottom-up” method to compute the nth value of A, for any given integer n.

I wrote a solution for each but found myself using auxiliary methods in both cases. A recent criticism comes to mind and I wonder if this is unnecessarily complex. Could it be simpler?

Of course any feedback on the efficacy of my approach is welcomed.

My recursive algorithm, stratified into two methods:

private static int computeAuxRecursive(int n) {
  if (n <= 0) {
    throw new IllegalArgumentException("n mustbe an integer larger than 0");
  }
  return n <= 2 ? 2 : computeNthRecursive(n - 1) + computeAuxRecursive(n - 2);
}

private static int computeNthRecursive(int n) {
 if (n <= 0) {
   throw new IllegalArgumentException("n must be an integer larger than 0");
 }
  return n <= 2 ? 1 : computeAuxRecursive(n - 1) + computeNthRecursive(n - 2);
}

Convenient testing method:

private static String retrieveSequenceRecursive(int length) {
    StringBuilder result = new StringBuilder();
    for (int i = 1; i <= length; i++) {
        result.append(", ").append(computeNthRecursive(i));
    }
    return result.substring(2);
}

For my bottom-up algorithm I elected to go with a map:

private static Map<Integer, int[]> memoizedMap = new HashMap<Integer, int[]>();

Pre-filled, according to specification, like so:

memoizedMap.put(1, new int[]{1, 2});
memoizedMap.put(2, new int[]{1, 2});

The idea is to use the Nth position requested as a key, and the array of length 2 to hold both the A and B value, using a flag to determine which is being requested.

Actual two methods used for Bottom up algorithm:

private static int computeNthBottomUp(int n) {
    if (n <= 0) {
        throw new IllegalArgumentException("n must be an integer larger than 0");
    }
    if (memoizedMap.containsKey(n)) {
        return memoizedMap.get(n)[0];
    }

    memoizedMap.put(n, new int[]{ bottomUpHelper(n, false), bottomUpHelper(n, true) });
    return memoizedMap.get(n)[0];
}
// flag boolean to check if we want the B value or not
private static int bottomUpHelper(int n, boolean bFlag) {
    if (memoizedMap.containsKey(n)) {
        return bFlag ? memoizedMap.get(n)[1] : memoizedMap.get(n)[0];
    }

    memoizedMap.put(n,
        new int[]{
            bottomUpHelper(n - 2, false) + bottomUpHelper(n - 1, true),
            bottomUpHelper(n - 2, true) + bottomUpHelper(n - 1, false)
        }
    );
    return bFlag ? memoizedMap.get(n)[1] : memoizedMap.get(n)[0];
}

Another convenience method:

private static String retrieveSequenceBottomUp(int begin, int end) {
    StringBuilder result = new StringBuilder();
    for (int i = begin; i <= end; i++) {
        result.append(", ").append(computeNthBottomUp(i));
    }
    return result.substring(2);
}

Sample tests:

@Test
public void testTenthInSequence() {
    assertEquals(76, computeNthRecursive(10));
    assertEquals(76, computeNthBottomUp(10));
}

@Test
public void testfirstTenRecursive() {
    assertEquals("1, 1, 3, 4, 8, 11, 21, 29, 55, 76", retrieveSequenceRecursive(10));
    assertEquals("1, 1, 3, 4, 8, 11, 21, 29, 55, 76", retrieveSequenceBottomUp(1, 10));
}


texts:
Here is my program which creates a linked list and reverses it:

#include<stdio.h>
#include<stdlib.h>
struct node {
    int data;
    struct node *next;
};
struct node *list=NULL;
struct node *root=NULL;
static int count=0;
struct node *create_node(int);//function to create node
void travel_list(void);
void create_list(int);
void reverse_list(void);
int main()
{
    int i, j, choice;
    printf("Enter a number this will be root of tree\n");
    scanf("%d", &i);
    create_list(i);
    printf("Enter  1 to enter more numbers \n 0 to quit\n");
    scanf("%d", &choice);
    while (choice!=0){
     printf("Enter a no for link list\n");
        scanf("%d",&i);
//  printf("going to create list in while\n");
    create_list(i);
        travel_list();
    printf("Enter  1 to enter more numbers \n 0 to quit\n");
    scanf("%d", &choice);
    }
    printf("reversing list\n");
     reverse_list();
     travel_list();
 }

// end of function main
void create_list (int data)
{
 struct node *t1,*t2;
 //printf("in fucntion create_list\n");
 t1=create_node(data);
 t2=list;
 if( count!=0)
 {
   while(t2->next!=NULL)
   {
   t2=t2->next;
   }
 t2->next=t1;
 count++;
 }
 else
  {
   root=t1;
   list=t1;
   count++;
  }
}
struct node *create_node(int data)
{
    struct node *temp;
    temp = (struct node *)malloc(sizeof(struct node));
        temp->data=data;
    temp->next=NULL;
  //      printf("create node temp->data=%d\n",temp->data);
//  printf("the adress of node created %p\n",temp);
    return temp;
}
void travel_list(void )
{
 struct node *t1;
 t1=list;
 printf("in travel list\n");
 while(t1!=NULL)
 {
 printf("%d-->",t1->data);
 t1=t1->next;
 }
 printf("\n");
}
void reverse_list(void)
{
    struct node *t1,*t2,*t3;
       t1=list;
    t2=list->next;
    t3=list->next->next;
   int reverse=0;
   if(reverse==0)
   {
    t1->next=NULL;
    t2->next=t1;
    t1=t2;
    t2=t3;
    t3=t3->next;
    reverse++;

    }

    while(t3!=NULL)
     {

     t2->next=t1;
    t1=t2;
    t2=t3;
    list=t1;
    travel_list();
    t3=t3->next;
    }
    t2->next=t1;
    list=t2;
}

I am posting it for further review if there can be any improvements to the algorithm, etc.


texts: Baby-sitting bash script using DVD drive

texts:
This is the script I wrote to make an automated POC baby-sitter in 5 lines.

I first found this on a GIF or meme site and thought of making a POC script that does the same.

#How Linux users babysit
while :
do
    eject
    eject -t
done

I don't know aything about bash. So, I want improvements.

You can find the origin and the script at
https://linuxandstuff.wordpress.com/2015/11/21/messing-with-the-dvd-drive-in-command-line/


texts: Get a list of indexes for list A based on criteria in list B in Python

texts:
I have one list of data with duplicate IDs and a second list of data with attributes for the IDs.

>>>a
[1,1,1,1,2,2,3,3]
>>>b
['No','No','Yes','No','Yes','No','No','No']

I want to create a list (c) that holds indexes for a that match the following criteria:

1) Only one index per ID in a

2) Indexes for IDs that have a 'Yes' in b take precedent

3) For IDs that don't have a 'Yes' any index is fine.

Using the above data as an example, the output would look like:

>>>c
[2,4,6]

So, you can see the data more easily:

>>> for c,(x,y) in enumerate(zip(a,b)): print(c,x,y)
...
0 1 No
1 1 No
2 1 Yes # grab this index ID 1
3 1 No
4 2 Yes # grab this index for ID 2
5 2 No
6 3 No  # grab this index, but either would have been fine for ID 3
7 3 No

Below is code that I've written. I am looking for a more efficient and Pythonic way to do it.

filterwhen='Yes'
uni=set(a)
sortedMain=sorted([list((i,c)) for c,i in enumerate(a)]) # sort list a
order=[i.pop() for i in sortedMain]
sortedFilt=[b[i] for i in order] # sort list b to keep data matched
sortedMain=[x for i in sortedMain for x in i]

c=[]
for i in uni:
    dex=[c for c,x in enumerate(sortedMain) if x==i]
    test=list(map((lambda x: x.lower().strip()==filterwhen.lower().strip()),[sortedFilt[i] for i in dex]))
    if any(test)==True:
        selecteddex=test.index(True)
        c.append(dex[selecteddex])
    else: c.append(dex[0])

print(c)

a has over 58,000 elements and 26,000+ are unique. Due to all the iterations, it takes too long to run this.


texts: Adding an item to a hierarchical data structure

texts:
What I need to do is create a new object, modify it using a recursive function, then merge it with another object, and do this all in such a way that the values of the new object take precedence over the values in the object I'm merging it with.

Currently, my code works, but I'd like to have more readable code, particularly this statement for the add operation:

@set.merge!(
    update(@set, insert(parent, id), @set[parent][1] + 1)
)

I've already refactored quite a bit, but I feel like there's a functional way, or at least more readable way, to write what I current have. I want it to be something like: new object → update it → merge it.

Here is the whole class with tests:

# Nested set for comments, for making it easy to load all comments in a list, sorted according to their nesting,
# and for nesting to be indicated.
class Database
    def initialize
        @set = {}
        @largest = -1
    end

    def fetch
        #Need Better syntax for this.
        @set.to_a.sort { |el1, el2| el1[1][0] <=> el2[1][0] }
    end

    def add(parent: nil, id: -1)
        if parent

            @set.merge!(
                update(@set, insert(parent, id), @set[parent][1] + 1)
            )
        else
            @set[id] = [@largest+1, @largest+2]
        end
        @largest += 2
        @set
    end

    private

    def insert(parent_id, id)
        parent_range = @set[parent_id]
        {
            parent_id => [parent_range[0], parent_range[1] + 2],
            id => [parent_range[1], parent_range[1] + 1]
        }
    end

    # O(n) * 2^n
    def update(old_state, state, target)
        # optimization for this:
        id,range = old_state.to_a.select{ |entry| entry[1][0] == target || entry[1][1] == target }[0]
        # better readability for this:
        if range && !state[id]
            state[id] =
                range.index(target) == 0 ? range.map{|n| n + 2} : [range[0], range[1] + 2]
            2.times do |i|
                update(old_state, state, range[i] + 1) if range[i] != state[id][i]
            end
        end
        state
    end
end

d = Database.new
d.add({id: 1, parent: nil })
d.add({id: 2, parent: nil })
d.add({id: 3, parent: nil })

p d.fetch == [
            [1, [0, 1]],
            [2, [2,3]],
            [3, [4,5]],
            ]

d.add({id: 4, parent: 1 })
d.add({id: 5, parent: 2 })
d.add({id: 6, parent: 3 })

p d.fetch == [
            [1, [0, 3]],
            [4, [1, 2]],
            [2, [4,7]],
            [5, [5,6]],
            [3, [8,11]],
            [6, [9,10]],
            ]

d.add({id: 7, parent: 1 })
d.add({id: 8, parent: 7 })

# Final output.
# 1
#     4
#     7
#         8
# 2
#     5
# 3
#     6

p d.fetch == [
            [1, [0, 7]],
            [4, [1, 2]],
            [7, [3, 6]],
            [8, [4, 5]],
            [2, [8,11]],
            [5, [9,10]],
            [3, [12,15]],
            [6, [13,14]],
            ]

UPDATE: Will probably just do this:

            insert(parent, id)
                .yield_self { |obj| update(@set, obj, @set[parent][1] + 1) }
                .yield_self { |updated_set| @set.merge!(updated_set) }


texts: Creating and manipulating a map for a text based game F#

texts:
I have put my whole code so far below, but what I am most interested in is how best to implement the map and utilise it. Any tips on organising my code and keeping it clean would also be greatly appreciated. Roomint is the function I am mostly worried about/ the room object.

type DamType=
    |Fire
    |Ice
    |Light
    |Dark
    |General

type Monster={
    name:string;
    dVal:float;
    dType:DamType;
    hVal:float;
    info:string;
    dInfo:string;
    dCry:string;
    Special:bool;
    sItem:int;
 }

type Armour={
    name:string;
    aVal:float;
    dType:DamType;
    info:string;
    iSpace:int;
}
type Weapon={
    name:string;
    dVal:float;
    dType:DamType;
    info:string;
    iSpace:int;
}

type Potion={
    name:string;
    pVal:float;
    info:string;
    iSpace:int;
}

type Bomb={
    name:string;
    bVal:float;
    dType: DamType;
    info:string;
    iSpace:int;
}

type User={
    name:string;
    Arm:Armour;
    Weap:Weapon;
    hVal:float;

}

An example of how weapon, armour, potion and bombs are formed and stored:

 let weap10 = {name="Legendary black blade";dVal=65.0;dType=General;
 info="The blade that was thought to be
 lost in time, was here all along, with this, you may aswell be
 unstoppable";iSpace=7 }

 let weapint =
     let weaplist =[weap1;weap2;weap3;weap4;weap5;weap6;weap7;weap8;weap9;weap10]
      weaplist

 let displayW (a:Weapon) =
    a.name

And lastly, how my rooms are stored, its a bit odd, and I hope there is a better way to form the rooms:

let r60 = {id=60;item=m8;n=61;e=0;s=59;w=0;complete=false}
let r61 = {id=61;item=m9;n=0;e=0;s=60;w=0;complete=false}
let row12 = [r60;r61]

let roomlist = List.concat[row1;row2;row3;row4;row5;row6;row7;row8;row9;row10;row11;row12]

roomlist

When a user enters a new room, if the object in the room (r1, r2, etc) is a monster, they battle the monster, if any other object, they have the option to put it into their inventory or move on. They can then move NESW depending on the room, the next room is loaded using the int value of their selected direction and loading the room with that ID, however I don't know how to go about this!
I am in my second year of university and am not so accustomed to F#.


texts:
I'm reading/writing half precision floating point numbers in C#. These are basically 16 bit floats, compared to the usual 32/64 bit floats and doubles we are used to working with.

I've taken some highly tested Java code from an obvious "expert on the subject" here and modified it to work with C#. Is this correct?

// ignores the higher 16 bits
public static float toFloat( int hbits )
{
    int mant = hbits & 0x03ff;            // 10 bits mantissa
    int exp =  hbits & 0x7c00;            // 5 bits exponent
    if( exp == 0x7c00 )                   // NaN/Inf
        exp = 0x3fc00;                    // -> NaN/Inf
    else if( exp != 0 )                   // normalized value
    {
        exp += 0x1c000;                   // exp - 15 + 127
        if( mant == 0 && exp > 0x1c400 )  // smooth transition
            return BitConverter.ToSingle(BitConverter.GetBytes( ( hbits & 0x8000 ) << 16
                                            | exp << 13 | 0x3ff ), 0);
    }
    else if( mant != 0 )                  // && exp==0 -> subnormal
    {
        exp = 0x1c400;                    // make it normal
        do {
            mant <<= 1;                   // mantissa * 2
            exp -= 0x400;                 // decrease exp by 1
        } while( ( mant & 0x400 ) == 0 ); // while not normal
        mant &= 0x3ff;                    // discard subnormal bit
    }                                     // else +/-0 -> +/-0
    return BitConverter.ToSingle(BitConverter.GetBytes(          // combine all parts
        ( hbits & 0x8000 ) << 16          // sign  << ( 31 - 15 )
        | ( exp | mant ) << 13 ), 0);         // value << ( 23 - 10 )
}
// returns all higher 16 bits as 0 for all results
public static int fromFloat( float fval )
{
    int fbits = BitConverter.ToInt32(BitConverter.GetBytes(fval), 0);
    int sign = fbits >>> 16 & 0x8000;          // sign only
    int val = ( fbits & 0x7fffffff ) + 0x1000; // rounded value

    if( val >= 0x47800000 )               // might be or become NaN/Inf
    {                                     // avoid Inf due to rounding
        if( ( fbits & 0x7fffffff ) >= 0x47800000 )
        {                                 // is or must become NaN/Inf
            if( val < 0x7f800000 )        // was value but too large
                return sign | 0x7c00;     // make it +/-Inf
            return sign | 0x7c00 |        // remains +/-Inf or NaN
                ( fbits & 0x007fffff ) >>> 13; // keep NaN (and Inf) bits
        }
        return sign | 0x7bff;             // unrounded not quite Inf
    }
    if( val >= 0x38800000 )               // remains normalized value
        return sign | val - 0x38000000 >>> 13; // exp - 127 + 15
    if( val < 0x33000000 )                // too small for subnormal
        return sign;                      // becomes +/-0
    val = ( fbits & 0x7fffffff ) >>> 23;  // tmp exp for subnormal calc
    return sign | ( ( fbits & 0x7fffff | 0x800000 ) // add subnormal bit
         + ( 0x800000 >>> val - 102 )     // round depending on cut off
      >>> 126 - val );   // div by 2^(1-(exp-127+15)) and >> 13 | exp=0
}


texts: Join - order by vote-sum and check if user has voted

texts:
I have a vote and a comment table. Now I want to display all comments and order them by votes-sum. Sum because some votes can have a higher value than others.

Therefore I want to display if the user has voted already on a comment. So I need to get that value too.

This is my actual query:

SELECT *, SUM(v.`value`) as votesum,

(
     SELECT 1
     FROM votes
     WHERE user_id = 123 and id = v.id

) as user_voted_already

FROM comments as c
LEFT JOIN votes as v
ON c.id = v.`foreign_id` and v.`foreign_type` = 'comment'
WHERE c.`network_id` = 3183
GROUP BY ( v.`foreign_id`)
ORDER BY votesum DESC

It's working but I'm just wondering if this is the right way (or: the fastest way).

These are the table definitions:

votes (polymorphic):
    id
    user_id
    guest_ip (for guest votes)
    foreign_id
    foreign_type
    category
    value
    comment
    created_at
    updated_at

comments
    id
    network_id
    network_name

… and many others that I don't think are needed for the question.


texts:
I'm in the process of delving into different design patterns and trying to implement them into my daily work routine.

I come from an unstructured world of PHP and not understanding how to utilize it to its potential. I have recently switched over to C# and I'm trying to unlearn some bad habits I picked up through my lack of understanding.

I have some of my WebAPI project, which will grow in the future so I'm trying to plan for that now. Please review the code and see if I have implemented a repository pattern correctly. The code is 100% functional but I put it together out of a few eBooks I'm reading and a few articles I found online.

Simple interface with only one method:

public interface IProductRepository
    {
        ProductViewModel GetProduct(string ProdNum);
    }
}

Product Repository Class:

public class ProductRepository : IProductRepository
{
    private ProductMaterialEntities pd;

    public ProductRepository(ProductMaterialEntities product)
    {
        pd = product;
    }
    public ProductViewModel GetProduct(string prodNum)
    {
        var result1 = pd.products.Where(x => x.ProdNum == prodNum).FirstOrDefault();
        var result2 = pd.ProductImagePaths.Where(x => x.ImageProdNum == prodNum).FirstOrDefault() ?? new ProductImagePath();
        if (result1 != null)
        {
            ProductViewModel product = new ProductViewModel()
            {
                ProdID = result1.ProdID,
                ProdNum = result1.ProdNum,
                ProdCode = result1.ProdCode,
                .
                .
                .
                .//whole bunch of attributes
                ImageCompany = result2.ImageCompany
            };
            return product;
        }
        //return empty ProductViewModel if nothing is found
        return new ProductViewModel();
    }
}

Default controller

public class ValuesController : ApiController
    {
        private IProductRepository productRepository;
        public ValuesController()
        {
            productRepository = new ProductRepository(new ProductMaterialEntities());
        }

        [Route("Product/GetProduct/{prodNum}")]
        // Access via: http://xxxxxxxxx/Product/GetProduct/02130
        public IHttpActionResult GetProduct(string prodNum)
    {
        var productInfo = productRepository.GetProduct(prodNum);
        if (productInfo.ProdID <= 0)
        {
            return NotFound();
        }
        return Ok(productInfo);
    }
   }


texts: Read in parameters with links from textfile

texts:
I'm trying to read in a few lines of parameters from an textfile and format these paths.

How can I improve this code to work with less lists? I just need the final paths.

import os
config = open("C:\\Users\\config.txt")
content = config.readlines()
removedEnds = []
removedStarts = []
finalPaths = []

for string in content:
    removedEnds.append(string.rstrip())

for string in removedEnds:
    print(string)
    if string.find('='):
        removedStarts.append(string[(string.find('=')+1):])

for string in removedStarts:
    finalPaths.append(string.split("\\"))

for string in finalPaths:
    print(os.path.join(*string))

The textfile looks like this:

Source=C:\Users\workspace\OMDB\WebContent\app
Target=C:\Apache24\htdocs


texts:
I wrote a script for validate the input field for following requirements

Not null
Multiple of hundreds
Less than needed amount

Here is my script:

    $('#investAmount,#invest-button').bind('keypress', function(event){
        if(event.which == 13){
            if(amountValidation('#investAmount','#inNeedAmt','#invalidAmt','#mult100','#needAmtValidation')){
                return false;
            }
            else{$(elementId).removeClass('errorField');}
        }
    });
    $('#invest-button').click( function(event){
        if(amountValidation('#investAmount','#inNeedAmt','#invalidAmt','#mult100','#needAmtValidation')){
            return false;
        }
        else{$(elementId).removeClass('errorField');}
    });

function amountValidation(elementId,needAmt,errorMsgId,errorMsgId2,errorMsgId3){
    var gvAmount =$(elementId).val();

    var errAmount = gvAmount == '';
    if(errAmount == true){$(elementId).addClass('errorField');}
    $(errorMsgId).toggle(errAmount);

    var errGVAmount = !errAmount && !gvAmount.match(/^[1-9]\d*00$/);
    $(errorMsgId2).toggle(errGVAmount);
    if(errGVAmount == true){$(elementId).addClass('errorField');}

    var errNeedAmount =parseInt($(needAmt).val()) <  parseInt(gvAmount);
    $(errorMsgId3).toggle(errNeedAmount);
    if(errNeedAmount == true){$(elementId).addClass('errorField');}

    return errAmount || errGVAmount || errNeedAmount;
}

Actually I am going to use this function in my website multiple places please help me to make this better script.
My jsfiddle is here


texts:
I have the following code which returned the solution I was wanting after running for 1 hour. Are there any techniques I could use to improve run-time?

If I were using imperative programming I would just more aggressively cache the partial results, but that's less appropriate for this approach.

How should I transform this function so it will have less run-time?

-module(pathing).
-export([paths/1]).

paths(N) -> paths(N, 0, 0, 0).

paths(0, 0, 0, 0) -> 1;
paths(0, _, _, _) -> 0;
paths(N, X, Y, Z) -> paths(N-1, X, Y+1, Z-1)
                 + paths(N-1, X, Y-1, Z+1)
                 + paths(N-1, X+1, Y, Z-1)
                 + paths(N-1, X-1, Y, Z+1)
                 + paths(N-1, X+1, Y-1, Z)
                 + paths(N-1, X-1, Y+1, Z).

The problem is to count the number of paths from a cell to itself in N steps on a hex grid.

p.s. This is a problem from a problem site. I would link to the problem but I don't wish for this to be a spoiler, and I am happy that this code is correct in terms of the actual problem definition.


texts: Adding order actions like "Print" or "RePrint"

texts:
The eventual desire to implement code that's clean and extendable. I always fear that I'm overusing If's and or not seeing the appropriate pattern to reduce conditionals.

Now I love architecture, micro service's etc I even enjoy IoC, ISP(SOLID) But when it comes down to small encapsulated methods, the nuances of reducing If's , I struggle to grasp.

I know I've instantiated concrete types and coupled the responsibility(May have just answered my own question). The reality is, I want to minimize the use of If's.

Could I kindly request a Code Review on the below snippet?

public async Task AddOrderActionAsync(Identity identity,
    string value,
    string order_number)
{
    if (!string.IsNullOrWhiteSpace(value))
    {
        var client = await _context.tbl_Client.FirstOrDefaultAsync(c =>
                            c.ClientKey == identity.ClientKey);
        try
        {
            // See if order action exists, if it does it could contain multiple
            // so delete all and re-add one
            var orderAction = _context.tbl_OrderActions.Where(o =>
            o.tbl_Client.ClientKey == identity.ClientKey &&
            o.OrderNumber == order_number).ToList();

            if (orderAction != null &&
                orderAction.Count() > 0)
            {
                _context.tbl_OrderActions.RemoveRange(orderAction);
               await AddOrderActionAsync(_context, identity,
                                       value, order_number);
            }
            else
            {
                await AddOrderActionAsync(_context, identity, value, order_number);
            }

            await _context.SaveChangesAsync();
        }
        catch (AddOrderActionException ex)
        {
            new Email().SendEmail(identity.ClientName,
                    "Add Order Action Error - Data API",
                    "Add Order Action Error(" + value + " - " + order_number + "): " + ex.Message,
                    "error@retain.me");

            //System needs to run regardless if this fails
            return;
        }
    }
}

The above code is adding an "OrderAction" which could be "Print" or "RePrint", there is a possibility that multiple could be added else where in the pipeline or another app. The ideas is to remove the multiple and re-add one an/or just add.


texts: Implement integer exponentiation faster than repeated multiplication

texts:
The task:

  Implement integer exponentiation. That is, implement the pow(x, y)
  function, where x and y are integers and returns x^y.

  Do this faster than the naive method of repeated multiplication.

  For example, pow(2, 10) should return 1024.

Solution 1

function pow(x, y) {
  if (!y) { return 1; }
  let tmp = res = x;
  for (let i = 1; i < y; i++) {
    for (let j = 1; j < x; j++) {
      tmp += res;
    }
    res = tmp;
  }
  return res;
}

console.log(pow(2, 10));

I can't claim the following solution to be originally by me. I read it up and implemented it the way I understood. I'm also not sure whether Solution 1 nor Solution 2 is "faster than (...) repeated multiplication".

Solution 2 Also known as "Exponentiation by squaring"

function pow2(x, y) {
  if (!y) { return 1; }
  if (y % 2) {
    return x * pow2(x, y - 1);
  }
  const p = pow2(x, y/2);
  return p * p;
}

console.log(pow2(2,10));