texts:
After seeing Snake coded in 10 minutes, I decided to try a similar challenge, albeit easier. The following is Tic Tac Toe that I coded in 10 minutes. Given the short time frame, I'm sure there are style and convention errors abound, and would appreciate any suggestions :)

I will also specifically ask about one thing - checking if there is a winner(done in the only ActionPerformed method). It feels long and convoluted, but it was the best I could think of at the time. Looking back, I still can't really think of any ways to write it better, actually...

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TicTacToe {
  private JFrame main;
  private TicButton[][] buttons;
  private JPanel[] rows;
  private boolean p1turn = true;
  private final Color bg1 = new Color(255,0,0);
  private final Color bg2 = new Color(0,255,0);
  public static void main(String[] args) {
    new TicTacToe().go();
  }
  public void go() {
    main = new JFrame("Tic Tac Toe!");
    buttons = new TicButton[3][3];
    rows = new JPanel[3];
    int r = 0;
    main.getContentPane().setLayout(new BoxLayout(main.getContentPane(),BoxLayout.Y_AXIS));
    for (int i = 0; i < 3; i++) {
      rows[r] = new JPanel();
      for (int j = 0; j < 3; j++) {
        buttons[i][j] = new TicButton();
        rows[r].add(buttons[i][j]);
      }
      main.getContentPane().add(rows[r]);
      r++;
    }
    main.pack();
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setVisible(true);
  }
  private class TicButton extends JButton{
    int value;
    private boolean clicked;
    public TicButton() {
      super("-");
      this.value = -1;
      clicked = false;
      setFocusable(false);
      this.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            if (!clicked) {
              clicked = true;
              setText(p1turn ? "X" : "O");
              value = p1turn ? 1 : 2;
              setBackground(p1turn ? bg1 : bg2);
              p1turn = !p1turn;
              setEnabled(false);
            }

          boolean winner = false;
          String win = "";
          for (TicButton[] tt : buttons) {
            if (tt[0].value == tt[1].value && tt[0].value == tt[2].value && tt[0].value != -1) {
              winner = true;
              win = tt[0].value == 1 ? "X" : "O";
              break;
            }
          }
          for (int j = 0; j < 3; j++) {
            if (buttons[0][j].value == buttons[1][j].value &&
                buttons[0][j].value == buttons[2][j].value &&
                buttons[0][j].value != -1) {
              winner = true;
              win = buttons[0][j].value == 1 ? "X" : "O";
              break;
            }
          }
          if (buttons[0][0].value == buttons[1][1].value && buttons[0][0].value == buttons[2][2].value &&
              buttons[0][0].value != -1) {
            winner = true;
            win = buttons[0][0].value == 1 ? "X" : "O";
          }
          if (buttons[0][2].value == buttons[1][1].value && buttons[0][2].value == buttons[2][0].value &&
              buttons[0][2].value != -1) {
            winner = true;
            win = buttons[0][2].value == 1 ? "X" : "O";
          }
          if (winner) {
            JOptionPane.showMessageDialog(main, win + " wins!");
            main.setVisible(false);
            System.exit(0);
          }
        }
      });
    }
  }

}


texts:
I've created a cli application that consists of a package with 2 functions. One to get the external ip address, and another function to update a dynamic dns record at dns.he.net. Both are then used in main based on the provided parameters.

Since this is my first "real" go application i would like to know if I'm using structs, interfaces and functions correctly, as well as the overal structure of the application and if stuff should move into the functions or should go into main.

(Since it is tailor-made for my specific case I've hardcoded the remote url's.)

All feedback is welcome.

usage:

dyn-he-updater get --ipv4

dyn-he-updater update --domain=example.com --password=skdffngkele --ipv4

dyn.go

package dyn

import (
    "crypto/tls"
    "github.com/go-resty/resty"
    "log"
    "net"
    "strings"
)

type Dyn interface {
    GetIp() string
    UpdateIp()
}

type He struct {
    Hostname string
    Password string
    Ip       net.IP
}

func GetIp(uri string) net.IP {
    resp, err := resty.R().Get(uri)
    if err != nil {
        log.Fatal("ERROR: %s", err)
    }

    ip := net.ParseIP(strings.TrimSpace(string(resp.Body())))

    if ip == nil {
        log.Fatal("ERROR: Failed to parse the IP.")
    }
    return ip
}

func (h *He) UpdateIp(uri string) {
    log.Println("INFO: updating the ip")
    log.Printf("INFO: URI: %s \nDomain: %s \nPassword: %s \nIP: %v\n", uri, h.Hostname, h.Password, h.Ip)

    resty.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})

    resp, err := resty.R().
        SetFormData(map[string]string{
            "hostname": h.Hostname,
            "password": h.Password,
            "myip":     h.Ip.String(),
        }).
        Post(uri)
    if err != nil {
        log.Fatal("ERROR: ", err)
    }

    log.Printf("INFO: resp: %v", string(resp.Body()))
}

main.go

package main

import (
    "fmt"
    "github.com/Adamar/dyn-he-updater/dyn"
    "gopkg.in/alecthomas/kingpin.v2"
    "net"
    "os"
)

var (
    app   = kingpin.New("dyn-he-updater", "A commandline updater for dynamic ip's from dyn.dns.he.net")
    debug = app.Flag("debug", "Enable debug mode.").Bool()

    get   = app.Command("get", "Get the raw ip from an external service.")
    getV4 = get.Flag("ipv4", "Get only the IPv4 ip address.").Bool()
    getV6 = get.Flag("ipv6", "Get only the IPv6 ip address.").Bool()

    update = app.Command("update", "Update the dynamic ip.")
    domain = update.Flag("domain", "Domain you want to update.").Required().String()
    pass   = update.Flag("password", "Password to update the domain.").Required().String()
    v4     = update.Flag("ipv4", "Update only the IPv4 ip address. (default)").Bool()
    v6     = update.Flag("ipv6", "Update only the IPv6 ip address.").Bool()

    CheckIPv4Uri = "http://ipv4.myexternalip.com/raw"
    CheckIPv6Uri = "http://ipv6.myexternalip.com/raw"
    UpdateIpUri  = "https://dyn.dns.he.net/nic/update"
)

func main() {
    kingpin.Version("0.0.1")

    switch kingpin.MustParse(app.Parse(os.Args[1:])) {

    case get.FullCommand():

        if *getV4 == true {
            r := dyn.GetIp(CheckIPv4Uri)
            fmt.Printf("IPv4: %s\n", r)
        } else if *getV6 {
            r := dyn.GetIp(CheckIPv6Uri)
            fmt.Printf("IPv6: %s\n", r)
        } else {
            r := dyn.GetIp(CheckIPv4Uri)
            fmt.Printf("IPv4: %s (default)\n", r)
        }

    case update.FullCommand():
        if *domain != "" && *pass != "" {

            var r net.IP
            if *v4 == true || *v6 == false {
                r = dyn.GetIp(CheckIPv4Uri)
            } else if *v6 == true {
                r = dyn.GetIp(CheckIPv6Uri)
            }

            d := dyn.He{Hostname: *domain, Password: *pass, Ip: r}
            d.UpdateIp(UpdateIpUri)
        }
    }
}


texts: All the knight moves in all the right places

texts:
Challenge

Find all possible moves for a knight on an empty chessboard.

Specifications

The first argument is a path to a file.
The file contains multiple lines.
Each line is a test case representing the position of the knight in CN form.

C is a letter from “a” to “h” and denotes a column.
N is a number from 1 to 8 and denotes a row.

For each test case, print all positions for the next move of the knight ordered alphabetically.

Sample Input

  g2
  a1
  d6
  e5
  b1

Sample Output

  e1 e3 f4 h4
  b3 c2
  b5 b7 c4 c8 e4 e8 f5 f7
  c4 c6 d3 d7 f3 f7 g4 g6
  a3 c3 d2

Source

My Solution

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

#define LINE_LENGTH 5
#define BOARD_LENGTH 8
#define MOVE_BUFFER 24

int rows[] = {1, 2, 3, 4, 5, 6, 7, 8};
char cols[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
char moves[MOVE_BUFFER];
int move_iter = 0;

char num_convert(int *n) {
    for (int i = 0; i < BOARD_LENGTH; i++) {
        if (*n == rows[i]) {
            return cols[i];
        }
    }
}

int alpha_convert(char *c) {
    for (int i = 0; i < BOARD_LENGTH; i++) {
        if (*c == cols[i]) {
            return rows[i];
        }
    }
}

void add_moves(int c, int n1, int n2) {
    if (c >= 1 && c <= 8) {
        if (n1 >= 1) {
            moves[move_iter++] = num_convert(&c);
            moves[move_iter++] = n1 + '0';
            moves[move_iter++] = ' ';
        }
        if (n2 <= 8) {
            moves[move_iter++] = num_convert(&c);
            moves[move_iter++] = n2 + '0';
            moves[move_iter++] = ' ';
        }
    }
}

char* valid_moves(char position[]) {
    int C = alpha_convert(&position[0]);
    int N = atoi(&position[1]);

    add_moves(C - 2, N - 1, N + 1);
    add_moves(C - 1, N - 2, N + 2);
    add_moves(C + 1, N - 2, N + 2);
    add_moves(C + 2, N - 1, N + 1);

    moves[move_iter - 1] = '\0';
    move_iter = 0;
    return moves;
 }

int main(int argc, char *args[]) {
    if (argc < 2) {
        fprintf(stderr, "File path not provided. Exiting...\n");
        return 1;
    }

    if (argc > 2) {
        puts("Excessive arguments, only the first will be considered.");
    }

    FILE *file = fopen(args[1], "r");
    if (file == NULL) {
        perror("Error");
        return 1;
    }

    char position[LINE_LENGTH];
    while (fgets(position, LINE_LENGTH, file)) {
        puts(valid_moves(position));
    }

    fclose(file);
}


texts: Simple spinlock for C using ASM, revision #1

texts:
Revision #1 for Simple spinlock for C using ASM

The code:

static inline void atomic_open(volatile int *gate)
{
    asm volatile (
        "jmp check\n"                // Renegade selected, lets skip the line!
        "wait:\n"                    // Honest citizens wait in line.
        "pause\n"                    // Stroke beard, check phone/watch.
        "check:\n"                   // Ok, lets do this...
        "mov %[lock], %%eax\n"       // eax = 1
        "lock xchg %%eax, %[gate]\n" // Exhange eax with gate value.
        "test %%eax, %%eax\n"        // 1 = closed, 0 = open.
        "jnz wait\n"                 // Ohhh man, here I go again...
        : [gate] "=m" (*gate)
        : [lock] "r" (1)
        : "eax"                      // Tell compiler you want to use eax register.
    );

}

static inline void atomic_close(volatile int *gate)
{
    asm volatile (
        "mov %[unlock], %[gate]\n"
        : [gate] "=m" (*gate)
        : [unlock] "r" (0)
    );
}

// Usage, example.
volatile int atomic_gate_memory = 0;
void *mymalloc(size_t size)
{
    atomic_open(&atomic_gate_memory);
    void *ptr = malloc(size);
    atomic_close(&atomic_gate_memory);
    return ptr;
}

The question is the same as before: Will atomic_[open/close] make mymalloc both threadsafe and reentrant?

If no, what is wrong?
If yes, it is still wrong; isn't it?... Give me a good rant about what to consider, what is missing or about better approach. If you want to suggest libraries, please restrict your self to C. I am not experienced enough to bind C++ stuff to other languages, so I often can't use the good stuff over there :'(


texts: MemoryError in Python while combining multiple JSON files and outputting as single CSV

texts:
I have a number of JSON files to combine and output as a single CSV (to load into R), with each JSON file at about 1.5GB.  While doing a trial on 4-5 JSON files at 250MB each, the code works when I only use 2-3 files but chokes when the total file sizes get larger.

I'm running Python version 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on 8GB RAM and Windows 7 Professional 64 bit.

I'm a Python novice and have little experience with writing optimized code.  I would appreciate guidance on optimizing my script below.

Python MemoryError

Traceback (most recent call last):
  File "C:\Users\...\tweetjson_to_csv.py", line 52, in <module>
    for line in file:
MemoryError
[Finished in 29.5s]

JSON to CSV conversion script

# csv file that you want to save to
out = open("output.csv", "ab")

filenames = ["8may.json", "9may.json", "10may.json", "11may.json", "12may.json"]
open_files = map(open, filenames)

# change argument to the file you want to open
for file in open_files:
    for line in file:
        # only keep tweets and not the empty lines
        if line.rstrip():
            try:
                tweets.append(json.loads(line))
            except:
                pass

for tweet in tweets:
    ids.append(tweet["id_str"])
    texts.append(tweet["text"])
    time_created.append(tweet["created_at"])
    retweet_counts.append(tweet["retweet_count"])
... ...

print >> out, "ids,text,time_created,retweet_counts,in_reply_to,geos,coordinates,places,country,language,screen_name,followers,friends,statuses,locations"
rows = zip(ids,texts,time_created,retweet_counts,in_reply_to_screen_name,geos,coordinates,places,places_country,lang,user_screen_names,user_followers_count,user_friends_count,user_statuses_count,user_locations)

csv = writer(out)

for row in rows:
    values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
    csv.writerow(values)

out.close()


texts: Given an integer array A and a range, find a subarray within the range with a minimum sum

texts:
Problem

HackerRank Range query:

  You are given an array A of n integers. You have to perform m
  queries on the array. The queries are of two types:

  Modify the ith element of the array.
  Given x, y, print min{Ai + Ai+1 +…+ Aj | x ≤ i ≤ j ≤ y}.

  Note: A brute force solution may not work; Try using an efficient data structure. Use fast I/O to avoid TLE.

  Input Format

  The first line contains an integer t denoting the number of test
  cases.

  The next line consists of an integer n.

  The following line contains n integers representing the array A.

  The next line contains an integer m denoting the number of queries.

  The following m lines contain integers of the form given below.

  0 x y: modify Ax into y
  1 x y: print min{Ai + Ai+1 +…+ Aj | x ≤ i ≤ j ≤ y}

  Constraints

    1 ≤ t ≤ 100

    1 ≤ n ≤ 50000

    -10000 ≤ Ai ≤ 10000

    0 ≤ m ≤ 50000

  Output Format

  For each query print the output as specified.

My Solution

Algorithm

Calculate prefix sums prefix_sums for the given array.
For the given interval, move from left to right and keep track of the largest encountered value max_prefix_sum of prefix_sums and the minimum subsum min_subsum (min_subsum = min(prefix_sums[i] - max_prefix_sum) for left=<i<=right). In the end, min_subsum is the answer.
If some value of the initial array is updated then prefix_sums must be updated accordingly.

The overall time complexity of the algorithm is O(n2). The space complexity is O(n). I know that for a O(n2) time complexity solution I don't need any additional array and there's a more elegant solution for this based on Maximum Subarray Problem. However, it feels like with prefix sums I have a better chance of having a O(nlogn) or O(n1.5) time complexity solution.

Code

import itertools

class MinSumRangeQuery:
    prefix_sums = None

    def __init__(self, array):
        self.prefix_sums = list(itertools.accumulate(array))

    def update(self, index, value):
        diff = value - array[index]
        for i in range(index, len(self.prefix_sums)):
            self.prefix_sums[i] += diff

    def min_subarray_sum(self, left, right):
        if left == right:
            return self.prefix_sums[left]

        min_subsum = 99999999
        max_prefix_sum = self.prefix_sums[left - 1]
        for i in range(left, right + 1):
            current_subsum = self.prefix_sums[i] - max_prefix_sum

            if min_subsum > current_subsum:
                min_subsum = current_subsum

            if max_prefix_sum <= self.prefix_sums[i]:
                max_prefix_sum = self.prefix_sums[i]

        return min_subsum

for _ in range(int(input())):
    n = int(input())
    array = [int(i) for i in input().split()]
    array.insert(0, 0)
    minSumRangeQuery = MinSumRangeQuery(array)

    for _ in range(int(input())):
        a, x, y = [int(i) for i in input().split()]
        if a == 1:
            print(minSumRangeQuery.min_subarray_sum(x, y))
        elif a == 0:
            if array[x] != y:
                minSumRangeQuery.update(x, y)

Question

Given the constraints above, the code times out for all but a default test case. What's a more efficient way to solve the problem?


texts:
I am implementing a class to mimic dynamic array as a part of my learning process of data structures. I have written the following class which works as a dynamic array data structure.
I have gone through some video tutorials and also read some code from Java's ArrayList implementation to understand how to code it in a simple manner. I would like to get the code reviewed from the following perspective:

Is there any design pattern that I should be following
Improvements like removing compile time warning related to generics.
Any tips on including test cases that can expose hidden issues in the code
Any other tips that will make it a better code like improve its performance or make it more modular.

import java.util.Arrays;
import java.util.Iterator;

public class DynamicArray<T> implements Iterable<T> {
  private Object[] elements;
  private int length = 0;
  private int capacity = 0;

  public DynamicArray() {
    this(10);
  }

  public DynamicArray(int capacity) {
    this.capacity = capacity;
    this.length = 0;
    this.elements = new Object[capacity];
  }

  public int size() {
    return length;
  }

  public boolean isEmpty() {
    return size() > 0;
  }

  public T get(int index) {
    validateIndexValue(index);
    return (T)elements[index];
  }

  public void set(int index, T element) {
    validateIndexValue(index);
    elements[index] = element;
  }

  public void clear() {
    for(int i = 0; i < length; i++) {
      elements[i] = null;
    }
    length = 0;
  }

  public boolean add(T element) {
    ensureCapacity(length + 1);
    elements[length++] = element;
    return true;
  }

  public T removeAt(int index) {
    validateIndexValue(index);
    T element = (T) elements[index];
    removeElement(index);
    return element;
  }

  public boolean remove(T element) {
    if(element == null) {
      for(int i = 0; i < length; i++) {
        if(elements[i] == null) {
          removeElement(i);
          return true;
        }
      }
    } else {
      for(int i = 0; i < length; i++) {
        if(element.equals(elements[i])) {
          removeElement(i);
          return false;
        }
      }
    }
    return false;
  }

  public int indexOf(T element) {
    if(element == null) return -1;
    for(int i = 0; i < length; i++) {
      if(element.equals(elements[i])) {
        return i;
      }
    }
    return -1;
  }

  public boolean contains(T element) {
    return indexOf(element) > -1;
  }

  public java.util.Iterator<T> iterator() {
    return new java.util.Iterator<T>() {
      int index = 0;
      public boolean hasNext() {
        return index < length;
      }

      public T next() {
        return (T) elements[index++];
      }
    };
  }

  private void removeElement(int index) {
    int elementsToMove = length - index - 1;
    if(elementsToMove > 0) {
      System.arraycopy(elements, index + 1, elements, index, elementsToMove);
    }
    elements[--length] = null;
  }

  private void ensureCapacity(int minSize) {
    if(minSize >= capacity) {
      capacity *= 2;
      elements = Arrays.copyOf(elements, capacity);
    }
  }

  private void validateIndexValue(int index) {
    if(index >= length || index < 0) {
      throw new IllegalArgumentException("Bad index value passed : " + index);
    }
  }
}
```


texts:
This is my solution for NQueen problem in scala.
I just want to know how to make it more easy to read, modular and areas i need to improve.

object Main {
  def main(args: Array[String]): Unit = {
    val matrix = Array.ofDim[Int](16,16)

    val queen_place = (2,2)

    nQueenSol(matrix,matrix.size)

  }

  def diagonal_rule(x1:Int,y1:Int,x2:Int,y2:Int) = x1 + y1 == x2 + y2 || x1 - y1 == x2 - y2
  def vertical_or_horizontal_rule(x1:Int,y1:Int,x2:Int,y2:Int) = x1 == x2 || y1 == y2

  def queen_places(x:Int,y:Int,chess_board:Array[Array[Int]]):Array[Array[Int]] = {
    for(i <- 0 until chess_board.size;
    j <- 0 until chess_board.size) {
      if(chess_board(i)(j) == 0)
        chess_board(i)(j) = if(diagonal_rule(x,y,i,j)|| vertical_or_horizontal_rule(x,y,i,j))1 else 0

    }
    chess_board
  }
  def printChessBoard(array: Array[Array[Int]]): Unit ={
    array.foreach(y => {
      y.foreach(x => print(x + " "))
      println()
    }
    )
  }

  def queenNotPresentAt(chessBoard:Array[Array[Int]])(x:Int,y:Int) = chessBoard(x - 1)(y) == 0

  def nQueenSol(chessBoard:Array[Array[Int]],nthQueen:Int): Unit ={

    if(nthQueen == 0) {printChessBoard(chessBoard);println}
    else {

      for(i <- 0 until chessBoard.size){
        val touched = chessBoard.map(_.clone())

        if(queenNotPresentAt(touched)(nthQueen, i)) {
          touched(nthQueen - 1)(i) = 2
          val newchessBoard = queen_places(nthQueen - 1,i,touched)

          nQueenSol(newchessBoard,nthQueen - 1)

        }
      }
    }
  }
}


texts: Length of longest palindrome subsequence

texts:
I had an interview, where I was asked to solve to this question:

Given an string str, find the maximum length of palindrome subsequence.
Example: >if str = 'abcda':
maximum_length = 3 'aca'

How can I improve this code?
def maximum_length_palindrome_subsequence(a):
    a = list(a)
    n = len(a)
    table = [[0 for i in xrange(n)] for j in xrange(n)]
    for i in xrange(n):
        table[i][i] = 1
    for gap in xrange(1,n):
        for i in xrange(n-1):
            h = i+gap
            if h>=n:
                continue
            if a[i] == a[h]:
                if i+1==h:
                    table[i][h] = 2
                else:
                    table[i][h] = table[i+1][h-1] + 2
            else:
                if h<n:
                    table[i][h] = max(table[i+1][h], table[i][h-1])
    return table[0][n-1]

print maximum_length_palindrome_subsequence('abcbda')


texts: Determining if a pair exists in a large sorted array

texts:
I'm doing practice interview questions from here. Here is the one I am currently on - if you are given a very large sorted int array, then check of there exists a pair.

public static int sumOfTwoExists(int[] largeArray, int a, int b) {
    A: for(int count = 0; count < largeArray.length; count ++) {
        for(int counter = count + 1; counter < largeArray.length; counter ++) {
            if(largeArray[count] + largeArray[counter] == a + b) {
                return 1;
            } else if(largeArray[count] + largeArray[counter] > a + b) {
                break A;
            }
        }
    }
    return -1;
}

I tested this code and it works. What I am having trouble with is the next part of the question - he asked if there's an optimal method \$O(1)\$ to find the match for the previous question?

How would you optimize this code so that the match is a constant time operation? I still don't how that would be done because it looks like iteration is still required.


texts: Python adding partialmethods to a class at compile time

texts:
I am writing a class for delayed operations on variables which are resolved at a later time. I am using pythons operator overloading but my class definition seems very boilerplatey.

Is there a more succinct way to define the following class?

from functools import partialmethod
import operator

class Forward:

    def resolve(self, env):
        raise NotImplementedError()

    def op(self, op, rhs):
        if not isinstance(rhs, Forward):
            raise TypeError('"{}" not of type `Forward`'.format(rhs))
        return Evaluation(op, self, rhs)

    __eq__ = partialmethod(op, operator.__eq__)
    __gt__ = partialmethod(op, operator.__gt__)
    __lt__ = partialmethod(op, operator.__lt__)
    __ge__ = partialmethod(op, operator.__ge__)
    __le__ = partialmethod(op, operator.__le__)

    __add__ = partialmethod(op, operator.__add__)
    __sub__ = partialmethod(op, operator.__sub__)
    __mul__ = partialmethod(op, operator.__mul__)
    __truediv__ = partialmethod(op, operator.__truediv__)
    __floordiv__ = partialmethod(op, operator.__floordiv__)
    __pow__ = partialmethod(op, operator.__pow__)

    __iadd__ = partialmethod(op, operator.__iadd__)
    __isub__ = partialmethod(op, operator.__isub__)
    __imul__ = partialmethod(op, operator.__imul__)
    __itruediv__ = partialmethod(op, operator.__itruediv__)
    __ifloordiv__ = partialmethod(op, operator.__ifloordiv__)
    __ipow__ = partialmethod(op, operator.__ipow__)

class Evaluation(Forward):

    def __init__(self, op, lhs, rhs):
        self.op = op
        self.lhs = lhs
        self.rhs = rhs

    def resolve(self, env):
        return self.op(self.lhs.resolve(env), self.rhs.resolve(env))

class Constant(Forward):

    def __init__(self, value):
        self.value = value

    def resolve(self, env):
        return self.value

class Variable(Forward):

    def __init__(self, name):
        self.name = name

    def resolve(self, env):
        return env[self.name]

if __name__ == "__main__":
    print((Variable('a') + Variable('b')).resolve({'a': 1, 'b': 2})

This code is part of a larger project which operates on time series data, I wanted a small way to add conditions that would evaluate whether or not to perform some other action based on the data (env) at that time, for example.

# All stages in a `pipeline` run each time a new entry is available.
# Log when simply logs the current data when `func` returns `True`.
pipeline.add(LogWhen(level=error, func=Variable('cash') < Constant(0)))

I have included enough code to demonstrate the purpose of this code but I am mainly concerned with defining the magic_methods on the Forward class. However review on any parts of the code is welcome.


texts: Writing a byte array image to disk with an automatically generated filename

texts:
I have the following code that that writes large images to disk. My application server is running out of memory and I'm wondering if I could somehow optimize the following:

public void writeImgToDisk(byte[] base64AttachmentInBytes, String dmxi){

        String destinationAndFileName  = "";
        String fileNameMinusExtension = getCurrentTimeStampForFileNaming();
        String extension="";
        try {

               TikaConfig config = TikaConfig.getDefaultConfig();
               InputStream stream = new ByteArrayInputStream(base64AttachmentInBytes);

               MediaType mediaType = config.getMimeRepository().detect(stream, new Metadata());
               MimeType mimeType;

            try {
                mimeType = config.getMimeRepository().forName(mediaType.toString());
                extension = mimeType.getExtension();
                System.out.println("Extension is:"+ extension);

                File folder  = new File("Z:\\images\\"+ sref);
                if (!folder.exists()){
                    folder.mkdir();
                }
                destinationAndFileName  = "Z:\\images\\"+ dmxi + "\\" + fileNameMinusExtension+ extension;

                System.out.println("destinationAndFileName is:"+ destinationAndFileName);
            } catch (MimeTypeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            InputStream input = new ByteArrayInputStream(base64AttachmentInBytes);
            OutputStream output = new FileOutputStream(destinationAndFileName);
            IOUtils.copy(input, output);

            System.out.println("It was written..");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

This works but its the cause of a bottleneck during high volume calls.


texts: Finding an element in multiple sorted lists efficiently

texts:
I have \$k\$ sorted Lists, each of size \$n\$. Currently I have hard-coded 5 sorted Lists each of size 3, but in general that is configurable.

I would like to search for single element in each of the \$k\$ Lists (or its predecessor, if it doesn't exist).

Obviously I can binary search each List individually, resulting in a \$O(k*log(n))\$ runtime. But I think we can do better than that: after all, we're doing the same search \$k\$ times.

Could this be improved?

private static TreeSet<Integer> tree = new TreeSet<Integer>();

public SearchItem(final List<List<Integer>> inputs) {
    tree = new TreeSet<Integer>();
    for (List<Integer> input : inputs) {
        tree.addAll(input);
    }
}

public Integer getItem(final Integer x) {
    if(tree.contains(x)) {
        return x;
    } else {
        return tree.higher(x);
    }
}

public static void main(String[] args) {
    List<List<Integer>> lists = new ArrayList<List<Integer>>();

    List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(3, 4, 6));
    List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
    List<Integer> list3 = new ArrayList<Integer>(Arrays.asList(2, 3, 6));
    List<Integer> list4 = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
    List<Integer> list5 = new ArrayList<Integer>(Arrays.asList(4, 8, 13));

    lists.add(list1);
    lists.add(list2);
    lists.add(list3);
    lists.add(list4);
    lists.add(list5);

    SearchItem search = new SearchItem(lists);
    System.out.println(tree);

    Integer dataOuput = search.getItem(5);

    System.out.println(dataOuput);
}


texts: Allow one thread to execute section while others wait and resume

texts:
I have a requirement that is summarized below.
void update()
{
  |   |   |   |
  |   |   |   |
  |   |   |   |
 \|  \|  \|  \|
  =============
      meat           <--- Only one thread must execute here, the rest should skip it.
  =============
  |   |   |   |  <--- Other threads wait here until the "first" thread is done w/ "meat"
  |   |   |   |
  |   |   |   |
  |/  |/  |/  |/
}

From an outsider perspective, "meat" should be executed just once (by the first thread that encounters it)
This post is similar but differs in that it also requires other threads to execute the meat code block one at a time.
// testExecutive.cpp
#include <atomic>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>

struct Target {
  int nhits = 0;
  inline void hit() { ++nhits; }
};

struct Executive {
  Executive() = delete;
  Executive(int _Id, Target &_Tgt) : m_Id(_Id), m_Ready(false), m_Tgt(_Tgt) {}
  void update() {
    { // only one thread can execute this
      std::scoped_lock<std::mutex> lk(m_Mtx);
      // std::cout << "++Acquired lk " << m_Id << " | tid: " <<
      // std::this_thread::get_id() << "++\n";
      if (!m_Ready.load()) {
        // std::cout << "==Updating" << m_Id << " | tid: " <<
        // std::this_thread::get_id() << "==\n";
        m_Ready.store(true);
        m_Tgt.hit();
        m_Cv.notify_all();
      }
      // std::cout << "++Releasing lk " << m_Id << " | tid: " <<
      // std::this_thread::get_id() << "++\n";
    }

    // the rest should wait here
    std::mutex wait_mtx;
    std::unique_lock<std::mutex> lk(wait_mtx);
    m_Cv.wait(lk, [&]() -> bool { return m_Ready.load(); });
  }
  inline void reset() { m_Ready.store(false); }

private:
  int m_Id;
  Target &m_Tgt;
  std::condition_variable m_Cv;
  std::mutex m_Mtx;
  std::atomic_bool m_Ready;
};

int main(int argc, char *argv[]) {
  int n(2);
  if (argc >= 2) {
    n = atoi(argv[1]);
  }
  Target tgt;
  Executive e(1, tgt);
  auto updFn = [&e]() { e.update(); };

  // update same executive from 3 threads. Repeat n times.
  int i(n);
  while (i > 0) {
    e.reset();
    {
      std::thread t1(updFn), t2(updFn), t3(updFn);
      t1.join();
      t2.join();
      t3.join();
    }
    --i;
  }
  std::cout << (n == tgt.nhits ? "[OK]" : "[ERR]") << " Updates: " << n << " | "
            << "Hits: " << tgt.nhits << "\n";
  return 0;
}

I setup a simple method to verify that exactly one out of three threads executes the desired code. The method hit() is called in Executive::Update. Compile and test like so.
jaswant@HAL9000:~$ g++ testExecutive.cpp -lpthread --std=c++17
jaswant@HAL9000:~$ ./a.out 2
[OK] Updates: 2 | Hits: 2
jaswant@HAL9000:~$ ./a.out 100
[OK] Updates: 100 | Hits: 100
jaswant@HAL9000:~$ ./a.out 2
[OK] Updates: 2 | Hits: 2
jaswant@HAL9000:~$ ./a.out 4
[OK] Updates: 4 | Hits: 4
jaswant@HAL9000:~$ ./a.out 8
[OK] Updates: 8 | Hits: 8
jaswant@HAL9000:~$ ./a.out 16
[OK] Updates: 16 | Hits: 16
jaswant@HAL9000:~$ ./a.out 256
[OK] Updates: 256 | Hits: 256
jaswant@HAL9000:~$ ./a.out 1024
[OK] Updates: 1024 | Hits: 1024
jaswant@HAL9000:~$ ./a.out 8192
[OK] Updates: 8192 | Hits: 8192
jaswant@HAL9000:~$ ./a.out 100000
[OK] Updates: 100000 | Hits: 100000

So, it works. Can anyone please point out bad usage of mutex/condition variables/locks and perhaps a way to do this w/o an atomic variable in the predicate?


texts: Assign multiple values to variables with a function in a class

texts:
I would like to use this feature

>>> def func():
>>>     return 1, 2
>>> x, y = func()

But I have a formatting problem, because I want to assign values in the __init__() of a Class.

import csv

class Filewriter:
    def __init__(self, jsonstring, filepath):
        self.katAsk, self.katBid, self.promAsk, self.promBid, self.montAsk, self.montBid, self.katProm, self.katMont, self.promKat, self.promMont, self.montKat, self.montProm, self.ticker = self.get_row()

        self.jsonstring = jsonstring
        self.filepath = filepath

    def jsonparse(self, ticker, label):
        try:
            output = self.jsonstring[ticker][label]
        except (KeyError, ValueError) as e:
            output = None
        return output

    def test(self, teststring, ticker, cx):
        return self.jsonparse(ticker, cx+"."+teststring)

    def get_row(self, ticker):

        checkdic = {"ticker": ticker}
        # Check if asks/bids exist
        checkdic["cx"] = "CI1"
        try:
            katAsk = float(self.test("ask", **checkdic))
        except (TypeError, ValueError) as e:
            katAsk = -1

        try:
            katBid = float(self.test("bid", **checkdic))
        except (TypeError, ValueError) as e:
            katBid = -1

        checkdic["cx"]="IC1"
        try:
            promAsk = float(self.test("ask", **checkdic))
        except (TypeError, ValueError) as e:
        promAsk = -1
        try:
            promBid = float(self.test("bid", **checkdic))
        except (TypeError, ValueError) as e:
            promBid = -1

        checkdic["cx"]="NC1"
        try:
            montAsk = float(self.test("ask", **checkdic))
        except (TypeError, ValueError) as e:
            montAsk = -1
        try:
            montBid = float(self.test("bid", **checkdic))
        except (TypeError, ValueError) as e:
            montBid = -1

        # bidDest - askSource = sales
        # Determine sales
        # Kat -> Prom
        if(promBid > 0 and katAsk > 0):
            katProm = promBid - katAsk
        else:
            katProm = -1

        # Kat -> Mont
        if(montBid > 0 and katAsk > 0):
            katMont = montBid - katAsk
        else:
            katMont = -1

        # Prom -> Kat
        if(katBid > 0 and promAsk > 0):
            promKat = katBid - promAsk
        else:
            promKat = -1

        # Prom -> Mont
        if(montBid > 0 and promAsk > 0):
            promMont = montBid - promAsk
        else:
            promMont = -1

        # Mont -> Kat
        if(katBid > 0 and montAsk > 0):
            montKat = katBid - montAsk
        else:
            montKat = -1

        # Mont -> Prom
        if(promBid > 0 and montAsk > 0):
            montProm = promBid - montAsk
        else:
            montProm = -1

        return katAsk, katBid, promAsk, promBid, montAsk, montBid, katProm, katMont, promKat, promMont, montKat, montProm, ticker

    def tablewriter(self):
        with open(self.filepath, mode='w', newline='') as ag:
            agWriter = csv.writer(ag, delimiter=',',
                                  quotechar='"',
                                  quoting=csv.QUOTE_MINIMAL)

            agWriter.writerow([self.ticker,
                               self.katAsk,
                               self.katBid,
                               self.promAsk,
                               self.promBid,
                               self.montAsk,
                               self.montBid,
                               "",
                               self.katProm,
                               self.katMont,
                               self.promKat,
                               self.promMont,
                               self.montKat,
                               self.montProm,
                               "",
                               ])

Is it possible to format this statement on more than one line ?

edit: edited with real code

edit2: noticed a missing "self." before test() calls


texts:
Resharper complain if you have code like this:

border-width: 0px 1px 1px 0px;

and insists that units should be removed from zeroes as they are redundant. They are redundant, that is absolutely true, but I don't like inconsistency that is introduced by removal of units. You get code like this

border-width: 0 1px 1px 0;

which is pretty hideous in my opinion. So, what do you guys think? Should I remove redundant units, or should I disable this warning?


texts:
I have the following code, which draws a overlay image onto video for each frame:

video.addEventListener( 'play', function() {

    var $this = this; // cache

    (function drawCurrentFrameToCanvas() {
        if ( ! $this.paused && ! $this.ended ) {
            drawImage();
            requestAnimationFrame( drawCurrentFrameToCanvas ); // rAF is supported by most browsers in nowdays.
        }
    })();

}, 0);

function drawImage() {

    var points = getTrackingPoints();

    if( ! points ) return;

    var lh = points.pt4.y - points.pt2.y;
    var lw = points.pt2.x - points.pt1.x;
    var pw = ( lw < points.pt4.x - points.pt3.x ) ? points.pt4.x - points.pt3.x : lw; /* get longest left/right side */
    var ph = ( lh < points.pt3.y - points.pt1.y ) ? points.pt3.y - points.pt1.y : lh; /* get longest top/bottom side */
    var dx = points.pt2.x - points.pt1.x;
    var dy = points.pt2.y - points.pt1.y;
    var radianAngle = (Math.atan2(dy,dx)+Math.PI*2) % (Math.PI*2);

    ctx.clearRect( 0 , 0 , canvas.width, canvas.height );

    dot( points.pt1.x, points.pt1.y );
    dot( points.pt2.x, points.pt2.y );
    dot( points.pt3.x, points.pt3.y );
    dot( points.pt4.x, points.pt4.y );

    ctx.save();

    ctx.translate( points.pt1.x, points.pt1.y );
    ctx.rotate( radianAngle );
    ctx.translate( -points.pt1.x, -points.pt1.y );

    // ctx.globalAlpha = 0.5;

    if( typeof template !== 'undefined' ) {
        ctx.drawImage(template, points.pt1.x, points.pt1.y, pw, ph);
    }

    ctx.restore();

}

Where template used here is standard HTMLImageElement:

ctx.drawImage(template, points.pt1.x, points.pt1.y, pw, ph);

Is there a way to optimize it, to work faster?


texts:
I have written this method for converting a date time zone. How do i reduce the execution time of this method further.

public static Timestamp convertTimeZone(final Timestamp fromDate, final TimeZone fromTZ, final TimeZone toTZ ){
                Long timeInDate  =  fromDate.getTime() ;
                int fromOffset = fromTZ.getOffset(timeInDate);
                int toOffset = toTZ.getOffset(timeInDate);
                Timestamp dateStamp = new Timestamp(fromDate.getTime());
                if( fromOffset >= 0){
                    int diff = 0;
                    if( toOffset > 0){
                        diff = ( fromOffset - toOffset);
                    }else{
                        diff = ( fromOffset + Math.abs(toOffset));
                    }
                    long date = fromDate.getTime() - diff;
                    dateStamp.setTime( date );
                }else{
                    int diff = 0;
                    if( toOffset > 0){
                        diff = ( Math.abs( fromOffset) + toOffset);
                    }else{
                        diff = ( Math.abs( fromOffset) - Math.abs(toOffset));
                    }
                    long date = fromDate.getTime() + diff;
                    dateStamp.setTime( date );
                }
                return dateStamp;
            }


texts: Simple exercice representing a slidepuzzle

texts:
I've been helping out a student with an exercice, typed this up rapidly and thought it would be the ideal opportunity to improve my own programming style and approach to problem solving.

In this exercice a grid represents one of those slide puzzles. The patterns have been replaced by numbers. The zero represents the missing piece which allows for movement. There is no gameplay as of yet and the aim is to simply swap the missing piece around as would be done before the start of a game.

How could I make the code more concise?
What would be a good way to cut up the code into functions?
What other things could be improved to approach a decent programming style in Java?

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Puzzle {

    public static void main(String[] args) {

        System.out.println("Please enter dimensions of the puzzle.");

        System.out.println("Enter length (>0) ");

        Scanner sc = new Scanner(System.in);
        int width = sc.nextInt();

        System.out.println("Enter height (>0)");

        int height = sc.nextInt();

        int[][] puzzle = new int[width][height];

        populatePuzzle( puzzle );

        System.out.println("Enter position of missing piece");

        int position = sc.nextInt();

        placeMissingPiece( position, puzzle );

        System.out.println( "Missing piece is at " + Arrays.toString( findNumber( puzzle, 0 ) ) );

        displayPuzzle( puzzle );

        int number = 0;

        while( true ){
            System.out.println("Enter the number to be swapped around");

            number = sc.nextInt();

            swapElementValues( puzzle, findNumber( puzzle, 0 ), findNumber( puzzle, number ) );

            displayPuzzle( puzzle );
        }
    }

    public static void swapElementValues( int[][] puzzle, int[] missing, int[] target ){

        int tempValue = puzzle[ missing[0] ][ missing[1] ];

        puzzle[ missing[0] ][ missing[1] ] = puzzle[ target[0] ][ target[1] ];
        puzzle[ target[0] ][ target[1] ] = tempValue;
    }

    public static int[] findNumber( int[][] puzzle, int number ){

        for( int i = 0; i < puzzle.length; i++ ){
            for( int j = 0; j < puzzle[0].length; j++ ){
                if( puzzle[i][j] == number ){
                    int[] foundCoords = new int[2];

                    foundCoords[0] = i;
                    foundCoords[1] = j;

                    return foundCoords;
                }
            }
        }

        return null;
    }

    public static int getRandomInteger(){

        Random randomGenerator = new Random();

        return randomGenerator.nextInt(99) + 1;
    }

    public static void populatePuzzle( int[][] puzzle ){

        for( int i = 0; i < puzzle.length; i++ ){
            for( int j = 0; j < puzzle[0].length; j++ ){
                puzzle[i][j] = getRandomInteger();
            }
        }

    }

    public static void displayPuzzle( int[][] puzzle ){

        for( int i = 0; i < puzzle.length; i++ ){
            for( int j = 0; j < puzzle[0].length; j++ ){
                System.out.print( puzzle[i][j] + "," );
            }

            System.out.println( "" ); // Carriage return
        }

    }

    public static void placeMissingPiece( int elementNumber, int[][] puzzle ){

        int counter = 0;

        for( int i = 0; i < puzzle.length; i++ ){
            for( int j = 0; j < puzzle[0].length; j++ ){
                counter++;

                if( counter == elementNumber ){
                    puzzle[i][j] = 0;
                }
            }
        }

    }
}


texts:
This may be a poor title name. So I'm basing what I did from this website.

The idea is though that I have made a lot of work to a Service Object for a OPOS MSR device. (useless detail) One of the DirectIO calls gets some data off of a card and was supposed to return a byte array. That ended up being a big mistake because Unicode and translating was just a big big BIG headache. So my suggestion was to just convert the byte array to a string in C++ then send fire a DirectIO event with said string and call it good. So I did that, and it appears to work. One thing that has me concerned though is one of the lines from that website

  The general rule to COM resource is, if you allocate it then you release it. The only exception is when a value is passed over a COM interface as an OUT param. In that case, the receiver of the value is responsible for releasing the resource

but I'm rather proud of my code none the less. I'll post my SO code and my mock up OPOS code (a test for me to show it works)

LONG ReaderHelper::ULCRead(LPVOID param)
{
    BYTE* bTmp = new BYTE[4];
    //a call to fill said bTmp with error checking and so forth
    CString str;
    for (int i = 0; i < 4; i++)
    {
        str.AppendFormat( _T("%02X"), bTmp[i]);
    }
    delete[] bTmp;
    BSTR bstring = str.AllocSysString();
    LONG data = str.GetLength();
    USNMSRRFID* pso = (USNMSRRFID*)param;
    COPOSMSR msr(pso->mlpDispatch);
    msr.SODirectIO(0, &data, &bstring);
    SysFreeString(bstring);
    msr.ReleaseDispatch();
}

MOCK UP OPOS
yes it is ugly, sorry

    void msr_DirectIOEvent(int EventNumber, ref int pData, ref string pString)
    {
        Console.WriteLine();
        Console.WriteLine("\t\t<{0}><{1}><{2}>:Len:{4}<{3}>", EventNumber, pData,pString, GetHexBytes(pString), pString.Length);
        Console.WriteLine();
    }
    string GetHexBytes(string str)
    {
        var bytes = System.Text.UnicodeEncoding.Unicode.GetBytes(str);
        string strbytes = "";
        foreach (byte b in bytes)
            strbytes += string.Format("{0}:", b.ToString("X2"));

        return strbytes;
    }

yields me this

2013-02-12.21:59:30 #Page:3#
2013-02-12.21:59:30     ULCRead(4)-00:00:00:00:
            <0><8><00000000>:Len:8<30:00:30:00:30:00:30:00:30:00:30:00:30:00:30:00:>
2013-02-12.21:59:30 #Page:4#
2013-02-12.21:59:30     ULCRead(4)-9D:5A:AD:47:
            <0><8><9D5AAD47>:Len:8<39:00:44:00:35:00:41:00:41:00:44:00:34:00:37:00:>
2013-02-12.21:59:30 #Page:5#
2013-02-12.21:59:30     ULCRead(4)-5D:E3:EC:93:
            <0><8><5DE3EC93>:Len:8<35:00:44:00:45:00:33:00:45:00:43:00:39:00:33:00:>


texts: A Text-Based Browser using Requests, Beautiful Soup, Sys, OS, and colorama

texts:
I have worked on this for quite a long while, and this is my 3rd attempt after completely demolishing 3 other 200 liners, and i really need ideas on how to make my code add more functionality or efficiency, or some python coding tricks, i can implement to make it more compact.
I'm still a beginning with about a month of learning.

this program is meant to run from the cmd:
syntax = python "Text-Based Browser.py path" foldername
- which essentially stores a folder to store the websites you visit, in shorter text, so the next time you visit the shortened site, it will be much faster.
foldername is stored in Current Working Directory

it has the following inputs in cmd:
1) back: checks the previous page, using stack implementation
2) exit: exits out the program
3) an Url: checks if the url is valid, and if it is valid then checks if a connection can be made, if a connection can be made, then it retrieves the html of the website, and then parses for the text based tags, and changes the "a" tags to the color blue using the colorama module, and writes the text in a file in the foldername. If the url is incorrect, prints a prompt

import sys
import os
import requests
from bs4 import BeautifulSoup
import colorama

dir_name = ''
if len(sys.argv) == 2:
    dir_name = sys.argv[1]
    if not os.path.exists(dir_name):
        os.mkdir(dir_name)
path = dir_name + '/' if dir_name else ''
colorama.init(autoreset=True)
protocol = 'https://'

def read_tab(file, directory):
    with open(directory + file, encoding='utf-8') as f:
        return f.readlines()

def write_tab(file, directory, text_list):
    tab = file.split(protocol)[-1]
    tab = '.'.join(tab.split('.')[:-1])
    with open(directory + tab, 'w', encoding='utf-8') as f:
        f.writelines(text_list)
    return tab

def request_page(page):
    if '.' not in url:
        raise Exception
    if protocol not in page:
        page = protocol + page
    response = requests.get(page, headers={'user-agent': 'Mozilla/5.0'}, timeout=5)
    if not response:
        raise Exception

    soup = BeautifulSoup(response.content, 'lxml')
    tag_set = {'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'ul', 'ol', 'li'}
    text_list = []
    for string in soup.strings:
        parents = {parent.name for parent in string.parents}
        if tag_set & parents:
            txt = '\033[34m' + str(string).strip() if 'a' in parents else str(string).strip()
            _ = text_list.append(txt + '\n') if len(txt) > 2 and not txt.startswith(('$', '.', '@')) else 0
    return text_list

history_stack = []
last_page = None
while True:
    content = []
    url = input("Text Based Webbrowser\nEnter Url/Action: ").strip()
    if url == 'back':
        if len(history_stack) == 0:
            continue
        url = history_stack.pop()
    else:
        _ = history_stack.append(last_page) if last_page else None
        if url == 'exit':
            break
    # Request URL and write Tab:
    try:
        content = request_page(url)
    except Exception:
        # Read Tab if error of requesting (this is tab probably):
        try:
            content = read_tab(url, path)
        except Exception:
            print('Error: Incorrect URL or Tab, enter again')
            continue
        else:
            last_page = url
    else:
        last_page = write_tab(url, path, content)
    finally:
        _ = [print(line, end='') for line in content]


texts: Javascript - Find a deepest node in a binary tree

texts:
Problem Statement

Given the root of a binary tree, return a deepest node.
For example, in the following tree, return d.
    a
   / \
  b   c
 /
d

My Implementation

module.exports = {
    deepestNode: function deepestNode(node, level) {
        if (!level)
            level = 0;

        node.depth = level;

        if (!node.left && !node.right)
            return node;

        let deepestLeft, deepestRight = node;

        if (node.left)
            deepestLeft = deepestNode(node.left, level + 1);

        if (node.right)
            deepestRight = deepestNode(node.right, level + 1);

        if (deepestLeft.depth > deepestRight.depth)
            return deepestLeft;
        else
            return deepestRight;
    },
    TreeNode: (val) => {
        return {
            val: val,
            left: null,
            right: null
        }
    }
};

Test Class

const expect = require('chai').expect;
const deepestNode = require('../../src/google/deepestNode');

let a = deepestNode.TreeNode('a');
let b = deepestNode.TreeNode('b');
let c = deepestNode.TreeNode('c');
let d = deepestNode.TreeNode('d');

a.left = b;
b.left = d;
a.right = c;

expect(deepestNode.deepestNode(a).val).eq('d');

a = deepestNode.TreeNode('a');
expect(deepestNode.deepestNode(a).val).eq('a');

I am a Javascript newbie so any comments regarding either the algorithm itself or the use of Javascript is welcome.


texts: Is there a more efficient way to do Base 32 encoding/decoding than this?

texts:
This journey started with a quest to create the shortest possible case-insensitive verification number. Based on the answers there, I worked out a Classic ASP/VBScript implementation of Crockford's Base32 Encoding and it has served me well so far.

Out of semi-idle curiosity, I was wondering if there was a way to further improve the performance. To be clear: it works, and it runs more than fast enough. I am planning to use it more extensively and since I never heard back on a better way, I was hoping for a second set of eyes to say "yes, it's as good as it's going to get" or "here's how to make it more awesome" or whatever.

So you don't have to go back to the latter Stack Overflow question to see the code, here it is:

'Base32 encoding functions for shorter, less confusing verification numbers
Const kBase32Digits = "0123456789abcdefghjkmnpqrstvwxyz"

Function ToBase32(ByVal lInput)
    Dim lModulo, sTemp
    Do Until lInput = 0
        lModulo = lInput Mod 32
        sTemp = Mid(kBase32Digits, lModulo + 1, 1) & sTemp
        lInput = lInput \ 32
    Loop
    ToBase32 = sTemp
End Function

Function FromBase32(ByVal sInput)
    Dim sTemp, sR, i,iY,lLen, zMultiplier
    sTemp = LCase(sInput)
    sTemp = Replace(sTemp,"o","0")
    sTemp = Replace(sTemp,"i","1")
    sTemp = Replace(sTemp,"l","1")
    sTemp = Replace(sTemp,"u","v")
    zMultiplier = 1
    lLen = Len(sTemp)
    For i = lLen To 1 Step -1
        sR = Mid(sTemp, i, 1)
        iY = InStr(1, kBase32Digits, sR, vbTextCompare) - 1
        FromBase32 = FromBase32 + iY * zMultiplier
        zMultiplier = zMultiplier * 32
    Next
End Function


texts:
I've just implemented a simulation of tower of hanoi in Java. Any suggestions are welcomed. Here's my code:

static class Node{
    int data;
    Node next;

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

static class Stack{
    Node top;
    String stackName;

    public Stack(String name){
        stackName = name;
    }

    public String getStackName(){
        return stackName;
    }

    public void push(int data){
        if(top==null){
            top = new Node(data);
            System.out.println("Created Stack, pushing : " + data);
        }else{
            System.out.println("Pushed : " + data);
            Node someNode = new Node(data);
            someNode.next = top;
            top = someNode;
        }
    }

    public Node pop(){
        if(top==null){
            System.out.println("Error : Stack is empty!");
            return new Node(-1);
        }
        if(top.next==null){
            Node toRet = new Node(top.data);
            System.out.println("Stack " + this.stackName + " will be emptied now");
            top = null;
            return toRet;
        }
        Node temp = top;
        top = top.next;
        System.out.println("Popped : " + temp.data);
        return temp;
    }

    public String getTop(){
        if(top==null){
            return "Stack is empty";
        }
        return String.valueOf(top.data);
    }

    public void pushTo(Stack anotherStack){
        System.out.println("Pushed " + this.top.data + " from " + this.stackName + " to " + anotherStack.stackName);
        Node toPush = this.pop();
        anotherStack.push(toPush.data);
    }

}

public static void tower(int number, Stack stackFrom, Stack stackInter, Stack stackTo){
    if(number == 1){
        stackFrom.pushTo(stackTo);
    }else{
        tower(number-1, stackFrom, stackTo, stackInter);
        stackFrom.pushTo(stackTo);
        tower(number-1, stackInter, stackFrom, stackTo);
    }
}

public static void main(String[] args) {
    Stack myStack = new Stack("A");
    myStack.push(10);
    myStack.push(15);
    myStack.push(20);
    myStack.push(25);
    Stack anotherStack = new Stack("B");
    Stack yetAnotherStack = new Stack("C");
    tower(4, myStack, anotherStack, yetAnotherStack);
}


texts:
def MinimumSwaps(Queue):
        MinSwaps = 0
        for i in range(len(Queue) - 1):
            if Queue[i] != i+1:
                for j in range(i+1,len(Queue)):
                    if Queue[j] == i+1:
                        Queue[i], Queue[j] = Queue[j], Queue[i]
                        MinSwaps += 1
                        break
            else:
                continue
        return MinSwaps

def main():
    Result = MinimumSwaps([7, 1, 3, 2, 4, 5, 6])
    print(Result)
if __name__ == "__main__":
    main()

The question: You are given an unordered array consisting of consecutive integers  [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.
The issue is that what I have provided is inefficient and fails on very large arrays, however Ive tried to optimise it as much as I can and im not aware of another technique to use. This question is likely related to a particular sorting algorithm but is there any way to modify the above code to make it faster?


texts:
In my web app, I have a view where users can search in receipts and drafts.

I've implemented this ability in search method at my view model, but I'm not sure if this is the best place to put it. So I'll let you take a look at it.

public class ProductCardSearchViewModel
{
    public IEnumerable<ProductCardRowViewModel> Search()
    {
        GenericRepository<Rows> repo = new GenericRepository<Rows>();
        var temp = repo.GetAll();

        if (this.Warehouse != 0)
            temp = temp.Where(x => x.Head.Warehouse == this.Warehouse );
        if (ProductCode > 0)
            temp = temp.Where(x => x.ProductCode == this.ProductCode );
        if (!string.IsNullOrEmpty(this.UnitCode))
            temp = temp.Where(x => x.UnitCode .Equals(this.UnitCode));

        List<ProductCardRowViewModel> data = new List<ProductCardRowViewModel>();

        foreach (Rows row in temp)
            data.Add(new ProductCardRowViewModel(row));

        return data;
    }

    [Display(Name = "")]
    public long Warehouse { get; set; }

    [Display(Name = "")]
    public string UnitCode { get; set; }

    [Display(Name = "")]
    public long ProductCode { get; set; }
}

Please feel free to suggest any improvements in this code. I'm not much interested to stick with design patterns, but I like to have SOLID code, and I'm kind of sure that this one is not!


texts:
I've just started learning myself Rust. I am practicing with the exercises from the book available on the official website.
Here is my attempt at the temperature converter exercise at the end of chapter 3.
Could you tell me if my approach is correct? Is there something I could have done more efficiently? Is there something I shouldn't do because it's not how Rust is supposed to work?
Thank you!
use std::io;

fn main() {
    println!("Enter a temperature.");

    let mut temperature = String::new();

    io::stdin()
        .read_line(&mut temperature)
        .expect("Failed to read temperature");

    let (value, unit) = temperature.split_at(temperature.len() - 2);

    let value: f32 = match value.trim().parse() {
        Ok(num) => num,
        Err(_) => panic!("{} is not a number", value),
    };
    let unit = unit.trim().to_lowercase();

    print!("The input temperature is: {}", temperature);

    if unit == "c" {
        c_to_f(value);
    } else if unit == "f" {
        f_to_c(value);
    } else {
        println!("Unsupported unit");
    }
}

fn c_to_f(c: f32) {
    output(c * 1.8 + 32.0, "F".to_string());
}

fn f_to_c(f: f32) {
    output((f - 32.0) / 1.8, "C".to_string());
}

fn output(t: f32, u: String) {
    println!("The output temperature is: {}{}", t, u);
}
```


texts:
This question is from a recently concluded competition on Codechef.

You are given an array A of size n, and there are q queries of the form a, b, c, d such that a <= b and c <= d.

For each query, we need to check if the sub arrays A[a:b] and A[c:d] are similar. The sub-arrays are of same length and are similar if their sorted representations contains only one mismatch in all of their positions. It is also possible that two sub arrays can overlapped.

For example

A = [36, 24, 12, 24, 60]
a = 0, b = 2, c = 2, d = 4
sorted A[a:b] = [12, 24, 36]
sorted A[c:d] = [12, 24, 60]

They differ at only one index, so they are similar.

I tried to solve this in brute-force method which could solve preliminary test cases, but getting TLE for large inputs. Following is my code. How can we efficiently solve this problem?

import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by renaganti on 6/11/17.
 */
public class Cloning {
    public static void main(String []args) {
        Scanner reader = new Scanner(System.in);
        int t = reader.nextInt();
        while(t-- > 0) {
            int n = reader.nextInt();
            int q = reader.nextInt();
            int i;
            int []arr = new int[n];
            for(i = 0; i < n; i++) {
                arr[i] = reader.nextInt();
            }

            for(i = 0; i < q; i++) {
                int a = reader.nextInt();
                int b = reader.nextInt();
                int c = reader.nextInt();
                int d = reader.nextInt();
                if( similar(arr, a, b, c, d) )
                    System.out.println("YES");
                else
                    System.out.println("NO");

            }
        }
    }
    private static boolean similar(int []arr, int a, int b, int c, int d) {
        int [] arr1 = new int[b-a+1];
        int [] arr2 = new int[d-c+1];

        for(int j = a-1, k = c-1, l = 0; j < b; j++, k++) {
            arr1[l] = arr[j];
            arr2[l] = arr[k];
            l++;
        }

        Arrays.sort(arr1);
        Arrays.sort(arr2);

        int diff = 0;
        for(int j = 0; j < arr1.length; j++) {
            if( arr1[j] != arr2[j])
                diff++;
            if( diff > 1 )
                break;
        }
        if( diff < 2 )
            return true;
        else
            return false;
    }
}


texts:
My code works, but the problem is that it is taking an increasingly long time to run, with the time required to complete calculations increasing every time I use the macro. I've tried a variety of variations and modifications with the syntax, but as I'm pretty new to VBA, I haven't made a whole lot of progress.

Here's the code I'm running (Note, it is running as a subset, and ScreenUpdate = False):

Public Sub deleteRows()

    Dim lastRow As Long
    Dim rng As Range
    With ActiveSheet
        .AutoFilterMode = False
        lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
        '~~> Set the range of interest, no need to include the entire data range
            With .Range("B2:F" & lastRow)
                .AutoFilter Field:=2, Criteria1:="=0.000", Operator:=xlFilterValues
                .AutoFilter Field:=5, Criteria1:="=0.000", Operator:=xlFilterValues
            End With
        .Range("B1:F" & lastRow).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        .AutoFilterMode = False
        Rows("1:1").Select
        Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    End With
    MsgBox Format(Time - start, "hh:mm:ss")

End Sub

This code basically removes zero-valued results from the data by deleting an entire row. Initially, it ran in about 12 seconds, but that soon became 55 second, which has progressed into increasing long runtimes, with a 'fast' now being in the 5 minuet range. Below is a spreadsheet with the recorded runtimes and corresponding changes made:

Runtime   Changes
6:30  None
7:50  None
5:37  Manually stepped through code
7:45  Run with .cells instead of .range("B1:B" & lastRow)
5:21  Run with .Range(B:B)  instead of .range("B1:B" & lastRow)
9:20  Run with application.calculation disabled/enabled, range unchanged
5:35  Run with application.enableEvents disabled/enabled, range unchanged
11:08 Run with application.enableEvents disabled/enabled, Range(B:B)
5:12  None
7:57  Run with Alternative code (old code)
5:45  Range changed to .Range(cells(2,2), Cells(lastRow,2)
10:25 Range changed to .Range(cells(2,2), Cells(lastRow,2), Application.Calculation Disabled/enabled
5:34  Range set to rngB  for .delete portion (range assigned to variable)
9:59  Range set as rng("B1:F" & lastRow)
5:58  Changed system settings for Excel to "High Priority", code reverted to original
9:41  Rerun of old code for comparison
9:26  Reun with change in old code criteria to "0.000"
0:10  Moved SpecialCells……..Delete into 2nd With/End With
5:15  Rerun  SpecialCells……..Delete into 2nd With/End With
11:31 Rerun  SpecialCells……..Delete into 2nd With/End With
11:38 Excel restart; Rerun  SpecialCells……..Delete into 2nd With/End With
5:18  Excel restart; Rerun  SpecialCells……..Delete into 2nd With/End With
6:49  Removed 2nd with 'loop'; all data put into first with statement

I did some research online, and it looks like this might be a known issue with Excel when working with large datasets, and as mine is ~51k rows, I can see how this might be the case.

  ...A macro that required several seconds to complete in an earlier version of Excel may require several minutes to complete in a later version of Excel. Alternatively, if you run a macro a second time, the macro may take twice as long to run as it did the first time.

Source

Is there any way to make this run faster, like it initially did? Why is this happening?


texts:
I'm working on a project where I often want to turn class instances into dictionaries to write them to MongoDB. I'd like some feedback on the following:

def getDict(self):
    self.dict = dict()
    for key in self.__dict__.keys():
        if key not in self.NOT_INCLUDE: # class variable
            try:
                self.dict[key] = getattr(getattr(self, key), "getDict")()
            except:
                self.dict[key] = getattr(self, key)
    return self.dict

This will turn any class with getDict into a dictionary, including any instance properties that themselves have a getDict method.

Also please let me know if there's an easy way to do this with the standard library that I missed.


texts:
I am new to jQuery, and after spending weeks to convert my pages using jQuery, I am now reading about jQuery optimization. In that effort, I'm rewriting one of my functions. Please comment whether it is right (both are working).

Previous

$("#mydiv").empty();
var i = 2;
$("#axisa option").each(function() {
    $("#mydiv").append("

");
    updateCharts($("#wd").slider("value"), $("#ht").slider("value"),$(this).val());
    i++
});

$("#axisb option").each(function() {
    $("#mydiv").append("

");
    updateCharts($("#wd").slider("value"), $("#ht").slider("value"),$(this).val());
    i++
});
$("#hiddendiv").show("slow");

Optimized

var mydiv = $("#mydiv");
var mywid = $("#wd").slider("value");
var myhet = $("#ht").slider("value");
var total = $("#axisa option").length + $("#axisb option").length+2;

mydiv.empty();
var design = "";

for(var i=2;i<total;i++){
    design += "

";
}
mydiv.append(design);
i = 2;

$("#axisa option").each(function() {
    updateCharts(mywid, myhet, $(this).val());
    i++
});

$("#axisb option").each(function() {
    updateCharts(mywid, myhet, $(this).val());
    i++
});
$("#hiddenDiv").show("slow");


texts: Overriding stringstream underflow function

texts:
I was answering a question here and I think it got the job done, but I have some parts that don't feel right.

Was it correct to use a static_cast to set the underlying buffer because I couldn't access the rdbuf function otherwise?

I only set one character for setg, but I suppose I could set it for the whole line at a time?

Maybe this could be more elegant in general?

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

class Mybuf : public std::streambuf {
    std::string line{};
    char ch{}; // single-byte buffer
protected:
    int underflow() override {
        if(line.empty()) {
            std::cout << "Please enter a line of text for the stream: ";
            getline(std::cin, line);
            line.push_back('\n');
        }
        ch = line[0];
        line.erase(0, 1);
        setg(&ch, &ch, &ch + 1); // make one read position available
        return ch;
    }
public:
    Mybuf(std::string line) : line{line} {};
};

class mystream : public std::istringstream {
    Mybuf mybuf;

public:
    mystream(std::string line) : std::istringstream{}, mybuf{line}
    {
        static_cast<std::istream&>(*this).rdbuf(&mybuf);
    }
};

int main()
{
    mystream ms{"The first line.\nThe second line.\nA partial line"};
    for(std::string line{}; std::getline(ms, line); )
        std::cout << "line: " << line << "\n";
}


texts: Creating and Organizing Registry Backups

texts:
I've never messed with batch really so I'm trying to introduce myself. I made this to back up all registry data and organize it like this:

RegBackup

November

11-27-2020

[Registry Files]

11-28-2020

[Registry Files]

Backup.bat

The script is:
@echo off

Rem set bat location as CD
cd /D "%~dp0"
Rem open explorer to CD
explorer "%~dp0"
setlocal EnableDelayedExpansion
Rem set Month string
set m=100
for %%m in (January
    February
    March
    April
    May
    June
    July
    August
    September
    October
    November
    December
) do (
  set /a m+=1
  set month[!m:~-2!]=%%m
)
set monthNow=%date:~3,3%
set monthNow=%monthNow: =%
set monthName=!month[%monthNow%]!
Rem create/enter Month string directory
if not exist %monthName% mkdir %monthName%
Rem set for current date in mm-dd-yyyy format
SET Today=%date:~-10,2%"-"%date:~7,2%"-"%date:~-4,4%
Rem create/enter mm-dd-yyyy directory
if not exist %Today% mkdir %Today%
cd %Today%
Rem save registry files into mm-dd-yyyy
REG SAVE HKLM\SOFTWARE SOFTWARE
REG SAVE HKLM\SYSTEM SYSTEM
REG SAVE HKU\.DEFAULT DEFAULT
REG SAVE HKLM\SECURITY SECURITY
REG SAVE HKLM\SAM SAM
Rem go up a folder. aka to .bat location directory
cd ..
Rem move mm-dd-yyyy into Month directory/already exists, delete new, pretend never happened.
move %Today% %monthName% || rmdir /Q /S %Today%

I added some remarks just to more or less explain whats going on, but I feel like there's an easier way than creating %Today%, filling it, and then moving the whole thing with all its contents, so I was hoping I could get some feedback on any ways I could improve, or just pointing me in the direction would be great. I know windows has a built in backup I could use but that's no fun :p.
(I hope I'm posting properly, I tried to make sure to follow the posting rules, I'm sorry if I messed something up!)


texts:
This bit of code is looking for the pair of integers that make up a product.
You can input any integer and it returns the pairs of numbers that, when multiplied together, make it up.
I have done a pretty bad job at explaining this, but the code it pretty simple.
All comments welcome.
num = 498
num_1 = 1

while num_1 < num:
    product = num / num_1
    if product < num_1:
        break
    if product - int(product) == 0:
        print(f"{num_1}, {int(product)}")
    num_1 += 1


texts: Leftist Tree in Dyalog APL -- can it be made more compact/idiomatic?

texts:
Following great feedback given in response to my previous question, I was encouraged to consider a different type of heap structure, the Leftist Tree. It lends itself better to a functional implementation. It's already shorter, but is there anything else I should consider in order to make this more idiomatic APL? Many thanks.

⍝ APL implementation of a leftist tree.
⍝
⍝ https://en.wikipedia.org/wiki/Leftist_tree
⍝ http://typeocaml.com/2015/03/12/heap-leftist-tree/

⎕io←0
Insert←{ ⍝ Insert item into leftist tree, returning the resulting tree
    (tree item)←⍵
    1 item ⍬ ⍬ Merge tree
}

Pop←{ ⍝ Pop off smallest element from a leftist tree
    0=≢⍵:⍬
    (v l r)←1↓⍵                 ⍝ value left right
    (l Merge r) v               ⍝ Return the resulting tree and the value
}

Merge←{ ⍝ Merge two leftist trees, t1 and t2
    t1←⍺ ⋄ t2←⍵
    0=≢t1:t2 ⋄ 0=≢t2:t1                          ⍝ If either is a leaf, return the other
    (key1 left right)←1↓t1 ⋄ key2←1⌷t2
    key1>key2:t2∇t1                              ⍝ Flip to ensure smallest is root of merged
    merged←right∇t2                              ⍝ Merge rightwards
    (⊃left)≥⊃merged:(1+⊃merged) key1 left merged ⍝ Right is shorter
    (1+⊃left) key1 merged left                   ⍝ Left is shorter; make it the new right
}

⍝ Example heap merge from http://typeocaml.com/2015/03/12/heap-leftist-tree/
h←Insert ⍬ 2
h←Insert h 10
h←Insert h 9

s←Insert ⍬ 3
s←Insert s 6

h Merge s
┌→─────────────────────────────────────────────────────────────┐
│     ┌→────────────────────────────────────┐ ┌→─────────────┐ │
│ 2 2 │     ┌→────────────┐ ┌→────────────┐ │ │      ┌⊖┐ ┌⊖┐ │ │
│     │ 2 3 │     ┌⊖┐ ┌⊖┐ │ │     ┌⊖┐ ┌⊖┐ │ │ │ 1 10 │0│ │0│ │ │
│     │     │ 1 6 │0│ │0│ │ │ 1 9 │0│ │0│ │ │ │      └~┘ └~┘ │ │
│     │     │     └~┘ └~┘ │ │     └~┘ └~┘ │ │ └∊─────────────┘ │
│     │     └∊────────────┘ └∊────────────┘ │                  │
│     └∊────────────────────────────────────┘                  │
└∊─────────────────────────────────────────────────────────────┘


texts: Synchronizing two SQL Server database tables with the most recent changes to both tables

texts:
I'm very new to SQL, but I'm coding a C# program that interacts with a database. There's a master database on my computer, and there's a client database on my tablet.

When I re-connect my tablet to the network, I want it to merge the two databases, so that changes made on the tablet are pushed to the master, and changes made to the master are pushed to the client.

Here's my code to initialize the local database on the tablet:

CREATE DATABASE LocalClaytonDB
ON (Filename = 'C:\ProgramData\Clayton\Clayton.mdf')
   , (Filename = 'C:\ProgramData\Clayton\Clayton_log.ldf')
FOR ATTACH;
GO

EXEC sp_addlinkedserver @server='Server'

Here's my code to synchronize the two databases:

-- update the client from the master
MERGE [LocalClaytonDB].[dbo].[tableName] trgt
using [Server].[Clayton].[dbo].[tableName] src

ON trgt.id = src.id

WHEN matched AND trgt.lastmodified <= src.lastmodified THEN
  -- if the master has a row newer than the client
  -- update the client
  UPDATE SET trgt.[allColumns]      = src.[allColumns],
             trgt.[id]              = src.[id],
             trgt.[lastmodified]    = src.[lastmodified]

-- delete any rows added by a client
WHEN NOT matched BY source
THEN
  DELETE

-- insert any rows added by the master
WHEN NOT matched BY target
THEN
  INSERT ( [allColumns],
           [id],
           [lastmodified])
  VALUES (src. [allColumns],
          src.[id],
          src.[lastmodified]);

-- now we update the master from the client
-- Note:
-- because the serverDB is a linked server
-- we can't use another MERGE statement, otherwise
-- we get the error: "The target of a MERGE statement
-- cannot be a remote table, a remote view, or a view over remote tables."

UPDATE
    serverDB

SET
    [allColumns]        = [localDB].[allColumns],
    [id]                = [localDB].[id],
    [lastmodified]      = [localDB].[lastmodified]

FROM
     [Server].[Clayton].[dbo].[tableName] serverDB

INNER JOIN
     [LocalClaytonDB].[dbo].[tableName] localDB

-- update where the id is the same but the client is newer than the master

ON serverDB.id = localDB.id
       AND localDB.lastmodified >= serverDB.lastmodified

Also, I'm slightly worried about what would happen if this script failed partway through the process, and also just for anything I might be missing.

I'd love it if someone could look over this and point out any shortcomings. As I said, this is the first real SQL I've written and my program is going to have to rely on it.


texts:
The following code gets video renditions from Brightcove using the media API. It then generates an ordered source list for the JW Player and selects the default rendition based on a pre-set bitrate.

function buildSourcesFromBrighcoveID(brightcoveID, onComplete) {
    var sources = [];
    var brightcoveAPI = 'http://api.brightcove.com/services/library';
    var parameters = {
      command: 'find_video_by_id',
      video_id: brightcoveID,
      video_fields: 'renditions',
      media_delivery: 'http',
      token: 'jskS1rEtQHy9exQKoc14IcMq8v5x2gCP6yaB7d0hraRtO__6HUuxMg..'
    };

    // Get renditions
    $.ajax({
      dataType: "jsonp",
      url: brightcoveAPI,
      data: parameters
    }).done(function(data){

      var targetRate = 800000; // Bps
      var lowestDiff;
      var closestRate;

      // Sort them by encoding rate, higher rate first
      data.renditions.sort(function(a, b) {
        return parseFloat(b.encodingRate) - parseFloat(a.encodingRate);
      });

      // Get the closest encoding rate to target
      var currentRate = data.renditions[0].encodingRate;
      var lowestDiff = Math.abs(currentRate - targetRate);

      $.each (data.renditions, function(id, rendition){
        var diff = Math.abs(rendition.encodingRate - targetRate);
        if (lowestDiff > diff) {
          lowestDiff = diff;
          closestRate = rendition.encodingRate;
        }
      });

      // Build sources for the player
      $.each (data.renditions, function(id, rendition){
        var newItem = {
          file: rendition.url,
          label: Math.round(rendition.encodingRate / 1000) + ' Kbps'
        }

        // Set default rendition
        if (rendition.encodingRate == closestRate) {
          newItem["default"] = true;
        }

        sources.push(newItem);

      });

      if (onComplete) onComplete(sources);
    });

    return sources;
  }

  function loadVideoPlayer(sources) {

    var playerInstance = jwplayer("player");
    playerInstance.setup({
      sources: sources,
      width: 727,
      height: 455,
      autostart: true
    });

  }

buildSourcesFromBrighcoveID('1520880903001', loadVideoPlayer);

Codepen

Questions

How can I be sure buildSourcesFromBrighcoveID completed before doing anything else? I currently run the function that builds the player from within the first function to be sure the Ajax completed, but I would like them to be independent.
Could I build the sources array in a more efficient way? I am currently iterating the renditions 3 times (to sort, to search for the best rendition and to build the sources array).


texts: Looking for Interstitial Array Join that works like String Join

texts:
I'm looking for an array join that will return an array with an element inserted between consecutive elements of an input array.

string[] input = { "red", "white", "blue" };
string[] result = InterstitialJoin("or", input);
// { "red", "or", "white", "or", "blue" }

If I use string.Join, then the output is a string, but I want the output to be an array.

Not quite what I want:

string.Join("or", input); // redorwhiteorblue

Does this already exist?  Is there a more straightforward or built-in way of doing it?

I could hand-roll a function to do this, but it seems like it would require you to write all the code to create an enumerator and yield elements interleaving them with the interstitial element.

e.g.

static IEnumerable<T> InterstitialJoin<T>(T interstitial, IEnumerable<T> elements)
{
    var e = elements.GetEnumerator();
    if (!e.MoveNext()) yield break;
    yield return e.Current;
    while (e.MoveNext()) {
        yield return interstitial;
        yield return e.Current;
    }
}

or directly with an array like this:

static T[] InterstitialArrayJoin<T>(T interstitial, T[] elements) {
    T[] results = new T[elements.Length + elements.Length - 1];
    int iResults = 0;
    int iElements = 0;
    while (iElements < elements.Length) {
        if (iElements != 0) results[iResults++] = interstitial;
        results[iResults++] = elements[iElements++];
    }
    return results;
}


texts:
I have an interface Animal with a class that implements it, Cat.
public interface Animal {
    public int price();
    public Breed.BreedType breedType();
}

public class Cat implements Animal {

    private int price;
    private Breed.BreedType breedType;

    public Cat(int price) {
        this.price = price;
    }

    public Cat(int price, Breed.BreedType breedType) {
        this.price = price;
        this.breedType = breedType;
    }

    @Override
    public int price() {
        return price;
    }

    @Override
    public Breed.BreedType breedType() {
        return breedType;
    }
}

I have decorated the Animal class with the following interface, Breed.
import java.util.List;

public interface Breed {
    public enum BreedType {
        RARE,
        EXOTIC
    }

    public int calculatePrice(List<Animal> animals);
}

The concrete decorator class looks as follows:
import java.util.List;

public class Exotic implements Breed {

    @Override
    public int calculatePrice(List<Animal> animals) {
        return animals.stream()
                .mapToInt(Animal::price)
                .map(i -> i * 2)
                .sum();
    }
}

Finally I iterate over a collection of animals and apply the decorator to them to work out their total cost of special breed animals.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) {
        Cat cat1 = new Cat(100);
        Cat cat2 = new Cat(100, Breed.BreedType.EXOTIC);
        Cat cat3 = new Cat(100, Breed.BreedType.EXOTIC);

        Map<Breed.BreedType, List<Animal>> map = Stream.of(cat1, cat2, cat3)
                .filter(animal -> animal.breedType() != null)
                .collect(Collectors.groupingBy(Animal::breedType, Collectors.toList()));

        int total = 0;
        for(Breed.BreedType breedType : map.keySet()) {
            if(breedType.equals(Breed.BreedType.EXOTIC)) {
                total += new Exotic().calculatePrice(map.get(breedType));
            }
        }
        System.out.println(total);
    }
}

This does not seem particularly flexible as I will end up with a giant if statement as more breeds are added. Is there a better way to do this? My enum and the corresponding method for the Exotic breed seem a bit disconnected.


texts:
Do you have an idea to "transfer" this CSS Code to Javascript (maybe jQuery)?

html { background-color: #B94FC1; }
html:before, html:after { content: ""; height: 100%; width: 100%; position: fixed; z-index: -6; }
html:before { background-image: linear-gradient(to bottom, #5856D6 0%, #C644FC 100%); animation: fgradient 5s linear 0s infinite alternate; }
html:after { background-image: linear-gradient(to bottom, #C643FC 0%, #FF5F37 100%); animation: sgradient 5s linear 0s infinite alternate; }
@keyframes fgradient { 0% { opacity: 1; } 100% { opacity: 0; } }
@keyframes sgradient { 0% { opacity: 0; } 100% { opacity: 1; } }

Fiddle.

I want a transition from a gradient to an other. My own code works well, but I want try the same with Javascript ;)

Hope somebody can help me.


texts: Iterative Flood Fill implementation in C

texts:
I am trying to implement an iterative version of flood fill in C:

#include<stdio.h>
int m,n;
void flood_fill(int [][n],int,int,int);
void print_wall(int [][n]);
int main(void)
{
    int i,j;
    scanf("%d%d",&m,&n);
    int arr[m][n];
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            scanf("%d",&arr[i][j]);
        }
    }
    int x,y;
    printf("Enter the coordinates of the point to be repainted\n");
    scanf("%d%d",&x,&y);
    int new_col;
    printf("Enter new color to be painted");
    scanf("%d",&new_col);
    flood_fill(arr,x,y,new_col);
    print_wall(arr);
    return 0;
}

void flood_fill(int a[][n],int x,int y,int n)
{
    int i,j;
    for(i=x+1;i<m-1;i++)
    {
        for(j=y;j<n-1;j++)
        {

            if(a[i][j]==a[x][y])
            a[i][j]=n;

        }
    }
    for(i=x;i>0;i--)
    {
        for(j=y-1;j>0;j--)
        {

            if(a[i][j]==a[x][y])
            a[i][j]=n;

        }
    }
    for(i=x+1;i<m-1;i++)
    {
        for(j=y;j>0;j--)
        {

            if(a[i][j]==a[x][y])
            a[i][j]=n;

        }
    }
    for(i=x;i>0;i--)
    {
        for(j=y+1;j<n-1;j++)
        {
            if(a[i][j]==a[x][y])
            a[i][j]=n;

        }
    }
a[x][y]=n;
}

void print_wall(int a[][n])
{
    int i,j;
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            printf("%d",a[i][j]);
        }
        printf("\n");
    }

}

Is my implementation correct? Is the stack/queue implementation better?


texts: Sorting linked list with comparator in Java

texts:
When I want to sort data on linked list by using collections.sort() and comparator will working after write (collections.sort (...)) and then use it again with comparator?

Is it possible to just use a comparator without collection.sort (...) first?

public class JavaApplication {
   public static void main(String[] args) {
      LinkedList lList = new LinkedList();
      lList.add("1");
      lList.add("2");
      lList.add("3");
      lList.add("4");
      lList.add("5");
      System.out.println(lList);
      lList.addFirst("0");
      System.out.println(lList);
      lList.addLast("6");
      System.out.println(lList);

      lList.addFirst("2");
      System.out.println(lList);

      lList.add(3, "10");
      System.out.println(lList);

      lList.add(4,"25");
      System.out.println(lList);

      getIterator( lList ).add( "60" );
      System.out.println(lList);

      lList.addLast("10");
      System.out.println(lList);
      lList.addLast("15");
      System.out.println(lList);

      lList.add(6,"40");
      System.out.println(lList);

      getIterator( lList ).add( "70" );
      System.out.println(lList);

      lList.addFirst("75");
      System.out.println(lList);

      Collections.sort(lList);

      Collections.sort(lList, new AComparator());
      System.out.println("LinkedList (after sorting using Comparator): "+lList);
   }

   private static ListIterator getIterator(LinkedList lList) {
       return lList.listIterator( lList.size() / 2 );

   }
}

class AComparator implements Comparator<String> {
    public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }
}

And can someone give me a suggest how to efficiency the code.

Output that I want :

Unsorted [75, 2, 0, 1, 10, 25, 60, 40, 70, 2, 3, 4, 5, 6, 10, 15]
LinkedList (after sorting using Comparator): [0, 1, 2, 2, 3, 4, 5, 6, 10, 10, 15, 25, 40, 60, 70, 75]


texts:
I am trying to upload an image (screenshot from desktop) to an SQL database as fast as possible. I would like to optimize my current procedure in terms of speed:

bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                       Screen.PrimaryScreen.Bounds.Height,
                       System.Drawing.Imaging.PixelFormat.Format32bppArgb);
gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                                    Screen.PrimaryScreen.Bounds.Y,
                                    0,
                                    0,
                                    Screen.PrimaryScreen.Bounds.Size,
                                    CopyPixelOperation.SourceCopy);

byte[] imageBytes = convertImageToByteArray(bmpScreenshot);
MemoryStream mem = new MemoryStream(imageBytes);
using (Bitmap bmp1 = (Bitmap)Image.FromStream(mem))
{

     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
     ImageCodecInfo jgpEncoder = codecs[1];

     System.Drawing.Imaging.Encoder myEncoder =
     System.Drawing.Imaging.Encoder.Quality;

}

  using (MemoryStream m = new MemoryStream())
                    {
                        EncoderParameters myEncoderParameters = new EncoderParameters(1);
                        EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 23L);
                        myEncoderParameters.Param[0] = myEncoderParameter;
                        bmp1.Save(m, jgpEncoder, myEncoderParameters);
   using (Bitmap bmpLast = (Bitmap)Image.FromStream(m))
                        {
                    string query = "UPDATE ScreenCapture SET ScreenCapture=@Image,BroadcastTime=@BroadcastTime WHERE ID = 1";
                    SqlCommand sqlCommand = new SqlCommand(query, SQLconn);
                    ImageConverter converter = new ImageConverter();
                    byte[] beforeUpload = (byte[])converter.ConvertTo(bmpLast, typeof(byte[]));
                    sqlCommand.Parameters.AddWithValue("@Image", beforeUpload);
                    sqlCommand.Parameters.AddWithValue("@BroadcastTime", DateTime.Now);
                    SQLconn.Open();
                    sqlCommand.ExecuteNonQuery();
                    SQLconn.Close();
                }
            }
        }

Profiling - Performance and Diagnostics in Visual Studio 2013

The method I posted has following usage:

40,8% - byte[] imageBytes = convertImageToByteArray(bmpScreenshot);
10,4% - MemoryStream mem = new MemoryStream(imageBytes);
37,8% - mp1.Save(m, jgpEncoder, myEncoderParameters);

From captureUpload which takes 93.6% in System.Windows.Forms.ni.dll:

69.9% - System.Drawing.ni.dll
26.8% - convertImageToByteArray
8.8 - PresentationFramework.ni.dll

convertImageToByteArray takes 26.8% on return ms.ToArray().

It now takes me about 1 second to upload and download on client side, which is not so  efficient in my case. If anyone have idea how this procedure is possible to make faster I would be glad to know. The image has around 60 KB, which is quite a lot.


texts: Lindenmayer System String Generator in F#

texts:
Lindenmayer Systems or L-systems are fractals that can be constructed by applying replacement rules to a string for a certain amount of iterations. For example:

Axiom (start): "FX"
Rules:
  X -> "X+YF+"
  Y -> "-FX-Y"

Iteration 0: FX
Iteration 1: FX+YF+
Iteration 2: FX+YF++-FX-YF+
Iteration 3: FX+YF++-FX-YF++-FX+YF+--FX-YF+

 F means draw forward
 + means turn clockwise 90 degrees
 - means turn counter-clockwise 90 degrees
 Everything else is ignored

So each can be simplified to:
 0: F
 1: F+F+
 2: F+F+F-F+
 3: F+F+F-F+F+F-F-F+

The goal of my program is to print out those simplified strings given the axiom, rules, and iteration

module LSystem

let getLSystem axiom rules i =
    let rec find i =
        let replace (str:string)=
            str
            |> List.ofSeq
            |> List.map (fun x ->
                match List.tryFind (fun (c,_) -> c = x) rules with
                | Some (_,r) -> r
                | None -> x.ToString() )
            |> List.reduce (+)
        match i with
        | 0 -> axiom
        | _ -> i-1 |> find |> replace
    let simplify (s:string) = s.Replace("X","").Replace("Y","").Replace("+++","-").Replace("---","+").Replace("+-","").Replace("-+","")
    i |> find |> simplify

And something to run it:

open LSystem

let getDragonCurve =
    let axiom = "FX"
    let rules  = [
        ('X',"X+YF+");
        ('Y',"-FX-Y")]
    getLSystem axiom rules

[for i in 0..5 -> getDragonCurve i]
|> List.iter (fun x -> printf "%s\n" x)

System.Console.ReadKey() |> ignore

I'm specifically concerned about the simplify function, as using straight up C# methods is often a sign you're doing things wrong. I'm quite new to F#, so any style-centric tips are greatly appreciated.


texts: Critique my first C++ "Hello World" program

texts:
This is my first attempt to write a simple C++ program:

#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

class Book {
    public:
    char title[30];

    Book(char *tit)  {
        strcpy(title,tit);
    };

    char *gettitle() {
        return title;
    }
};

int main() {

    Book miolibro((char *)"aaa");
    cout << miolibro.gettitle() << endl;

   std::vector<Book> vettorelibri;
   for (int i=0; i<10; i++) {
        Book l( (char *)"aaa" );   // i tried something like "aaa"+i but it does not work

        vettorelibri.push_back(l);
    }

    for(int i=0; i<10; i++) {
        cout << vettorelibri[i].gettitle() << endl;
    }
};


texts:
I have an entity with opening and closing times and I have to list timetable in HTML label.

Times can be empty.
Ugly attribute names getHorarioMIni or getHorarioTFin cannot be changed due external DB relations and the auto-populating methods.

How to optimize this function:

public String getTimetable() {
    final String SEPARATOR = " - ";
    final String NEW_LINE = "
";
    StringBuilder sb  = new StringBuilder();

    if (nNoE(getHorarioMIni()))
        sb.append(getHorarioMIni());
    if (nNoE(getHorarioMIni()) && nNoE(getHorarioMFin()))
        sb.append(SEPARATOR);
    if (nNoE(getHorarioMFin()))
        sb.append(getHorarioMFin());

    if ((nNoE(getHorarioMIni()) || nNoE(getHorarioMFin())) && (nNoE(getHorarioTIni()) || nNoE(getHorarioTFin())))
        sb.append(NEW_LINE);

    if (nNoE(getHorarioTIni()))
        sb.append(getHorarioTIni());
    if (nNoE(getHorarioTIni()) && nNoE(getHorarioTFin()))
        sb.append(SEPARATOR);
    if (nNoE(getHorarioTFin()))
        sb.append(getHorarioTFin());

    System.out.println(sb);
    return sb.toString();
}

private boolean nNoE(String toCheck) {
    return  toCheck != null && !toCheck.isEmpty();
}

Expected outputs (just commenting example constructor attributes):

08:00 - 12:00
15:00 - 18:00
15:00 - 18:00
08:00 - 12:00
08:00 - 12:00
18:00

Extra
There is an easy way to achieve this? if only one of each group (T and M) filled?

08:00 - 18:00

MCVE

To test it you can copy paste in a java class named Main and execute

class Main {
    public static void main(String args[]) throws Exception {
        Silo silo = new Silo();
        System.out.println(silo.getHorarios());
    }
}

class Silo {

    public Silo() {
        // comment any time to check different outputs.
        this.horarioMIni = "8:00";
        this.horarioMFin = "12:00";

        this.horarioTIni = "15:00";
        this.horarioTFin = "18:00";
    }

    // M group (morning)
    private String horarioMIni;
    private String horarioMFin;
    // T group (evening)
    private String horarioTIni;
    private String horarioTFin;

    public String getHorarioMIni() {
        return horarioMIni;
    }
    public void setHorarioMIni(String horarioMIni) {
        this.horarioMIni = horarioMIni;
    }
    public String getHorarioMFin() {
        return horarioMFin;
    }
    public void setHorarioMFin(String horarioMFin) {
        this.horarioMFin = horarioMFin;
    }
    public String getHorarioTIni() {
        return horarioTIni;
    }
    public void setHorarioTIni(String horarioTIni) {
        this.horarioTIni = horarioTIni;
    }
    public String getHorarioTFin() {
        return horarioTFin;
    }
    public void setHorarioTFin(String horarioTFin) {
        this.horarioTFin = horarioTFin;
    }
    public String getHorarios() {
        final String SEPARATOR = " - ";
        final String NEW_LINE = "
";
        StringBuilder sb  = new StringBuilder();

        if (nNoE(getHorarioMIni()))
            sb.append(getHorarioMIni());
        if (nNoE(getHorarioMIni()) && nNoE(getHorarioMFin()))
            sb.append(SEPARATOR);
        if (nNoE(getHorarioMFin()))
            sb.append(getHorarioMFin());

        if ((nNoE(getHorarioMIni()) || nNoE(getHorarioMFin())) && (nNoE(getHorarioTIni()) || nNoE(getHorarioTFin())))
            sb.append(NEW_LINE);

        if (nNoE(getHorarioTIni()))
            sb.append(getHorarioTIni());
        if (nNoE(getHorarioTIni()) && nNoE(getHorarioTFin()))
            sb.append(SEPARATOR);
        if (nNoE(getHorarioTFin()))
            sb.append(getHorarioTFin());

        System.out.println(sb);
        return sb.toString();
    }

    private boolean nNoE(String toCheck) {
        return  toCheck != null && !toCheck.isEmpty();
    }

}


texts: Conway's Game of Life - Conventional JavaScript?

texts:
I'm using the Game of Life Kata to help me learn JavaScript. I've picked up the syntax through Codecademy tutorials, but my current skill level is Novice.

The example code has working functionality for initialising a World with live cells and asking it to 'tick'.

All suggestions for improvement are welcome. I'd especially like feedback on the following:

JavaScript idioms and conventions
Function and variable scoping
Making use of built-in functions and datatypes

myapp = {};

/**
 * World represents a 2 dimensional square matrix of cells.
 * @param dimension
 * @param liveCellCoordinates
 * @returns {myapp.World}
 */

myapp.World = function(dimension, liveCellCoordinatesArray) {
    this.dimension = dimension;
    this.liveCellCoordinates = liveCellCoordinatesArray;
};

/**
 *
 * @returns {Array} of live cells after tick.
 */
myapp.World.prototype.tick = function() {
    var nextGenerationOfLiveCells = [];

// for each cell in world
for(var y=0; y<this.dimension; y++) {
    for(var x=0; x<this.dimension; x++) {

        var liveNeighbours = this.getLiveNeighbourCount(x, y);
        if(this.isCellAlive(x, y)) {
            if(isSurvivor(liveNeighbours)) {
                nextGenerationOfLiveCells.push([x,y]);
            }
        }
        else {
            if(isBorn(liveNeighbours)) {
                nextGenerationOfLiveCells.push([x,y]);
            }
        }
    }
}

this.liveCellCoordinates = nextGenerationOfLiveCells;

return nextGenerationOfLiveCells;
};

myapp.World.prototype.getLiveNeighbourCount = function(x, y) {
var liveNeighbours = 0;

if(this.isCellAlive(x-1, y-1)) liveNeighbours++;
if(this.isCellAlive(x,   y-1)) liveNeighbours++;
if(this.isCellAlive(x+1, y-1)) liveNeighbours++;
if(this.isCellAlive(x-1, y)) liveNeighbours++;
if(this.isCellAlive(x+1, y)) liveNeighbours++;
if(this.isCellAlive(x-1, y+1)) liveNeighbours++;
if(this.isCellAlive(x,   y+1)) liveNeighbours++;
if(this.isCellAlive(x+1, y+1)) liveNeighbours++;

//  jstestdriver.console.log(">>> liveNeighbours of ", x, y, ": ", liveNeighbours);

return liveNeighbours;
};

myapp.World.prototype.isCellAlive = function(x, y) {
    for(var cell in this.liveCellCoordinates) {
        if(x === this.liveCellCoordinates[cell][0] && y === this.liveCellCoordinates[cell][1]) {
            return true;
        }
    }
    return false;
};

function isBorn(liveNeighbours) {
    return liveNeighbours === 3;
}

function isSurvivor(liveNeighbours) {
    return liveNeighbours === 2 || liveNeighbours === 3;
}